medusa-analytics 0.0.24 → 0.0.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/.medusa/server/src/admin/index.js +499 -4076
  2. package/.medusa/server/src/admin/index.mjs +504 -4081
  3. package/.medusa/server/src/api/admin/analytics/customers-over-time/route.js +7 -14
  4. package/.medusa/server/src/api/admin/analytics/customers-summary/route.js +7 -14
  5. package/.medusa/server/src/api/admin/analytics/orders-over-time/route.js +100 -193
  6. package/.medusa/server/src/api/admin/analytics/orders-over-time/types.js +1 -1
  7. package/.medusa/server/src/api/admin/analytics/orders-summary/route.js +38 -10
  8. package/README.md +255 -131
  9. package/package.json +2 -4
  10. package/.medusa/server/src/api/admin/analytics/fetch-orders-for-analytics.js +0 -129
  11. package/.medusa/server/src/api/admin/analytics/orders-analytics-helpers.js +0 -64
  12. package/.medusa/server/src/api/admin/analytics/orders-analytics-meta.js +0 -18
  13. package/.medusa/server/src/api/admin/analytics/orders-insights/route.js +0 -262
  14. package/.medusa/server/src/api/admin/analytics/orders-insights/types.js +0 -3
  15. package/.medusa/server/src/api/admin/analytics/products/shared.js +0 -719
  16. package/.medusa/server/src/api/admin/analytics/products-filters/route.js +0 -21
  17. package/.medusa/server/src/api/admin/analytics/products-filters/types.js +0 -3
  18. package/.medusa/server/src/api/admin/analytics/products-over-time/route.js +0 -28
  19. package/.medusa/server/src/api/admin/analytics/products-over-time/types.js +0 -3
  20. package/.medusa/server/src/api/admin/analytics/products-performance/route.js +0 -51
  21. package/.medusa/server/src/api/admin/analytics/products-performance/types.js +0 -3
  22. package/.medusa/server/src/api/admin/analytics/products-summary/route.js +0 -36
  23. package/.medusa/server/src/api/admin/analytics/products-summary/types.js +0 -3
  24. package/.medusa/server/src/api/admin/analytics/products-top-sellers/route.js +0 -48
  25. package/.medusa/server/src/api/admin/analytics/products-top-sellers/types.js +0 -3
  26. package/.medusa/server/src/api/admin/analytics/repeat-customers/route.js +0 -78
  27. package/.medusa/server/src/api/admin/analytics/repeat-customers/types.js +0 -3
  28. package/.medusa/server/src/api/admin/analytics/store-context/resolve-default-currency-code.js +0 -86
  29. package/.medusa/server/src/api/admin/analytics/store-context/route.js +0 -19
  30. package/.medusa/server/src/api/admin/analytics/store-context/types.js +0 -3
  31. package/index.js +0 -5
@@ -1,729 +1,61 @@
1
- import { jsx, jsxs, Fragment } from "react/jsx-runtime";
2
- import { createContext, useState, useEffect, useCallback, useMemo, useContext, useId } from "react";
1
+ import { jsx, jsxs } from "react/jsx-runtime";
2
+ import { useState, useEffect } from "react";
3
3
  import { defineRouteConfig } from "@medusajs/admin-sdk";
4
- import { CurrencyDollar, ShoppingCart, TruckFast, Cash, UsersSolid, User, UserGroup, Trash, Tag, CubeSolid, ChartBar } from "@medusajs/icons";
5
- import { Container, Text, Heading, Label, Table } from "@medusajs/ui";
6
- import { ResponsiveContainer, BarChart, CartesianGrid, XAxis, YAxis, Tooltip, Bar, PieChart, Pie, Cell, ComposedChart, Legend, Area, LineChart, Line, ReferenceLine, Sector, ScatterChart, Scatter } from "recharts";
7
- const AnalyticsCurrencyContext = createContext(
8
- null
9
- );
10
- function formatMoney(value, currencyCode, compact) {
11
- return new Intl.NumberFormat(void 0, {
12
- style: "currency",
13
- currency: currencyCode,
14
- minimumFractionDigits: 0,
15
- maximumFractionDigits: compact ? 1 : 0,
16
- ...compact ? { notation: "compact" } : {}
17
- }).format(value);
18
- }
19
- function AnalyticsCurrencyProvider({ children }) {
20
- const [currencyCode, setCurrencyCode] = useState("USD");
21
- useEffect(() => {
22
- let cancelled = false;
23
- fetch("/admin/analytics/store-context", { credentials: "include" }).then((res) => {
24
- if (!res.ok) throw new Error(res.statusText);
25
- return res.json();
26
- }).then((body) => {
27
- if (cancelled) return;
28
- const code = typeof body.default_currency_code === "string" ? body.default_currency_code.trim().toUpperCase() : "";
29
- if (code && /^[A-Z]{3}$/.test(code)) {
30
- setCurrencyCode(code);
31
- }
32
- }).catch(() => {
33
- if (!cancelled) setCurrencyCode("USD");
34
- });
35
- return () => {
36
- cancelled = true;
37
- };
38
- }, []);
39
- const formatCurrency = useCallback(
40
- (value2) => formatMoney(value2, currencyCode, false),
41
- [currencyCode]
42
- );
43
- const formatCompactCurrency = useCallback(
44
- (value2) => formatMoney(value2, currencyCode, true),
45
- [currencyCode]
46
- );
47
- const value = useMemo(
48
- () => ({
49
- currencyCode,
50
- formatCurrency,
51
- formatCompactCurrency
52
- }),
53
- [currencyCode, formatCurrency, formatCompactCurrency]
54
- );
55
- return /* @__PURE__ */ jsx(AnalyticsCurrencyContext.Provider, { value, children });
56
- }
57
- function useAnalyticsCurrency() {
58
- const ctx = useContext(AnalyticsCurrencyContext);
59
- if (!ctx) {
60
- throw new Error("useAnalyticsCurrency must be used within AnalyticsCurrencyProvider");
61
- }
62
- return ctx;
63
- }
64
- const ORDERS_ANALYTICS_MAX_FETCH = 5e4;
65
- const ACCENT_STYLES = {
66
- blue: {
67
- border: "border-sky-400/30",
68
- glow: "shadow-[0_0_0_1px_rgba(56,189,248,0.12),0_18px_40px_-28px_rgba(59,130,246,0.55)]",
69
- band: "from-sky-400/70 via-blue-400/30 to-transparent"
70
- },
71
- purple: {
72
- border: "border-fuchsia-400/25",
73
- glow: "shadow-[0_0_0_1px_rgba(217,70,239,0.10),0_18px_40px_-28px_rgba(168,85,247,0.5)]",
74
- band: "from-fuchsia-400/65 via-violet-400/25 to-transparent"
75
- },
76
- green: {
77
- border: "border-emerald-400/25",
78
- glow: "shadow-[0_0_0_1px_rgba(52,211,153,0.10),0_18px_40px_-28px_rgba(16,185,129,0.45)]",
79
- band: "from-emerald-400/65 via-teal-400/25 to-transparent"
80
- },
81
- amber: {
82
- border: "border-amber-400/25",
83
- glow: "shadow-[0_0_0_1px_rgba(251,191,36,0.10),0_18px_40px_-28px_rgba(245,158,11,0.45)]",
84
- band: "from-amber-400/65 via-orange-400/25 to-transparent"
85
- },
86
- rose: {
87
- border: "border-rose-400/25",
88
- glow: "shadow-[0_0_0_1px_rgba(251,113,133,0.10),0_18px_40px_-28px_rgba(244,63,94,0.45)]",
89
- band: "from-rose-400/65 via-pink-400/25 to-transparent"
90
- },
91
- slate: {
92
- border: "border-ui-border-strong",
93
- glow: "shadow-[0_0_0_1px_rgba(15,23,42,0.05),0_18px_40px_-28px_rgba(15,23,42,0.22)]",
94
- band: "from-ui-border-strong via-ui-border-base to-transparent"
95
- }
96
- };
97
- function getAccentStyle(accent) {
98
- return ACCENT_STYLES[accent];
99
- }
100
- function AnalyticsDashboardShell({ children, className }) {
101
- return /* @__PURE__ */ jsx("div", { className: ["space-y-2.5 md:space-y-3", className].filter(Boolean).join(" "), children });
102
- }
103
- function AnalyticsDashboardHeader({
104
- title,
105
- description,
106
- actions,
107
- variant = "default",
108
- actionsBare = false,
109
- appearance = "card",
110
- actionsClassName
111
- }) {
112
- const isPremium = variant === "premium";
113
- const isInset = appearance === "inset";
114
- const headerRow = /* @__PURE__ */ jsxs(
115
- "div",
116
- {
117
- className: `flex flex-col gap-2 px-4 py-2.5 lg:flex-row lg:items-center lg:justify-between lg:gap-4 ${isPremium ? "border-b border-ui-border-base/80" : "border-b border-ui-border-base"}`.trim(),
118
- children: [
119
- /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1 space-y-0.5", children: [
120
- /* @__PURE__ */ jsx(Heading, { level: "h2", className: isPremium ? "text-lg font-semibold tracking-tight" : "tracking-tight", children: title }),
121
- description ? /* @__PURE__ */ jsx(Text, { className: `text-ui-fg-muted ${isPremium ? "max-w-2xl text-xs leading-snug" : "text-sm"}`.trim(), children: description }) : null
122
- ] }),
123
- actions ? actionsBare ? /* @__PURE__ */ jsx(
124
- "div",
125
- {
126
- className: [
127
- "flex flex-wrap items-center gap-3 self-start lg:shrink-0 lg:self-auto",
128
- actionsClassName ?? ""
129
- ].join(" ").trim(),
130
- children: actions
131
- }
132
- ) : /* @__PURE__ */ jsx(
133
- "div",
134
- {
135
- className: `flex self-start rounded-xl border px-2 py-1.5 lg:self-auto ${isPremium ? "border-ui-border-strong bg-ui-bg-subtle shadow-[inset_0_1px_0_rgba(255,255,255,0.35)]" : "border-ui-border-base bg-ui-bg-subtle"}`.trim(),
136
- children: actions
137
- }
138
- ) : null
139
- ]
140
- }
141
- );
142
- if (isInset) {
143
- return /* @__PURE__ */ jsx("div", { className: "border-0 bg-transparent p-0 shadow-none", children: headerRow });
144
- }
145
- return /* @__PURE__ */ jsxs(
146
- Container,
147
- {
148
- className: `overflow-hidden rounded-2xl border bg-ui-bg-base p-0 ${isPremium ? "border-ui-border-strong shadow-sm" : "border-ui-border-base shadow-sm"}`.trim(),
149
- children: [
150
- headerRow,
151
- /* @__PURE__ */ jsx(
152
- "div",
153
- {
154
- className: `h-px w-full ${isPremium ? "bg-gradient-to-r from-transparent via-ui-border-strong to-transparent" : "bg-ui-bg-subtle"}`.trim()
155
- }
156
- )
157
- ]
158
- }
159
- );
160
- }
161
- function AnalyticsStatCard({
162
- label,
163
- value,
164
- helper,
165
- className,
166
- valueClassName,
167
- variant = "default",
168
- accent = "slate"
169
- }) {
170
- const accentStyle = getAccentStyle(accent);
171
- const isHero = variant === "hero";
172
- const isCompact = variant === "compact";
173
- return /* @__PURE__ */ jsxs(
174
- Container,
175
- {
176
- className: `relative h-full overflow-hidden rounded-2xl border bg-ui-bg-base transition-shadow ${isHero ? `p-3 ${accentStyle.border} ${accentStyle.glow} shadow-sm` : isCompact ? "border-ui-border-base bg-ui-bg-subtle/70 p-2.5 shadow-none" : "border-ui-border-base p-4 shadow-sm"} ${className ?? ""}`.trim(),
177
- children: [
178
- isHero ? /* @__PURE__ */ jsxs(Fragment, { children: [
179
- /* @__PURE__ */ jsx(
180
- "div",
181
- {
182
- className: `pointer-events-none absolute inset-x-3 top-0 h-10 rounded-b-full bg-gradient-to-r ${accentStyle.band} blur-xl`
183
- }
184
- ),
185
- /* @__PURE__ */ jsx("div", { className: "pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r from-transparent via-white/40 to-transparent" })
186
- ] }) : null,
187
- /* @__PURE__ */ jsxs(
188
- "div",
189
- {
190
- className: `relative flex flex-col justify-between gap-1 ${isCompact ? "min-h-[64px]" : isHero ? "min-h-[72px]" : "min-h-[92px]"}`.trim(),
191
- children: [
192
- /* @__PURE__ */ jsx(
193
- Text,
194
- {
195
- className: `text-ui-fg-muted font-medium ${isHero ? "text-[10px] uppercase tracking-[0.16em]" : "text-xs"}`.trim(),
196
- children: label
197
- }
198
- ),
199
- /* @__PURE__ */ jsx(
200
- Heading,
201
- {
202
- level: "h2",
203
- className: `leading-tight tracking-tight ${isHero ? "text-xl sm:text-2xl" : isCompact ? "text-lg" : "text-2xl"} ${valueClassName ?? ""}`.trim(),
204
- children: value
205
- }
206
- ),
207
- helper ? /* @__PURE__ */ jsx(Text, { className: `text-ui-fg-muted leading-snug ${isHero ? "text-[10px]" : "text-xs"}`.trim(), children: helper }) : null
208
- ]
209
- }
210
- )
211
- ]
212
- }
213
- );
214
- }
215
- function AnalyticsSection({
216
- title,
217
- description,
218
- actions,
219
- children,
220
- className,
221
- variant = "default",
222
- actionsBare = false
223
- }) {
224
- const isAtlas = variant === "atlas";
225
- const isPremium = variant !== "default" && !isAtlas;
226
- const shellClass = isAtlas ? "min-w-0 overflow-x-clip overflow-y-visible rounded-lg border border-ui-border-base bg-ui-bg-base shadow-sm" : `overflow-hidden rounded-2xl border bg-ui-bg-base p-0 ${isPremium ? "border-ui-border-strong shadow-sm" : "border-ui-border-base shadow-sm"}`.trim();
227
- const headerClass = isAtlas ? "flex flex-col gap-1 border-b border-ui-border-base bg-ui-bg-subtle/40 px-3 py-2 lg:flex-row lg:items-center lg:justify-between" : `flex flex-col gap-2 px-4 py-2.5 lg:flex-row lg:items-center lg:justify-between ${isPremium ? "border-b border-ui-border-base/80" : "border-b border-ui-border-base"}`.trim();
228
- const titleClass = isAtlas ? "text-sm font-semibold tracking-tight text-ui-fg-base" : isPremium ? "text-base font-semibold tracking-tight" : "tracking-tight";
229
- const descClass = isAtlas ? "max-w-2xl text-[11px] leading-snug text-ui-fg-muted" : isPremium ? "max-w-2xl text-xs leading-snug" : "text-sm";
230
- const actionsShellClass = isAtlas ? "flex shrink-0 flex-wrap items-center gap-1.5 rounded-md border border-ui-border-base bg-ui-bg-base px-2 py-1" : `flex shrink-0 flex-wrap items-center gap-1.5 rounded-xl border px-2 py-1.5 ${isPremium ? "border-ui-border-strong bg-ui-bg-subtle shadow-[inset_0_1px_0_rgba(255,255,255,0.32)]" : "border-ui-border-base bg-ui-bg-subtle"}`.trim();
231
- const bodyClass = isAtlas ? "p-2" : variant === "hero" ? "px-4 py-3" : "px-4 py-3";
232
- return /* @__PURE__ */ jsxs(Container, { className: `${shellClass} ${className ?? ""}`.trim(), children: [
233
- /* @__PURE__ */ jsxs("div", { className: headerClass, children: [
234
- /* @__PURE__ */ jsxs("div", { className: "min-w-0 space-y-0.5", children: [
235
- /* @__PURE__ */ jsx(Heading, { level: "h3", className: titleClass, children: title }),
236
- description ? /* @__PURE__ */ jsx(Text, { className: `text-ui-fg-muted ${descClass}`.trim(), children: description }) : null
237
- ] }),
238
- actions ? actionsBare ? /* @__PURE__ */ jsx("div", { className: "flex shrink-0 flex-wrap items-center gap-2", children: actions }) : /* @__PURE__ */ jsx("div", { className: actionsShellClass, children: actions }) : null
239
- ] }),
240
- /* @__PURE__ */ jsx("div", { className: bodyClass, children })
241
- ] });
242
- }
243
- function AnalyticsChartSurface({
244
- children,
245
- className,
246
- variant = "default"
247
- }) {
248
- const surfaceClassName = variant === "atlas" ? "rounded-lg border border-ui-border-base bg-ui-bg-subtle/50 p-2 shadow-sm" : variant === "glass" ? "rounded-xl border border-ui-border-strong bg-[linear-gradient(180deg,rgba(255,255,255,0.12),rgba(255,255,255,0.03))] p-2.5 shadow-[inset_0_1px_0_rgba(255,255,255,0.22)]" : variant === "panel" ? "rounded-xl border border-ui-border-base/90 bg-ui-bg-base p-2.5 shadow-[inset_0_1px_0_rgba(255,255,255,0.18)]" : "rounded-lg border border-ui-border-base bg-ui-bg-subtle p-2 shadow-inner";
249
- return /* @__PURE__ */ jsx(
250
- "div",
251
- {
252
- className: `${surfaceClassName} ${className ?? ""}`.trim(),
253
- children
254
- }
255
- );
256
- }
257
- function AnalyticsTableSurface({ children, className }) {
258
- return /* @__PURE__ */ jsx(
259
- "div",
260
- {
261
- className: [
262
- "min-w-0 overflow-x-auto overflow-y-visible rounded-xl border border-ui-border-base bg-ui-bg-base",
263
- "[scrollbar-width:thin]",
264
- className ?? ""
265
- ].join(" ").trim(),
266
- children
267
- }
268
- );
269
- }
270
- function AnalyticsTooltipCard({
271
- title,
272
- children,
273
- variant = "default"
4
+ import { ChartBar } from "@medusajs/icons";
5
+ import { Text, Container, Heading, Label, Button } from "@medusajs/ui";
6
+ import { ResponsiveContainer, PieChart, Pie, Cell, Tooltip, Legend, LineChart, CartesianGrid, XAxis, YAxis, Line } from "recharts";
7
+ function OrdersOverTimeTooltip({
8
+ active,
9
+ payload,
10
+ label
274
11
  }) {
275
- const compact = variant === "compact";
12
+ var _a, _b;
13
+ if (!active || !(payload == null ? void 0 : payload.length)) return null;
14
+ const row = (_a = payload[0]) == null ? void 0 : _a.payload;
15
+ const displayLabel = (row == null ? void 0 : row.label) ?? (label ? new Date(label).toLocaleDateString() : label);
16
+ const value = ((_b = payload[0]) == null ? void 0 : _b.value) ?? 0;
276
17
  return /* @__PURE__ */ jsxs(
277
18
  "div",
278
19
  {
279
20
  style: {
280
- background: "linear-gradient(180deg, rgba(255,255,255,0.98) 0%, rgba(248,250,252,0.96) 100%)",
21
+ backgroundColor: "rgb(250, 234, 234)",
281
22
  color: "#111827",
282
- border: "1px solid rgba(148, 163, 184, 0.18)",
283
- borderRadius: compact ? "8px" : "14px",
284
- padding: compact ? "5px 8px" : "12px 14px",
285
- boxShadow: compact ? "0 6px 16px rgba(15, 23, 42, 0.1)" : "0 16px 40px rgba(15, 23, 42, 0.12)",
286
- fontSize: compact ? "11px" : "13px",
287
- lineHeight: compact ? 1.35 : 1.5,
288
- minWidth: compact ? 0 : 176,
289
- maxWidth: compact ? "min(92vw, 200px)" : "min(96vw, 380px)"
23
+ border: "1px solid rgb(229, 231, 235)",
24
+ borderRadius: "8px",
25
+ padding: "12px 16px",
26
+ boxShadow: "0 4px 14px rgba(102, 102, 102, 0.99)",
27
+ fontSize: "14px",
28
+ lineHeight: 1.5
290
29
  },
291
30
  children: [
292
- /* @__PURE__ */ jsx(
293
- "div",
294
- {
295
- style: {
296
- fontWeight: 600,
297
- marginBottom: compact ? "2px" : "6px",
298
- fontSize: compact ? "10px" : "inherit",
299
- lineHeight: compact ? 1.25 : 1.35,
300
- wordBreak: "break-word"
301
- },
302
- children: title
303
- }
304
- ),
305
- children
31
+ /* @__PURE__ */ jsx("div", { style: { fontWeight: 600, marginBottom: "6px", color: "#111827" }, children: displayLabel }),
32
+ /* @__PURE__ */ jsxs("div", { style: { color: "#374151" }, children: [
33
+ "Orders: ",
34
+ /* @__PURE__ */ jsx("strong", { style: { color: "#1f2937" }, children: value })
35
+ ] })
306
36
  ]
307
37
  }
308
38
  );
309
39
  }
310
- function isDailyOrderRow(value) {
311
- if (typeof value !== "object" || value === null) return false;
312
- const v = value;
313
- return typeof v.date === "string" && typeof v.orders_count === "number" && typeof v.total_revenue === "number";
314
- }
315
- function nonCancelledRevenue(d) {
316
- const delivered = d.revenue_delivered ?? 0;
317
- const open = d.revenue_open ?? 0;
318
- if (delivered > 0 || open > 0 || (d.revenue_cancelled ?? 0) > 0) {
319
- return delivered + open;
320
- }
321
- return Math.max(0, d.total_revenue - (d.revenue_cancelled ?? 0));
322
- }
323
- function isOrdersTodayPoint(value) {
324
- return isDailyOrderRow(value) && "isToday" in value && typeof value.isToday === "boolean";
325
- }
326
- function formatChartLabel$2(value) {
327
- if (!value) return "";
328
- const parsed = new Date(value);
329
- if (Number.isNaN(parsed.getTime())) return value;
330
- return `${parsed.getUTCMonth() + 1}/${parsed.getUTCDate()}`;
331
- }
332
- function formatPercent(value) {
333
- return `${value.toFixed(1)}%`;
334
- }
335
- function formatShortNumber$1(value) {
40
+ const STATUS_COLORS = {
41
+ pending: "#F59E0B",
42
+ cancelled: "#EF4444",
43
+ delivered: "#10B981"
44
+ };
45
+ const ORDER_CHART_STATUSES = [
46
+ { key: "pending", label: "Pending", color: STATUS_COLORS.pending },
47
+ { key: "cancelled", label: "Cancelled", color: STATUS_COLORS.cancelled },
48
+ { key: "delivered", label: "Delivered", color: STATUS_COLORS.delivered }
49
+ ];
50
+ function formatCurrency(value) {
336
51
  return new Intl.NumberFormat("en-IN", {
337
- notation: "compact",
338
- maximumFractionDigits: value < 10 ? 1 : 0
52
+ style: "currency",
53
+ currency: "INR",
54
+ minimumFractionDigits: 0,
55
+ maximumFractionDigits: 0
339
56
  }).format(value);
340
57
  }
341
- const SALES_GRANULARITY_TABS = [
342
- { value: "hour", label: "Hour" },
343
- { value: "day", label: "Day" },
344
- { value: "week", label: "Week" },
345
- { value: "month", label: "Month" }
346
- ];
347
- function getSalesBreakdownOtPeriod(g) {
348
- if (g === "day") return "one_week";
349
- if (g === "week") return "two_months";
350
- if (g === "month") return "one_year";
351
- return null;
352
- }
353
- function monthKeyFromDateStr(dateStr) {
354
- if (dateStr.length >= 7) return dateStr.slice(0, 7);
355
- return dateStr;
356
- }
357
- function utcSundayWeekStartKeyFromDateStr(dateStr) {
358
- const parsed = new Date(dateStr);
359
- if (Number.isNaN(parsed.getTime())) return dateStr;
360
- const y = parsed.getUTCFullYear();
361
- const m = parsed.getUTCMonth();
362
- const day = parsed.getUTCDate();
363
- const dow = parsed.getUTCDay();
364
- const start = new Date(Date.UTC(y, m, day - dow));
365
- const ys = start.getUTCFullYear();
366
- const ms = String(start.getUTCMonth() + 1).padStart(2, "0");
367
- const ds = String(start.getUTCDate()).padStart(2, "0");
368
- return `${ys}-${ms}-${ds}`;
369
- }
370
- function formatWeekStartDm(weekStartKey) {
371
- const parsed = /* @__PURE__ */ new Date(`${weekStartKey}T00:00:00.000Z`);
372
- if (Number.isNaN(parsed.getTime())) return weekStartKey;
373
- return `${parsed.getUTCDate()}/${parsed.getUTCMonth() + 1}`;
374
- }
375
- function formatDayBreakdownDm(dateStr) {
376
- const parsed = new Date(dateStr);
377
- if (Number.isNaN(parsed.getTime())) return dateStr;
378
- return `${parsed.getUTCDate()}/${parsed.getUTCMonth() + 1}`;
379
- }
380
- function toDateKeyUtcFromDate(d) {
381
- const y = d.getUTCFullYear();
382
- const m = String(d.getUTCMonth() + 1).padStart(2, "0");
383
- const day = String(d.getUTCDate()).padStart(2, "0");
384
- return `${y}-${m}-${day}`;
385
- }
386
- function lastNWeekStartKeysUtc(n) {
387
- const now = /* @__PURE__ */ new Date();
388
- const todayUtc = new Date(
389
- Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
390
- );
391
- const dow = todayUtc.getUTCDay();
392
- const currentWeekStart = new Date(todayUtc);
393
- currentWeekStart.setUTCDate(currentWeekStart.getUTCDate() - dow);
394
- const keys = [];
395
- for (let i = n - 1; i >= 0; i -= 1) {
396
- const d = new Date(currentWeekStart);
397
- d.setUTCDate(d.getUTCDate() - 7 * i);
398
- keys.push(toDateKeyUtcFromDate(d));
399
- }
400
- return keys;
401
- }
402
- function formatMonthBucketLabel(ymKey) {
403
- const [ys, ms] = ymKey.split("-");
404
- const y = Number(ys);
405
- const m = Number(ms);
406
- if (!Number.isFinite(y) || !Number.isFinite(m)) return ymKey;
407
- return new Intl.DateTimeFormat("en-IN", {
408
- month: "short",
409
- timeZone: "UTC"
410
- }).format(new Date(Date.UTC(y, m - 1, 1)));
411
- }
412
- function isSalesBreakdownBarRow(value) {
413
- if (typeof value !== "object" || value === null) return false;
414
- const v = value;
415
- return typeof v.key === "string" && typeof v.label === "string" && typeof v.orders_count === "number" && typeof v.revenue === "number";
416
- }
417
- function SalesBreakdownTooltip({
418
- active,
419
- payload
420
- }) {
421
- var _a, _b;
422
- const { formatCurrency } = useAnalyticsCurrency();
423
- if (!active || !(payload == null ? void 0 : payload.length)) return null;
424
- const row = isSalesBreakdownBarRow((_a = payload[0]) == null ? void 0 : _a.payload) ? (_b = payload[0]) == null ? void 0 : _b.payload : void 0;
425
- if (!row) return null;
426
- return /* @__PURE__ */ jsxs(AnalyticsTooltipCard, { variant: "compact", title: row.label, children: [
427
- /* @__PURE__ */ jsxs("div", { children: [
428
- "Revenue: ",
429
- /* @__PURE__ */ jsx("strong", { children: formatCurrency(row.revenue) })
430
- ] }),
431
- /* @__PURE__ */ jsxs("div", { children: [
432
- "Orders:",
433
- " ",
434
- /* @__PURE__ */ jsx("strong", { children: Math.floor(row.orders_count).toLocaleString() })
435
- ] })
436
- ] });
437
- }
438
- function OrdersTodayTooltip({
439
- active,
440
- payload,
441
- label
442
- }) {
443
- var _a, _b, _c;
444
- if (!active || !(payload == null ? void 0 : payload.length)) return null;
445
- const row = isOrdersTodayPoint((_a = payload[0]) == null ? void 0 : _a.payload) ? (_b = payload[0]) == null ? void 0 : _b.payload : void 0;
446
- const displayLabel = (row == null ? void 0 : row.label) ?? (label ? new Date(label).toLocaleDateString() : "");
447
- const orders = ((_c = payload[0]) == null ? void 0 : _c.value) ?? 0;
448
- return /* @__PURE__ */ jsxs(AnalyticsTooltipCard, { variant: "compact", title: displayLabel, children: [
449
- /* @__PURE__ */ jsxs("div", { children: [
450
- "Orders: ",
451
- /* @__PURE__ */ jsx("strong", { children: Math.floor(orders).toLocaleString() })
452
- ] }),
453
- (row == null ? void 0 : row.isToday) ? /* @__PURE__ */ jsx("div", { style: { color: "#6B7280" }, children: "Current day" }) : null
454
- ] });
455
- }
456
- function OutcomesTrendTooltip({
457
- active,
458
- payload,
459
- label
460
- }) {
461
- var _a, _b;
462
- if (!active || !(payload == null ? void 0 : payload.length)) return null;
463
- const row = isDailyOrderRow((_a = payload[0]) == null ? void 0 : _a.payload) ? (_b = payload[0]) == null ? void 0 : _b.payload : void 0;
464
- const displayLabel = (row == null ? void 0 : row.label) ?? (label ? new Date(label).toLocaleDateString() : "");
465
- return /* @__PURE__ */ jsx(AnalyticsTooltipCard, { variant: "compact", title: displayLabel, children: payload.map((entry) => /* @__PURE__ */ jsxs("div", { children: [
466
- entry.name,
467
- ":",
468
- " ",
469
- /* @__PURE__ */ jsx("strong", { children: Math.floor(Number(entry.value) || 0).toLocaleString() })
470
- ] }, String(entry.name))) });
471
- }
472
- const TREND_MIX_PIE_COLORS = {
473
- revenue: "#c084fc",
474
- orders: "#7dd3fc",
475
- aov: "#fdba74"
476
- };
477
- function buildTrendMixPieSlices(dailyOrders, trendRevenueTotal, trendOrdersTotal, formatCompactCurrencyFn, formatCurrencyFn) {
478
- const ncRev = dailyOrders.reduce((s, d) => s + nonCancelledRevenue(d), 0);
479
- const ncOrd = dailyOrders.reduce(
480
- (s, d) => s + Math.max(0, d.orders_count - d.cancelled_count),
481
- 0
482
- );
483
- const windowAov = ncOrd > 0 ? ncRev / ncOrd : 0;
484
- const lr = Math.log1p(Math.max(trendRevenueTotal, 0));
485
- const lo = Math.log1p(Math.max(trendOrdersTotal, 0));
486
- const la = Math.log1p(Math.max(windowAov, 0));
487
- const sumW = lr + lo + la;
488
- const share = (w) => sumW > 0 ? w / sumW * 100 : 100 / 3;
489
- const sR = share(lr);
490
- const sO = share(lo);
491
- const sA = share(la);
492
- return [
493
- {
494
- key: "revenue",
495
- name: "Revenue",
496
- value: sR,
497
- fill: TREND_MIX_PIE_COLORS.revenue,
498
- sharePercent: sR,
499
- formattedPrimary: formatCompactCurrencyFn(trendRevenueTotal),
500
- formattedDetail: "Total revenue for this range, all days summed."
501
- },
502
- {
503
- key: "orders",
504
- name: "Orders",
505
- value: sO,
506
- fill: TREND_MIX_PIE_COLORS.orders,
507
- sharePercent: sO,
508
- formattedPrimary: Math.floor(trendOrdersTotal).toLocaleString(),
509
- formattedDetail: "Order count in this range from daily totals."
510
- },
511
- {
512
- key: "aov",
513
- name: "AOV",
514
- value: sA,
515
- fill: TREND_MIX_PIE_COLORS.aov,
516
- sharePercent: sA,
517
- formattedPrimary: formatCurrencyFn(windowAov),
518
- formattedDetail: "Average per non-cancelled order for the window."
519
- }
520
- ];
521
- }
522
- const TREND_MIX_LEADER_STROKE = "#b8956a";
523
- function isTrendMixPayload(value) {
524
- if (typeof value !== "object" || value === null) return false;
525
- const k = value.key;
526
- return k === "revenue" || k === "orders" || k === "aov";
527
- }
528
- function splitDetailTwoLines(s, firstLineMax) {
529
- const t = s.trim();
530
- if (t.length <= firstLineMax) return [t, ""];
531
- const sliceEnd = t.lastIndexOf(" ", firstLineMax);
532
- const cut = sliceEnd > firstLineMax * 0.45 ? sliceEnd : firstLineMax;
533
- const a = t.slice(0, cut).trim();
534
- const b = t.slice(cut).trim();
535
- return b ? [a, b] : [a, ""];
536
- }
537
- function TrendMixExplodedSector(props) {
538
- const {
539
- cx,
540
- cy,
541
- innerRadius,
542
- outerRadius,
543
- startAngle,
544
- endAngle,
545
- fill,
546
- stroke,
547
- strokeWidth,
548
- cornerRadius
549
- } = props;
550
- const midDeg = (Number(startAngle) + Number(endAngle)) / 2;
551
- const rad = -midDeg * Math.PI / 180;
552
- const offset = 19;
553
- const ncx = (Number(cx) || 0) + offset * Math.cos(rad);
554
- const ncy = (Number(cy) || 0) + offset * Math.sin(rad);
555
- return /* @__PURE__ */ jsx(
556
- Sector,
557
- {
558
- cx: ncx,
559
- cy: ncy,
560
- innerRadius,
561
- outerRadius,
562
- startAngle,
563
- endAngle,
564
- fill,
565
- stroke,
566
- strokeWidth,
567
- cornerRadius,
568
- style: {
569
- filter: "drop-shadow(0 5px 6px rgba(0,0,0,0.5)) drop-shadow(0 2px 2px rgba(0,0,0,0.35))"
570
- }
571
- }
572
- );
573
- }
574
- function createTrendMixInfographicLabel(slices) {
575
- return function TrendMixInfographicLabel(props) {
576
- const { cx, cy, midAngle, outerRadius, percent, payload, index } = props;
577
- const slice = typeof index === "number" && slices[index] !== void 0 ? slices[index] : isTrendMixPayload(payload) ? payload : null;
578
- if (slice === null || cx === void 0 || cy === void 0 || midAngle === void 0) {
579
- return null;
580
- }
581
- const p = percent ?? 0;
582
- const ang = midAngle;
583
- const RAD = Math.PI / 180;
584
- const cos = Math.cos(-RAD * ang);
585
- const sin = Math.sin(-RAD * ang);
586
- const or = Number(outerRadius);
587
- if (!Number.isFinite(or)) return null;
588
- const rimPad = 24;
589
- const sx = Number(cx) + (or + rimPad) * cos;
590
- const sy = Number(cy) + (or + rimPad) * sin;
591
- const elbow = 30;
592
- const mx = sx + elbow * cos;
593
- const my = sy;
594
- const extend = 58;
595
- const rightSide = cos >= 0;
596
- const hx = mx + (rightSide ? extend : -58);
597
- const anchor = rightSide ? "start" : "end";
598
- const tx = hx + (rightSide ? 4 : -4);
599
- const yRule = my + 14;
600
- const pctStr = `${(p * 100).toFixed(0)}%`;
601
- const ruleHalfW = 52;
602
- const xRuleA = rightSide ? tx - 2 : tx - ruleHalfW;
603
- const xRuleB = rightSide ? tx + ruleHalfW : tx + 2;
604
- const [detail1, detail2] = splitDetailTwoLines(slice.formattedDetail, 46);
605
- return /* @__PURE__ */ jsxs("g", { "aria-hidden": true, children: [
606
- /* @__PURE__ */ jsx(
607
- "polyline",
608
- {
609
- points: `${sx},${sy} ${mx},${my} ${hx},${yRule - 18}`,
610
- fill: "none",
611
- stroke: TREND_MIX_LEADER_STROKE,
612
- strokeWidth: 1.15,
613
- strokeLinecap: "round",
614
- strokeLinejoin: "round"
615
- }
616
- ),
617
- /* @__PURE__ */ jsx(
618
- "circle",
619
- {
620
- cx: sx,
621
- cy: sy,
622
- r: 3.5,
623
- fill: "none",
624
- stroke: TREND_MIX_LEADER_STROKE,
625
- strokeWidth: 1.15
626
- }
627
- ),
628
- /* @__PURE__ */ jsx(
629
- "line",
630
- {
631
- x1: xRuleA,
632
- y1: yRule,
633
- x2: xRuleB,
634
- y2: yRule,
635
- stroke: TREND_MIX_LEADER_STROKE,
636
- strokeWidth: 1.15,
637
- strokeLinecap: "round"
638
- }
639
- ),
640
- /* @__PURE__ */ jsx(
641
- "text",
642
- {
643
- x: tx,
644
- y: yRule - 8,
645
- textAnchor: anchor,
646
- fill: "#f8fafc",
647
- className: "text-[13px] font-bold tabular-nums",
648
- children: pctStr
649
- }
650
- ),
651
- /* @__PURE__ */ jsx(
652
- "text",
653
- {
654
- x: tx,
655
- y: yRule + 16,
656
- textAnchor: anchor,
657
- fill: "#f1f5f9",
658
- className: "text-[9px] font-semibold uppercase tracking-[0.16em]",
659
- children: slice.name
660
- }
661
- ),
662
- /* @__PURE__ */ jsx(
663
- "text",
664
- {
665
- x: tx,
666
- y: yRule + 32,
667
- textAnchor: anchor,
668
- fill: "#f8fafc",
669
- className: "text-[11px] font-bold tabular-nums",
670
- children: slice.formattedPrimary
671
- }
672
- ),
673
- /* @__PURE__ */ jsxs(
674
- "text",
675
- {
676
- x: tx,
677
- y: yRule + 46,
678
- textAnchor: anchor,
679
- fill: "#94a3b8",
680
- className: "text-[8px] leading-snug",
681
- children: [
682
- /* @__PURE__ */ jsx("tspan", { x: tx, dy: 0, children: detail1 }),
683
- detail2 ? /* @__PURE__ */ jsx("tspan", { x: tx, dy: 11, children: detail2 }) : null
684
- ]
685
- }
686
- )
687
- ] });
688
- };
689
- }
690
- const KPI_ICON_BG$2 = {
691
- green: "bg-emerald-500/20",
692
- blue: "bg-sky-500/20",
693
- purple: "bg-violet-500/20",
694
- amber: "bg-amber-500/20"
695
- };
696
- const KPI_ICONS$2 = {
697
- green: CurrencyDollar,
698
- blue: ShoppingCart,
699
- purple: TruckFast,
700
- amber: Cash
701
- };
702
- const PIE_PALETTE = ["#6366F1", "#94A3B8", "#10B981", "#F59E0B"];
703
- function AtlasKpiCard$2({
704
- label,
705
- value,
706
- helper,
707
- accent
708
- }) {
709
- const Icon = KPI_ICONS$2[accent];
710
- return /* @__PURE__ */ jsxs("div", { className: "flex h-full min-h-[112px] min-w-0 flex-col rounded-xl border border-ui-border-base/80 bg-ui-bg-subtle/25 p-4 shadow-sm", children: [
711
- /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2", children: [
712
- /* @__PURE__ */ jsx(Text, { className: "min-w-0 flex-1 text-left text-xs font-medium leading-snug text-ui-fg-base", children: label }),
713
- /* @__PURE__ */ jsx(
714
- "div",
715
- {
716
- className: `flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${KPI_ICON_BG$2[accent]}`,
717
- "aria-hidden": true,
718
- children: /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4 text-ui-fg-base" })
719
- }
720
- )
721
- ] }),
722
- /* @__PURE__ */ jsx("div", { className: "mt-3 text-xl font-semibold tabular-nums tracking-tight text-ui-fg-base sm:text-2xl", children: value }),
723
- helper ? /* @__PURE__ */ jsx(Text, { className: "mt-2 text-[11px] leading-snug text-ui-fg-muted", children: helper }) : null
724
- ] });
725
- }
726
- const SUMMARY_PERIODS$1 = [
58
+ const SUMMARY_PERIODS = [
727
59
  { value: "all", label: "All time" },
728
60
  { value: "0", label: "Today's orders" },
729
61
  { value: "7", label: "Last 7 days" },
@@ -735,3472 +67,563 @@ const OVER_TIME_PERIODS = [
735
67
  { value: "one_month", label: "One month" },
736
68
  { value: "one_year", label: "One year" }
737
69
  ];
738
- const STATUS_BAR_COLORS = {
739
- delivered: "#10B981",
740
- cancelled: "#EF4444",
741
- exchange: "#F59E0B",
742
- return: "#8B5CF6",
743
- today: "var(--medusa-color-ui-fg-interactive)",
744
- todayMuted: "#BFDBFE",
745
- orders: "#38BDF8",
746
- revenue: "#D946EF"
747
- };
748
- const CHART_AXIS_TICK$2 = { fontSize: 10, fill: "#e5e7eb" };
749
- const CHART_AXIS_TICK_SM$1 = { fontSize: 9, fill: "#e5e7eb" };
750
- const CHART_AXIS_LINE$2 = "#94a3b8";
751
- const SELECT_CLASS_NAME$2 = "h-9 min-w-[132px] cursor-pointer appearance-none rounded border border-ui-border-base bg-ui-bg-base py-1.5 pl-3 pr-8 text-xs text-ui-fg-base outline-none transition focus:ring-2 focus:ring-ui-fg-interactive";
752
- function EmptyAnalyticsPanel$1({
753
- title,
754
- description
755
- }) {
756
- return /* @__PURE__ */ jsxs("div", { className: "flex min-h-[88px] flex-col gap-1.5 rounded-lg border border-dashed border-ui-border-base px-3 py-3", children: [
757
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-xs font-semibold", children: title }),
758
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[11px] leading-snug", children: description })
759
- ] });
760
- }
761
70
  function OrdersDashboard() {
762
- var _a, _b, _c, _d, _e;
763
- const { formatCurrency, formatCompactCurrency } = useAnalyticsCurrency();
764
71
  const [data, setData] = useState(null);
765
72
  const [loading, setLoading] = useState(true);
766
73
  const [error, setError] = useState(null);
767
74
  const [filter, setFilter] = useState("all");
768
75
  const [dailyOrders, setDailyOrders] = useState([]);
769
- const [previousPeriodDailyOrders, setPreviousPeriodDailyOrders] = useState([]);
770
- const [overTimePeriod, setOverTimePeriod] = useState("one_week");
771
- const [overTimeLoading, setOverTimeLoading] = useState(true);
772
- const [overTimeError, setOverTimeError] = useState(null);
773
- const [overTimeOrdersMeta, setOverTimeOrdersMeta] = useState(null);
774
- const [ordersInsights, setOrdersInsights] = useState(null);
775
- const [insightsLoading, setInsightsLoading] = useState(true);
776
- const [insightsError, setInsightsError] = useState(null);
777
- const [todayContext, setTodayContext] = useState([]);
778
- const [todayContextLoading, setTodayContextLoading] = useState(true);
779
- const [todayContextError, setTodayContextError] = useState(null);
780
- const [salesGranularity, setSalesGranularity] = useState("day");
781
- const [salesBreakdownDaily, setSalesBreakdownDaily] = useState(
782
- []
783
- );
784
- const [salesBreakdownOtLoading, setSalesBreakdownOtLoading] = useState(true);
785
- const [salesBreakdownOtError, setSalesBreakdownOtError] = useState(null);
786
- const [salesBreakdownHourlyRolling, setSalesBreakdownHourlyRolling] = useState([]);
787
- const [salesBreakdownHourlyLoading, setSalesBreakdownHourlyLoading] = useState(false);
788
- const [salesBreakdownHourlyError, setSalesBreakdownHourlyError] = useState(null);
789
- const salesBreakdownOtPeriod = useMemo(
790
- () => getSalesBreakdownOtPeriod(salesGranularity),
791
- [salesGranularity]
792
- );
793
- useEffect(() => {
794
- if (salesBreakdownOtPeriod === null) {
795
- setSalesBreakdownDaily([]);
796
- setSalesBreakdownOtLoading(false);
797
- setSalesBreakdownOtError(null);
798
- return;
799
- }
800
- let cancelled = false;
801
- setSalesBreakdownOtLoading(true);
802
- setSalesBreakdownOtError(null);
803
- fetch(
804
- `/admin/analytics/orders-over-time?period=${salesBreakdownOtPeriod}`,
805
- { credentials: "include" }
806
- ).then((res) => {
807
- if (!res.ok) throw new Error(res.statusText);
808
- return res.json();
809
- }).then((body) => {
810
- if (!cancelled) {
811
- setSalesBreakdownDaily(body.dailyOrders ?? []);
812
- }
813
- }).catch((e) => {
814
- if (!cancelled) {
815
- setSalesBreakdownOtError(e instanceof Error ? e.message : String(e));
816
- }
817
- }).finally(() => {
818
- if (!cancelled) setSalesBreakdownOtLoading(false);
819
- });
820
- return () => {
821
- cancelled = true;
822
- };
823
- }, [salesBreakdownOtPeriod]);
824
- useEffect(() => {
825
- if (salesGranularity !== "hour") {
826
- setSalesBreakdownHourlyRolling([]);
827
- setSalesBreakdownHourlyLoading(false);
828
- setSalesBreakdownHourlyError(null);
829
- return;
830
- }
831
- let cancelled = false;
832
- setSalesBreakdownHourlyLoading(true);
833
- setSalesBreakdownHourlyError(null);
834
- fetch("/admin/analytics/orders-insights?last_hours=24", {
835
- credentials: "include"
836
- }).then((res) => {
837
- if (!res.ok) throw new Error(res.statusText);
838
- return res.json();
839
- }).then((body) => {
840
- if (!cancelled) {
841
- setSalesBreakdownHourlyRolling(body.hourly_rolling ?? []);
842
- }
843
- }).catch((e) => {
844
- if (!cancelled) {
845
- setSalesBreakdownHourlyError(
846
- e instanceof Error ? e.message : String(e)
847
- );
848
- }
849
- }).finally(() => {
850
- if (!cancelled) setSalesBreakdownHourlyLoading(false);
851
- });
852
- return () => {
853
- cancelled = true;
854
- };
855
- }, [salesGranularity]);
856
- useEffect(() => {
857
- let cancelled = false;
858
- setLoading(true);
859
- setError(null);
860
- const url = `/admin/analytics/orders-summary?days=${filter}`;
861
- fetch(url, { credentials: "include" }).then((res) => {
862
- if (!res.ok) throw new Error(res.statusText);
863
- return res.json();
864
- }).then((body) => {
865
- if (!cancelled) setData(body);
866
- }).catch((e) => {
867
- if (!cancelled) setError(e instanceof Error ? e.message : String(e));
868
- }).finally(() => {
869
- if (!cancelled) setLoading(false);
870
- });
871
- return () => {
872
- cancelled = true;
873
- };
874
- }, [filter]);
875
- useEffect(() => {
876
- let cancelled = false;
877
- setOverTimeLoading(true);
878
- setOverTimeError(null);
879
- const url = `/admin/analytics/orders-over-time?period=${overTimePeriod}`;
880
- fetch(url, { credentials: "include" }).then((res) => {
881
- if (!res.ok) throw new Error(res.statusText);
882
- return res.json();
883
- }).then((body) => {
884
- if (!cancelled) {
885
- setDailyOrders(body.dailyOrders ?? []);
886
- setPreviousPeriodDailyOrders(body.previousPeriodDailyOrders ?? []);
887
- setOverTimeOrdersMeta(body.ordersAnalyticsMeta ?? null);
888
- }
889
- }).catch((e) => {
890
- if (!cancelled) {
891
- setOverTimeError(e instanceof Error ? e.message : String(e));
892
- setOverTimeOrdersMeta(null);
893
- }
894
- }).finally(() => {
895
- if (!cancelled) setOverTimeLoading(false);
896
- });
897
- return () => {
898
- cancelled = true;
899
- };
900
- }, [overTimePeriod]);
901
- const insightsWindowDays = useMemo(() => {
902
- if (overTimePeriod === "one_week") return 7;
903
- if (overTimePeriod === "one_month") return 30;
904
- return 365;
905
- }, [overTimePeriod]);
906
- useEffect(() => {
907
- let cancelled = false;
908
- setInsightsLoading(true);
909
- setInsightsError(null);
910
- fetch(`/admin/analytics/orders-insights?days=${insightsWindowDays}`, {
911
- credentials: "include"
912
- }).then((res) => {
913
- if (!res.ok) throw new Error(res.statusText);
914
- return res.json();
915
- }).then((body) => {
916
- if (!cancelled) setOrdersInsights(body);
917
- }).catch((e) => {
918
- if (!cancelled) setInsightsError(e instanceof Error ? e.message : String(e));
919
- }).finally(() => {
920
- if (!cancelled) setInsightsLoading(false);
921
- });
922
- return () => {
923
- cancelled = true;
924
- };
925
- }, [insightsWindowDays]);
926
- useEffect(() => {
927
- let cancelled = false;
928
- setTodayContextLoading(true);
929
- setTodayContextError(null);
930
- fetch("/admin/analytics/orders-over-time?period=one_week", {
931
- credentials: "include"
932
- }).then((res) => {
933
- if (!res.ok) throw new Error(res.statusText);
934
- return res.json();
935
- }).then((body) => {
936
- if (!cancelled) setTodayContext(body.dailyOrders ?? []);
937
- }).catch((e) => {
938
- if (!cancelled) {
939
- setTodayContextError(e instanceof Error ? e.message : String(e));
940
- }
941
- }).finally(() => {
942
- if (!cancelled) setTodayContextLoading(false);
943
- });
944
- return () => {
945
- cancelled = true;
946
- };
947
- }, []);
948
- const selectedSummaryPeriod = ((_a = SUMMARY_PERIODS$1.find((period) => period.value === filter)) == null ? void 0 : _a.label) ?? "All time";
949
- const operationsBreakdown = (data == null ? void 0 : data.operationalCounts) ?? {
950
- cancelled: (data == null ? void 0 : data.cancelledOrders) ?? 0,
951
- delivered: (data == null ? void 0 : data.deliveredOrders) ?? 0,
952
- exchange: (data == null ? void 0 : data.exchangeOrders) ?? 0,
953
- return: (data == null ? void 0 : data.returnOrders) ?? 0
954
- };
955
- const outcomesTimeSeriesHasPoints = useMemo(
956
- () => dailyOrders.some(
957
- (d) => d.delivered_count > 0 || d.cancelled_count > 0 || d.exchange_count > 0 || d.return_count > 0
958
- ),
959
- [dailyOrders]
960
- );
961
- const totalResolvedOrders = operationsBreakdown.delivered + operationsBreakdown.cancelled;
962
- const deliveryRate = totalResolvedOrders > 0 ? operationsBreakdown.delivered / totalResolvedOrders * 100 : 0;
963
- const primaryStats = data ? [
964
- {
965
- label: "Total revenue",
966
- value: formatCurrency(data.totalRevenue),
967
- helper: "Non-cancelled orders",
968
- accent: "green"
969
- },
970
- {
971
- label: "Total orders",
972
- value: data.totalOrders.toLocaleString(),
973
- helper: selectedSummaryPeriod,
974
- accent: "blue"
975
- },
976
- {
977
- label: "Delivery rate",
978
- value: formatPercent(deliveryRate),
979
- helper: "Delivered vs cancelled",
980
- accent: "purple"
981
- },
982
- {
983
- label: "Average order value",
984
- value: formatCurrency(data.aov),
985
- helper: "Per non-cancelled order",
986
- accent: "amber"
987
- }
988
- ] : [];
989
- const secondaryStats = data ? [
990
- { label: "Orders today", value: data.ordersToday.toLocaleString() },
991
- { label: "Pending orders", value: data.pendingOrders.toLocaleString() },
992
- { label: "Delivered orders", value: data.deliveredOrders.toLocaleString() },
993
- { label: "Cancelled orders", value: data.cancelledOrders.toLocaleString() },
994
- { label: "Exchange orders", value: data.exchangeOrders.toLocaleString() },
995
- {
996
- label: "Avg. fulfillment time",
997
- value: data.avgFulfillmentTimeHours != null ? `${data.avgFulfillmentTimeHours}h` : "—",
998
- helper: "Measured in hours"
999
- }
1000
- ] : [];
1001
- const todayChartData = useMemo(
1002
- () => todayContext.map((point, index) => ({
1003
- ...point,
1004
- isToday: index === todayContext.length - 1
1005
- })),
1006
- [todayContext]
1007
- );
1008
- const todayOrdersAverage = todayChartData.length > 0 ? todayChartData.reduce((sum, point) => sum + point.orders_count, 0) / todayChartData.length : 0;
1009
- const todayPoint = todayChartData[todayChartData.length - 1] ?? null;
1010
- const todayDelta = todayPoint && todayOrdersAverage > 0 ? todayPoint.orders_count - todayOrdersAverage : null;
1011
- const trendRevenueTotal = dailyOrders.reduce(
1012
- (sum, point) => sum + point.total_revenue,
1013
- 0
1014
- );
1015
- const trendOrdersTotal = dailyOrders.reduce(
1016
- (sum, point) => sum + point.orders_count,
1017
- 0
1018
- );
1019
- const trendAverageRevenue = dailyOrders.length > 0 ? trendRevenueTotal / dailyOrders.length : 0;
1020
- const trendAverageOrders = dailyOrders.length > 0 ? trendOrdersTotal / dailyOrders.length : 0;
1021
- const peakRevenuePoint = dailyOrders.length > 0 ? dailyOrders.reduce(
1022
- (peak, point) => point.total_revenue > peak.total_revenue ? point : peak
1023
- ) : null;
1024
- const previousPeriodRevenueTotal = useMemo(
1025
- () => previousPeriodDailyOrders.reduce((s, d) => s + d.total_revenue, 0),
1026
- [previousPeriodDailyOrders]
1027
- );
1028
- const previousPeriodOrdersTotal = useMemo(
1029
- () => previousPeriodDailyOrders.reduce((s, d) => s + d.orders_count, 0),
1030
- [previousPeriodDailyOrders]
1031
- );
1032
- const revenueVsPreviousPercent = previousPeriodRevenueTotal > 0 ? (trendRevenueTotal - previousPeriodRevenueTotal) / previousPeriodRevenueTotal * 100 : null;
1033
- const ordersVsPreviousPercent = previousPeriodOrdersTotal > 0 ? (trendOrdersTotal - previousPeriodOrdersTotal) / previousPeriodOrdersTotal * 100 : null;
1034
- const trendMixPieSlices = useMemo(
1035
- () => buildTrendMixPieSlices(
1036
- dailyOrders,
1037
- trendRevenueTotal,
1038
- trendOrdersTotal,
1039
- formatCompactCurrency,
1040
- formatCurrency
1041
- ),
1042
- [
1043
- dailyOrders,
1044
- trendRevenueTotal,
1045
- trendOrdersTotal,
1046
- formatCompactCurrency,
1047
- formatCurrency
1048
- ]
1049
- );
1050
- const trendMixPieLabelRenderer = useMemo(
1051
- () => createTrendMixInfographicLabel(trendMixPieSlices),
1052
- [trendMixPieSlices]
1053
- );
1054
- const trendMixRangeFootnote = useMemo(() => {
1055
- const ncRev = dailyOrders.reduce((s, d) => s + nonCancelledRevenue(d), 0);
1056
- const ncOrd = dailyOrders.reduce(
1057
- (s, d) => s + Math.max(0, d.orders_count - d.cancelled_count),
1058
- 0
1059
- );
1060
- const windowAov = ncOrd > 0 ? ncRev / ncOrd : 0;
1061
- return {
1062
- revenue: formatCompactCurrency(trendRevenueTotal),
1063
- orders: Math.floor(trendOrdersTotal).toLocaleString(),
1064
- aov: formatCurrency(windowAov)
1065
- };
1066
- }, [
1067
- dailyOrders,
1068
- trendRevenueTotal,
1069
- trendOrdersTotal,
1070
- formatCompactCurrency,
1071
- formatCurrency
1072
- ]);
1073
- const salesBreakdownChartRows = useMemo(() => {
1074
- if (salesGranularity === "hour") {
1075
- return salesBreakdownHourlyRolling.map((b, i) => ({
1076
- key: `rolling-${i}`,
1077
- label: b.label,
1078
- orders_count: b.orders_count,
1079
- revenue: b.revenue
1080
- }));
1081
- }
1082
- if (salesGranularity === "week") {
1083
- const targetKeys = lastNWeekStartKeysUtc(7);
1084
- const agg = /* @__PURE__ */ new Map();
1085
- for (const d of salesBreakdownDaily) {
1086
- const wk = utcSundayWeekStartKeyFromDateStr(d.date);
1087
- const cur = agg.get(wk) ?? { orders: 0, revenue: 0 };
1088
- cur.orders += d.orders_count;
1089
- cur.revenue += d.total_revenue;
1090
- agg.set(wk, cur);
1091
- }
1092
- return targetKeys.map((key) => {
1093
- var _a2, _b2;
1094
- return {
1095
- key,
1096
- label: formatWeekStartDm(key),
1097
- orders_count: ((_a2 = agg.get(key)) == null ? void 0 : _a2.orders) ?? 0,
1098
- revenue: ((_b2 = agg.get(key)) == null ? void 0 : _b2.revenue) ?? 0
1099
- };
1100
- });
1101
- }
1102
- if (salesGranularity === "month") {
1103
- return salesBreakdownDaily.map((d) => ({
1104
- key: d.date,
1105
- label: d.label ?? formatMonthBucketLabel(monthKeyFromDateStr(d.date)),
1106
- orders_count: d.orders_count,
1107
- revenue: d.total_revenue
1108
- }));
1109
- }
1110
- return salesBreakdownDaily.map((d) => ({
1111
- key: d.date,
1112
- label: formatDayBreakdownDm(d.date),
1113
- orders_count: d.orders_count,
1114
- revenue: d.total_revenue
1115
- }));
1116
- }, [
1117
- salesGranularity,
1118
- salesBreakdownDaily,
1119
- salesBreakdownHourlyRolling
1120
- ]);
1121
- const salesBreakdownDescription = useMemo(() => {
1122
- switch (salesGranularity) {
1123
- case "hour":
1124
- return "Last 24 hours from now (UTC): one bar per clock hour in the rolling window.";
1125
- case "day":
1126
- return "Last 7 calendar days (UTC), one bar per day — axis day/month.";
1127
- case "week":
1128
- return "Last 7 weeks (UTC, weeks start Sunday); axis shows each week’s start as day/month.";
1129
- case "month":
1130
- return "Last 12 calendar months through the current month (UTC) — Jan, Feb, Mar, …";
1131
- default:
1132
- return "";
1133
- }
1134
- }, [salesGranularity]);
1135
- const salesBreakdownXAxisInterval = useMemo(() => {
1136
- const n = salesBreakdownChartRows.length;
1137
- if (salesGranularity === "hour") return 3;
1138
- if (salesGranularity === "day" && n > 24)
1139
- return Math.max(0, Math.ceil(n / 10) - 1);
1140
- return 0;
1141
- }, [salesGranularity, salesBreakdownChartRows.length]);
1142
- const ordersVsDraftsPie = useMemo(() => {
1143
- var _a2;
1144
- if (!ordersInsights) return [];
1145
- const placed = ((_a2 = ordersInsights.funnel[0]) == null ? void 0 : _a2.count) ?? 0;
1146
- const draftsCount = ordersInsights.drafts.available === true ? ordersInsights.drafts.count : 0;
1147
- return [
1148
- { name: "Orders placed (window)", value: placed, key: "placed" },
1149
- {
1150
- name: ordersInsights.drafts.available === true ? "Open draft orders (snapshot)" : "Draft orders (unavailable)",
1151
- value: draftsCount,
1152
- key: "drafts"
1153
- }
1154
- ];
1155
- }, [ordersInsights]);
1156
- const funnelTimeSeriesRows = useMemo(() => {
1157
- return dailyOrders.map((d) => {
1158
- const placed = d.orders_count;
1159
- const notCancelled = Math.max(0, d.orders_count - d.cancelled_count);
1160
- const shipped = d.shipped_count ?? 0;
1161
- const delivered = d.delivered_count;
1162
- const pctNotCancelled = placed > 0 ? notCancelled / placed * 100 : 0;
1163
- const pctShippedOfNc = notCancelled > 0 ? shipped / notCancelled * 100 : 0;
1164
- const pctDeliveredOfShipped = shipped > 0 ? delivered / shipped * 100 : 0;
1165
- return {
1166
- date: d.date,
1167
- label: d.label ?? formatChartLabel$2(d.date),
1168
- placed,
1169
- not_cancelled: notCancelled,
1170
- shipped,
1171
- delivered,
1172
- pct_not_cancelled: Math.round(pctNotCancelled * 10) / 10,
1173
- pct_shipped_of_active: Math.round(pctShippedOfNc * 10) / 10,
1174
- pct_delivered_of_shipped: Math.round(pctDeliveredOfShipped * 10) / 10
1175
- };
1176
- });
1177
- }, [dailyOrders]);
1178
- const selectedTrendPeriodLabel = ((_b = OVER_TIME_PERIODS.find((p) => p.value === overTimePeriod)) == null ? void 0 : _b.label) ?? "Selected range";
1179
- const orderSampleLikelyTruncated = (((_c = data == null ? void 0 : data.ordersAnalyticsMeta) == null ? void 0 : _c.likely_truncated) ?? false) || ((overTimeOrdersMeta == null ? void 0 : overTimeOrdersMeta.likely_truncated) ?? false) || (((_d = ordersInsights == null ? void 0 : ordersInsights.ordersAnalyticsMeta) == null ? void 0 : _d.likely_truncated) ?? false);
1180
- const quickPulseMetrics = [
1181
- {
1182
- label: "Range revenue",
1183
- value: formatCompactCurrency(trendRevenueTotal),
1184
- helper: selectedTrendPeriodLabel,
1185
- accentClassName: "border-emerald-400/25 bg-emerald-500/5"
1186
- },
1187
- {
1188
- label: "Range orders",
1189
- value: formatShortNumber$1(trendOrdersTotal),
1190
- helper: "Current trend window",
1191
- accentClassName: "border-sky-400/25 bg-sky-500/5"
1192
- },
1193
- {
1194
- label: "Avg/day orders",
1195
- value: trendAverageOrders.toFixed(1),
1196
- helper: "Across selected chart range",
1197
- accentClassName: "border-violet-400/25 bg-violet-500/5"
1198
- },
1199
- {
1200
- label: "Peak revenue day",
1201
- value: peakRevenuePoint ? formatCompactCurrency(peakRevenuePoint.total_revenue) : "—",
1202
- helper: (peakRevenuePoint == null ? void 0 : peakRevenuePoint.label) ?? formatChartLabel$2(peakRevenuePoint == null ? void 0 : peakRevenuePoint.date),
1203
- accentClassName: "border-amber-400/25 bg-amber-500/5"
1204
- }
1205
- ];
1206
- if (loading) {
1207
- return /* @__PURE__ */ jsx(
1208
- "div",
1209
- {
1210
- className: "flex min-h-[200px] items-center justify-center",
1211
- role: "status",
1212
- "aria-label": "Loading analytics",
1213
- children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted", children: "Loading…" })
1214
- }
1215
- );
1216
- }
1217
- if (error || !data) {
1218
- return /* @__PURE__ */ jsx(Container, { className: "p-6", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger", children: error ?? "Failed to load analytics" }) });
1219
- }
1220
- const salesBreakdownWaiting = salesGranularity === "hour" ? salesBreakdownHourlyLoading : salesBreakdownOtLoading;
1221
- const salesBreakdownFetchError = salesGranularity === "hour" ? salesBreakdownHourlyError : salesBreakdownOtError;
1222
- const salesBreakdownBody = (() => {
1223
- if (salesBreakdownWaiting) {
1224
- return /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsx("div", { className: "flex min-h-[min(176px,28vh)] items-center justify-center py-6", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "Loading chart…" }) }) });
1225
- }
1226
- if (salesBreakdownFetchError) {
1227
- return /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsx("div", { className: "flex min-h-[min(176px,28vh)] items-center justify-center px-2 py-6", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger text-center text-xs", children: salesBreakdownFetchError }) }) });
1228
- }
1229
- if (salesBreakdownChartRows.length === 0) {
1230
- return /* @__PURE__ */ jsx(
1231
- EmptyAnalyticsPanel$1,
1232
- {
1233
- title: "No sales data",
1234
- description: "Nothing to show for this view and range."
1235
- }
1236
- );
1237
- }
1238
- return /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsx("div", { className: "h-[min(200px,30vh)] min-h-[160px] w-full sm:h-[min(220px,32vh)]", children: /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxs(
1239
- BarChart,
1240
- {
1241
- data: salesBreakdownChartRows,
1242
- margin: { top: 4, right: 8, left: 4, bottom: 4 },
1243
- children: [
1244
- /* @__PURE__ */ jsx(
1245
- CartesianGrid,
1246
- {
1247
- strokeDasharray: "3 3",
1248
- vertical: false,
1249
- stroke: "rgba(148,163,184,0.12)"
1250
- }
1251
- ),
1252
- /* @__PURE__ */ jsx(
1253
- XAxis,
1254
- {
1255
- dataKey: "label",
1256
- tick: CHART_AXIS_TICK_SM$1,
1257
- tickLine: false,
1258
- axisLine: false,
1259
- interval: salesBreakdownXAxisInterval
1260
- }
1261
- ),
1262
- /* @__PURE__ */ jsx(
1263
- YAxis,
1264
- {
1265
- width: 44,
1266
- tick: CHART_AXIS_TICK_SM$1,
1267
- tickLine: false,
1268
- axisLine: false,
1269
- tickFormatter: (v) => formatCompactCurrency(Number(v))
1270
- }
1271
- ),
1272
- /* @__PURE__ */ jsx(
1273
- Tooltip,
1274
- {
1275
- content: /* @__PURE__ */ jsx(SalesBreakdownTooltip, {}),
1276
- cursor: { fill: "rgba(148,163,184,0.08)" }
1277
- }
1278
- ),
1279
- /* @__PURE__ */ jsx(
1280
- Bar,
1281
- {
1282
- dataKey: "revenue",
1283
- name: "Revenue",
1284
- fill: "#D946EF",
1285
- radius: [6, 6, 0, 0]
1286
- }
1287
- )
1288
- ]
1289
- }
1290
- ) }) }) });
1291
- })();
1292
- return /* @__PURE__ */ jsx(AnalyticsDashboardShell, { children: /* @__PURE__ */ jsxs("div", { className: "overflow-hidden rounded-2xl border border-ui-border-base/80 bg-ui-bg-base shadow-sm", children: [
1293
- orderSampleLikelyTruncated ? /* @__PURE__ */ jsx(
1294
- "div",
1295
- {
1296
- className: "border-b border-amber-400/30 bg-amber-500/10 px-4 py-2.5 sm:px-5",
1297
- role: "status",
1298
- children: /* @__PURE__ */ jsxs(Text, { className: "text-ui-fg-base text-xs leading-snug", children: [
1299
- "Order analytics loaded up to ",
1300
- ORDERS_ANALYTICS_MAX_FETCH.toLocaleString(),
1301
- " ",
1302
- "orders per request. If you have more orders, KPIs and charts may under-count. Plan server-side aggregation or pagination for exact totals at very high volume."
1303
- ] })
1304
- }
1305
- ) : null,
1306
- /* @__PURE__ */ jsx(
1307
- AnalyticsDashboardHeader,
1308
- {
1309
- variant: "premium",
1310
- appearance: "inset",
1311
- actionsBare: true,
1312
- title: "Orders",
1313
- description: "Revenue, volume, and outcomes in a compact overview sized for a single viewport.",
1314
- actions: /* @__PURE__ */ jsxs(Fragment, { children: [
1315
- /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
1316
- /* @__PURE__ */ jsx(
1317
- Label,
1318
- {
1319
- htmlFor: "analytics-period",
1320
- className: "shrink-0 text-ui-fg-muted text-xs font-medium",
1321
- children: "Period"
1322
- }
1323
- ),
1324
- /* @__PURE__ */ jsx(
1325
- "select",
1326
- {
1327
- id: "analytics-period",
1328
- value: filter,
1329
- onChange: (e) => setFilter(e.target.value),
1330
- className: SELECT_CLASS_NAME$2,
1331
- children: SUMMARY_PERIODS$1.map((p) => /* @__PURE__ */ jsx("option", { value: p.value, children: p.label }, p.value))
1332
- }
1333
- )
1334
- ] }),
1335
- filter !== "all" ? /* @__PURE__ */ jsx(
1336
- "button",
1337
- {
1338
- type: "button",
1339
- onClick: () => setFilter("all"),
1340
- className: "text-xs text-ui-fg-muted transition-colors hover:text-ui-fg-base",
1341
- "aria-label": "Show all orders (clear filter)",
1342
- children: "Clear period"
1343
- }
1344
- ) : null
1345
- ] })
1346
- }
1347
- ),
1348
- /* @__PURE__ */ jsxs("div", { className: "space-y-3 p-3 pt-0 md:p-4 md:pt-0", children: [
1349
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
1350
- /* @__PURE__ */ jsx("div", { className: "px-0.5", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.16em]", children: "Order overview" }) }),
1351
- /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 gap-3 lg:grid-cols-4", children: primaryStats.map((stat) => /* @__PURE__ */ jsx(
1352
- AtlasKpiCard$2,
1353
- {
1354
- label: stat.label,
1355
- value: stat.value,
1356
- helper: stat.helper,
1357
- accent: stat.accent
1358
- },
1359
- stat.label
1360
- )) })
1361
- ] }),
1362
- /* @__PURE__ */ jsxs("div", { className: "mt-3 grid grid-cols-12 gap-2 xl:items-start", children: [
1363
- /* @__PURE__ */ jsx("div", { className: "col-span-12 xl:col-span-6", children: /* @__PURE__ */ jsx(
1364
- AnalyticsSection,
1365
- {
1366
- variant: "atlas",
1367
- actionsBare: true,
1368
- title: "Revenue & orders",
1369
- description: "Time series for the selected range. Window totals below match this chart.",
1370
- actions: /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
1371
- /* @__PURE__ */ jsx(
1372
- Label,
1373
- {
1374
- htmlFor: "over-time-period",
1375
- className: "shrink-0 text-ui-fg-muted text-xs font-medium",
1376
- children: "Range"
1377
- }
1378
- ),
1379
- /* @__PURE__ */ jsx(
1380
- "select",
1381
- {
1382
- id: "over-time-period",
1383
- value: overTimePeriod,
1384
- onChange: (e) => setOverTimePeriod(e.target.value),
1385
- className: SELECT_CLASS_NAME$2,
1386
- children: OVER_TIME_PERIODS.map((p) => /* @__PURE__ */ jsx("option", { value: p.value, children: p.label }, p.value))
1387
- }
1388
- )
1389
- ] }),
1390
- children: /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
1391
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-1.5 sm:grid-cols-3", children: [
1392
- /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
1393
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: "Window revenue" }),
1394
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-lg font-semibold tracking-tight", children: formatCompactCurrency(trendRevenueTotal) }),
1395
- /* @__PURE__ */ jsxs(Text, { className: "text-ui-fg-muted text-[10px]", children: [
1396
- "Avg/day ",
1397
- formatCompactCurrency(trendAverageRevenue)
1398
- ] })
1399
- ] }) }),
1400
- /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
1401
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: "Window orders" }),
1402
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-lg font-semibold tracking-tight", children: trendOrdersTotal.toLocaleString() }),
1403
- /* @__PURE__ */ jsxs(Text, { className: "text-ui-fg-muted text-[10px]", children: [
1404
- "Avg/day ",
1405
- trendAverageOrders.toFixed(1)
1406
- ] })
1407
- ] }) }),
1408
- /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
1409
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: "vs previous period" }),
1410
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-lg font-semibold tracking-tight", children: revenueVsPreviousPercent === null ? "—" : `${revenueVsPreviousPercent >= 0 ? "+" : ""}${revenueVsPreviousPercent.toFixed(1)}% rev` }),
1411
- /* @__PURE__ */ jsxs(Text, { className: "text-ui-fg-muted text-[10px] leading-snug", children: [
1412
- "Orders",
1413
- " ",
1414
- ordersVsPreviousPercent === null ? "—" : `${ordersVsPreviousPercent >= 0 ? "+" : ""}${ordersVsPreviousPercent.toFixed(1)}%`
1415
- ] })
1416
- ] }) })
1417
- ] }),
1418
- !overTimeLoading && !overTimeError && dailyOrders.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
1419
- /* @__PURE__ */ jsxs(AnalyticsChartSurface, { variant: "atlas", children: [
1420
- /* @__PURE__ */ jsxs("div", { className: "mb-2 min-w-0", children: [
1421
- /* @__PURE__ */ jsx(Text, { className: "text-[10px] font-medium uppercase tracking-[0.14em] text-ui-fg-muted", children: "Revenue, orders & AOV" }),
1422
- /* @__PURE__ */ jsxs(Text, { className: "text-ui-fg-muted text-[9px] leading-snug", children: [
1423
- "Floating wedges with open center · leader labels only (no hover). Window:",
1424
- " ",
1425
- /* @__PURE__ */ jsx("span", { className: "text-ui-fg-subtle", children: selectedTrendPeriodLabel }),
1426
- "."
1427
- ] })
1428
- ] }),
1429
- /* @__PURE__ */ jsxs(
1430
- "div",
1431
- {
1432
- className: "w-full rounded-2xl bg-[radial-gradient(ellipse_at_50%_42%,rgba(148,163,184,0.14)_0%,transparent_58%)] py-1",
1433
- role: "img",
1434
- "aria-label": `Revenue, orders, and AOV for ${selectedTrendPeriodLabel}. Values are shown on leader labels.`,
1435
- children: [
1436
- /* @__PURE__ */ jsx("div", { className: "h-[min(340px,48vh)] min-h-[288px] w-full", children: /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsx(
1437
- PieChart,
1438
- {
1439
- margin: { top: 20, right: 132, bottom: 28, left: 132 },
1440
- children: /* @__PURE__ */ jsx(
1441
- Pie,
1442
- {
1443
- data: trendMixPieSlices,
1444
- dataKey: "value",
1445
- nameKey: "name",
1446
- cx: "50%",
1447
- cy: "50%",
1448
- startAngle: 90,
1449
- endAngle: -270,
1450
- innerRadius: "26%",
1451
- outerRadius: "46%",
1452
- paddingAngle: 9,
1453
- cornerRadius: 8,
1454
- stroke: "rgba(15,23,42,0.55)",
1455
- strokeWidth: 2,
1456
- shape: TrendMixExplodedSector,
1457
- label: trendMixPieLabelRenderer,
1458
- labelLine: false,
1459
- isAnimationActive: false,
1460
- children: trendMixPieSlices.map((slice) => /* @__PURE__ */ jsx(Cell, { fill: slice.fill }, slice.key))
1461
- }
1462
- )
1463
- }
1464
- ) }) }),
1465
- /* @__PURE__ */ jsxs(Text, { className: "mt-2 px-1 text-center text-[9px] leading-snug text-ui-fg-muted", children: [
1466
- "Range snapshot — Revenue ",
1467
- trendMixRangeFootnote.revenue,
1468
- " · Orders",
1469
- " ",
1470
- trendMixRangeFootnote.orders,
1471
- " · AOV ",
1472
- trendMixRangeFootnote.aov
1473
- ] })
1474
- ]
1475
- }
1476
- )
1477
- ] }),
1478
- /* @__PURE__ */ jsxs(AnalyticsChartSurface, { variant: "atlas", className: "mt-1.5", children: [
1479
- /* @__PURE__ */ jsx(Text, { className: "mb-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-ui-fg-muted", children: "Revenue breakdown (stacked — by order status)" }),
1480
- /* @__PURE__ */ jsx("div", { className: "h-[min(168px,26vh)] min-h-[140px] w-full", children: /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxs(
1481
- ComposedChart,
1482
- {
1483
- data: dailyOrders,
1484
- margin: { top: 4, right: 8, left: -4, bottom: 0 },
1485
- children: [
1486
- /* @__PURE__ */ jsx(
1487
- CartesianGrid,
1488
- {
1489
- stroke: "rgba(148,163,184,0.14)",
1490
- strokeDasharray: "3 3",
1491
- vertical: false
1492
- }
1493
- ),
1494
- /* @__PURE__ */ jsx(
1495
- XAxis,
1496
- {
1497
- dataKey: "date",
1498
- tick: CHART_AXIS_TICK$2,
1499
- tickLine: false,
1500
- axisLine: false,
1501
- tickFormatter: (value) => {
1502
- const row = dailyOrders.find(
1503
- (d) => d.date === String(value)
1504
- );
1505
- return (row == null ? void 0 : row.label) ?? formatChartLabel$2(String(value));
1506
- }
1507
- }
1508
- ),
1509
- /* @__PURE__ */ jsx(
1510
- YAxis,
1511
- {
1512
- tick: CHART_AXIS_TICK$2,
1513
- tickFormatter: (v) => formatCompactCurrency(Number(v))
1514
- }
1515
- ),
1516
- /* @__PURE__ */ jsx(
1517
- Tooltip,
1518
- {
1519
- content: ({ active, payload, label }) => active && (payload == null ? void 0 : payload.length) ? /* @__PURE__ */ jsx(AnalyticsTooltipCard, { variant: "compact", title: String(label), children: payload.map((p) => /* @__PURE__ */ jsxs("div", { children: [
1520
- p.name,
1521
- ":",
1522
- " ",
1523
- /* @__PURE__ */ jsx("strong", { children: formatCurrency(Number(p.value) || 0) })
1524
- ] }, String(p.name))) }) : null
1525
- }
1526
- ),
1527
- /* @__PURE__ */ jsx(Legend, { wrapperStyle: { fontSize: 10 }, iconType: "circle" }),
1528
- /* @__PURE__ */ jsx(
1529
- Area,
1530
- {
1531
- type: "natural",
1532
- dataKey: "revenue_delivered",
1533
- name: "Delivered",
1534
- stackId: "r",
1535
- fill: "#10B981",
1536
- stroke: "#059669",
1537
- fillOpacity: 0.85
1538
- }
1539
- ),
1540
- /* @__PURE__ */ jsx(
1541
- Area,
1542
- {
1543
- type: "natural",
1544
- dataKey: "revenue_open",
1545
- name: "Open / pending",
1546
- stackId: "r",
1547
- fill: "#3B82F6",
1548
- stroke: "#2563eb",
1549
- fillOpacity: 0.85
1550
- }
1551
- ),
1552
- /* @__PURE__ */ jsx(
1553
- Area,
1554
- {
1555
- type: "natural",
1556
- dataKey: "revenue_cancelled",
1557
- name: "Cancelled",
1558
- stackId: "r",
1559
- fill: "#F87171",
1560
- stroke: "#EF4444",
1561
- fillOpacity: 0.75
1562
- }
1563
- )
1564
- ]
1565
- }
1566
- ) }) })
1567
- ] })
1568
- ] }) : null
1569
- ] })
1570
- }
1571
- ) }),
1572
- /* @__PURE__ */ jsxs("div", { className: "col-span-12 flex flex-col gap-2 xl:col-span-6", children: [
1573
- /* @__PURE__ */ jsx(
1574
- AnalyticsSection,
1575
- {
1576
- variant: "atlas",
1577
- title: "Pulse & range",
1578
- description: "Window totals for the selected range.",
1579
- children: /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 gap-2", children: quickPulseMetrics.map((metric) => /* @__PURE__ */ jsxs(
1580
- "div",
1581
- {
1582
- className: `rounded-lg border border-ui-border-base bg-ui-bg-base px-2 py-2 shadow-sm ${metric.accentClassName}`.trim(),
1583
- children: [
1584
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: metric.label }),
1585
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base mt-0.5 text-sm font-semibold tracking-tight", children: metric.value }),
1586
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted mt-0.5 text-[9px] leading-snug", children: metric.helper })
1587
- ]
1588
- },
1589
- metric.label
1590
- )) })
1591
- }
1592
- ),
1593
- /* @__PURE__ */ jsx(
1594
- AnalyticsSection,
1595
- {
1596
- variant: "atlas",
1597
- title: "Order → fulfillment funnel",
1598
- description: `Stages by order created date (UTC), same range as Revenue & orders (${((_e = OVER_TIME_PERIODS.find((p) => p.value === overTimePeriod)) == null ? void 0 : _e.label) ?? "period"}). Not storefront visitors.`,
1599
- children: overTimeLoading ? /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsx("div", { className: "flex min-h-[120px] items-center justify-center py-3", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "Loading…" }) }) }) : overTimeError ? /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsx("div", { className: "flex min-h-[120px] items-center justify-center px-2 py-3", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger text-center text-xs", children: overTimeError }) }) }) : funnelTimeSeriesRows.length > 0 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2", children: [
1600
- /* @__PURE__ */ jsxs(AnalyticsChartSurface, { variant: "atlas", children: [
1601
- /* @__PURE__ */ jsx(Text, { className: "mb-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-ui-fg-muted", children: "Stage counts (time series)" }),
1602
- /* @__PURE__ */ jsx("div", { className: "h-[min(200px,30vh)] min-h-[168px] w-full", children: /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxs(
1603
- LineChart,
1604
- {
1605
- data: funnelTimeSeriesRows,
1606
- margin: { top: 4, right: 8, left: 0, bottom: 4 },
1607
- children: [
1608
- /* @__PURE__ */ jsx(
1609
- CartesianGrid,
1610
- {
1611
- strokeDasharray: "3 3",
1612
- stroke: "rgba(148,163,184,0.2)"
1613
- }
1614
- ),
1615
- /* @__PURE__ */ jsx(
1616
- XAxis,
1617
- {
1618
- dataKey: "date",
1619
- tick: CHART_AXIS_TICK_SM$1,
1620
- stroke: CHART_AXIS_LINE$2,
1621
- tickLine: { stroke: CHART_AXIS_LINE$2 },
1622
- tickFormatter: (value) => {
1623
- const row = dailyOrders.find((r) => r.date === value);
1624
- return (row == null ? void 0 : row.label) ?? formatChartLabel$2(String(value));
1625
- }
1626
- }
1627
- ),
1628
- /* @__PURE__ */ jsx(
1629
- YAxis,
1630
- {
1631
- tick: CHART_AXIS_TICK_SM$1,
1632
- stroke: CHART_AXIS_LINE$2,
1633
- tickLine: { stroke: CHART_AXIS_LINE$2 },
1634
- width: 28,
1635
- allowDecimals: false,
1636
- tickFormatter: (v) => Math.floor(Number(v) || 0).toLocaleString()
1637
- }
1638
- ),
1639
- /* @__PURE__ */ jsx(
1640
- Tooltip,
1641
- {
1642
- content: ({ active, payload, label }) => {
1643
- var _a2;
1644
- return active && (payload == null ? void 0 : payload.length) ? /* @__PURE__ */ jsx(
1645
- AnalyticsTooltipCard,
1646
- {
1647
- variant: "compact",
1648
- title: typeof label === "string" ? ((_a2 = dailyOrders.find((r) => r.date === label)) == null ? void 0 : _a2.label) ?? formatChartLabel$2(label) : String(label),
1649
- children: payload.map((p) => /* @__PURE__ */ jsxs("div", { children: [
1650
- String(p.name),
1651
- ":",
1652
- " ",
1653
- /* @__PURE__ */ jsx("strong", { children: Math.floor(Number(p.value) || 0).toLocaleString() })
1654
- ] }, String(p.dataKey)))
1655
- }
1656
- ) : null;
1657
- }
1658
- }
1659
- ),
1660
- /* @__PURE__ */ jsx(
1661
- Legend,
1662
- {
1663
- wrapperStyle: { fontSize: 9, color: "#e5e7eb", paddingTop: 4 },
1664
- iconType: "circle",
1665
- iconSize: 6
1666
- }
1667
- ),
1668
- /* @__PURE__ */ jsx(
1669
- Line,
1670
- {
1671
- type: "natural",
1672
- dataKey: "placed",
1673
- name: "Placed",
1674
- stroke: "#6366F1",
1675
- strokeWidth: 2,
1676
- dot: false
1677
- }
1678
- ),
1679
- /* @__PURE__ */ jsx(
1680
- Line,
1681
- {
1682
- type: "natural",
1683
- dataKey: "not_cancelled",
1684
- name: "Not cancelled",
1685
- stroke: "#22d3ee",
1686
- strokeWidth: 2,
1687
- dot: false
1688
- }
1689
- ),
1690
- /* @__PURE__ */ jsx(
1691
- Line,
1692
- {
1693
- type: "natural",
1694
- dataKey: "shipped",
1695
- name: "Shipped",
1696
- stroke: "#F59E0B",
1697
- strokeWidth: 2,
1698
- dot: false
1699
- }
1700
- ),
1701
- /* @__PURE__ */ jsx(
1702
- Line,
1703
- {
1704
- type: "natural",
1705
- dataKey: "delivered",
1706
- name: "Delivered",
1707
- stroke: "#10B981",
1708
- strokeWidth: 2,
1709
- dot: false
1710
- }
1711
- )
1712
- ]
1713
- }
1714
- ) }) })
1715
- ] }),
1716
- /* @__PURE__ */ jsxs(AnalyticsChartSurface, { variant: "atlas", children: [
1717
- /* @__PURE__ */ jsx(Text, { className: "mb-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-ui-fg-muted", children: "Stage conversion (% of prior stage, same buckets)" }),
1718
- /* @__PURE__ */ jsx("div", { className: "h-[min(168px,26vh)] min-h-[140px] w-full", children: /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxs(
1719
- LineChart,
1720
- {
1721
- data: funnelTimeSeriesRows,
1722
- margin: { top: 4, right: 8, left: 0, bottom: 4 },
1723
- children: [
1724
- /* @__PURE__ */ jsx(
1725
- CartesianGrid,
1726
- {
1727
- strokeDasharray: "3 3",
1728
- stroke: "rgba(148,163,184,0.2)"
1729
- }
1730
- ),
1731
- /* @__PURE__ */ jsx(
1732
- XAxis,
1733
- {
1734
- dataKey: "date",
1735
- tick: CHART_AXIS_TICK_SM$1,
1736
- stroke: CHART_AXIS_LINE$2,
1737
- tickLine: { stroke: CHART_AXIS_LINE$2 },
1738
- tickFormatter: (value) => {
1739
- const row = dailyOrders.find((r) => r.date === value);
1740
- return (row == null ? void 0 : row.label) ?? formatChartLabel$2(String(value));
1741
- }
1742
- }
1743
- ),
1744
- /* @__PURE__ */ jsx(
1745
- YAxis,
1746
- {
1747
- domain: [0, 100],
1748
- tick: CHART_AXIS_TICK_SM$1,
1749
- stroke: CHART_AXIS_LINE$2,
1750
- tickLine: { stroke: CHART_AXIS_LINE$2 },
1751
- width: 36,
1752
- tickFormatter: (v) => `${Math.round(Number(v) || 0)}%`
1753
- }
1754
- ),
1755
- /* @__PURE__ */ jsx(
1756
- Tooltip,
1757
- {
1758
- content: ({ active, payload, label }) => {
1759
- var _a2;
1760
- return active && (payload == null ? void 0 : payload.length) ? /* @__PURE__ */ jsx(
1761
- AnalyticsTooltipCard,
1762
- {
1763
- variant: "compact",
1764
- title: typeof label === "string" ? ((_a2 = dailyOrders.find((r) => r.date === label)) == null ? void 0 : _a2.label) ?? formatChartLabel$2(label) : String(label),
1765
- children: payload.map((p) => /* @__PURE__ */ jsxs("div", { children: [
1766
- String(p.name),
1767
- ":",
1768
- " ",
1769
- /* @__PURE__ */ jsx("strong", { children: formatPercent(Number(p.value) || 0) })
1770
- ] }, String(p.dataKey)))
1771
- }
1772
- ) : null;
1773
- }
1774
- }
1775
- ),
1776
- /* @__PURE__ */ jsx(
1777
- Legend,
1778
- {
1779
- wrapperStyle: { fontSize: 9, color: "#e5e7eb", paddingTop: 4 },
1780
- iconType: "circle",
1781
- iconSize: 6
1782
- }
1783
- ),
1784
- /* @__PURE__ */ jsx(
1785
- Line,
1786
- {
1787
- type: "natural",
1788
- dataKey: "pct_not_cancelled",
1789
- name: "Not cancelled / placed",
1790
- stroke: "#6366F1",
1791
- strokeWidth: 2,
1792
- dot: false
1793
- }
1794
- ),
1795
- /* @__PURE__ */ jsx(
1796
- Line,
1797
- {
1798
- type: "natural",
1799
- dataKey: "pct_shipped_of_active",
1800
- name: "Shipped / not cancelled",
1801
- stroke: "#F59E0B",
1802
- strokeWidth: 2,
1803
- dot: false
1804
- }
1805
- ),
1806
- /* @__PURE__ */ jsx(
1807
- Line,
1808
- {
1809
- type: "natural",
1810
- dataKey: "pct_delivered_of_shipped",
1811
- name: "Delivered / shipped",
1812
- stroke: "#10B981",
1813
- strokeWidth: 2,
1814
- dot: false
1815
- }
1816
- )
1817
- ]
1818
- }
1819
- ) }) })
1820
- ] })
1821
- ] }) : /* @__PURE__ */ jsx(
1822
- EmptyAnalyticsPanel$1,
1823
- {
1824
- title: "No funnel data",
1825
- description: "No orders in this range to chart."
1826
- }
1827
- )
1828
- }
1829
- )
1830
- ] })
1831
- ] }),
1832
- /* @__PURE__ */ jsxs("div", { className: "mt-3 space-y-1.5", children: [
1833
- /* @__PURE__ */ jsx("div", { className: "px-0.5", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.16em]", children: "Operational signals" }) }),
1834
- /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 gap-2 lg:grid-cols-3 xl:grid-cols-6", children: secondaryStats.map((stat) => /* @__PURE__ */ jsx(
1835
- AnalyticsStatCard,
1836
- {
1837
- label: stat.label,
1838
- value: stat.value,
1839
- helper: stat.helper,
1840
- variant: "compact"
1841
- },
1842
- stat.label
1843
- )) })
1844
- ] }),
1845
- /* @__PURE__ */ jsxs("div", { className: "mt-3 grid grid-cols-1 items-start gap-2 xl:grid-cols-12", children: [
1846
- /* @__PURE__ */ jsx(
1847
- AnalyticsSection,
1848
- {
1849
- variant: "atlas",
1850
- className: "xl:col-span-7",
1851
- title: "Order outcomes",
1852
- description: "Delivered, cancelled, exchanges, and returns per bucket — same window as Revenue & orders.",
1853
- children: /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsx("div", { className: "h-[176px] sm:h-[196px]", children: overTimeLoading ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "Loading…" }) }) : overTimeError ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger text-xs", children: overTimeError }) }) : !outcomesTimeSeriesHasPoints ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "No outcome events in this range." }) }) : /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxs(
1854
- LineChart,
1855
- {
1856
- data: dailyOrders,
1857
- margin: { top: 4, right: 8, left: 0, bottom: 0 },
1858
- children: [
1859
- /* @__PURE__ */ jsx(
1860
- CartesianGrid,
1861
- {
1862
- stroke: "rgba(148,163,184,0.14)",
1863
- strokeDasharray: "3 3",
1864
- vertical: false
1865
- }
1866
- ),
1867
- /* @__PURE__ */ jsx(
1868
- XAxis,
1869
- {
1870
- dataKey: "date",
1871
- tick: CHART_AXIS_TICK$2,
1872
- tickLine: false,
1873
- axisLine: false,
1874
- tickFormatter: (value) => {
1875
- const dateStr = typeof value === "string" ? value : String(value);
1876
- const row = dailyOrders.find((d) => d.date === dateStr);
1877
- return (row == null ? void 0 : row.label) ?? formatChartLabel$2(dateStr);
1878
- }
1879
- }
1880
- ),
1881
- /* @__PURE__ */ jsx(
1882
- YAxis,
1883
- {
1884
- width: 28,
1885
- tick: CHART_AXIS_TICK$2,
1886
- tickLine: false,
1887
- axisLine: false,
1888
- allowDecimals: false,
1889
- tickFormatter: (value) => Math.floor(Number(value) || 0).toLocaleString()
1890
- }
1891
- ),
1892
- /* @__PURE__ */ jsx(
1893
- Tooltip,
1894
- {
1895
- content: /* @__PURE__ */ jsx(OutcomesTrendTooltip, {}),
1896
- cursor: { stroke: "rgba(148,163,184,0.35)", strokeWidth: 1 }
1897
- }
1898
- ),
1899
- /* @__PURE__ */ jsx(
1900
- Legend,
1901
- {
1902
- wrapperStyle: { fontSize: 9, paddingTop: 0 },
1903
- iconType: "circle",
1904
- iconSize: 6
1905
- }
1906
- ),
1907
- /* @__PURE__ */ jsx(
1908
- Line,
1909
- {
1910
- type: "natural",
1911
- dataKey: "delivered_count",
1912
- name: "Delivered",
1913
- stroke: STATUS_BAR_COLORS.delivered,
1914
- strokeWidth: 2,
1915
- dot: false
1916
- }
1917
- ),
1918
- /* @__PURE__ */ jsx(
1919
- Line,
1920
- {
1921
- type: "natural",
1922
- dataKey: "cancelled_count",
1923
- name: "Cancelled",
1924
- stroke: STATUS_BAR_COLORS.cancelled,
1925
- strokeWidth: 2,
1926
- dot: false
1927
- }
1928
- ),
1929
- /* @__PURE__ */ jsx(
1930
- Line,
1931
- {
1932
- type: "natural",
1933
- dataKey: "exchange_count",
1934
- name: "Exchanges",
1935
- stroke: STATUS_BAR_COLORS.exchange,
1936
- strokeWidth: 2,
1937
- dot: false
1938
- }
1939
- ),
1940
- /* @__PURE__ */ jsx(
1941
- Line,
1942
- {
1943
- type: "natural",
1944
- dataKey: "return_count",
1945
- name: "Returns",
1946
- stroke: STATUS_BAR_COLORS.return,
1947
- strokeWidth: 2,
1948
- dot: false
1949
- }
1950
- )
1951
- ]
1952
- }
1953
- ) }) }) })
1954
- }
1955
- ),
1956
- /* @__PURE__ */ jsx(
1957
- AnalyticsSection,
1958
- {
1959
- variant: "atlas",
1960
- className: "xl:col-span-5",
1961
- title: "Recent orders (7 days)",
1962
- description: "Daily order count vs 7-day average — time series.",
1963
- children: /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
1964
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-1.5", children: [
1965
- /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-ui-border-base bg-ui-bg-subtle/50 px-2 py-2", children: [
1966
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: "Today" }),
1967
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-base font-semibold tracking-tight", children: (todayPoint == null ? void 0 : todayPoint.orders_count.toLocaleString()) ?? "0" })
1968
- ] }),
1969
- /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-ui-border-base bg-ui-bg-subtle/50 px-2 py-2", children: [
1970
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: "7-day avg" }),
1971
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-base font-semibold tracking-tight", children: todayOrdersAverage.toFixed(1) })
1972
- ] })
1973
- ] }),
1974
- /* @__PURE__ */ jsx("div", { className: "h-[140px] sm:h-[156px]", children: todayContextLoading ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "Loading…" }) }) : todayContextError ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger text-xs", children: todayContextError }) }) : todayChartData.length === 0 ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "No recent activity." }) }) : /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxs(
1975
- ComposedChart,
1976
- {
1977
- data: todayChartData,
1978
- margin: { top: 4, right: 4, left: -4, bottom: 0 },
1979
- children: [
1980
- /* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsxs("linearGradient", { id: "todayOrdersFill", x1: "0", y1: "0", x2: "0", y2: "1", children: [
1981
- /* @__PURE__ */ jsx("stop", { offset: "0%", stopColor: "#3b82f6", stopOpacity: 0.2 }),
1982
- /* @__PURE__ */ jsx("stop", { offset: "100%", stopColor: "#3b82f6", stopOpacity: 0 })
1983
- ] }) }),
1984
- /* @__PURE__ */ jsx(
1985
- CartesianGrid,
1986
- {
1987
- stroke: "rgba(148,163,184,0.14)",
1988
- strokeDasharray: "3 3",
1989
- vertical: false
1990
- }
1991
- ),
1992
- /* @__PURE__ */ jsx(
1993
- XAxis,
1994
- {
1995
- dataKey: "date",
1996
- tick: CHART_AXIS_TICK$2,
1997
- tickLine: false,
1998
- axisLine: false,
1999
- tickFormatter: formatChartLabel$2
2000
- }
2001
- ),
2002
- /* @__PURE__ */ jsx(
2003
- YAxis,
2004
- {
2005
- width: 28,
2006
- tick: CHART_AXIS_TICK$2,
2007
- tickLine: false,
2008
- axisLine: false,
2009
- allowDecimals: false,
2010
- tickFormatter: (value) => Math.floor(Number(value) || 0).toLocaleString()
2011
- }
2012
- ),
2013
- /* @__PURE__ */ jsx(Tooltip, { content: /* @__PURE__ */ jsx(OrdersTodayTooltip, {}), cursor: { stroke: "rgba(148,163,184,0.35)", strokeWidth: 1 } }),
2014
- /* @__PURE__ */ jsx(
2015
- ReferenceLine,
2016
- {
2017
- y: todayOrdersAverage,
2018
- stroke: "rgba(148,163,184,0.65)",
2019
- strokeDasharray: "4 4"
2020
- }
2021
- ),
2022
- /* @__PURE__ */ jsx(
2023
- Area,
2024
- {
2025
- type: "natural",
2026
- dataKey: "orders_count",
2027
- stroke: "none",
2028
- fill: "url(#todayOrdersFill)",
2029
- isAnimationActive: false
2030
- }
2031
- ),
2032
- /* @__PURE__ */ jsx(
2033
- Line,
2034
- {
2035
- type: "natural",
2036
- dataKey: "orders_count",
2037
- name: "Orders",
2038
- stroke: "#3b82f6",
2039
- strokeWidth: 2,
2040
- dot: (props) => {
2041
- const { cx, cy, payload } = props;
2042
- if (payload && typeof payload === "object" && "isToday" in payload && payload.isToday) {
2043
- return /* @__PURE__ */ jsx(
2044
- "circle",
2045
- {
2046
- cx,
2047
- cy,
2048
- r: 4,
2049
- fill: STATUS_BAR_COLORS.today,
2050
- stroke: "var(--medusa-color-ui-bg-base)",
2051
- strokeWidth: 1
2052
- }
2053
- );
2054
- }
2055
- return /* @__PURE__ */ jsx("circle", { cx, cy, r: 0, fill: "transparent" });
2056
- }
2057
- }
2058
- )
2059
- ]
2060
- }
2061
- ) }) }),
2062
- /* @__PURE__ */ jsxs(Container, { className: "rounded-lg border border-ui-border-base bg-ui-bg-subtle/40 px-2 py-1.5 shadow-sm", children: [
2063
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: "Note" }),
2064
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-[11px] leading-snug", children: todayDelta === null ? "Compares the latest day to the 7-day mean." : todayDelta >= 0 ? `Latest day is ${todayDelta.toFixed(1)} above the 7-day average.` : `Latest day is ${Math.abs(todayDelta).toFixed(1)} below the 7-day average.` })
2065
- ] })
2066
- ] }) })
2067
- }
2068
- )
2069
- ] }),
2070
- /* @__PURE__ */ jsxs("div", { className: "mt-3 grid grid-cols-1 items-start gap-3 xl:grid-cols-12", children: [
2071
- /* @__PURE__ */ jsx(
2072
- AnalyticsSection,
2073
- {
2074
- variant: "atlas",
2075
- className: "xl:col-span-8",
2076
- title: "Sales breakdown",
2077
- description: salesBreakdownDescription,
2078
- actionsBare: true,
2079
- actions: /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-stretch gap-1 sm:flex-row sm:items-center sm:gap-2", children: [
2080
- /* @__PURE__ */ jsx(
2081
- Label,
2082
- {
2083
- htmlFor: "sales-breakdown-granularity",
2084
- className: "shrink-0 text-ui-fg-muted text-xs font-medium",
2085
- children: "Breakdown"
2086
- }
2087
- ),
2088
- /* @__PURE__ */ jsx(
2089
- "select",
2090
- {
2091
- id: "sales-breakdown-granularity",
2092
- value: salesGranularity,
2093
- onChange: (e) => {
2094
- const v = e.target.value;
2095
- if (v === "hour" || v === "day" || v === "week" || v === "month") {
2096
- setSalesGranularity(v);
2097
- }
2098
- },
2099
- className: SELECT_CLASS_NAME$2,
2100
- "aria-label": "Sales breakdown time bucket",
2101
- children: SALES_GRANULARITY_TABS.map((tab) => /* @__PURE__ */ jsx("option", { value: tab.value, children: tab.value === "hour" ? "Hour (last 24h)" : tab.value === "day" ? "Day (last 7 days)" : tab.value === "week" ? "Week (last 7 weeks)" : "Month (last 12 months)" }, tab.value))
2102
- }
2103
- )
2104
- ] }),
2105
- children: salesBreakdownBody
2106
- }
2107
- ),
2108
- /* @__PURE__ */ jsx(
2109
- AnalyticsSection,
2110
- {
2111
- variant: "atlas",
2112
- className: "xl:col-span-4",
2113
- title: "Placed orders vs drafts",
2114
- description: "Window order count vs current open draft orders (admin). Not storefront cart abandonment.",
2115
- children: insightsLoading ? /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsx("div", { className: "flex min-h-[100px] items-center justify-center py-4", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "Loading…" }) }) }) : insightsError ? /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsx("div", { className: "flex min-h-[100px] items-center justify-center px-2 py-4", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger text-center text-xs", children: insightsError }) }) }) : ordersVsDraftsPie.some((s) => s.value > 0) ? /* @__PURE__ */ jsxs(AnalyticsChartSurface, { variant: "atlas", children: [
2116
- /* @__PURE__ */ jsx("div", { className: "h-[min(176px,28vh)] min-h-[148px] w-full", children: /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxs(PieChart, { margin: { top: 2, bottom: 2, left: 2, right: 2 }, children: [
2117
- /* @__PURE__ */ jsx(
2118
- Pie,
2119
- {
2120
- data: ordersVsDraftsPie,
2121
- dataKey: "value",
2122
- nameKey: "name",
2123
- cx: "50%",
2124
- cy: "46%",
2125
- innerRadius: 40,
2126
- outerRadius: 58,
2127
- paddingAngle: 2,
2128
- children: ordersVsDraftsPie.map((slice, i) => /* @__PURE__ */ jsx(
2129
- Cell,
2130
- {
2131
- fill: PIE_PALETTE[i % PIE_PALETTE.length]
2132
- },
2133
- slice.key
2134
- ))
2135
- }
2136
- ),
2137
- /* @__PURE__ */ jsx(
2138
- Tooltip,
2139
- {
2140
- content: ({ active, payload }) => {
2141
- var _a2, _b2;
2142
- return active && (payload == null ? void 0 : payload.length) ? /* @__PURE__ */ jsx(AnalyticsTooltipCard, { variant: "compact", title: String(((_a2 = payload[0]) == null ? void 0 : _a2.name) ?? ""), children: /* @__PURE__ */ jsxs("div", { children: [
2143
- "Count:",
2144
- " ",
2145
- /* @__PURE__ */ jsx("strong", { children: Math.floor(
2146
- Number((_b2 = payload[0]) == null ? void 0 : _b2.value) || 0
2147
- ).toLocaleString() })
2148
- ] }) }) : null;
2149
- }
2150
- }
2151
- ),
2152
- /* @__PURE__ */ jsx(
2153
- Legend,
2154
- {
2155
- wrapperStyle: { fontSize: 9, paddingTop: 0 },
2156
- verticalAlign: "bottom",
2157
- height: 22,
2158
- iconType: "circle"
2159
- }
2160
- )
2161
- ] }) }) }),
2162
- (ordersInsights == null ? void 0 : ordersInsights.drafts.available) === false ? /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted mt-0.5 px-0.5 text-[10px] leading-snug", children: "Draft totals need draft_order remote query access." }) : null
2163
- ] }) : /* @__PURE__ */ jsx(
2164
- EmptyAnalyticsPanel$1,
2165
- {
2166
- title: "Nothing to compare",
2167
- description: "No placed orders and no draft rows in this snapshot."
2168
- }
2169
- )
2170
- }
2171
- )
2172
- ] })
2173
- ] })
2174
- ] }) });
2175
- }
2176
- const KPI_ICON_BG$1 = {
2177
- green: "bg-emerald-500/20",
2178
- blue: "bg-sky-500/20",
2179
- purple: "bg-violet-500/20",
2180
- amber: "bg-amber-500/20"
2181
- };
2182
- const KPI_ICONS$1 = {
2183
- green: UsersSolid,
2184
- blue: User,
2185
- purple: UserGroup,
2186
- amber: Trash
2187
- };
2188
- function AtlasKpiCard$1({
2189
- label,
2190
- value,
2191
- helper,
2192
- accent
2193
- }) {
2194
- const Icon = KPI_ICONS$1[accent];
2195
- return /* @__PURE__ */ jsxs("div", { className: "flex h-full min-h-[88px] min-w-0 flex-col rounded-xl border border-ui-border-base/80 bg-ui-bg-subtle/25 p-3 shadow-sm", children: [
2196
- /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2", children: [
2197
- /* @__PURE__ */ jsx(Text, { className: "min-w-0 flex-1 text-left text-xs font-medium leading-snug text-ui-fg-base", children: label }),
2198
- /* @__PURE__ */ jsx(
2199
- "div",
2200
- {
2201
- className: `flex h-7 w-7 shrink-0 items-center justify-center rounded-lg ${KPI_ICON_BG$1[accent]}`,
2202
- "aria-hidden": true,
2203
- children: /* @__PURE__ */ jsx(Icon, { className: "h-3.5 w-3.5 text-ui-fg-base" })
2204
- }
2205
- )
2206
- ] }),
2207
- /* @__PURE__ */ jsx("div", { className: "mt-2 text-lg font-semibold tabular-nums tracking-tight text-ui-fg-base sm:text-xl", children: value }),
2208
- helper ? /* @__PURE__ */ jsx(Text, { className: "mt-2 text-[11px] leading-snug text-ui-fg-muted", children: helper }) : null
2209
- ] });
2210
- }
2211
- function CustomersOverTimeTooltip({
2212
- active,
2213
- payload,
2214
- label
2215
- }) {
2216
- var _a, _b, _c;
2217
- if (!active || !(payload == null ? void 0 : payload.length)) return null;
2218
- const row = (_a = payload[0]) == null ? void 0 : _a.payload;
2219
- const displayLabel = (row == null ? void 0 : row.label) ?? (label ? new Date(label).toLocaleDateString() : label);
2220
- const registered = Math.floor(((_b = payload.find((p) => p.name === "Registered")) == null ? void 0 : _b.value) ?? 0);
2221
- const guest = Math.floor(((_c = payload.find((p) => p.name === "Guest")) == null ? void 0 : _c.value) ?? 0);
2222
- return /* @__PURE__ */ jsxs(AnalyticsTooltipCard, { title: String(displayLabel ?? ""), children: [
2223
- /* @__PURE__ */ jsxs("div", { children: [
2224
- "Registered: ",
2225
- /* @__PURE__ */ jsx("strong", { children: registered.toLocaleString() })
2226
- ] }),
2227
- /* @__PURE__ */ jsxs("div", { children: [
2228
- "Guest: ",
2229
- /* @__PURE__ */ jsx("strong", { children: guest.toLocaleString() })
2230
- ] })
2231
- ] });
2232
- }
2233
- function MixPieTooltip({
2234
- active,
2235
- payload
2236
- }) {
2237
- if (!active || !(payload == null ? void 0 : payload.length)) return null;
2238
- const row = payload[0];
2239
- return /* @__PURE__ */ jsx(AnalyticsTooltipCard, { variant: "compact", title: String(row.name ?? ""), children: /* @__PURE__ */ jsxs("div", { children: [
2240
- "Count: ",
2241
- /* @__PURE__ */ jsx("strong", { children: Math.floor(Number(row.value) || 0).toLocaleString() })
2242
- ] }) });
2243
- }
2244
- const COUNT_DAY_PRESETS = [
2245
- { value: "all", label: "All time" },
2246
- { value: "0", label: "Today" },
2247
- { value: "7", label: "Last 7 days" },
2248
- { value: "30", label: "Last 30 days" },
2249
- { value: "90", label: "Last 90 days" }
2250
- ];
2251
- const GRAPH_PERIODS$1 = [
2252
- { value: "one_week", label: "One week" },
2253
- { value: "one_month", label: "One month" },
2254
- { value: "one_year", label: "One year" }
2255
- ];
2256
- const REGISTERED_COLOR = "var(--medusa-color-ui-fg-interactive)";
2257
- const GUEST_COLOR = "#6B7280";
2258
- const CHART_AXIS_TICK$1 = { fontSize: 10, fill: "#e5e7eb" };
2259
- const CHART_AXIS_LINE$1 = "#94a3b8";
2260
- const SELECT_CLASS_NAME$1 = "h-9 w-full min-w-[8rem] max-w-full cursor-pointer appearance-none rounded border border-ui-border-base bg-ui-bg-base py-1.5 pl-3 pr-8 text-xs text-ui-fg-base outline-none transition focus:ring-2 focus:ring-ui-fg-interactive sm:w-auto sm:min-w-[132px] sm:max-w-[220px]";
2261
- function formatChartLabel$1(value) {
2262
- if (!value) return "";
2263
- const parsed = new Date(value);
2264
- if (Number.isNaN(parsed.getTime())) return value;
2265
- return `${parsed.getUTCMonth() + 1}/${parsed.getUTCDate()}`;
2266
- }
2267
- function CustomersDashboard() {
2268
- var _a, _b, _c;
2269
- const [data, setData] = useState(null);
2270
- const [loading, setLoading] = useState(true);
2271
- const [error, setError] = useState(null);
2272
- const [countDays, setCountDays] = useState("all");
2273
- const [series, setSeries] = useState([]);
2274
- const [graphPeriod, setGraphPeriod] = useState("one_week");
2275
- const [graphLoading, setGraphLoading] = useState(true);
2276
- const [graphError, setGraphError] = useState(null);
2277
- const [repeatStats, setRepeatStats] = useState(null);
2278
- const [repeatLoading, setRepeatLoading] = useState(true);
2279
- const [repeatError, setRepeatError] = useState(null);
2280
- useEffect(() => {
2281
- let cancelled = false;
2282
- setLoading(true);
2283
- setError(null);
2284
- const url = `/admin/analytics/customers-summary?days=${countDays}`;
2285
- fetch(url, { credentials: "include" }).then((res) => {
2286
- if (!res.ok) throw new Error(res.statusText);
2287
- return res.json();
2288
- }).then((body) => {
2289
- if (!cancelled) setData(body);
2290
- }).catch((e) => {
2291
- if (!cancelled) setError(e instanceof Error ? e.message : String(e));
2292
- }).finally(() => {
2293
- if (!cancelled) setLoading(false);
2294
- });
2295
- return () => {
2296
- cancelled = true;
2297
- };
2298
- }, [countDays]);
2299
- useEffect(() => {
2300
- let cancelled = false;
2301
- setGraphLoading(true);
2302
- setGraphError(null);
2303
- const url = `/admin/analytics/customers-over-time?period=${graphPeriod}`;
2304
- fetch(url, { credentials: "include" }).then((res) => {
2305
- if (!res.ok) throw new Error(res.statusText);
2306
- return res.json();
2307
- }).then((body) => {
2308
- if (!cancelled) setSeries(body.series ?? []);
2309
- }).catch((e) => {
2310
- if (!cancelled) setGraphError(e instanceof Error ? e.message : String(e));
2311
- }).finally(() => {
2312
- if (!cancelled) setGraphLoading(false);
2313
- });
2314
- return () => {
2315
- cancelled = true;
2316
- };
2317
- }, [graphPeriod]);
2318
- useEffect(() => {
2319
- let cancelled = false;
2320
- setRepeatLoading(true);
2321
- setRepeatError(null);
2322
- fetch(`/admin/analytics/repeat-customers?days=${countDays}`, {
2323
- credentials: "include"
2324
- }).then((res) => {
2325
- if (!res.ok) throw new Error(res.statusText);
2326
- return res.json();
2327
- }).then((body) => {
2328
- if (!cancelled) setRepeatStats(body);
2329
- }).catch((e) => {
2330
- if (!cancelled) setRepeatError(e instanceof Error ? e.message : String(e));
2331
- }).finally(() => {
2332
- if (!cancelled) setRepeatLoading(false);
2333
- });
2334
- return () => {
2335
- cancelled = true;
2336
- };
2337
- }, [countDays]);
2338
- const selectedCountPeriodLabel = ((_a = COUNT_DAY_PRESETS.find((p) => p.value === countDays)) == null ? void 0 : _a.label) ?? "All time";
2339
- const guestRegisteredPieData = useMemo(() => {
2340
- const g = Math.max(0, Math.floor((data == null ? void 0 : data.guestCount) ?? 0));
2341
- const r = Math.max(0, Math.floor((data == null ? void 0 : data.registeredCount) ?? 0));
2342
- return [
2343
- { name: "Guest checkout", value: g, key: "guest" },
2344
- { name: "Registered", value: r, key: "registered" }
2345
- ].filter((s) => s.value > 0);
2346
- }, [data]);
2347
- const seriesWindowTotals = useMemo(() => {
2348
- let registered = 0;
2349
- let guest = 0;
2350
- for (const row of series) {
2351
- registered += Math.max(0, Math.floor(row.registered_count));
2352
- guest += Math.max(0, Math.floor(row.guest_count));
2353
- }
2354
- return {
2355
- registered,
2356
- guest,
2357
- points: series.length
2358
- };
2359
- }, [series]);
2360
- const primaryStats = data ? [
2361
- {
2362
- label: "Guest customers",
2363
- value: Math.floor(data.guestCount).toLocaleString(),
2364
- helper: selectedCountPeriodLabel,
2365
- accent: "blue"
2366
- },
2367
- {
2368
- label: "Registered customers",
2369
- value: Math.floor(data.registeredCount).toLocaleString(),
2370
- helper: selectedCountPeriodLabel,
2371
- accent: "purple"
2372
- },
2373
- {
2374
- label: "Overall customers",
2375
- value: Math.floor(data.totalCount).toLocaleString(),
2376
- helper: "Guest + registered",
2377
- accent: "green"
2378
- },
2379
- {
2380
- label: "Deleted accounts",
2381
- value: (data.deletedAccountsCount ?? 0).toLocaleString(),
2382
- helper: "Removed profiles",
2383
- accent: "amber"
2384
- }
2385
- ] : [];
2386
- if (loading) {
2387
- return /* @__PURE__ */ jsx(
2388
- "div",
2389
- {
2390
- className: "flex min-h-[200px] items-center justify-center",
2391
- role: "status",
2392
- "aria-label": "Loading analytics",
2393
- children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted", children: "Loading…" })
2394
- }
2395
- );
2396
- }
2397
- if (error || !data) {
2398
- return /* @__PURE__ */ jsx(Container, { className: "p-6", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger", children: error ?? "Failed to load analytics" }) });
2399
- }
2400
- return /* @__PURE__ */ jsx(AnalyticsDashboardShell, { className: "w-full min-w-0 max-w-full", children: /* @__PURE__ */ jsxs("div", { className: "w-full min-w-0 max-w-full overflow-hidden rounded-2xl border border-ui-border-base/80 bg-ui-bg-base shadow-sm", children: [
2401
- /* @__PURE__ */ jsx(
2402
- AnalyticsDashboardHeader,
2403
- {
2404
- variant: "premium",
2405
- appearance: "inset",
2406
- actionsBare: true,
2407
- title: "Customers",
2408
- description: "Acquisition mix, repeat behavior, and signups over time — aligned with Orders and Products analytics.",
2409
- actions: /* @__PURE__ */ jsxs(Fragment, { children: [
2410
- /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
2411
- /* @__PURE__ */ jsx(
2412
- Label,
2413
- {
2414
- htmlFor: "customers-count-period",
2415
- className: "shrink-0 text-ui-fg-muted text-xs font-medium",
2416
- children: "Period"
2417
- }
2418
- ),
2419
- /* @__PURE__ */ jsx(
2420
- "select",
2421
- {
2422
- id: "customers-count-period",
2423
- value: countDays,
2424
- onChange: (e) => setCountDays(e.target.value),
2425
- className: SELECT_CLASS_NAME$1,
2426
- children: COUNT_DAY_PRESETS.map((p) => /* @__PURE__ */ jsx("option", { value: p.value, children: p.label }, p.value))
2427
- }
2428
- )
2429
- ] }),
2430
- countDays !== "all" ? /* @__PURE__ */ jsx(
2431
- "button",
2432
- {
2433
- type: "button",
2434
- onClick: () => setCountDays("all"),
2435
- className: "text-xs text-ui-fg-muted transition-colors hover:text-ui-fg-base",
2436
- "aria-label": "Show all customers (clear filter)",
2437
- children: "Clear period"
2438
- }
2439
- ) : null
2440
- ] })
2441
- }
2442
- ),
2443
- /* @__PURE__ */ jsxs("div", { className: "space-y-2 p-2 pt-0 sm:p-3 sm:pt-0 md:p-4 md:pt-0", children: [
2444
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
2445
- /* @__PURE__ */ jsx("div", { className: "px-0.5", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.16em]", children: "Customer overview" }) }),
2446
- /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 gap-2 lg:grid-cols-4", children: primaryStats.map((stat) => /* @__PURE__ */ jsx(
2447
- AtlasKpiCard$1,
2448
- {
2449
- label: stat.label,
2450
- value: stat.value,
2451
- helper: stat.helper,
2452
- accent: stat.accent
2453
- },
2454
- stat.label
2455
- )) })
2456
- ] }),
2457
- /* @__PURE__ */ jsxs("div", { className: "mt-2 grid grid-cols-12 gap-2 lg:items-stretch", children: [
2458
- /* @__PURE__ */ jsx("div", { className: "col-span-12 flex min-h-0 min-w-0 lg:col-span-5", children: /* @__PURE__ */ jsx(
2459
- AnalyticsSection,
2460
- {
2461
- variant: "atlas",
2462
- className: "flex min-h-0 w-full flex-col",
2463
- title: "Guest vs registered",
2464
- description: "Mix for the selected period (same filter as overview).",
2465
- children: /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", className: "min-h-0 flex-1", children: /* @__PURE__ */ jsx("div", { className: "h-[min(168px,22vh)] min-h-[140px] w-full sm:h-[min(176px,24vh)]", children: guestRegisteredPieData.length === 0 ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center px-2", children: /* @__PURE__ */ jsx(Text, { className: "text-center text-ui-fg-muted text-[11px] leading-snug", children: "No guest or registered customers in this range." }) }) : /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxs(PieChart, { margin: { top: 2, right: 2, left: 2, bottom: 2 }, children: [
2466
- /* @__PURE__ */ jsx(
2467
- Pie,
2468
- {
2469
- data: guestRegisteredPieData,
2470
- dataKey: "value",
2471
- nameKey: "name",
2472
- cx: "50%",
2473
- cy: "48%",
2474
- innerRadius: 34,
2475
- outerRadius: 54,
2476
- paddingAngle: 2,
2477
- children: guestRegisteredPieData.map((entry) => /* @__PURE__ */ jsx(
2478
- Cell,
2479
- {
2480
- fill: entry.key === "guest" ? GUEST_COLOR : REGISTERED_COLOR
2481
- },
2482
- entry.key
2483
- ))
2484
- }
2485
- ),
2486
- /* @__PURE__ */ jsx(Tooltip, { content: /* @__PURE__ */ jsx(MixPieTooltip, {}) }),
2487
- /* @__PURE__ */ jsx(
2488
- Legend,
2489
- {
2490
- wrapperStyle: { fontSize: 9, paddingTop: 0 },
2491
- verticalAlign: "bottom",
2492
- height: 22,
2493
- iconType: "circle"
2494
- }
2495
- )
2496
- ] }) }) }) })
2497
- }
2498
- ) }),
2499
- /* @__PURE__ */ jsx("div", { className: "col-span-12 flex min-h-0 min-w-0 lg:col-span-7", children: /* @__PURE__ */ jsx(
2500
- AnalyticsSection,
2501
- {
2502
- variant: "atlas",
2503
- className: "flex min-h-0 w-full flex-col",
2504
- title: "Repeat purchases",
2505
- description: "Orders with a customer_id in the same window (guest checkouts excluded from rate).",
2506
- children: /* @__PURE__ */ jsx("div", { className: "flex min-h-0 flex-1 flex-col gap-1.5", children: repeatLoading ? /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", className: "flex flex-1 items-center justify-center py-6", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "Loading…" }) }) : repeatError ? /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", className: "flex flex-1 items-center justify-center px-2 py-6", children: /* @__PURE__ */ jsx(Text, { className: "text-center text-ui-fg-danger text-xs", children: repeatError }) }) : repeatStats ? /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-1.5 sm:grid-cols-3", children: [
2507
- ((_b = repeatStats.ordersAnalyticsMeta) == null ? void 0 : _b.likely_truncated) ? /* @__PURE__ */ jsx("div", { className: "col-span-full rounded-md border border-amber-400/25 bg-amber-500/10 px-2 py-1.5", children: /* @__PURE__ */ jsxs(Text, { className: "text-ui-fg-base text-[10px] leading-snug", children: [
2508
- "Repeat stats are computed from a sample of up to",
2509
- " ",
2510
- repeatStats.ordersAnalyticsMeta.max_fetch.toLocaleString(),
2511
- " ",
2512
- "orders; your true repeat rate may differ if you exceed that sample."
2513
- ] }) }) : null,
2514
- /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
2515
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: "Repeat rate" }),
2516
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-lg font-semibold tracking-tight", children: `${repeatStats.repeat_rate_percent.toFixed(1)}%` }),
2517
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] leading-snug", children: repeatStats.window_days >= 365 ? "Approx. 12-month window" : `Last ${repeatStats.window_days} days` })
2518
- ] }) }),
2519
- /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
2520
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: "With orders" }),
2521
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-lg font-semibold tracking-tight", children: repeatStats.customers_with_orders.toLocaleString() }),
2522
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] leading-snug", children: "Customers in window" })
2523
- ] }) }),
2524
- /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
2525
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: "Repeat (2+ orders)" }),
2526
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-lg font-semibold tracking-tight", children: repeatStats.repeat_customers.toLocaleString() }),
2527
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] leading-snug", children: "Multi-order customers" })
2528
- ] }) })
2529
- ] }) : /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", className: "flex flex-1 items-center justify-center py-6", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "No data." }) }) })
2530
- }
2531
- ) })
2532
- ] }),
2533
- /* @__PURE__ */ jsx(
2534
- AnalyticsSection,
2535
- {
2536
- variant: "atlas",
2537
- actionsBare: true,
2538
- title: "Customers over time",
2539
- description: "New registered vs guest activity for the chart range below.",
2540
- actions: /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
2541
- /* @__PURE__ */ jsx(
2542
- Label,
2543
- {
2544
- htmlFor: "customers-graph-period",
2545
- className: "shrink-0 text-ui-fg-muted text-xs font-medium",
2546
- children: "Range"
2547
- }
2548
- ),
2549
- /* @__PURE__ */ jsx(
2550
- "select",
2551
- {
2552
- id: "customers-graph-period",
2553
- value: graphPeriod,
2554
- onChange: (e) => setGraphPeriod(e.target.value),
2555
- className: SELECT_CLASS_NAME$1,
2556
- children: GRAPH_PERIODS$1.map((p) => /* @__PURE__ */ jsx("option", { value: p.value, children: p.label }, p.value))
2557
- }
2558
- )
2559
- ] }),
2560
- children: /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
2561
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-1.5 sm:grid-cols-3", children: [
2562
- /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
2563
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: "Window registered (sum)" }),
2564
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-lg font-semibold tracking-tight", children: seriesWindowTotals.registered.toLocaleString() }),
2565
- /* @__PURE__ */ jsxs(Text, { className: "text-ui-fg-muted text-[10px]", children: [
2566
- "Across ",
2567
- seriesWindowTotals.points,
2568
- " buckets"
2569
- ] })
2570
- ] }) }),
2571
- /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
2572
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: "Window guest (sum)" }),
2573
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-lg font-semibold tracking-tight", children: seriesWindowTotals.guest.toLocaleString() }),
2574
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px]", children: "Same range as chart" })
2575
- ] }) }),
2576
- /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
2577
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: "Chart period" }),
2578
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-lg font-semibold tracking-tight", children: ((_c = GRAPH_PERIODS$1.find((p) => p.value === graphPeriod)) == null ? void 0 : _c.label) ?? graphPeriod }),
2579
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] leading-snug", children: "Independent of summary period filter" })
2580
- ] }) })
2581
- ] }),
2582
- /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsx("div", { className: "h-[212px] w-full sm:h-[228px]", children: graphLoading ? /* @__PURE__ */ jsx(
2583
- "div",
2584
- {
2585
- className: "flex h-full items-center justify-center",
2586
- role: "status",
2587
- "aria-label": "Loading customers over time",
2588
- children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "Loading chart…" })
2589
- }
2590
- ) : graphError ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center px-2", children: /* @__PURE__ */ jsx(Text, { className: "text-center text-ui-fg-danger text-xs", children: graphError }) }) : /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxs(
2591
- LineChart,
2592
- {
2593
- data: series,
2594
- margin: { top: 6, right: 8, left: 0, bottom: 4 },
2595
- children: [
2596
- /* @__PURE__ */ jsx(
2597
- CartesianGrid,
2598
- {
2599
- strokeDasharray: "3 3",
2600
- vertical: false,
2601
- stroke: "rgba(148,163,184,0.12)"
2602
- }
2603
- ),
2604
- /* @__PURE__ */ jsx(
2605
- XAxis,
2606
- {
2607
- dataKey: "date",
2608
- tick: CHART_AXIS_TICK$1,
2609
- stroke: CHART_AXIS_LINE$1,
2610
- tickLine: false,
2611
- axisLine: { stroke: CHART_AXIS_LINE$1 },
2612
- tickFormatter: (value) => {
2613
- const row = series.find((p) => p.date === String(value));
2614
- if (row == null ? void 0 : row.label) return row.label;
2615
- return formatChartLabel$1(
2616
- (row == null ? void 0 : row.date) ?? (typeof value === "string" ? value : String(value))
2617
- );
2618
- }
2619
- }
2620
- ),
2621
- /* @__PURE__ */ jsx(
2622
- YAxis,
2623
- {
2624
- width: 36,
2625
- tick: CHART_AXIS_TICK$1,
2626
- stroke: CHART_AXIS_LINE$1,
2627
- tickLine: false,
2628
- axisLine: { stroke: CHART_AXIS_LINE$1 },
2629
- tickFormatter: (v) => String(Math.floor(Number(v))),
2630
- allowDecimals: false
2631
- }
2632
- ),
2633
- /* @__PURE__ */ jsx(Tooltip, { content: /* @__PURE__ */ jsx(CustomersOverTimeTooltip, {}) }),
2634
- /* @__PURE__ */ jsx(
2635
- Legend,
2636
- {
2637
- wrapperStyle: { fontSize: 10, paddingTop: 4 },
2638
- iconType: "circle"
2639
- }
2640
- ),
2641
- /* @__PURE__ */ jsx(
2642
- Line,
2643
- {
2644
- type: "monotone",
2645
- dataKey: "registered_count",
2646
- name: "Registered",
2647
- stroke: REGISTERED_COLOR,
2648
- strokeWidth: 2,
2649
- dot: { r: 2 }
2650
- }
2651
- ),
2652
- /* @__PURE__ */ jsx(
2653
- Line,
2654
- {
2655
- type: "monotone",
2656
- dataKey: "guest_count",
2657
- name: "Guest",
2658
- stroke: GUEST_COLOR,
2659
- strokeWidth: 2,
2660
- dot: { r: 2 }
2661
- }
2662
- )
2663
- ]
2664
- }
2665
- ) }) }) })
2666
- ] })
2667
- }
2668
- )
2669
- ] })
2670
- ] }) });
2671
- }
2672
- function buildAnalyticsUrl(path, params) {
2673
- const search = new URLSearchParams();
2674
- for (const [key, value] of Object.entries(params)) {
2675
- if (value !== void 0 && value !== null) {
2676
- search.set(key, String(value));
2677
- }
2678
- }
2679
- const query = search.toString();
2680
- return query ? `${path}?${query}` : path;
2681
- }
2682
- const SUMMARY_PERIODS = [
2683
- { value: "all", label: "All time" },
2684
- { value: "0", label: "Today" },
2685
- { value: "7", label: "Last 7 days" },
2686
- { value: "30", label: "Last 30 days" },
2687
- { value: "90", label: "Last 90 days" }
2688
- ];
2689
- const GRAPH_PERIODS = [
2690
- { value: "one_week", label: "One week" },
2691
- { value: "one_month", label: "One month" },
2692
- { value: "one_year", label: "One year" }
2693
- ];
2694
- const TOP_SELLER_PERIODS = [
2695
- { value: "week", label: "Week" },
2696
- { value: "month", label: "Month" },
2697
- { value: "year", label: "Year" },
2698
- { value: "all", label: "All time" }
2699
- ];
2700
- const PRODUCT_CHART_COLORS = {
2701
- units: "#38BDF8",
2702
- views: "#C084FC",
2703
- revenue: "#D946EF",
2704
- revenueMuted: "#94A3B8",
2705
- scatter: "#A855F7"
2706
- };
2707
- const KPI_ICON_BG = {
2708
- green: "bg-emerald-500/20",
2709
- blue: "bg-sky-500/20",
2710
- purple: "bg-violet-500/20",
2711
- amber: "bg-amber-500/20"
2712
- };
2713
- const KPI_ICONS = {
2714
- green: CurrencyDollar,
2715
- blue: ShoppingCart,
2716
- purple: Tag,
2717
- amber: CubeSolid
2718
- };
2719
- const CHART_AXIS_TICK = { fontSize: 10, fill: "#e5e7eb" };
2720
- const CHART_AXIS_TICK_SM = { fontSize: 9, fill: "#e5e7eb" };
2721
- const CHART_AXIS_LINE = "#94a3b8";
2722
- const SELECT_CLASS_NAME = "h-9 w-full min-w-[8rem] max-w-full cursor-pointer appearance-none rounded border border-ui-border-base bg-ui-bg-base py-1.5 pl-3 pr-8 text-xs text-ui-fg-base outline-none transition focus:ring-2 focus:ring-ui-fg-interactive sm:w-auto sm:min-w-[132px] sm:max-w-[220px]";
2723
- const LEADERBOARD_TABLE_CLASS = "min-w-[32rem] sm:min-w-[36rem] max-w-none";
2724
- const OPPORTUNITIES_TABLE_CLASS = "min-w-[30rem] sm:min-w-[34rem] max-w-none";
2725
- const TABLE_HEAD_CELL_NOWRAP = "whitespace-nowrap";
2726
- function formatChartLabel(value) {
2727
- if (!value) return "";
2728
- const parsed = new Date(value);
2729
- if (Number.isNaN(parsed.getTime())) return value;
2730
- return `${parsed.getUTCMonth() + 1}/${parsed.getUTCDate()}`;
2731
- }
2732
- function formatRatio(value) {
2733
- if (value === null || Number.isNaN(value)) return "N/A";
2734
- return `${value.toFixed(2)}x`;
2735
- }
2736
- function formatShortNumber(value) {
2737
- return new Intl.NumberFormat("en-IN", {
2738
- notation: "compact",
2739
- maximumFractionDigits: value < 10 ? 1 : 0
2740
- }).format(value);
2741
- }
2742
- function topSellerPeriodToGraphPeriod(period) {
2743
- if (period === "month") return "one_month";
2744
- if (period === "year" || period === "all") return "one_year";
2745
- return "one_week";
2746
- }
2747
- function summaryDaysToGraphPeriod(days) {
2748
- if (days === "30") return "one_month";
2749
- if (days === "all" || days === "90") return "one_year";
2750
- return "one_week";
2751
- }
2752
- function isProductOverTimePoint(value) {
2753
- if (typeof value !== "object" || value === null) return false;
2754
- const v = value;
2755
- return typeof v.date === "string" && typeof v.units_sold === "number" && typeof v.revenue === "number" && typeof v.views === "number";
2756
- }
2757
- function TrendTooltip({
2758
- active,
2759
- payload,
2760
- label
2761
- }) {
2762
- var _a, _b, _c, _d, _e;
2763
- const { formatCurrency } = useAnalyticsCurrency();
2764
- if (!active || !(payload == null ? void 0 : payload.length)) return null;
2765
- const row = isProductOverTimePoint((_a = payload[0]) == null ? void 0 : _a.payload) ? (_b = payload[0]) == null ? void 0 : _b.payload : void 0;
2766
- const displayLabel = (row == null ? void 0 : row.label) ?? (label ? new Date(label).toLocaleDateString() : "");
2767
- const unitsSold = ((_c = payload.find((entry) => entry.name === "Units sold")) == null ? void 0 : _c.value) ?? 0;
2768
- const views = ((_d = payload.find((entry) => entry.name === "Views")) == null ? void 0 : _d.value) ?? 0;
2769
- const revenue = ((_e = payload.find((entry) => entry.name === "Revenue")) == null ? void 0 : _e.value) ?? 0;
2770
- return /* @__PURE__ */ jsxs(AnalyticsTooltipCard, { title: displayLabel, children: [
2771
- /* @__PURE__ */ jsxs("div", { children: [
2772
- "Units sold: ",
2773
- /* @__PURE__ */ jsx("strong", { children: Math.floor(Number(unitsSold)).toLocaleString() })
2774
- ] }),
2775
- /* @__PURE__ */ jsxs("div", { children: [
2776
- "Views: ",
2777
- /* @__PURE__ */ jsx("strong", { children: Math.floor(Number(views)).toLocaleString() })
2778
- ] }),
2779
- /* @__PURE__ */ jsxs("div", { children: [
2780
- "Revenue: ",
2781
- /* @__PURE__ */ jsx("strong", { children: formatCurrency(Number(revenue)) })
2782
- ] })
2783
- ] });
2784
- }
2785
- function MiniTrendTooltip({
2786
- active,
2787
- payload,
2788
- label,
2789
- productHeadline,
2790
- hideViewsRow,
2791
- hideUnitsRow,
2792
- hideRevenueRow
2793
- }) {
2794
- var _a, _b, _c, _d, _e;
2795
- const { formatCurrency } = useAnalyticsCurrency();
2796
- if (!active || !(payload == null ? void 0 : payload.length)) return null;
2797
- const row = isProductOverTimePoint((_a = payload[0]) == null ? void 0 : _a.payload) ? (_b = payload[0]) == null ? void 0 : _b.payload : void 0;
2798
- const labelKey = label !== void 0 && label !== null ? String(label) : "";
2799
- const displayLabel = (row == null ? void 0 : row.label) ?? (labelKey ? new Date(labelKey).toLocaleDateString() : "");
2800
- const unitsSold = ((_c = payload.find((entry) => entry.name === "Units sold")) == null ? void 0 : _c.value) ?? 0;
2801
- const views = ((_d = payload.find((entry) => entry.name === "Views")) == null ? void 0 : _d.value) ?? 0;
2802
- const revenue = ((_e = payload.find((entry) => entry.name === "Revenue")) == null ? void 0 : _e.value) ?? 0;
2803
- const title = productHeadline ?? displayLabel;
2804
- return /* @__PURE__ */ jsxs(AnalyticsTooltipCard, { variant: "compact", title, children: [
2805
- productHeadline ? /* @__PURE__ */ jsx("div", { className: "mb-1 text-[10px] leading-tight opacity-80", children: displayLabel }) : null,
2806
- !hideUnitsRow ? /* @__PURE__ */ jsxs("div", { children: [
2807
- "Units sold: ",
2808
- /* @__PURE__ */ jsx("strong", { children: Math.floor(Number(unitsSold)).toLocaleString() })
2809
- ] }) : null,
2810
- !hideViewsRow ? /* @__PURE__ */ jsxs("div", { children: [
2811
- "Views: ",
2812
- /* @__PURE__ */ jsx("strong", { children: Math.floor(Number(views)).toLocaleString() })
2813
- ] }) : null,
2814
- !hideRevenueRow ? /* @__PURE__ */ jsxs("div", { children: [
2815
- "Revenue: ",
2816
- /* @__PURE__ */ jsx("strong", { children: formatCurrency(Number(revenue)) })
2817
- ] }) : null
2818
- ] });
2819
- }
2820
- function ProductBarTooltip({
2821
- active,
2822
- payload,
2823
- showViews = true
2824
- }) {
2825
- var _a;
2826
- const { formatCurrency } = useAnalyticsCurrency();
2827
- if (!active || !(payload == null ? void 0 : payload.length)) return null;
2828
- const row = (_a = payload[0]) == null ? void 0 : _a.payload;
2829
- if (!row) return null;
2830
- const unitsSold = "units_sold" in row ? row.units_sold : 0;
2831
- const totalViews = "total_views" in row ? row.total_views : 0;
2832
- const revenue = "revenue" in row ? row.revenue : 0;
2833
- return /* @__PURE__ */ jsxs(AnalyticsTooltipCard, { variant: "compact", title: row.product_title, children: [
2834
- /* @__PURE__ */ jsxs("div", { children: [
2835
- "Units sold: ",
2836
- /* @__PURE__ */ jsx("strong", { children: Math.floor(unitsSold).toLocaleString() })
2837
- ] }),
2838
- showViews ? /* @__PURE__ */ jsxs("div", { children: [
2839
- "Views: ",
2840
- /* @__PURE__ */ jsx("strong", { children: Math.floor(totalViews).toLocaleString() })
2841
- ] }) : null,
2842
- /* @__PURE__ */ jsxs("div", { children: [
2843
- "Revenue: ",
2844
- /* @__PURE__ */ jsx("strong", { children: formatCurrency(Number(revenue)) })
2845
- ] })
2846
- ] });
2847
- }
2848
- function AtlasKpiCard({
2849
- label,
2850
- value,
2851
- helper,
2852
- accent
2853
- }) {
2854
- const Icon = KPI_ICONS[accent];
2855
- return /* @__PURE__ */ jsxs("div", { className: "flex h-full min-h-[88px] min-w-0 flex-col rounded-xl border border-ui-border-base/80 bg-ui-bg-subtle/25 p-3 shadow-sm", children: [
2856
- /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2", children: [
2857
- /* @__PURE__ */ jsx(Text, { className: "min-w-0 flex-1 text-left text-xs font-medium leading-snug text-ui-fg-base", children: label }),
2858
- /* @__PURE__ */ jsx(
2859
- "div",
2860
- {
2861
- className: `flex h-7 w-7 shrink-0 items-center justify-center rounded-lg ${KPI_ICON_BG[accent]}`,
2862
- "aria-hidden": true,
2863
- children: /* @__PURE__ */ jsx(Icon, { className: "h-3.5 w-3.5 text-ui-fg-base" })
2864
- }
2865
- )
2866
- ] }),
2867
- /* @__PURE__ */ jsx("div", { className: "mt-2 text-lg font-semibold tabular-nums tracking-tight text-ui-fg-base sm:text-xl", children: value }),
2868
- helper ? /* @__PURE__ */ jsx(Text, { className: "mt-2 text-[11px] leading-snug text-ui-fg-muted", children: helper }) : null
2869
- ] });
2870
- }
2871
- function EmptyAnalyticsPanel({ title, description }) {
2872
- return /* @__PURE__ */ jsxs("div", { className: "flex min-h-[88px] flex-col gap-1.5 rounded-lg border border-dashed border-ui-border-base px-3 py-3", children: [
2873
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-xs font-semibold", children: title }),
2874
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[11px] leading-snug", children: description })
2875
- ] });
2876
- }
2877
- function ProductsDashboard() {
2878
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2879
- const { formatCurrency, formatCompactCurrency } = useAnalyticsCurrency();
2880
- const chartGradientPrefix = useId().replace(/:/g, "");
2881
- const gid = (suffix) => `${chartGradientPrefix}-${suffix}`;
2882
- const [summaryDays, setSummaryDays] = useState("all");
2883
- const [graphPeriod, setGraphPeriod] = useState("one_week");
2884
- const [topSellerPeriod, setTopSellerPeriod] = useState("week");
2885
- const [salesChannelId, setSalesChannelId] = useState("all");
2886
- const [salesChannels, setSalesChannels] = useState([]);
2887
- const [filtersLoading, setFiltersLoading] = useState(true);
2888
- const [filtersError, setFiltersError] = useState(null);
2889
- const [summary, setSummary] = useState(null);
2890
- const [summaryLoading, setSummaryLoading] = useState(true);
2891
- const [summaryError, setSummaryError] = useState(null);
2892
- const [overTime, setOverTime] = useState(null);
2893
- const [overTimeLoading, setOverTimeLoading] = useState(true);
2894
- const [overTimeError, setOverTimeError] = useState(null);
2895
- const [topSellers, setTopSellers] = useState(null);
2896
- const [topSellersLoading, setTopSellersLoading] = useState(true);
2897
- const [topSellersError, setTopSellersError] = useState(null);
2898
- const [performance, setPerformance] = useState(null);
2899
- const [performanceLoading, setPerformanceLoading] = useState(true);
2900
- const [performanceError, setPerformanceError] = useState(null);
2901
- const [bestSellersTrend, setBestSellersTrend] = useState(null);
2902
- const [bestSellersTrendLoading, setBestSellersTrendLoading] = useState(true);
2903
- const [bestSellersTrendError, setBestSellersTrendError] = useState(null);
2904
- const [mostViewedTrend, setMostViewedTrend] = useState(null);
2905
- const [mostViewedTrendLoading, setMostViewedTrendLoading] = useState(true);
2906
- const [mostViewedTrendError, setMostViewedTrendError] = useState(null);
2907
- useEffect(() => {
2908
- let cancelled = false;
2909
- setFiltersLoading(true);
2910
- setFiltersError(null);
2911
- fetch("/admin/analytics/products-filters", { credentials: "include" }).then((res) => {
2912
- if (!res.ok) throw new Error(res.statusText);
2913
- return res.json();
2914
- }).then((body) => {
2915
- if (!cancelled) {
2916
- setSalesChannels(body.salesChannels ?? []);
2917
- }
2918
- }).catch((error) => {
2919
- if (!cancelled) {
2920
- setFiltersError(error instanceof Error ? error.message : String(error));
2921
- }
2922
- }).finally(() => {
2923
- if (!cancelled) setFiltersLoading(false);
2924
- });
2925
- return () => {
2926
- cancelled = true;
2927
- };
2928
- }, []);
2929
- useEffect(() => {
2930
- let cancelled = false;
2931
- setSummaryLoading(true);
2932
- setSummaryError(null);
2933
- fetch(
2934
- buildAnalyticsUrl("/admin/analytics/products-summary", {
2935
- days: summaryDays,
2936
- sales_channel_id: salesChannelId !== "all" ? salesChannelId : null
2937
- }),
2938
- { credentials: "include" }
2939
- ).then((res) => {
2940
- if (!res.ok) throw new Error(res.statusText);
2941
- return res.json();
2942
- }).then((body) => {
2943
- if (!cancelled) setSummary(body);
2944
- }).catch((error) => {
2945
- if (!cancelled) {
2946
- setSummaryError(error instanceof Error ? error.message : String(error));
2947
- }
2948
- }).finally(() => {
2949
- if (!cancelled) setSummaryLoading(false);
2950
- });
2951
- return () => {
2952
- cancelled = true;
2953
- };
2954
- }, [salesChannelId, summaryDays]);
2955
- useEffect(() => {
2956
- let cancelled = false;
2957
- setOverTimeLoading(true);
2958
- setOverTimeError(null);
2959
- fetch(
2960
- buildAnalyticsUrl("/admin/analytics/products-over-time", {
2961
- period: graphPeriod,
2962
- sales_channel_id: salesChannelId !== "all" ? salesChannelId : null
2963
- }),
2964
- { credentials: "include" }
2965
- ).then((res) => {
2966
- if (!res.ok) throw new Error(res.statusText);
2967
- return res.json();
2968
- }).then((body) => {
2969
- if (!cancelled) setOverTime(body);
2970
- }).catch((error) => {
2971
- if (!cancelled) {
2972
- setOverTimeError(error instanceof Error ? error.message : String(error));
2973
- }
2974
- }).finally(() => {
2975
- if (!cancelled) setOverTimeLoading(false);
2976
- });
2977
- return () => {
2978
- cancelled = true;
2979
- };
2980
- }, [graphPeriod, salesChannelId]);
2981
- useEffect(() => {
2982
- let cancelled = false;
2983
- setTopSellersLoading(true);
2984
- setTopSellersError(null);
2985
- fetch(
2986
- buildAnalyticsUrl("/admin/analytics/products-top-sellers", {
2987
- period: topSellerPeriod,
2988
- sales_channel_id: salesChannelId !== "all" ? salesChannelId : null
2989
- }),
2990
- { credentials: "include" }
2991
- ).then((res) => {
2992
- if (!res.ok) throw new Error(res.statusText);
2993
- return res.json();
2994
- }).then((body) => {
2995
- if (!cancelled) setTopSellers(body);
2996
- }).catch((error) => {
2997
- if (!cancelled) {
2998
- setTopSellersError(error instanceof Error ? error.message : String(error));
2999
- }
3000
- }).finally(() => {
3001
- if (!cancelled) setTopSellersLoading(false);
3002
- });
3003
- return () => {
3004
- cancelled = true;
3005
- };
3006
- }, [salesChannelId, topSellerPeriod]);
3007
- useEffect(() => {
3008
- var _a2;
3009
- let cancelled = false;
3010
- if (topSellersLoading) {
3011
- setBestSellersTrendLoading(true);
3012
- return () => {
3013
- cancelled = true;
3014
- };
3015
- }
3016
- if (topSellersError) {
3017
- setBestSellersTrendLoading(false);
3018
- setBestSellersTrendError(topSellersError);
3019
- setBestSellersTrend(null);
3020
- return () => {
3021
- cancelled = true;
3022
- };
3023
- }
3024
- const topSellersByUnits2 = [...(topSellers == null ? void 0 : topSellers.products) ?? []].sort((a, b) => {
3025
- if (b.units_sold !== a.units_sold) return b.units_sold - a.units_sold;
3026
- if (b.order_count !== a.order_count) return b.order_count - a.order_count;
3027
- return b.revenue - a.revenue;
3028
- });
3029
- const topProductId = (_a2 = topSellersByUnits2[0]) == null ? void 0 : _a2.product_id;
3030
- if (!topProductId) {
3031
- setBestSellersTrendLoading(false);
3032
- setBestSellersTrendError(null);
3033
- setBestSellersTrend({
3034
- series: [],
3035
- productViewsConnected: (topSellers == null ? void 0 : topSellers.productViewsConnected) ?? false,
3036
- product: null
3037
- });
3038
- return () => {
3039
- cancelled = true;
3040
- };
3041
- }
3042
- setBestSellersTrendLoading(true);
3043
- setBestSellersTrendError(null);
3044
- const period = topSellerPeriodToGraphPeriod(topSellerPeriod);
3045
- fetch(
3046
- buildAnalyticsUrl("/admin/analytics/products-over-time", {
3047
- period,
3048
- sales_channel_id: salesChannelId !== "all" ? salesChannelId : null,
3049
- product_id: topProductId
3050
- }),
3051
- { credentials: "include" }
3052
- ).then((res) => {
3053
- if (!res.ok) throw new Error(res.statusText);
3054
- return res.json();
3055
- }).then((body) => {
3056
- if (!cancelled) setBestSellersTrend(body);
3057
- }).catch((error) => {
3058
- if (!cancelled) {
3059
- setBestSellersTrendError(error instanceof Error ? error.message : String(error));
3060
- }
3061
- }).finally(() => {
3062
- if (!cancelled) setBestSellersTrendLoading(false);
3063
- });
3064
- return () => {
3065
- cancelled = true;
3066
- };
3067
- }, [salesChannelId, topSellerPeriod, topSellersLoading, topSellersError, topSellers]);
76
+ const [overTimePeriod, setOverTimePeriod] = useState("one_week");
77
+ const [overTimeLoading, setOverTimeLoading] = useState(true);
78
+ const [overTimeError, setOverTimeError] = useState(null);
3068
79
  useEffect(() => {
3069
- var _a2, _b2;
3070
80
  let cancelled = false;
3071
- if (performanceLoading) {
3072
- setMostViewedTrendLoading(true);
3073
- return () => {
3074
- cancelled = true;
3075
- };
3076
- }
3077
- if (performanceError) {
3078
- setMostViewedTrendLoading(false);
3079
- setMostViewedTrendError(performanceError);
3080
- setMostViewedTrend(null);
3081
- return () => {
3082
- cancelled = true;
3083
- };
3084
- }
3085
- if (!(performance == null ? void 0 : performance.productViewsConnected)) {
3086
- setMostViewedTrendLoading(false);
3087
- setMostViewedTrendError(null);
3088
- setMostViewedTrend(null);
3089
- return () => {
3090
- cancelled = true;
3091
- };
3092
- }
3093
- const topViewedId = (_b2 = (_a2 = performance.topViewedProducts) == null ? void 0 : _a2[0]) == null ? void 0 : _b2.product_id;
3094
- if (!topViewedId) {
3095
- setMostViewedTrendLoading(false);
3096
- setMostViewedTrendError(null);
3097
- setMostViewedTrend({
3098
- series: [],
3099
- productViewsConnected: true,
3100
- product: null
3101
- });
3102
- return () => {
3103
- cancelled = true;
3104
- };
3105
- }
3106
- setMostViewedTrendLoading(true);
3107
- setMostViewedTrendError(null);
3108
- const period = summaryDaysToGraphPeriod(summaryDays);
3109
- fetch(
3110
- buildAnalyticsUrl("/admin/analytics/products-over-time", {
3111
- period,
3112
- sales_channel_id: salesChannelId !== "all" ? salesChannelId : null,
3113
- product_id: topViewedId
3114
- }),
3115
- { credentials: "include" }
3116
- ).then((res) => {
81
+ setLoading(true);
82
+ setError(null);
83
+ const url = `/admin/analytics/orders-summary?days=${filter}`;
84
+ fetch(url).then((res) => {
3117
85
  if (!res.ok) throw new Error(res.statusText);
3118
86
  return res.json();
3119
87
  }).then((body) => {
3120
- if (!cancelled) setMostViewedTrend(body);
3121
- }).catch((error) => {
3122
- if (!cancelled) {
3123
- setMostViewedTrendError(error instanceof Error ? error.message : String(error));
3124
- }
88
+ if (!cancelled) setData(body);
89
+ }).catch((e) => {
90
+ if (!cancelled) setError(e instanceof Error ? e.message : String(e));
3125
91
  }).finally(() => {
3126
- if (!cancelled) setMostViewedTrendLoading(false);
92
+ if (!cancelled) setLoading(false);
3127
93
  });
3128
94
  return () => {
3129
95
  cancelled = true;
3130
96
  };
3131
- }, [salesChannelId, summaryDays, performanceLoading, performanceError, performance]);
97
+ }, [filter]);
3132
98
  useEffect(() => {
3133
99
  let cancelled = false;
3134
- setPerformanceLoading(true);
3135
- setPerformanceError(null);
3136
- fetch(
3137
- buildAnalyticsUrl("/admin/analytics/products-performance", {
3138
- days: summaryDays,
3139
- sales_channel_id: salesChannelId !== "all" ? salesChannelId : null
3140
- }),
3141
- { credentials: "include" }
3142
- ).then((res) => {
100
+ setOverTimeLoading(true);
101
+ setOverTimeError(null);
102
+ const url = `/admin/analytics/orders-over-time?period=${overTimePeriod}`;
103
+ fetch(url).then((res) => {
3143
104
  if (!res.ok) throw new Error(res.statusText);
3144
105
  return res.json();
3145
106
  }).then((body) => {
3146
- if (!cancelled) setPerformance(body);
3147
- }).catch((error) => {
3148
- if (!cancelled) {
3149
- setPerformanceError(error instanceof Error ? error.message : String(error));
3150
- }
107
+ if (!cancelled) setDailyOrders(body.dailyOrders ?? []);
108
+ }).catch((e) => {
109
+ if (!cancelled) setOverTimeError(e instanceof Error ? e.message : String(e));
3151
110
  }).finally(() => {
3152
- if (!cancelled) setPerformanceLoading(false);
111
+ if (!cancelled) setOverTimeLoading(false);
3153
112
  });
3154
113
  return () => {
3155
114
  cancelled = true;
3156
115
  };
3157
- }, [salesChannelId, summaryDays]);
3158
- const series = (overTime == null ? void 0 : overTime.series) ?? [];
3159
- const trendTotals = useMemo(() => {
3160
- const totalUnits = series.reduce((s, p) => s + p.units_sold, 0);
3161
- const totalRevenue = series.reduce((s, p) => s + p.revenue, 0);
3162
- const totalViews = series.reduce((s, p) => s + p.views, 0);
3163
- const n = series.length || 1;
3164
- return {
3165
- totalUnits,
3166
- totalRevenue,
3167
- totalViews,
3168
- avgUnitsPerDay: totalUnits / n,
3169
- avgRevenuePerDay: totalRevenue / n,
3170
- avgViewsPerDay: totalViews / n
3171
- };
3172
- }, [series]);
3173
- const peakRevenuePoint = series.length > 0 ? series.reduce((peak, point) => point.revenue > peak.revenue ? point : peak) : null;
3174
- const viewsConnectedForPulse = ((summary == null ? void 0 : summary.productViewsConnected) ?? false) || (overTime == null ? void 0 : overTime.productViewsConnected) === true || (topSellers == null ? void 0 : topSellers.productViewsConnected) === true || (performance == null ? void 0 : performance.productViewsConnected) === true;
3175
- const topSellersByUnits = useMemo(
3176
- () => [...(topSellers == null ? void 0 : topSellers.products) ?? []].sort((a, b) => {
3177
- if (b.units_sold !== a.units_sold) return b.units_sold - a.units_sold;
3178
- if (b.order_count !== a.order_count) return b.order_count - a.order_count;
3179
- return b.revenue - a.revenue;
3180
- }),
3181
- [topSellers]
3182
- );
3183
- const bestSellersTrendSeries = (bestSellersTrend == null ? void 0 : bestSellersTrend.series) ?? [];
3184
- const mostViewedTrendSeries = (mostViewedTrend == null ? void 0 : mostViewedTrend.series) ?? [];
3185
- const bestSellerTrendProductTitle = ((_a = bestSellersTrend == null ? void 0 : bestSellersTrend.product) == null ? void 0 : _a.product_title) ?? ((_b = topSellersByUnits[0]) == null ? void 0 : _b.product_title) ?? null;
3186
- const mostViewedTrendProductTitle = ((_c = mostViewedTrend == null ? void 0 : mostViewedTrend.product) == null ? void 0 : _c.product_title) ?? ((_e = (_d = performance == null ? void 0 : performance.topViewedProducts) == null ? void 0 : _d[0]) == null ? void 0 : _e.product_title) ?? null;
3187
- const viewsVsUnitsScatterData = useMemo(
3188
- () => ((performance == null ? void 0 : performance.topViewedProducts) ?? []).slice(0, 48).filter((row) => row.total_views > 0 || row.units_sold > 0),
3189
- [performance]
3190
- );
3191
- const selectedSummaryPeriod = ((_f = SUMMARY_PERIODS.find((p) => p.value === summaryDays)) == null ? void 0 : _f.label) ?? "All time";
3192
- const selectedGraphPeriodLabel = ((_g = GRAPH_PERIODS.find((p) => p.value === graphPeriod)) == null ? void 0 : _g.label) ?? "One week";
3193
- const quickPulseMetrics = [
3194
- {
3195
- label: "Range units",
3196
- value: formatShortNumber(trendTotals.totalUnits),
3197
- helper: selectedGraphPeriodLabel,
3198
- accentClassName: "border-sky-400/25 bg-sky-500/5"
3199
- },
3200
- {
3201
- label: "Range revenue",
3202
- value: formatCompactCurrency(trendTotals.totalRevenue),
3203
- helper: "Current chart window",
3204
- accentClassName: "border-fuchsia-400/25 bg-fuchsia-500/5"
3205
- },
3206
- {
3207
- label: "Avg/day views",
3208
- value: trendTotals.avgViewsPerDay.toFixed(0),
3209
- helper: viewsConnectedForPulse ? "Across chart range" : "Views need tracking",
3210
- accentClassName: "border-violet-400/25 bg-violet-500/5"
3211
- },
3212
- {
3213
- label: "Peak revenue day",
3214
- value: peakRevenuePoint ? formatCompactCurrency(peakRevenuePoint.revenue) : "—",
3215
- helper: (peakRevenuePoint == null ? void 0 : peakRevenuePoint.label) ?? formatChartLabel(peakRevenuePoint == null ? void 0 : peakRevenuePoint.date),
3216
- accentClassName: "border-amber-400/25 bg-amber-500/5"
3217
- }
3218
- ];
3219
- if (summaryLoading) {
116
+ }, [overTimePeriod]);
117
+ if (loading) {
3220
118
  return /* @__PURE__ */ jsx(
3221
119
  "div",
3222
120
  {
3223
- className: "flex min-h-[200px] items-center justify-center",
121
+ className: "flex items-center justify-center min-h-[320px]",
3224
122
  role: "status",
3225
- "aria-label": "Loading product analytics",
123
+ "aria-label": "Loading analytics",
3226
124
  children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted", children: "Loading…" })
3227
125
  }
3228
126
  );
3229
127
  }
3230
- if (summaryError || !summary) {
3231
- return /* @__PURE__ */ jsx(Container, { className: "p-6", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger", children: summaryError ?? "Failed to load product analytics" }) });
128
+ if (error || !data) {
129
+ return /* @__PURE__ */ jsx(Container, { className: "p-6", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger", children: error ?? "Failed to load analytics" }) });
3232
130
  }
3233
- const viewsConnected = summary.productViewsConnected || (overTime == null ? void 0 : overTime.productViewsConnected) === true || (topSellers == null ? void 0 : topSellers.productViewsConnected) === true || (performance == null ? void 0 : performance.productViewsConnected) === true;
3234
- const selectedChannelLabel = salesChannelId === "all" ? "All channels" : ((_h = salesChannels.find((channel) => channel.id === salesChannelId)) == null ? void 0 : _h.name) ?? "Selected channel";
3235
- const primaryStats = [
3236
- {
3237
- label: "Units sold",
3238
- value: summary.unitsSold.toLocaleString(),
3239
- helper: selectedSummaryPeriod,
3240
- accent: "amber"
3241
- },
3242
- {
3243
- label: "Product revenue",
3244
- value: formatCurrency(summary.productRevenue),
3245
- helper: selectedSummaryPeriod,
3246
- accent: "green"
3247
- },
3248
- {
3249
- label: "Orders with products",
3250
- value: summary.ordersWithProducts.toLocaleString(),
3251
- helper: "Distinct orders",
3252
- accent: "blue"
3253
- },
3254
- {
3255
- label: "Active products sold",
3256
- value: summary.activeProductsSold.toLocaleString(),
3257
- helper: "Unique SKUs with sales",
3258
- accent: "purple"
3259
- },
3260
- {
3261
- label: "Product views",
3262
- value: summary.totalProductViews.toLocaleString(),
3263
- helper: viewsConnected ? "Tracked views" : "Tracking unavailable",
3264
- accent: "green"
3265
- },
3266
- {
3267
- label: "View / order ratio",
3268
- value: formatRatio(summary.viewToOrderRatio),
3269
- helper: viewsConnected ? "Views per product order" : "N/A without views",
3270
- accent: "blue"
3271
- }
3272
- ];
3273
- return /* @__PURE__ */ jsx(AnalyticsDashboardShell, { className: "w-full min-w-0 max-w-full", children: /* @__PURE__ */ jsxs("div", { className: "w-full min-w-0 max-w-full overflow-hidden rounded-2xl border border-ui-border-base/80 bg-ui-bg-base shadow-sm", children: [
3274
- /* @__PURE__ */ jsx(
3275
- AnalyticsDashboardHeader,
3276
- {
3277
- variant: "premium",
3278
- appearance: "inset",
3279
- actionsBare: true,
3280
- actionsClassName: "w-full justify-start lg:w-auto lg:justify-end",
3281
- title: "Products",
3282
- description: "Units, revenue, best sellers, and visit behavior in a compact layout aligned with Orders analytics.",
3283
- actions: /* @__PURE__ */ jsxs("div", { className: "flex w-full min-w-0 flex-wrap items-center gap-x-3 gap-y-2 sm:flex-nowrap lg:gap-x-4", children: [
3284
- /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-2 sm:flex-initial sm:flex-none", children: [
131
+ const pieData = ORDER_CHART_STATUSES.map(({ key, label, color }) => {
132
+ const value = key === "delivered" ? data.statusCounts.delivered ?? data.deliveredOrders ?? 0 : key === "cancelled" ? data.statusCounts.cancelled ?? data.cancelledOrders ?? 0 : data.statusCounts.pending ?? data.pendingOrders ?? 0;
133
+ return { name: label, value, color };
134
+ }).filter((d) => d.value > 0);
135
+ const returnsExchangesData = [
136
+ { name: "Return orders", value: data.returnOrders, color: "#EF4444" },
137
+ { name: "Exchange orders", value: data.exchangeOrders, color: "#F59E0B" }
138
+ ].filter((d) => d.value > 0);
139
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-8", children: [
140
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-4", children: [
141
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: "Orders" }),
142
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
143
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
144
+ /* @__PURE__ */ jsx(Label, { htmlFor: "analytics-period", className: "text-ui-fg-muted text-sm", children: "Period" }),
145
+ /* @__PURE__ */ jsx(
146
+ "select",
147
+ {
148
+ id: "analytics-period",
149
+ value: filter,
150
+ onChange: (e) => setFilter(e.target.value),
151
+ className: "h-9 rounded-md border border-ui-border-base bg-transparent px-3 text-sm text-ui-fg-base outline-none transition focus:ring-2 focus:ring-ui-fg-interactive",
152
+ children: SUMMARY_PERIODS.map((p) => /* @__PURE__ */ jsx("option", { value: p.value, children: p.label }, p.value))
153
+ }
154
+ )
155
+ ] }),
156
+ filter !== "all" && /* @__PURE__ */ jsx(
157
+ "button",
158
+ {
159
+ type: "button",
160
+ onClick: () => setFilter("all"),
161
+ className: "text-xs text-ui-fg-muted hover:text-ui-fg-base transition-colors",
162
+ "aria-label": "Show all orders (clear filter)",
163
+ children: "Clear filter"
164
+ }
165
+ )
166
+ ] })
167
+ ] }),
168
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4", children: [
169
+ /* @__PURE__ */ jsxs(Container, { className: "p-4", children: [
170
+ /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm", children: "Total orders" }),
171
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: data.totalOrders.toLocaleString() })
172
+ ] }),
173
+ /* @__PURE__ */ jsxs(Container, { className: "p-4", children: [
174
+ /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm", children: "Total revenue" }),
175
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: formatCurrency(data.totalRevenue) })
176
+ ] }),
177
+ /* @__PURE__ */ jsxs(Container, { className: "p-4", children: [
178
+ /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm", children: "Average order value" }),
179
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: formatCurrency(data.aov) })
180
+ ] }),
181
+ /* @__PURE__ */ jsxs(Container, { className: "p-4", children: [
182
+ /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm", children: "Orders today" }),
183
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: data.ordersToday.toLocaleString() })
184
+ ] })
185
+ ] }),
186
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-2 gap-6", children: [
187
+ /* @__PURE__ */ jsxs(Container, { className: "p-4", children: [
188
+ /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm mb-2", children: "Pending orders" }),
189
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: data.pendingOrders.toLocaleString() })
190
+ ] }),
191
+ /* @__PURE__ */ jsxs(Container, { className: "p-4", children: [
192
+ /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm mb-2", children: "Avg. fulfillment time (hours)" }),
193
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: data.avgFulfillmentTimeHours != null ? `${data.avgFulfillmentTimeHours}h` : "—" })
194
+ ] })
195
+ ] }),
196
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4", children: [
197
+ /* @__PURE__ */ jsxs(Container, { className: "p-4", children: [
198
+ /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm", children: "Cancelled orders" }),
199
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: data.cancelledOrders.toLocaleString() })
200
+ ] }),
201
+ /* @__PURE__ */ jsxs(Container, { className: "p-4", children: [
202
+ /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm", children: "Delivered orders" }),
203
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: data.deliveredOrders.toLocaleString() })
204
+ ] }),
205
+ /* @__PURE__ */ jsxs(Container, { className: "p-4", children: [
206
+ /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm", children: "Exchange orders" }),
207
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: data.exchangeOrders.toLocaleString() })
208
+ ] }),
209
+ /* @__PURE__ */ jsxs(Container, { className: "p-4", children: [
210
+ /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm", children: "Return orders" }),
211
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: data.returnOrders.toLocaleString() })
212
+ ] })
213
+ ] }),
214
+ /* @__PURE__ */ jsx(Container, { className: "p-6", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col sm:flex-row flex-wrap gap-6 items-stretch", children: [
215
+ /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0 flex flex-col", style: { minWidth: "280px" }, children: [
216
+ /* @__PURE__ */ jsx(Heading, { level: "h3", className: "mb-3", children: "Orders by status" }),
217
+ /* @__PURE__ */ jsx("div", { className: "flex-1 min-h-[280px] flex items-center justify-center", children: pieData.length > 0 ? /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: 280, children: /* @__PURE__ */ jsxs(PieChart, { margin: { top: 8, right: 8, bottom: 8, left: 8 }, children: [
218
+ /* @__PURE__ */ jsx(
219
+ Pie,
220
+ {
221
+ data: pieData,
222
+ cx: "50%",
223
+ cy: "50%",
224
+ innerRadius: 52,
225
+ outerRadius: 78,
226
+ paddingAngle: 2,
227
+ dataKey: "value",
228
+ nameKey: "name",
229
+ isAnimationActive: true,
230
+ children: pieData.map((entry, index) => /* @__PURE__ */ jsx(Cell, { fill: entry.color }, `cell-${index}`))
231
+ }
232
+ ),
233
+ /* @__PURE__ */ jsx(Tooltip, { formatter: (value) => [value ?? 0, "Orders"] }),
234
+ /* @__PURE__ */ jsx(Legend, { verticalAlign: "bottom", height: 36 })
235
+ ] }) }) : /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm", children: "No orders in this period" }) })
236
+ ] }),
237
+ /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0 flex flex-col", style: { minWidth: "280px" }, children: [
238
+ /* @__PURE__ */ jsx(Heading, { level: "h3", className: "mb-3", children: "Returns & exchanges" }),
239
+ /* @__PURE__ */ jsx("div", { className: "flex-1 min-h-[280px] flex items-center justify-center", children: returnsExchangesData.length > 0 ? /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: 280, children: /* @__PURE__ */ jsxs(PieChart, { margin: { top: 8, right: 8, bottom: 8, left: 8 }, children: [
240
+ /* @__PURE__ */ jsx(
241
+ Pie,
242
+ {
243
+ data: returnsExchangesData,
244
+ cx: "50%",
245
+ cy: "50%",
246
+ innerRadius: 52,
247
+ outerRadius: 78,
248
+ paddingAngle: 2,
249
+ dataKey: "value",
250
+ nameKey: "name",
251
+ isAnimationActive: true,
252
+ children: returnsExchangesData.map((entry, index) => /* @__PURE__ */ jsx(Cell, { fill: entry.color }, `cell-re-${index}`))
253
+ }
254
+ ),
255
+ /* @__PURE__ */ jsx(Tooltip, { formatter: (value) => [value ?? 0, "Count"] }),
256
+ /* @__PURE__ */ jsx(Legend, { verticalAlign: "bottom", height: 36 })
257
+ ] }) }) : /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm", children: "No returns or exchanges in this period" }) })
258
+ ] })
259
+ ] }) }),
260
+ /* @__PURE__ */ jsxs(Container, { className: "p-6", children: [
261
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-4 mb-4", children: [
262
+ /* @__PURE__ */ jsx(Heading, { level: "h3", children: "Orders over time" }),
263
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
264
+ /* @__PURE__ */ jsx(Label, { htmlFor: "over-time-period", className: "text-ui-fg-muted text-sm", children: "Range" }),
265
+ /* @__PURE__ */ jsx(
266
+ "select",
267
+ {
268
+ id: "over-time-period",
269
+ value: overTimePeriod,
270
+ onChange: (e) => setOverTimePeriod(e.target.value),
271
+ className: "h-9 rounded-md border border-ui-border-base bg-transparent px-3 text-sm text-ui-fg-base outline-none transition focus:ring-2 focus:ring-ui-fg-interactive",
272
+ children: OVER_TIME_PERIODS.map((p) => /* @__PURE__ */ jsx("option", { value: p.value, children: p.label }, p.value))
273
+ }
274
+ )
275
+ ] })
276
+ ] }),
277
+ /* @__PURE__ */ jsx("div", { className: "h-72", children: overTimeLoading ? /* @__PURE__ */ jsx(
278
+ "div",
279
+ {
280
+ className: "flex items-center justify-center h-full",
281
+ role: "status",
282
+ "aria-label": "Loading orders over time",
283
+ children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted", children: "Loading chart…" })
284
+ }
285
+ ) : overTimeError ? /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center h-full", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger", children: overTimeError }) }) : /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxs(
286
+ LineChart,
287
+ {
288
+ data: dailyOrders,
289
+ margin: { top: 8, right: 8, left: 8, bottom: 8 },
290
+ children: [
291
+ /* @__PURE__ */ jsx(CartesianGrid, { strokeDasharray: "3 3", className: "stroke-ui-border-base" }),
3285
292
  /* @__PURE__ */ jsx(
3286
- Label,
293
+ XAxis,
3287
294
  {
3288
- htmlFor: "products-channel-filter",
3289
- className: "shrink-0 whitespace-nowrap text-ui-fg-muted text-xs font-medium",
3290
- children: "Channel"
295
+ dataKey: "date",
296
+ tick: { fontSize: 12 },
297
+ tickFormatter: (v, index) => {
298
+ const row = dailyOrders[index];
299
+ if (row == null ? void 0 : row.label) return row.label;
300
+ const d = new Date(v);
301
+ return `${d.getUTCMonth() + 1}/${d.getUTCDate()}`;
302
+ }
3291
303
  }
3292
304
  ),
3293
- /* @__PURE__ */ jsxs(
3294
- "select",
3295
- {
3296
- id: "products-channel-filter",
3297
- value: salesChannelId,
3298
- onChange: (event) => setSalesChannelId(event.target.value),
3299
- disabled: filtersLoading,
3300
- className: SELECT_CLASS_NAME,
3301
- "aria-busy": filtersLoading,
3302
- children: [
3303
- /* @__PURE__ */ jsx("option", { value: "all", children: "All channels" }),
3304
- salesChannels.map((channel) => /* @__PURE__ */ jsx("option", { value: channel.id, children: channel.name }, channel.id))
3305
- ]
3306
- }
3307
- )
3308
- ] }),
3309
- /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-2 sm:flex-initial sm:flex-none", children: [
3310
305
  /* @__PURE__ */ jsx(
3311
- Label,
306
+ YAxis,
3312
307
  {
3313
- htmlFor: "products-summary-period",
3314
- className: "shrink-0 whitespace-nowrap text-ui-fg-muted text-xs font-medium",
3315
- children: "Period"
308
+ tick: { fontSize: 12 },
309
+ allowDecimals: false,
310
+ domain: [0, "auto"],
311
+ ticks: (() => {
312
+ const max = Math.max(
313
+ 1,
314
+ ...dailyOrders.map((d) => d.orders_count ?? 0)
315
+ );
316
+ const step = max <= 10 ? 1 : Math.ceil(max / 6);
317
+ const arr = [];
318
+ for (let i = 0; i <= max; i += step) arr.push(i);
319
+ if (arr[arr.length - 1] !== max) arr.push(max);
320
+ return arr;
321
+ })(),
322
+ tickFormatter: (v) => String(Math.floor(Number(v) || 0))
3316
323
  }
3317
324
  ),
325
+ /* @__PURE__ */ jsx(Tooltip, { content: /* @__PURE__ */ jsx(OrdersOverTimeTooltip, {}) }),
3318
326
  /* @__PURE__ */ jsx(
3319
- "select",
327
+ Line,
3320
328
  {
3321
- id: "products-summary-period",
3322
- value: summaryDays,
3323
- onChange: (event) => setSummaryDays(event.target.value),
3324
- className: SELECT_CLASS_NAME,
3325
- children: SUMMARY_PERIODS.map((period) => /* @__PURE__ */ jsx("option", { value: period.value, children: period.label }, period.value))
329
+ type: "monotone",
330
+ dataKey: "orders_count",
331
+ name: "Orders",
332
+ stroke: "var(--medusa-color-ui-fg-interactive)",
333
+ strokeWidth: 2,
334
+ dot: { r: 3 }
3326
335
  }
3327
336
  )
3328
- ] }),
3329
- /* @__PURE__ */ jsxs("div", { className: "flex w-full shrink-0 flex-wrap items-center gap-x-3 gap-y-1 sm:w-auto sm:pl-1", children: [
3330
- summaryDays !== "all" ? /* @__PURE__ */ jsx(
3331
- "button",
3332
- {
3333
- type: "button",
3334
- onClick: () => setSummaryDays("all"),
3335
- className: "text-xs text-ui-fg-muted transition-colors hover:text-ui-fg-base",
3336
- "aria-label": "Clear summary period filter",
3337
- children: "Clear period"
3338
- }
3339
- ) : null,
3340
- salesChannelId !== "all" ? /* @__PURE__ */ jsx(
3341
- "button",
3342
- {
3343
- type: "button",
3344
- onClick: () => setSalesChannelId("all"),
3345
- className: "text-xs text-ui-fg-muted transition-colors hover:text-ui-fg-base",
3346
- "aria-label": "Clear sales channel filter",
3347
- children: "Clear channel"
3348
- }
3349
- ) : null
3350
- ] })
337
+ ]
338
+ }
339
+ ) }) })
340
+ ] })
341
+ ] });
342
+ }
343
+ function CustomersOverTimeTooltip({
344
+ active,
345
+ payload,
346
+ label
347
+ }) {
348
+ var _a, _b, _c;
349
+ if (!active || !(payload == null ? void 0 : payload.length)) return null;
350
+ const row = (_a = payload[0]) == null ? void 0 : _a.payload;
351
+ const displayLabel = (row == null ? void 0 : row.label) ?? (label ? new Date(label).toLocaleDateString() : label);
352
+ const registered = Math.floor(((_b = payload.find((p) => p.name === "Registered")) == null ? void 0 : _b.value) ?? 0);
353
+ const guest = Math.floor(((_c = payload.find((p) => p.name === "Guest")) == null ? void 0 : _c.value) ?? 0);
354
+ return /* @__PURE__ */ jsxs(
355
+ "div",
356
+ {
357
+ style: {
358
+ backgroundColor: "rgb(254, 254, 254)",
359
+ color: "#111827",
360
+ border: "1px solid rgb(229, 231, 235)",
361
+ borderRadius: "8px",
362
+ padding: "12px 16px",
363
+ boxShadow: "0 4px 14px rgba(0, 0, 0, 0.08)",
364
+ fontSize: "14px",
365
+ lineHeight: 1.5
366
+ },
367
+ children: [
368
+ /* @__PURE__ */ jsx("div", { style: { fontWeight: 600, marginBottom: "6px", color: "#111827" }, children: displayLabel }),
369
+ /* @__PURE__ */ jsxs("div", { style: { color: "#374151" }, children: [
370
+ "Registered: ",
371
+ /* @__PURE__ */ jsx("strong", { style: { color: "#1f2937" }, children: registered })
372
+ ] }),
373
+ /* @__PURE__ */ jsxs("div", { style: { color: "#374151" }, children: [
374
+ "Guest: ",
375
+ /* @__PURE__ */ jsx("strong", { style: { color: "#1f2937" }, children: guest })
3351
376
  ] })
377
+ ]
378
+ }
379
+ );
380
+ }
381
+ const COUNT_DAY_PRESETS = [
382
+ { value: "all", label: "All time" },
383
+ { value: "0", label: "Today" },
384
+ { value: "7", label: "Last 7 days" },
385
+ { value: "30", label: "Last 30 days" },
386
+ { value: "90", label: "Last 90 days" }
387
+ ];
388
+ const GRAPH_PERIODS = [
389
+ { value: "one_week", label: "One week" },
390
+ { value: "one_month", label: "One month" },
391
+ { value: "one_year", label: "One year" }
392
+ ];
393
+ const REGISTERED_COLOR = "var(--medusa-color-ui-fg-interactive)";
394
+ const GUEST_COLOR = "#6B7280";
395
+ function CustomersDashboard() {
396
+ const [data, setData] = useState(null);
397
+ const [loading, setLoading] = useState(true);
398
+ const [error, setError] = useState(null);
399
+ const [countDays, setCountDays] = useState("all");
400
+ const [series, setSeries] = useState([]);
401
+ const [graphPeriod, setGraphPeriod] = useState("one_week");
402
+ const [graphLoading, setGraphLoading] = useState(true);
403
+ const [graphError, setGraphError] = useState(null);
404
+ useEffect(() => {
405
+ let cancelled = false;
406
+ setLoading(true);
407
+ setError(null);
408
+ const url = `/admin/analytics/customers-summary?days=${countDays}`;
409
+ fetch(url).then((res) => {
410
+ if (!res.ok) throw new Error(res.statusText);
411
+ return res.json();
412
+ }).then((body) => {
413
+ if (!cancelled) setData(body);
414
+ }).catch((e) => {
415
+ if (!cancelled) setError(e instanceof Error ? e.message : String(e));
416
+ }).finally(() => {
417
+ if (!cancelled) setLoading(false);
418
+ });
419
+ return () => {
420
+ cancelled = true;
421
+ };
422
+ }, [countDays]);
423
+ useEffect(() => {
424
+ let cancelled = false;
425
+ setGraphLoading(true);
426
+ setGraphError(null);
427
+ const url = `/admin/analytics/customers-over-time?period=${graphPeriod}`;
428
+ fetch(url).then((res) => {
429
+ if (!res.ok) throw new Error(res.statusText);
430
+ return res.json();
431
+ }).then((body) => {
432
+ if (!cancelled) setSeries(body.series ?? []);
433
+ }).catch((e) => {
434
+ if (!cancelled) setGraphError(e instanceof Error ? e.message : String(e));
435
+ }).finally(() => {
436
+ if (!cancelled) setGraphLoading(false);
437
+ });
438
+ return () => {
439
+ cancelled = true;
440
+ };
441
+ }, [graphPeriod]);
442
+ if (loading) {
443
+ return /* @__PURE__ */ jsx(
444
+ "div",
445
+ {
446
+ className: "flex items-center justify-center min-h-[320px]",
447
+ role: "status",
448
+ "aria-label": "Loading analytics",
449
+ children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted", children: "Loading…" })
3352
450
  }
3353
- ),
3354
- /* @__PURE__ */ jsxs("div", { className: "space-y-2 p-2 pt-0 sm:p-3 sm:pt-0 md:p-4 md:pt-0", children: [
3355
- filtersError ? /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-dashed border-ui-border-base bg-ui-bg-subtle/30 px-3 py-2", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger text-xs", children: filtersError }) }) : null,
3356
- !viewsConnected ? /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-dashed border-ui-border-base bg-ui-bg-subtle/30 px-3 py-2", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[11px] leading-snug", children: "Product views are unavailable until the `medusa-product-helper` tracking module is registered and storefront page views are being recorded." }) }) : null,
3357
- salesChannelId !== "all" && viewsConnected ? /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-ui-border-base/80 bg-ui-bg-subtle/25 px-3 py-2 shadow-sm", children: /* @__PURE__ */ jsxs(Text, { className: "text-ui-fg-muted text-[11px] leading-snug", children: [
3358
- "Showing analytics for ",
3359
- /* @__PURE__ */ jsx("span", { className: "font-medium text-ui-fg-base", children: selectedChannelLabel }),
3360
- ". Views are scoped to products assigned to this sales channel."
3361
- ] }) }) : null,
3362
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
3363
- /* @__PURE__ */ jsx("div", { className: "px-0.5", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.16em]", children: "Product overview" }) }),
3364
- /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-6", children: primaryStats.map((stat) => /* @__PURE__ */ jsx(
3365
- AtlasKpiCard,
3366
- {
3367
- label: stat.label,
3368
- value: stat.value,
3369
- helper: stat.helper,
3370
- accent: stat.accent
3371
- },
3372
- stat.label
3373
- )) })
3374
- ] }),
3375
- /* @__PURE__ */ jsxs("div", { className: "mt-2 grid grid-cols-12 gap-2 lg:items-start", children: [
3376
- /* @__PURE__ */ jsx("div", { className: "col-span-12 lg:col-span-6", children: /* @__PURE__ */ jsx(
3377
- AnalyticsSection,
3378
- {
3379
- variant: "atlas",
3380
- actionsBare: true,
3381
- title: "Sales & views over time",
3382
- description: "Units and views share the left axis; revenue uses the right. Window totals match this range.",
3383
- actions: /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
3384
- /* @__PURE__ */ jsx(
3385
- Label,
3386
- {
3387
- htmlFor: "products-graph-period",
3388
- className: "shrink-0 text-ui-fg-muted text-xs font-medium",
3389
- children: "Range"
3390
- }
3391
- ),
3392
- /* @__PURE__ */ jsx(
3393
- "select",
3394
- {
3395
- id: "products-graph-period",
3396
- value: graphPeriod,
3397
- onChange: (event) => setGraphPeriod(event.target.value),
3398
- className: SELECT_CLASS_NAME,
3399
- children: GRAPH_PERIODS.map((period) => /* @__PURE__ */ jsx("option", { value: period.value, children: period.label }, period.value))
3400
- }
3401
- )
3402
- ] }),
3403
- children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2", children: [
3404
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-2 sm:grid-cols-3 sm:gap-1.5", children: [
3405
- /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", className: "min-h-0", children: /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
3406
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: "Window units" }),
3407
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-lg font-semibold tracking-tight", children: formatShortNumber(trendTotals.totalUnits) }),
3408
- /* @__PURE__ */ jsxs(Text, { className: "text-ui-fg-muted text-[10px]", children: [
3409
- "Avg/day ",
3410
- trendTotals.avgUnitsPerDay.toFixed(1)
3411
- ] })
3412
- ] }) }),
3413
- /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", className: "min-h-0", children: /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
3414
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: "Window revenue" }),
3415
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-lg font-semibold tracking-tight", children: formatCompactCurrency(trendTotals.totalRevenue) }),
3416
- /* @__PURE__ */ jsxs(Text, { className: "text-ui-fg-muted text-[10px]", children: [
3417
- "Avg/day ",
3418
- formatCompactCurrency(trendTotals.avgRevenuePerDay)
3419
- ] })
3420
- ] }) }),
3421
- /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", className: "min-h-0", children: /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
3422
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: "Window views" }),
3423
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-lg font-semibold tracking-tight", children: formatShortNumber(trendTotals.totalViews) }),
3424
- /* @__PURE__ */ jsxs(Text, { className: "text-ui-fg-muted text-[10px]", children: [
3425
- "Avg/day ",
3426
- trendTotals.avgViewsPerDay.toFixed(0)
3427
- ] })
3428
- ] }) })
3429
- ] }),
3430
- /* @__PURE__ */ jsxs(AnalyticsChartSurface, { variant: "atlas", className: "relative overflow-hidden", children: [
3431
- /* @__PURE__ */ jsx("div", { className: "pointer-events-none absolute inset-x-6 top-0 h-12 rounded-b-full bg-gradient-to-r from-sky-400/10 via-fuchsia-400/10 to-transparent blur-xl" }),
3432
- /* @__PURE__ */ jsxs("div", { className: "relative space-y-1", children: [
3433
- /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-1.5", children: [
3434
- /* @__PURE__ */ jsxs("div", { className: "space-y-0", children: [
3435
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.16em]", children: "Trend overview" }),
3436
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base text-sm font-semibold", children: selectedGraphPeriodLabel })
3437
- ] }),
3438
- /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap justify-end gap-2 text-[10px] text-ui-fg-muted", children: [
3439
- /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1", children: [
3440
- /* @__PURE__ */ jsx("span", { className: "h-1.5 w-1.5 rounded-full bg-sky-400" }),
3441
- "Units"
3442
- ] }),
3443
- /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1", children: [
3444
- /* @__PURE__ */ jsx("span", { className: "h-1.5 w-1.5 rounded-full bg-violet-400" }),
3445
- "Views"
3446
- ] }),
3447
- /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1", children: [
3448
- /* @__PURE__ */ jsx("span", { className: "h-1.5 w-1.5 rounded-full bg-fuchsia-400" }),
3449
- "Revenue"
3450
- ] })
3451
- ] })
3452
- ] }),
3453
- /* @__PURE__ */ jsx("div", { className: "h-[min(168px,24vh)] min-h-[140px] sm:h-[min(184px,26vh)]", children: overTimeLoading ? /* @__PURE__ */ jsx(
3454
- "div",
3455
- {
3456
- className: "flex h-full items-center justify-center",
3457
- role: "status",
3458
- "aria-label": "Loading product trend chart",
3459
- children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "Loading chart…" })
3460
- }
3461
- ) : overTimeError ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center px-2", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger text-center text-xs", children: overTimeError }) }) : series.length === 0 ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "No data in this range." }) }) : /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxs(
3462
- ComposedChart,
3463
- {
3464
- data: series,
3465
- margin: { top: 4, right: 6, left: -6, bottom: 0 },
3466
- children: [
3467
- /* @__PURE__ */ jsxs("defs", { children: [
3468
- /* @__PURE__ */ jsxs(
3469
- "linearGradient",
3470
- {
3471
- id: gid("trend-units-line"),
3472
- x1: "0",
3473
- y1: "0",
3474
- x2: "1",
3475
- y2: "0",
3476
- children: [
3477
- /* @__PURE__ */ jsx("stop", { offset: "0%", stopColor: "#67E8F9" }),
3478
- /* @__PURE__ */ jsx("stop", { offset: "100%", stopColor: "#3B82F6" })
3479
- ]
3480
- }
3481
- ),
3482
- /* @__PURE__ */ jsxs(
3483
- "linearGradient",
3484
- {
3485
- id: gid("trend-revenue-line"),
3486
- x1: "0",
3487
- y1: "0",
3488
- x2: "1",
3489
- y2: "0",
3490
- children: [
3491
- /* @__PURE__ */ jsx("stop", { offset: "0%", stopColor: "#F472B6" }),
3492
- /* @__PURE__ */ jsx("stop", { offset: "100%", stopColor: "#C084FC" })
3493
- ]
3494
- }
3495
- ),
3496
- /* @__PURE__ */ jsxs(
3497
- "linearGradient",
3498
- {
3499
- id: gid("trend-units-area"),
3500
- x1: "0",
3501
- y1: "0",
3502
- x2: "0",
3503
- y2: "1",
3504
- children: [
3505
- /* @__PURE__ */ jsx("stop", { offset: "0%", stopColor: "#38BDF8", stopOpacity: 0.22 }),
3506
- /* @__PURE__ */ jsx("stop", { offset: "100%", stopColor: "#38BDF8", stopOpacity: 0 })
3507
- ]
3508
- }
3509
- ),
3510
- /* @__PURE__ */ jsxs(
3511
- "linearGradient",
3512
- {
3513
- id: gid("trend-revenue-area"),
3514
- x1: "0",
3515
- y1: "0",
3516
- x2: "0",
3517
- y2: "1",
3518
- children: [
3519
- /* @__PURE__ */ jsx("stop", { offset: "0%", stopColor: "#E879F9", stopOpacity: 0.2 }),
3520
- /* @__PURE__ */ jsx("stop", { offset: "100%", stopColor: "#E879F9", stopOpacity: 0 })
3521
- ]
3522
- }
3523
- ),
3524
- /* @__PURE__ */ jsxs(
3525
- "linearGradient",
3526
- {
3527
- id: gid("trend-views-area"),
3528
- x1: "0",
3529
- y1: "0",
3530
- x2: "0",
3531
- y2: "1",
3532
- children: [
3533
- /* @__PURE__ */ jsx("stop", { offset: "0%", stopColor: "#C084FC", stopOpacity: 0.18 }),
3534
- /* @__PURE__ */ jsx("stop", { offset: "100%", stopColor: "#C084FC", stopOpacity: 0 })
3535
- ]
3536
- }
3537
- )
3538
- ] }),
3539
- /* @__PURE__ */ jsx(
3540
- CartesianGrid,
3541
- {
3542
- stroke: "rgba(148,163,184,0.14)",
3543
- strokeDasharray: "3 3",
3544
- vertical: false
3545
- }
3546
- ),
3547
- /* @__PURE__ */ jsx(
3548
- XAxis,
3549
- {
3550
- dataKey: "date",
3551
- tick: CHART_AXIS_TICK,
3552
- tickLine: false,
3553
- axisLine: false,
3554
- tickFormatter: (value) => {
3555
- const row = series.find((p) => p.date === String(value));
3556
- return (row == null ? void 0 : row.label) ?? formatChartLabel(String(value));
3557
- }
3558
- }
3559
- ),
3560
- /* @__PURE__ */ jsx(
3561
- YAxis,
3562
- {
3563
- yAxisId: "counts",
3564
- width: 32,
3565
- tick: CHART_AXIS_TICK,
3566
- tickLine: false,
3567
- axisLine: false,
3568
- allowDecimals: false,
3569
- tickFormatter: (value) => Math.floor(Number(value) || 0).toLocaleString()
3570
- }
3571
- ),
3572
- /* @__PURE__ */ jsx(
3573
- YAxis,
3574
- {
3575
- yAxisId: "revenue",
3576
- orientation: "right",
3577
- width: 40,
3578
- tick: CHART_AXIS_TICK,
3579
- tickLine: false,
3580
- axisLine: false,
3581
- tickFormatter: (value) => formatCompactCurrency(Number(value) || 0)
3582
- }
3583
- ),
3584
- /* @__PURE__ */ jsx(
3585
- Tooltip,
3586
- {
3587
- content: /* @__PURE__ */ jsx(TrendTooltip, {}),
3588
- cursor: {
3589
- stroke: "rgba(248, 250, 252, 0.35)",
3590
- strokeWidth: 1
3591
- }
3592
- }
3593
- ),
3594
- /* @__PURE__ */ jsx(
3595
- Area,
3596
- {
3597
- yAxisId: "counts",
3598
- type: "natural",
3599
- dataKey: "units_sold",
3600
- stroke: "none",
3601
- fill: `url(#${gid("trend-units-area")})`,
3602
- isAnimationActive: false,
3603
- legendType: "none"
3604
- }
3605
- ),
3606
- /* @__PURE__ */ jsx(
3607
- Area,
3608
- {
3609
- yAxisId: "counts",
3610
- type: "natural",
3611
- dataKey: "views",
3612
- stroke: "none",
3613
- fill: `url(#${gid("trend-views-area")})`,
3614
- isAnimationActive: false,
3615
- legendType: "none"
3616
- }
3617
- ),
3618
- /* @__PURE__ */ jsx(
3619
- Area,
3620
- {
3621
- yAxisId: "revenue",
3622
- type: "natural",
3623
- dataKey: "revenue",
3624
- stroke: "none",
3625
- fill: `url(#${gid("trend-revenue-area")})`,
3626
- isAnimationActive: false,
3627
- legendType: "none"
3628
- }
3629
- ),
3630
- /* @__PURE__ */ jsx(
3631
- Line,
3632
- {
3633
- yAxisId: "counts",
3634
- type: "natural",
3635
- dataKey: "units_sold",
3636
- name: "Units sold",
3637
- stroke: `url(#${gid("trend-units-line")})`,
3638
- strokeWidth: 2,
3639
- dot: false,
3640
- activeDot: { r: 4, fill: PRODUCT_CHART_COLORS.units }
3641
- }
3642
- ),
3643
- /* @__PURE__ */ jsx(
3644
- Line,
3645
- {
3646
- yAxisId: "counts",
3647
- type: "natural",
3648
- dataKey: "views",
3649
- name: "Views",
3650
- stroke: PRODUCT_CHART_COLORS.views,
3651
- strokeWidth: 1.5,
3652
- strokeDasharray: "4 3",
3653
- dot: false,
3654
- activeDot: { r: 4, fill: PRODUCT_CHART_COLORS.views }
3655
- }
3656
- ),
3657
- /* @__PURE__ */ jsx(
3658
- Line,
3659
- {
3660
- yAxisId: "revenue",
3661
- type: "natural",
3662
- dataKey: "revenue",
3663
- name: "Revenue",
3664
- stroke: `url(#${gid("trend-revenue-line")})`,
3665
- strokeWidth: 2,
3666
- dot: false,
3667
- activeDot: { r: 4, fill: PRODUCT_CHART_COLORS.revenue }
3668
- }
3669
- )
3670
- ]
3671
- }
3672
- ) }) })
3673
- ] })
3674
- ] })
3675
- ] })
3676
- }
3677
- ) }),
3678
- /* @__PURE__ */ jsxs("div", { className: "col-span-12 flex flex-col gap-2 lg:col-span-6", children: [
451
+ );
452
+ }
453
+ if (error || !data) {
454
+ return /* @__PURE__ */ jsx(Container, { className: "p-6", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger", children: error ?? "Failed to load analytics" }) });
455
+ }
456
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-8", children: [
457
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-4", children: [
458
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: "Customers" }),
459
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
460
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
3679
461
  /* @__PURE__ */ jsx(
3680
- AnalyticsSection,
462
+ Label,
3681
463
  {
3682
- variant: "atlas",
3683
- title: "Pulse & range",
3684
- description: "Totals for the chart window above — independent of the summary period filter.",
3685
- children: /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 gap-2", children: quickPulseMetrics.map((metric) => /* @__PURE__ */ jsxs(
3686
- "div",
3687
- {
3688
- className: `rounded-lg border border-ui-border-base bg-ui-bg-base px-2 py-2 shadow-sm ${metric.accentClassName}`.trim(),
3689
- children: [
3690
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-[10px] font-medium uppercase tracking-[0.14em]", children: metric.label }),
3691
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-base mt-0.5 text-sm font-semibold tracking-tight", children: metric.value }),
3692
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted mt-0.5 text-[9px] leading-snug", children: metric.helper })
3693
- ]
3694
- },
3695
- metric.label
3696
- )) })
464
+ htmlFor: "customers-count-period",
465
+ className: "text-ui-fg-muted text-sm",
466
+ children: "Period (counts)"
3697
467
  }
3698
468
  ),
3699
469
  /* @__PURE__ */ jsx(
3700
- AnalyticsSection,
470
+ "select",
3701
471
  {
3702
- variant: "atlas",
3703
- actionsBare: true,
3704
- title: "Best sellers",
3705
- description: bestSellerTrendProductTitle ? `Revenue and units over time for “${bestSellerTrendProductTitle}” (#1 by units sold in this window; all-time uses a 12‑month chart).` : "Revenue and units over time for the top product by units sold in this window (all-time leaderboard uses a 12‑month chart).",
3706
- actions: /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
3707
- /* @__PURE__ */ jsx(
3708
- Label,
3709
- {
3710
- htmlFor: "products-top-seller-period",
3711
- className: "shrink-0 text-ui-fg-muted text-xs font-medium",
3712
- children: "Window"
3713
- }
3714
- ),
3715
- /* @__PURE__ */ jsx(
3716
- "select",
3717
- {
3718
- id: "products-top-seller-period",
3719
- value: topSellerPeriod,
3720
- onChange: (event) => setTopSellerPeriod(event.target.value),
3721
- className: SELECT_CLASS_NAME,
3722
- children: TOP_SELLER_PERIODS.map((period) => /* @__PURE__ */ jsx("option", { value: period.value, children: period.label }, period.value))
3723
- }
3724
- )
3725
- ] }),
3726
- children: /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", className: "min-w-0 overflow-x-auto", children: /* @__PURE__ */ jsx("div", { className: "h-[212px] min-w-[280px] w-full sm:h-[228px]", children: bestSellersTrendLoading ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "Loading…" }) }) : bestSellersTrendError ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center px-2", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger text-center text-xs", children: bestSellersTrendError }) }) : bestSellersTrendSeries.length === 0 ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "No product sales for this range." }) }) : /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", minWidth: 0, children: /* @__PURE__ */ jsxs(
3727
- ComposedChart,
3728
- {
3729
- data: bestSellersTrendSeries,
3730
- margin: { left: 0, right: 8, top: 6, bottom: 2 },
3731
- children: [
3732
- /* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsxs(
3733
- "linearGradient",
3734
- {
3735
- id: gid("best-revenue-area"),
3736
- x1: "0",
3737
- y1: "0",
3738
- x2: "0",
3739
- y2: "1",
3740
- children: [
3741
- /* @__PURE__ */ jsx(
3742
- "stop",
3743
- {
3744
- offset: "0%",
3745
- stopColor: PRODUCT_CHART_COLORS.revenue,
3746
- stopOpacity: 0.22
3747
- }
3748
- ),
3749
- /* @__PURE__ */ jsx(
3750
- "stop",
3751
- {
3752
- offset: "100%",
3753
- stopColor: PRODUCT_CHART_COLORS.revenue,
3754
- stopOpacity: 0
3755
- }
3756
- )
3757
- ]
3758
- }
3759
- ) }),
3760
- /* @__PURE__ */ jsx(
3761
- CartesianGrid,
3762
- {
3763
- strokeDasharray: "3 3",
3764
- vertical: false,
3765
- stroke: "rgba(148,163,184,0.12)"
3766
- }
3767
- ),
3768
- /* @__PURE__ */ jsx(
3769
- XAxis,
3770
- {
3771
- dataKey: "date",
3772
- tick: CHART_AXIS_TICK_SM,
3773
- tickFormatter: (value) => {
3774
- const row = bestSellersTrendSeries.find(
3775
- (p) => p.date === String(value)
3776
- );
3777
- return (row == null ? void 0 : row.label) ?? formatChartLabel(String(value));
3778
- },
3779
- tickLine: false,
3780
- axisLine: { stroke: CHART_AXIS_LINE }
3781
- }
3782
- ),
3783
- /* @__PURE__ */ jsx(
3784
- YAxis,
3785
- {
3786
- yAxisId: "units",
3787
- tick: CHART_AXIS_TICK_SM,
3788
- tickFormatter: (value) => formatShortNumber(Number(value)),
3789
- width: 36,
3790
- tickLine: false,
3791
- axisLine: { stroke: CHART_AXIS_LINE },
3792
- allowDecimals: false
3793
- }
3794
- ),
3795
- /* @__PURE__ */ jsx(
3796
- YAxis,
3797
- {
3798
- yAxisId: "revenue",
3799
- orientation: "right",
3800
- tick: CHART_AXIS_TICK_SM,
3801
- tickFormatter: (value) => formatCompactCurrency(Number(value)),
3802
- width: 44,
3803
- tickLine: false,
3804
- axisLine: { stroke: CHART_AXIS_LINE }
3805
- }
3806
- ),
3807
- /* @__PURE__ */ jsx(
3808
- Tooltip,
3809
- {
3810
- content: (tooltipProps) => /* @__PURE__ */ jsx(
3811
- MiniTrendTooltip,
3812
- {
3813
- ...tooltipProps,
3814
- productHeadline: bestSellerTrendProductTitle,
3815
- hideViewsRow: true
3816
- }
3817
- )
3818
- }
3819
- ),
3820
- /* @__PURE__ */ jsx(
3821
- Area,
3822
- {
3823
- yAxisId: "revenue",
3824
- type: "natural",
3825
- dataKey: "revenue",
3826
- name: "Revenue",
3827
- stroke: "transparent",
3828
- fill: `url(#${gid("best-revenue-area")})`,
3829
- isAnimationActive: false
3830
- }
3831
- ),
3832
- /* @__PURE__ */ jsx(
3833
- Line,
3834
- {
3835
- yAxisId: "revenue",
3836
- type: "natural",
3837
- dataKey: "revenue",
3838
- name: "Revenue",
3839
- stroke: PRODUCT_CHART_COLORS.revenue,
3840
- strokeWidth: 2,
3841
- dot: false,
3842
- activeDot: { r: 4, fill: PRODUCT_CHART_COLORS.revenue },
3843
- isAnimationActive: false
3844
- }
3845
- ),
3846
- /* @__PURE__ */ jsx(
3847
- Line,
3848
- {
3849
- yAxisId: "units",
3850
- type: "natural",
3851
- dataKey: "units_sold",
3852
- name: "Units sold",
3853
- stroke: PRODUCT_CHART_COLORS.units,
3854
- strokeWidth: 2,
3855
- dot: false,
3856
- activeDot: { r: 4, fill: PRODUCT_CHART_COLORS.units },
3857
- isAnimationActive: false
3858
- }
3859
- )
3860
- ]
3861
- }
3862
- ) }) }) })
472
+ id: "customers-count-period",
473
+ value: countDays,
474
+ onChange: (e) => setCountDays(e.target.value),
475
+ className: "h-9 rounded-md border border-ui-border-base bg-transparent px-3 text-sm text-ui-fg-base outline-none transition focus:ring-2 focus:ring-ui-fg-interactive",
476
+ children: COUNT_DAY_PRESETS.map((p) => /* @__PURE__ */ jsx("option", { value: p.value, children: p.label }, p.value))
3863
477
  }
3864
478
  )
3865
- ] })
3866
- ] }),
3867
- /* @__PURE__ */ jsxs("div", { className: "mt-2 grid grid-cols-1 gap-2 md:grid-cols-2 md:items-stretch xl:grid-cols-3 xl:gap-3", children: [
3868
- /* @__PURE__ */ jsx(
3869
- AnalyticsSection,
3870
- {
3871
- variant: "atlas",
3872
- className: "min-w-0 md:col-span-1 xl:col-span-1",
3873
- title: "Leaderboard table",
3874
- description: "Products ranked by units sold — same window as Best sellers.",
3875
- children: /* @__PURE__ */ jsx("div", { className: "min-h-[212px] min-w-0 sm:min-h-[228px]", children: /* @__PURE__ */ jsx(AnalyticsTableSurface, { className: "shadow-sm", children: /* @__PURE__ */ jsxs(Table, { className: LEADERBOARD_TABLE_CLASS, children: [
3876
- /* @__PURE__ */ jsx(Table.Header, { children: /* @__PURE__ */ jsxs(Table.Row, { children: [
3877
- /* @__PURE__ */ jsx(Table.HeaderCell, { className: TABLE_HEAD_CELL_NOWRAP, children: "Product" }),
3878
- /* @__PURE__ */ jsx(Table.HeaderCell, { className: TABLE_HEAD_CELL_NOWRAP, children: "Units" }),
3879
- /* @__PURE__ */ jsx(Table.HeaderCell, { className: TABLE_HEAD_CELL_NOWRAP, children: "Orders" }),
3880
- /* @__PURE__ */ jsx(Table.HeaderCell, { className: TABLE_HEAD_CELL_NOWRAP, children: "Revenue" })
3881
- ] }) }),
3882
- /* @__PURE__ */ jsxs(Table.Body, { children: [
3883
- topSellersError ? /* @__PURE__ */ jsxs(Table.Row, { children: [
3884
- /* @__PURE__ */ jsx(Table.Cell, { children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger text-xs", children: topSellersError }) }),
3885
- /* @__PURE__ */ jsx(Table.Cell, {}),
3886
- /* @__PURE__ */ jsx(Table.Cell, {}),
3887
- /* @__PURE__ */ jsx(Table.Cell, {})
3888
- ] }) : null,
3889
- !topSellersError ? topSellersByUnits.slice(0, 8).map((product) => {
3890
- var _a2;
3891
- return /* @__PURE__ */ jsxs(
3892
- Table.Row,
3893
- {
3894
- className: product.product_id === ((_a2 = topSellersByUnits[0]) == null ? void 0 : _a2.product_id) ? "bg-emerald-500/5" : void 0,
3895
- children: [
3896
- /* @__PURE__ */ jsx(Table.Cell, { children: product.product_title }),
3897
- /* @__PURE__ */ jsx(Table.Cell, { children: product.units_sold.toLocaleString() }),
3898
- /* @__PURE__ */ jsx(Table.Cell, { children: product.order_count.toLocaleString() }),
3899
- /* @__PURE__ */ jsx(Table.Cell, { children: formatCurrency(product.revenue) })
3900
- ]
3901
- },
3902
- product.product_id
3903
- );
3904
- }) : null,
3905
- !topSellersLoading && !topSellersError && (((_i = topSellers == null ? void 0 : topSellers.products) == null ? void 0 : _i.length) ?? 0) === 0 ? /* @__PURE__ */ jsxs(Table.Row, { children: [
3906
- /* @__PURE__ */ jsx(Table.Cell, { children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "No best seller data yet." }) }),
3907
- /* @__PURE__ */ jsx(Table.Cell, {}),
3908
- /* @__PURE__ */ jsx(Table.Cell, {}),
3909
- /* @__PURE__ */ jsx(Table.Cell, {})
3910
- ] }) : null
3911
- ] })
3912
- ] }) }) })
3913
- }
3914
- ),
3915
- /* @__PURE__ */ jsx(
3916
- AnalyticsSection,
3917
- {
3918
- variant: "atlas",
3919
- className: "min-w-0 md:col-span-1 xl:col-span-1",
3920
- title: "Most viewed products",
3921
- description: mostViewedTrendProductTitle ? `Views over time for “${mostViewedTrendProductTitle}” (top of the list for your summary period; buckets follow period: today / 7d → week, 30d → month, 90d / all → year).` : "Views over time for the most-viewed product in your summary period (buckets: today / 7d → week, 30d → month, 90d / all → year).",
3922
- children: performanceLoading ? /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsx("div", { className: "flex h-[212px] items-center justify-center sm:h-[228px]", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "Loading…" }) }) }) : performanceError ? /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsx("div", { className: "flex h-[212px] items-center justify-center px-2 sm:h-[228px]", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger text-center text-xs", children: performanceError }) }) }) : !(performance == null ? void 0 : performance.productViewsConnected) ? /* @__PURE__ */ jsx("div", { className: "min-h-[212px] sm:min-h-[228px]", children: /* @__PURE__ */ jsx(
3923
- EmptyAnalyticsPanel,
3924
- {
3925
- title: "Views unavailable",
3926
- description: "Product view tracking is not available in this environment."
3927
- }
3928
- ) }) : ((performance == null ? void 0 : performance.topViewedProducts) ?? []).length === 0 ? /* @__PURE__ */ jsx("div", { className: "min-h-[212px] sm:min-h-[228px]", children: /* @__PURE__ */ jsx(
3929
- EmptyAnalyticsPanel,
3930
- {
3931
- title: "No views",
3932
- description: "No product views found for this summary period."
3933
- }
3934
- ) }) : /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", className: "min-w-0 overflow-x-auto", children: /* @__PURE__ */ jsx("div", { className: "h-[212px] min-w-[280px] w-full sm:h-[228px]", children: mostViewedTrendLoading ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "Loading chart…" }) }) : mostViewedTrendError ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center px-2", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger text-center text-xs", children: mostViewedTrendError }) }) : mostViewedTrendSeries.length === 0 ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "No view data in this range." }) }) : /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", minWidth: 0, children: /* @__PURE__ */ jsxs(
3935
- ComposedChart,
3936
- {
3937
- data: mostViewedTrendSeries,
3938
- margin: { left: 0, right: 8, top: 6, bottom: 2 },
3939
- children: [
3940
- /* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsxs(
3941
- "linearGradient",
3942
- {
3943
- id: gid("viewed-views-area"),
3944
- x1: "0",
3945
- y1: "0",
3946
- x2: "0",
3947
- y2: "1",
3948
- children: [
3949
- /* @__PURE__ */ jsx(
3950
- "stop",
3951
- {
3952
- offset: "0%",
3953
- stopColor: PRODUCT_CHART_COLORS.views,
3954
- stopOpacity: 0.22
3955
- }
3956
- ),
3957
- /* @__PURE__ */ jsx(
3958
- "stop",
3959
- {
3960
- offset: "100%",
3961
- stopColor: PRODUCT_CHART_COLORS.views,
3962
- stopOpacity: 0
3963
- }
3964
- )
3965
- ]
3966
- }
3967
- ) }),
3968
- /* @__PURE__ */ jsx(
3969
- CartesianGrid,
3970
- {
3971
- strokeDasharray: "3 3",
3972
- vertical: false,
3973
- stroke: "rgba(148,163,184,0.12)"
3974
- }
3975
- ),
3976
- /* @__PURE__ */ jsx(
3977
- XAxis,
3978
- {
3979
- dataKey: "date",
3980
- tick: CHART_AXIS_TICK_SM,
3981
- tickFormatter: (value) => {
3982
- const row = mostViewedTrendSeries.find(
3983
- (p) => p.date === String(value)
3984
- );
3985
- return (row == null ? void 0 : row.label) ?? formatChartLabel(String(value));
3986
- },
3987
- tickLine: false,
3988
- axisLine: { stroke: CHART_AXIS_LINE }
3989
- }
3990
- ),
3991
- /* @__PURE__ */ jsx(
3992
- YAxis,
3993
- {
3994
- tick: CHART_AXIS_TICK_SM,
3995
- tickFormatter: (value) => formatShortNumber(Number(value)),
3996
- width: 36,
3997
- tickLine: false,
3998
- axisLine: { stroke: CHART_AXIS_LINE },
3999
- allowDecimals: false
4000
- }
4001
- ),
4002
- /* @__PURE__ */ jsx(
4003
- Tooltip,
4004
- {
4005
- content: (tooltipProps) => /* @__PURE__ */ jsx(
4006
- MiniTrendTooltip,
4007
- {
4008
- ...tooltipProps,
4009
- productHeadline: mostViewedTrendProductTitle,
4010
- hideUnitsRow: true,
4011
- hideRevenueRow: true
4012
- }
4013
- )
4014
- }
4015
- ),
4016
- /* @__PURE__ */ jsx(
4017
- Area,
4018
- {
4019
- type: "natural",
4020
- dataKey: "views",
4021
- name: "Views",
4022
- stroke: "transparent",
4023
- fill: `url(#${gid("viewed-views-area")})`,
4024
- isAnimationActive: false
4025
- }
4026
- ),
4027
- /* @__PURE__ */ jsx(
4028
- Line,
4029
- {
4030
- type: "natural",
4031
- dataKey: "views",
4032
- name: "Views",
4033
- stroke: PRODUCT_CHART_COLORS.views,
4034
- strokeWidth: 2,
4035
- dot: false,
4036
- activeDot: { r: 4, fill: PRODUCT_CHART_COLORS.views },
4037
- isAnimationActive: false
4038
- }
4039
- )
4040
- ]
4041
- }
4042
- ) }) }) })
4043
- }
4044
- ),
4045
- /* @__PURE__ */ jsx(
4046
- AnalyticsSection,
479
+ ] }),
480
+ countDays !== "all" && /* @__PURE__ */ jsx(
481
+ "button",
4047
482
  {
4048
- variant: "atlas",
4049
- className: "min-w-0 md:col-span-2 xl:col-span-1",
4050
- title: "View-to-sales opportunities",
4051
- description: "Products with attention but weaker unit conversion.",
4052
- children: /* @__PURE__ */ jsx("div", { className: "min-h-[212px] min-w-0 sm:min-h-[228px]", children: /* @__PURE__ */ jsx(AnalyticsTableSurface, { className: "shadow-sm", children: /* @__PURE__ */ jsxs(Table, { className: OPPORTUNITIES_TABLE_CLASS, children: [
4053
- /* @__PURE__ */ jsx(Table.Header, { children: /* @__PURE__ */ jsxs(Table.Row, { children: [
4054
- /* @__PURE__ */ jsx(Table.HeaderCell, { className: TABLE_HEAD_CELL_NOWRAP, children: "Product" }),
4055
- /* @__PURE__ */ jsx(Table.HeaderCell, { className: TABLE_HEAD_CELL_NOWRAP, children: "Views" }),
4056
- /* @__PURE__ */ jsx(Table.HeaderCell, { className: TABLE_HEAD_CELL_NOWRAP, children: "Units" }),
4057
- /* @__PURE__ */ jsx(Table.HeaderCell, { className: TABLE_HEAD_CELL_NOWRAP, children: "Views / unit" })
4058
- ] }) }),
4059
- /* @__PURE__ */ jsxs(Table.Body, { children: [
4060
- ((performance == null ? void 0 : performance.viewOpportunities) ?? []).slice(0, 8).map((product) => /* @__PURE__ */ jsxs(Table.Row, { children: [
4061
- /* @__PURE__ */ jsx(Table.Cell, { children: product.product_title }),
4062
- /* @__PURE__ */ jsx(Table.Cell, { children: product.total_views.toLocaleString() }),
4063
- /* @__PURE__ */ jsx(Table.Cell, { children: product.units_sold.toLocaleString() }),
4064
- /* @__PURE__ */ jsx(Table.Cell, { children: formatRatio(product.views_per_unit) })
4065
- ] }, product.product_id)),
4066
- !performanceLoading && !performanceError && (((_j = performance == null ? void 0 : performance.viewOpportunities) == null ? void 0 : _j.length) ?? 0) === 0 ? /* @__PURE__ */ jsxs(Table.Row, { children: [
4067
- /* @__PURE__ */ jsx(Table.Cell, { children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "No product view opportunities yet." }) }),
4068
- /* @__PURE__ */ jsx(Table.Cell, {}),
4069
- /* @__PURE__ */ jsx(Table.Cell, {}),
4070
- /* @__PURE__ */ jsx(Table.Cell, {})
4071
- ] }) : null
4072
- ] })
4073
- ] }) }) })
483
+ type: "button",
484
+ onClick: () => setCountDays("all"),
485
+ className: "text-xs text-ui-fg-muted hover:text-ui-fg-base transition-colors",
486
+ "aria-label": "Show all customers (clear filter)",
487
+ children: "Clear filter"
4074
488
  }
4075
489
  )
490
+ ] })
491
+ ] }),
492
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4", children: [
493
+ /* @__PURE__ */ jsxs(Container, { className: "p-4", children: [
494
+ /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm", children: "Guest customers" }),
495
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: Math.floor(data.guestCount).toLocaleString() })
496
+ ] }),
497
+ /* @__PURE__ */ jsxs(Container, { className: "p-4", children: [
498
+ /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm", children: "Registered customers" }),
499
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: Math.floor(data.registeredCount).toLocaleString() })
500
+ ] }),
501
+ /* @__PURE__ */ jsxs(Container, { className: "p-4", children: [
502
+ /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm", children: "Overall customers" }),
503
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: Math.floor(data.totalCount).toLocaleString() })
504
+ ] }),
505
+ /* @__PURE__ */ jsxs(Container, { className: "p-4", children: [
506
+ /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm", children: "Deleted accounts" }),
507
+ /* @__PURE__ */ jsx(Heading, { level: "h2", children: (data.deletedAccountsCount ?? 0).toLocaleString() })
508
+ ] })
509
+ ] }),
510
+ /* @__PURE__ */ jsxs(Container, { className: "p-6", children: [
511
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-4 mb-4", children: [
512
+ /* @__PURE__ */ jsx(Heading, { level: "h3", children: "Customers over time" }),
513
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
514
+ /* @__PURE__ */ jsx(
515
+ Label,
516
+ {
517
+ htmlFor: "customers-graph-period",
518
+ className: "text-ui-fg-muted text-sm",
519
+ children: "Range"
520
+ }
521
+ ),
522
+ /* @__PURE__ */ jsx(
523
+ "select",
524
+ {
525
+ id: "customers-graph-period",
526
+ value: graphPeriod,
527
+ onChange: (e) => setGraphPeriod(e.target.value),
528
+ className: "h-9 rounded-md border border-ui-border-base bg-transparent px-3 text-sm text-ui-fg-base outline-none transition focus:ring-2 focus:ring-ui-fg-interactive",
529
+ children: GRAPH_PERIODS.map((p) => /* @__PURE__ */ jsx("option", { value: p.value, children: p.label }, p.value))
530
+ }
531
+ )
532
+ ] })
4076
533
  ] }),
4077
- /* @__PURE__ */ jsx(
4078
- AnalyticsSection,
534
+ /* @__PURE__ */ jsx("div", { className: "h-72", children: graphLoading ? /* @__PURE__ */ jsx(
535
+ "div",
4079
536
  {
4080
- variant: "atlas",
4081
- className: "mt-2",
4082
- title: "Views vs units sold",
4083
- description: "Each point is a product (top viewed in this period). Requires product view tracking.",
4084
- children: /* @__PURE__ */ jsx(AnalyticsChartSurface, { variant: "atlas", children: /* @__PURE__ */ jsx("div", { className: "h-[220px] w-full sm:h-[248px]", children: performanceLoading ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "Loading scatter…" }) }) : performanceError || !performance ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center px-2", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger text-center text-xs", children: performanceError ?? "Failed to load product performance" }) }) : !performance.productViewsConnected ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "Product view tracking is not available in this environment." }) }) : viewsVsUnitsScatterData.length === 0 ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-xs", children: "No products with views or sales in this range." }) }) : /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxs(ScatterChart, { margin: { top: 12, right: 16, bottom: 8, left: 8 }, children: [
4085
- /* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsxs("radialGradient", { id: gid("scatter-glow"), cx: "50%", cy: "50%", r: "50%", children: [
4086
- /* @__PURE__ */ jsx("stop", { offset: "0%", stopColor: "#E879F9", stopOpacity: 0.95 }),
4087
- /* @__PURE__ */ jsx("stop", { offset: "100%", stopColor: "#6366F1", stopOpacity: 0.65 })
4088
- ] }) }),
537
+ className: "flex items-center justify-center h-full",
538
+ role: "status",
539
+ "aria-label": "Loading customers over time",
540
+ children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted", children: "Loading chart…" })
541
+ }
542
+ ) : graphError ? /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center h-full", children: /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-danger", children: graphError }) }) : /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxs(
543
+ LineChart,
544
+ {
545
+ data: series,
546
+ margin: { top: 8, right: 8, left: 8, bottom: 8 },
547
+ children: [
4089
548
  /* @__PURE__ */ jsx(
4090
549
  CartesianGrid,
4091
550
  {
4092
551
  strokeDasharray: "3 3",
4093
- stroke: "rgba(148,163,184,0.14)"
552
+ className: "stroke-ui-border-base"
4094
553
  }
4095
554
  ),
4096
555
  /* @__PURE__ */ jsx(
4097
556
  XAxis,
4098
557
  {
4099
- type: "number",
4100
- dataKey: "total_views",
4101
- name: "Views",
4102
- tick: CHART_AXIS_TICK_SM,
4103
- stroke: CHART_AXIS_LINE,
4104
- tickLine: { stroke: CHART_AXIS_LINE },
4105
- allowDecimals: false,
4106
- label: {
4107
- value: "Views",
4108
- position: "insideBottom",
4109
- offset: -4,
4110
- fontSize: 10,
4111
- fill: "#9ca3af"
558
+ dataKey: "date",
559
+ tick: { fontSize: 12 },
560
+ tickFormatter: (v, index) => {
561
+ const row = series[index];
562
+ if (row == null ? void 0 : row.label) return row.label;
563
+ const d = new Date(v);
564
+ return `${d.getUTCMonth() + 1}/${d.getUTCDate()}`;
4112
565
  }
4113
566
  }
4114
567
  ),
4115
568
  /* @__PURE__ */ jsx(
4116
569
  YAxis,
4117
570
  {
4118
- type: "number",
4119
- dataKey: "units_sold",
4120
- name: "Units sold",
4121
- tick: CHART_AXIS_TICK_SM,
4122
- stroke: CHART_AXIS_LINE,
4123
- tickLine: { stroke: CHART_AXIS_LINE },
4124
- allowDecimals: false,
4125
- label: {
4126
- value: "Units sold",
4127
- angle: -90,
4128
- position: "insideLeft",
4129
- fontSize: 10,
4130
- fill: "#9ca3af"
4131
- }
571
+ tick: { fontSize: 12 },
572
+ tickFormatter: (v) => String(Math.floor(Number(v))),
573
+ allowDecimals: false
4132
574
  }
4133
575
  ),
576
+ /* @__PURE__ */ jsx(Tooltip, { content: /* @__PURE__ */ jsx(CustomersOverTimeTooltip, {}) }),
577
+ /* @__PURE__ */ jsx(Legend, {}),
4134
578
  /* @__PURE__ */ jsx(
4135
- Tooltip,
579
+ Line,
4136
580
  {
4137
- cursor: { strokeDasharray: "4 4", stroke: "rgba(148,163,184,0.45)" },
4138
- content: /* @__PURE__ */ jsx(ProductBarTooltip, {})
581
+ type: "monotone",
582
+ dataKey: "registered_count",
583
+ name: "Registered",
584
+ stroke: REGISTERED_COLOR,
585
+ strokeWidth: 2,
586
+ dot: { r: 3 }
4139
587
  }
4140
588
  ),
4141
589
  /* @__PURE__ */ jsx(
4142
- Scatter,
590
+ Line,
4143
591
  {
4144
- name: "Products",
4145
- data: viewsVsUnitsScatterData,
4146
- fill: `url(#${gid("scatter-glow")})`
592
+ type: "monotone",
593
+ dataKey: "guest_count",
594
+ name: "Guest",
595
+ stroke: GUEST_COLOR,
596
+ strokeWidth: 2,
597
+ dot: { r: 3 }
4147
598
  }
4148
599
  )
4149
- ] }) }) }) })
600
+ ]
4150
601
  }
4151
- )
602
+ ) }) })
4152
603
  ] })
4153
- ] }) });
604
+ ] });
4154
605
  }
4155
606
  const ANALYTICS_MODULES = [
4156
607
  { id: "orders", label: "Orders" },
4157
- { id: "customers", label: "Customers" },
4158
- { id: "products", label: "Products" }
608
+ { id: "customers", label: "Customers" }
4159
609
  ];
4160
610
  const AnalyticsPage = () => {
4161
611
  const [activeModule, setActiveModule] = useState("orders");
4162
- return /* @__PURE__ */ jsx(AnalyticsCurrencyProvider, { children: /* @__PURE__ */ jsx("div", { className: "flex h-full bg-ui-bg-subtle", children: /* @__PURE__ */ jsx("main", { className: "flex-1 overflow-auto", children: /* @__PURE__ */ jsxs(
4163
- "div",
4164
- {
4165
- className: `mx-auto flex w-full min-w-0 flex-col ${activeModule === "products" ? "max-w-full gap-2 px-3 py-3 sm:px-4 sm:py-3" : "max-w-[1600px] gap-4 p-4"}`.trim(),
4166
- children: [
4167
- /* @__PURE__ */ jsx(Container, { className: "overflow-hidden rounded-xl border border-ui-border-base bg-ui-bg-base p-0 shadow-sm", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4 px-4 py-4 sm:gap-5 sm:px-5 sm:py-5 xl:flex-row xl:items-end xl:justify-between", children: [
4168
- /* @__PURE__ */ jsxs("div", { className: "min-w-0 space-y-1.5", children: [
4169
- /* @__PURE__ */ jsx(Heading, { level: "h1", className: "tracking-tight", children: "Analytics" }),
4170
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted text-sm", children: "Review orders, customers, and products in one organized workspace." })
4171
- ] }),
4172
- /* @__PURE__ */ jsx(
4173
- "div",
4174
- {
4175
- className: "flex shrink-0 flex-wrap items-center gap-1",
4176
- role: "tablist",
4177
- "aria-label": "Analytics modules",
4178
- children: ANALYTICS_MODULES.map((m) => {
4179
- const active = activeModule === m.id;
4180
- return /* @__PURE__ */ jsx(
4181
- "button",
4182
- {
4183
- type: "button",
4184
- role: "tab",
4185
- "aria-selected": active,
4186
- onClick: () => setActiveModule(m.id),
4187
- className: `rounded-md px-3 py-1.5 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ui-fg-interactive focus-visible:ring-offset-2 focus-visible:ring-offset-ui-bg-base ${active ? "bg-ui-bg-base text-ui-fg-base shadow-sm" : "text-ui-fg-muted hover:bg-ui-bg-base/60 hover:text-ui-fg-base"}`.trim(),
4188
- children: m.label
4189
- },
4190
- m.id
4191
- );
4192
- })
4193
- }
4194
- )
4195
- ] }) }),
4196
- /* @__PURE__ */ jsxs("div", { className: "min-w-0 w-full", children: [
4197
- activeModule === "orders" && /* @__PURE__ */ jsx(OrdersDashboard, {}),
4198
- activeModule === "customers" && /* @__PURE__ */ jsx(CustomersDashboard, {}),
4199
- activeModule === "products" && /* @__PURE__ */ jsx(ProductsDashboard, {})
4200
- ] })
4201
- ]
4202
- }
4203
- ) }) }) });
612
+ return /* @__PURE__ */ jsx("div", { className: "flex h-full bg-ui-bg-base", children: /* @__PURE__ */ jsx("main", { className: "flex-1 overflow-auto", children: /* @__PURE__ */ jsx(Container, { className: "divide-y p-0", children: /* @__PURE__ */ jsxs("div", { className: "py-6 px-6", children: [
613
+ /* @__PURE__ */ jsx(Heading, { level: "h1", className: "mb-4", children: "Analytics" }),
614
+ /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2 mb-6", children: ANALYTICS_MODULES.map((m) => /* @__PURE__ */ jsx(
615
+ Button,
616
+ {
617
+ variant: activeModule === m.id ? "secondary" : "transparent",
618
+ size: "small",
619
+ onClick: () => setActiveModule(m.id),
620
+ children: m.label
621
+ },
622
+ m.id
623
+ )) }),
624
+ activeModule === "orders" && /* @__PURE__ */ jsx(OrdersDashboard, {}),
625
+ activeModule === "customers" && /* @__PURE__ */ jsx(CustomersDashboard, {})
626
+ ] }) }) }) });
4204
627
  };
4205
628
  const config = defineRouteConfig({
4206
629
  label: "Analytics",