@tokenoftrust/storefront-runner 6.14.3 → 6.14.4

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.
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The per-sku sold / unsold / velocity report behind `GET /api/apps/v1/reports`.
3
+ *
4
+ * Scoped to one tenant and one commerce stage. Sold units come from the paid orders in that stage's
5
+ * order ledger whose placement falls inside the window (cancelled, voided and refunded orders do not
6
+ * count); unsold units are the stage's projected availability balance; velocity is sold units per
7
+ * day over the window; days of cover is unsold units over velocity (null when nothing sold).
8
+ */
9
+ import type { CommerceStage } from "@tot/public-runtime";
10
+ import { readAvailabilityBalances } from "@/lib/inventory/mirrorStock.js";
11
+ import { readLedgerContractOrderRecords } from "@/lib/orders/data/ledgerContractOrders.js";
12
+ import { ScrappyOrderLedger } from "@/lib/orders/data/ordersStore.js";
13
+
14
+ export const SALES_VELOCITY_REPORT_ID = "sales-velocity";
15
+ export const DEFAULT_REPORT_WINDOW_DAYS = 30;
16
+ export const MAX_REPORT_WINDOW_DAYS = 365;
17
+
18
+ type Queryable = ConstructorParameters<typeof ScrappyOrderLedger>[0];
19
+
20
+ const DAY_MS = 86_400_000;
21
+
22
+ export interface SalesVelocitySku {
23
+ sku: string;
24
+ soldUnits: number;
25
+ unsoldUnits: number;
26
+ velocityPerDay: number;
27
+ daysOfCover: number | null;
28
+ }
29
+
30
+ export interface SalesVelocityReport {
31
+ id: typeof SALES_VELOCITY_REPORT_ID;
32
+ title: string;
33
+ generatedAt: string;
34
+ format: "json";
35
+ window: { days: number; from: string; to: string };
36
+ skus: SalesVelocitySku[];
37
+ }
38
+
39
+ /** A valid `windowDays` query value, or null when it is not an integer in 1..MAX_REPORT_WINDOW_DAYS. */
40
+ export function parseReportWindowDays(raw: string | null): number | null {
41
+ if (raw === null) return DEFAULT_REPORT_WINDOW_DAYS;
42
+ if (!/^[0-9]{1,4}$/.test(raw)) return null;
43
+ const days = Number(raw);
44
+ return days >= 1 && days <= MAX_REPORT_WINDOW_DAYS ? days : null;
45
+ }
46
+
47
+ function round(value: number, places: number): number {
48
+ const factor = 10 ** places;
49
+ return Math.round(value * factor) / factor;
50
+ }
51
+
52
+ export async function buildSalesVelocityReport(
53
+ db: Queryable,
54
+ input: { tenantId: string; stage: CommerceStage; windowDays: number; now: Date },
55
+ ): Promise<SalesVelocityReport> {
56
+ const toMs = input.now.getTime();
57
+ const fromMs = toMs - input.windowDays * DAY_MS;
58
+
59
+ const records = await readLedgerContractOrderRecords(
60
+ new ScrappyOrderLedger(db),
61
+ { tenantId: input.tenantId, stage: input.stage },
62
+ async () => "",
63
+ );
64
+ const sold = new Map<string, number>();
65
+ for (const { order } of records) {
66
+ if (order.status === "cancelled") continue;
67
+ const placedMs = Date.parse(order.createdAt);
68
+ if (!Number.isFinite(placedMs) || placedMs < fromMs || placedMs > toMs) continue;
69
+ for (const line of order.lineItems ?? []) {
70
+ sold.set(line.sku, (sold.get(line.sku) ?? 0) + line.quantity);
71
+ }
72
+ }
73
+
74
+ const balances = await readAvailabilityBalances(db, { tenantId: input.tenantId, stage: input.stage });
75
+ const skus = [...new Set([...sold.keys(), ...balances.keys()])].sort();
76
+
77
+ return {
78
+ id: SALES_VELOCITY_REPORT_ID,
79
+ title: "Sold, unsold and sales velocity by sku",
80
+ generatedAt: input.now.toISOString(),
81
+ format: "json",
82
+ window: { days: input.windowDays, from: new Date(fromMs).toISOString(), to: input.now.toISOString() },
83
+ skus: skus.map((sku) => {
84
+ const soldUnits = sold.get(sku) ?? 0;
85
+ const unsoldUnits = Math.max(0, balances.get(sku)?.balance ?? 0);
86
+ const velocity = soldUnits / input.windowDays;
87
+ return {
88
+ sku,
89
+ soldUnits,
90
+ unsoldUnits,
91
+ velocityPerDay: round(velocity, 4),
92
+ daysOfCover: velocity > 0 ? round(unsoldUnits / velocity, 2) : null,
93
+ };
94
+ }),
95
+ };
96
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.14.3",
3
+ "version": "6.14.4",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
6
6
  "packageManager": "pnpm@11.9.0",