Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Register the home-screen operations counters on Spree.reporting

Damian Legawiecf22266621dde
diff --git a/docs/developer/core-concepts/reporting.mdx b/docs/developer/core-concepts/reporting.mdx
index e801673a0b..cb0a17017c 100644
--- a/docs/developer/core-concepts/reporting.mdx
+++ b/docs/developer/core-concepts/reporting.mdx
@@ -157,6 +157,50 @@ Declaring `subject` without `key_scope` raises at registration, so a member
cannot ship with one axis unguarded. The schema endpoint filters by the same
rule, so a picker never offers a dimension whose query would be refused.
+## Counters
+
+Not everything on the home screen is a report over a period. "Orders to
+fulfill", "Open returns" and "Low stock variants" are the state of the store
+right now, with no time range and no currency. The registry holds these as
+**counters** beside metrics and dimensions, and `GET /dashboard/operations`
+evaluates them:
+
+```json
+{
+ "channel_id": null,
+ "counters": [
+ {
+ "key": "orders_to_fulfill",
+ "label": "Orders to fulfill",
+ "description": "Placed orders with nothing shipped yet.",
+ "value": 12,
+ "link": {
+ "resource": "orders",
+ "filters": [{ "field": "fulfillment_status", "operator": "eq", "value": "unfulfilled" }]
+ }
+ }
+ ]
+}
+```
+
+Three things follow from counters living in the registry:
+
+- **Labels come from the server**, the same way metric labels do, so a
+ counter an extension registers appears on every merchant's home screen
+ without a dashboard release.
+- **Each counter carries its own `subject` and `key_scope`**, filtered by the
+ same rule as the rest of the vocabulary. A role without stock access gets
+ a shorter list, not a refused card.
+- **The link is declared beside the count.** The list a number opens shows
+ exactly the rows that were counted, because the filter and the query are
+ registered together. A counter with no list that can honestly show what it
+ counted carries no link.
+
+Core ships five: orders to fulfill, payments to collect, open returns, low
+stock variants and out of stock variants. The low stock counter reads the
+store's `low_stock_threshold` preference (default five units; zero turns it
+off), which merchants set under store settings → Inventory.
+
## What a report counts
Two rules decide what the numbers mean:
diff --git a/docs/developer/how-to/extend-reporting.mdx b/docs/developer/how-to/extend-reporting.mdx
index da30b0e653..f61f826903 100644
--- a/docs/developer/how-to/extend-reporting.mdx
+++ b/docs/developer/how-to/extend-reporting.mdx
@@ -151,6 +151,27 @@ RSpec.describe 'seller reporting vocabulary' do
end
```
+## Add a counter
+
+A counter is a point-in-time number for the home screen's Operations card:
+no time range, no currency, no base. It takes the store and the channel the
+merchant is looking at and returns an integer.
+
+```ruby
+Spree.reporting.counter :orders_on_hold,
+ subject: -> { Spree::Order }, key_scope: 'read_orders',
+ count: ->(store, channel:) { store.orders.complete.for_channel(channel).where(on_hold: true).count },
+ link: { resource: 'orders', filters: [{ field: 'on_hold', operator: 'eq', value: 'true' }] }
+```
+
+Add `reporting.counters.orders_on_hold.label` (and optionally `.description`)
+to your locale file; without an entry the name is humanized. Declare `link`
+only when the list filter shows exactly the rows counted — the dashboard
+resolves `resource` to one of its lists (`orders`, `returns`, `products`) and
+appends the channel filter itself for order lists. A counter whose meaning
+depends on a store setting can pass `description:` as a lambda receiving the
+store, which is how the built-in low stock counter names its threshold.
+
## Overriding a built-in member
Registration refuses a duplicate name unless you say so explicitly:
diff --git a/docs/plans/6.0-analytics-semantic-layer.md b/docs/plans/6.0-analytics-semantic-layer.md
index d42bbc2524..3dffcd0157 100644
--- a/docs/plans/6.0-analytics-semantic-layer.md
+++ b/docs/plans/6.0-analytics-semantic-layer.md
@@ -4,7 +4,7 @@
**Target:** Spree 6.0 (core + new dashboard home + Reports page) → 6.1 (facts adapter, AI) — Enterprise ClickHouse adapter out of band
**Depends on:** `6.0-admin-api.md` (v3 conventions), `5.5-admin-api-key-scopes.md` (scope gating), `6.0-multi-vendor-marketplace.md` (vendor forced scope + vendor dashboard consumer), `5.5-admin-api-cli.md` (first agent surface), `5.6-solid-queue-single-container.md` (fact writes + reconciliation jobs)
**Author:** Damian + Claude
-**Last updated:** 2026-09-09 (Decision 14: industry sales chain, seller and margin vocabulary)
+**Last updated:** 2026-09-10 (Decision 15: operations counters join the registry; low stock threshold becomes a store preference)
## Summary
@@ -192,6 +192,10 @@ walk, the only tenancy path that table has.
Sessions, referrers and conversion rates stay unavailable: a headless storefront
does not send us the data. That is now the only recorded gap.
+### Decision 15 — Operations counters are registry members; the low stock threshold is a store preference (2026-09-10)
+
+The home screen's Operations card was the last hand-rolled number surface: five counts as private methods on a serializer in the API gem, five matching icon-plus-filter rows hardcoded in the dashboard, one permission (`read_dashboard`) covering all of them, and a `low_stock_threshold` request parameter the dashboard never sent. **Counters now join `Spree.reporting`** as a fourth member type beside metrics, dimensions and bases: `registry.counter :name, count: ->(store, channel:) { … }, subject:, key_scope:, link:, description:`. They are not compiled into the query (no range, no currency, no base — a counter is the state of the store at this instant), so the registry only stores the lambda; `Spree::Reporting::Counters` evaluates them for one store and channel, filtered by the same `member_allowed?` predicate the schema and the query apply, now shared through `Admin::ReportingAuthorization`. `GET /dashboard/operations` returns `{ channel_id, counters: [{ key, label, description, value, link }] }` and the dashboard renders whatever arrives, keeping only an icon map with a fallback. Labels resolve through `reporting.counters.<key>` in the locale the way metric labels do. **The link is declared beside the count** so the list a merchant lands on shows exactly the rows counted — the previous out-of-stock link pointed at a products filter the server silently dropped. **`low_stock_threshold` is a `Spree::Store` preference** (integer, default 5, 0 = off), edited under Settings → Store → Inventory and named in the counter's own description; neither reference platform has a per-variant threshold, and Shopify's inventory report bands by days of supply rather than a count, so store-level is the grain. Not `Spree.operations` (reserved) and not a second namespace — the plan's own line that "state metrics join the registry" is the design.
+
## Design Details
### Registry (`spree/core`)
@@ -271,13 +275,13 @@ Everything below lands on `claude/react-dashboard-home-reporting-71weaz`. Nothin
| Rankings → Customers tab | `metrics: [total_sales, orders]`, `dimensions: [customer]`, `sort: -total_sales`, `limit: 5` | `rows` (dimension meta → name/email + customer link) |
| Rankings → Categories tab | `metrics: [net_sales, units_sold]`, `dimensions: [category]`, `sort: -net_sales`, `limit: 5` | `rows` (dimension meta → category link) |
| Top products | `metrics: [net_sales, units_sold]`, `dimensions: [product]`, `compare: previous_period`, `sort: -net_sales`, `limit: 5` | `rows` (+ per-row growth for trend badges; product meta → thumbnail/slug/price) |
-| Operations card | *(unchanged)* `dashboard.operations` | Point-in-time counts stay bespoke; joins the registry later as "state metrics" if ever |
+| Operations card | `dashboard.operations` | Evaluates the **counters** registered on `Spree.reporting` (Decision 15); the card renders whatever arrives — label, value and link all come from the server |
Chart/tile/ranking-row components become shape-generic (consume `ReportingResult`), which is what the Reports page reuses in Step 7. GrowthBadge, legend, deep-link rows carry over as-is.
### Step 6 — Delete the replaced surface
-`dashboard_analytics_serializer.rb`, `dashboard_rankings_serializer.rb`, `dashboard_serializer_helpers.rb`, the `analytics`/`rankings` controller actions + routes, their specs, and the SDK members from Step 4. `DashboardOperationsSerializer` + `dashboard/operations` survive. The home e2e spec is updated in place — its UI-level assertions (tiles, legend, switcher, deep links) should pass unchanged, which is the acceptance test for the rebuild.
+`dashboard_analytics_serializer.rb`, `dashboard_rankings_serializer.rb`, `dashboard_serializer_helpers.rb`, the `analytics`/`rankings` controller actions + routes, their specs, and the SDK members from Step 4. `dashboard/operations` survives (its hand-rolled serializer was later replaced by registry counters — Decision 15). The home e2e spec is updated in place — its UI-level assertions (tiles, legend, switcher, deep links) should pass unchanged, which is the acceptance test for the rebuild.
### Step 7 — Schema enrichment (serves the builder and the AI layer in one change)
@@ -315,7 +319,10 @@ Legacy surfaces: `Spree::Admin::AnalyticsConcern` untouched (legacy admin is mai
- Every consumer that executes a reporting query authorizes through `Query#unreadable_subjects` — no second copy of the member walk.
- Time-range values are ISO 8601 dates or datetimes (`iso8601`, never `parse`); bare dates cover the store's whole day on either edge and the dashboard sends custom ranges as bare dates.
-- **No new hand-rolled aggregate endpoints.** New analytics needs go through the registry + `POST /reporting/query`; `dashboard/operations` (point-in-time counts) is the only bespoke endpoint that stays.
+- **No new hand-rolled aggregate endpoints.** New analytics needs go through the registry + `POST /reporting/query`; a point-in-time count for the home screen is a registered **counter** evaluated by `dashboard/operations` — never a new method on a serializer, and never a number the dashboard computes or labels itself.
+- **A counter's link is declared beside its count**, or not at all: the list a number opens must show exactly the rows counted. Stock counters carry no link until an inventory list can filter by on-hand quantity (`6.0-inventory-operations.md` Phase 7).
+- **Every surface that lists vocabulary members filters through `ReportingAuthorization#member_allowed?`** — metrics, dimensions and counters declare `subject` + `key_scope` alike; no endpoint gets a second predicate.
+- **The low stock threshold is the store's `low_stock_threshold` preference**, read through `preferred_low_stock_threshold`; no request parameter, no global, no per-variant column.
- **Dimension joins are LEFT joins.** An optional association (an order's shipping address, a product's categories) must produce an "Unassigned" group, never drop the row — the Total counts it either way, and a breakdown summing to less than its own total is a silent undercount.
- **A new base is registered, never hardcoded** — `registry.base` declares its family, table, relation, time column and reachability; nothing in the compiler branches on a base name, and the `resolve_sql` table map is the only remaining place a new table is named.
- **One family per query.** Sales, payments and inventory never mix — a metric from one family beside a metric from another is refused, not joined.
@@ -335,7 +342,6 @@ Legacy surfaces: `Spree::Admin::AnalyticsConcern` untouched (legacy admin is mai
- **Seller-scoped saved reports**: how store-wide saved reports appear in the seller panel once the seller forced scope lands (visibility itself is decided — Decision 12).
- **Checks/alerts** (Blazer-style scheduled saved-report thresholds → email/webhook): follow-up plan or a rider on the facts-adapter work?
- **Deleting a seeded report**: `Seeds::SavedReports` skips by name, so a built-in report a merchant deletes returns on the next `db:seed`. A persisted seed key (or a tombstone) would let the seed tell "never created" from "deliberately removed" — it needs a column and an upgrade path for stores already seeded, so it is deferred rather than patched into the seeding loop.
-- **Operations "state metrics"**: the operations card stays a bespoke point-in-time endpoint on this branch (decided — see Implementation Path); whether time-less "state metrics" ever join the registry is deferred until a second consumer wants them.
## References
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 823a14fef4..68aa5cac4b 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1,3 +1,11 @@
+## 2026-09-10: Home-screen operations counters are reporting registry members
+
+**Context:** `dashboard/operations` served five counts as private methods on a serializer in the API gem, the dashboard hardcoded the matching rows (icons, labels, deep-link filters), one permission covered all five, and the out-of-stock deep link pointed at a products filter the server silently dropped. The low stock threshold was a request parameter with a hardcoded default that nothing sent.
+
+**Decision:** Counters are a fourth member type on `Spree.reporting` (`registry.counter`), evaluated by `Spree::Reporting::Counters` rather than compiled into the query — a counter has no range, currency or base. Each declares `subject` + `key_scope` like every other member and is filtered by the shared `Admin::ReportingAuthorization#member_allowed?`; the endpoint returns `{ key, label, description, value, link }` per counter and the dashboard renders whatever arrives. The link is declared beside the count so the list opened shows exactly the rows counted; a counter with no honest list (the stock ones, until the Inventory page) carries none. `low_stock_threshold` is a `Spree::Store` preference (default 5, 0 = off) surfaced in store settings. `Spree.operations` stays reserved; the registry name `Spree.reporting` is unchanged.
+
+**Consequences:** An extension registers a counter with a locale label and it appears on every merchant's home screen with the right permission gating and no dashboard change. A limited role sees a shorter list, not a refused card. New point-in-time numbers for the home screen are registrations — never serializer methods or client-side derivations. See `6.0-analytics-semantic-layer.md` Decision 15.
+
## 2026-09-10: Close-short writes the incoming counter, the Inventory page opens on every location, and the recount is an upgrade step
**Context:** Implementing Phase 7 of `6.0-inventory-operations.md` turned up three things the plan left open. The incoming writer table listed `Update` (which refuses anything past `draft`, so it never changes an incoming figure) and omitted the `Close` workflows, whose whole job is to take a document out of the open set the recount reads. The page had no stated default before a location is picked. And the backfill was described as "run it once" without saying who runs it.
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index 1194d12a94..2baa5bf2be 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -123,12 +123,12 @@ export interface ReportingSchema {
export interface DashboardOperations {
/** Prefixed channel id the order-based counts are scoped to; null means all channels. Stock counts are always store-wide. */
channel_id: string | null
- low_stock_threshold: number
- orders_to_fulfill: number
- payments_to_collect: number
- open_returns: number
- low_stock_items: number
- out_of_stock_items: number
+ /**
+ * The counters registered on `Spree.reporting` that this caller may read,
+ * in registration order. Labels and links come from the server, so a
+ * counter an extension registers renders without a dashboard change.
+ */
+ counters: DashboardCounter[]
}
export interface AuthTokens {
@@ -385,6 +385,7 @@ import type {
CustomerGroup,
CustomField,
CustomFieldDefinition,
+ DashboardCounter,
Delivery,
DeliveryMethod,
DeliveryMethodRule,
@@ -913,7 +914,7 @@ export class AdminClient {
readonly dashboard = {
operations: (
- params?: { low_stock_threshold?: number; channel_id?: string },
+ params?: { channel_id?: string },
options?: RequestOptions,
): Promise<DashboardOperations> =>
this.request<DashboardOperations>('GET', '/dashboard/operations', { ...options, params }),
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index 6d193ae721..34c76378a5 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -71,6 +71,8 @@ export interface StoreUpdateParams {
preferred_track_inventory_levels?: boolean
/** Holds stock for shoppers while they check out, so the same item can't be sold twice. */
preferred_stock_reservations_enabled?: boolean
+ /** On-hand units at or below which a tracked variant counts as low stock on the home screen; 0 turns the warning off. */
+ preferred_low_stock_threshold?: number
/** Records price changes for the EU Omnibus lowest-price-in-30-days display. */
preferred_track_price_history?: boolean
/** Whether products with no price in the shopper's currency still appear in listings. */
diff --git a/packages/admin-sdk/src/types/generated/DashboardCounter.ts b/packages/admin-sdk/src/types/generated/DashboardCounter.ts
new file mode 100644
index 0000000000..5a44e9d245
--- /dev/null
+++ b/packages/admin-sdk/src/types/generated/DashboardCounter.ts
@@ -0,0 +1,14 @@
+// Typelizer digest aa3687c1a949ba4231ccf94aaef269f4
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+interface DashboardCounter {
+ key: string;
+ label: string;
+ description: string | null;
+ value: number;
+ /** The list filter that shows exactly the rows counted, or null when no list can. */
+ link: { resource: string; filters: Array<{ field: string; operator: string; value: string }> } | null;
+}
+
+export default DashboardCounter;
diff --git a/packages/admin-sdk/src/types/generated/Store.ts b/packages/admin-sdk/src/types/generated/Store.ts
index 3d5476b94f..8ff26b41de 100644
--- a/packages/admin-sdk/src/types/generated/Store.ts
+++ b/packages/admin-sdk/src/types/generated/Store.ts
@@ -1,4 +1,4 @@
-// Typelizer digest c9549c74f8854097dc45c032053ec201
+// Typelizer digest 0070011fef453aa21c0e6fba41c422eb
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {SetupTask} from '@/types'
@@ -28,6 +28,7 @@ interface Store {
preferred_capture_method: string;
preferred_track_inventory_levels: boolean;
preferred_stock_reservations_enabled: boolean;
+ preferred_low_stock_threshold: number;
preferred_tax_using_ship_address: boolean;
preferred_track_price_history: boolean;
preferred_show_products_without_price: boolean;
diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.ts
index 62d3fda0cc..84eeda8456 100644
--- a/packages/admin-sdk/src/types/generated/index.ts
+++ b/packages/admin-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 71203d023f5adcd4947ceb6115c4f66a
+// Typelizer digest 36b0732995aed27eaf1cad4dd3780171
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { ClaimStatus, DataRequestStatus, ExchangeStatus, FeeKind, FulfillmentItemStatus, FulfillmentStatus, GiftCardStatus, ImportRowStatus, ImportStatus, InvitationStatus, PaymentStatus, PriceListStatus, ProductStatus, ProductSubmissionStatus, ReturnStatus, SellerPayoutStatus, SellerRequirementSubmissionStatus, SellerStatus, SellerTransferStatus, ShippingLabelStatus, StockLocationKind, TaxExemptionCertificateStatus } from './Enums'
@@ -37,6 +37,7 @@ export type { default as CustomFieldDefinition } from './CustomFieldDefinition'
export type { default as CustomField } from './CustomField'
export type { default as CustomerGroup } from './CustomerGroup'
export type { default as Customer } from './Customer'
+export type { default as DashboardCounter } from './DashboardCounter'
export type { default as DataRequest } from './DataRequest'
export type { default as DeliveryMethodRule } from './DeliveryMethodRule'
export type { default as DeliveryMethod } from './DeliveryMethod'
diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.ts
index 21cc5804a1..4880bb7b8d 100644
--- a/packages/admin-sdk/src/types/index.ts
+++ b/packages/admin-sdk/src/types/index.ts
@@ -47,6 +47,7 @@ export type { default as Customer } from './generated/Customer'
export type { default as CustomerGroup } from './generated/CustomerGroup'
export type { default as CustomField } from './generated/CustomField'
export type { default as CustomFieldDefinition } from './generated/CustomFieldDefinition'
+export type { default as DashboardCounter } from './generated/DashboardCounter'
export type { default as Delivery } from './generated/Delivery'
export type { default as DeliveryMethod } from './generated/DeliveryMethod'
export type { default as DeliveryMethodRule } from './generated/DeliveryMethodRule'
diff --git a/packages/dashboard-ui/src/spree/icons.ts b/packages/dashboard-ui/src/spree/icons.ts
index 7e83faeda3..3a7fab991f 100644
--- a/packages/dashboard-ui/src/spree/icons.ts
+++ b/packages/dashboard-ui/src/spree/icons.ts
@@ -36,6 +36,7 @@ export {
ChevronsRightIcon,
ChevronsUpDownIcon,
CircleCheckIcon,
+ CircleDotIcon,
CircleIcon,
ClipboardCheckIcon,
ClockIcon,
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 6db4d95199..a022e4a34a 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -2094,6 +2094,11 @@
"help": "احتساب الضريبة من عنوان شحن العميل. أوقف هذا الخيار لاحتساب الضريبة حسب عنوان الفوترة بدلاً من ذلك.",
"label": "احتساب الضريبة حسب عنوان الشحن"
},
+ "low_stock_threshold": {
+ "help": "يُعدّ المتغير المتتبَّع الذي يتوفر منه هذا العدد من الوحدات أو أقل مخزونًا منخفضًا في الصفحة الرئيسية. القيمة 0 توقف التنبيه.",
+ "label": "حدّ المخزون المنخفض",
+ "suffix": "وحدة"
+ },
"track_inventory_levels": {
"help": "احتساب الكميات المتوفرة. أوقفه لمعاملة كل منتج على أنه متاح دائمًا.",
"label": "تتبع مستويات المخزون"
@@ -3201,11 +3206,8 @@
"operations": {
"title": "العمليات",
"subtitle": "ما يتطلب انتباهك الآن.",
- "orders_to_fulfill": "طلبات بانتظار الشحن",
- "payments_to_collect": "مدفوعات مستحقة التحصيل",
- "open_returns": "مرتجعات مفتوحة",
- "low_stock_items": "متغيرات ذات مخزون منخفض",
- "out_of_stock_items": "متغيرات نفد مخزونها"
+ "failed": "تعذّر تحميل هذه الأعداد.",
+ "empty": "لا يوجد هنا ما يمكن لدورك رؤيته."
},
"rankings": {
"title": "التصنيفات",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 7c5a489208..8a4c679321 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -2076,6 +2076,11 @@
"help": "Die Steuer anhand der Lieferadresse des Kunden berechnen. Deaktivieren Sie diese Option, um stattdessen die Rechnungsadresse zu verwenden.",
"label": "Steuer nach Lieferadresse"
},
+ "low_stock_threshold": {
+ "help": "Eine bestandsgeführte Variante mit höchstens so vielen Einheiten gilt auf der Startseite als niedriger Bestand. 0 schaltet den Hinweis aus.",
+ "label": "Schwelle für niedrigen Bestand",
+ "suffix": "Stück"
+ },
"track_inventory_levels": {
"help": "Bestände zählen. Ausschalten, um jedes Produkt als immer verfügbar zu behandeln.",
"label": "Lagerbestand verfolgen"
@@ -3184,11 +3189,8 @@
"operations": {
"title": "Aufgaben",
"subtitle": "Was gerade Ihre Aufmerksamkeit braucht.",
- "orders_to_fulfill": "Zu versendende Bestellungen",
- "payments_to_collect": "Ausstehende Zahlungen",
- "open_returns": "Offene Retouren",
- "low_stock_items": "Varianten mit niedrigem Bestand",
- "out_of_stock_items": "Nicht vorrätige Varianten"
+ "failed": "Diese Zahlen konnten nicht geladen werden.",
+ "empty": "Für Ihre Rolle gibt es hier nichts zu sehen."
},
"rankings": {
"title": "Rangliste",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 6f4f5a594d..52d23a7ea0 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -2076,6 +2076,11 @@
"help": "Calculate tax from the customer's shipping address. Turn this off to tax by the billing address instead.",
"label": "Tax by shipping address"
},
+ "low_stock_threshold": {
+ "help": "A tracked variant with this many units or fewer on hand counts as low stock on the home screen. 0 turns the warning off.",
+ "label": "Low stock threshold",
+ "suffix": "units"
+ },
"track_inventory_levels": {
"help": "Count on-hand quantities. Turn off to treat every product as always available.",
"label": "Track stock levels"
@@ -3184,11 +3189,8 @@
"operations": {
"title": "Operations",
"subtitle": "What needs your attention right now.",
- "orders_to_fulfill": "Orders to fulfill",
- "payments_to_collect": "Payments to collect",
- "open_returns": "Open returns",
- "low_stock_items": "Low stock variants",
- "out_of_stock_items": "Out of stock variants"
+ "failed": "Could not load these counts.",
+ "empty": "Nothing here is visible to your role."
},
"rankings": {
"title": "Rankings",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index e09b09c567..12458ca136 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -2076,6 +2076,11 @@
"help": "Calculer la taxe à partir de l'adresse de livraison du client. Désactivez cette option pour utiliser l'adresse de facturation.",
"label": "Taxe selon l'adresse de livraison"
},
+ "low_stock_threshold": {
+ "help": "Une variante suivie ayant au plus ce nombre d’unités en stock est signalée en stock faible sur l’accueil. 0 désactive l’alerte.",
+ "label": "Seuil de stock faible",
+ "suffix": "unités"
+ },
"track_inventory_levels": {
"help": "Compter les quantités disponibles. Désactivez pour traiter chaque produit comme toujours disponible.",
"label": "Suivre les niveaux de stock"
@@ -3184,11 +3189,8 @@
"operations": {
"title": "Opérations",
"subtitle": "Ce qui demande votre attention en ce moment.",
- "orders_to_fulfill": "Commandes à expédier",
- "payments_to_collect": "Paiements à encaisser",
- "open_returns": "Retours ouverts",
- "low_stock_items": "Variantes en stock faible",
- "out_of_stock_items": "Variantes en rupture de stock"
+ "failed": "Impossible de charger ces compteurs.",
+ "empty": "Rien ici n’est visible pour votre rôle."
},
"rankings": {
"title": "Classements",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index b20bbd64a9..3824b07ab4 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -2094,6 +2094,11 @@
"help": "Oblicz podatek na podstawie adresu dostawy klienta. Wyłącz tę opcję, aby zamiast tego użyć adresu rozliczeniowego.",
"label": "Podatek według adresu dostawy"
},
+ "low_stock_threshold": {
+ "help": "Śledzony wariant z co najwyżej taką liczbą sztuk jest oznaczany na stronie głównej jako niski stan. 0 wyłącza ostrzeżenie.",
+ "label": "Próg niskiego stanu",
+ "suffix": "szt."
+ },
"track_inventory_levels": {
"help": "Licz dostępne ilości. Wyłącz, aby traktować każdy produkt jako zawsze dostępny.",
"label": "Śledź stany magazynowe"
@@ -3216,11 +3221,8 @@
"operations": {
"title": "Operacje",
"subtitle": "Co teraz wymaga Twojej uwagi.",
- "orders_to_fulfill": "Zamówienia do wysłania",
- "payments_to_collect": "Płatności do pobrania",
- "open_returns": "Otwarte zwroty",
- "low_stock_items": "Warianty z niskim stanem magazynowym",
- "out_of_stock_items": "Warianty niedostępne"
+ "failed": "Nie udało się wczytać tych liczników.",
+ "empty": "Twoja rola nie ma tu nic do wyświetlenia."
},
"rankings": {
"title": "Rankingi",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 8636ce01db..b5fc8e7a12 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -2071,6 +2071,11 @@
"help": "根据客户的配送地址计算税费。关闭此选项则改用账单地址计税。",
"label": "按配送地址计税"
},
+ "low_stock_threshold": {
+ "help": "现有库存不超过此数量的跟踪款式会在首页显示为低库存。设为 0 可关闭提醒。",
+ "label": "低库存阈值",
+ "suffix": "件"
+ },
"track_inventory_levels": {
"help": "统计现有库存。关闭后,所有商品都视为始终有货。",
"label": "跟踪库存数量"
@@ -3176,11 +3181,8 @@
"operations": {
"title": "运营事项",
"subtitle": "当前需要您处理的事项。",
- "orders_to_fulfill": "待发货订单",
- "payments_to_collect": "待收款订单",
- "open_returns": "未处理退货",
- "low_stock_items": "低库存款式",
- "out_of_stock_items": "缺货款式"
+ "failed": "无法加载这些统计。",
+ "empty": "您的角色在此没有可查看的内容。"
},
"rankings": {
"title": "排行榜",
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
index aedc212d09..94df18ae93 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx
@@ -1,4 +1,4 @@
-import type { DashboardOperations, ReportingQuery } from '@spree/admin-sdk'
+import type { DashboardCounter, DashboardOperations, ReportingQuery } from '@spree/admin-sdk'
import { SpreeError } from '@spree/admin-sdk'
import {
adminClient,
@@ -43,6 +43,7 @@ import {
import {
ChartColumnIcon,
ChevronRightIcon,
+ CircleDotIcon,
CreditCardIcon,
PackageXIcon,
RotateCcwIcon,
@@ -223,51 +224,51 @@ function DashboardPage() {
const OPERATIONS_ROW_CLASS =
'flex items-center gap-3 border-b border-border-subtle px-4 py-3 last:border-0'
-type OperationsFilter = { id: string; field: string; operator: string; value: string }
+/** Icons for the counters core ships. A counter an extension registers
+ * arrives with a label and a link but no icon, so it takes the fallback. */
+const COUNTER_ICONS: Record<string, typeof TruckIcon> = {
+ orders_to_fulfill: TruckIcon,
+ payments_to_collect: CreditCardIcon,
+ open_returns: RotateCcwIcon,
+ low_stock_items: TriangleAlertIcon,
+ out_of_stock_items: PackageXIcon,
+}
-const OPERATIONS_ROWS: Array<{
- key: keyof Omit<DashboardOperations, 'low_stock_threshold' | 'channel_id'>
- icon: typeof TruckIcon
- link?: { to: '/$storeId/orders' | '/$storeId/products'; filters: OperationsFilter[] }
-}> = [
- {
- key: 'orders_to_fulfill',
- icon: TruckIcon,
- link: {
- to: '/$storeId/orders',
- filters: [
- // Mirrors the `ready_to_ship` scope backing the count.
- { id: 'home-fulfill', field: 'fulfillment_status', operator: 'eq', value: 'unfulfilled' },
- ],
- },
- },
- {
- key: 'payments_to_collect',
- icon: CreditCardIcon,
- link: {
- to: '/$storeId/orders',
- filters: [
- // Mirrors the payments_to_collect statuses backing the count.
- {
- id: 'home-collect',
- field: 'payment_status',
- operator: 'in',
- value: 'none,authorized,partially_paid',
- },
- ],
- },
- },
- { key: 'open_returns', icon: RotateCcwIcon },
- { key: 'low_stock_items', icon: TriangleAlertIcon },
- {
- key: 'out_of_stock_items',
- icon: PackageXIcon,
- link: {
- to: '/$storeId/products',
- filters: [{ id: 'home-oos', field: 'in_stock', operator: 'eq', value: 'false' }],
- },
- },
-]
+/** Lists a server-declared link can land on. A resource this dashboard has
+ * no list for renders as a plain row rather than a dead link. */
+const COUNTER_ROUTES = {
+ orders: '/$storeId/orders',
+ returns: '/$storeId/returns',
+ products: '/$storeId/products',
+} as const
+
+/** The counters core registers, so the skeleton holds the card's height
+ * until the numbers arrive. */
+const COUNTER_SKELETON_ROWS = Object.keys(COUNTER_ICONS)
+
+type CounterLink = {
+ to: (typeof COUNTER_ROUTES)[keyof typeof COUNTER_ROUTES]
+ filters: Array<{ id: string; field: string; operator: string; value: string }>
+}
+
+/** The list a counter opens. The server declares the filter beside the count
+ * so the two cannot drift; the client only adds the channel it is viewing. */
+function counterLink(
+ link: DashboardCounter['link'],
+ channelId: string | undefined,
+): CounterLink | undefined {
+ if (!link) return undefined
+ const to = COUNTER_ROUTES[link.resource as keyof typeof COUNTER_ROUTES]
+ if (!to) return undefined
+
+ const filters = link.filters.map((filter) => ({ id: `home-${filter.field}`, ...filter }))
+ // Order counts are channel-scoped, so their lists must be too; stock and
+ // returns are store-wide and take no channel filter.
+ if (channelId && link.resource === 'orders') {
+ filters.push({ id: 'home-channel', field: 'channel_id', operator: 'eq', value: channelId })
+ }
+ return { to, filters }
+}
function OperationsCard({
data,
@@ -279,11 +280,12 @@ function OperationsCard({
className: string
/** The screen's channel, or undefined for all channels. */
channelId: string | undefined
- /** The counts could not be loaded — show a dash rather than a skeleton forever. */
+ /** The counts could not be loaded — say so rather than show a skeleton forever. */
failed: boolean
}) {
const { t } = useTranslation()
const { storeId } = Route.useParams()
+ const counters = data?.counters
return (
<Card className={className}>
@@ -293,69 +295,89 @@ function OperationsCard({
</CardHeader>
<CardContent className="p-0">
<div className="flex flex-col">
- {OPERATIONS_ROWS.map(({ key, icon: Icon, link }) => {
- const count = data?.[key]
- // Order counts are channel-scoped, so their lists must be too;
- // stock counts are store-wide and take no channel filter.
- const filters =
- link && channelId && link.to === '/$storeId/orders'
- ? [
- ...link.filters,
- { id: 'home-channel', field: 'channel_id', operator: 'eq', value: channelId },
- ]
- : link?.filters
- const content = (
- <>
- <span className="flex size-8 shrink-0 items-center justify-center rounded-md border hover:bg-accent/50">
- <Icon className="size-4 text-muted-foreground" />
- </span>
- <span className="flex-1 text-sm">{t(`admin.pages.home.operations.${key}`)}</span>
- {count === undefined ? (
- failed ? (
- <span className="text-sm text-muted-foreground">—</span>
- ) : (
- <Skeleton className="h-4 w-8" />
- )
- ) : (
- <span
- className={cn(
- 'text-sm font-semibold tabular-nums',
- count === 0 && 'text-muted-foreground',
- )}
- >
- {count.toLocaleString()}
- </span>
- )}
- {link && <ChevronRightIcon className="size-4 text-muted-foreground" />}
- </>
- )
-
- if (link) {
- return (
- <Link
- key={key}
- to={link.to}
- params={{ storeId }}
- search={{ filters }}
- className={cn(OPERATIONS_ROW_CLASS, 'hover:bg-accent/50')}
- >
- {content}
- </Link>
- )
- }
-
- return (
- <div key={key} className={OPERATIONS_ROW_CLASS}>
- {content}
- </div>
+ {counters === undefined ? (
+ failed ? (
+ <p className="px-4 py-3 text-sm text-muted-foreground">
+ {t('admin.pages.home.operations.failed')}
+ </p>
+ ) : (
+ COUNTER_SKELETON_ROWS.map((key) => (
+ <div key={key} className={OPERATIONS_ROW_CLASS}>
+ <Skeleton className="size-8 rounded-md" />
+ <Skeleton className="h-4 flex-1" />
+ <Skeleton className="h-4 w-8" />
+ </div>
+ ))
)
- })}
+ ) : counters.length === 0 ? (
+ <p className="px-4 py-3 text-sm text-muted-foreground">
+ {t('admin.pages.home.operations.empty')}
+ </p>
+ ) : (
+ counters.map((counter) => (
+ <CounterRow
+ key={counter.key}
+ counter={counter}
+ link={counterLink(counter.link, channelId)}
+ storeId={storeId}
+ />
+ ))
+ )}
</div>
</CardContent>
</Card>
)
}
+function CounterRow({
+ counter,
+ link,
+ storeId,
+}: {
+ counter: DashboardCounter
+ link: CounterLink | undefined
+ storeId: string
+}) {
+ const Icon = COUNTER_ICONS[counter.key] ?? CircleDotIcon
+ const content = (
+ <>
+ <span className="flex size-8 shrink-0 items-center justify-center rounded-md border">
+ <Icon className="size-4 text-muted-foreground" />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="text-sm">{counter.label}</span>
+ {counter.description && (
+ <span className="truncate text-xs text-muted-foreground">{counter.description}</span>
+ )}
+ </span>
+ <span
+ className={cn(
+ 'text-sm font-semibold tabular-nums',
+ counter.value === 0 && 'text-muted-foreground',
+ )}
+ >
+ {counter.value.toLocaleString()}
+ </span>
+ {link && <ChevronRightIcon className="size-4 text-muted-foreground" />}
+ </>
+ )
+
+ if (link) {
+ return (
+ <Link
+ to={link.to}
+ params={{ storeId }}
+ search={{ filters: link.filters }}
+ className={cn(OPERATIONS_ROW_CLASS, 'hover:bg-accent/50')}
+ >
+ {content}
+ </Link>
+ )
+ }
+
+ return <div className={OPERATIONS_ROW_CLASS}>{content}</div>
+}
+
type RankingTab = 'customers' | 'categories' | 'companies' | 'sellers'
// Each tab is one contract query; the revenue metric doubles as the share bar.
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx
index 8bca9bb211..29d9d5ee96 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx
@@ -25,6 +25,10 @@ import {
FieldLabel,
FormActions,
Input,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ InputGroupText,
ResourceLayout,
Select,
SelectContent,
@@ -133,6 +137,7 @@ function storeToFormValues(store: Store): StoreSettingsFormValues {
preferred_tax_using_ship_address: store.preferred_tax_using_ship_address ?? true,
preferred_track_inventory_levels: store.preferred_track_inventory_levels ?? true,
preferred_stock_reservations_enabled: store.preferred_stock_reservations_enabled ?? true,
+ preferred_low_stock_threshold: store.preferred_low_stock_threshold ?? 5,
preferred_track_price_history: store.preferred_track_price_history ?? true,
preferred_show_products_without_price: store.preferred_show_products_without_price ?? false,
preferred_disable_sku_validation: store.preferred_disable_sku_validation ?? false,
@@ -257,6 +262,7 @@ function StoreSettingsForm({ store }: { store: Store }) {
preferred_tax_using_ship_address: values.preferred_tax_using_ship_address,
preferred_track_inventory_levels: values.preferred_track_inventory_levels,
preferred_stock_reservations_enabled: values.preferred_stock_reservations_enabled,
+ preferred_low_stock_threshold: values.preferred_low_stock_threshold,
preferred_track_price_history: values.preferred_track_price_history,
preferred_show_products_without_price: values.preferred_show_products_without_price,
preferred_disable_sku_validation: values.preferred_disable_sku_validation,
@@ -647,6 +653,30 @@ function StoreSettingsForm({ store }: { store: Store }) {
name="preferred_stock_reservations_enabled"
control={form.control}
/>
+ <Field>
+ <FieldLabel htmlFor="store-low-stock-threshold">
+ {t('admin.fields.store.low_stock_threshold.label')}
+ </FieldLabel>
+ <InputGroup>
+ <InputGroupInput
+ id="store-low-stock-threshold"
+ type="number"
+ min={0}
+ step={1}
+ aria-invalid={!!errors.preferred_low_stock_threshold || undefined}
+ {...form.register('preferred_low_stock_threshold')}
+ />
+ <InputGroupAddon align="inline-end">
+ <InputGroupText>
+ {t('admin.fields.store.low_stock_threshold.suffix')}
+ </InputGroupText>
+ </InputGroupAddon>
+ </InputGroup>
+ <FieldDescription>
+ {t('admin.fields.store.low_stock_threshold.help')}
+ </FieldDescription>
+ <FieldError errors={[errors.preferred_low_stock_threshold]} />
+ </Field>
</FieldGroup>
</CardContent>
</Card>
diff --git a/packages/dashboard/src/schemas/store.ts b/packages/dashboard/src/schemas/store.ts
index d9e8edb950..0d967841a9 100644
--- a/packages/dashboard/src/schemas/store.ts
+++ b/packages/dashboard/src/schemas/store.ts
@@ -57,6 +57,10 @@ export const storeSettingsFormSchema = z.object({
preferred_tax_using_ship_address: z.boolean(),
preferred_track_inventory_levels: z.boolean(),
preferred_stock_reservations_enabled: z.boolean(),
+ preferred_low_stock_threshold: z.coerce
+ .number()
+ .int()
+ .min(0, { error: requiredMessage('store.preferred_low_stock_threshold') }),
preferred_track_price_history: z.boolean(),
preferred_show_products_without_price: z.boolean(),
preferred_disable_sku_validation: z.boolean(),
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/reporting_authorization.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/reporting_authorization.rb
new file mode 100644
index 0000000000..8ba590c3ad
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/reporting_authorization.rb
@@ -0,0 +1,27 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Per-member authorization for the reporting vocabulary. Metrics,
+ # dimensions and counters all declare a `subject` (checked for JWT
+ # staff through CanCanCan) paired with a `key_scope` (checked for
+ # secret keys), so one predicate answers for every member and every
+ # surface that lists them — the schema, a query, the home screen's
+ # counters — filters by the same rule.
+ module ReportingAuthorization
+ extend ActiveSupport::Concern
+
+ private
+
+ def member_allowed?(member)
+ if current_api_key.present?
+ member.key_scope.blank? || current_api_key.has_scope?(member.key_scope)
+ else
+ member.subject.nil? || can?(:read, member.subject.call)
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb
index d9d98ffbeb..125ff21ae3 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb
@@ -2,33 +2,34 @@ module Spree
module Api
module V3
module Admin
- # Point-in-time operational counts for the dashboard home. Time-series
+ # Point-in-time operational counts for the dashboard home, evaluated
+ # from the counters registered on Spree.reporting. Time-series
# analytics live in the semantic reporting endpoint (ReportingController).
class DashboardController < Admin::BaseController
+ include ReportingAuthorization
+
scoped_resource :dashboard
# GET /api/v3/admin/dashboard/operations
+ #
+ # Filtered to the counters this caller may read, so a limited role
+ # gets a shorter list rather than a refused card.
def operations
- serializer = DashboardOperationsSerializer.new(
+ channel = requested_channel
+ counters = Spree::Reporting::Counters.new(
store: current_store,
- channel: requested_channel,
- low_stock_threshold: low_stock_threshold
+ channel: channel,
+ allowed: ->(counter) { member_allowed?(counter) }
)
- render json: serializer.to_h
+ render json: {
+ channel_id: channel&.prefixed_id,
+ counters: DashboardCounterSerializer.new(counters.to_a).serializable_hash
+ }
end
private
- # `?low_stock_threshold[]=1` arrives as an Array, which has no #to_i;
- # anything that is not a plain integer falls back to the default.
- def low_stock_threshold
- value = params[:low_stock_threshold]
- threshold = value.is_a?(String) || value.is_a?(Integer) ? Integer(value, exception: false) : nil
-
- (threshold || DashboardOperationsSerializer::DEFAULT_LOW_STOCK_THRESHOLD).clamp(1, 1000)
- end
-
def action_kind
'read'
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/reporting_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/reporting_controller.rb
index 2f5730fe33..1fb8b1de2e 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/reporting_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/reporting_controller.rb
@@ -6,6 +6,8 @@ module Spree
# one query endpoint compiled against the Spree.reporting registry, plus
# registry introspection for pickers and agent tool schemas.
class ReportingController < Admin::BaseController
+ include ReportingAuthorization
+
scoped_resource :reports
rescue_from Spree::Reporting::UnknownMember, Spree::Reporting::InvalidQuery, with: :render_invalid_query
@@ -74,16 +76,6 @@ module Spree
end
end
- # Metrics and dimensions declare authorization the same way, so one
- # predicate answers for both.
- def member_allowed?(member)
- if current_api_key.present?
- member.key_scope.blank? || current_api_key.has_scope?(member.key_scope)
- else
- member.subject.nil? || can?(:read, member.subject.call)
- end
- end
-
# An unknown member carries what it was and what was valid instead.
# Passing those through as `details` lets a client correct the query
# without parsing the sentence — the same list the schema endpoint
diff --git a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb
index 919ebdb116..25d06037ab 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb
@@ -91,6 +91,7 @@ module Spree
:preferred_auto_capture_on_dispatch,
:preferred_track_inventory_levels,
:preferred_stock_reservations_enabled,
+ :preferred_low_stock_threshold,
:preferred_tax_using_ship_address,
:preferred_track_price_history,
:preferred_show_products_without_price,
diff --git a/spree/api/app/serializers/spree/api/v3/admin/dashboard_counter_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/dashboard_counter_serializer.rb
new file mode 100644
index 0000000000..a17593a79a
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/dashboard_counter_serializer.rb
@@ -0,0 +1,20 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # One home-screen counter, as evaluated for the caller. A value
+ # object, so it carries no id: `key` is the registered counter name.
+ class DashboardCounterSerializer
+ include Alba::Resource
+ include Typelizer::DSL
+
+ typelize key: :string, label: :string, description: [:string, nullable: true], value: :number,
+ link: ['{ resource: string; filters: Array<{ field: string; operator: string; value: string }> } | null',
+ comment: 'The list filter that shows exactly the rows counted, or null when no list can.']
+
+ attributes :key, :label, :description, :value, :link
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/dashboard_operations_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/dashboard_operations_serializer.rb
deleted file mode 100644
index 82b4f595b0..0000000000
--- a/spree/api/app/serializers/spree/api/v3/admin/dashboard_operations_serializer.rb
+++ /dev/null
@@ -1,81 +0,0 @@
-module Spree
- module Api
- module V3
- module Admin
- # Builds the home dashboard operations payload: counts of things that
- # need back-office attention right now (not scoped to a date range).
- # A channel narrows the order-derived counts; stock counts stay
- # store-wide since inventory is channel-agnostic.
- class DashboardOperationsSerializer
- DEFAULT_LOW_STOCK_THRESHOLD = 5
-
- attr_reader :store, :channel, :low_stock_threshold
-
- def initialize(store:, channel: nil, low_stock_threshold: DEFAULT_LOW_STOCK_THRESHOLD)
- @store = store
- @channel = channel
- @low_stock_threshold = low_stock_threshold
- end
-
- def to_h
- {
- channel_id: channel&.prefixed_id,
- low_stock_threshold: low_stock_threshold,
- orders_to_fulfill: orders_to_fulfill,
- payments_to_collect: payments_to_collect,
- open_returns: open_returns,
- low_stock_items: low_stock_items,
- out_of_stock_items: out_of_stock_items
- }
- end
-
- private
-
- def actionable_orders
- store.orders.complete.not_canceled.for_channel(channel)
- end
-
- def orders_to_fulfill
- actionable_orders.ready_to_ship.count
- end
-
- # Placed orders still owed money: nothing collected yet, authorized but
- # not captured, or only partially paid.
- def payments_to_collect
- actionable_orders.where(payment_status: %w[none authorized partially_paid]).count
- end
-
- def open_returns
- store.returns
- .joins(:order)
- .where(status: %w[requested approved])
- .merge(Spree::Order.for_channel(channel))
- .count
- end
-
- def low_stock_items
- tracked_stock_items
- .where(count_on_hand: 1..low_stock_threshold)
- .distinct
- .count(:variant_id)
- end
-
- def out_of_stock_items
- tracked_stock_items
- .where(count_on_hand: ..0)
- .distinct
- .count(:variant_id)
- end
-
- # `store.stock_levels` walks products → variants, so paranoia default
- # scopes already exclude deleted products/variants.
- def tracked_stock_items
- store.stock_levels
- .with_active_stock_location
- .where(Spree::Variant.table_name => { track_inventory: true })
- end
- end
- end
- end
- end
-end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb
index 09bd7aa6a5..14df8ac42e 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb
@@ -28,6 +28,7 @@ module Spree
preferred_capture_method: :string,
preferred_track_inventory_levels: :boolean,
preferred_stock_reservations_enabled: :boolean,
+ preferred_low_stock_threshold: :number,
preferred_tax_using_ship_address: :boolean,
preferred_track_price_history: :boolean,
preferred_show_products_without_price: :boolean,
@@ -74,6 +75,7 @@ module Spree
:preferred_capture_method,
:preferred_track_inventory_levels,
:preferred_stock_reservations_enabled,
+ :preferred_low_stock_threshold,
:preferred_tax_using_ship_address,
:preferred_track_price_history,
:preferred_show_products_without_price,
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/dashboard_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/dashboard_controller_spec.rb
index 3b52a9c695..4850dd87f8 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/dashboard_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/dashboard_controller_spec.rb
@@ -10,73 +10,74 @@ RSpec.describe Spree::Api::V3::Admin::DashboardController, type: :controller do
describe 'GET #operations' do
subject { get :operations, as: :json }
- it 'returns all counters' do
+ let(:counter_keys) { json_response['counters'].map { |counter| counter['key'] } }
+
+ it 'returns every registered counter with its label, value and link' do
subject
+
expect(response).to have_http_status(:ok)
- expect(json_response).to include(
- 'low_stock_threshold', 'orders_to_fulfill', 'payments_to_collect',
- 'open_returns', 'low_stock_items', 'out_of_stock_items'
+ expect(json_response['channel_id']).to be_nil
+ expect(counter_keys).to eq(%w[orders_to_fulfill payments_to_collect open_returns low_stock_items out_of_stock_items])
+
+ fulfill = json_response['counters'].first
+ expect(fulfill).to include('label' => 'Orders to fulfill', 'value' => 0)
+ expect(fulfill['link']).to eq(
+ 'resource' => 'orders',
+ 'filters' => [{ 'field' => 'fulfillment_status', 'operator' => 'eq', 'value' => 'unfulfilled' }]
)
end
- context 'with actionable orders' do
- let!(:ready_order) { create(:order_ready_to_ship, store: store) }
- let!(:balance_due_order) do
- create(:completed_order_with_totals, store: store, payment_status: 'authorized', fulfillment_status: 'fulfilled')
- end
+ it 'scopes order counts to the requested channel' do
+ channel = create(:channel, store: store)
+ create(:order_ready_to_ship, store: store)
+ create(:order_ready_to_ship, store: store, channel: channel)
- it 'counts orders to fulfill and payments to collect' do
- subject
- expect(json_response['orders_to_fulfill']).to eq(1)
- expect(json_response['payments_to_collect']).to eq(1)
- end
+ get :operations, params: { channel_id: channel.prefixed_id }, as: :json
- it 'scopes order counts to the requested channel' do
- channel = create(:channel, store: store)
- create(:order_ready_to_ship, store: store, channel: channel)
-
- get :operations, params: { channel_id: channel.prefixed_id }, as: :json
- expect(json_response['channel_id']).to eq(channel.prefixed_id)
- expect(json_response['orders_to_fulfill']).to eq(1)
- expect(json_response['payments_to_collect']).to eq(0)
- end
+ expect(json_response['channel_id']).to eq(channel.prefixed_id)
+ expect(json_response['counters'].find { |c| c['key'] == 'orders_to_fulfill' }['value']).to eq(1)
end
- context 'with an open return' do
- let!(:open_return) { create(:return) }
+ it 'refuses a channel from another store' do
+ other_channel = create(:channel, store: create(:store))
- it 'counts requested and approved returns' do
- subject
- expect(json_response['open_returns']).to eq(1)
- end
+ get :operations, params: { channel_id: other_channel.prefixed_id }, as: :json
+ expect(response).to have_http_status(:not_found)
end
- context 'with stock levels' do
- let!(:low_stock_product) { create(:product, store: store) }
- let!(:out_of_stock_product) { create(:product, store: store) }
+ context 'via a secret key' do
+ let(:headers) { { 'x-spree-api-key' => key.plaintext_token } }
+ let(:key) { create(:api_key, :secret, store: store, scopes: scopes) }
- before do
- low_stock_product.default_variant.stock_levels.first.update!(count_on_hand: 3)
- end
+ context 'with the dashboard scope alone' do
+ let(:scopes) { %w[read_dashboard] }
- it 'counts low stock and out of stock variants' do
- subject
- expect(json_response['low_stock_items']).to eq(1)
- expect(json_response['out_of_stock_items']).to eq(1)
+ it 'returns an empty list rather than counters over data the key cannot read' do
+ subject
+ expect(response).to have_http_status(:ok)
+ expect(counter_keys).to be_empty
+ end
end
- it 'respects the low_stock_threshold param' do
- get :operations, params: { low_stock_threshold: 2 }, as: :json
- expect(json_response['low_stock_threshold']).to eq(2)
- expect(json_response['low_stock_items']).to eq(0)
+ context 'with the scopes some counters require' do
+ let(:scopes) { %w[read_dashboard read_stock] }
+
+ it 'returns only those counters' do
+ subject
+ expect(counter_keys).to eq(%w[low_stock_items out_of_stock_items])
+ end
end
+ end
+
+ context 'for a staff role without order access' do
+ include_context 'API v3 Admin with custom permissions'
- it 'ignores variants that do not track inventory' do
- low_stock_product.default_variant.update!(track_inventory: false)
- out_of_stock_product.default_variant.update!(track_inventory: false)
+ let(:custom_permissions) { %w[read_dashboard read_stock] }
+
+ it 'returns only the stock counters' do
subject
- expect(json_response['low_stock_items']).to eq(0)
- expect(json_response['out_of_stock_items']).to eq(0)
+ expect(response).to have_http_status(:ok)
+ expect(counter_keys).to eq(%w[low_stock_items out_of_stock_items])
end
end
@@ -89,10 +90,4 @@ RSpec.describe Spree::Api::V3::Admin::DashboardController, type: :controller do
end
end
end
-
- it 'ignores a non-scalar low_stock_threshold instead of raising' do
- get :operations, params: { low_stock_threshold: ['1'] }, as: :json
-
- expect(response).to have_http_status(:ok)
- end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb
index 5970afb464..285cb0eb25 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb
@@ -187,6 +187,22 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
end
end
+ context 'with the low stock threshold' do
+ let(:params) { { preferred_low_stock_threshold: 12 } }
+
+ it 'saves it and returns it' do
+ subject
+ expect(response).to have_http_status(:ok)
+ expect(json_response['preferred_low_stock_threshold']).to eq(12)
+ expect(store.reload.preferred_low_stock_threshold).to eq(12)
+ end
+
+ it 'refuses a negative threshold' do
+ patch :update, params: { preferred_low_stock_threshold: -1 }, as: :json
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+ end
+
context 'with invalid params' do
let(:params) { { name: '' } }
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 2a2d349c3b..8dcdb4898b 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -116,6 +116,9 @@ module Spree
default: Spree::ProviderFailurePolicy::DEFAULT_INVENTORY_POLICY
# Catalog preferences
preference :track_inventory_levels, :boolean, default: true
+ # On-hand quantity at or below which a tracked variant counts as running
+ # low on the home screen. 0 turns the warning off.
+ preference :low_stock_threshold, :integer, default: 5
preference :show_products_without_price, :boolean, default: false
preference :disable_sku_validation, :boolean, default: false
# Records price changes so the storefront can show the lowest price of the
@@ -316,6 +319,7 @@ module Spree
validates :preferred_digital_asset_link_expire_time,
numericality: { only_integer: true, greater_than: 0, less_than_or_equal_to: 1.hour.to_i }
validates :preferred_stock_reservation_ttl_minutes, numericality: { only_integer: true, greater_than: 0 }
+ validates :preferred_low_stock_threshold, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
# A fraction, not a percentage: 0.21 is 21%. Bounded because the value is
# multiplied straight into what a seller is charged, so a negative would
# credit them and a figure above 1 would bill more tax than fee.
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 39cfcca692..fcd458d357 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -1685,6 +1685,25 @@ en:
products_performance: Products performance
sales_total: Sales total
reporting:
+ counters:
+ low_stock_items:
+ description:
+ one: 1 unit or fewer on hand at an active location.
+ other: "%{count} units or fewer on hand at an active location."
+ zero: Turned off. Set a low stock threshold in store settings to use this.
+ label: Low stock variants
+ open_returns:
+ description: Returns requested or approved and not yet received.
+ label: Open returns
+ orders_to_fulfill:
+ description: Placed orders with nothing shipped yet.
+ label: Orders to fulfill
+ out_of_stock_items:
+ description: Tracked variants with nothing on hand at any active location.
+ label: Out of stock variants
+ payments_to_collect:
+ description: Placed orders still owed money.
+ label: Payments to collect
dimensions:
category:
description: The category the sold product belongs to.
diff --git a/spree/core/lib/spree/reporting.rb b/spree/core/lib/spree/reporting.rb
index 3f6159fa29..f8f07caf54 100644
--- a/spree/core/lib/spree/reporting.rb
+++ b/spree/core/lib/spree/reporting.rb
@@ -3,6 +3,8 @@ require 'spree/reporting/default_vocabulary'
require 'spree/reporting/query'
require 'spree/reporting/schema'
require 'spree/reporting/result'
+require 'spree/reporting/counter_result'
+require 'spree/reporting/counters'
require 'spree/reporting/hydration'
require 'spree/reporting/adapters/base'
require 'spree/reporting/adapters/live'
@@ -14,6 +16,7 @@ module Spree
#
# Spree.reporting.metric :wholesale_margin, sql: '...', base: :line_items, format: :money
# Spree.reporting.dimension :warehouse, base: :orders, column: :stock_location_id, lookup: 'Spree::StockLocation'
+ # Spree.reporting.counter :orders_on_hold, count: ->(store, channel:) { store.orders.on_hold.count }
#
# Consumers (Admin API, dashboard, saved reports, AI tools) compose queries
# against registered names only — see Spree::Reporting::Query.
diff --git a/spree/core/lib/spree/reporting/counter_result.rb b/spree/core/lib/spree/reporting/counter_result.rb
new file mode 100644
index 0000000000..78caf82f22
--- /dev/null
+++ b/spree/core/lib/spree/reporting/counter_result.rb
@@ -0,0 +1,18 @@
+module Spree
+ module Reporting
+ # One evaluated counter: what it is called, what it counts right now, and
+ # where that number leads. Never persisted — a fresh evaluation each time
+ # the home screen asks.
+ class CounterResult
+ include ActiveModel::Model
+ include ActiveModel::Attributes
+
+ attribute :key, :string
+ attribute :label, :string
+ attribute :description, :string
+ attribute :value, :integer
+ # `{ resource:, filters: [...] }` as registered, or nil.
+ attribute :link
+ end
+ end
+end
diff --git a/spree/core/lib/spree/reporting/counters.rb b/spree/core/lib/spree/reporting/counters.rb
new file mode 100644
index 0000000000..4daa658878
--- /dev/null
+++ b/spree/core/lib/spree/reporting/counters.rb
@@ -0,0 +1,46 @@
+module Spree
+ module Reporting
+ # Evaluates the registered counters for one store, filtered to those the
+ # caller may read. Labels resolve through the locale the way the schema
+ # resolves metric labels, so an extension's counter needs no dashboard
+ # release to show up with a name.
+ class Counters
+ # @param store [Spree::Store]
+ # @param channel [Spree::Channel, nil] narrows order-derived counts; nil means all channels
+ # @param registry [Registry]
+ # @param allowed [Proc] ->(counter) { true/false } — the same permission
+ # gate the schema applies to metrics and dimensions
+ def initialize(store:, channel: nil, registry: Spree.reporting, allowed: ->(_counter) { true })
+ @store = store
+ @channel = channel
+ @registry = registry
+ @allowed = allowed
+ end
+
+ # @return [Array<CounterResult>] in registration order
+ def to_a
+ @registry.counters.values.select { |counter| @allowed.call(counter) }.map do |counter|
+ CounterResult.new(
+ key: counter.name,
+ label: translate(counter.name, :label) || counter.name.to_s.humanize,
+ description: description_for(counter),
+ value: counter.count.call(@store, channel: @channel),
+ link: counter.link&.deep_stringify_keys
+ )
+ end
+ end
+
+ private
+
+ def description_for(counter)
+ return counter.description.call(@store) if counter.description.respond_to?(:call)
+
+ translate(counter.name, :description)
+ end
+
+ def translate(name, facet)
+ Spree.t("reporting.counters.#{name}.#{facet}", default: nil)
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/reporting/default_vocabulary.rb b/spree/core/lib/spree/reporting/default_vocabulary.rb
index d543129dc7..76e7d00fdf 100644
--- a/spree/core/lib/spree/reporting/default_vocabulary.rb
+++ b/spree/core/lib/spree/reporting/default_vocabulary.rb
@@ -87,6 +87,20 @@ module Spree
"SUM(CASE WHEN %{stock_movements}.kind = '#{kind}' THEN %{stock_movements}.quantity ELSE 0 END)"
end
+ PAYMENTS_OWED = %w[none authorized partially_paid].freeze
+ OPEN_RETURN_STATUSES = %w[requested approved].freeze
+
+ # Placed orders a merchant still acts on, narrowed to a channel when one
+ # is being looked at.
+ PLACED_ORDERS = ->(store, channel) { store.orders.complete.not_canceled.for_channel(channel) }
+
+ # Stock a merchant is actually counting: tracked variants at active
+ # locations. `store.stock_levels` walks products → variants, so paranoia
+ # default scopes already exclude deleted products and variants.
+ TRACKED_STOCK = lambda { |store|
+ store.stock_levels.with_active_stock_location.where(Spree::Variant.table_name => { track_inventory: true })
+ }
+
def self.install(registry)
registry.instance_eval do
# ---- bases ----
@@ -384,6 +398,54 @@ module Spree
[location.id, { id: location.prefixed_id, label: location.name, meta: {} }]
end
}
+
+ # ---- counters ----
+ #
+ # What needs attention right now. Order counters honour the channel
+ # a merchant is looking at; stock is channel-agnostic. Each link
+ # names the list filter that shows exactly the rows counted — the
+ # stock counters carry none until an inventory list can express
+ # "at or below n on hand" (docs/plans/6.0-inventory-operations.md).
+
+ counter :orders_to_fulfill,
+ subject: -> { Spree::Order }, key_scope: 'read_orders',
+ count: ->(store, channel:) { PLACED_ORDERS.call(store, channel).ready_to_ship.count },
+ link: { resource: 'orders',
+ filters: [{ field: 'fulfillment_status', operator: 'eq', value: 'unfulfilled' }] }
+
+ # Placed orders still owed money: nothing collected yet, authorized
+ # but not captured, or only partially paid.
+ counter :payments_to_collect,
+ subject: -> { Spree::Order }, key_scope: 'read_orders',
+ count: lambda { |store, channel:|
+ PLACED_ORDERS.call(store, channel).where(payment_status: PAYMENTS_OWED).count
+ },
+ link: { resource: 'orders',
+ filters: [{ field: 'payment_status', operator: 'in', value: PAYMENTS_OWED.join(',') }] }
+
+ counter :open_returns,
+ subject: -> { Spree::Return }, key_scope: 'read_orders',
+ count: lambda { |store, channel:|
+ store.returns.joins(:order).where(status: OPEN_RETURN_STATUSES).
+ merge(Spree::Order.for_channel(channel)).count
+ },
+ link: { resource: 'returns',
+ filters: [{ field: 'status', operator: 'in', value: OPEN_RETURN_STATUSES.join(',') }] }
+
+ counter :low_stock_items,
+ subject: -> { Spree::StockLevel }, key_scope: 'read_stock',
+ count: lambda { |store, channel:|
+ TRACKED_STOCK.call(store).where(count_on_hand: 1..store.preferred_low_stock_threshold).
+ distinct.count(:variant_id)
+ },
+ description: lambda { |store|
+ Spree.t('reporting.counters.low_stock_items.description',
+ count: store.preferred_low_stock_threshold)
+ }
+
+ counter :out_of_stock_items,
+ subject: -> { Spree::StockLevel }, key_scope: 'read_stock',
+ count: ->(store, channel:) { TRACKED_STOCK.call(store).where(count_on_hand: ..0).distinct.count(:variant_id) }
end
end
end
diff --git a/spree/core/lib/spree/reporting/registry.rb b/spree/core/lib/spree/reporting/registry.rb
index 13766e16bd..e149918bd8 100644
--- a/spree/core/lib/spree/reporting/registry.rb
+++ b/spree/core/lib/spree/reporting/registry.rb
@@ -105,16 +105,39 @@ module Spree
def reaches?(dimension_base) = Array(reaches).include?(dimension_base)
end
- # Allowlist of queryable metrics + dimensions. One global instance lives at
- # `Spree.reporting`; core seeds the starter vocabulary in the engine
- # initializer and applications/extensions append theirs in initializer files.
+ # A point-in-time count of things that need attention right now: orders
+ # waiting to ship, returns waiting on a decision, variants running low.
+ # No time range, no currency and no base — a counter is not a report
+ # over a period but the state of the store at this instant, which is why
+ # it is evaluated by a lambda rather than compiled into the query.
+ #
+ # @!attribute count
+ # ->(store, channel:) returning an Integer. A channel narrows what can
+ # be narrowed (orders); store-wide facts such as stock ignore it.
+ # @!attribute subject / key_scope
+ # Authorization, declared the same way as on metrics and dimensions,
+ # so a caller sees only the counters over data they may read.
+ # @!attribute link
+ # Where the number leads, declared beside the count so the two cannot
+ # disagree: `{ resource: 'orders', filters: [{ field:, operator:, value: }] }`.
+ # Omitted when no list can honestly show exactly what was counted.
+ # @!attribute description
+ # ->(store) returning a sentence, for counters whose meaning depends on
+ # a store setting (a threshold). Omitted = the locale's static text.
+ Counter = Struct.new(:name, :count, :subject, :key_scope, :link, :description, keyword_init: true)
+
+ # Allowlist of queryable metrics, dimensions and counters. One global
+ # instance lives at `Spree.reporting`; core seeds the starter vocabulary in
+ # the engine initializer and applications/extensions append theirs in
+ # initializer files.
class Registry
- attr_reader :metrics, :dimensions, :bases
+ attr_reader :metrics, :dimensions, :bases, :counters
def initialize
@metrics = {}
@dimensions = {}
@bases = {}
+ @counters = {}
end
# @param name [Symbol]
@@ -161,10 +184,28 @@ module Spree
@dimensions[name] = Dimension.new(name: name, **opts)
end
+ # @param name [Symbol]
+ # @param count [Proc] ->(store, channel:) → Integer
+ # @param link [Hash, nil] `{ resource:, filters: [{ field:, operator:, value: }] }`
+ # @param description [Proc, nil] ->(store) → String
+ def counter(name, replace: false, count:, subject: nil, key_scope: nil, link: nil, description: nil)
+ name = name.to_sym
+ raise ArgumentError, "counter #{name} already registered (pass replace: true to override)" if @counters.key?(name) && !replace
+ raise ArgumentError, "counter #{name} declares a subject and must also declare its key_scope" if subject && key_scope.blank?
+ raise ArgumentError, "counter #{name} needs a callable count" unless count.respond_to?(:call)
+
+ @counters[name] = Counter.new(name: name, count: count, subject: subject, key_scope: key_scope,
+ link: link, description: description)
+ end
+
def metric!(name)
@metrics[name.to_sym] || raise(UnknownMember.new(:metric, name, @metrics.keys))
end
+ def counter!(name)
+ @counters[name.to_sym] || raise(UnknownMember.new(:counter, name, @counters.keys))
+ end
+
def dimension!(name)
@dimensions[name.to_sym] || raise(UnknownMember.new(:dimension, name, @dimensions.keys))
end
@@ -192,7 +233,6 @@ module Spree
def family_of(metric)
base!(components(metric).first.base).family
end
-
end
end
end
diff --git a/spree/core/spec/lib/spree/reporting/counters_spec.rb b/spree/core/spec/lib/spree/reporting/counters_spec.rb
new file mode 100644
index 0000000000..301c0dd334
--- /dev/null
+++ b/spree/core/spec/lib/spree/reporting/counters_spec.rb
@@ -0,0 +1,106 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Reporting::Counters do
+ let(:store) { @default_store }
+
+ def evaluate(**options)
+ described_class.new(store: store, **options).to_a.index_by(&:key)
+ end
+
+ it 'evaluates every registered counter with a localized label and its link' do
+ results = evaluate
+
+ expect(results.keys).to eq(%w[orders_to_fulfill payments_to_collect open_returns low_stock_items out_of_stock_items])
+ expect(results['orders_to_fulfill'].label).to eq('Orders to fulfill')
+ expect(results['orders_to_fulfill'].link).to eq(
+ 'resource' => 'orders',
+ 'filters' => [{ 'field' => 'fulfillment_status', 'operator' => 'eq', 'value' => 'unfulfilled' }]
+ )
+ expect(results['out_of_stock_items'].link).to be_nil
+ expect(results.values.map(&:value)).to all(be_a(Integer))
+ end
+
+ it 'keeps only the counters the caller may read' do
+ results = evaluate(allowed: ->(counter) { counter.key_scope == 'read_stock' })
+
+ expect(results.keys).to eq(%w[low_stock_items out_of_stock_items])
+ end
+
+ it 'humanizes the name of a counter with no locale entry' do
+ registry = Spree::Reporting::Registry.new
+ registry.counter :flagged_orders, count: ->(_store, channel:) { 7 }
+
+ result = described_class.new(store: store, registry: registry).to_a.first
+ expect(result.label).to eq('Flagged orders')
+ expect(result.description).to be_nil
+ expect(result.value).to eq(7)
+ end
+
+ context 'with orders' do
+ let!(:ready_order) { create(:order_ready_to_ship, store: store) }
+ let!(:balance_due_order) do
+ create(:completed_order_with_totals, store: store, payment_status: 'authorized', fulfillment_status: 'fulfilled')
+ end
+
+ it 'counts orders to fulfill and payments to collect' do
+ results = evaluate
+ expect(results['orders_to_fulfill'].value).to eq(1)
+ expect(results['payments_to_collect'].value).to eq(1)
+ end
+
+ it 'narrows order counts to a channel' do
+ channel = create(:channel, store: store)
+ create(:order_ready_to_ship, store: store, channel: channel)
+
+ results = evaluate(channel: channel)
+ expect(results['orders_to_fulfill'].value).to eq(1)
+ expect(results['payments_to_collect'].value).to eq(0)
+ end
+ end
+
+ context 'with an open return' do
+ let!(:open_return) { create(:return) }
+
+ it 'counts requested and approved returns' do
+ expect(evaluate['open_returns'].value).to eq(1)
+ end
+ end
+
+ context 'with stock levels' do
+ let!(:low_stock_product) { create(:product, store: store) }
+ let!(:out_of_stock_product) { create(:product, store: store) }
+
+ before { low_stock_product.default_variant.stock_levels.first.update!(count_on_hand: 3) }
+
+ it 'counts low stock and out of stock variants' do
+ results = evaluate
+ expect(results['low_stock_items'].value).to eq(1)
+ expect(results['out_of_stock_items'].value).to eq(1)
+ end
+
+ it 'reads the low stock threshold from the store and says so in the description' do
+ stub_store_preferences(store, low_stock_threshold: 2)
+
+ result = evaluate['low_stock_items']
+ expect(result.value).to eq(0)
+ expect(result.description).to eq('2 units or fewer on hand at an active location.')
+ end
+
+ it 'turns the low stock warning off at a threshold of zero' do
+ stub_store_preferences(store, low_stock_threshold: 0)
+
+ result = evaluate['low_stock_items']
+ expect(result.value).to eq(0)
+ expect(result.description).to start_with('Turned off')
+ end
+
+ it 'ignores variants that do not track inventory' do
+ low_stock_product.default_variant.update!(track_inventory: false)
+ out_of_stock_product.default_variant.update!(track_inventory: false)
+
+ results = evaluate
+ expect(results['low_stock_items'].value).to eq(0)
+ expect(results['out_of_stock_items'].value).to eq(0)
+ end
+ end
+end
diff --git a/spree/core/spec/lib/spree/reporting/registry_spec.rb b/spree/core/spec/lib/spree/reporting/registry_spec.rb
index 5ecec40737..a69f1c7266 100644
--- a/spree/core/spec/lib/spree/reporting/registry_spec.rb
+++ b/spree/core/spec/lib/spree/reporting/registry_spec.rb
@@ -32,12 +32,43 @@ RSpec.describe Spree::Reporting::Registry do
end
end
+ describe '#counter' do
+ let(:count) { ->(store, channel:) { 1 } }
+
+ it 'registers and fetches counters in registration order' do
+ registry.counter :on_hold, count: count, link: { resource: 'orders', filters: [] }
+ registry.counter :flagged, count: count
+
+ expect(registry.counters.keys).to eq(%i[on_hold flagged])
+ expect(registry.counter!('on_hold').link[:resource]).to eq('orders')
+ end
+
+ it 'requires a key_scope whenever a subject is declared' do
+ expect do
+ registry.counter :on_hold, count: count, subject: -> { Spree::Order }
+ end.to raise_error(ArgumentError, /key_scope/)
+ end
+
+ it 'refuses a count that is not callable' do
+ expect { registry.counter :on_hold, count: 3 }.to raise_error(ArgumentError, /callable/)
+ end
+
+ it 'raises on duplicate registration unless replace: true' do
+ registry.counter :on_hold, count: count
+ expect { registry.counter :on_hold, count: count }.to raise_error(ArgumentError, /already registered/)
+
+ registry.counter :on_hold, count: ->(_store, channel:) { 2 }, replace: true
+ expect(registry.counter!(:on_hold).count.call(nil, channel: nil)).to eq(2)
+ end
+ end
+
describe 'unknown members' do
it 'raises UnknownMember naming the valid options' do
registry.metric :margin, sql: 'SUM(x)', base: :orders
expect { registry.metric!(:nope) }.to raise_error(Spree::Reporting::UnknownMember, /margin/)
expect { registry.dimension!(:nope) }.to raise_error(Spree::Reporting::UnknownMember)
+ expect { registry.counter!(:nope) }.to raise_error(Spree::Reporting::UnknownMember, /counter/)
end
end
@@ -47,6 +78,7 @@ RSpec.describe Spree::Reporting::Registry do
expect(Spree.reporting.metric!(:average_order_value).derived?).to be true
expect(Spree.reporting.dimension!(:completed_at).grains).to include(:day)
expect(Spree.reporting.dimension!(:product).lookup).to eq(:product)
+ expect(Spree.reporting.counter!(:orders_to_fulfill).key_scope).to eq('read_orders')
end
end