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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add a Reports section to the dashboard on the reporting contract
Damian Legawiec3f42036ba422
diff --git a/docs/plans/6.0-analytics-semantic-layer.md b/docs/plans/6.0-analytics-semantic-layer.mdindex f87e75be64..fa0ff5768f 100644--- a/docs/plans/6.0-analytics-semantic-layer.md+++ b/docs/plans/6.0-analytics-semantic-layer.md@@ -1,10 +1,10 @@# Reporting Semantic Layer-**Status:** In Progress — Implementation Path Steps 1–6 shipped on `claude/react-dashboard-home-reporting-71weaz` (registry + compiler + live adapter + `reporting/query`/`schema` endpoints + member-level permissions + home screen rebuilt on the contract; the branch's `dashboard/analytics|rankings` endpoints are deleted, `dashboard/operations` remains). Rebased onto main 2026-09-03 (status-column renames, `Spree::Return`, `StockLevel`, `ProductCategory`, permissions catalog `:reports` resource). Steps 7–10 pending.+**Status:** In Progress — Implementation Path Steps 1–9 implemented on `feat/dashboard-reports` (registry + compiler + live adapter + `reporting/query`/`schema` endpoints + member-level permissions + home screen on the contract; Step 7 schema enrichment, Step 8 presets/`week` grain/market·country·variant dimensions/discount·delivery·tax metrics; Step 9 `Spree::SavedReport` + `reporting/saved_reports` CRUD + nine seeded classics + `Spree::Exports::Report` CSV + the Reports SPA pages with the picker builder and inferred visualizations). Rebased onto main 2026-09-03. Step 10 (agent surface) pending.**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-03 (Decision 12)+**Last updated:** 2026-09-03 (Steps 7–9 implemented)## Summarydiff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 1012ab9b36..a157446aeb 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -14,13 +14,20 @@ import { getParams, transformListParams } from '@spree/sdk-core'// Semantic reporting contract (docs/plans/6.0-analytics-semantic-layer.md)// ============================================+export type ReportingGrain = 'day' | 'week' | 'month'+export interface ReportingQuery {/** Registered metric names — discover via `reporting.schema()`. */metrics: string[]- dimensions?: Array<string | { name: string; grain?: 'day' | 'month' }>+ dimensions?: Array<string | { name: string; grain?: ReportingGrain }>filters?: Array<{ dimension: string; op: 'eq' | 'in'; value: string | string[] }>- /** ISO datetimes/dates or relative (`"-30d"`); defaults to the last 30 days. */- time_range?: { since?: string; until?: string }+ /**+ * A named preset (`last_month`, `week_to_date`, `last_4_weeks`, any+ * `last_<n>_<days|weeks|months>`), or ISO 8601 dates/datetimes in+ * since/until (a bare date covers the store's whole day); defaults to the+ * last 30 days. Everything resolves in the store timezone.+ */+ time_range?: { preset?: string; since?: string; until?: string }compare?: 'previous_period'/** Metric name, `-` prefix for descending. */sort?: string@@ -64,9 +71,42 @@ export interface ReportingResult {rows: ReportingRow[]}+export interface ReportingSchemaMetric {+ name: string+ label: string+ description?: string+ format: 'money' | 'integer' | 'decimal' | string+ currency?: string+ derived: boolean+}++export interface ReportingSchemaDimension {+ name: string+ label: string+ description?: string+ type: 'value' | 'time' | string+ grains?: ReportingGrain[]+ /** Set when rows carry hydrated `{ id, label, meta }` payloads for this dimension. */+ lookup?: string+ filter_ops: Array<'eq' | 'in'>+ /** Enumerated raw values for status-like dimensions. */+ values?: Array<{ name: string; label: string }>+ /** Metrics this dimension can break down without double counting. */+ compatible_metrics: string[]+}++/** The self-describing contract, filtered to what the caller may reference. */export interface ReportingSchema {- metrics: Array<{ name: string; format: string; derived: boolean }>- dimensions: Array<{ name: string; type: string; grains?: string[]; lookup?: string }>+ meta: { currency: string; timezone: string; supported_currencies: string[] }+ metrics: ReportingSchemaMetric[]+ dimensions: ReportingSchemaDimension[]+ time_range: {+ presets: Array<{ name: string; label: string }>+ relative: string[]+ absolute: string+ }+ /** Ranking defaults the server applies (`limit` when omitted, and its ceiling). */+ limits: { default: number; max: number }}export interface DashboardOperations {@@ -263,6 +303,8 @@ import type {ReturnUpdateParams,RoleCreateParams,RoleUpdateParams,+ SavedReportCreateParams,+ SavedReportUpdateParams,SellerApproveParams,SellerCreateParams,SellerInviteParams,@@ -383,6 +425,7 @@ import type {Return,ReturnReason,Role,+ SavedReport,Seller,SellerBalance,SellerPayout,@@ -824,6 +867,37 @@ export class AdminClient {/** Registry introspection — drives pickers and agent tool schemas. */schema: (options?: RequestOptions): Promise<ReportingSchema> =>this.request<ReportingSchema>('GET', '/reporting/schema', options),++ /** Store-wide saved reports: a contract query plus visualization config. */+ savedReports: {+ list: (+ params?: ListParams & Record<string, unknown>,+ options?: RequestOptions,+ ): Promise<PaginatedResponse<SavedReport>> =>+ this.request<PaginatedResponse<SavedReport>>('GET', '/reporting/saved_reports', {+ ...options,+ params: params ? transformListParams(params) : undefined,+ }),++ get: (id: string, options?: RequestOptions): Promise<SavedReport> =>+ this.request<SavedReport>('GET', `/reporting/saved_reports/${id}`, options),++ create: (params: SavedReportCreateParams, options?: RequestOptions): Promise<SavedReport> =>+ this.request<SavedReport>('POST', '/reporting/saved_reports', { ...options, body: params }),++ update: (+ id: string,+ params: SavedReportUpdateParams,+ options?: RequestOptions,+ ): Promise<SavedReport> =>+ this.request<SavedReport>('PATCH', `/reporting/saved_reports/${id}`, {+ ...options,+ body: params,+ }),++ delete: (id: string, options?: RequestOptions): Promise<void> =>+ this.request<void>('DELETE', `/reporting/saved_reports/${id}`, options),+ },}readonly dashboard = {diff --git a/packages/admin-sdk/src/index.ts b/packages/admin-sdk/src/index.tsindex 290c95488f..ef73c52245 100644--- a/packages/admin-sdk/src/index.ts+++ b/packages/admin-sdk/src/index.ts@@ -12,11 +12,14 @@ export type {MeResponse,PermissionRule,ReportingDimensionValue,+ ReportingGrain,ReportingMetricValue,ReportingQuery,ReportingResult,ReportingRow,ReportingSchema,+ ReportingSchemaDimension,+ ReportingSchemaMetric,} from './admin-client'// Admin client class (for advanced use / subclassing)export { AdminClient } from './admin-client'diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex a535197f72..c2362756ff 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -1,6 +1,7 @@// Request parameter types for Admin API endpoints// Based on the Admin API OpenAPI specification+import type { ReportingQuery } from './admin-client'import type { SellerRequirementStatus } from './types'/** One pricing or inventory engine a store can choose between. */@@ -3054,6 +3055,8 @@ export interface SavedReportCreateParams {description?: string | null/** A reporting contract query — validated against the registry on save. */query: ReportingQuery+ /** Visualization config; inferred from the query shape when omitted. */+ viz?: Record<string, unknown> | null}export type SavedReportUpdateParams = Partial<SavedReportCreateParams>diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.tsindex 323d6c1caa..21cc5804a1 100644--- a/packages/admin-sdk/src/types/index.ts+++ b/packages/admin-sdk/src/types/index.ts@@ -110,6 +110,7 @@ export type { default as Return } from './generated/Return'export type { default as ReturnLineItem } from './generated/ReturnLineItem'export type { default as ReturnReason } from './generated/ReturnReason'export type { default as Role } from './generated/Role'+export type { default as SavedReport } from './generated/SavedReport'export type { default as Seller } from './generated/Seller'export type { default as SellerBalance } from './generated/SellerBalance'export type { default as SellerPayout } from './generated/SellerPayout'diff --git a/packages/dashboard-core/src/lib/permissions.ts b/packages/dashboard-core/src/lib/permissions.tsindex 4db788797e..339a90de9c 100644--- a/packages/dashboard-core/src/lib/permissions.ts+++ b/packages/dashboard-core/src/lib/permissions.ts@@ -13,6 +13,8 @@ export const Subject = {Media: 'Spree::Media',Variant: 'Spree::Variant',Order: 'Spree::Order',+ SavedReport: 'Spree::SavedReport',+ ReportExport: 'Spree::Exports::Report',Customer: 'Spree::User',CustomerGroup: 'Spree::CustomerGroup',AdminUser: 'Spree::AdminUser',diff --git a/packages/dashboard-core/src/providers/store-provider.tsx b/packages/dashboard-core/src/providers/store-provider.tsxindex 1d8593fbca..54376cf299 100644--- a/packages/dashboard-core/src/providers/store-provider.tsx+++ b/packages/dashboard-core/src/providers/store-provider.tsx@@ -31,11 +31,25 @@ interface StoreContextValue {/** ISO country the store sells from — used to pre-fill new address forms. */defaultCountry: string/** IANA timezone for the store (e.g. `Europe/Berlin`). Falls back to the- * browser's resolved timezone when the store hasn't loaded yet. */+ * browser's resolved timezone when the store hasn't loaded yet, or when+ * the store's preference is not a name this platform recognizes. */timezone: stringrefetch: () => Promise<unknown>}+const browserTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'++/** The store's zone when it is an IANA name the platform knows, else the browser's. */+function resolveTimezone(preferred: string | null | undefined): string {+ if (!preferred) return browserTimezone()+ try {+ Intl.DateTimeFormat('en-US', { timeZone: preferred })+ return preferred+ } catch {+ return browserTimezone()+ }+}+const StoreContext = createContext<StoreContextValue | null>(null)export function StoreProvider({ storeId, children }: { storeId: string; children: ReactNode }) {@@ -82,8 +96,10 @@ export function StoreProvider({ storeId, children }: { storeId: string; childrenconst defaultCurrency = store?.default_currency ?? 'USD'const defaultLocale = store?.default_locale ?? 'en'const defaultCountry = store?.default_country_code ?? ''- const timezone =- store?.preferred_timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC'+ // A store's zone preference defaults to the host app's `Time.zone.name`,+ // which may be a Rails name ("Eastern Time (US & Canada)") that Intl and+ // date-fns-tz reject — falling back keeps every date control working.+ const timezone = resolveTimezone(store?.preferred_timezone)return (<StoreContext.Providerdiff --git a/packages/dashboard-starter/src/routeTree.gen.ts b/packages/dashboard-starter/src/routeTree.gen.tsindex 46457d4c91..915a220624 100644--- a/packages/dashboard-starter/src/routeTree.gen.ts+++ b/packages/dashboard-starter/src/routeTree.gen.ts@@ -28,6 +28,7 @@ import { Route as SplatRouteImport } from './../../dashboard/src/routes/_authentimport { Route as TransfersIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/transfers/index'import { Route as SettingsIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/index'import { Route as SellersIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/sellers/index'+import { Route as ReportsIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/reports/index'import { Route as PurchaseOrdersIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/purchase-orders/index'import { Route as PromotionsIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/promotions/index'import { Route as ProductsIndexRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/products/index'@@ -60,6 +61,8 @@ import { Route as SettingsApiKeysRouteImport } from './../../dashboard/src/routeimport { Route as SettingsAllowedOriginsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/allowed-origins'import { Route as SellersTransfersRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/sellers/transfers'import { Route as SellersSellerIdRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/sellers/$sellerId'+import { Route as ReportsNewRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/reports/new'+import { Route as ReportsReportIdRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/reports/$reportId'import { Route as PurchaseOrdersNewRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/purchase-orders/new'import { Route as PromotionsNewRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/promotions/new'import { Route as PromotionsGiftCardsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/promotions/gift-cards'@@ -197,6 +200,11 @@ const SellersIndexRoute = SellersIndexRouteImport.update({path: '/sellers/',getParentRoute: () => authenticatedStoreIdRoute,} as any)+const ReportsIndexRoute = ReportsIndexRouteImport.update({+ id: '/reports/',+ path: '/reports/',+ getParentRoute: () => authenticatedStoreIdRoute,+} as any)const PurchaseOrdersIndexRoute = PurchaseOrdersIndexRouteImport.update({id: '/purchase-orders/',path: '/purchase-orders/',@@ -359,6 +367,16 @@ const SellersSellerIdRoute = SellersSellerIdRouteImport.update({path: '/sellers/$sellerId',getParentRoute: () => authenticatedStoreIdRoute,} as any)+const ReportsNewRoute = ReportsNewRouteImport.update({+ id: '/reports/new',+ path: '/reports/new',+ getParentRoute: () => authenticatedStoreIdRoute,+} as any)+const ReportsReportIdRoute = ReportsReportIdRouteImport.update({+ id: '/reports/$reportId',+ path: '/reports/$reportId',+ getParentRoute: () => authenticatedStoreIdRoute,+} as any)const PurchaseOrdersNewRoute = PurchaseOrdersNewRouteImport.update({id: '/purchase-orders/new',path: '/purchase-orders/new',@@ -609,6 +627,8 @@ export interface FileRoutesByFullPath {'/$storeId/promotions/gift-cards': typeof PromotionsGiftCardsRoute'/$storeId/promotions/new': typeof PromotionsNewRoute'/$storeId/purchase-orders/new': typeof PurchaseOrdersNewRoute+ '/$storeId/reports/$reportId': typeof ReportsReportIdRoute+ '/$storeId/reports/new': typeof ReportsNewRoute'/$storeId/sellers/$sellerId': typeof SellersSellerIdRoute'/$storeId/sellers/transfers': typeof SellersTransfersRoute'/$storeId/settings/allowed-origins': typeof SettingsAllowedOriginsRoute@@ -641,6 +661,7 @@ export interface FileRoutesByFullPath {'/$storeId/products/': typeof ProductsIndexRoute'/$storeId/promotions/': typeof PromotionsIndexRoute'/$storeId/purchase-orders/': typeof PurchaseOrdersIndexRoute+ '/$storeId/reports/': typeof ReportsIndexRoute'/$storeId/sellers/': typeof SellersIndexRoute'/$storeId/settings/': typeof SettingsIndexRoute'/$storeId/transfers/': typeof TransfersIndexRoute@@ -700,6 +721,8 @@ export interface FileRoutesByTo {'/$storeId/promotions/gift-cards': typeof PromotionsGiftCardsRoute'/$storeId/promotions/new': typeof PromotionsNewRoute'/$storeId/purchase-orders/new': typeof PurchaseOrdersNewRoute+ '/$storeId/reports/$reportId': typeof ReportsReportIdRoute+ '/$storeId/reports/new': typeof ReportsNewRoute'/$storeId/sellers/$sellerId': typeof SellersSellerIdRoute'/$storeId/sellers/transfers': typeof SellersTransfersRoute'/$storeId/settings/allowed-origins': typeof SettingsAllowedOriginsRoute@@ -732,6 +755,7 @@ export interface FileRoutesByTo {'/$storeId/products': typeof ProductsIndexRoute'/$storeId/promotions': typeof PromotionsIndexRoute'/$storeId/purchase-orders': typeof PurchaseOrdersIndexRoute+ '/$storeId/reports': typeof ReportsIndexRoute'/$storeId/sellers': typeof SellersIndexRoute'/$storeId/settings': typeof SettingsIndexRoute'/$storeId/transfers': typeof TransfersIndexRoute@@ -795,6 +819,8 @@ export interface FileRoutesById {'/_authenticated/$storeId/promotions/gift-cards': typeof PromotionsGiftCardsRoute'/_authenticated/$storeId/promotions/new': typeof PromotionsNewRoute'/_authenticated/$storeId/purchase-orders/new': typeof PurchaseOrdersNewRoute+ '/_authenticated/$storeId/reports/$reportId': typeof ReportsReportIdRoute+ '/_authenticated/$storeId/reports/new': typeof ReportsNewRoute'/_authenticated/$storeId/sellers/$sellerId': typeof SellersSellerIdRoute'/_authenticated/$storeId/sellers/transfers': typeof SellersTransfersRoute'/_authenticated/$storeId/settings/allowed-origins': typeof SettingsAllowedOriginsRoute@@ -827,6 +853,7 @@ export interface FileRoutesById {'/_authenticated/$storeId/products/': typeof ProductsIndexRoute'/_authenticated/$storeId/promotions/': typeof PromotionsIndexRoute'/_authenticated/$storeId/purchase-orders/': typeof PurchaseOrdersIndexRoute+ '/_authenticated/$storeId/reports/': typeof ReportsIndexRoute'/_authenticated/$storeId/sellers/': typeof SellersIndexRoute'/_authenticated/$storeId/settings/': typeof SettingsIndexRoute'/_authenticated/$storeId/transfers/': typeof TransfersIndexRoute@@ -890,6 +917,8 @@ export interface FileRouteTypes {| '/$storeId/promotions/gift-cards'| '/$storeId/promotions/new'| '/$storeId/purchase-orders/new'+ | '/$storeId/reports/$reportId'+ | '/$storeId/reports/new'| '/$storeId/sellers/$sellerId'| '/$storeId/sellers/transfers'| '/$storeId/settings/allowed-origins'@@ -922,6 +951,7 @@ export interface FileRouteTypes {| '/$storeId/products/'| '/$storeId/promotions/'| '/$storeId/purchase-orders/'+ | '/$storeId/reports/'| '/$storeId/sellers/'| '/$storeId/settings/'| '/$storeId/transfers/'@@ -981,6 +1011,8 @@ export interface FileRouteTypes {| '/$storeId/promotions/gift-cards'| '/$storeId/promotions/new'| '/$storeId/purchase-orders/new'+ | '/$storeId/reports/$reportId'+ | '/$storeId/reports/new'| '/$storeId/sellers/$sellerId'| '/$storeId/sellers/transfers'| '/$storeId/settings/allowed-origins'@@ -1013,6 +1045,7 @@ export interface FileRouteTypes {| '/$storeId/products'| '/$storeId/promotions'| '/$storeId/purchase-orders'+ | '/$storeId/reports'| '/$storeId/sellers'| '/$storeId/settings'| '/$storeId/transfers'@@ -1075,6 +1108,8 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/promotions/gift-cards'| '/_authenticated/$storeId/promotions/new'| '/_authenticated/$storeId/purchase-orders/new'+ | '/_authenticated/$storeId/reports/$reportId'+ | '/_authenticated/$storeId/reports/new'| '/_authenticated/$storeId/sellers/$sellerId'| '/_authenticated/$storeId/sellers/transfers'| '/_authenticated/$storeId/settings/allowed-origins'@@ -1107,6 +1142,7 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/products/'| '/_authenticated/$storeId/promotions/'| '/_authenticated/$storeId/purchase-orders/'+ | '/_authenticated/$storeId/reports/'| '/_authenticated/$storeId/sellers/'| '/_authenticated/$storeId/settings/'| '/_authenticated/$storeId/transfers/'@@ -1282,6 +1318,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SellersIndexRouteImportparentRoute: typeof authenticatedStoreIdRoute}+ '/_authenticated/$storeId/reports/': {+ id: '/_authenticated/$storeId/reports/'+ path: '/reports'+ fullPath: '/$storeId/reports/'+ preLoaderRoute: typeof ReportsIndexRouteImport+ parentRoute: typeof authenticatedStoreIdRoute+ }'/_authenticated/$storeId/purchase-orders/': {id: '/_authenticated/$storeId/purchase-orders/'path: '/purchase-orders'@@ -1506,6 +1549,20 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SellersSellerIdRouteImportparentRoute: typeof authenticatedStoreIdRoute}+ '/_authenticated/$storeId/reports/new': {+ id: '/_authenticated/$storeId/reports/new'+ path: '/reports/new'+ fullPath: '/$storeId/reports/new'+ preLoaderRoute: typeof ReportsNewRouteImport+ parentRoute: typeof authenticatedStoreIdRoute+ }+ '/_authenticated/$storeId/reports/$reportId': {+ id: '/_authenticated/$storeId/reports/$reportId'+ path: '/reports/$reportId'+ fullPath: '/$storeId/reports/$reportId'+ preLoaderRoute: typeof ReportsReportIdRouteImport+ parentRoute: typeof authenticatedStoreIdRoute+ }'/_authenticated/$storeId/purchase-orders/new': {id: '/_authenticated/$storeId/purchase-orders/new'path: '/purchase-orders/new'@@ -1892,6 +1949,8 @@ interface authenticatedStoreIdRouteChildren {PromotionsGiftCardsRoute: typeof PromotionsGiftCardsRoutePromotionsNewRoute: typeof PromotionsNewRoutePurchaseOrdersNewRoute: typeof PurchaseOrdersNewRoute+ ReportsReportIdRoute: typeof ReportsReportIdRoute+ ReportsNewRoute: typeof ReportsNewRouteSellersSellerIdRoute: typeof SellersSellerIdRouteSellersTransfersRoute: typeof SellersTransfersRouteTransfersNewRoute: typeof TransfersNewRoute@@ -1903,6 +1962,7 @@ interface authenticatedStoreIdRouteChildren {ProductsIndexRoute: typeof ProductsIndexRoutePromotionsIndexRoute: typeof PromotionsIndexRoutePurchaseOrdersIndexRoute: typeof PurchaseOrdersIndexRoute+ ReportsIndexRoute: typeof ReportsIndexRouteSellersIndexRoute: typeof SellersIndexRouteTransfersIndexRoute: typeof TransfersIndexRouteOrdersOrderIdEditRoute: typeof OrdersOrderIdEditRoute@@ -1950,6 +2010,8 @@ const authenticatedStoreIdRouteChildren: authenticatedStoreIdRouteChildren = {PromotionsGiftCardsRoute: PromotionsGiftCardsRoute,PromotionsNewRoute: PromotionsNewRoute,PurchaseOrdersNewRoute: PurchaseOrdersNewRoute,+ ReportsReportIdRoute: ReportsReportIdRoute,+ ReportsNewRoute: ReportsNewRoute,SellersSellerIdRoute: SellersSellerIdRoute,SellersTransfersRoute: SellersTransfersRoute,TransfersNewRoute: TransfersNewRoute,@@ -1961,6 +2023,7 @@ const authenticatedStoreIdRouteChildren: authenticatedStoreIdRouteChildren = {ProductsIndexRoute: ProductsIndexRoute,PromotionsIndexRoute: PromotionsIndexRoute,PurchaseOrdersIndexRoute: PurchaseOrdersIndexRoute,+ ReportsIndexRoute: ReportsIndexRoute,SellersIndexRoute: SellersIndexRoute,TransfersIndexRoute: TransfersIndexRoute,OrdersOrderIdEditRoute: OrdersOrderIdEditRoute,diff --git a/packages/dashboard-ui/src/index.ts b/packages/dashboard-ui/src/index.tsindex a18d83b929..15bb93ba09 100644--- a/packages/dashboard-ui/src/index.ts+++ b/packages/dashboard-ui/src/index.ts@@ -123,6 +123,7 @@ export * from './ui/sidebar'export * from './ui/skeleton'export * from './ui/slot'export * from './ui/switch'+export * from './ui/tabs'export * from './ui/textarea'export * from './ui/thumbnail'export * from './ui/toast'diff --git a/packages/dashboard-ui/src/spree/icons.ts b/packages/dashboard-ui/src/spree/icons.tsindex c794855293..7e83faeda3 100644--- a/packages/dashboard-ui/src/spree/icons.ts+++ b/packages/dashboard-ui/src/spree/icons.ts@@ -25,6 +25,7 @@ export {Building2Icon,CalendarIcon,CalendarOffIcon,+ ChartColumnIcon,CheckCircle2Icon,CheckCircleIcon,CheckIcon,diff --git a/packages/dashboard-ui/src/ui/tabs.tsx b/packages/dashboard-ui/src/ui/tabs.tsxnew file mode 100644index 0000000000..ea09098a65--- /dev/null+++ b/packages/dashboard-ui/src/ui/tabs.tsx@@ -0,0 +1,64 @@+import { Tabs as TabsPrimitive } from '@base-ui/react/tabs'+import type * as React from 'react'+import { cn } from '../lib/utils'++function Tabs({+ className,+ orientation = 'horizontal',+ ...props+}: React.ComponentProps<typeof TabsPrimitive.Root>) {+ return (+ <TabsPrimitive.Root+ data-slot="tabs"+ orientation={orientation}+ className={cn(+ 'group/tabs flex gap-2 data-[orientation=horizontal]:flex-col data-[orientation=vertical]:flex-row',+ className,+ )}+ {...props}+ />+ )+}++function TabsList({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.List>) {+ return (+ <TabsPrimitive.List+ data-slot="tabs-list"+ className={cn(+ 'inline-flex h-9 w-fit items-center justify-center rounded-lg bg-muted p-[3px] text-muted-foreground',+ 'group-data-[orientation=vertical]/tabs:h-auto group-data-[orientation=vertical]/tabs:flex-col',+ className,+ )}+ {...props}+ />+ )+}++function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Tab>) {+ return (+ <TabsPrimitive.Tab+ data-slot="tabs-trigger"+ className={cn(+ 'inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 whitespace-nowrap rounded-md border border-transparent px-2 py-1 text-sm font-medium text-muted-foreground transition-[color,box-shadow]',+ 'hover:text-foreground focus-visible:border-ring focus-visible:outline-1 focus-visible:outline-ring focus-visible:ring-[3px] focus-visible:ring-ring/50',+ 'disabled:pointer-events-none disabled:opacity-50',+ 'data-[active]:bg-background data-[active]:text-foreground data-[active]:shadow-sm dark:data-[active]:border-input dark:data-[active]:bg-input/30',+ "[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ className,+ )}+ {...props}+ />+ )+}++function TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Panel>) {+ return (+ <TabsPrimitive.Panel+ data-slot="tabs-content"+ className={cn('flex-1 outline-none', className)}+ {...props}+ />+ )+}++export { Tabs, TabsContent, TabsList, TabsTrigger }diff --git a/packages/dashboard/e2e/home-dashboard.spec.ts b/packages/dashboard/e2e/home-dashboard.spec.tsindex 46a4993239..2ce1102f46 100644--- a/packages/dashboard/e2e/home-dashboard.spec.ts+++ b/packages/dashboard/e2e/home-dashboard.spec.ts@@ -14,8 +14,8 @@ test.describe('home dashboard', () => {// KPI metric tiles (buttons that switch the chart metric)await expect(page.getByRole('button', { name: /total sales/i })).toBeVisible()- await expect(page.getByRole('button', { name: /total orders/i })).toBeVisible()- await expect(page.getByRole('button', { name: /avg order value/i })).toBeVisible()+ await expect(page.getByRole('button', { name: /^orders\b/i })).toBeVisible()+ await expect(page.getByRole('button', { name: /average order value/i })).toBeVisible()await expect(page.getByRole('button', { name: /units sold/i })).toBeVisible()// Comparison legend under the chart@@ -23,7 +23,7 @@ test.describe('home dashboard', () => {await expect(page.getByText(/^previous period$/i)).toBeVisible()// Switching the active metric keeps the chart rendered- await page.getByRole('button', { name: /total orders/i }).click()+ await page.getByRole('button', { name: /^orders\b/i }).click()await expect(page.getByText(/^this period$/i)).toBeVisible()})@@ -44,8 +44,8 @@ test.describe('home dashboard', () => {// Rankings card with customer/category tabsawait expect(page.getByText('Rankings', { exact: true })).toBeVisible()- await page.getByRole('button', { name: /^categories$/i }).click()- await page.getByRole('button', { name: /^customers$/i }).click()+ await page.getByRole('tab', { name: /^categories$/i }).click()+ await page.getByRole('tab', { name: /^customers$/i }).click()})test('scopes metrics by channel via the switcher', async ({ page }) => {diff --git a/packages/dashboard/e2e/reports.spec.ts b/packages/dashboard/e2e/reports.spec.tsnew file mode 100644index 0000000000..22b380eccb--- /dev/null+++ b/packages/dashboard/e2e/reports.spec.ts@@ -0,0 +1,85 @@+import { expect, test } from '@playwright/test'+import { login } from './helpers'++const REPORTS_PATH = (storeId: string) => `/${storeId}/reports`++test.describe('reports', () => {+ test('lists the built-in reports and opens one', async ({ page }) => {+ const creds = await login(page)+ await page.goto(REPORTS_PATH(creds.store_id))++ await expect(page.getByRole('link', { name: /sales over time/i })).toBeVisible({+ timeout: 15_000,+ })+ await expect(page.getByText(/^built-in$/i).first()).toBeVisible()++ await page.getByRole('link', { name: /sales over time/i }).click()++ await expect(page.getByRole('heading', { name: /sales over time/i })).toBeVisible({+ timeout: 15_000,+ })+ // A time-series report renders the metric tiles and the comparison legend.+ await expect(page.getByRole('button', { name: /total sales/i })).toBeVisible()+ await expect(page.getByText(/^previous period$/i)).toBeVisible()+ // Built-in reports offer a copy, never an in-place save.+ await expect(page.getByRole('button', { name: /save a copy/i })).toBeVisible()+ await expect(page.getByRole('button', { name: /^save$/i })).toHaveCount(0)+ })++ test('builds, saves, renames and deletes a custom report', async ({ page }) => {+ const creds = await login(page)+ const name = `Orders by payment ${Date.now()}`+ await page.goto(`${REPORTS_PATH(creds.store_id)}/new`)++ await expect(page.getByRole('heading', { name: /^new report$/i })).toBeVisible({+ timeout: 15_000,+ })++ // Group the default metrics by payment status → a ranked table.+ await page.getByRole('combobox', { name: /group by/i }).click()+ await page.getByRole('option', { name: /payment status/i }).click()+ // The seeded database may hold no completed orders in range — a ranked+ // table with the breakdown column, or the empty state, both prove the+ // query ran with the new shape.+ await expect(+ page+ .getByRole('columnheader', { name: /payment status/i })+ .or(page.getByText(/no data for this period/i)),+ ).toBeVisible({ timeout: 15_000 })++ await page.getByRole('button', { name: /^save$/i }).click()+ const dialog = page.getByRole('dialog')+ await dialog.getByLabel(/^name$/i).fill(name)+ await dialog.getByRole('button', { name: /^save$/i }).click()++ await expect(page.getByRole('heading', { name })).toBeVisible({ timeout: 15_000 })+ await expect(page.getByRole('button', { name: /export csv/i })).toBeVisible()++ // Rename through the more-actions menu.+ await page.getByRole('button', { name: /more actions/i }).click()+ await page.getByRole('menuitem', { name: /rename/i }).click()+ await page+ .getByRole('dialog')+ .getByLabel(/^name$/i)+ .fill(`${name} renamed`)+ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^save$/i })+ .click()+ await expect(page.getByRole('heading', { name: `${name} renamed` })).toBeVisible({+ timeout: 15_000,+ })++ // Delete from the same menu and land back on the list.+ await page.getByRole('button', { name: /more actions/i }).click()+ await page.getByRole('menuitem', { name: /^delete$/i }).click()+ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^delete$/i })+ .click()+ await expect(page.getByRole('link', { name: /sales over time/i })).toBeVisible({+ timeout: 15_000,+ })+ await expect(page.getByRole('link', { name: `${name} renamed` })).toHaveCount(0)+ })+})diff --git a/packages/dashboard/src/components/spree/reporting/growth-badge.tsx b/packages/dashboard/src/components/spree/reporting/growth-badge.tsxnew file mode 100644index 0000000000..cc4151fd2c--- /dev/null+++ b/packages/dashboard/src/components/spree/reporting/growth-badge.tsx@@ -0,0 +1,47 @@+import { Badge, cn } from '@spree/dashboard-ui'+import { MinusIcon, TrendingDownIcon, TrendingUpIcon } from '@spree/dashboard-ui/icons'+import { useTranslation } from 'react-i18next'++/**+ * Period-over-period delta indicator: green/red trend arrow + percentage, a+ * neutral dash at 0, and a "New" badge when there is no previous-period+ * baseline (`growth === null`).+ */+export function GrowthBadge({ growth }: { growth: number | null | undefined }) {+ const { t } = useTranslation()++ if (growth === null || growth === undefined) {+ return (+ <Badge variant="secondary" title={t('admin.pages.home.growth.vs_previous')}>+ {t('admin.pages.home.growth.new')}+ </Badge>+ )+ }++ const formatted = `${growth > 0 ? '+' : ''}${growth.toLocaleString()}%`++ if (growth === 0) {+ return (+ <span+ className="inline-flex items-center gap-0.5 text-xs font-medium text-muted-foreground"+ title={t('admin.pages.home.growth.vs_previous')}+ >+ <MinusIcon className="size-3" />+ {formatted}+ </span>+ )+ }++ return (+ <span+ className={cn(+ 'inline-flex items-center gap-0.5 text-xs font-medium',+ growth > 0 ? 'text-green-700 dark:text-green-400' : 'text-destructive',+ )}+ title={t('admin.pages.home.growth.vs_previous')}+ >+ {growth > 0 ? <TrendingUpIcon className="size-3" /> : <TrendingDownIcon className="size-3" />}+ {formatted}+ </span>+ )+}diff --git a/packages/dashboard/src/components/spree/reporting/report-builder.tsx b/packages/dashboard/src/components/spree/reporting/report-builder.tsxnew file mode 100644index 0000000000..cb6cec0933--- /dev/null+++ b/packages/dashboard/src/components/spree/reporting/report-builder.tsx@@ -0,0 +1,525 @@+import type { ReportingGrain, ReportingSchema, ReportingSchemaDimension } from '@spree/admin-sdk'+import {+ CountryMultiCombobox,+ MarketMultiCombobox,+ ResourceMultiAutocomplete,+ resolveDatePreset,+ useStore,+} from '@spree/dashboard-core'+import {+ Button,+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ Checkbox,+ cn,+ type DateRange,+ DateRangePicker,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ Field,+ FieldLabel,+ FieldLegend,+ FieldSet,+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@spree/dashboard-ui'+import { PlusIcon, XIcon } from '@spree/dashboard-ui/icons'+import { format, parseISO } from 'date-fns'+import { useTranslation } from 'react-i18next'+import { categoryAutocompleteProps } from '../../../hooks/use-categories'+import { channelAutocompleteProps, useChannels } from '../../../hooks/use-channels'+import { customerAutocompleteProps } from '../../../hooks/use-customers'+import { useAllMarkets } from '../../../hooks/use-markets'+import { productAutocompleteProps } from '../../../hooks/use-products'+import { findDimension, isTimeDimension, type ReportDraft, type ReportFilter } from './report-draft'++const NONE = '__none__'+const CUSTOM_RANGE = '__custom__'++interface ReportBuilderProps {+ draft: ReportDraft+ onChange: (draft: ReportDraft) => void+ schema: ReportingSchema+}++/**+ * Sidebar editor for a report draft, driven entirely by the reporting schema:+ * which metrics exist, which dimensions they can be grouped or filtered by,+ * which time presets the server knows. Nothing in here names a metric.+ */+export function ReportBuilder({ draft, onChange, schema }: ReportBuilderProps) {+ const { t } = useTranslation()+ const { timezone } = useStore()+ const dimension = findDimension(schema, draft.dimension)+ const timeDimension = isTimeDimension(dimension)++ const update = (patch: Partial<ReportDraft>) => onChange({ ...draft, ...patch })++ const groupableDimensions = schema.dimensions.filter((d) =>+ draft.metrics.every((metric) => d.compatible_metrics.includes(metric)),+ )+ const dimensionOptions = [+ { value: NONE, label: t('admin.reports.builder.none') },+ ...groupableDimensions.map((d) => ({ value: d.name, label: d.label })),+ ]++ const grainOptions = (dimension?.grains ?? []).map((grain) => ({+ value: grain,+ label: t(`admin.reports.grains.${grain}`),+ }))++ // Presets come from the schema (named + common relative ranges); whatever a+ // saved report carries stays selectable even if it is not among them.+ const presetValue = 'preset' in draft.timeRange ? draft.timeRange.preset : CUSTOM_RANGE+ const presetOptions = [+ ...schema.time_range.presets.map((preset) => ({ value: preset.name, label: preset.label })),+ { value: CUSTOM_RANGE, label: t('admin.reports.builder.custom_range') },+ ]+ if (!presetOptions.some((option) => option.value === presetValue)) {+ presetOptions.unshift({ value: presetValue, label: presetValue.replace(/_/g, ' ') })+ }+ // A custom range travels as bare dates: the server widens them to the+ // store's whole day on each edge, so the last day is never cut off at+ // the browser's midnight and no browser timezone leaks into the query.+ const defaultRange = resolveDatePreset('last_30_days', timezone)+ const customRange: DateRange =+ 'since' in draft.timeRange+ ? { from: parseISO(draft.timeRange.since), to: parseISO(draft.timeRange.until) }+ : { from: parseISO(defaultRange.from as string), to: parseISO(defaultRange.to as string) }+ const dateRangeValue = (range: DateRange) => ({+ since: format(range.from, 'yyyy-MM-dd'),+ until: format(range.to, 'yyyy-MM-dd'),+ })++ // Same compatibility rule as Group by: an order-level metric cannot be+ // filtered by a line-item dimension, and the compiler would refuse it.+ const filterableDimensions = schema.dimensions.filter(+ (d) =>+ d.type !== 'time' &&+ draft.metrics.every((metric) => d.compatible_metrics.includes(metric)) &&+ !draft.filters.some((filter) => filter.dimension === d.name),+ )++ const metricOptions = draft.metrics.map((name) => ({+ value: name,+ label: schema.metrics.find((metric) => metric.name === name)?.label ?? name,+ }))+ const directionOptions = [+ { value: 'desc', label: t('admin.reports.builder.sort_desc') },+ { value: 'asc', label: t('admin.reports.builder.sort_asc') },+ ]++ function toggleMetric(name: string, checked: boolean) {+ const metrics = checked+ ? [...draft.metrics, name]+ : draft.metrics.filter((metric) => metric !== name)+ update({ metrics })+ }++ function setDimension(value: string) {+ const next = value === NONE ? null : value+ const definition = findDimension(schema, next)+ update({+ dimension: next,+ grain: definition?.grains?.includes(draft.grain)+ ? draft.grain+ : (definition?.grains?.[0] ?? 'day'),+ })+ }++ function setPreset(value: string) {+ if (value === CUSTOM_RANGE) {+ update({ timeRange: dateRangeValue(customRange) })+ } else {+ update({ timeRange: { preset: value } })+ }+ }++ function addFilter(name: string) {+ update({ filters: [...draft.filters, { dimension: name, values: [] }] })+ }++ function setFilter(index: number, filter: ReportFilter) {+ update({ filters: draft.filters.map((current, i) => (i === index ? filter : current)) })+ }++ function removeFilter(index: number) {+ update({ filters: draft.filters.filter((_, i) => i !== index) })+ }++ return (+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.reports.builder.title')}</CardTitle>+ </CardHeader>+ <CardContent className="flex flex-col gap-6">+ <FieldSet className="flex flex-col gap-2">+ <FieldLegend variant="label">{t('admin.reports.builder.metrics')}</FieldLegend>+ {schema.metrics.map((metric) => {+ const id = `metric-${metric.name}`+ // Greyed out when the chosen breakdown or any active filter cannot+ // be combined with this metric.+ const incompatible = [+ dimension,+ ...draft.filters.map((f) => findDimension(schema, f.dimension)),+ ].some((d) => d && !d.compatible_metrics.includes(metric.name))+ return (+ <Field key={metric.name} orientation="horizontal">+ <Checkbox+ id={id}+ checked={draft.metrics.includes(metric.name)}+ disabled={incompatible}+ onCheckedChange={(checked) => toggleMetric(metric.name, checked)}+ />+ <FieldLabel+ htmlFor={id}+ className={cn('font-normal', incompatible && 'text-muted-foreground')}+ >+ {metric.label}+ </FieldLabel>+ </Field>+ )+ })}+ {draft.metrics.length === 0 && (+ <p className="text-xs text-destructive">{t('admin.reports.builder.no_metrics')}</p>+ )}+ </FieldSet>++ <Field>+ <FieldLabel>{t('admin.reports.builder.group_by')}</FieldLabel>+ <OptionSelect+ items={dimensionOptions}+ value={draft.dimension ?? NONE}+ onValueChange={(value) => setDimension(value as string)}+ label={t('admin.reports.builder.group_by')}+ />+ </Field>++ {timeDimension && grainOptions.length > 0 && (+ <Field>+ <FieldLabel>{t('admin.reports.builder.grain')}</FieldLabel>+ <OptionSelect+ items={grainOptions}+ value={draft.grain}+ onValueChange={(value) => update({ grain: value as ReportingGrain })}+ label={t('admin.reports.builder.grain')}+ />+ </Field>+ )}++ <Field>+ <FieldLabel>{t('admin.reports.builder.time_range')}</FieldLabel>+ <OptionSelect+ items={presetOptions}+ value={presetValue}+ onValueChange={(value) => setPreset(value as string)}+ label={t('admin.reports.builder.time_range')}+ />+ {presetValue === CUSTOM_RANGE && (+ <DateRangePicker+ value={customRange}+ onChange={(range) => update({ timeRange: dateRangeValue(range) })}+ />+ )}+ </Field>++ <Field orientation="horizontal">+ <Checkbox+ id="report-compare"+ checked={draft.compare}+ onCheckedChange={(checked) => update({ compare: checked })}+ />+ <FieldLabel htmlFor="report-compare" className="font-normal">+ {t('admin.reports.builder.compare')}+ </FieldLabel>+ </Field>++ <FieldSet className="flex flex-col gap-3">+ <FieldLegend variant="label" className="mb-0">+ {t('admin.reports.builder.filters')}+ </FieldLegend>+ {draft.filters.map((filter, index) => {+ const definition = findDimension(schema, filter.dimension)+ return (+ <div key={filter.dimension} className="flex flex-col gap-1.5 rounded-md border p-3">+ <div className="flex items-center justify-between gap-2">+ <span className="text-sm font-medium">+ {definition?.label ?? filter.dimension}+ </span>+ {+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label={t('admin.reports.builder.remove_filter')}+ onClick={() => removeFilter(index)}+ >+ <XIcon className="size-4" />+ </Button>+ }+ </div>+ <FilterValues+ dimension={definition}+ values={filter.values}+ onChange={(values) => setFilter(index, { ...filter, values })}+ />+ </div>+ )+ })}+ {filterableDimensions.length > 0 && (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button variant="outline" size="sm" className="self-start">+ <PlusIcon className="size-4" />+ {t('admin.reports.builder.add_filter')}+ </Button>+ }+ />+ <DropdownMenuContent align="start">+ {filterableDimensions.map((d) => (+ <DropdownMenuItem key={d.name} onClick={() => addFilter(d.name)}>+ {d.label}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </FieldSet>++ {draft.dimension && !timeDimension && (+ <div className="grid grid-cols-2 gap-3">+ <Field className="col-span-2">+ <FieldLabel>{t('admin.reports.builder.sort')}</FieldLabel>+ <OptionSelect+ items={metricOptions}+ value={+ draft.sortMetric && draft.metrics.includes(draft.sortMetric)+ ? draft.sortMetric+ : (draft.metrics[0] ?? null)+ }+ onValueChange={(value) => update({ sortMetric: value as string })}+ label={t('admin.reports.builder.sort')}+ disabled={metricOptions.length === 0}+ />+ </Field>+ <Field>+ <FieldLabel>{t('admin.reports.builder.direction')}</FieldLabel>+ <OptionSelect+ items={directionOptions}+ value={draft.sortDirection}+ onValueChange={(value) => update({ sortDirection: value as 'asc' | 'desc' })}+ label={t('admin.reports.builder.direction')}+ />+ </Field>+ <Field>+ <FieldLabel htmlFor="report-limit">{t('admin.reports.builder.limit')}</FieldLabel>+ <Input+ id="report-limit"+ type="number"+ min={1}+ max={schema.limits.max}+ value={draft.limit}+ onChange={(event) => {+ const next = Number.parseInt(event.target.value, 10)+ if (Number.isFinite(next))+ update({ limit: Math.min(Math.max(next, 1), schema.limits.max) })+ }}+ />+ </Field>+ </div>+ )}+ </CardContent>+ </Card>+ )+}++/** Value picker for one filter, chosen by how the dimension is keyed. */+function FilterValues({+ dimension,+ values,+ onChange,+}: {+ dimension: ReportingSchemaDimension | undefined+ values: string[]+ onChange: (values: string[]) => void+}) {+ const { t } = useTranslation()++ if (!dimension) return null++ if (dimension.values?.length) {+ return (+ <CheckboxList+ idPrefix={`filter-${dimension.name}`}+ options={dimension.values.map((value) => ({ value: value.name, label: value.label }))}+ values={values}+ onChange={onChange}+ />+ )+ }++ // Lookup-backed filters pick records through the same autocompletes the+ // rest of the dashboard uses; a lookup without a picker falls back to ids.+ const key = `report-filter-${dimension.name}`+ switch (dimension.lookup) {+ case 'channel':+ return <ChannelFilterValues values={values} onChange={onChange} />+ case 'category':+ return (+ <ResourceMultiAutocomplete+ {...categoryAutocompleteProps(key)}+ value={values}+ onChange={onChange}+ />+ )+ case 'product':+ return (+ <ResourceMultiAutocomplete+ {...productAutocompleteProps(key)}+ value={values}+ onChange={onChange}+ />+ )+ case 'customer':+ return (+ <ResourceMultiAutocomplete+ {...customerAutocompleteProps(key)}+ value={values}+ onChange={onChange}+ />+ )+ case 'market':+ return <MarketFilterValues values={values} onChange={onChange} />+ case 'country':+ return <CountryMultiCombobox value={values} onValueChange={onChange} />+ default:+ return (+ <Input+ value={values.join(', ')}+ placeholder={t('admin.reports.builder.ids_placeholder')}+ onChange={(event) =>+ onChange(+ event.target.value+ .split(',')+ .map((v) => v.trim())+ .filter(Boolean),+ )+ }+ />+ )+ }+}++function CheckboxList({+ idPrefix,+ options,+ values,+ onChange,+}: {+ idPrefix: string+ options: Array<{ value: string; label: string }>+ values: string[]+ onChange: (values: string[]) => void+}) {+ return (+ <div className="flex flex-col gap-1.5">+ {options.map((option) => {+ const id = `${idPrefix}-${option.value}`+ return (+ <Field key={option.value} orientation="horizontal">+ <Checkbox+ id={id}+ checked={values.includes(option.value)}+ onCheckedChange={(checked) =>+ onChange(+ checked ? [...values, option.value] : values.filter((v) => v !== option.value),+ )+ }+ />+ <FieldLabel htmlFor={id} className="font-normal">+ {option.label}+ </FieldLabel>+ </Field>+ )+ })}+ </div>+ )+}++/** Markets are a short store-level list, fetched only when a market filter is on screen. */+function MarketFilterValues({+ values,+ onChange,+}: {+ values: string[]+ onChange: (values: string[]) => void+}) {+ const { markets } = useAllMarkets()+ return <MarketMultiCombobox markets={markets} value={values} onValueChange={onChange} />+}++function OptionSelect({+ items,+ value,+ onValueChange,+ label,+ disabled,+}: {+ items: Array<{ value: string; label: string }>+ value: string | null+ onValueChange: (value: string) => void+ label: string+ disabled?: boolean+}) {+ return (+ <Select+ items={items}+ value={value}+ onValueChange={(next) => onValueChange(next as string)}+ disabled={disabled}+ >+ <SelectTrigger aria-label={label}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {items.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )+}++/**+ * Channels are a short store-level list, so the picker opens with every one of+ * them rather than waiting for the merchant to type a search that matches.+ */+function ChannelFilterValues({+ values,+ onChange,+}: {+ values: string[]+ onChange: (values: string[]) => void+}) {+ const { data } = useChannels()++ return (+ <ResourceMultiAutocomplete+ {...channelAutocompleteProps('report-filter-channel')}+ initialItems={data?.data}+ value={values}+ onChange={onChange}+ />+ )+}diff --git a/packages/dashboard/src/components/spree/reporting/report-draft.ts b/packages/dashboard/src/components/spree/reporting/report-draft.tsnew file mode 100644index 0000000000..2c662dd5fd--- /dev/null+++ b/packages/dashboard/src/components/spree/reporting/report-draft.ts@@ -0,0 +1,140 @@+import type {+ ReportingGrain,+ ReportingQuery,+ ReportingSchema,+ ReportingSchemaDimension,+} from '@spree/admin-sdk'++export const DEFAULT_PRESET = 'last_4_weeks'+// Used only until the schema (which publishes the server's real limits) has loaded.+const FALLBACK_LIMIT = 50++export type ReportTimeRange = { preset: string } | { since: string; until: string }++export interface ReportFilter {+ dimension: string+ values: string[]+}++/**+ * The builder's editable state. It is a UI-shaped projection of the query+ * contract (one dimension, one sort metric, filters as value lists) — the+ * contract itself stays the only thing the API sees and the only thing a+ * saved report stores.+ */+export interface ReportDraft {+ metrics: string[]+ dimension: string | null+ grain: ReportingGrain+ timeRange: ReportTimeRange+ filters: ReportFilter[]+ compare: boolean+ sortMetric: string | null+ sortDirection: 'asc' | 'desc'+ limit: number+}++type ReportViz = 'chart' | 'ranking' | 'stats'++/** What a brand-new report starts from: revenue and orders per day, compared. */+export const EMPTY_QUERY: ReportingQuery = {+ metrics: ['gross_revenue', 'orders_count'],+ dimensions: [{ name: 'completed_at', grain: 'day' }],+ time_range: { preset: DEFAULT_PRESET },+ compare: 'previous_period',+}++export function findDimension(+ schema: ReportingSchema | undefined,+ name: string | null | undefined,+): ReportingSchemaDimension | undefined {+ return name ? schema?.dimensions.find((d) => d.name === name) : undefined+}++export function isTimeDimension(dimension: ReportingSchemaDimension | undefined): boolean {+ return dimension?.type === 'time'+}++export function queryDimension(+ query: ReportingQuery,+): { name: string; grain?: ReportingGrain } | null {+ const first = query.dimensions?.[0]+ if (!first) return null+ return typeof first === 'string' ? { name: first } : first+}++export function draftFromQuery(query: ReportingQuery, schema?: ReportingSchema): ReportDraft {+ const dimension = queryDimension(query)+ const sort = query.sort ?? null+ const range = query.time_range+ // Same precedence as the server: a named preset wins over since/until.+ const timeRange: ReportTimeRange = range?.preset+ ? { preset: range.preset }+ : range?.since && range?.until+ ? { since: range.since, until: range.until }+ : { preset: DEFAULT_PRESET }++ return {+ metrics: [...query.metrics],+ dimension: dimension?.name ?? null,+ grain: dimension?.grain ?? 'day',+ timeRange,+ filters: (query.filters ?? []).map((filter) => ({+ dimension: filter.dimension,+ values: Array.isArray(filter.value) ? filter.value : [filter.value],+ })),+ compare: query.compare === 'previous_period',+ sortMetric: sort ? sort.replace(/^-/, '') : null,+ sortDirection: sort && !sort.startsWith('-') ? 'asc' : 'desc',+ limit: query.limit ?? schema?.limits.default ?? FALLBACK_LIMIT,+ }+}++export function queryFromDraft(draft: ReportDraft, schema?: ReportingSchema): ReportingQuery {+ const dimension = findDimension(schema, draft.dimension)+ const timeDimension = isTimeDimension(dimension)+ const query: ReportingQuery = { metrics: draft.metrics, time_range: { ...draft.timeRange } }++ if (draft.dimension) {+ query.dimensions = timeDimension+ ? [{ name: draft.dimension, grain: draft.grain }]+ : [draft.dimension]+ }++ const filters = draft.filters+ .filter((filter) => filter.values.length > 0)+ .map((filter) =>+ filter.values.length === 1+ ? { dimension: filter.dimension, op: 'eq' as const, value: filter.values[0] }+ : { dimension: filter.dimension, op: 'in' as const, value: filter.values },+ )+ if (filters.length > 0) query.filters = filters+ if (draft.compare) query.compare = 'previous_period'++ // Sort and limit only mean something for a ranking; a time series is+ // always complete and chronological.+ if (draft.dimension && !timeDimension) {+ const sortMetric =+ draft.sortMetric && draft.metrics.includes(draft.sortMetric)+ ? draft.sortMetric+ : draft.metrics[0]+ if (sortMetric) query.sort = `${draft.sortDirection === 'desc' ? '-' : ''}${sortMetric}`+ query.limit = draft.limit+ }++ return query+}++/**+ * Picks the visualization from the query's shape: a time dimension is a+ * chart, any other dimension a ranked table, no dimension a row of totals.+ * Without a schema (a saved report referencing a dimension the viewer cannot+ * read) the grain the query carries is the time hint.+ */+export function inferViz(query: ReportingQuery, schema?: ReportingSchema): ReportViz {+ const dimension = queryDimension(query)+ if (!dimension) return 'stats'+ const definition = findDimension(schema, dimension.name)+ const time = definition ? isTimeDimension(definition) : !!dimension.grain+ return time ? 'chart' : 'ranking'+}diff --git a/packages/dashboard/src/components/spree/reporting/report-view.tsx b/packages/dashboard/src/components/spree/reporting/report-view.tsxnew file mode 100644index 0000000000..8111a05048--- /dev/null+++ b/packages/dashboard/src/components/spree/reporting/report-view.tsx@@ -0,0 +1,520 @@+import type {+ ReportingDimensionValue,+ ReportingGrain,+ ReportingMetricValue,+ ReportingQuery,+ ReportingResult,+ ReportingRow,+ ReportingSchema,+ ReportingSchemaMetric,+} from '@spree/admin-sdk'+import {+ Card,+ CardContent,+ CardHeader,+ type ChartConfig,+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+ cn,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+ Progress,+ Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableHeaderRow,+ TableRow,+} from '@spree/dashboard-ui'+import { ChartColumnIcon, TriangleAlertIcon } from '@spree/dashboard-ui/icons'+import { memo, useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { Bar, CartesianGrid, ComposedChart, Line, XAxis } from 'recharts'+import { entityDimension, metaString, rawDimension } from '../../../hooks/use-reporting'+import { GrowthBadge } from './growth-badge'+import { inferViz, queryDimension } from './report-draft'++interface ReportViewProps {+ query: ReportingQuery+ schema: ReportingSchema+ result: ReportingResult | undefined+ error?: Error | null+}++/**+ * Renders a reporting result in the visualization its query shape implies+ * (see `inferViz`). Shape-generic on purpose: any saved report — and any+ * future client of the contract — renders through it, so nothing here knows+ * metric or dimension names.+ */+export const ReportView = memo(function ReportView({+ query,+ schema,+ result,+ error,+}: ReportViewProps) {+ const { t } = useTranslation()+ const viz = inferViz(query, schema)+ const compare = query.compare === 'previous_period'+ const metrics = useMemo(() => resolveMetrics(query.metrics, schema), [query.metrics, schema])++ if (error) {+ return (+ <Card>+ <CardContent>+ <Empty>+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <TriangleAlertIcon />+ </EmptyMedia>+ <EmptyTitle>{t('admin.reports.view.error')}</EmptyTitle>+ <EmptyDescription>{error.message}</EmptyDescription>+ </EmptyHeader>+ </Empty>+ </CardContent>+ </Card>+ )+ }++ if (!result) {+ return <ReportSkeleton />+ }++ if (viz === 'stats') {+ return <StatTiles metrics={metrics} result={result} compare={compare} />+ }++ const dimension = queryDimension(query)+ if (!dimension) return null+ const dimensionLabel =+ schema.dimensions.find((d) => d.name === dimension.name)?.label ?? dimension.name++ if (result.rows.length === 0) {+ return (+ <Card>+ <CardContent>+ <Empty>+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <ChartColumnIcon />+ </EmptyMedia>+ <EmptyTitle>{t('admin.reports.view.empty')}</EmptyTitle>+ </EmptyHeader>+ </Empty>+ </CardContent>+ </Card>+ )+ }++ if (viz === 'chart') {+ return (+ <div className="flex flex-col gap-6">+ <TimeSeriesChart+ metrics={metrics}+ result={result}+ dimension={dimension.name}+ grain={dimension.grain ?? 'day'}+ compare={compare}+ />+ <ResultTable+ rows={result.rows}+ totals={result.totals}+ metrics={metrics}+ dimensionLabel={dimensionLabel}+ renderLabel={(row) => (+ <BucketLabel+ value={rawDimension(row, dimension.name)}+ grain={dimension.grain ?? 'day'}+ />+ )}+ compare={compare}+ />+ </div>+ )+ }++ return (+ <ResultTable+ rows={result.rows}+ totals={result.totals}+ metrics={metrics}+ dimensionLabel={dimensionLabel}+ renderLabel={(row) => <EntityLabel row={row} dimension={dimension.name} />}+ compare={compare}+ ranked+ />+ )+})++/**+ * Metric definitions in the order asked for, falling back to a bare label for+ * one the schema does not describe (a saved report referencing a member the+ * viewer cannot read).+ */+export function resolveMetrics(names: string[], schema: ReportingSchema): ReportingSchemaMetric[] {+ const byName = new Map(schema.metrics.map((metric) => [metric.name, metric]))+ return names.map(+ (name) => byName.get(name) ?? { name, label: name, format: 'decimal', derived: false },+ )+}++/** Formatted metric value: the server's money display when present, else a locale number. */+export function formatMetric(+ value: ReportingMetricValue | undefined,+ metric: ReportingSchemaMetric,+ locale: string,+): string {+ if (!value) return '—'+ if (value.display) return value.display+ return value.value.toLocaleString(locale, {+ maximumFractionDigits: metric.format === 'integer' ? 0 : 2,+ })+}++/** Label, formatted total and (when comparing) the period-over-period delta. */+function MetricTile({+ metric,+ total,+ compare,+ size = 'md',+}: {+ metric: ReportingSchemaMetric+ total: ReportingMetricValue | undefined+ compare: boolean+ size?: 'md' | 'lg'+}) {+ const { i18n } = useTranslation()+ return (+ <>+ <span className="text-xs text-muted-foreground">{metric.label}</span>+ <span className="flex items-center gap-2">+ <span+ className={cn(+ 'font-bold leading-none tabular-nums',+ size === 'lg' ? 'text-2xl' : 'text-lg',+ )}+ >+ {formatMetric(total, metric, i18n.language)}+ </span>+ {compare && <GrowthBadge growth={total?.growth} />}+ </span>+ </>+ )+}++function StatTiles({+ metrics,+ result,+ compare,+}: {+ metrics: ReportingSchemaMetric[]+ result: ReportingResult+ compare: boolean+}) {+ return (+ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">+ {metrics.map((metric) => (+ <Card key={metric.name}>+ <CardContent className="flex flex-col gap-1 py-5">+ <MetricTile+ metric={metric}+ total={result.totals[metric.name]}+ compare={compare}+ size="lg"+ />+ </CardContent>+ </Card>+ ))}+ </div>+ )+}++const BUCKET_FORMATS: Record<ReportingGrain, Intl.DateTimeFormatOptions> = {+ day: { month: 'short', day: 'numeric' },+ week: { month: 'short', day: 'numeric' },+ month: { month: 'short', year: 'numeric' },+}++export function formatBucket(value: string, grain: ReportingGrain, locale: string, long = false) {+ // Buckets arrive as store-local dates (`yyyy-MM-dd`); parsing them as UTC+ // midnight keeps the day stable whatever the browser's zone.+ const date = new Date(value.length === 10 ? `${value}T00:00:00Z` : value)+ if (Number.isNaN(date.getTime())) return value+ const options: Intl.DateTimeFormatOptions = {+ ...BUCKET_FORMATS[grain],+ ...(long && grain !== 'month' ? { year: 'numeric' } : {}),+ timeZone: 'UTC',+ }+ return date.toLocaleDateString(locale, options)+}++function BucketLabel({ value, grain }: { value: string; grain: ReportingGrain }) {+ const { i18n } = useTranslation()+ return <span className="tabular-nums">{formatBucket(value, grain, i18n.language, true)}</span>+}++/**+ * A hydrated dimension's name, with its email on a second line when the two+ * differ (a customer known by both). Shared with the home rankings.+ */+export function DimensionLabel({ dimension }: { dimension: ReportingDimensionValue }) {+ const email = metaString(dimension, 'email')++ return (+ <span className="min-w-0">+ <span className="block truncate font-medium">{dimension.label}</span>+ {email && email !== dimension.label && (+ <span className="block truncate text-xs text-muted-foreground">{email}</span>+ )}+ </span>+ )+}++/** Share of the largest value in the set, floored so a tiny bar stays visible. */+export function sharePercent(value: number, max: number): number {+ return max > 0 ? Math.max((value / max) * 100, 2) : 0+}++function EntityLabel({ row, dimension }: { row: ReportingRow; dimension: string }) {+ return <DimensionLabel dimension={entityDimension(row, dimension)} />+}++export function TimeSeriesChart({+ metrics,+ result,+ dimension,+ grain,+ compare,+}: {+ metrics: ReportingSchemaMetric[]+ result: ReportingResult+ dimension: string+ grain: ReportingGrain+ compare: boolean+}) {+ const { t, i18n } = useTranslation()+ const locale = i18n.language+ const [activeName, setActiveName] = useState(metrics[0]?.name)+ const active = metrics.find((metric) => metric.name === activeName) ?? metrics[0]++ // Recharts re-renders the whole chart on a new `data` identity, so both are+ // rebuilt only when the rows or the selected metric change.+ const chartData = useMemo(+ () =>+ result.rows.map((row) => ({+ bucket: rawDimension(row, dimension),+ current: row.metrics[active.name]?.value ?? 0,+ previous: row.metrics[active.name]?.previous ?? 0,+ })),+ [result.rows, dimension, active.name],+ )++ const chartConfig: ChartConfig = useMemo(+ () => ({+ current: { label: active.label, color: 'var(--chart-2)' },+ previous: { label: t('admin.pages.home.legend.previous'), color: 'var(--muted-foreground)' },+ }),+ [active.label, t],+ )++ const columns = Math.min(metrics.length, 5)++ return (+ <Card>+ <CardHeader+ className="grid h-auto gap-0 border-b p-0"+ style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}+ >+ {metrics.map((metric) => (+ <button+ key={metric.name}+ type="button"+ onClick={() => setActiveName(metric.name)}+ className={cn(+ 'relative flex flex-col justify-center gap-1 border-l px-6 py-4 text-left first:border-l-0',+ active.name === metric.name ? 'bg-muted/50' : 'hover:bg-muted/25',+ )}+ >+ <MetricTile metric={metric} total={result.totals[metric.name]} compare={compare} />+ {active.name === metric.name && (+ <span className="absolute inset-x-0 bottom-0 h-0.5 bg-primary" />+ )}+ </button>+ ))}+ </CardHeader>+ <CardContent className="px-2 pt-4 sm:px-6 sm:pt-6">+ <ChartContainer config={chartConfig} className="aspect-auto h-[250px] w-full">+ <ComposedChart data={chartData}>+ <CartesianGrid vertical={false} />+ <XAxis+ dataKey="bucket"+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ minTickGap={32}+ tickFormatter={(value: string) => formatBucket(value, grain, locale)}+ />+ <ChartTooltip+ cursor={{ fill: 'rgba(0, 0, 0, 0.04)' }}+ content={+ <ChartTooltipContent+ labelFormatter={(value: string) => formatBucket(value, grain, locale, true)}+ />+ }+ />+ <Bar+ dataKey="current"+ fill="var(--color-current)"+ opacity={0.8}+ activeBar={{ opacity: 1 }}+ radius={[4, 4, 0, 0]}+ />+ {compare && (+ <Line+ dataKey="previous"+ stroke="var(--color-previous)"+ strokeWidth={2}+ strokeDasharray="4 4"+ strokeOpacity={0.7}+ dot={false}+ type="monotone"+ />+ )}+ </ComposedChart>+ </ChartContainer>+ {compare && (+ <div className="flex items-center justify-center gap-6 pb-2 pt-3 text-xs text-muted-foreground">+ <span className="inline-flex items-center gap-1.5">+ <span className="size-2.5 rounded-[2px]" style={{ background: 'var(--chart-2)' }} />+ {t('admin.pages.home.legend.current')}+ </span>+ <span className="inline-flex items-center gap-1.5">+ <span+ className="h-0 w-4 border-t-2 border-dashed"+ style={{ borderColor: 'var(--muted-foreground)' }}+ />+ {t('admin.pages.home.legend.previous')}+ </span>+ </div>+ )}+ </CardContent>+ </Card>+ )+}++function ResultTable({+ rows,+ totals,+ metrics,+ dimensionLabel,+ renderLabel,+ compare,+ ranked = false,+}: {+ rows: ReportingRow[]+ totals: ReportingResult['totals']+ metrics: ReportingSchemaMetric[]+ dimensionLabel: string+ renderLabel: (row: ReportingRow) => React.ReactNode+ compare: boolean+ ranked?: boolean+}) {+ const { t, i18n } = useTranslation()+ const locale = i18n.language+ // The first metric doubles as the share bar on a ranking, like the home rankings.+ const shareMetric = ranked ? metrics[0] : undefined+ const maxShare = shareMetric+ ? Math.max(...rows.map((row) => row.metrics[shareMetric.name]?.value ?? 0), 0)+ : 0++ return (+ <Card>+ <CardContent className="p-0">+ <Table data-testid="report-table" roundedBottom>+ <TableHeader>+ <TableHeaderRow>+ {ranked && <TableHead className="w-10">#</TableHead>}+ <TableHead>{dimensionLabel}</TableHead>+ {metrics.map((metric) => (+ <TableHead key={metric.name} className="text-right">+ {metric.label}+ </TableHead>+ ))}+ {compare && (+ <TableHead className="text-right">{t('admin.reports.view.change')}</TableHead>+ )}+ </TableHeaderRow>+ </TableHeader>+ <TableBody>+ {rows.map((row, index) => {+ const share = shareMetric ? (row.metrics[shareMetric.name]?.value ?? 0) : 0+ return (+ <TableRow key={JSON.stringify(row.dimensions)}>+ {ranked && (+ <TableCell className="text-muted-foreground tabular-nums">+ {index + 1}.+ </TableCell>+ )}+ <TableCell>+ {renderLabel(row)}+ {shareMetric && (+ <Progress className="mt-2 max-w-xs" value={sharePercent(share, maxShare)} />+ )}+ </TableCell>+ {metrics.map((metric) => (+ <TableCell key={metric.name} className="text-right tabular-nums">+ {formatMetric(row.metrics[metric.name], metric, locale)}+ </TableCell>+ ))}+ {compare && (+ <TableCell className="text-right">+ <GrowthBadge growth={row.metrics[metrics[0]?.name]?.growth} />+ </TableCell>+ )}+ </TableRow>+ )+ })}+ <TableRow className="bg-muted/30 font-medium">+ {ranked && <TableCell />}+ <TableCell>{t('admin.reports.view.total')}</TableCell>+ {metrics.map((metric) => (+ <TableCell key={metric.name} className="text-right tabular-nums">+ {formatMetric(totals[metric.name], metric, locale)}+ </TableCell>+ ))}+ {compare && (+ <TableCell className="text-right">+ <GrowthBadge growth={totals[metrics[0]?.name]?.growth} />+ </TableCell>+ )}+ </TableRow>+ </TableBody>+ </Table>+ </CardContent>+ </Card>+ )+}++export function ReportSkeleton() {+ return (+ <Card>+ <CardHeader className="grid h-auto grid-cols-2 gap-0 border-b p-0 sm:grid-cols-4">+ {['a', 'b', 'c', 'd'].map((key) => (+ <div key={key} className="flex flex-col gap-2 px-6 py-4 sm:border-l sm:first:border-l-0">+ <Skeleton className="h-3 w-20" />+ <Skeleton className="h-7 w-28" />+ </div>+ ))}+ </CardHeader>+ <CardContent className="px-2 pt-4 sm:px-6 sm:pt-6">+ <Skeleton className="h-[250px] w-full" />+ </CardContent>+ </Card>+ )+}diff --git a/packages/dashboard/src/components/spree/reporting/report-workspace.tsx b/packages/dashboard/src/components/spree/reporting/report-workspace.tsxnew file mode 100644index 0000000000..ff52d4db4f--- /dev/null+++ b/packages/dashboard/src/components/spree/reporting/report-workspace.tsx@@ -0,0 +1,30 @@+import type { ReportingQuery, ReportingResult, ReportingSchema } from '@spree/admin-sdk'+import { ReportBuilder } from './report-builder'+import type { ReportDraft } from './report-draft'+import { ReportView } from './report-view'++interface ReportWorkspaceProps {+ draft: ReportDraft+ onChange: (draft: ReportDraft) => void+ schema: ReportingSchema+ query: ReportingQuery+ result: ReportingResult | undefined+ error?: Error | null+}++/** Builder beside a live preview — the layout both the new and the saved report pages share. */+export function ReportWorkspace({+ draft,+ onChange,+ schema,+ query,+ result,+ error,+}: ReportWorkspaceProps) {+ return (+ <div className="grid items-start gap-6 lg:grid-cols-[20rem_minmax(0,1fr)]">+ <ReportBuilder draft={draft} onChange={onChange} schema={schema} />+ <ReportView query={query} schema={schema} result={result} error={error} />+ </div>+ )+}diff --git a/packages/dashboard/src/components/spree/reporting/save-report-dialog.tsx b/packages/dashboard/src/components/spree/reporting/save-report-dialog.tsxnew file mode 100644index 0000000000..fde428a898--- /dev/null+++ b/packages/dashboard/src/components/spree/reporting/save-report-dialog.tsx@@ -0,0 +1,115 @@+import { zodResolver } from '@hookform/resolvers/zod'+import { mapSpreeErrorsToForm } from '@spree/dashboard-core'+import {+ Button,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldError,+ FieldGroup,+ FieldLabel,+ Input,+ Textarea,+} from '@spree/dashboard-ui'+import { useForm } from 'react-hook-form'+import { useTranslation } from 'react-i18next'+import { z } from 'zod/v4'++const saveReportSchema = z.object({+ name: z.string().trim().min(1),+ description: z.string().trim().optional(),+})++export type SaveReportValues = z.infer<typeof saveReportSchema>++interface SaveReportDialogProps {+ open: boolean+ onOpenChange: (open: boolean) => void+ title: string+ description?: string+ submitLabel: string+ defaultValues?: Partial<SaveReportValues>+ onSubmit: (values: SaveReportValues) => Promise<unknown>+}++/**+ * Name + description prompt shared by "save", "save a copy" and "rename".+ * Mount it only while open — the form's defaults are read once.+ */+export function SaveReportDialog({+ open,+ onOpenChange,+ title,+ description,+ submitLabel,+ defaultValues,+ onSubmit,+}: SaveReportDialogProps) {+ const { t } = useTranslation()+ const form = useForm<SaveReportValues>({+ resolver: zodResolver(saveReportSchema),+ defaultValues: { name: '', description: '', ...defaultValues },+ })++ async function handleSubmit(values: SaveReportValues) {+ try {+ await onSubmit(values)+ onOpenChange(false)+ } catch (err) {+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err+ }+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent>+ <form onSubmit={form.handleSubmit(handleSubmit)}>+ <DialogHeader>+ <DialogTitle>{title}</DialogTitle>+ {description && <DialogDescription>{description}</DialogDescription>}+ </DialogHeader>+ <DialogBody>+ <FieldGroup>+ {form.formState.errors.root?.message && (+ <p className="text-sm text-destructive" role="alert">+ {form.formState.errors.root.message}+ </p>+ )}+ <Field>+ <FieldLabel htmlFor="report-name">+ {t('admin.reports.save_dialog.name_label')}+ </FieldLabel>+ <Input+ id="report-name"+ autoFocus+ aria-invalid={!!form.formState.errors.name}+ {...form.register('name')}+ />+ <FieldError errors={[form.formState.errors.name]} />+ </Field>+ <Field>+ <FieldLabel htmlFor="report-description">+ {t('admin.reports.save_dialog.description_label')}+ </FieldLabel>+ <Textarea id="report-description" rows={3} {...form.register('description')} />+ </Field>+ </FieldGroup>+ </DialogBody>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>+ {t('admin.actions.cancel')}+ </Button>+ <Button type="submit" disabled={form.formState.isSubmitting}>+ {submitLabel}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ )+}diff --git a/packages/dashboard/src/hooks/use-report-run.ts b/packages/dashboard/src/hooks/use-report-run.tsnew file mode 100644index 0000000000..44dc2431b7--- /dev/null+++ b/packages/dashboard/src/hooks/use-report-run.ts@@ -0,0 +1,45 @@+import type { ReportingQuery, ReportingSchema } from '@spree/admin-sdk'+import { useMemo, useState } from 'react'+import {+ draftFromQuery,+ queryFromDraft,+ type ReportDraft,+} from '../components/spree/reporting/report-draft'+import { useReportingQuery } from './use-reporting'++/**+ * The builder loop shared by the new-report and saved-report pages: editable+ * draft → contract query → live result. Placeholder data is the previous+ * query's result, a different shape while the builder changes, so the view+ * gets `undefined` until the real rows arrive.+ */+export function useReportRun(+ initialQuery: ReportingQuery | null,+ schema: ReportingSchema | undefined,+) {+ const [draft, setDraft] = useState<ReportDraft>(() =>+ draftFromQuery(initialQuery ?? { metrics: [] }, schema),+ )+ const query = useMemo(() => queryFromDraft(draft, schema), [draft, schema])+ const runnable = !!schema && draft.metrics.length > 0+ const { data, error, isPlaceholderData } = useReportingQuery(query, { enabled: runnable })++ // The saved query round-trips through the draft so formatting differences+ // (grain defaults, filter op normalization) never count as edits.+ const baseline = useMemo(+ () =>+ initialQuery ? JSON.stringify(queryFromDraft(draftFromQuery(initialQuery), schema)) : null,+ [initialQuery, schema],+ )+ const dirty = baseline !== null && JSON.stringify(query) !== baseline++ return {+ draft,+ setDraft,+ query,+ runnable,+ dirty,+ result: runnable && !isPlaceholderData ? data : undefined,+ error,+ }+}diff --git a/packages/dashboard/src/hooks/use-reporting.ts b/packages/dashboard/src/hooks/use-reporting.tsindex 5bebf8787e..8730f0871e 100644--- a/packages/dashboard/src/hooks/use-reporting.ts+++ b/packages/dashboard/src/hooks/use-reporting.ts@@ -3,6 +3,7 @@ import type {ReportingQuery,ReportingResult,ReportingRow,+ ReportingSchema,} from '@spree/admin-sdk'import { adminClient, useResourceKey } from '@spree/dashboard-core'import { useQuery } from '@tanstack/react-query'@@ -30,12 +31,14 @@ export function useReportingQuery(query: ReportingQuery, options: { enabled?: bo*/export function entityDimension(row: ReportingRow, name: string): ReportingDimensionValue {const value = row.dimensions[name]+ if (value === undefined) return { id: null, label: '', meta: {} }return typeof value === 'string' ? { id: null, label: value, meta: {} } : value}/** Narrows a row's dimension value to a raw bucket/status string. */export function rawDimension(row: ReportingRow, name: string): string {const value = row.dimensions[name]+ if (value === undefined) return ''return typeof value === 'string' ? value : value.label}@@ -44,3 +47,17 @@ export function metaString(dimension: ReportingDimensionValue, key: string): strconst value = dimension.meta?.[key]return typeof value === 'string' ? value : undefined}++/**+ * The permission-filtered reporting vocabulary (`GET /reporting/schema`):+ * metrics, dimensions (with compatible metrics, filter ops and enumerated+ * values) and time-range presets. Drives the report builder so the UI never+ * hardcodes what the server can compute.+ */+export function useReportingSchema() {+ return useQuery<ReportingSchema>({+ queryKey: useResourceKey('reporting', 'schema'),+ queryFn: () => adminClient.reporting.schema(),+ staleTime: 30 * 60 * 1000,+ })+}diff --git a/packages/dashboard/src/hooks/use-saved-reports.ts b/packages/dashboard/src/hooks/use-saved-reports.tsnew file mode 100644index 0000000000..e59ff92baa--- /dev/null+++ b/packages/dashboard/src/hooks/use-saved-reports.ts@@ -0,0 +1,54 @@+import type {+ SavedReport,+ SavedReportCreateParams,+ SavedReportUpdateParams,+} from '@spree/admin-sdk'+import {+ adminClient,+ useResourceKey,+ useResourceKeyBuilder,+ useResourceMutation,+} from '@spree/dashboard-core'+import { useQuery, useQueryClient } from '@tanstack/react-query'+import i18n from 'i18next'++export function useSavedReport(id: string | undefined) {+ return useQuery({+ queryKey: useResourceKey('saved-reports', id ?? 'noop'),+ queryFn: () => adminClient.reporting.savedReports.get(id as string),+ enabled: !!id,+ })+}++export function useCreateSavedReport() {+ return useResourceMutation<SavedReport, Error, SavedReportCreateParams>({+ mutationFn: (params) => adminClient.reporting.savedReports.create(params),+ invalidate: [['saved-reports']],+ successMessage: i18n.t('admin.reports.messages.created'),+ errorMessage: i18n.t('admin.reports.messages.create_failed'),+ })+}++export function useUpdateSavedReport(id: string) {+ return useResourceMutation<SavedReport, Error, SavedReportUpdateParams>({+ mutationFn: (params) => adminClient.reporting.savedReports.update(id, params),+ invalidate: [['saved-reports'], ['saved-reports', id]],+ successMessage: i18n.t('admin.reports.messages.updated'),+ errorMessage: i18n.t('admin.reports.messages.update_failed'),+ })+}++export function useDeleteSavedReport() {+ const queryClient = useQueryClient()+ const buildKey = useResourceKeyBuilder()++ return useResourceMutation<void, Error, string>({+ mutationFn: (id) => adminClient.reporting.savedReports.delete(id),+ invalidate: [['saved-reports']],+ successMessage: i18n.t('admin.reports.messages.deleted'),+ errorMessage: i18n.t('admin.reports.messages.delete_failed'),+ onSuccess: (_data, id) => {+ queryClient.removeQueries({ queryKey: buildKey('saved-reports', id) })+ },+ })+}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex a0c7008e4c..565564dd4a 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -3227,6 +3227,10 @@"units_count_many": "{{count}} وحدة","units_count_other": "{{count}} وحدة","empty": "لا توجد بيانات لهذه الفترة بعد."+ },+ "unavailable": {+ "title": "التقارير غير متاحة لدورك",+ "description": "اطلب من المسؤول صلاحية «التقارير» (مع الوصول إلى الطلبات) لعرض أرقام المبيعات هنا."}},"orders": {@@ -5805,6 +5809,80 @@"confirm": "إغلاق بالنقص"},"load_failed": "تعذّر تحميل التسليمات."+ },+ "reports": {+ "title": "التقارير",+ "subtitle": "تقارير محفوظة عن مبيعاتك ومنتجاتك وعملائك.",+ "new_cta": "تقرير جديد",+ "new_title": "تقرير جديد",+ "copy_name": "نسخة من {{name}}",+ "table": {+ "search_placeholder": "البحث في التقارير…",+ "empty": "لا توجد تقارير بعد. أنشئ تقريرًا للبدء.",+ "columns": {+ "name": "الاسم",+ "kind": "النوع",+ "author": "أنشأه"+ }+ },+ "kind": {+ "built_in": "مدمج",+ "custom": "مخصص"+ },+ "builder": {+ "metrics": "المقاييس",+ "no_metrics": "اختر مقياسًا واحدًا على الأقل.",+ "group_by": "تجميع حسب",+ "none": "بدون (الإجماليات فقط)",+ "grain": "الفاصل الزمني",+ "time_range": "النطاق الزمني",+ "custom_range": "نطاق مخصص",+ "compare": "مقارنة بالفترة السابقة",+ "filters": "عوامل التصفية",+ "add_filter": "إضافة عامل تصفية",+ "remove_filter": "إزالة عامل التصفية",+ "sort": "ترتيب حسب",+ "direction": "الترتيب",+ "sort_desc": "الأعلى أولاً",+ "sort_asc": "الأدنى أولاً",+ "limit": "الصفوف",+ "ids_placeholder": "معرّفات مفصولة بفواصل",+ "title": "إعدادات التقرير"+ },+ "grains": {+ "day": "يومي",+ "week": "أسبوعي",+ "month": "شهري"+ },+ "view": {+ "empty": "لا توجد بيانات لهذه الفترة.",+ "total": "الإجمالي",+ "change": "التغير",+ "error": "تعذر تحميل هذا التقرير"+ },+ "actions": {+ "save": "حفظ",+ "save_copy": "حفظ نسخة",+ "export_csv": "تصدير CSV",+ "rename": "إعادة تسمية"+ },+ "save_dialog": {+ "title_create": "حفظ التقرير",+ "title_copy": "حفظ نسخة",+ "title_rename": "إعادة تسمية التقرير",+ "name_label": "الاسم",+ "description_label": "الوصف"+ },+ "seeded_hint": "لا يمكن تعديل التقارير المدمجة. عدّل الإعدادات واحفظ نسخة للاحتفاظ بنسختك.",+ "delete_confirm": "حذف التقرير \"{{name}}\"؟ لا يمكن التراجع عن هذا الإجراء.",+ "messages": {+ "created": "تم حفظ التقرير",+ "create_failed": "تعذر حفظ التقرير",+ "updated": "تم تحديث التقرير",+ "update_failed": "تعذر تحديث التقرير",+ "deleted": "تم حذف التقرير",+ "delete_failed": "تعذر حذف التقرير"+ }}}}diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 8367857bb3..1f365bfd3f 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -3202,6 +3202,10 @@"units_count_one": "{{count}} Stück","units_count_other": "{{count}} Stück","empty": "Noch keine Daten für diesen Zeitraum."+ },+ "unavailable": {+ "title": "Berichte sind für Ihre Rolle nicht verfügbar",+ "description": "Bitten Sie einen Administrator um die Berechtigung „Berichte“ (mit Zugriff auf Bestellungen), um hier Verkaufszahlen zu sehen."}},"orders": {@@ -5768,6 +5772,80 @@"confirm": "Vorzeitig abschließen"},"load_failed": "Die Lieferungen konnten nicht geladen werden."+ },+ "reports": {+ "title": "Berichte",+ "subtitle": "Gespeicherte Berichte zu Umsatz, Produkten und Kunden.",+ "new_cta": "Neuer Bericht",+ "new_title": "Neuer Bericht",+ "copy_name": "Kopie von {{name}}",+ "table": {+ "search_placeholder": "Berichte durchsuchen…",+ "empty": "Noch keine Berichte. Erstellen Sie einen, um loszulegen.",+ "columns": {+ "name": "Name",+ "kind": "Typ",+ "author": "Erstellt von"+ }+ },+ "kind": {+ "built_in": "Integriert",+ "custom": "Benutzerdefiniert"+ },+ "builder": {+ "metrics": "Kennzahlen",+ "no_metrics": "Wählen Sie mindestens eine Kennzahl.",+ "group_by": "Gruppieren nach",+ "none": "Keine (nur Summen)",+ "grain": "Intervall",+ "time_range": "Zeitraum",+ "custom_range": "Benutzerdefinierter Zeitraum",+ "compare": "Mit Vorperiode vergleichen",+ "filters": "Filter",+ "add_filter": "Filter hinzufügen",+ "remove_filter": "Filter entfernen",+ "sort": "Sortieren nach",+ "direction": "Reihenfolge",+ "sort_desc": "Höchste zuerst",+ "sort_asc": "Niedrigste zuerst",+ "limit": "Zeilen",+ "ids_placeholder": "Kommagetrennte IDs",+ "title": "Berichtseinstellungen"+ },+ "grains": {+ "day": "Täglich",+ "week": "Wöchentlich",+ "month": "Monatlich"+ },+ "view": {+ "empty": "Keine Daten für diesen Zeitraum.",+ "total": "Gesamt",+ "change": "Veränderung",+ "error": "Dieser Bericht konnte nicht geladen werden"+ },+ "actions": {+ "save": "Speichern",+ "save_copy": "Kopie speichern",+ "export_csv": "CSV exportieren",+ "rename": "Umbenennen"+ },+ "save_dialog": {+ "title_create": "Bericht speichern",+ "title_copy": "Kopie speichern",+ "title_rename": "Bericht umbenennen",+ "name_label": "Name",+ "description_label": "Beschreibung"+ },+ "seeded_hint": "Integrierte Berichte können nicht geändert werden. Passen Sie die Einstellungen an und speichern Sie eine Kopie.",+ "delete_confirm": "Bericht „{{name}}“ löschen? Dies kann nicht rückgängig gemacht werden.",+ "messages": {+ "created": "Bericht gespeichert",+ "create_failed": "Bericht konnte nicht gespeichert werden",+ "updated": "Bericht aktualisiert",+ "update_failed": "Bericht konnte nicht aktualisiert werden",+ "deleted": "Bericht gelöscht",+ "delete_failed": "Bericht konnte nicht gelöscht werden"+ }}}}diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex efaeee38ec..af9a54775a 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -3202,6 +3202,10 @@"units_count_one": "{{count}} unit","units_count_other": "{{count}} units","empty": "No data for this period yet."+ },+ "unavailable": {+ "title": "Reports are unavailable for your role",+ "description": "Ask an administrator for the “Reports” permission (with access to orders) to see sales figures here."}},"orders": {@@ -5768,6 +5772,80 @@"confirm": "Close short"},"load_failed": "The deliveries could not be loaded."+ },+ "reports": {+ "title": "Reports",+ "subtitle": "Saved reports over your sales, products and customers.",+ "new_cta": "New report",+ "new_title": "New report",+ "copy_name": "Copy of {{name}}",+ "table": {+ "search_placeholder": "Search reports…",+ "empty": "No reports yet. Create one to get started.",+ "columns": {+ "name": "Name",+ "kind": "Type",+ "author": "Created by"+ }+ },+ "kind": {+ "built_in": "Built-in",+ "custom": "Custom"+ },+ "builder": {+ "metrics": "Metrics",+ "no_metrics": "Pick at least one metric.",+ "group_by": "Group by",+ "none": "None (totals only)",+ "grain": "Interval",+ "time_range": "Time range",+ "custom_range": "Custom range",+ "compare": "Compare with previous period",+ "filters": "Filters",+ "add_filter": "Add filter",+ "remove_filter": "Remove filter",+ "sort": "Sort by",+ "direction": "Order",+ "sort_desc": "Highest first",+ "sort_asc": "Lowest first",+ "limit": "Rows",+ "ids_placeholder": "Comma-separated IDs",+ "title": "Report settings"+ },+ "grains": {+ "day": "Daily",+ "week": "Weekly",+ "month": "Monthly"+ },+ "view": {+ "empty": "No data for this period.",+ "total": "Total",+ "change": "Change",+ "error": "Could not load this report"+ },+ "actions": {+ "save": "Save",+ "save_copy": "Save a copy",+ "export_csv": "Export CSV",+ "rename": "Rename"+ },+ "save_dialog": {+ "title_create": "Save report",+ "title_copy": "Save a copy",+ "title_rename": "Rename report",+ "name_label": "Name",+ "description_label": "Description"+ },+ "seeded_hint": "Built-in reports can't be changed. Adjust the settings and save a copy to keep your version.",+ "delete_confirm": "Delete report \"{{name}}\"? This can't be undone.",+ "messages": {+ "created": "Report saved",+ "create_failed": "Could not save the report",+ "updated": "Report updated",+ "update_failed": "Could not update the report",+ "deleted": "Report deleted",+ "delete_failed": "Could not delete the report"+ }}}}diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 1a7e8ba8f6..4739a28e76 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -3202,6 +3202,10 @@"units_count_one": "{{count}} unité","units_count_other": "{{count}} unités","empty": "Pas encore de données pour cette période."+ },+ "unavailable": {+ "title": "Les rapports ne sont pas disponibles pour votre rôle",+ "description": "Demandez à un administrateur la permission « Rapports » (avec accès aux commandes) pour voir les chiffres de vente ici."}},"orders": {@@ -5768,6 +5772,80 @@"confirm": "Clôturer en l'état"},"load_failed": "Les livraisons n'ont pas pu être chargées."+ },+ "reports": {+ "title": "Rapports",+ "subtitle": "Rapports enregistrés sur vos ventes, produits et clients.",+ "new_cta": "Nouveau rapport",+ "new_title": "Nouveau rapport",+ "copy_name": "Copie de {{name}}",+ "table": {+ "search_placeholder": "Rechercher des rapports…",+ "empty": "Aucun rapport pour l'instant. Créez-en un pour commencer.",+ "columns": {+ "name": "Nom",+ "kind": "Type",+ "author": "Créé par"+ }+ },+ "kind": {+ "built_in": "Intégré",+ "custom": "Personnalisé"+ },+ "builder": {+ "metrics": "Indicateurs",+ "no_metrics": "Choisissez au moins un indicateur.",+ "group_by": "Regrouper par",+ "none": "Aucun (totaux uniquement)",+ "grain": "Intervalle",+ "time_range": "Période",+ "custom_range": "Période personnalisée",+ "compare": "Comparer à la période précédente",+ "filters": "Filtres",+ "add_filter": "Ajouter un filtre",+ "remove_filter": "Retirer le filtre",+ "sort": "Trier par",+ "direction": "Ordre",+ "sort_desc": "Plus élevé d'abord",+ "sort_asc": "Plus bas d'abord",+ "limit": "Lignes",+ "ids_placeholder": "Identifiants séparés par des virgules",+ "title": "Paramètres du rapport"+ },+ "grains": {+ "day": "Quotidien",+ "week": "Hebdomadaire",+ "month": "Mensuel"+ },+ "view": {+ "empty": "Aucune donnée pour cette période.",+ "total": "Total",+ "change": "Évolution",+ "error": "Impossible de charger ce rapport"+ },+ "actions": {+ "save": "Enregistrer",+ "save_copy": "Enregistrer une copie",+ "export_csv": "Exporter en CSV",+ "rename": "Renommer"+ },+ "save_dialog": {+ "title_create": "Enregistrer le rapport",+ "title_copy": "Enregistrer une copie",+ "title_rename": "Renommer le rapport",+ "name_label": "Nom",+ "description_label": "Description"+ },+ "seeded_hint": "Les rapports intégrés ne peuvent pas être modifiés. Ajustez les paramètres et enregistrez une copie pour conserver votre version.",+ "delete_confirm": "Supprimer le rapport « {{name}} » ? Cette action est irréversible.",+ "messages": {+ "created": "Rapport enregistré",+ "create_failed": "Impossible d'enregistrer le rapport",+ "updated": "Rapport mis à jour",+ "update_failed": "Impossible de mettre à jour le rapport",+ "deleted": "Rapport supprimé",+ "delete_failed": "Impossible de supprimer le rapport"+ }}}}diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex bb51f67e18..06bf060500 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -3238,6 +3238,10 @@"units_count_many": "{{count}} sztuk","units_count_other": "{{count}} sztuki","empty": "Brak danych dla tego okresu."+ },+ "unavailable": {+ "title": "Raporty są niedostępne dla Twojej roli",+ "description": "Poproś administratora o uprawnienie „Raporty” (z dostępem do zamówień), aby zobaczyć tutaj dane sprzedaży."}},"orders": {@@ -5834,6 +5838,80 @@"confirm": "Zamknij z brakami"},"load_failed": "Nie udało się wczytać dostaw."+ },+ "reports": {+ "title": "Raporty",+ "subtitle": "Zapisane raporty dotyczące sprzedaży, produktów i klientów.",+ "new_cta": "Nowy raport",+ "new_title": "Nowy raport",+ "copy_name": "Kopia {{name}}",+ "table": {+ "search_placeholder": "Szukaj raportów…",+ "empty": "Brak raportów. Utwórz pierwszy, aby zacząć.",+ "columns": {+ "name": "Nazwa",+ "kind": "Typ",+ "author": "Autor"+ }+ },+ "kind": {+ "built_in": "Wbudowany",+ "custom": "Własny"+ },+ "builder": {+ "metrics": "Metryki",+ "no_metrics": "Wybierz co najmniej jedną metrykę.",+ "group_by": "Grupuj według",+ "none": "Brak (tylko sumy)",+ "grain": "Interwał",+ "time_range": "Zakres czasu",+ "custom_range": "Własny zakres",+ "compare": "Porównaj z poprzednim okresem",+ "filters": "Filtry",+ "add_filter": "Dodaj filtr",+ "remove_filter": "Usuń filtr",+ "sort": "Sortuj według",+ "direction": "Kolejność",+ "sort_desc": "Od najwyższych",+ "sort_asc": "Od najniższych",+ "limit": "Wiersze",+ "ids_placeholder": "Identyfikatory rozdzielone przecinkami",+ "title": "Ustawienia raportu"+ },+ "grains": {+ "day": "Dziennie",+ "week": "Tygodniowo",+ "month": "Miesięcznie"+ },+ "view": {+ "empty": "Brak danych dla tego okresu.",+ "total": "Razem",+ "change": "Zmiana",+ "error": "Nie udało się wczytać tego raportu"+ },+ "actions": {+ "save": "Zapisz",+ "save_copy": "Zapisz kopię",+ "export_csv": "Eksportuj CSV",+ "rename": "Zmień nazwę"+ },+ "save_dialog": {+ "title_create": "Zapisz raport",+ "title_copy": "Zapisz kopię",+ "title_rename": "Zmień nazwę raportu",+ "name_label": "Nazwa",+ "description_label": "Opis"+ },+ "seeded_hint": "Wbudowanych raportów nie można zmieniać. Dostosuj ustawienia i zapisz kopię, aby zachować swoją wersję.",+ "delete_confirm": "Usunąć raport „{{name}}”? Tej operacji nie można cofnąć.",+ "messages": {+ "created": "Raport zapisany",+ "create_failed": "Nie udało się zapisać raportu",+ "updated": "Raport zaktualizowany",+ "update_failed": "Nie udało się zaktualizować raportu",+ "deleted": "Raport usunięty",+ "delete_failed": "Nie udało się usunąć raportu"+ }}}}diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex c7e4aed140..4442b0c643 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -3192,6 +3192,10 @@"orders_count_other": "{{count}} 笔订单","units_count_other": "{{count}} 件","empty": "该时间段暂无数据。"+ },+ "unavailable": {+ "title": "您的角色无法查看报表",+ "description": "请管理员授予“报表”权限(并可访问订单),以在此查看销售数据。"}},"orders": {@@ -5755,6 +5759,80 @@"confirm": "短缺结单"},"load_failed": "无法加载到货记录。"+ },+ "reports": {+ "title": "报表",+ "subtitle": "关于销售、商品和客户的已保存报表。",+ "new_cta": "新建报表",+ "new_title": "新建报表",+ "copy_name": "{{name}} 的副本",+ "table": {+ "search_placeholder": "搜索报表…",+ "empty": "暂无报表。创建一个开始使用。",+ "columns": {+ "name": "名称",+ "kind": "类型",+ "author": "创建者"+ }+ },+ "kind": {+ "built_in": "内置",+ "custom": "自定义"+ },+ "builder": {+ "metrics": "指标",+ "no_metrics": "请至少选择一个指标。",+ "group_by": "分组依据",+ "none": "无(仅汇总)",+ "grain": "时间粒度",+ "time_range": "时间范围",+ "custom_range": "自定义范围",+ "compare": "与上一周期比较",+ "filters": "筛选条件",+ "add_filter": "添加筛选",+ "remove_filter": "移除筛选",+ "sort": "排序依据",+ "direction": "顺序",+ "sort_desc": "从高到低",+ "sort_asc": "从低到高",+ "limit": "行数",+ "ids_placeholder": "以逗号分隔的 ID",+ "title": "报表设置"+ },+ "grains": {+ "day": "按天",+ "week": "按周",+ "month": "按月"+ },+ "view": {+ "empty": "该时间段内暂无数据。",+ "total": "合计",+ "change": "变化",+ "error": "无法加载此报表"+ },+ "actions": {+ "save": "保存",+ "save_copy": "保存副本",+ "export_csv": "导出 CSV",+ "rename": "重命名"+ },+ "save_dialog": {+ "title_create": "保存报表",+ "title_copy": "保存副本",+ "title_rename": "重命名报表",+ "name_label": "名称",+ "description_label": "描述"+ },+ "seeded_hint": "内置报表无法修改。调整设置并保存副本以保留您的版本。",+ "delete_confirm": "删除报表“{{name}}”?此操作无法撤销。",+ "messages": {+ "created": "报表已保存",+ "create_failed": "无法保存报表",+ "updated": "报表已更新",+ "update_failed": "无法更新报表",+ "deleted": "报表已删除",+ "delete_failed": "无法删除报表"+ }}}}diff --git a/packages/dashboard/src/routeTree.gen.ts b/packages/dashboard/src/routeTree.gen.tsindex 8b61a6fee2..974230d4df 100644--- a/packages/dashboard/src/routeTree.gen.ts+++ b/packages/dashboard/src/routeTree.gen.ts@@ -18,24 +18,21 @@ import { Route as authenticatedIndexRouteImport } from './routes/_authenticated/import { Route as acceptInvitationDotinvitationIdRouteImport } from './routes/accept-invitation.$invitationId'import { Route as authenticatedStoreIdRouteImport } from './routes/_authenticated/$storeId'import { Route as IndexRouteImport } from './routes/_authenticated/$storeId/index'-import { Route as SuppliersRouteImport } from './routes/_authenticated/$storeId/suppliers'import { Route as SettingsRouteImport } from './routes/_authenticated/$storeId/settings'import { Route as ReturnsRouteImport } from './routes/_authenticated/$storeId/returns'import { Route as GettingStartedRouteImport } from './routes/_authenticated/$storeId/getting-started'import { Route as ExchangesRouteImport } from './routes/_authenticated/$storeId/exchanges'import { Route as ClaimsRouteImport } from './routes/_authenticated/$storeId/claims'import { Route as SplatRouteImport } from './routes/_authenticated/$storeId/$'-import { Route as TransfersIndexRouteImport } from './routes/_authenticated/$storeId/transfers/index'import { Route as SettingsIndexRouteImport } from './routes/_authenticated/$storeId/settings/index'import { Route as SellersIndexRouteImport } from './routes/_authenticated/$storeId/sellers/index'-import { Route as PurchaseOrdersIndexRouteImport } from './routes/_authenticated/$storeId/purchase-orders/index'+import { Route as ReportsIndexRouteImport } from './routes/_authenticated/$storeId/reports/index'import { Route as PromotionsIndexRouteImport } from './routes/_authenticated/$storeId/promotions/index'import { Route as ProductsIndexRouteImport } from './routes/_authenticated/$storeId/products/index'import { Route as OrdersIndexRouteImport } from './routes/_authenticated/$storeId/orders/index'import { Route as InventoryIndexRouteImport } from './routes/_authenticated/$storeId/inventory/index'import { Route as CustomersIndexRouteImport } from './routes/_authenticated/$storeId/customers/index'import { Route as CompaniesIndexRouteImport } from './routes/_authenticated/$storeId/companies/index'-import { Route as TransfersNewRouteImport } from './routes/_authenticated/$storeId/transfers/new'import { Route as SettingsTaxRatesRouteImport } from './routes/_authenticated/$storeId/settings/tax-rates'import { Route as SettingsTaxCategoriesRouteImport } from './routes/_authenticated/$storeId/settings/tax-categories'import { Route as SettingsStoreRouteImport } from './routes/_authenticated/$storeId/settings/store'@@ -59,11 +56,13 @@ import { Route as SettingsApiKeysRouteImport } from './routes/_authenticated/$stimport { Route as SettingsAllowedOriginsRouteImport } from './routes/_authenticated/$storeId/settings/allowed-origins'import { Route as SellersTransfersRouteImport } from './routes/_authenticated/$storeId/sellers/transfers'import { Route as SellersSellerIdRouteImport } from './routes/_authenticated/$storeId/sellers/$sellerId'-import { Route as PurchaseOrdersNewRouteImport } from './routes/_authenticated/$storeId/purchase-orders/new'+import { Route as ReportsNewRouteImport } from './routes/_authenticated/$storeId/reports/new'+import { Route as ReportsReportIdRouteImport } from './routes/_authenticated/$storeId/reports/$reportId'import { Route as PromotionsNewRouteImport } from './routes/_authenticated/$storeId/promotions/new'import { Route as PromotionsGiftCardsRouteImport } from './routes/_authenticated/$storeId/promotions/gift-cards'import { Route as PromotionsPromotionIdRouteImport } from './routes/_authenticated/$storeId/promotions/$promotionId'import { Route as ProductsTranslationsRouteImport } from './routes/_authenticated/$storeId/products/translations'+import { Route as ProductsTransfersRouteImport } from './routes/_authenticated/$storeId/products/transfers'import { Route as ProductsOptionsRouteImport } from './routes/_authenticated/$storeId/products/options'import { Route as ProductsNewRouteImport } from './routes/_authenticated/$storeId/products/new'import { Route as ProductsMediaRouteImport } from './routes/_authenticated/$storeId/products/media'@@ -73,21 +72,17 @@ import { Route as OrdersDraftsRouteImport } from './routes/_authenticated/$storeimport { Route as CustomersGroupsRouteImport } from './routes/_authenticated/$storeId/customers/groups'import { Route as CustomersCustomerIdRouteImport } from './routes/_authenticated/$storeId/customers/$customerId'import { Route as CompaniesCompanyIdRouteImport } from './routes/_authenticated/$storeId/companies/$companyId'-import { Route as TransfersTransferIdIndexRouteImport } from './routes/_authenticated/$storeId/transfers/$transferId/index'import { Route as SettingsWebhooksIndexRouteImport } from './routes/_authenticated/$storeId/settings/webhooks/index'import { Route as SettingsImportsIndexRouteImport } from './routes/_authenticated/$storeId/settings/imports/index'import { Route as SettingsDeliveryProfilesIndexRouteImport } from './routes/_authenticated/$storeId/settings/delivery-profiles/index'import { Route as SellersPayoutsIndexRouteImport } from './routes/_authenticated/$storeId/sellers/payouts/index'-import { Route as PurchaseOrdersPurchaseOrderIdIndexRouteImport } from './routes/_authenticated/$storeId/purchase-orders/$purchaseOrderId/index'import { Route as ProductsPriceListsIndexRouteImport } from './routes/_authenticated/$storeId/products/price-lists/index'import { Route as ProductsCollectionsIndexRouteImport } from './routes/_authenticated/$storeId/products/collections/index'import { Route as ProductsCategoriesIndexRouteImport } from './routes/_authenticated/$storeId/products/categories/index'import { Route as ProductsCatalogsIndexRouteImport } from './routes/_authenticated/$storeId/products/catalogs/index'import { Route as OrdersOrderIdIndexRouteImport } from './routes/_authenticated/$storeId/orders/$orderId/index'-import { Route as TransfersTransferIdEditRouteImport } from './routes/_authenticated/$storeId/transfers/$transferId/edit'import { Route as SettingsWebhooksWebhookEndpointIdRouteImport } from './routes/_authenticated/$storeId/settings/webhooks/$webhookEndpointId'import { Route as SellersPayoutsPayoutIdRouteImport } from './routes/_authenticated/$storeId/sellers/payouts/$payoutId'-import { Route as PurchaseOrdersPurchaseOrderIdEditRouteImport } from './routes/_authenticated/$storeId/purchase-orders/$purchaseOrderId/edit'import { Route as ProductsPriceListsNewRouteImport } from './routes/_authenticated/$storeId/products/price-lists/new'import { Route as ProductsCollectionsNewRouteImport } from './routes/_authenticated/$storeId/products/collections/new'import { Route as ProductsCollectionsCollectionIdRouteImport } from './routes/_authenticated/$storeId/products/collections/$collectionId'@@ -145,11 +140,6 @@ const IndexRoute = IndexRouteImport.update({path: '/',getParentRoute: () => authenticatedStoreIdRoute,} as any)-const SuppliersRoute = SuppliersRouteImport.update({- id: '/suppliers',- path: '/suppliers',- getParentRoute: () => authenticatedStoreIdRoute,-} as any)const SettingsRoute = SettingsRouteImport.update({id: '/settings',path: '/settings',@@ -180,11 +170,6 @@ const SplatRoute = SplatRouteImport.update({path: '/$',getParentRoute: () => authenticatedStoreIdRoute,} as any)-const TransfersIndexRoute = TransfersIndexRouteImport.update({- id: '/transfers/',- path: '/transfers/',- getParentRoute: () => authenticatedStoreIdRoute,-} as any)const SettingsIndexRoute = SettingsIndexRouteImport.update({id: '/',path: '/',@@ -195,9 +180,9 @@ const SellersIndexRoute = SellersIndexRouteImport.update({path: '/sellers/',getParentRoute: () => authenticatedStoreIdRoute,} as any)-const PurchaseOrdersIndexRoute = PurchaseOrdersIndexRouteImport.update({- id: '/purchase-orders/',- path: '/purchase-orders/',+const ReportsIndexRoute = ReportsIndexRouteImport.update({+ id: '/reports/',+ path: '/reports/',getParentRoute: () => authenticatedStoreIdRoute,} as any)const PromotionsIndexRoute = PromotionsIndexRouteImport.update({@@ -230,11 +215,6 @@ const CompaniesIndexRoute = CompaniesIndexRouteImport.update({path: '/companies/',getParentRoute: () => authenticatedStoreIdRoute,} as any)-const TransfersNewRoute = TransfersNewRouteImport.update({- id: '/transfers/new',- path: '/transfers/new',- getParentRoute: () => authenticatedStoreIdRoute,-} as any)const SettingsTaxRatesRoute = SettingsTaxRatesRouteImport.update({id: '/tax-rates',path: '/tax-rates',@@ -352,9 +332,14 @@ const SellersSellerIdRoute = SellersSellerIdRouteImport.update({path: '/sellers/$sellerId',getParentRoute: () => authenticatedStoreIdRoute,} as any)-const PurchaseOrdersNewRoute = PurchaseOrdersNewRouteImport.update({- id: '/purchase-orders/new',- path: '/purchase-orders/new',+const ReportsNewRoute = ReportsNewRouteImport.update({+ id: '/reports/new',+ path: '/reports/new',+ getParentRoute: () => authenticatedStoreIdRoute,+} as any)+const ReportsReportIdRoute = ReportsReportIdRouteImport.update({+ id: '/reports/$reportId',+ path: '/reports/$reportId',getParentRoute: () => authenticatedStoreIdRoute,} as any)const PromotionsNewRoute = PromotionsNewRouteImport.update({@@ -377,6 +362,11 @@ const ProductsTranslationsRoute = ProductsTranslationsRouteImport.update({path: '/products/translations',getParentRoute: () => authenticatedStoreIdRoute,} as any)+const ProductsTransfersRoute = ProductsTransfersRouteImport.update({+ id: '/products/transfers',+ path: '/products/transfers',+ getParentRoute: () => authenticatedStoreIdRoute,+} as any)const ProductsOptionsRoute = ProductsOptionsRouteImport.update({id: '/products/options',path: '/products/options',@@ -422,12 +412,6 @@ const CompaniesCompanyIdRoute = CompaniesCompanyIdRouteImport.update({path: '/companies/$companyId',getParentRoute: () => authenticatedStoreIdRoute,} as any)-const TransfersTransferIdIndexRoute =- TransfersTransferIdIndexRouteImport.update({- id: '/transfers/$transferId/',- path: '/transfers/$transferId/',- getParentRoute: () => authenticatedStoreIdRoute,- } as any)const SettingsWebhooksIndexRoute = SettingsWebhooksIndexRouteImport.update({id: '/webhooks/',path: '/webhooks/',@@ -449,12 +433,6 @@ const SellersPayoutsIndexRoute = SellersPayoutsIndexRouteImport.update({path: '/sellers/payouts/',getParentRoute: () => authenticatedStoreIdRoute,} as any)-const PurchaseOrdersPurchaseOrderIdIndexRoute =- PurchaseOrdersPurchaseOrderIdIndexRouteImport.update({- id: '/purchase-orders/$purchaseOrderId/',- path: '/purchase-orders/$purchaseOrderId/',- getParentRoute: () => authenticatedStoreIdRoute,- } as any)const ProductsPriceListsIndexRoute = ProductsPriceListsIndexRouteImport.update({id: '/products/price-lists/',path: '/products/price-lists/',@@ -481,11 +459,6 @@ const OrdersOrderIdIndexRoute = OrdersOrderIdIndexRouteImport.update({path: '/orders/$orderId/',getParentRoute: () => authenticatedStoreIdRoute,} as any)-const TransfersTransferIdEditRoute = TransfersTransferIdEditRouteImport.update({- id: '/transfers/$transferId/edit',- path: '/transfers/$transferId/edit',- getParentRoute: () => authenticatedStoreIdRoute,-} as any)const SettingsWebhooksWebhookEndpointIdRoute =SettingsWebhooksWebhookEndpointIdRouteImport.update({id: '/webhooks/$webhookEndpointId',@@ -497,12 +470,6 @@ const SellersPayoutsPayoutIdRoute = SellersPayoutsPayoutIdRouteImport.update({path: '/sellers/payouts/$payoutId',getParentRoute: () => authenticatedStoreIdRoute,} as any)-const PurchaseOrdersPurchaseOrderIdEditRoute =- PurchaseOrdersPurchaseOrderIdEditRouteImport.update({- id: '/purchase-orders/$purchaseOrderId/edit',- path: '/purchase-orders/$purchaseOrderId/edit',- getParentRoute: () => authenticatedStoreIdRoute,- } as any)const ProductsPriceListsNewRoute = ProductsPriceListsNewRouteImport.update({id: '/products/price-lists/new',path: '/products/price-lists/new',@@ -580,7 +547,6 @@ export interface FileRoutesByFullPath {'/$storeId/getting-started': typeof GettingStartedRoute'/$storeId/returns': typeof ReturnsRoute'/$storeId/settings': typeof SettingsRouteWithChildren- '/$storeId/suppliers': typeof SuppliersRoute'/$storeId/': typeof IndexRoute'/$storeId/companies/$companyId': typeof CompaniesCompanyIdRoute'/$storeId/customers/$customerId': typeof CustomersCustomerIdRoute@@ -591,11 +557,13 @@ export interface FileRoutesByFullPath {'/$storeId/products/media': typeof ProductsMediaRoute'/$storeId/products/new': typeof ProductsNewRoute'/$storeId/products/options': typeof ProductsOptionsRoute+ '/$storeId/products/transfers': typeof ProductsTransfersRoute'/$storeId/products/translations': typeof ProductsTranslationsRoute'/$storeId/promotions/$promotionId': typeof PromotionsPromotionIdRoute'/$storeId/promotions/gift-cards': typeof PromotionsGiftCardsRoute'/$storeId/promotions/new': typeof PromotionsNewRoute- '/$storeId/purchase-orders/new': typeof PurchaseOrdersNewRoute+ '/$storeId/reports/$reportId': typeof ReportsReportIdRoute+ '/$storeId/reports/new': typeof ReportsNewRoute'/$storeId/sellers/$sellerId': typeof SellersSellerIdRoute'/$storeId/sellers/transfers': typeof SellersTransfersRoute'/$storeId/settings/allowed-origins': typeof SettingsAllowedOriginsRoute@@ -619,17 +587,15 @@ export interface FileRoutesByFullPath {'/$storeId/settings/store': typeof SettingsStoreRoute'/$storeId/settings/tax-categories': typeof SettingsTaxCategoriesRoute'/$storeId/settings/tax-rates': typeof SettingsTaxRatesRoute- '/$storeId/transfers/new': typeof TransfersNewRoute'/$storeId/companies/': typeof CompaniesIndexRoute'/$storeId/customers/': typeof CustomersIndexRoute'/$storeId/inventory/': typeof InventoryIndexRoute'/$storeId/orders/': typeof OrdersIndexRoute'/$storeId/products/': typeof ProductsIndexRoute'/$storeId/promotions/': typeof PromotionsIndexRoute- '/$storeId/purchase-orders/': typeof PurchaseOrdersIndexRoute+ '/$storeId/reports/': typeof ReportsIndexRoute'/$storeId/sellers/': typeof SellersIndexRoute'/$storeId/settings/': typeof SettingsIndexRoute- '/$storeId/transfers/': typeof TransfersIndexRoute'/$storeId/orders/$orderId/edit': typeof OrdersOrderIdEditRoute'/$storeId/products/catalogs/$catalogId': typeof ProductsCatalogsCatalogIdRoute'/$storeId/products/categories/$categoryId': typeof ProductsCategoriesCategoryIdRoute@@ -637,21 +603,17 @@ export interface FileRoutesByFullPath {'/$storeId/products/collections/$collectionId': typeof ProductsCollectionsCollectionIdRoute'/$storeId/products/collections/new': typeof ProductsCollectionsNewRoute'/$storeId/products/price-lists/new': typeof ProductsPriceListsNewRoute- '/$storeId/purchase-orders/$purchaseOrderId/edit': typeof PurchaseOrdersPurchaseOrderIdEditRoute'/$storeId/sellers/payouts/$payoutId': typeof SellersPayoutsPayoutIdRoute'/$storeId/settings/webhooks/$webhookEndpointId': typeof SettingsWebhooksWebhookEndpointIdRoute- '/$storeId/transfers/$transferId/edit': typeof TransfersTransferIdEditRoute'/$storeId/orders/$orderId/': typeof OrdersOrderIdIndexRoute'/$storeId/products/catalogs/': typeof ProductsCatalogsIndexRoute'/$storeId/products/categories/': typeof ProductsCategoriesIndexRoute'/$storeId/products/collections/': typeof ProductsCollectionsIndexRoute'/$storeId/products/price-lists/': typeof ProductsPriceListsIndexRoute- '/$storeId/purchase-orders/$purchaseOrderId/': typeof PurchaseOrdersPurchaseOrderIdIndexRoute'/$storeId/sellers/payouts/': typeof SellersPayoutsIndexRoute'/$storeId/settings/delivery-profiles/': typeof SettingsDeliveryProfilesIndexRoute'/$storeId/settings/imports/': typeof SettingsImportsIndexRoute'/$storeId/settings/webhooks/': typeof SettingsWebhooksIndexRoute- '/$storeId/transfers/$transferId/': typeof TransfersTransferIdIndexRoute'/$storeId/products/price-lists/$priceListId/': typeof ProductsPriceListsPriceListIdIndexRoute'/$storeId/settings/delivery-profiles/$profileId/': typeof SettingsDeliveryProfilesProfileIdIndexRoute'/$storeId/settings/delivery-profiles/$profileId/methods/$methodId': typeof SettingsDeliveryProfilesProfileIdMethodsMethodIdRoute@@ -669,7 +631,6 @@ export interface FileRoutesByTo {'/$storeId/exchanges': typeof ExchangesRoute'/$storeId/getting-started': typeof GettingStartedRoute'/$storeId/returns': typeof ReturnsRoute- '/$storeId/suppliers': typeof SuppliersRoute'/$storeId': typeof IndexRoute'/$storeId/companies/$companyId': typeof CompaniesCompanyIdRoute'/$storeId/customers/$customerId': typeof CustomersCustomerIdRoute@@ -680,11 +641,13 @@ export interface FileRoutesByTo {'/$storeId/products/media': typeof ProductsMediaRoute'/$storeId/products/new': typeof ProductsNewRoute'/$storeId/products/options': typeof ProductsOptionsRoute+ '/$storeId/products/transfers': typeof ProductsTransfersRoute'/$storeId/products/translations': typeof ProductsTranslationsRoute'/$storeId/promotions/$promotionId': typeof PromotionsPromotionIdRoute'/$storeId/promotions/gift-cards': typeof PromotionsGiftCardsRoute'/$storeId/promotions/new': typeof PromotionsNewRoute- '/$storeId/purchase-orders/new': typeof PurchaseOrdersNewRoute+ '/$storeId/reports/$reportId': typeof ReportsReportIdRoute+ '/$storeId/reports/new': typeof ReportsNewRoute'/$storeId/sellers/$sellerId': typeof SellersSellerIdRoute'/$storeId/sellers/transfers': typeof SellersTransfersRoute'/$storeId/settings/allowed-origins': typeof SettingsAllowedOriginsRoute@@ -708,17 +671,15 @@ export interface FileRoutesByTo {'/$storeId/settings/store': typeof SettingsStoreRoute'/$storeId/settings/tax-categories': typeof SettingsTaxCategoriesRoute'/$storeId/settings/tax-rates': typeof SettingsTaxRatesRoute- '/$storeId/transfers/new': typeof TransfersNewRoute'/$storeId/companies': typeof CompaniesIndexRoute'/$storeId/customers': typeof CustomersIndexRoute'/$storeId/inventory': typeof InventoryIndexRoute'/$storeId/orders': typeof OrdersIndexRoute'/$storeId/products': typeof ProductsIndexRoute'/$storeId/promotions': typeof PromotionsIndexRoute- '/$storeId/purchase-orders': typeof PurchaseOrdersIndexRoute+ '/$storeId/reports': typeof ReportsIndexRoute'/$storeId/sellers': typeof SellersIndexRoute'/$storeId/settings': typeof SettingsIndexRoute- '/$storeId/transfers': typeof TransfersIndexRoute'/$storeId/orders/$orderId/edit': typeof OrdersOrderIdEditRoute'/$storeId/products/catalogs/$catalogId': typeof ProductsCatalogsCatalogIdRoute'/$storeId/products/categories/$categoryId': typeof ProductsCategoriesCategoryIdRoute@@ -726,21 +687,17 @@ export interface FileRoutesByTo {'/$storeId/products/collections/$collectionId': typeof ProductsCollectionsCollectionIdRoute'/$storeId/products/collections/new': typeof ProductsCollectionsNewRoute'/$storeId/products/price-lists/new': typeof ProductsPriceListsNewRoute- '/$storeId/purchase-orders/$purchaseOrderId/edit': typeof PurchaseOrdersPurchaseOrderIdEditRoute'/$storeId/sellers/payouts/$payoutId': typeof SellersPayoutsPayoutIdRoute'/$storeId/settings/webhooks/$webhookEndpointId': typeof SettingsWebhooksWebhookEndpointIdRoute- '/$storeId/transfers/$transferId/edit': typeof TransfersTransferIdEditRoute'/$storeId/orders/$orderId': typeof OrdersOrderIdIndexRoute'/$storeId/products/catalogs': typeof ProductsCatalogsIndexRoute'/$storeId/products/categories': typeof ProductsCategoriesIndexRoute'/$storeId/products/collections': typeof ProductsCollectionsIndexRoute'/$storeId/products/price-lists': typeof ProductsPriceListsIndexRoute- '/$storeId/purchase-orders/$purchaseOrderId': typeof PurchaseOrdersPurchaseOrderIdIndexRoute'/$storeId/sellers/payouts': typeof SellersPayoutsIndexRoute'/$storeId/settings/delivery-profiles': typeof SettingsDeliveryProfilesIndexRoute'/$storeId/settings/imports': typeof SettingsImportsIndexRoute'/$storeId/settings/webhooks': typeof SettingsWebhooksIndexRoute- '/$storeId/transfers/$transferId': typeof TransfersTransferIdIndexRoute'/$storeId/products/price-lists/$priceListId': typeof ProductsPriceListsPriceListIdIndexRoute'/$storeId/settings/delivery-profiles/$profileId': typeof SettingsDeliveryProfilesProfileIdIndexRoute'/$storeId/settings/delivery-profiles/$profileId/methods/$methodId': typeof SettingsDeliveryProfilesProfileIdMethodsMethodIdRoute@@ -762,7 +719,6 @@ export interface FileRoutesById {'/_authenticated/$storeId/getting-started': typeof GettingStartedRoute'/_authenticated/$storeId/returns': typeof ReturnsRoute'/_authenticated/$storeId/settings': typeof SettingsRouteWithChildren- '/_authenticated/$storeId/suppliers': typeof SuppliersRoute'/_authenticated/$storeId/': typeof IndexRoute'/_authenticated/$storeId/companies/$companyId': typeof CompaniesCompanyIdRoute'/_authenticated/$storeId/customers/$customerId': typeof CustomersCustomerIdRoute@@ -773,11 +729,13 @@ export interface FileRoutesById {'/_authenticated/$storeId/products/media': typeof ProductsMediaRoute'/_authenticated/$storeId/products/new': typeof ProductsNewRoute'/_authenticated/$storeId/products/options': typeof ProductsOptionsRoute+ '/_authenticated/$storeId/products/transfers': typeof ProductsTransfersRoute'/_authenticated/$storeId/products/translations': typeof ProductsTranslationsRoute'/_authenticated/$storeId/promotions/$promotionId': typeof PromotionsPromotionIdRoute'/_authenticated/$storeId/promotions/gift-cards': typeof PromotionsGiftCardsRoute'/_authenticated/$storeId/promotions/new': typeof PromotionsNewRoute- '/_authenticated/$storeId/purchase-orders/new': typeof PurchaseOrdersNewRoute+ '/_authenticated/$storeId/reports/$reportId': typeof ReportsReportIdRoute+ '/_authenticated/$storeId/reports/new': typeof ReportsNewRoute'/_authenticated/$storeId/sellers/$sellerId': typeof SellersSellerIdRoute'/_authenticated/$storeId/sellers/transfers': typeof SellersTransfersRoute'/_authenticated/$storeId/settings/allowed-origins': typeof SettingsAllowedOriginsRoute@@ -801,17 +759,15 @@ export interface FileRoutesById {'/_authenticated/$storeId/settings/store': typeof SettingsStoreRoute'/_authenticated/$storeId/settings/tax-categories': typeof SettingsTaxCategoriesRoute'/_authenticated/$storeId/settings/tax-rates': typeof SettingsTaxRatesRoute- '/_authenticated/$storeId/transfers/new': typeof TransfersNewRoute'/_authenticated/$storeId/companies/': typeof CompaniesIndexRoute'/_authenticated/$storeId/customers/': typeof CustomersIndexRoute'/_authenticated/$storeId/inventory/': typeof InventoryIndexRoute'/_authenticated/$storeId/orders/': typeof OrdersIndexRoute'/_authenticated/$storeId/products/': typeof ProductsIndexRoute'/_authenticated/$storeId/promotions/': typeof PromotionsIndexRoute- '/_authenticated/$storeId/purchase-orders/': typeof PurchaseOrdersIndexRoute+ '/_authenticated/$storeId/reports/': typeof ReportsIndexRoute'/_authenticated/$storeId/sellers/': typeof SellersIndexRoute'/_authenticated/$storeId/settings/': typeof SettingsIndexRoute- '/_authenticated/$storeId/transfers/': typeof TransfersIndexRoute'/_authenticated/$storeId/orders/$orderId/edit': typeof OrdersOrderIdEditRoute'/_authenticated/$storeId/products/catalogs/$catalogId': typeof ProductsCatalogsCatalogIdRoute'/_authenticated/$storeId/products/categories/$categoryId': typeof ProductsCategoriesCategoryIdRoute@@ -819,21 +775,17 @@ export interface FileRoutesById {'/_authenticated/$storeId/products/collections/$collectionId': typeof ProductsCollectionsCollectionIdRoute'/_authenticated/$storeId/products/collections/new': typeof ProductsCollectionsNewRoute'/_authenticated/$storeId/products/price-lists/new': typeof ProductsPriceListsNewRoute- '/_authenticated/$storeId/purchase-orders/$purchaseOrderId/edit': typeof PurchaseOrdersPurchaseOrderIdEditRoute'/_authenticated/$storeId/sellers/payouts/$payoutId': typeof SellersPayoutsPayoutIdRoute'/_authenticated/$storeId/settings/webhooks/$webhookEndpointId': typeof SettingsWebhooksWebhookEndpointIdRoute- '/_authenticated/$storeId/transfers/$transferId/edit': typeof TransfersTransferIdEditRoute'/_authenticated/$storeId/orders/$orderId/': typeof OrdersOrderIdIndexRoute'/_authenticated/$storeId/products/catalogs/': typeof ProductsCatalogsIndexRoute'/_authenticated/$storeId/products/categories/': typeof ProductsCategoriesIndexRoute'/_authenticated/$storeId/products/collections/': typeof ProductsCollectionsIndexRoute'/_authenticated/$storeId/products/price-lists/': typeof ProductsPriceListsIndexRoute- '/_authenticated/$storeId/purchase-orders/$purchaseOrderId/': typeof PurchaseOrdersPurchaseOrderIdIndexRoute'/_authenticated/$storeId/sellers/payouts/': typeof SellersPayoutsIndexRoute'/_authenticated/$storeId/settings/delivery-profiles/': typeof SettingsDeliveryProfilesIndexRoute'/_authenticated/$storeId/settings/imports/': typeof SettingsImportsIndexRoute'/_authenticated/$storeId/settings/webhooks/': typeof SettingsWebhooksIndexRoute- '/_authenticated/$storeId/transfers/$transferId/': typeof TransfersTransferIdIndexRoute'/_authenticated/$storeId/products/price-lists/$priceListId/': typeof ProductsPriceListsPriceListIdIndexRoute'/_authenticated/$storeId/settings/delivery-profiles/$profileId/': typeof SettingsDeliveryProfilesProfileIdIndexRoute'/_authenticated/$storeId/settings/delivery-profiles/$profileId/methods/$methodId': typeof SettingsDeliveryProfilesProfileIdMethodsMethodIdRoute@@ -855,7 +807,6 @@ export interface FileRouteTypes {| '/$storeId/getting-started'| '/$storeId/returns'| '/$storeId/settings'- | '/$storeId/suppliers'| '/$storeId/'| '/$storeId/companies/$companyId'| '/$storeId/customers/$customerId'@@ -866,11 +817,13 @@ export interface FileRouteTypes {| '/$storeId/products/media'| '/$storeId/products/new'| '/$storeId/products/options'+ | '/$storeId/products/transfers'| '/$storeId/products/translations'| '/$storeId/promotions/$promotionId'| '/$storeId/promotions/gift-cards'| '/$storeId/promotions/new'- | '/$storeId/purchase-orders/new'+ | '/$storeId/reports/$reportId'+ | '/$storeId/reports/new'| '/$storeId/sellers/$sellerId'| '/$storeId/sellers/transfers'| '/$storeId/settings/allowed-origins'@@ -894,17 +847,15 @@ export interface FileRouteTypes {| '/$storeId/settings/store'| '/$storeId/settings/tax-categories'| '/$storeId/settings/tax-rates'- | '/$storeId/transfers/new'| '/$storeId/companies/'| '/$storeId/customers/'| '/$storeId/inventory/'| '/$storeId/orders/'| '/$storeId/products/'| '/$storeId/promotions/'- | '/$storeId/purchase-orders/'+ | '/$storeId/reports/'| '/$storeId/sellers/'| '/$storeId/settings/'- | '/$storeId/transfers/'| '/$storeId/orders/$orderId/edit'| '/$storeId/products/catalogs/$catalogId'| '/$storeId/products/categories/$categoryId'@@ -912,21 +863,17 @@ export interface FileRouteTypes {| '/$storeId/products/collections/$collectionId'| '/$storeId/products/collections/new'| '/$storeId/products/price-lists/new'- | '/$storeId/purchase-orders/$purchaseOrderId/edit'| '/$storeId/sellers/payouts/$payoutId'| '/$storeId/settings/webhooks/$webhookEndpointId'- | '/$storeId/transfers/$transferId/edit'| '/$storeId/orders/$orderId/'| '/$storeId/products/catalogs/'| '/$storeId/products/categories/'| '/$storeId/products/collections/'| '/$storeId/products/price-lists/'- | '/$storeId/purchase-orders/$purchaseOrderId/'| '/$storeId/sellers/payouts/'| '/$storeId/settings/delivery-profiles/'| '/$storeId/settings/imports/'| '/$storeId/settings/webhooks/'- | '/$storeId/transfers/$transferId/'| '/$storeId/products/price-lists/$priceListId/'| '/$storeId/settings/delivery-profiles/$profileId/'| '/$storeId/settings/delivery-profiles/$profileId/methods/$methodId'@@ -944,7 +891,6 @@ export interface FileRouteTypes {| '/$storeId/exchanges'| '/$storeId/getting-started'| '/$storeId/returns'- | '/$storeId/suppliers'| '/$storeId'| '/$storeId/companies/$companyId'| '/$storeId/customers/$customerId'@@ -955,11 +901,13 @@ export interface FileRouteTypes {| '/$storeId/products/media'| '/$storeId/products/new'| '/$storeId/products/options'+ | '/$storeId/products/transfers'| '/$storeId/products/translations'| '/$storeId/promotions/$promotionId'| '/$storeId/promotions/gift-cards'| '/$storeId/promotions/new'- | '/$storeId/purchase-orders/new'+ | '/$storeId/reports/$reportId'+ | '/$storeId/reports/new'| '/$storeId/sellers/$sellerId'| '/$storeId/sellers/transfers'| '/$storeId/settings/allowed-origins'@@ -983,17 +931,15 @@ export interface FileRouteTypes {| '/$storeId/settings/store'| '/$storeId/settings/tax-categories'| '/$storeId/settings/tax-rates'- | '/$storeId/transfers/new'| '/$storeId/companies'| '/$storeId/customers'| '/$storeId/inventory'| '/$storeId/orders'| '/$storeId/products'| '/$storeId/promotions'- | '/$storeId/purchase-orders'+ | '/$storeId/reports'| '/$storeId/sellers'| '/$storeId/settings'- | '/$storeId/transfers'| '/$storeId/orders/$orderId/edit'| '/$storeId/products/catalogs/$catalogId'| '/$storeId/products/categories/$categoryId'@@ -1001,21 +947,17 @@ export interface FileRouteTypes {| '/$storeId/products/collections/$collectionId'| '/$storeId/products/collections/new'| '/$storeId/products/price-lists/new'- | '/$storeId/purchase-orders/$purchaseOrderId/edit'| '/$storeId/sellers/payouts/$payoutId'| '/$storeId/settings/webhooks/$webhookEndpointId'- | '/$storeId/transfers/$transferId/edit'| '/$storeId/orders/$orderId'| '/$storeId/products/catalogs'| '/$storeId/products/categories'| '/$storeId/products/collections'| '/$storeId/products/price-lists'- | '/$storeId/purchase-orders/$purchaseOrderId'| '/$storeId/sellers/payouts'| '/$storeId/settings/delivery-profiles'| '/$storeId/settings/imports'| '/$storeId/settings/webhooks'- | '/$storeId/transfers/$transferId'| '/$storeId/products/price-lists/$priceListId'| '/$storeId/settings/delivery-profiles/$profileId'| '/$storeId/settings/delivery-profiles/$profileId/methods/$methodId'@@ -1036,7 +978,6 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/getting-started'| '/_authenticated/$storeId/returns'| '/_authenticated/$storeId/settings'- | '/_authenticated/$storeId/suppliers'| '/_authenticated/$storeId/'| '/_authenticated/$storeId/companies/$companyId'| '/_authenticated/$storeId/customers/$customerId'@@ -1047,11 +988,13 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/products/media'| '/_authenticated/$storeId/products/new'| '/_authenticated/$storeId/products/options'+ | '/_authenticated/$storeId/products/transfers'| '/_authenticated/$storeId/products/translations'| '/_authenticated/$storeId/promotions/$promotionId'| '/_authenticated/$storeId/promotions/gift-cards'| '/_authenticated/$storeId/promotions/new'- | '/_authenticated/$storeId/purchase-orders/new'+ | '/_authenticated/$storeId/reports/$reportId'+ | '/_authenticated/$storeId/reports/new'| '/_authenticated/$storeId/sellers/$sellerId'| '/_authenticated/$storeId/sellers/transfers'| '/_authenticated/$storeId/settings/allowed-origins'@@ -1075,17 +1018,15 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/settings/store'| '/_authenticated/$storeId/settings/tax-categories'| '/_authenticated/$storeId/settings/tax-rates'- | '/_authenticated/$storeId/transfers/new'| '/_authenticated/$storeId/companies/'| '/_authenticated/$storeId/customers/'| '/_authenticated/$storeId/inventory/'| '/_authenticated/$storeId/orders/'| '/_authenticated/$storeId/products/'| '/_authenticated/$storeId/promotions/'- | '/_authenticated/$storeId/purchase-orders/'+ | '/_authenticated/$storeId/reports/'| '/_authenticated/$storeId/sellers/'| '/_authenticated/$storeId/settings/'- | '/_authenticated/$storeId/transfers/'| '/_authenticated/$storeId/orders/$orderId/edit'| '/_authenticated/$storeId/products/catalogs/$catalogId'| '/_authenticated/$storeId/products/categories/$categoryId'@@ -1093,21 +1034,17 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/products/collections/$collectionId'| '/_authenticated/$storeId/products/collections/new'| '/_authenticated/$storeId/products/price-lists/new'- | '/_authenticated/$storeId/purchase-orders/$purchaseOrderId/edit'| '/_authenticated/$storeId/sellers/payouts/$payoutId'| '/_authenticated/$storeId/settings/webhooks/$webhookEndpointId'- | '/_authenticated/$storeId/transfers/$transferId/edit'| '/_authenticated/$storeId/orders/$orderId/'| '/_authenticated/$storeId/products/catalogs/'| '/_authenticated/$storeId/products/categories/'| '/_authenticated/$storeId/products/collections/'| '/_authenticated/$storeId/products/price-lists/'- | '/_authenticated/$storeId/purchase-orders/$purchaseOrderId/'| '/_authenticated/$storeId/sellers/payouts/'| '/_authenticated/$storeId/settings/delivery-profiles/'| '/_authenticated/$storeId/settings/imports/'| '/_authenticated/$storeId/settings/webhooks/'- | '/_authenticated/$storeId/transfers/$transferId/'| '/_authenticated/$storeId/products/price-lists/$priceListId/'| '/_authenticated/$storeId/settings/delivery-profiles/$profileId/'| '/_authenticated/$storeId/settings/delivery-profiles/$profileId/methods/$methodId'@@ -1188,13 +1125,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof IndexRouteImportparentRoute: typeof authenticatedStoreIdRoute}- '/_authenticated/$storeId/suppliers': {- id: '/_authenticated/$storeId/suppliers'- path: '/suppliers'- fullPath: '/$storeId/suppliers'- preLoaderRoute: typeof SuppliersRouteImport- parentRoute: typeof authenticatedStoreIdRoute- }'/_authenticated/$storeId/settings': {id: '/_authenticated/$storeId/settings'path: '/settings'@@ -1237,13 +1167,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SplatRouteImportparentRoute: typeof authenticatedStoreIdRoute}- '/_authenticated/$storeId/transfers/': {- id: '/_authenticated/$storeId/transfers/'- path: '/transfers'- fullPath: '/$storeId/transfers/'- preLoaderRoute: typeof TransfersIndexRouteImport- parentRoute: typeof authenticatedStoreIdRoute- }'/_authenticated/$storeId/settings/': {id: '/_authenticated/$storeId/settings/'path: '/'@@ -1258,11 +1181,11 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SellersIndexRouteImportparentRoute: typeof authenticatedStoreIdRoute}- '/_authenticated/$storeId/purchase-orders/': {- id: '/_authenticated/$storeId/purchase-orders/'- path: '/purchase-orders'- fullPath: '/$storeId/purchase-orders/'- preLoaderRoute: typeof PurchaseOrdersIndexRouteImport+ '/_authenticated/$storeId/reports/': {+ id: '/_authenticated/$storeId/reports/'+ path: '/reports'+ fullPath: '/$storeId/reports/'+ preLoaderRoute: typeof ReportsIndexRouteImportparentRoute: typeof authenticatedStoreIdRoute}'/_authenticated/$storeId/promotions/': {@@ -1307,13 +1230,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof CompaniesIndexRouteImportparentRoute: typeof authenticatedStoreIdRoute}- '/_authenticated/$storeId/transfers/new': {- id: '/_authenticated/$storeId/transfers/new'- path: '/transfers/new'- fullPath: '/$storeId/transfers/new'- preLoaderRoute: typeof TransfersNewRouteImport- parentRoute: typeof authenticatedStoreIdRoute- }'/_authenticated/$storeId/settings/tax-rates': {id: '/_authenticated/$storeId/settings/tax-rates'path: '/tax-rates'@@ -1475,11 +1391,18 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SellersSellerIdRouteImportparentRoute: typeof authenticatedStoreIdRoute}- '/_authenticated/$storeId/purchase-orders/new': {- id: '/_authenticated/$storeId/purchase-orders/new'- path: '/purchase-orders/new'- fullPath: '/$storeId/purchase-orders/new'- preLoaderRoute: typeof PurchaseOrdersNewRouteImport+ '/_authenticated/$storeId/reports/new': {+ id: '/_authenticated/$storeId/reports/new'+ path: '/reports/new'+ fullPath: '/$storeId/reports/new'+ preLoaderRoute: typeof ReportsNewRouteImport+ parentRoute: typeof authenticatedStoreIdRoute+ }+ '/_authenticated/$storeId/reports/$reportId': {+ id: '/_authenticated/$storeId/reports/$reportId'+ path: '/reports/$reportId'+ fullPath: '/$storeId/reports/$reportId'+ preLoaderRoute: typeof ReportsReportIdRouteImportparentRoute: typeof authenticatedStoreIdRoute}'/_authenticated/$storeId/promotions/new': {@@ -1510,6 +1433,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ProductsTranslationsRouteImportparentRoute: typeof authenticatedStoreIdRoute}+ '/_authenticated/$storeId/products/transfers': {+ id: '/_authenticated/$storeId/products/transfers'+ path: '/products/transfers'+ fullPath: '/$storeId/products/transfers'+ preLoaderRoute: typeof ProductsTransfersRouteImport+ parentRoute: typeof authenticatedStoreIdRoute+ }'/_authenticated/$storeId/products/options': {id: '/_authenticated/$storeId/products/options'path: '/products/options'@@ -1573,13 +1503,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof CompaniesCompanyIdRouteImportparentRoute: typeof authenticatedStoreIdRoute}- '/_authenticated/$storeId/transfers/$transferId/': {- id: '/_authenticated/$storeId/transfers/$transferId/'- path: '/transfers/$transferId'- fullPath: '/$storeId/transfers/$transferId/'- preLoaderRoute: typeof TransfersTransferIdIndexRouteImport- parentRoute: typeof authenticatedStoreIdRoute- }'/_authenticated/$storeId/settings/webhooks/': {id: '/_authenticated/$storeId/settings/webhooks/'path: '/webhooks'@@ -1608,13 +1531,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SellersPayoutsIndexRouteImportparentRoute: typeof authenticatedStoreIdRoute}- '/_authenticated/$storeId/purchase-orders/$purchaseOrderId/': {- id: '/_authenticated/$storeId/purchase-orders/$purchaseOrderId/'- path: '/purchase-orders/$purchaseOrderId'- fullPath: '/$storeId/purchase-orders/$purchaseOrderId/'- preLoaderRoute: typeof PurchaseOrdersPurchaseOrderIdIndexRouteImport- parentRoute: typeof authenticatedStoreIdRoute- }'/_authenticated/$storeId/products/price-lists/': {id: '/_authenticated/$storeId/products/price-lists/'path: '/products/price-lists'@@ -1650,13 +1566,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof OrdersOrderIdIndexRouteImportparentRoute: typeof authenticatedStoreIdRoute}- '/_authenticated/$storeId/transfers/$transferId/edit': {- id: '/_authenticated/$storeId/transfers/$transferId/edit'- path: '/transfers/$transferId/edit'- fullPath: '/$storeId/transfers/$transferId/edit'- preLoaderRoute: typeof TransfersTransferIdEditRouteImport- parentRoute: typeof authenticatedStoreIdRoute- }'/_authenticated/$storeId/settings/webhooks/$webhookEndpointId': {id: '/_authenticated/$storeId/settings/webhooks/$webhookEndpointId'path: '/webhooks/$webhookEndpointId'@@ -1671,13 +1580,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SellersPayoutsPayoutIdRouteImportparentRoute: typeof authenticatedStoreIdRoute}- '/_authenticated/$storeId/purchase-orders/$purchaseOrderId/edit': {- id: '/_authenticated/$storeId/purchase-orders/$purchaseOrderId/edit'- path: '/purchase-orders/$purchaseOrderId/edit'- fullPath: '/$storeId/purchase-orders/$purchaseOrderId/edit'- preLoaderRoute: typeof PurchaseOrdersPurchaseOrderIdEditRouteImport- parentRoute: typeof authenticatedStoreIdRoute- }'/_authenticated/$storeId/products/price-lists/new': {id: '/_authenticated/$storeId/products/price-lists/new'path: '/products/price-lists/new'@@ -1837,7 +1739,6 @@ interface authenticatedStoreIdRouteChildren {GettingStartedRoute: typeof GettingStartedRouteReturnsRoute: typeof ReturnsRouteSettingsRoute: typeof SettingsRouteWithChildren- SuppliersRoute: typeof SuppliersRouteIndexRoute: typeof IndexRouteCompaniesCompanyIdRoute: typeof CompaniesCompanyIdRouteCustomersCustomerIdRoute: typeof CustomersCustomerIdRoute@@ -1848,23 +1749,23 @@ interface authenticatedStoreIdRouteChildren {ProductsMediaRoute: typeof ProductsMediaRouteProductsNewRoute: typeof ProductsNewRouteProductsOptionsRoute: typeof ProductsOptionsRoute+ ProductsTransfersRoute: typeof ProductsTransfersRouteProductsTranslationsRoute: typeof ProductsTranslationsRoutePromotionsPromotionIdRoute: typeof PromotionsPromotionIdRoutePromotionsGiftCardsRoute: typeof PromotionsGiftCardsRoutePromotionsNewRoute: typeof PromotionsNewRoute- PurchaseOrdersNewRoute: typeof PurchaseOrdersNewRoute+ ReportsReportIdRoute: typeof ReportsReportIdRoute+ ReportsNewRoute: typeof ReportsNewRouteSellersSellerIdRoute: typeof SellersSellerIdRouteSellersTransfersRoute: typeof SellersTransfersRoute- TransfersNewRoute: typeof TransfersNewRouteCompaniesIndexRoute: typeof CompaniesIndexRouteCustomersIndexRoute: typeof CustomersIndexRouteInventoryIndexRoute: typeof InventoryIndexRouteOrdersIndexRoute: typeof OrdersIndexRouteProductsIndexRoute: typeof ProductsIndexRoutePromotionsIndexRoute: typeof PromotionsIndexRoute- PurchaseOrdersIndexRoute: typeof PurchaseOrdersIndexRoute+ ReportsIndexRoute: typeof ReportsIndexRouteSellersIndexRoute: typeof SellersIndexRoute- TransfersIndexRoute: typeof TransfersIndexRouteOrdersOrderIdEditRoute: typeof OrdersOrderIdEditRouteProductsCatalogsCatalogIdRoute: typeof ProductsCatalogsCatalogIdRouteProductsCategoriesCategoryIdRoute: typeof ProductsCategoriesCategoryIdRoute@@ -1872,17 +1773,13 @@ interface authenticatedStoreIdRouteChildren {ProductsCollectionsCollectionIdRoute: typeof ProductsCollectionsCollectionIdRouteProductsCollectionsNewRoute: typeof ProductsCollectionsNewRouteProductsPriceListsNewRoute: typeof ProductsPriceListsNewRoute- PurchaseOrdersPurchaseOrderIdEditRoute: typeof PurchaseOrdersPurchaseOrderIdEditRouteSellersPayoutsPayoutIdRoute: typeof SellersPayoutsPayoutIdRoute- TransfersTransferIdEditRoute: typeof TransfersTransferIdEditRouteOrdersOrderIdIndexRoute: typeof OrdersOrderIdIndexRouteProductsCatalogsIndexRoute: typeof ProductsCatalogsIndexRouteProductsCategoriesIndexRoute: typeof ProductsCategoriesIndexRouteProductsCollectionsIndexRoute: typeof ProductsCollectionsIndexRouteProductsPriceListsIndexRoute: typeof ProductsPriceListsIndexRoute- PurchaseOrdersPurchaseOrderIdIndexRoute: typeof PurchaseOrdersPurchaseOrderIdIndexRouteSellersPayoutsIndexRoute: typeof SellersPayoutsIndexRoute- TransfersTransferIdIndexRoute: typeof TransfersTransferIdIndexRouteProductsPriceListsPriceListIdIndexRoute: typeof ProductsPriceListsPriceListIdIndexRoute}@@ -1893,7 +1790,6 @@ const authenticatedStoreIdRouteChildren: authenticatedStoreIdRouteChildren = {GettingStartedRoute: GettingStartedRoute,ReturnsRoute: ReturnsRoute,SettingsRoute: SettingsRouteWithChildren,- SuppliersRoute: SuppliersRoute,IndexRoute: IndexRoute,CompaniesCompanyIdRoute: CompaniesCompanyIdRoute,CustomersCustomerIdRoute: CustomersCustomerIdRoute,@@ -1904,23 +1800,23 @@ const authenticatedStoreIdRouteChildren: authenticatedStoreIdRouteChildren = {ProductsMediaRoute: ProductsMediaRoute,ProductsNewRoute: ProductsNewRoute,ProductsOptionsRoute: ProductsOptionsRoute,+ ProductsTransfersRoute: ProductsTransfersRoute,ProductsTranslationsRoute: ProductsTranslationsRoute,PromotionsPromotionIdRoute: PromotionsPromotionIdRoute,PromotionsGiftCardsRoute: PromotionsGiftCardsRoute,PromotionsNewRoute: PromotionsNewRoute,- PurchaseOrdersNewRoute: PurchaseOrdersNewRoute,+ ReportsReportIdRoute: ReportsReportIdRoute,+ ReportsNewRoute: ReportsNewRoute,SellersSellerIdRoute: SellersSellerIdRoute,SellersTransfersRoute: SellersTransfersRoute,- TransfersNewRoute: TransfersNewRoute,CompaniesIndexRoute: CompaniesIndexRoute,CustomersIndexRoute: CustomersIndexRoute,InventoryIndexRoute: InventoryIndexRoute,OrdersIndexRoute: OrdersIndexRoute,ProductsIndexRoute: ProductsIndexRoute,PromotionsIndexRoute: PromotionsIndexRoute,- PurchaseOrdersIndexRoute: PurchaseOrdersIndexRoute,+ ReportsIndexRoute: ReportsIndexRoute,SellersIndexRoute: SellersIndexRoute,- TransfersIndexRoute: TransfersIndexRoute,OrdersOrderIdEditRoute: OrdersOrderIdEditRoute,ProductsCatalogsCatalogIdRoute: ProductsCatalogsCatalogIdRoute,ProductsCategoriesCategoryIdRoute: ProductsCategoriesCategoryIdRoute,@@ -1928,19 +1824,13 @@ const authenticatedStoreIdRouteChildren: authenticatedStoreIdRouteChildren = {ProductsCollectionsCollectionIdRoute: ProductsCollectionsCollectionIdRoute,ProductsCollectionsNewRoute: ProductsCollectionsNewRoute,ProductsPriceListsNewRoute: ProductsPriceListsNewRoute,- PurchaseOrdersPurchaseOrderIdEditRoute:- PurchaseOrdersPurchaseOrderIdEditRoute,SellersPayoutsPayoutIdRoute: SellersPayoutsPayoutIdRoute,- TransfersTransferIdEditRoute: TransfersTransferIdEditRoute,OrdersOrderIdIndexRoute: OrdersOrderIdIndexRoute,ProductsCatalogsIndexRoute: ProductsCatalogsIndexRoute,ProductsCategoriesIndexRoute: ProductsCategoriesIndexRoute,ProductsCollectionsIndexRoute: ProductsCollectionsIndexRoute,ProductsPriceListsIndexRoute: ProductsPriceListsIndexRoute,- PurchaseOrdersPurchaseOrderIdIndexRoute:- PurchaseOrdersPurchaseOrderIdIndexRoute,SellersPayoutsIndexRoute: SellersPayoutsIndexRoute,- TransfersTransferIdIndexRoute: TransfersTransferIdIndexRoute,ProductsPriceListsPriceListIdIndexRoute:ProductsPriceListsPriceListIdIndexRoute,}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsxindex 2637331afe..9a6dffbeb7 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx@@ -1,72 +1,88 @@-import type {- DashboardOperations,- ReportingDimensionValue,- ReportingQuery,- ReportingResult,-} from '@spree/admin-sdk'-import { adminClient, Can, Subject, usePermissions } from '@spree/dashboard-core'+import type { DashboardOperations, ReportingDimensionValue, ReportingQuery } from '@spree/admin-sdk'+import { SpreeError } from '@spree/admin-sdk'+import {+ adminClient,+ Can,+ resolveDatePreset,+ Subject,+ usePermissions,+ useResourceKey,+ useStore,+} from '@spree/dashboard-core'import {- Badge,Card,CardContent,CardDescription,CardHeader,CardTitle,- type ChartConfig,- ChartContainer,- ChartTooltip,- ChartTooltipContent,+ cn,type DateRange,DateRangePicker,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+ Progress,Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableHeaderRow,+ TableRow,+ Tabs,+ TabsList,+ TabsTrigger,Thumbnail,} from '@spree/dashboard-ui'import {+ ChartColumnIcon,ChevronRightIcon,CreditCardIcon,- MinusIcon,PackageXIcon,RotateCcwIcon,- TrendingDownIcon,- TrendingUpIcon,TriangleAlertIcon,TruckIcon,} from '@spree/dashboard-ui/icons'import { useQuery } from '@tanstack/react-query'import { createFileRoute, Link } from '@tanstack/react-router'-import { subDays } from 'date-fns'+import { format, parseISO } from 'date-fns'import { useState } from 'react'import { useTranslation } from 'react-i18next'-import { Bar, CartesianGrid, ComposedChart, Line, XAxis } from 'recharts'import { ALL_CHANNELS, ChannelSelect } from '../../../components/spree/channel-select'+import { GrowthBadge } from '../../../components/spree/reporting/growth-badge'+import {+ DimensionLabel,+ ReportSkeleton,+ resolveMetrics,+ sharePercent,+ TimeSeriesChart,+} from '../../../components/spree/reporting/report-view'import {entityDimension,metaString,- rawDimension,useReportingQuery,+ useReportingSchema,} from '../../../hooks/use-reporting'export const Route = createFileRoute('/_authenticated/$storeId/')({component: DashboardPage,})-// UI metric keys (stable i18n keys) → registered reporting metric names.-const CHART_METRICS = {- sales: 'gross_revenue',- orders: 'orders_count',- avg_order_value: 'aov',- units: 'units_sold',- customers: 'customers_count',-} as const--type ChartMetric = keyof typeof CHART_METRICS+// The five headline metrics, in tile order; labels come from the reporting schema.+const CHART_METRICS = ['gross_revenue', 'orders_count', 'aov', 'units_sold', 'customers_count']function DashboardPage() {const { t } = useTranslation()const { permissions } = usePermissions()- const [dateRange, setDateRange] = useState<DateRange>({- from: subDays(new Date(), 30),- to: new Date(),+ const { timezone } = useStore()+ // Seeded on the store's calendar, not the browser's, and sent as bare dates+ // so the server widens both edges to the store's whole day.+ const [dateRange, setDateRange] = useState<DateRange>(() => {+ const preset = resolveDatePreset('last_30_days', timezone)+ return { from: parseISO(preset.from as string), to: parseISO(preset.to as string) }})const [channelId, setChannelId] = useState<string>(ALL_CHANNELS)@@ -81,26 +97,68 @@ function DashboardPage() {const channelParam = channelId === ALL_CHANNELS ? undefined : channelId// Shared by every widget query — the switcher and date range scope the whole screen.const scope: Pick<ReportingQuery, 'time_range' | 'filters'> = {- time_range: { since: dateRange.from.toISOString(), until: dateRange.to.toISOString() },+ time_range: {+ since: format(dateRange.from, 'yyyy-MM-dd'),+ until: format(dateRange.to, 'yyyy-MM-dd'),+ },...(channelParam? { filters: [{ dimension: 'channel', op: 'eq' as const, value: channelParam }] }: {}),}- const { data: overview } = useReportingQuery({- metrics: Object.values(CHART_METRICS),+ const overviewQuery: ReportingQuery = {+ metrics: CHART_METRICS,dimensions: [{ name: 'completed_at', grain: 'day' }],compare: 'previous_period',...scope,- })+ }+ const { data: overview, error: overviewError } = useReportingQuery(overviewQuery)+ const { data: schema } = useReportingSchema()+ const chartMetrics = schema+ ? resolveMetrics(CHART_METRICS, schema)+ : CHART_METRICS.map((name) => ({ name, label: name, format: 'decimal', derived: false }))const { data: operations } = useQuery({- queryKey: ['dashboard', 'operations', channelId],+ queryKey: useResourceKey('dashboard', 'operations', channelId),queryFn: () => adminClient.dashboard.operations({ channel_id: channelParam }),staleTime: 5 * 60 * 1000,placeholderData: (previousData) => previousData,})+ // A role without `read_reports` (or order data) gets a 403 here — say so+ // rather than leaving the skeleton up forever. Any other failure is a plain+ // error, not a permission problem.+ if (overviewError) {+ const forbidden = overviewError instanceof SpreeError && overviewError.status === 403+ return (+ <div className="flex flex-col gap-6">+ <div>+ <h1 className="text-2xl font-bold">{t('admin.pages.home.title')}</h1>+ <p className="text-muted-foreground">{t('admin.pages.home.subtitle')}</p>+ </div>+ <Card>+ <CardContent>+ <Empty>+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <ChartColumnIcon />+ </EmptyMedia>+ <EmptyTitle>+ {forbidden ? t('admin.pages.home.unavailable.title') : t('admin.errors.generic')}+ </EmptyTitle>+ <EmptyDescription>+ {forbidden+ ? t('admin.pages.home.unavailable.description')+ : overviewError.message}+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ </CardContent>+ </Card>+ </div>+ )+ }+if (!overview) {return <DashboardSkeleton />}@@ -123,7 +181,13 @@ function DashboardPage() {<DateRangePicker value={dateRange} onChange={setDateRange} /></div></div>- <AnalyticsChart data={overview} />+ <TimeSeriesChart+ metrics={chartMetrics}+ result={overview}+ dimension="completed_at"+ grain="day"+ compare+ /><div className="grid gap-6 lg:grid-cols-5"><OperationsCarddata={operations}@@ -138,167 +202,6 @@ function DashboardPage() {)}-/**- * Period-over-period delta indicator: green/red trend arrow + percentage, a- * neutral dash at 0, and a "New" badge when there is no previous-period- * baseline (`growth === null`).- */-function GrowthBadge({ growth }: { growth: number | null | undefined }) {- const { t } = useTranslation()-- if (growth === null || growth === undefined) {- return (- <Badge variant="secondary" title={t('admin.pages.home.growth.vs_previous')}>- {t('admin.pages.home.growth.new')}- </Badge>- )- }-- const formatted = `${growth > 0 ? '+' : ''}${growth.toLocaleString()}%`-- if (growth === 0) {- return (- <span- className="inline-flex items-center gap-0.5 text-xs font-medium text-muted-foreground"- title={t('admin.pages.home.growth.vs_previous')}- >- <MinusIcon className="size-3" />- {formatted}- </span>- )- }-- return (- <span- className={`inline-flex items-center gap-0.5 text-xs font-medium ${- growth > 0 ? 'text-green-700 dark:text-green-400' : 'text-destructive'- }`}- title={t('admin.pages.home.growth.vs_previous')}- >- {growth > 0 ? <TrendingUpIcon className="size-3" /> : <TrendingDownIcon className="size-3" />}- {formatted}- </span>- )-}--function AnalyticsChart({ data }: { data: ReportingResult }) {- const { t, i18n } = useTranslation()- const locale = i18n.language- const [activeMetric, setActiveMetric] = useState<ChartMetric>('sales')-- const totalFor = (uiKey: ChartMetric) => data.totals[CHART_METRICS[uiKey]]- const displayFor = (uiKey: ChartMetric) => {- const total = totalFor(uiKey)- return total?.display ?? (total?.value ?? 0).toLocaleString()- }-- // One reporting query feeds both series: `value` is the current period,- // `previous` the aligned bucket from the comparison period.- const chartData = data.rows.map((row) => ({- date: rawDimension(row, 'completed_at'),- current: row.metrics[CHART_METRICS[activeMetric]]?.value ?? 0,- previous: row.metrics[CHART_METRICS[activeMetric]]?.previous ?? 0,- }))-- const chartConfig: ChartConfig = {- current: {- label: t(`admin.pages.home.metric_short.${activeMetric}`),- color: 'var(--chart-2)',- },- previous: {- label: t('admin.pages.home.legend.previous'),- color: 'var(--muted-foreground)',- },- }-- const formatDay = (value: string) =>- new Date(value).toLocaleDateString(locale, { month: 'short', day: 'numeric' })-- return (- <Card>- <CardHeader className="grid h-auto grid-cols-2 gap-0 border-b p-0 sm:grid-cols-3 lg:grid-cols-5">- {(Object.keys(CHART_METRICS) as ChartMetric[]).map((metric) => (- <button- key={metric}- type="button"- onClick={() => setActiveMetric(metric)}- className="relative flex min-w-0 flex-1 flex-col justify-center gap-1 border-l px-3 py-3 text-left transition-colors first:border-l-0 hover:bg-accent/40 sm:px-6 sm:py-4"- >- <span className="text-xs text-muted-foreground">- {t(`admin.pages.home.metrics.${metric}`)}- </span>- <span className="flex items-center gap-2">- <span className="text-lg font-bold leading-none">{displayFor(metric)}</span>- <GrowthBadge growth={totalFor(metric)?.growth} />- </span>- {activeMetric === metric && (- <span className="absolute inset-x-0 bottom-0 h-0.5 bg-primary" />- )}- </button>- ))}- </CardHeader>- <CardContent className="px-2 pt-4 sm:px-6 sm:pt-6">- <ChartContainer config={chartConfig} className="aspect-auto h-[250px] w-full">- <ComposedChart data={chartData}>- <CartesianGrid vertical={false} />- <XAxis- dataKey="date"- tickLine={false}- axisLine={false}- tickMargin={8}- minTickGap={32}- tickFormatter={formatDay}- />- <ChartTooltip- cursor={{ fill: 'rgba(0, 0, 0, 0.04)' }}- content={- <ChartTooltipContent- labelFormatter={(value: string) => {- return new Date(value).toLocaleDateString(locale, {- month: 'short',- day: 'numeric',- year: 'numeric',- })- }}- />- }- />- <Bar- dataKey="current"- fill="var(--color-current)"- opacity={0.8}- activeBar={{ opacity: 1 }}- radius={[4, 4, 0, 0]}- />- <Line- dataKey="previous"- stroke="var(--color-previous)"- strokeWidth={2}- strokeDasharray="4 4"- strokeOpacity={0.7}- dot={false}- type="monotone"- />- </ComposedChart>- </ChartContainer>- <div className="flex items-center justify-center gap-6 pb-2 pt-3 text-xs text-muted-foreground">- <span className="inline-flex items-center gap-1.5">- <span className="size-2.5 rounded-[2px]" style={{ background: 'var(--chart-2)' }} />- {t('admin.pages.home.legend.current')}- </span>- <span className="inline-flex items-center gap-1.5">- <span- className="h-0 w-4 border-t-2 border-dashed"- style={{ borderColor: 'var(--muted-foreground)' }}- />- {t('admin.pages.home.legend.previous')}- </span>- </div>- </CardContent>- </Card>- )-}-const OPERATIONS_ROW_CLASS = 'flex items-center gap-3 border-b px-4 py-3 last:border-0'type OperationsFilter = { id: string; field: string; operator: string; value: string }@@ -377,9 +280,10 @@ function OperationsCard({<Skeleton className="h-4 w-8" />) : (<span- className={`text-sm font-semibold tabular-nums ${- count === 0 ? 'text-muted-foreground' : ''- }`}+ className={cn(+ 'text-sm font-semibold tabular-nums',+ count === 0 && 'text-muted-foreground',+ )}>{count.toLocaleString()}</span>@@ -395,7 +299,7 @@ function OperationsCard({to={link.to}params={{ storeId }}search={{ filters: link.filters }}- className={`${OPERATIONS_ROW_CLASS} hover:bg-muted/25`}+ className={cn(OPERATIONS_ROW_CLASS, 'hover:bg-muted/25')}>{content}</Link>@@ -460,9 +364,11 @@ function RankingsCard({const [tab, setTab] = useState<RankingTab>(tabs[0])const { query, revenueMetric, countMetric } = RANKING_QUERIES[tab]- const { data } = useReportingQuery({ ...query, ...scope })+ const { data, isPlaceholderData } = useReportingQuery({ ...query, ...scope })- const rows = data?.rows.map((row) => {+ // Placeholder data belongs to the previous tab (other dimension, other+ // metrics) — show the skeleton until this tab's own rows arrive.+ const rows = (isPlaceholderData ? undefined : data)?.rows.map((row) => {const dimension = entityDimension(row, tab === 'customers' ? 'customer' : 'category')const amount = row.metrics[revenueMetric]const count = row.metrics[countMetric]?.value ?? 0@@ -487,20 +393,15 @@ function RankingsCard({<CardTitle>{t('admin.pages.home.rankings.title')}</CardTitle><CardDescription>{t('admin.pages.home.rankings.subtitle')}</CardDescription></div>- <div className="flex rounded-lg border p-0.5">- {tabs.map((value) => (- <button- key={value}- type="button"- onClick={() => setTab(value)}- className={`rounded-md px-3 py-1 text-sm ${- tab === value ? 'bg-muted font-medium' : 'text-muted-foreground hover:bg-muted/50'- }`}- >- {t(`admin.pages.home.rankings.tabs.${value}`)}- </button>- ))}- </div>+ <Tabs value={tab} onValueChange={(value) => setTab(value as RankingTab)}>+ <TabsList>+ {tabs.map((value) => (+ <TabsTrigger key={value} value={value}>+ {t(`admin.pages.home.rankings.tabs.${value}`)}+ </TabsTrigger>+ ))}+ </TabsList>+ </Tabs></CardHeader><CardContent className="p-0">{rows === undefined ? (@@ -512,7 +413,7 @@ function RankingsCard({) : (<div className="flex flex-col">{rows.map((row, index) => (- <div key={`${tab}-${row.key}`} className="border-b px-4 py-3 last:border-0">+ <div key={`${tab}-${row.key ?? index}`} className="border-b px-4 py-3 last:border-0"><div className="flex items-baseline justify-between gap-3"><span className="flex min-w-0 items-baseline gap-2 text-sm"><span className="w-5 shrink-0 text-muted-foreground tabular-nums">@@ -525,15 +426,7 @@ function RankingsCard({<span className="block text-xs text-muted-foreground">{row.meta}</span></span></div>- <div className="mt-2 h-1 w-full overflow-hidden rounded-full bg-muted">- <div- className="h-full rounded-full"- style={{- background: 'var(--chart-2)',- width: `${maxAmount > 0 ? Math.max((row.amount / maxAmount) * 100, 2) : 0}%`,- }}- />- </div>+ <Progress className="mt-2" value={sharePercent(row.amount, maxAmount)} /></div>))}</div>@@ -552,15 +445,7 @@ function RankingName({storeId: stringdimension: ReportingDimensionValue}) {- const email = metaString(dimension, 'email')- const label = (- <span className="min-w-0">- <span className="block truncate font-medium">{dimension.label}</span>- {email && email !== dimension.label && (- <span className="block truncate text-xs text-muted-foreground">{email}</span>- )}- </span>- )+ const label = <DimensionLabel dimension={dimension} />if (!dimension.id) {return label@@ -629,23 +514,17 @@ function TopProducts({ scope }: { scope: Pick<ReportingQuery, 'time_range' | 'fi<CardDescription>{t('admin.pages.home.top_products_description')}</CardDescription></CardHeader><CardContent className="p-0">- <table className="w-full text-sm">- <thead>- <tr className="border-b text-left text-muted-foreground">- <th className="px-4 py-2 font-medium">{t('admin.pages.home.columns.product')}</th>- <th className="px-4 py-2 text-right font-medium">- {t('admin.pages.home.columns.price')}- </th>- <th className="px-4 py-2 text-right font-medium">- {t('admin.pages.home.columns.sold')}- </th>- <th className="px-4 py-2 text-right font-medium">{t('admin.fields.total.label')}</th>- <th className="px-4 py-2 text-right font-medium">- {t('admin.pages.home.columns.trend')}- </th>- </tr>- </thead>- <tbody>+ <Table roundedBottom>+ <TableHeader>+ <TableHeaderRow>+ <TableHead>{t('admin.pages.home.columns.product')}</TableHead>+ <TableHead className="text-right">{t('admin.pages.home.columns.price')}</TableHead>+ <TableHead className="text-right">{t('admin.pages.home.columns.sold')}</TableHead>+ <TableHead className="text-right">{t('admin.fields.total.label')}</TableHead>+ <TableHead className="text-right">{t('admin.pages.home.columns.trend')}</TableHead>+ </TableHeaderRow>+ </TableHeader>+ <TableBody>{data.rows.map((row) => {const product = entityDimension(row, 'product')const productId = product.id@@ -654,8 +533,8 @@ function TopProducts({ scope }: { scope: Pick<ReportingQuery, 'time_range' | 'ficonst price = metaString(product, 'price')return (- <tr key={productId ?? product.label} className="border-b last:border-0">- <td className="px-4 py-3">+ <TableRow key={productId ?? product.label}>+ <TableCell>{productId ? (<Linkto="/$storeId/products/$productId"@@ -671,20 +550,20 @@ function TopProducts({ scope }: { scope: Pick<ReportingQuery, 'time_range' | 'fi<span className="font-medium">{product.label}</span></span>)}- </td>- <td className="px-4 py-3 text-right text-muted-foreground">{price ?? '-'}</td>- <td className="px-4 py-3 text-right">{row.metrics.units_sold?.value ?? 0}</td>- <td className="px-4 py-3 text-right font-medium">+ </TableCell>+ <TableCell className="text-right text-muted-foreground">{price ?? '-'}</TableCell>+ <TableCell className="text-right">{row.metrics.units_sold?.value ?? 0}</TableCell>+ <TableCell className="text-right font-medium">{revenue?.display ?? revenue?.value}- </td>- <td className="px-4 py-3 text-right">+ </TableCell>+ <TableCell className="text-right"><GrowthBadge growth={revenue?.growth} />- </td>- </tr>+ </TableCell>+ </TableRow>)})}- </tbody>- </table>+ </TableBody>+ </Table></CardContent></Card>)@@ -698,22 +577,7 @@ function DashboardSkeleton() {<h1 className="text-2xl font-bold">{t('admin.pages.home.title')}</h1><p className="text-muted-foreground">{t('admin.pages.home.subtitle')}</p></div>- <Card>- <CardHeader className="grid h-auto grid-cols-2 gap-0 border-b p-0 sm:grid-cols-3 lg:grid-cols-5">- {['stat-1', 'stat-2', 'stat-3', 'stat-4', 'stat-5'].map((key) => (- <div- key={key}- className="flex flex-col gap-2 px-6 py-4 sm:border-l sm:first:border-l-0"- >- <Skeleton className="h-3 w-20" />- <Skeleton className="h-7 w-28" />- </div>- ))}- </CardHeader>- <CardContent className="px-2 pt-4 sm:px-6 sm:pt-6">- <Skeleton className="h-[250px] w-full" />- </CardContent>- </Card>+ <ReportSkeleton /><div className="grid gap-6 lg:grid-cols-5"><Card className="lg:col-span-2"><CardHeader>diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/reports/$reportId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/reports/$reportId.tsxnew file mode 100644index 0000000000..97356a520b--- /dev/null+++ b/packages/dashboard/src/routes/_authenticated/$storeId/reports/$reportId.tsx@@ -0,0 +1,198 @@+import type { ReportingQuery, ReportingSchema, SavedReport } from '@spree/admin-sdk'+import { PageHeader, Subject, useExport, usePermissions } from '@spree/dashboard-core'+import { Badge, Button, DropdownMenuItem, ResourceLayout, useConfirm } from '@spree/dashboard-ui'+import { DownloadIcon } from '@spree/dashboard-ui/icons'+import { createFileRoute, useNavigate } from '@tanstack/react-router'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { ReportWorkspace } from '../../../../components/spree/reporting/report-workspace'+import { SaveReportDialog } from '../../../../components/spree/reporting/save-report-dialog'+import { useReportRun } from '../../../../hooks/use-report-run'+import { useReportingSchema } from '../../../../hooks/use-reporting'+import {+ useCreateSavedReport,+ useDeleteSavedReport,+ useSavedReport,+ useUpdateSavedReport,+} from '../../../../hooks/use-saved-reports'++export const Route = createFileRoute('/_authenticated/$storeId/reports/$reportId')({+ component: ReportPage,+})++const EXPORT_TYPE = 'Spree::Exports::Report'++function ReportPage() {+ const { t } = useTranslation()+ const { storeId, reportId } = Route.useParams()+ const { data: report } = useSavedReport(reportId)+ const { data: schema } = useReportingSchema()++ if (!report || !schema) {+ return (+ <ResourceLayout+ header={<PageHeader title={t('admin.common.loading')} backTo="reports" />}+ main={<div className="text-sm text-muted-foreground">{t('admin.common.loading')}</div>}+ />+ )+ }++ // Keyed by id so navigating between reports re-seeds the draft from the+ // freshly loaded record instead of syncing state in an effect.+ return <ReportDetail key={report.id} report={report} schema={schema} storeId={storeId} />+}++function ReportDetail({+ report,+ schema,+ storeId,+}: {+ report: SavedReport+ schema: ReportingSchema+ storeId: string+}) {+ const { t } = useTranslation()+ const navigate = useNavigate()+ const confirm = useConfirm()+ const { permissions } = usePermissions()+ const savedQuery = report.query as unknown as ReportingQuery+ const [dialog, setDialog] = useState<'copy' | 'rename' | null>(null)+ const { draft, setDraft, query, runnable, dirty, result, error } = useReportRun(+ savedQuery,+ schema,+ )++ const update = useUpdateSavedReport(report.id)+ const create = useCreateSavedReport()+ const remove = useDeleteSavedReport()+ const exportMutation = useExport()++ const canCreate = permissions.can('create', Subject.SavedReport)+ const canExport = permissions.can('create', Subject.ReportExport)+ const canUpdate = !report.seeded && permissions.can('update', Subject.SavedReport)+ const canDestroy = permissions.can('destroy', Subject.SavedReport)++ async function handleDelete() {+ const ok = await confirm({+ title: t('admin.actions.delete'),+ message: t('admin.reports.delete_confirm', { name: report.name }),+ variant: 'destructive',+ confirmLabel: t('admin.actions.delete'),+ })+ if (!ok) return+ await remove.mutateAsync(report.id)+ navigate({ to: '/$storeId/reports', params: { storeId } })+ }++ return (+ <>+ <ResourceLayout+ header={+ <PageHeader+ title={report.name}+ subtitle={report.description ?? undefined}+ backTo="reports"+ badges={+ report.seeded && <Badge variant="secondary">{t('admin.reports.kind.built_in')}</Badge>+ }+ actions={+ <>+ {canExport && (+ <Button+ variant="outline"+ disabled={!runnable || exportMutation.isPending}+ onClick={() =>+ exportMutation.mutate({ type: EXPORT_TYPE, search_params: { query } })+ }+ >+ <DownloadIcon className="size-4" />+ {t('admin.reports.actions.export_csv')}+ </Button>+ )}+ {canUpdate && (+ <Button+ disabled={!dirty || !runnable || update.isPending}+ onClick={() => update.mutate({ query })}+ >+ {t('admin.reports.actions.save')}+ </Button>+ )}+ {report.seeded && canCreate && (+ <Button disabled={!runnable} onClick={() => setDialog('copy')}>+ {t('admin.reports.actions.save_copy')}+ </Button>+ )}+ </>+ }+ dropdownItems={+ <>+ {canUpdate && (+ <DropdownMenuItem onClick={() => setDialog('rename')}>+ {t('admin.reports.actions.rename')}+ </DropdownMenuItem>+ )}+ {!report.seeded && canCreate && (+ <DropdownMenuItem disabled={!runnable} onClick={() => setDialog('copy')}>+ {t('admin.reports.actions.save_copy')}+ </DropdownMenuItem>+ )}+ </>+ }+ destructiveItems={+ canDestroy ? (+ <DropdownMenuItem+ variant="destructive"+ disabled={remove.isPending}+ onClick={handleDelete}+ >+ {t('admin.actions.delete')}+ </DropdownMenuItem>+ ) : undefined+ }+ />+ }+ main={+ <div className="flex flex-col gap-4">+ {report.seeded && (+ <p className="text-sm text-muted-foreground">{t('admin.reports.seeded_hint')}</p>+ )}+ <ReportWorkspace+ draft={draft}+ onChange={setDraft}+ schema={schema}+ query={query}+ result={result}+ error={error}+ />+ </div>+ }+ />+ {dialog === 'rename' && (+ <SaveReportDialog+ open+ onOpenChange={(open) => !open && setDialog(null)}+ title={t('admin.reports.save_dialog.title_rename')}+ submitLabel={t('admin.reports.actions.save')}+ defaultValues={{ name: report.name, description: report.description ?? '' }}+ onSubmit={(values) => update.mutateAsync(values)}+ />+ )}+ {dialog === 'copy' && (+ <SaveReportDialog+ open+ onOpenChange={(open) => !open && setDialog(null)}+ title={t('admin.reports.save_dialog.title_copy')}+ submitLabel={t('admin.reports.actions.save')}+ defaultValues={{+ name: t('admin.reports.copy_name', { name: report.name }),+ description: report.description ?? '',+ }}+ onSubmit={async (values) => {+ const copy = await create.mutateAsync({ ...values, query })+ navigate({ to: '/$storeId/reports/$reportId', params: { storeId, reportId: copy.id } })+ }}+ />+ )}+ </>+ )+}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/reports/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/reports/index.tsxnew file mode 100644index 0000000000..2449a03bd4--- /dev/null+++ b/packages/dashboard/src/routes/_authenticated/$storeId/reports/index.tsx@@ -0,0 +1,90 @@+import type { SavedReport } from '@spree/admin-sdk'+import {+ adminClient,+ ResourceTable,+ resourceSearchSchema,+ Subject,+ usePermissions,+} from '@spree/dashboard-core'+import { Button, RowActions, useConfirm } from '@spree/dashboard-ui'+import { PlusIcon } from '@spree/dashboard-ui/icons'+import { createFileRoute, useNavigate } from '@tanstack/react-router'+import { useTranslation } from 'react-i18next'+import { useDeleteSavedReport } from '../../../../hooks/use-saved-reports'+import '../../../../tables/saved-reports'++export const Route = createFileRoute('/_authenticated/$storeId/reports/')({+ validateSearch: resourceSearchSchema,+ component: ReportsPage,+})++function ReportsPage() {+ const { t } = useTranslation()+ const { storeId } = Route.useParams()+ const searchParams = Route.useSearch()+ const navigate = useNavigate()+ const { permissions } = usePermissions()++ return (+ <ResourceTable<SavedReport>+ tableKey="saved-reports"+ queryKey="saved-reports"+ queryFn={(params) => adminClient.reporting.savedReports.list(params)}+ searchParams={searchParams}+ rowActions={(report) => <ReportRowActions report={report} storeId={storeId} />}+ actions={+ permissions.can('create', Subject.SavedReport) ? (+ <Button+ size="sm"+ className="h-[2.125rem]"+ onClick={() => navigate({ to: '/$storeId/reports/new', params: { storeId } })}+ >+ <PlusIcon className="size-4" />+ {t('admin.reports.new_cta')}+ </Button>+ ) : null+ }+ />+ )+}++function ReportRowActions({ report, storeId }: { report: SavedReport; storeId: string }) {+ const { t } = useTranslation()+ const navigate = useNavigate()+ const confirm = useConfirm()+ const deleteMutation = useDeleteSavedReport()+ const { permissions } = usePermissions()++ async function handleDelete() {+ const ok = await confirm({+ title: t('admin.actions.delete'),+ message: t('admin.reports.delete_confirm', { name: report.name }),+ variant: 'destructive',+ confirmLabel: t('admin.actions.delete'),+ })+ if (!ok) return+ await deleteMutation.mutateAsync(report.id).catch(() => undefined)+ }++ return (+ <RowActions+ actions={[+ {+ key: 'edit',+ onSelect: () =>+ navigate({+ to: '/$storeId/reports/$reportId',+ params: { storeId, reportId: report.id },+ }),+ },+ {+ key: 'delete',+ destructive: true,+ visible: permissions.can('destroy', Subject.SavedReport),+ disabled: deleteMutation.isPending,+ onSelect: handleDelete,+ },+ ]}+ />+ )+}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/reports/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/reports/new.tsxnew file mode 100644index 0000000000..ad27f7859b--- /dev/null+++ b/packages/dashboard/src/routes/_authenticated/$storeId/reports/new.tsx@@ -0,0 +1,96 @@+import type { ReportingQuery } from '@spree/admin-sdk'+import { PageHeader } from '@spree/dashboard-core'+import { Button, ResourceLayout } from '@spree/dashboard-ui'+import { createFileRoute, useNavigate } from '@tanstack/react-router'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { z } from 'zod/v4'+import { EMPTY_QUERY } from '../../../../components/spree/reporting/report-draft'+import { ReportWorkspace } from '../../../../components/spree/reporting/report-workspace'+import { SaveReportDialog } from '../../../../components/spree/reporting/save-report-dialog'+import { useReportRun } from '../../../../hooks/use-report-run'+import { useReportingSchema } from '../../../../hooks/use-reporting'+import { useCreateSavedReport } from '../../../../hooks/use-saved-reports'++// `?query=` carries a JSON query contract so any widget (the home screen+// cards, a future assistant) can hand its query over as a starting point.+const newReportSearchSchema = z.object({ query: z.string().optional() })++export const Route = createFileRoute('/_authenticated/$storeId/reports/new')({+ validateSearch: newReportSearchSchema,+ component: NewReportPage,+})++function seedQuery(seed: string | undefined): ReportingQuery {+ if (!seed) return EMPTY_QUERY+ try {+ const parsed = JSON.parse(seed) as ReportingQuery+ return Array.isArray(parsed.metrics) ? parsed : EMPTY_QUERY+ } catch {+ return EMPTY_QUERY+ }+}++function NewReportPage() {+ const { t } = useTranslation()+ const { storeId } = Route.useParams()+ const { query: seedParam } = Route.useSearch()+ const navigate = useNavigate()+ const { data: schema } = useReportingSchema()+ const [seed] = useState(() => seedQuery(seedParam))+ const [saveOpen, setSaveOpen] = useState(false)+ const create = useCreateSavedReport()+ const { draft, setDraft, query, runnable, result, error } = useReportRun(seed, schema)++ if (!schema) {+ return (+ <ResourceLayout+ header={<PageHeader title={t('admin.reports.new_title')} backTo="reports" />}+ main={<div className="text-sm text-muted-foreground">{t('admin.common.loading')}</div>}+ />+ )+ }++ return (+ <>+ <ResourceLayout+ header={+ <PageHeader+ title={t('admin.reports.new_title')}+ backTo="reports"+ actions={+ <Button onClick={() => setSaveOpen(true)} disabled={!runnable}>+ {t('admin.reports.actions.save')}+ </Button>+ }+ />+ }+ main={+ <ReportWorkspace+ draft={draft}+ onChange={setDraft}+ schema={schema}+ query={query}+ result={result}+ error={error}+ />+ }+ />+ {saveOpen && (+ <SaveReportDialog+ open+ onOpenChange={setSaveOpen}+ title={t('admin.reports.save_dialog.title_create')}+ submitLabel={t('admin.reports.actions.save')}+ onSubmit={async (values) => {+ const report = await create.mutateAsync({ ...values, query })+ navigate({+ to: '/$storeId/reports/$reportId',+ params: { storeId, reportId: report.id },+ })+ }}+ />+ )}+ </>+ )+}diff --git a/packages/dashboard/src/tables/saved-reports.tsx b/packages/dashboard/src/tables/saved-reports.tsxnew file mode 100644index 0000000000..869b96ca06--- /dev/null+++ b/packages/dashboard/src/tables/saved-reports.tsx@@ -0,0 +1,52 @@+import type { SavedReport } from '@spree/admin-sdk'+import { defineTable } from '@spree/dashboard-core'+import { Badge } from '@spree/dashboard-ui'+import { ChartColumnIcon } from '@spree/dashboard-ui/icons'+import { Link } from '@tanstack/react-router'+import i18n from 'i18next'++defineTable<SavedReport>('saved-reports', {+ title: i18n.t('admin.reports.title'),+ description: i18n.t('admin.reports.subtitle'),+ searchParam: 'name_cont',+ searchPlaceholder: i18n.t('admin.reports.table.search_placeholder'),+ defaultSort: { field: 'name', direction: 'asc' },+ emptyIcon: <ChartColumnIcon className="size-8 text-muted-foreground" />,+ emptyMessage: i18n.t('admin.reports.table.empty'),+ columns: [+ {+ key: 'name',+ label: i18n.t('admin.reports.table.columns.name'),+ sortable: true,+ default: true,+ render: (report) => (+ <Link+ to={'/$storeId/reports/$reportId' as string}+ params={{ reportId: report.id }}+ className="block no-underline"+ >+ <span className="block font-medium text-foreground">{report.name}</span>+ {report.description && (+ <span className="block text-xs text-muted-foreground">{report.description}</span>+ )}+ </Link>+ ),+ },+ {+ key: 'seeded',+ label: i18n.t('admin.reports.table.columns.kind'),+ default: true,+ render: (report) => (+ <Badge variant={report.seeded ? 'secondary' : 'outline'}>+ {i18n.t(report.seeded ? 'admin.reports.kind.built_in' : 'admin.reports.kind.custom')}+ </Badge>+ ),+ },+ {+ key: 'author_name',+ label: i18n.t('admin.reports.table.columns.author'),+ default: true,+ render: (report) => report.author_name ?? '—',+ },+ ],+})diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rbindex 7360b5af25..278b28b4db 100644--- a/spree/core/lib/spree/core/engine.rb+++ b/spree/core/lib/spree/core/engine.rb@@ -468,7 +468,7 @@ module SpreeSpree::Exports::NewsletterSubscribers,Spree::Exports::CouponCodes,Spree::Exports::PriceListPrices,- Spree::Exports::PurchaseOrders+ Spree::Exports::PurchaseOrders,Spree::Exports::Report]