@tokenoftrust/storefront-runner 6.14.2 → 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.
- package/apps/storefront/public/js/dashboard-apps.js +11 -1
- package/apps/storefront/src/lib/fulfillment/fulfillmentService.ts +21 -6
- package/apps/storefront/src/lib/integrations/apps/reports/salesVelocityReport.ts +96 -0
- package/apps/storefront/src/lib/integrations/webhooks/commercePayloads.ts +12 -1
- package/apps/storefront/src/lib/integrations/webhooks/deliveryStore.ts +18 -1
- package/apps/storefront/src/lib/integrations/webhooks/events.ts +1 -0
- package/apps/storefront/src/lib/orders/vault/appRecipientRead.ts +11 -6
- package/package.json +1 -1
|
@@ -22,6 +22,13 @@
|
|
|
22
22
|
return ms >= 1000 ? (ms / 1000).toFixed(1) + "s" : ms + "ms";
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
function fmtAge(seconds) {
|
|
26
|
+
if (seconds < 60) return seconds + "s";
|
|
27
|
+
if (seconds < 3600) return Math.floor(seconds / 60) + "m";
|
|
28
|
+
if (seconds < 86400) return Math.floor(seconds / 3600) + "h";
|
|
29
|
+
return Math.floor(seconds / 86400) + "d";
|
|
30
|
+
}
|
|
31
|
+
|
|
25
32
|
function badge(text, cls) {
|
|
26
33
|
const span = document.createElement("span");
|
|
27
34
|
span.className = "badge " + cls;
|
|
@@ -61,7 +68,10 @@
|
|
|
61
68
|
row("Webhook", app.hasWebhookEndpoint ? "configured" : "not configured");
|
|
62
69
|
row("p95 delivery", fmtDuration(app.health.p95DeliveryMs));
|
|
63
70
|
row("Failure streak", String(app.health.failureStreak));
|
|
64
|
-
row("Dead-lettered", String(app.
|
|
71
|
+
row("Dead-lettered", String(app.deadLetterCount));
|
|
72
|
+
if (app.deadLetterCount > 0 && app.oldestDeadLetterAgeSeconds !== null) {
|
|
73
|
+
row("Oldest dead letter", fmtAge(app.oldestDeadLetterAgeSeconds) + " ago");
|
|
74
|
+
}
|
|
65
75
|
if (app.health.lastSuccessAt) row("Last success", app.health.lastSuccessAt);
|
|
66
76
|
card.appendChild(dl);
|
|
67
77
|
|
|
@@ -1354,11 +1354,8 @@ export class FulfillmentService {
|
|
|
1354
1354
|
params: [order.tenantId, order.stage, order.orderId, version],
|
|
1355
1355
|
};
|
|
1356
1356
|
const next = await purchaseIdFor(order.tenantId, order.stage, order.orderId, state.labelGeneration + 1);
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
sourceAdvance: false,
|
|
1360
|
-
deliveries: [],
|
|
1361
|
-
statements: [
|
|
1357
|
+
const plan: PlanStatements = { deliveries: [], statements: [] };
|
|
1358
|
+
plan.statements.push(
|
|
1362
1359
|
{
|
|
1363
1360
|
sql: `UPDATE scrappy_commerce_orders
|
|
1364
1361
|
SET label_state = 'none', event_version = event_version + 1
|
|
@@ -1403,7 +1400,25 @@ export class FulfillmentService {
|
|
|
1403
1400
|
version,
|
|
1404
1401
|
stamp(this.now(), state.auditCount + 1),
|
|
1405
1402
|
),
|
|
1406
|
-
|
|
1403
|
+
);
|
|
1404
|
+
this.appendCommerceEvent(plan, {
|
|
1405
|
+
tenantId: order.tenantId,
|
|
1406
|
+
stage: order.stage,
|
|
1407
|
+
topic: "fulfillment.label.voided",
|
|
1408
|
+
payload: {
|
|
1409
|
+
assignmentId: binding.assignmentId,
|
|
1410
|
+
orderId: order.orderId,
|
|
1411
|
+
purchaseId: evidence.purchaseId,
|
|
1412
|
+
occurredAt: this.now(),
|
|
1413
|
+
},
|
|
1414
|
+
gate: atVersion,
|
|
1415
|
+
installIds: [binding.installId],
|
|
1416
|
+
});
|
|
1417
|
+
return {
|
|
1418
|
+
type: "write",
|
|
1419
|
+
sourceAdvance: false,
|
|
1420
|
+
deliveries: plan.deliveries,
|
|
1421
|
+
statements: plan.statements,
|
|
1407
1422
|
view: appShipmentView(state, next, { version, label: "none", facts: null }),
|
|
1408
1423
|
};
|
|
1409
1424
|
});
|
|
@@ -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
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Payload admission for the commerce topics the single commerce emitter writes:
|
|
3
|
-
* `fulfillment.assignment.created`, `fulfillment.assignment.updated`, `order.fulfilled`,
|
|
3
|
+
* `fulfillment.assignment.created`, `fulfillment.assignment.updated`, `fulfillment.label.voided`, `order.fulfilled`,
|
|
4
4
|
* `order.partially_fulfilled` and `inventory.changed`.
|
|
5
5
|
*
|
|
6
6
|
* Each topic has a closed key set (`asyncapi.yaml` `FulfillmentAssignmentData`, `OrderData`
|
|
@@ -12,6 +12,7 @@ import type { WebhookTopic } from "./deliveryStore.js";
|
|
|
12
12
|
export type CommerceTopic =
|
|
13
13
|
| "fulfillment.assignment.created"
|
|
14
14
|
| "fulfillment.assignment.updated"
|
|
15
|
+
| "fulfillment.label.voided"
|
|
15
16
|
| "order.paid"
|
|
16
17
|
| "order.fulfilled"
|
|
17
18
|
| "order.partially_fulfilled"
|
|
@@ -22,6 +23,7 @@ export type CommerceTopic =
|
|
|
22
23
|
export const COMMERCE_TOPICS: readonly CommerceTopic[] = [
|
|
23
24
|
"fulfillment.assignment.created",
|
|
24
25
|
"fulfillment.assignment.updated",
|
|
26
|
+
"fulfillment.label.voided",
|
|
25
27
|
"order.paid",
|
|
26
28
|
"order.fulfilled",
|
|
27
29
|
"order.partially_fulfilled",
|
|
@@ -54,6 +56,7 @@ export const COMMERCE_PRIVATE_KEYS = new Set([
|
|
|
54
56
|
|
|
55
57
|
const ASSIGNMENT_KEYS = ["assignmentId", "orderId", "stage", "state", "eventVersion", "occurredAt"] as const;
|
|
56
58
|
const ASSIGNMENT_STATES = new Set(["active", "held", "cancelled"]);
|
|
59
|
+
const LABEL_VOIDED_KEYS = ["assignmentId", "orderId", "purchaseId", "occurredAt"] as const;
|
|
57
60
|
const ORDER_DATA_KEYS = new Set(["id", "status", "currency", "customerHash", "subtotal", "total", "lineItems"]);
|
|
58
61
|
const LINE_ITEM_KEYS = new Set(["sku", "handle", "quantity", "lineTotal"]);
|
|
59
62
|
export const INVENTORY_CHANGED_KEYS = ["sku", "locationId", "balance", "available", "asOf"] as const;
|
|
@@ -90,6 +93,13 @@ function assignmentAdmissible(topic: CommerceTopic, payload: Record<string, unkn
|
|
|
90
93
|
return typeof payload.occurredAt === "string" && Number.isFinite(Date.parse(payload.occurredAt));
|
|
91
94
|
}
|
|
92
95
|
|
|
96
|
+
function labelVoidedAdmissible(payload: Record<string, unknown>): boolean {
|
|
97
|
+
const keys = Object.keys(payload);
|
|
98
|
+
if (keys.length !== LABEL_VOIDED_KEYS.length || !LABEL_VOIDED_KEYS.every((key) => keys.includes(key))) return false;
|
|
99
|
+
if (!nonEmptyString(payload.assignmentId) || !nonEmptyString(payload.orderId) || !nonEmptyString(payload.purchaseId)) return false;
|
|
100
|
+
return typeof payload.occurredAt === "string" && Number.isFinite(Date.parse(payload.occurredAt));
|
|
101
|
+
}
|
|
102
|
+
|
|
93
103
|
/** `OrderData` with `status` in `allowedStatuses` and optional/required `lineItems`. */
|
|
94
104
|
function orderDataAdmissible(
|
|
95
105
|
payload: Record<string, unknown>,
|
|
@@ -144,5 +154,6 @@ export function commercePayloadAdmissible(topic: CommerceTopic, payload: unknown
|
|
|
144
154
|
if (topic === "order.cancelled") return orderDataAdmissible(payload, ["cancelled"], true);
|
|
145
155
|
if (topic === "order.updated") return orderDataAdmissible(payload, ["created", "fulfilled", "cancelled"], true);
|
|
146
156
|
if (topic === "inventory.changed") return inventoryChangedAdmissible(payload);
|
|
157
|
+
if (topic === "fulfillment.label.voided") return labelVoidedAdmissible(payload);
|
|
147
158
|
return assignmentAdmissible(topic, payload);
|
|
148
159
|
}
|
|
@@ -60,7 +60,8 @@ export type WebhookTopic =
|
|
|
60
60
|
| "customer.marketing_consent.updated"
|
|
61
61
|
| "attribution.finalized"
|
|
62
62
|
| "fulfillment.assignment.created"
|
|
63
|
-
| "fulfillment.assignment.updated"
|
|
63
|
+
| "fulfillment.assignment.updated"
|
|
64
|
+
| "fulfillment.label.voided";
|
|
64
65
|
|
|
65
66
|
/** Mirrors `Delivery.state` in `docs/private-apps/contract/openapi.yaml` EXACTLY. */
|
|
66
67
|
export type DeliveryState = "pending" | "retrying" | "delivered" | "dead-lettered";
|
|
@@ -104,6 +105,12 @@ export interface InstallHealth {
|
|
|
104
105
|
recentTraceIds: string[];
|
|
105
106
|
}
|
|
106
107
|
|
|
108
|
+
/** The install's current dead-lettered deliveries: how many, and when the oldest parked. */
|
|
109
|
+
export interface DeadLetterSummary {
|
|
110
|
+
count: number;
|
|
111
|
+
oldestAt: string | null;
|
|
112
|
+
}
|
|
113
|
+
|
|
107
114
|
export interface CreateEventInput {
|
|
108
115
|
/** Optional caller-supplied event id (e.g. for a caller-owned idempotency key). Defaults to a fresh UUID. */
|
|
109
116
|
eventId?: string;
|
|
@@ -545,6 +552,16 @@ export class WebhookDeliveryStore {
|
|
|
545
552
|
return p95DeliveryMs != null ? { ...health, p95DeliveryMs } : health;
|
|
546
553
|
}
|
|
547
554
|
|
|
555
|
+
/** Counts the install's deliveries in `dead-lettered` now; `oldestAt` is when the oldest one parked. */
|
|
556
|
+
async deadLetterSummary(installId: string): Promise<DeadLetterSummary> {
|
|
557
|
+
const row = await this.db.first<{ count: number; oldest_at: string | null }>(
|
|
558
|
+
`SELECT COUNT(*) AS count, MIN(updated_at) AS oldest_at
|
|
559
|
+
FROM webhook_deliveries WHERE install_id = ? AND state = 'dead-lettered'`,
|
|
560
|
+
installId,
|
|
561
|
+
);
|
|
562
|
+
return { count: Number(row?.count ?? 0), oldestAt: row?.oldest_at ?? null };
|
|
563
|
+
}
|
|
564
|
+
|
|
548
565
|
/**
|
|
549
566
|
* p95 across `webhook_delivery_attempts.duration_ms` for the install's
|
|
550
567
|
* {@link P95_SAMPLE_SIZE} most recent deliveries — one bounded `IN (...)`
|
|
@@ -35,6 +35,7 @@ export const TOPIC_REQUIRED_SCOPE: Record<WebhookTopic, string | null> = {
|
|
|
35
35
|
"attribution.finalized": "attribution:write",
|
|
36
36
|
"fulfillment.assignment.created": "fulfillment:process",
|
|
37
37
|
"fulfillment.assignment.updated": "fulfillment:process",
|
|
38
|
+
"fulfillment.label.voided": "fulfillment:process",
|
|
38
39
|
};
|
|
39
40
|
|
|
40
41
|
/** `type`'s reverse-DNS prefix (asyncapi.yaml `CloudEventEnvelope.type`). */
|
|
@@ -66,7 +66,7 @@ export type AppRecipientCode =
|
|
|
66
66
|
|
|
67
67
|
export type AppRecipientOutcome =
|
|
68
68
|
| { ok: true; recipient: AppRecipient }
|
|
69
|
-
| { ok: false; status: number; code: AppRecipientCode };
|
|
69
|
+
| { ok: false; status: number; code: AppRecipientCode; retryAfterSeconds?: number };
|
|
70
70
|
|
|
71
71
|
export interface AppRecipientInput {
|
|
72
72
|
tenantId: string;
|
|
@@ -131,7 +131,7 @@ async function classifyRefusal(
|
|
|
131
131
|
deps: AppRecipientDeps,
|
|
132
132
|
input: AppRecipientInput,
|
|
133
133
|
admitted: { eventVersion: number },
|
|
134
|
-
): Promise<{ status: number; code: AppRecipientCode } | null> {
|
|
134
|
+
): Promise<{ status: number; code: AppRecipientCode; retryAfterSeconds?: number } | null> {
|
|
135
135
|
const { db } = deps;
|
|
136
136
|
const { tenantId, stage, installId, now } = input;
|
|
137
137
|
const current = await eligibility(deps, input);
|
|
@@ -154,11 +154,16 @@ async function classifyRefusal(
|
|
|
154
154
|
return { status: 403, code: latest.revoked_at !== null ? "consent-revoked" : "consent-expired" };
|
|
155
155
|
}
|
|
156
156
|
const hourAgo = new Date(now.getTime() - HOUR_MS).toISOString();
|
|
157
|
-
const used = await db.first<{ n: number }>(
|
|
158
|
-
"SELECT COUNT(*) AS n FROM app_contact_access_audit WHERE install_id = ? AND tenant_id = ? AND at > ?",
|
|
157
|
+
const used = await db.first<{ n: number; oldest: string | null }>(
|
|
158
|
+
"SELECT COUNT(*) AS n, MIN(at) AS oldest FROM app_contact_access_audit WHERE install_id = ? AND tenant_id = ? AND at > ?",
|
|
159
159
|
installId, tenantId, hourAgo,
|
|
160
160
|
);
|
|
161
|
-
if (Number(used?.n ?? 0) >= APP_CONTACT_READS_PER_HOUR)
|
|
161
|
+
if (Number(used?.n ?? 0) >= APP_CONTACT_READS_PER_HOUR) {
|
|
162
|
+
// The oldest counted read leaves the window an hour after it was admitted.
|
|
163
|
+
const oldest = used?.oldest ? Date.parse(used.oldest) : Number.NaN;
|
|
164
|
+
const wait = Number.isFinite(oldest) ? Math.ceil((oldest + HOUR_MS - now.getTime()) / 1000) : 1;
|
|
165
|
+
return { status: 429, code: "quota", retryAfterSeconds: Math.max(1, wait) };
|
|
166
|
+
}
|
|
162
167
|
return null;
|
|
163
168
|
}
|
|
164
169
|
|
|
@@ -205,7 +210,7 @@ export async function readAppRecipient(deps: AppRecipientDeps, input: AppRecipie
|
|
|
205
210
|
}
|
|
206
211
|
if (read.ok) return { ok: true, recipient: exported(input.orderId, read.shipTo) };
|
|
207
212
|
if (read.reason !== "not-admitted") return { ok: false, status: read.status, code: read.reason };
|
|
208
|
-
let why: { status: number; code: AppRecipientCode } | null;
|
|
213
|
+
let why: { status: number; code: AppRecipientCode; retryAfterSeconds?: number } | null;
|
|
209
214
|
try {
|
|
210
215
|
why = await classifyRefusal(deps, input, eligible);
|
|
211
216
|
} catch {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "6.14.
|
|
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",
|