Skip to content

armgit / spree

Public Imported from GitHub
0

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

Add dashboard with analytics charts, top products, and date range picker

Damian Legawiec2c3b2c4a2d4c
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index e30dd59a78..bcad77dc53 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -2,6 +2,37 @@ import type { RequestFn, RequestOptions } from '@spree/sdk-core';
import { transformListParams, getParams } from '@spree/sdk-core';
import type { PaginatedResponse, ListParams } from '@spree/sdk-core';
+export interface DashboardAnalytics {
+ currency: string;
+ date_from: string;
+ date_to: string;
+ summary: {
+ sales_total: number;
+ display_sales_total: string;
+ sales_growth: number;
+ orders_count: number;
+ orders_growth: number;
+ avg_order_value: number;
+ display_avg_order_value: string;
+ avg_order_value_growth: number;
+ };
+ chart_data: Array<{
+ date: string;
+ sales: number;
+ orders: number;
+ avg_order_value: number;
+ }>;
+ top_products: Array<{
+ id: string;
+ name: string;
+ slug: string;
+ image_url: string | null;
+ price: string | null;
+ quantity: number;
+ total: string;
+ }>;
+}
+
export interface AuthTokens {
token: string;
refresh_token?: string;
@@ -82,6 +113,18 @@ export class AdminClient {
this.request<MeResponse>('GET', '/me', options),
};
+ // ============================================
+ // Dashboard
+ // ============================================
+
+ readonly dashboard = {
+ analytics: (params?: { date_from?: string; date_to?: string; currency?: string }, options?: RequestOptions): Promise<DashboardAnalytics> =>
+ this.request<DashboardAnalytics>('GET', '/dashboard/analytics', {
+ ...options,
+ params: params as Record<string, string>,
+ }),
+ };
+
// ============================================
// Store Settings
// ============================================
diff --git a/packages/admin-sdk/src/index.ts b/packages/admin-sdk/src/index.ts
index 8bb169fb61..18df56716d 100644
--- a/packages/admin-sdk/src/index.ts
+++ b/packages/admin-sdk/src/index.ts
@@ -4,7 +4,7 @@ export type { AdminClientConfig, Client } from './client';
// Admin client class (for advanced use / subclassing)
export { AdminClient } from './admin-client';
-export type { AuthTokens, LoginCredentials, PermissionRule, MeResponse } from './admin-client';
+export type { AuthTokens, LoginCredentials, PermissionRule, MeResponse, DashboardAnalytics } from './admin-client';
// Request infrastructure (re-export from sdk-core)
export { SpreeError } from '@spree/sdk-core';
diff --git a/packages/admin/package.json b/packages/admin/package.json
index 31c59dc8ad..ea55a1d8a3 100644
--- a/packages/admin/package.json
+++ b/packages/admin/package.json
@@ -31,6 +31,7 @@
"react-day-picker": "^9.14.0",
"react-dom": "^19.2.0",
"react-hook-form": "^7.71.2",
+ "recharts": "^3.8.1",
"shadcn": "^4.0.0",
"sonner": "^2.0.7",
"spark-md5": "^3.0.2",
diff --git a/packages/admin/src/components/date-range-picker.tsx b/packages/admin/src/components/date-range-picker.tsx
new file mode 100644
index 0000000000..ddbc3817d1
--- /dev/null
+++ b/packages/admin/src/components/date-range-picker.tsx
@@ -0,0 +1,142 @@
+import { CalendarIcon, ChevronDownIcon } from 'lucide-react'
+import { useMemo, useState } from 'react'
+import { format, subDays, subHours, subMonths } from 'date-fns'
+import type { DateRange as DayPickerDateRange } from 'react-day-picker'
+import { Button } from '@/components/ui/button'
+import { Calendar } from '@/components/ui/calendar'
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
+
+export interface DateRange {
+ from: Date
+ to: Date
+}
+
+interface Preset {
+ label: string
+ value: () => DateRange
+}
+
+const presets: Preset[] = [
+ { label: 'Last 24 hours', value: () => ({ from: subHours(new Date(), 24), to: new Date() }) },
+ { label: 'Last 7 days', value: () => ({ from: subDays(new Date(), 7), to: new Date() }) },
+ { label: 'Last 30 days', value: () => ({ from: subDays(new Date(), 30), to: new Date() }) },
+ { label: 'Last 3 months', value: () => ({ from: subMonths(new Date(), 3), to: new Date() }) },
+]
+
+interface DateRangePickerProps {
+ value: DateRange
+ onChange: (range: DateRange) => void
+}
+
+export function DateRangePicker({ value, onChange }: DateRangePickerProps) {
+ const [open, setOpen] = useState(false)
+ const [selecting, setSelecting] = useState<'presets' | 'custom'>('presets')
+ const [customRange, setCustomRange] = useState<DayPickerDateRange | undefined>({
+ from: value.from,
+ to: value.to,
+ })
+
+ const activePresetLabel = useMemo(() => {
+ const now = new Date()
+ const diffMs = now.getTime() - value.from.getTime()
+ const diffHours = diffMs / (1000 * 60 * 60)
+ const diffDays = diffMs / (1000 * 60 * 60 * 24)
+
+ if (diffHours <= 25) return 'Last 24 hours'
+ if (diffDays <= 8) return 'Last 7 days'
+ if (diffDays <= 31) return 'Last 30 days'
+ if (diffDays <= 92) return 'Last 3 months'
+ return `${format(value.from, 'MMM d, yyyy')} – ${format(value.to, 'MMM d, yyyy')}`
+ }, [value])
+
+ function handlePreset(preset: Preset) {
+ onChange(preset.value())
+ setOpen(false)
+ setSelecting('presets')
+ }
+
+ function handleCustomApply() {
+ if (customRange?.from && customRange?.to) {
+ onChange({ from: customRange.from, to: customRange.to })
+ setOpen(false)
+ setSelecting('presets')
+ }
+ }
+
+ const displayRange = customRange?.from && customRange?.to
+ ? `${format(customRange.from, 'MMM d, yyyy')} – ${format(customRange.to, 'MMM d, yyyy')}`
+ : customRange?.from
+ ? `${format(customRange.from, 'MMM d, yyyy')} – ...`
+ : 'Select start and end dates'
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button variant="outline" size="sm" className="h-8 gap-2 text-sm font-normal">
+ <CalendarIcon className="size-3.5" />
+ {activePresetLabel}
+ <ChevronDownIcon className="size-3.5 text-muted-foreground" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-auto p-0">
+ {selecting === 'presets' ? (
+ <div className="flex flex-col">
+ {presets.map((preset) => (
+ <button
+ key={preset.label}
+ type="button"
+ onClick={() => handlePreset(preset)}
+ className="px-4 py-2.5 text-left text-sm hover:bg-muted transition-colors first:rounded-t-lg"
+ >
+ {preset.label}
+ </button>
+ ))}
+ <div className="border-t" />
+ <button
+ type="button"
+ onClick={() => {
+ setSelecting('custom')
+ setCustomRange({ from: value.from, to: value.to })
+ }}
+ className="px-4 py-2.5 text-left text-sm hover:bg-muted transition-colors rounded-b-lg"
+ >
+ Custom range...
+ </button>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-3 p-3">
+ <div className="text-sm font-medium">Select date range</div>
+ <Calendar
+ mode="range"
+ defaultMonth={customRange?.from}
+ selected={customRange}
+ onSelect={setCustomRange}
+ numberOfMonths={2}
+ />
+ <div className="flex items-center justify-between border-t pt-3">
+ <div className="text-xs text-muted-foreground">
+ {displayRange}
+ </div>
+ <div className="flex gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setSelecting('presets')}
+ >
+ Back
+ </Button>
+ <Button
+ size="sm"
+ disabled={!customRange?.from || !customRange?.to}
+ onClick={handleCustomApply}
+ >
+ Apply
+ </Button>
+ </div>
+ </div>
+ </div>
+ )}
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/packages/admin/src/components/ui/button.tsx b/packages/admin/src/components/ui/button.tsx
index f45fe8a673..e18f7f1364 100644
--- a/packages/admin/src/components/ui/button.tsx
+++ b/packages/admin/src/components/ui/button.tsx
@@ -13,7 +13,7 @@ const buttonVariants = cva(
outline:
'border-border bg-muted text-foreground shadow-xs hover:bg-gray-100 hover:text-foreground aria-expanded:bg-gray-100',
secondary:
- 'bg-blue-50 text-blue-900 border-blue-100/75 shadow-xs hover:border-blue-100 hover:bg-blue-100/75',
+ 'bg-blue-50/50 text-blue-900 border-blue-100/75 shadow-xs hover:border-blue-100 hover:bg-blue-50/75',
ghost: 'hover:bg-accent hover:text-accent-foreground aria-expanded:bg-accent',
destructive: 'text-destructive bg-muted border-border shadow-xs hover:bg-red-100',
link: 'text-primary underline-offset-4 hover:underline',
diff --git a/packages/admin/src/components/ui/calendar.tsx b/packages/admin/src/components/ui/calendar.tsx
index 2ac0200bf6..26dde0b5fa 100644
--- a/packages/admin/src/components/ui/calendar.tsx
+++ b/packages/admin/src/components/ui/calendar.tsx
@@ -34,6 +34,7 @@ function Calendar({
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500',
'aria-selected:bg-blue-600 aria-selected:text-white aria-selected:hover:bg-blue-700 aria-selected:focus:bg-blue-700',
),
+ range_start: 'day-range-start rounded-l-md',
range_end: 'day-range-end rounded-r-md',
selected: 'bg-blue-600 text-white hover:bg-blue-700 focus:bg-blue-700',
today: 'bg-gray-100 text-gray-950',
diff --git a/packages/admin/src/components/ui/chart.tsx b/packages/admin/src/components/ui/chart.tsx
new file mode 100644
index 0000000000..7251168d4a
--- /dev/null
+++ b/packages/admin/src/components/ui/chart.tsx
@@ -0,0 +1,94 @@
+import * as React from 'react'
+import { ResponsiveContainer, Tooltip } from 'recharts'
+import { cn } from '@/lib/utils'
+
+export type ChartConfig = Record<string, { label: string; color?: string }>
+
+interface ChartContextValue {
+ config: ChartConfig
+}
+
+const ChartContext = React.createContext<ChartContextValue | null>(null)
+
+export function useChart() {
+ const ctx = React.useContext(ChartContext)
+ if (!ctx) throw new Error('useChart must be used within ChartContainer')
+ return ctx
+}
+
+export function ChartContainer({
+ config,
+ className,
+ children,
+ ...props
+}: React.ComponentProps<'div'> & { config: ChartConfig }) {
+ const cssVars = Object.entries(config).reduce(
+ (acc, [key, value]) => {
+ if (value.color) acc[`--color-${key}` as string] = value.color
+ return acc
+ },
+ {} as Record<string, string>,
+ )
+
+ return (
+ <ChartContext.Provider value={{ config }}>
+ <div
+ data-slot="chart"
+ className={cn(
+ "flex justify-center text-xs [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-hidden [&_.recharts-surface]:outline-hidden",
+ className,
+ )}
+ style={cssVars}
+ {...props}
+ >
+ <ResponsiveContainer>{children}</ResponsiveContainer>
+ </div>
+ </ChartContext.Provider>
+ )
+}
+
+export const ChartTooltip = Tooltip
+
+export function ChartTooltipContent({
+ active,
+ payload,
+ label,
+ className,
+ labelFormatter,
+}: {
+ active?: boolean
+ payload?: Array<{ dataKey?: string; name?: string; value?: number | string; color?: string }>
+ label?: string
+ className?: string
+ nameKey?: string
+ labelFormatter?: (label: string) => string
+}) {
+ const { config } = useChart()
+ if (!active || !payload?.length) return null
+
+ const formattedLabel = labelFormatter ? labelFormatter(label ?? '') : label
+
+ return (
+ <div className={cn('rounded-lg border bg-background px-3 py-2 text-sm shadow-md', className)}>
+ <div className="mb-1 font-medium">{formattedLabel}</div>
+ <div className="flex flex-col gap-0.5">
+ {payload.map((item, i) => {
+ const key = item.dataKey ?? item.name ?? ''
+ const conf = config[key]
+ return (
+ <div key={i} className="flex items-center gap-2">
+ <div
+ className="size-2.5 rounded-[2px]"
+ style={{ background: item.color || conf?.color }}
+ />
+ <span className="text-muted-foreground">{conf?.label || item.name}:</span>
+ <span className="font-medium">
+ {typeof item.value === 'number' ? item.value.toLocaleString() : item.value}
+ </span>
+ </div>
+ )
+ })}
+ </div>
+ </div>
+ )
+}
diff --git a/packages/admin/src/routes/_authenticated.tsx b/packages/admin/src/routes/_authenticated.tsx
index 92ba512043..0509a194d3 100644
--- a/packages/admin/src/routes/_authenticated.tsx
+++ b/packages/admin/src/routes/_authenticated.tsx
@@ -36,7 +36,7 @@ function AuthenticatedLayout() {
</Breadcrumb>
</div>
</header>
- <div className="flex flex-1 flex-col gap-4 p-4">
+ <div className="container mx-auto flex flex-1 flex-col gap-4 p-4">
<Outlet />
</div>
</SidebarInset>
diff --git a/packages/admin/src/routes/_authenticated/$storeId/index.tsx b/packages/admin/src/routes/_authenticated/$storeId/index.tsx
index d0e191fe2d..77b864f026 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/index.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/index.tsx
@@ -1,14 +1,264 @@
-import { createFileRoute } from '@tanstack/react-router'
+import { createFileRoute, Link } from '@tanstack/react-router'
+import { useQuery } from '@tanstack/react-query'
+import { useState } from 'react'
+import { subDays } from 'date-fns'
+import { Bar, BarChart, CartesianGrid, XAxis } from 'recharts'
+import { PackageIcon } from 'lucide-react'
+import { adminClient } from '@/client'
+import { DateRangePicker, type DateRange } from '@/components/date-range-picker'
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from '@/components/ui/card'
+import {
+ ChartContainer,
+ ChartTooltip,
+ ChartTooltipContent,
+ type ChartConfig,
+} from '@/components/ui/chart'
+import { Skeleton } from '@/components/ui/skeleton'
+import type { DashboardAnalytics } from '@spree/admin-sdk'
export const Route = createFileRoute('/_authenticated/$storeId/')({
component: DashboardPage,
})
+type ChartMetric = 'sales' | 'orders' | 'avg_order_value'
+
+const chartTabs: Array<{ key: ChartMetric; label: string }> = [
+ { key: 'sales', label: 'Total Sales' },
+ { key: 'orders', label: 'Total Orders' },
+ { key: 'avg_order_value', label: 'Avg Order Value' },
+]
+
+const chartConfigs: Record<ChartMetric, ChartConfig> = {
+ sales: {
+ sales: { label: 'Sales', color: 'var(--chart-2)' },
+ },
+ orders: {
+ orders: { label: 'Orders', color: 'var(--chart-2)' },
+ },
+ avg_order_value: {
+ avg_order_value: { label: 'AOV', color: 'var(--chart-2)' },
+ },
+}
+
function DashboardPage() {
+ const [dateRange, setDateRange] = useState<DateRange>({
+ from: subDays(new Date(), 30),
+ to: new Date(),
+ })
+
+ const { data, isLoading } = useQuery({
+ queryKey: ['dashboard', 'analytics', dateRange.from.toISOString(), dateRange.to.toISOString()],
+ queryFn: () =>
+ adminClient.dashboard.analytics({
+ date_from: dateRange.from.toISOString(),
+ date_to: dateRange.to.toISOString(),
+ }),
+ staleTime: 5 * 60 * 1000,
+ })
+
+ if (isLoading || !data) {
+ return <DashboardSkeleton />
+ }
+
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="flex items-center justify-between">
+ <div>
+ <h1 className="text-2xl font-bold">Dashboard</h1>
+ <p className="text-muted-foreground">Overview of your store performance</p>
+ </div>
+ <DateRangePicker value={dateRange} onChange={setDateRange} />
+ </div>
+ <AnalyticsChart data={data} />
+ <TopProducts products={data.top_products} />
+ </div>
+ )
+}
+
+function AnalyticsChart({ data }: { data: DashboardAnalytics }) {
+ const [activeMetric, setActiveMetric] = useState<ChartMetric>('sales')
+
+ const summaryValues: Record<ChartMetric, string> = {
+ sales: data.summary.display_sales_total,
+ orders: data.summary.orders_count.toLocaleString(),
+ avg_order_value: data.summary.display_avg_order_value,
+ }
+
+ return (
+ <Card>
+ <CardHeader className="flex h-auto flex-col border-b p-0 sm:flex-row">
+ {chartTabs.map((tab) => (
+ <button
+ key={tab.key}
+ type="button"
+ onClick={() => setActiveMetric(tab.key)}
+ className={`relative flex flex-1 flex-col justify-center gap-1 px-6 py-4 text-left ${
+ activeMetric === tab.key
+ ? 'bg-muted/50'
+ : 'hover:bg-muted/25'
+ } sm:border-l sm:first:border-l-0`}
+ >
+ <span className="text-xs text-muted-foreground">{tab.label}</span>
+ <span className="text-lg font-bold leading-none">{summaryValues[tab.key]}</span>
+ {activeMetric === tab.key && (
+ <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={chartConfigs[activeMetric]} className="aspect-auto h-[250px] w-full">
+ <BarChart data={data.chart_data}>
+ <CartesianGrid vertical={false} />
+ <XAxis
+ dataKey="date"
+ tickLine={false}
+ axisLine={false}
+ tickMargin={8}
+ minTickGap={32}
+ tickFormatter={(value: string) => {
+ const date = new Date(value)
+ return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
+ }}
+ />
+ <ChartTooltip
+ cursor={{ fill: 'rgba(0, 0, 0, 0.04)' }}
+ content={
+ <ChartTooltipContent
+ labelFormatter={(value: string) => {
+ return new Date(value).toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+ })
+ }}
+ />
+ }
+ />
+ <Bar
+ dataKey={activeMetric}
+ fill={`var(--color-${activeMetric})`}
+ opacity={0.8}
+ activeBar={{ opacity: 1 }}
+ radius={[4, 4, 0, 0]}
+ />
+ </BarChart>
+ </ChartContainer>
+ </CardContent>
+ </Card>
+ )
+}
+
+function TopProducts({
+ products,
+}: {
+ products: DashboardAnalytics['top_products']
+}) {
+ if (products.length === 0) {
+ return null
+ }
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Top Products</CardTitle>
+ <CardDescription>Best selling products by revenue</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">Product</th>
+ <th className="px-4 py-2 text-right font-medium">Price</th>
+ <th className="px-4 py-2 text-right font-medium">Sold</th>
+ <th className="px-4 py-2 text-right font-medium">Total</th>
+ </tr>
+ </thead>
+ <tbody>
+ {products.map((product) => (
+ <tr key={product.id} className="border-b last:border-0">
+ <td className="px-4 py-3">
+ <Link
+ to="/$storeId/products/$productId"
+ params={(prev) => ({
+ storeId: prev.storeId!,
+ productId: product.id,
+ })}
+ className="flex items-center gap-3 hover:underline"
+ >
+ {product.image_url ? (
+ <img
+ src={product.image_url}
+ alt={product.name}
+ className="size-10 rounded-md border object-cover"
+ />
+ ) : (
+ <div className="flex size-10 items-center justify-center rounded-md border bg-muted">
+ <PackageIcon className="size-4 text-muted-foreground" />
+ </div>
+ )}
+ <span className="font-medium">{product.name}</span>
+ </Link>
+ </td>
+ <td className="px-4 py-3 text-right text-muted-foreground">
+ {product.price ?? '-'}
+ </td>
+ <td className="px-4 py-3 text-right">{product.quantity}</td>
+ <td className="px-4 py-3 text-right font-medium">{product.total}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </CardContent>
+ </Card>
+ )
+}
+
+function DashboardSkeleton() {
return (
- <div className="space-y-4">
- <h1 className="text-2xl font-bold">Dashboard</h1>
- <p className="text-muted-foreground">Welcome to the Spree Admin dashboard.</p>
+ <div className="flex flex-col gap-6">
+ <div>
+ <h1 className="text-2xl font-bold">Dashboard</h1>
+ <p className="text-muted-foreground">Overview of your store performance</p>
+ </div>
+ <Card>
+ <CardHeader className="flex h-auto flex-col border-b p-0 sm:flex-row">
+ {Array.from({ length: 3 }).map((_, i) => (
+ <div key={i} className="flex flex-1 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>
+ <Card>
+ <CardHeader>
+ <Skeleton className="h-5 w-32" />
+ <Skeleton className="h-4 w-56" />
+ </CardHeader>
+ <CardContent className="p-0">
+ <div className="flex flex-col">
+ {Array.from({ length: 5 }).map((_, i) => (
+ <div key={i} className="flex items-center gap-3 border-b px-4 py-3 last:border-0">
+ <Skeleton className="size-10 rounded-md" />
+ <Skeleton className="h-4 w-32 flex-1" />
+ <Skeleton className="h-4 w-16" />
+ <Skeleton className="h-4 w-12" />
+ <Skeleton className="h-4 w-20" />
+ </div>
+ ))}
+ </div>
+ </CardContent>
+ </Card>
</div>
)
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2643826f93..e39e681896 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -75,6 +75,9 @@ importers:
react-hook-form:
specifier: ^7.71.2
version: 7.71.2([email protected])
+ recharts:
+ specifier: ^3.8.1
shadcn:
specifier: ^4.0.0
version: 4.0.3(@types/[email protected])([email protected])
@@ -916,6 +919,17 @@ packages:
'@oxc-project/[email protected]':
resolution: {integrity: sha512-4n91DKnebUS4yjUHl2g3/b2T+IUdCfmoZGhmwsovZCDaJSs+QkVAM+0AqqTxHSsHfeiMuueT75cZaZcT/m0pSw==}
+ '@reduxjs/[email protected]':
+ resolution: {integrity: sha512-Kd6kAHTA6/nUpp8mySPqj3en3dm0tdMIgbttnQ1xFMVpufoj+ADi8pXLBsd4xzTRHQa7t/Jv8W5UnCuW4kuWMQ==}
+ peerDependencies:
+ react: ^16.9.0 || ^17.0.0 || ^18 || ^19
+ react-redux: ^7.2.1 || ^8.1.3 || ^9.0.0
+ peerDependenciesMeta:
+ react:
+ optional: true
+ react-redux:
+ optional: true
+
'@remirror/[email protected]':
resolution: {integrity: sha512-42aWfPrimMfDKDi4YegyS7x+/0tlzaqwPQCULLanv3DMIlu96KTJR0fM5isWX2UViOqlGnX6YFgqWepcX+XMNg==}
@@ -1516,6 +1530,33 @@ packages:
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==}
+
resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
@@ -1921,6 +1962,50 @@ packages:
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
+ resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==}
engines: {node: '>= 12'}
@@ -1943,6 +2028,9 @@ packages:
supports-color:
optional: true
+ resolution: {integrity: sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==}
+
resolution: {integrity: sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==}
peerDependencies:
@@ -2056,6 +2144,9 @@ packages:
resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-/jhoOj/Fx+A+IIyDNOvO3TItGmlMKhtX8ISAHKE90c4b/k1tqaqEZ+uUqfpU8DMnW5cgNJv606zS55jGvza0Xw==}
+
resolution: {integrity: sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==}
engines: {node: '>=18'}
@@ -2084,6 +2175,9 @@ packages:
resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==}
engines: {node: '>= 0.6'}
+ resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==}
+
resolution: {integrity: sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==}
engines: {node: '>=18.0.0'}
@@ -2321,6 +2415,12 @@ packages:
resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}
engines: {node: '>= 4'}
+ resolution: {integrity: sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==}
+
+ resolution: {integrity: sha512-XREFCPo6ksxVzP4E0ekD5aMdf8WMwmdNaz6vuvxgI40UaEiu6q3p8X52aU6GdyvLY3XXX/8R7JOTXStz/nBbRw==}
+
resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==}
engines: {node: '>=6'}
@@ -2328,6 +2428,10 @@ packages:
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
+ resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==}
engines: {node: '>= 12'}
@@ -3114,6 +3218,21 @@ packages:
peerDependencies:
react: ^16.8.0 || ^17 || ^18 || ^19
+ resolution: {integrity: sha512-Dn0t8IQhCmeIT3wu+Apm1/YVsJXsGWi6k4sPdnBIdqMVtHtv0IGi6dcpNpNkNac0zB2uUAqNX3MHzN8c+z2rwQ==}
+
+ resolution: {integrity: sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==}
+ peerDependencies:
+ '@types/react': ^18.2.25 || ^19
+ react: ^18.0 || ^19
+ redux: ^5.0.0
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ redux:
+ optional: true
+
resolution: {integrity: sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==}
engines: {node: '>=0.10.0'}
@@ -3138,6 +3257,22 @@ packages:
resolution: {integrity: sha512-YTUo+Flmw4ZXiWfQKGcwwc11KnoRAYgzAE2E7mXKCjSviTKShtxBsN6YUUBB2gtaBzKzeKunxhUwNHQuRryhWA==}
engines: {node: '>= 4'}
+ resolution: {integrity: sha512-mwzmO1s9sFL0TduUpwndxCUNoXsBw3u3E/0+A+cLcrSfQitSG62L32N69GhqUrrT5qKcAE3pCGVINC6pqkBBQg==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ react-dom: ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ react-is: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+
+ resolution: {integrity: sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==}
+ peerDependencies:
+ redux: ^5.0.0
+
+ resolution: {integrity: sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==}
+
resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}
engines: {node: '>=0.10.0'}
@@ -3564,6 +3699,9 @@ packages:
resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}
engines: {node: '>= 0.8'}
+ resolution: {integrity: sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==}
+
resolution: {integrity: sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -4576,6 +4714,18 @@ snapshots:
'@oxc-project/[email protected]': {}
+ dependencies:
+ '@standard-schema/spec': 1.1.0
+ '@standard-schema/utils': 0.3.0
+ immer: 11.1.4
+ redux: 5.0.1
+ redux-thunk: 3.1.0([email protected])
+ reselect: 5.1.1
+ optionalDependencies:
+ react: 19.2.4
+
'@remirror/[email protected]': {}
'@rolldown/[email protected]':
@@ -5107,6 +5257,30 @@ snapshots:
'@types/deep-eql': 4.0.2
assertion-error: 2.0.1
+ '@types/[email protected]': {}
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-color': 3.1.3
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-time': 3.0.4
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-path': 3.1.1
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -5522,6 +5696,44 @@ snapshots:
+ dependencies:
+ internmap: 2.0.3
+
+
+
+
+ dependencies:
+ d3-color: 3.1.0
+
+
+ dependencies:
+ d3-array: 3.2.4
+ d3-format: 3.1.2
+ d3-interpolate: 3.0.1
+ d3-time: 3.1.0
+ d3-time-format: 4.1.0
+
+ dependencies:
+ d3-path: 3.1.0
+
+ dependencies:
+ d3-time: 3.1.0
+
+ dependencies:
+ d3-array: 3.2.4
+
+
@@ -5534,6 +5746,8 @@ snapshots:
dependencies:
ms: 2.1.3
+
@@ -5616,6 +5830,8 @@ snapshots:
dependencies:
es-errors: 1.3.0
+
optionalDependencies:
'@esbuild/aix-ppc64': 0.27.7
@@ -5659,6 +5875,8 @@ snapshots:
+
@@ -5935,6 +6153,10 @@ snapshots:
+
+
dependencies:
parent-module: 1.0.1
@@ -5942,6 +6164,8 @@ snapshots:
+
@@ -6646,6 +6870,17 @@ snapshots:
dependencies:
react: 19.2.4
+
+ dependencies:
+ '@types/use-sync-external-store': 0.0.6
+ react: 19.2.4
+ use-sync-external-store: 1.6.0([email protected])
+ optionalDependencies:
+ '@types/react': 19.2.13
+ redux: 5.0.1
+
@@ -6671,6 +6906,32 @@ snapshots:
tiny-invariant: 1.3.3
tslib: 2.8.1
+ dependencies:
+ clsx: 2.1.1
+ decimal.js-light: 2.5.1
+ es-toolkit: 1.45.1
+ eventemitter3: 5.0.4
+ immer: 10.2.0
+ react: 19.2.4
+ react-dom: 19.2.4([email protected])
+ react-is: 19.2.5
+ reselect: 5.1.1
+ tiny-invariant: 1.3.3
+ use-sync-external-store: 1.6.0([email protected])
+ victory-vendor: 37.3.6
+ transitivePeerDependencies:
+ - '@types/react'
+ - redux
+
+ dependencies:
+ redux: 5.0.1
+
+
@@ -7144,6 +7405,23 @@ snapshots:
+ dependencies:
+ '@types/d3-array': 3.2.2
+ '@types/d3-ease': 3.0.2
+ '@types/d3-interpolate': 3.0.4
+ '@types/d3-scale': 4.0.9
+ '@types/d3-shape': 3.1.8
+ '@types/d3-time': 3.0.4
+ '@types/d3-timer': 3.0.2
+ d3-array: 3.2.4
+ d3-ease: 3.0.1
+ d3-interpolate: 3.0.1
+ d3-scale: 4.0.2
+ d3-shape: 3.2.0
+ d3-time: 3.1.0
+ d3-timer: 3.0.1
+
dependencies:
esbuild: 0.27.7
diff --git a/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb
new file mode 100644
index 0000000000..438b65c604
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb
@@ -0,0 +1,38 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ class DashboardController < Admin::BaseController
+ # GET /api/v3/admin/dashboard/analytics
+ def analytics
+ date_from = (params[:date_from] || 30.days.ago).to_time.beginning_of_day
+ date_to = (params[:date_to] || Time.current).to_time.end_of_day
+ currency = params[:currency] || current_store.default_currency
+
+ serializer = DashboardAnalyticsSerializer.new(
+ store: current_store,
+ currency: currency,
+ time_range: date_from..date_to,
+ params: serializer_params
+ )
+
+ render json: serializer.to_h
+ end
+
+ private
+
+ def serializer_params
+ {
+ store: current_store,
+ locale: current_locale,
+ currency: current_currency,
+ user: current_user,
+ includes: [],
+ expand: []
+ }
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/dashboard_analytics_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/dashboard_analytics_serializer.rb
new file mode 100644
index 0000000000..cc2fa205e2
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/dashboard_analytics_serializer.rb
@@ -0,0 +1,143 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ class DashboardAnalyticsSerializer
+ attr_reader :store, :currency, :time_range, :params
+
+ def initialize(store:, currency:, time_range:, params: {})
+ @store = store
+ @currency = currency
+ @time_range = time_range
+ @params = params
+ end
+
+ def to_h
+ {
+ currency: currency,
+ date_from: time_range.first.iso8601,
+ date_to: time_range.last.iso8601,
+ summary: summary,
+ chart_data: chart_data,
+ top_products: top_products
+ }
+ end
+
+ private
+
+ def orders
+ @orders ||= store.orders.complete.where(currency: currency, completed_at: time_range)
+ end
+
+ def prev_orders
+ @prev_orders ||= store.orders.complete.where(currency: currency, completed_at: previous_time_range)
+ end
+
+ def previous_time_range
+ duration = time_range.last - time_range.first
+ (time_range.first - duration)..(time_range.last - duration)
+ end
+
+ # ---- Summary ----
+
+ def summary
+ sales = sales_total
+ count = orders_count
+ avg = count > 0 ? (sales / count).round(2) : 0.0
+
+ prev_sales = prev_orders.sum(:total).to_f
+ prev_count = prev_orders.count
+ prev_avg = prev_count > 0 ? (prev_sales / prev_count).round(2) : 0.0
+
+ {
+ sales_total: sales.round(2),
+ display_sales_total: money(sales),
+ sales_growth: growth_rate(sales, prev_sales),
+ orders_count: count,
+ orders_growth: growth_rate(count, prev_count),
+ avg_order_value: avg,
+ display_avg_order_value: money(avg),
+ avg_order_value_growth: growth_rate(avg, prev_avg)
+ }
+ end
+
+ def sales_total
+ @sales_total ||= orders.sum(:total).to_f
+ end
+
+ def orders_count
+ @orders_count ||= orders.count
+ end
+
+ # ---- Chart data ----
+
+ def chart_data
+ daily = orders
+ .select("DATE(completed_at) AS day, SUM(total) AS day_total, COUNT(*) AS day_count")
+ .group("DATE(completed_at)")
+ .order("day")
+ .index_by { |r| r.day.to_s }
+
+ (time_range.first.to_date..time_range.last.to_date).map do |date|
+ key = date.to_s
+ row = daily[key]
+ total = row&.day_total.to_f
+ count = row&.day_count.to_i || 0
+ {
+ date: key,
+ sales: total.round(2),
+ orders: count,
+ avg_order_value: count > 0 ? (total / count).round(2) : 0.0
+ }
+ end
+ end
+
+ # ---- Top products ----
+
+ def top_products
+ rows = Spree::LineItem
+ .joins(:variant)
+ .where(order: orders)
+ .group('spree_variants.product_id')
+ .order(Arel.sql('SUM(spree_line_items.quantity * spree_line_items.price) DESC'))
+ .limit(5)
+ .pluck(Arel.sql('spree_variants.product_id, SUM(spree_line_items.quantity), SUM(spree_line_items.quantity * spree_line_items.price)'))
+
+ product_ids = rows.map(&:first).compact
+ return [] if product_ids.empty?
+
+ products = store.products.with_deleted.includes(:primary_media).where(id: product_ids)
+ product_serializer = Spree.api.admin_product_serializer
+
+ rows.filter_map do |product_id, quantity, amount|
+ product = products.find { |p| p.id == product_id }
+ next unless product
+
+ serialized = product_serializer.new(product, params: params).to_h
+ {
+ id: serialized['id'],
+ name: serialized['name'],
+ slug: serialized['slug'],
+ image_url: serialized['thumbnail_url'],
+ price: serialized.dig('price', 'display_amount'),
+ quantity: quantity.to_i,
+ total: money(amount)
+ }
+ end
+ end
+
+ # ---- Helpers ----
+
+ def money(amount)
+ Spree::Money.new(amount, currency: currency).to_s
+ end
+
+ def growth_rate(current, previous)
+ return 0.0 if previous.zero?
+ (((current - previous) / previous.to_f) * 100).round(1)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index ce24f75011..07e514241e 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -95,6 +95,11 @@ Spree::Core::Engine.add_routes do
post 'auth/login', to: 'auth#create'
post 'auth/refresh', to: 'auth#refresh'
+ # Dashboard
+ namespace :dashboard do
+ get :analytics
+ end
+
# Current admin user + permissions (for UI permission checks)
get 'me', to: 'me#show'
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/dashboard_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/dashboard_controller_spec.rb
new file mode 100644
index 0000000000..0c083b0aa1
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/dashboard_controller_spec.rb
@@ -0,0 +1,120 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::DashboardController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #analytics' do
+ subject { get :analytics, as: :json }
+
+ it 'returns ok' do
+ subject
+ expect(response).to have_http_status(:ok)
+ end
+
+ it 'returns summary stats' do
+ subject
+ expect(json_response['summary']).to include(
+ 'sales_total', 'display_sales_total', 'sales_growth',
+ 'orders_count', 'orders_growth',
+ 'avg_order_value', 'display_avg_order_value', 'avg_order_value_growth'
+ )
+ end
+
+ it 'returns chart_data as an array' do
+ subject
+ expect(json_response['chart_data']).to be_an(Array)
+ expect(json_response['chart_data'].length).to eq(31) # default 30 days + today
+ end
+
+ it 'returns chart_data entries with date, sales, orders, avg_order_value' do
+ subject
+ entry = json_response['chart_data'].first
+ expect(entry.keys).to match_array(%w[date sales orders avg_order_value])
+ end
+
+ it 'returns top_products as an array' do
+ subject
+ expect(json_response['top_products']).to be_an(Array)
+ end
+
+ it 'returns currency and date range' do
+ subject
+ expect(json_response['currency']).to eq(store.default_currency)
+ expect(json_response['date_from']).to be_present
+ expect(json_response['date_to']).to be_present
+ end
+
+ context 'with completed orders' do
+ let!(:order1) { create(:completed_order_with_totals, store: store, completed_at: 5.days.ago) }
+ let!(:order2) { create(:completed_order_with_totals, store: store, completed_at: 2.days.ago) }
+
+ it 'calculates sales total from completed orders' do
+ subject
+ expected_total = (order1.total + order2.total).to_f.round(2)
+ expect(json_response['summary']['sales_total']).to eq(expected_total)
+ end
+
+ it 'counts orders' do
+ subject
+ expect(json_response['summary']['orders_count']).to eq(2)
+ end
+
+ it 'calculates average order value' do
+ subject
+ expected_avg = ((order1.total + order2.total) / 2.0).round(2)
+ expect(json_response['summary']['avg_order_value']).to eq(expected_avg)
+ end
+
+ it 'includes orders in chart_data on their completed dates' do
+ subject
+ chart = json_response['chart_data']
+ day_with_order = chart.find { |d| d['date'] == 5.days.ago.to_date.to_s }
+ expect(day_with_order['orders']).to be >= 1
+ expect(day_with_order['sales']).to be > 0
+ end
+
+ it 'returns top products from line items' do
+ subject
+ expect(json_response['top_products'].length).to be >= 1
+
+ top = json_response['top_products'].first
+ expect(top).to include('id', 'name', 'slug', 'quantity', 'total')
+ expect(top['id']).to start_with('prod_')
+ expect(top['quantity']).to be > 0
+ end
+ end
+
+ context 'with custom date range' do
+ it 'accepts date_from and date_to params' do
+ get :analytics, params: { date_from: 7.days.ago.to_s, date_to: Time.current.to_s }, as: :json
+ expect(response).to have_http_status(:ok)
+ expect(json_response['chart_data'].length).to be_between(7, 8)
+ end
+ end
+
+ context 'with growth rate calculation' do
+ let!(:recent_order) { create(:completed_order_with_totals, store: store, completed_at: 5.days.ago) }
+ let!(:older_order) { create(:completed_order_with_totals, store: store, completed_at: 35.days.ago) }
+
+ it 'calculates growth rates compared to previous period' do
+ subject
+ # Recent period has orders, previous period also has orders
+ expect(json_response['summary']['sales_growth']).to be_a(Numeric)
+ expect(json_response['summary']['orders_growth']).to be_a(Numeric)
+ end
+ end
+
+ context 'without authentication' do
+ let(:headers) { {} }
+
+ it 'returns unauthorized' do
+ subject
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+ end
+end
diff --git a/spree/api/spec/serializers/spree/api/v3/admin/dashboard_analytics_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/dashboard_analytics_serializer_spec.rb
new file mode 100644
index 0000000000..b7612296f6
--- /dev/null
+++ b/spree/api/spec/serializers/spree/api/v3/admin/dashboard_analytics_serializer_spec.rb
@@ -0,0 +1,129 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::DashboardAnalyticsSerializer do
+ let(:store) { @default_store }
+ let(:currency) { store.default_currency }
+ let(:time_range) { 30.days.ago.beginning_of_day..Time.current.end_of_day }
+ let(:params) do
+ {
+ store: store,
+ locale: 'en',
+ currency: currency,
+ user: nil,
+ includes: [],
+ expand: []
+ }
+ end
+
+ subject { described_class.new(store: store, currency: currency, time_range: time_range, params: params) }
+
+ describe '#to_h' do
+ let(:result) { subject.to_h }
+
+ it 'returns currency and date range' do
+ expect(result[:currency]).to eq(currency)
+ expect(result[:date_from]).to be_present
+ expect(result[:date_to]).to be_present
+ end
+
+ it 'returns summary with all expected keys' do
+ expect(result[:summary]).to include(
+ :sales_total, :display_sales_total, :sales_growth,
+ :orders_count, :orders_growth,
+ :avg_order_value, :display_avg_order_value, :avg_order_value_growth
+ )
+ end
+
+ it 'returns chart_data covering the full date range' do
+ expected_days = (time_range.first.to_date..time_range.last.to_date).count
+ expect(result[:chart_data].length).to eq(expected_days)
+ end
+
+ it 'returns chart_data entries with correct keys' do
+ entry = result[:chart_data].first
+ expect(entry.keys).to match_array(%i[date sales orders avg_order_value])
+ end
+
+ it 'returns top_products as an array' do
+ expect(result[:top_products]).to be_an(Array)
+ end
+
+ context 'with no orders' do
+ it 'returns zero summary values' do
+ expect(result[:summary][:sales_total]).to eq(0.0)
+ expect(result[:summary][:orders_count]).to eq(0)
+ expect(result[:summary][:avg_order_value]).to eq(0.0)
+ expect(result[:summary][:sales_growth]).to eq(0.0)
+ end
+
+ it 'returns empty top_products' do
+ expect(result[:top_products]).to eq([])
+ end
+
+ it 'returns zero values in chart_data' do
+ result[:chart_data].each do |entry|
+ expect(entry[:sales]).to eq(0.0)
+ expect(entry[:orders]).to eq(0)
+ expect(entry[:avg_order_value]).to eq(0.0)
+ end
+ end
+ end
+
+ context 'with completed orders' do
+ let!(:order1) { create(:completed_order_with_totals, store: store, completed_at: 5.days.ago) }
+ let!(:order2) { create(:completed_order_with_totals, store: store, completed_at: 2.days.ago) }
+
+ it 'calculates sales total' do
+ expected = (order1.total + order2.total).to_f.round(2)
+ expect(result[:summary][:sales_total]).to eq(expected)
+ end
+
+ it 'counts orders' do
+ expect(result[:summary][:orders_count]).to eq(2)
+ end
+
+ it 'calculates avg order value' do
+ expected = ((order1.total + order2.total) / 2.0).round(2)
+ expect(result[:summary][:avg_order_value]).to eq(expected)
+ end
+
+ it 'formats display values as money strings' do
+ expect(result[:summary][:display_sales_total]).to include('$')
+ expect(result[:summary][:display_avg_order_value]).to include('$')
+ end
+
+ it 'populates chart_data on order dates' do
+ day = result[:chart_data].find { |d| d[:date] == 5.days.ago.to_date.to_s }
+ expect(day[:orders]).to be >= 1
+ expect(day[:sales]).to be > 0
+ end
+
+ it 'returns top products with serialized fields' do
+ expect(result[:top_products].length).to be >= 1
+ top = result[:top_products].first
+ expect(top[:id]).to start_with('prod_').or be_present
+ expect(top[:name]).to be_present
+ expect(top[:quantity]).to be > 0
+ expect(top[:total]).to include('$')
+ end
+ end
+
+ context 'with growth rate calculation' do
+ let!(:recent_order) { create(:completed_order_with_totals, store: store, completed_at: 5.days.ago) }
+ let!(:older_order) { create(:completed_order_with_totals, store: store, completed_at: 35.days.ago) }
+
+ it 'calculates non-zero growth rates when both periods have data' do
+ expect(result[:summary][:sales_growth]).to be_a(Numeric)
+ expect(result[:summary][:orders_growth]).to be_a(Numeric)
+ end
+ end
+
+ context 'with custom 7-day range' do
+ let(:time_range) { 7.days.ago.beginning_of_day..Time.current.end_of_day }
+
+ it 'returns chart_data for 7-8 days' do
+ expect(result[:chart_data].length).to be_between(7, 8)
+ end
+ end
+ end
+end