@tokenoftrust/storefront-runner 6.12.4 → 6.12.6
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/migrations-apps/0028_app_jwk_and_candidates.sql +133 -0
- package/apps/storefront/migrations-apps/0029_inventory_locations_wms.sql +38 -0
- package/apps/storefront/src/lib/fulfillment/appShipmentEvidence.ts +24 -2
- package/apps/storefront/src/lib/fulfillment/carrierEvidence.ts +51 -11
- package/apps/storefront/src/lib/fulfillment/commerceProjection.ts +1 -1
- package/apps/storefront/src/lib/fulfillment/fulfillmentService.ts +178 -26
- package/apps/storefront/src/lib/fulfillment/readiness.ts +38 -9
- package/apps/storefront/src/lib/integrations/apps/credentials.ts +58 -1
- package/apps/storefront/src/lib/integrations/apps/inventoryWrite.ts +634 -89
- package/apps/storefront/src/lib/integrations/apps/registryAccess.ts +9 -5
- package/apps/storefront/src/lib/integrations/apps/registryService.ts +77 -30
- package/apps/storefront/src/lib/integrations/webhooks/commercePayloads.ts +2 -2
- package/apps/storefront/src/lib/integrations/webhooks/emit.ts +1 -126
- package/apps/storefront/src/lib/inventory/allocations.ts +87 -8
- package/apps/storefront/src/lib/inventory/mirrorStock.ts +453 -38
- package/apps/storefront/src/middleware/controlPlane.ts +2 -6
- package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +8 -1
- package/package.json +1 -1
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
import { AppRegistryService } from "./registryService.js";
|
|
17
17
|
import { D1CredentialStore } from "./credentials.js";
|
|
18
18
|
import { DEFAULT_APP_GATEWAY_KID, APP_GATEWAY_KID_ENV } from "./gatewayKeys.js";
|
|
19
|
-
import { fromD1 } from "../../catalog/d1/catalog.js";
|
|
19
|
+
import { fromD1, type Queryable } from "../../catalog/d1/catalog.js";
|
|
20
20
|
import { readD1, readEnv, readKv } from "../../publication/shared/env.js";
|
|
21
21
|
|
|
22
22
|
/**
|
|
@@ -36,12 +36,16 @@ export function json(body: unknown, status = 200): Response {
|
|
|
36
36
|
* this runtime. Never leaks binding/secret detail in the response body.
|
|
37
37
|
*/
|
|
38
38
|
export async function getRegistryService(): Promise<AppRegistryService | Response> {
|
|
39
|
+
const apps = await getAppsDb();
|
|
40
|
+
if (apps instanceof Response) return apps;
|
|
41
|
+
return new AppRegistryService(apps.db, new D1CredentialStore(apps.db, apps.activeKid));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The `STOREFRONT_APPS_DB` binding as a Queryable plus the active gateway kid, or a 503 Response. */
|
|
45
|
+
export async function getAppsDb(): Promise<{ db: Queryable; activeKid: string } | Response> {
|
|
39
46
|
const d1 = await readD1("STOREFRONT_APPS_DB");
|
|
40
47
|
if (!d1) return json({ error: "app registry not configured" }, 503);
|
|
41
|
-
|
|
42
|
-
const activeKid = (await readEnv(APP_GATEWAY_KID_ENV)) ?? DEFAULT_APP_GATEWAY_KID;
|
|
43
|
-
const credentials = new D1CredentialStore(db, activeKid);
|
|
44
|
-
return new AppRegistryService(db, credentials);
|
|
48
|
+
return { db: fromD1(d1), activeKid: (await readEnv(APP_GATEWAY_KID_ENV)) ?? DEFAULT_APP_GATEWAY_KID };
|
|
45
49
|
}
|
|
46
50
|
|
|
47
51
|
/**
|
|
@@ -102,8 +102,70 @@ export type AppAuditEvent =
|
|
|
102
102
|
| "resumed"
|
|
103
103
|
| "uninstalled"
|
|
104
104
|
| "credentials_rotated"
|
|
105
|
+
| "client_keys_registered"
|
|
105
106
|
| "rolled_back";
|
|
106
107
|
|
|
108
|
+
/** One `app_audit_log` row insert. `detail` carries opaque handles only, never key or secret material. */
|
|
109
|
+
export function auditRowStatement(params: {
|
|
110
|
+
installId: string;
|
|
111
|
+
tenantId: string;
|
|
112
|
+
event: AppAuditEvent;
|
|
113
|
+
actor: string;
|
|
114
|
+
at: string;
|
|
115
|
+
detail?: Record<string, unknown>;
|
|
116
|
+
traceId?: string;
|
|
117
|
+
}): { sql: string; params: unknown[] } {
|
|
118
|
+
return {
|
|
119
|
+
sql: `INSERT INTO app_audit_log (id, install_id, tenant_id, event, actor, trace_id, detail, at)
|
|
120
|
+
VALUES (?,?,?,?,?,?,?,?)`,
|
|
121
|
+
params: [
|
|
122
|
+
crypto.randomUUID(),
|
|
123
|
+
params.installId,
|
|
124
|
+
params.tenantId,
|
|
125
|
+
params.event,
|
|
126
|
+
params.actor,
|
|
127
|
+
params.traceId ?? null,
|
|
128
|
+
JSON.stringify(params.detail ?? {}),
|
|
129
|
+
params.at,
|
|
130
|
+
],
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The `app_installs` columns an install row writes, in {@link installRowStatement} parameter order. */
|
|
135
|
+
export const INSTALL_ROW_COLUMNS =
|
|
136
|
+
"install_id, app_id, app_version, tenant_id, env, status, scopes, manifest, webhook_endpoint, widget_placements, install_actor, created_at, updated_at";
|
|
137
|
+
|
|
138
|
+
/** The parameters of one active `app_installs` row, in {@link INSTALL_ROW_COLUMNS} order. */
|
|
139
|
+
export function installRowParams(row: {
|
|
140
|
+
installId: string;
|
|
141
|
+
appId: string;
|
|
142
|
+
appVersion: string;
|
|
143
|
+
tenantId: string;
|
|
144
|
+
env: string;
|
|
145
|
+
scopes: string[];
|
|
146
|
+
manifest: unknown;
|
|
147
|
+
webhookEndpoint: string | null;
|
|
148
|
+
widgetPlacements: WidgetPlacementInput[];
|
|
149
|
+
actor: string;
|
|
150
|
+
now: string;
|
|
151
|
+
}): unknown[] {
|
|
152
|
+
return [
|
|
153
|
+
row.installId,
|
|
154
|
+
row.appId,
|
|
155
|
+
row.appVersion,
|
|
156
|
+
row.tenantId,
|
|
157
|
+
row.env,
|
|
158
|
+
"active",
|
|
159
|
+
JSON.stringify(row.scopes),
|
|
160
|
+
JSON.stringify(row.manifest),
|
|
161
|
+
row.webhookEndpoint,
|
|
162
|
+
JSON.stringify(row.widgetPlacements),
|
|
163
|
+
row.actor,
|
|
164
|
+
row.now,
|
|
165
|
+
row.now,
|
|
166
|
+
];
|
|
167
|
+
}
|
|
168
|
+
|
|
107
169
|
/** The auth-derived context every install is scoped to — never caller input. */
|
|
108
170
|
export interface InstallActorContext {
|
|
109
171
|
tenantId: string;
|
|
@@ -441,22 +503,20 @@ export class AppRegistryService {
|
|
|
441
503
|
const installId = crypto.randomUUID();
|
|
442
504
|
const now = this.now();
|
|
443
505
|
await this.db.run(
|
|
444
|
-
`INSERT INTO app_installs
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
now,
|
|
459
|
-
now,
|
|
506
|
+
`INSERT INTO app_installs (${INSTALL_ROW_COLUMNS}) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
|
507
|
+
...installRowParams({
|
|
508
|
+
installId,
|
|
509
|
+
appId: input.appId,
|
|
510
|
+
appVersion: facets.appVersion,
|
|
511
|
+
tenantId: ctx.tenantId,
|
|
512
|
+
env: input.env,
|
|
513
|
+
scopes: validation.scopes,
|
|
514
|
+
manifest: input.manifest,
|
|
515
|
+
webhookEndpoint: input.webhookEndpoint ?? null,
|
|
516
|
+
widgetPlacements,
|
|
517
|
+
actor: ctx.actor,
|
|
518
|
+
now,
|
|
519
|
+
}),
|
|
460
520
|
);
|
|
461
521
|
|
|
462
522
|
let issued: IssuedCredentialSecret;
|
|
@@ -846,20 +906,7 @@ export class AppRegistryService {
|
|
|
846
906
|
detail?: Record<string, unknown>;
|
|
847
907
|
traceId?: string;
|
|
848
908
|
}): { sql: string; params: unknown[] } {
|
|
849
|
-
return {
|
|
850
|
-
sql: `INSERT INTO app_audit_log (id, install_id, tenant_id, event, actor, trace_id, detail, at)
|
|
851
|
-
VALUES (?,?,?,?,?,?,?,?)`,
|
|
852
|
-
params: [
|
|
853
|
-
crypto.randomUUID(),
|
|
854
|
-
params.installId,
|
|
855
|
-
params.tenantId,
|
|
856
|
-
params.event,
|
|
857
|
-
params.actor,
|
|
858
|
-
params.traceId ?? null,
|
|
859
|
-
JSON.stringify(params.detail ?? {}),
|
|
860
|
-
this.now(),
|
|
861
|
-
],
|
|
862
|
-
};
|
|
909
|
+
return auditRowStatement({ ...params, at: this.now() });
|
|
863
910
|
}
|
|
864
911
|
|
|
865
912
|
private async appendAudit(params: Parameters<AppRegistryService["auditStatement"]>[0]): Promise<void> {
|
|
@@ -50,7 +50,7 @@ const ASSIGNMENT_KEYS = ["assignmentId", "orderId", "stage", "state", "eventVers
|
|
|
50
50
|
const ASSIGNMENT_STATES = new Set(["active", "held", "cancelled"]);
|
|
51
51
|
const ORDER_DATA_KEYS = new Set(["id", "status", "currency", "customerHash", "subtotal", "total", "lineItems"]);
|
|
52
52
|
const LINE_ITEM_KEYS = new Set(["sku", "handle", "quantity", "lineTotal"]);
|
|
53
|
-
export const INVENTORY_CHANGED_KEYS = ["sku", "locationId", "balance", "asOf"] as const;
|
|
53
|
+
export const INVENTORY_CHANGED_KEYS = ["sku", "locationId", "balance", "available", "asOf"] as const;
|
|
54
54
|
const LOCATION_ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
55
55
|
|
|
56
56
|
export function isCommerceTopic(topic: WebhookTopic): topic is CommerceTopic {
|
|
@@ -113,7 +113,7 @@ export function inventoryChangedAdmissible(payload: unknown): boolean {
|
|
|
113
113
|
}
|
|
114
114
|
if (!nonEmptyString(payload.sku) || payload.sku.trim() !== payload.sku) return false;
|
|
115
115
|
if (typeof payload.locationId !== "string" || !LOCATION_ID_RE.test(payload.locationId)) return false;
|
|
116
|
-
if (!Number.isSafeInteger(payload.balance)) return false;
|
|
116
|
+
if (!Number.isSafeInteger(payload.balance) || !Number.isSafeInteger(payload.available)) return false;
|
|
117
117
|
return typeof payload.asOf === "string" && Number.isFinite(Date.parse(payload.asOf));
|
|
118
118
|
}
|
|
119
119
|
|
|
@@ -56,9 +56,6 @@ import {
|
|
|
56
56
|
COMMERCE_DELIVERY_GRACE_MS,
|
|
57
57
|
CommercePayloadRefused,
|
|
58
58
|
WebhookDeliveryStore,
|
|
59
|
-
commerceEventStatements,
|
|
60
|
-
commerceTargetsQuery,
|
|
61
|
-
type CommerceEventStatement,
|
|
62
59
|
type WebhookTopic,
|
|
63
60
|
} from "./deliveryStore.js";
|
|
64
61
|
import { commercePayloadAdmissible, isCommerceTopic } from "./commercePayloads.js";
|
|
@@ -67,7 +64,7 @@ import { TOPIC_REQUIRED_SCOPE } from "./events.js";
|
|
|
67
64
|
import { getDispatcher } from "./getDispatcher.js";
|
|
68
65
|
import { getRegistryService } from "../apps/registryAccess.js";
|
|
69
66
|
import type { AppInstall } from "../apps/registryService.js";
|
|
70
|
-
import { fromD1
|
|
67
|
+
import { fromD1 } from "../../catalog/d1/catalog.js";
|
|
71
68
|
import { setInventoryChangedNotify } from "../../inventory/mirrorStock.js";
|
|
72
69
|
import { getWorkerEnv, readD1, readEnv } from "../../publication/shared/env.js";
|
|
73
70
|
import type { CommerceStage } from "@tot/public-runtime";
|
|
@@ -215,38 +212,6 @@ export async function emitWebhookEvent<T extends WebhookTopic>(
|
|
|
215
212
|
return { eventId: event.id, deliveryCount: deliveries.length };
|
|
216
213
|
}
|
|
217
214
|
|
|
218
|
-
export interface InventoryChangedPayload {
|
|
219
|
-
sku: string;
|
|
220
|
-
locationId: string;
|
|
221
|
-
balance: number;
|
|
222
|
-
asOf: string;
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
export interface InventoryMovementIdentity {
|
|
226
|
-
tenantId: string;
|
|
227
|
-
stage: CommerceStage;
|
|
228
|
-
source: string;
|
|
229
|
-
sourceEventId: string;
|
|
230
|
-
sku: string;
|
|
231
|
-
locationId: string;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
async function digestPrefix(prefix: string, parts: readonly string[]): Promise<string> {
|
|
235
|
-
const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(parts.join("\n"))));
|
|
236
|
-
const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
237
|
-
return `${prefix}.${hex.slice(0, 48)}`;
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
/** Deterministic `webhook_events.id` for one inventory movement key, so replays cannot double-emit. */
|
|
241
|
-
export async function inventoryEventId(key: InventoryMovementIdentity): Promise<string> {
|
|
242
|
-
return digestPrefix("inv", [key.tenantId, key.stage, key.source, key.sourceEventId, key.sku, key.locationId]);
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
/** Deterministic `webhook_deliveries.delivery_id` for one `(eventId, installId)` pair. */
|
|
246
|
-
export async function inventoryDeliveryId(eventId: string, installId: string): Promise<string> {
|
|
247
|
-
return digestPrefix("invdlv", [eventId, installId]);
|
|
248
|
-
}
|
|
249
|
-
|
|
250
215
|
/**
|
|
251
216
|
* Best-effort dispatch after committing `inventory.changed` delivery rows: arms the tenant
|
|
252
217
|
* commerce alarm and enqueues each delivery on the configured dispatcher.
|
|
@@ -277,94 +242,4 @@ export async function dispatchInventoryDeliveries(
|
|
|
277
242
|
}
|
|
278
243
|
}
|
|
279
244
|
|
|
280
|
-
/**
|
|
281
|
-
* Emit `inventory.changed` once for a committed inventory movement on `db`. Writes the
|
|
282
|
-
* `webhook_events` row and one `pending` `webhook_deliveries` row per active `inventory:read`
|
|
283
|
-
* install on `input.tenantId` in the install env `input.stage` admits, gated on `input.gate` (defaulting to the movement row's presence in
|
|
284
|
-
* `commerce_inventory_movements`) and the absence of the deterministic `eventId`.
|
|
285
|
-
*/
|
|
286
|
-
export async function emitInventoryChanged(
|
|
287
|
-
db: Queryable,
|
|
288
|
-
input: InventoryMovementIdentity &
|
|
289
|
-
InventoryChangedPayload & {
|
|
290
|
-
gate?: CommerceEventStatement;
|
|
291
|
-
notify?: (tenantId: string, deliveryIds: readonly string[]) => void | Promise<void>;
|
|
292
|
-
},
|
|
293
|
-
): Promise<{ eventId: string; deliveryIds: string[] } | null> {
|
|
294
|
-
const eventId = await inventoryEventId(input);
|
|
295
|
-
const payload: InventoryChangedPayload = {
|
|
296
|
-
sku: input.sku,
|
|
297
|
-
locationId: input.locationId,
|
|
298
|
-
balance: input.balance,
|
|
299
|
-
asOf: input.asOf,
|
|
300
|
-
};
|
|
301
|
-
const targetsQuery = commerceTargetsQuery(input.tenantId, "inventory.changed", input.stage);
|
|
302
|
-
const installs = await db.all<{ install_id: string }>(targetsQuery.sql, ...targetsQuery.params);
|
|
303
|
-
const targets = await Promise.all(
|
|
304
|
-
installs.map(async (row) => ({
|
|
305
|
-
installId: row.install_id,
|
|
306
|
-
deliveryId: await inventoryDeliveryId(eventId, row.install_id),
|
|
307
|
-
})),
|
|
308
|
-
);
|
|
309
|
-
const existingEvent = await db.first<{ ok: number }>(`SELECT 1 AS ok FROM webhook_events WHERE id = ?`, eventId);
|
|
310
|
-
const existingDeliveries =
|
|
311
|
-
targets.length > 0
|
|
312
|
-
? await db.all<{ delivery_id: string }>(
|
|
313
|
-
`SELECT delivery_id FROM webhook_deliveries WHERE event_id = ?`,
|
|
314
|
-
eventId,
|
|
315
|
-
)
|
|
316
|
-
: [];
|
|
317
|
-
const existingDeliveryIds = new Set(existingDeliveries.map((row) => row.delivery_id));
|
|
318
|
-
const missingTargets = targets.filter((target) => !existingDeliveryIds.has(target.deliveryId));
|
|
319
|
-
if (existingEvent && missingTargets.length === 0) {
|
|
320
|
-
return { eventId, deliveryIds: targets.map((target) => target.deliveryId) };
|
|
321
|
-
}
|
|
322
|
-
const baseGate: CommerceEventStatement = input.gate ?? {
|
|
323
|
-
sql: `EXISTS (
|
|
324
|
-
SELECT 1 FROM commerce_inventory_movements
|
|
325
|
-
WHERE tenant_id = ? AND stage = ? AND source = ? AND source_event_id = ? AND sku = ? AND location_id = ?
|
|
326
|
-
)`,
|
|
327
|
-
params: [input.tenantId, input.stage, input.source, input.sourceEventId, input.sku, input.locationId],
|
|
328
|
-
};
|
|
329
|
-
const gate: CommerceEventStatement = {
|
|
330
|
-
sql: `(${baseGate.sql}) AND NOT EXISTS (SELECT 1 FROM webhook_events WHERE id = ?)`,
|
|
331
|
-
params: [...baseGate.params, eventId],
|
|
332
|
-
};
|
|
333
|
-
const statements = commerceEventStatements({
|
|
334
|
-
eventId,
|
|
335
|
-
tenantId: input.tenantId,
|
|
336
|
-
stage: input.stage,
|
|
337
|
-
topic: "inventory.changed",
|
|
338
|
-
payload,
|
|
339
|
-
gate,
|
|
340
|
-
targets,
|
|
341
|
-
now: input.asOf,
|
|
342
|
-
});
|
|
343
|
-
if (db.batch) {
|
|
344
|
-
await db.batch(statements.map((s) => ({ sql: s.sql, params: [...s.params] })));
|
|
345
|
-
} else {
|
|
346
|
-
for (const statement of statements) await db.run(statement.sql, ...statement.params);
|
|
347
|
-
}
|
|
348
|
-
const written = await db.first<{ ok: number }>(`SELECT 1 AS ok FROM webhook_events WHERE id = ?`, eventId);
|
|
349
|
-
if (!written) return null;
|
|
350
|
-
const committed =
|
|
351
|
-
targets.length > 0
|
|
352
|
-
? await db.all<{ delivery_id: string }>(
|
|
353
|
-
`SELECT delivery_id FROM webhook_deliveries WHERE event_id = ? ORDER BY created_at ASC, delivery_id ASC`,
|
|
354
|
-
eventId,
|
|
355
|
-
)
|
|
356
|
-
: [];
|
|
357
|
-
const deliveryIds = committed.map((row) => row.delivery_id);
|
|
358
|
-
const newDeliveryIds = deliveryIds.filter((id) => !existingDeliveryIds.has(id));
|
|
359
|
-
if (newDeliveryIds.length > 0) {
|
|
360
|
-
const notify = input.notify ?? dispatchInventoryDeliveries;
|
|
361
|
-
try {
|
|
362
|
-
await notify(input.tenantId, newDeliveryIds);
|
|
363
|
-
} catch {
|
|
364
|
-
// Pending rows remain durable in webhook_deliveries.
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
return { eventId, deliveryIds };
|
|
368
|
-
}
|
|
369
|
-
|
|
370
245
|
setInventoryChangedNotify(dispatchInventoryDeliveries);
|
|
@@ -346,6 +346,7 @@ export async function reserveAllocation(runner: StatementRunner, input: ReserveI
|
|
|
346
346
|
|
|
347
347
|
const seenAt = `${input.now}|${crypto.randomUUID()}`;
|
|
348
348
|
const holds = [...input.holds].sort((left, right) => left.sku.localeCompare(right.sku) || left.locationId.localeCompare(right.locationId));
|
|
349
|
+
const sync = allocationSync({ tenantId: input.tenantId, stage: input.stage, now: input.now, scope: itemScope(holds) });
|
|
349
350
|
const statements: SqlStatement[] = [
|
|
350
351
|
{
|
|
351
352
|
sql: `INSERT INTO scrappy_caller_replay (tenant_id, stage, issuer, jti, seen_at)
|
|
@@ -433,6 +434,7 @@ export async function reserveAllocation(runner: StatementRunner, input: ReserveI
|
|
|
433
434
|
RETURNING order_id`,
|
|
434
435
|
params: [input.tenantId, input.stage, input.orderId, input.tenantId, input.stage, input.orderId],
|
|
435
436
|
},
|
|
437
|
+
...sync.statements,
|
|
436
438
|
{
|
|
437
439
|
sql: `SELECT authorization_id, expires_at FROM scrappy_final_cart_authorizations
|
|
438
440
|
WHERE tenant_id = ? AND stage = ? AND cart_digest = ? AND state IN ('active', 'consumed')
|
|
@@ -454,6 +456,7 @@ export async function reserveAllocation(runner: StatementRunner, input: ReserveI
|
|
|
454
456
|
params: [input.tenantId,input.stage,cart.provider,cart.id],
|
|
455
457
|
});
|
|
456
458
|
const results = await runner.batch(statements);
|
|
459
|
+
await notifyAllocationSync(runner, input.tenantId, sync.token);
|
|
457
460
|
const replayRows = results[0] ?? [];
|
|
458
461
|
const authRows = results[2 + holds.length + (cart ? 1 : 0)] ?? [];
|
|
459
462
|
const selected = results[results.length - 1] ?? [];
|
|
@@ -494,6 +497,12 @@ export async function releaseHoldOnce(
|
|
|
494
497
|
},
|
|
495
498
|
): Promise<number> {
|
|
496
499
|
const scope = [input.tenantId, input.stage, input.orderId];
|
|
500
|
+
const sync = allocationSync({
|
|
501
|
+
tenantId: input.tenantId,
|
|
502
|
+
stage: input.stage,
|
|
503
|
+
now: new Date().toISOString(),
|
|
504
|
+
scope: orderScope(input.tenantId, input.stage, input.orderId),
|
|
505
|
+
});
|
|
497
506
|
const results = await runner.batch([
|
|
498
507
|
{
|
|
499
508
|
sql: `UPDATE scrappy_final_cart_authorizations
|
|
@@ -518,7 +527,9 @@ export async function releaseHoldOnce(
|
|
|
518
527
|
RETURNING order_id`,
|
|
519
528
|
params: [input.orderStock, ...scope],
|
|
520
529
|
},
|
|
530
|
+
...sync.statements,
|
|
521
531
|
]);
|
|
532
|
+
await notifyAllocationSync(runner, input.tenantId, sync.token);
|
|
522
533
|
return sumQuantity(results[1] ?? []);
|
|
523
534
|
}
|
|
524
535
|
|
|
@@ -529,6 +540,21 @@ export async function settleExpired(
|
|
|
529
540
|
const orderId = input.orderId ?? "";
|
|
530
541
|
const force = input.force ? 1 : 0;
|
|
531
542
|
const due = [input.tenantId, input.stage, orderId, orderId, input.now, force];
|
|
543
|
+
// Read before the batch: an allocation reserved after this read and expired by it stays counted
|
|
544
|
+
// until the next sync of its sku, which errs toward underselling.
|
|
545
|
+
const expiring = await runner.all(
|
|
546
|
+
`SELECT DISTINCT sku, location_id FROM scrappy_allocations
|
|
547
|
+
WHERE tenant_id = ? AND stage = ? AND state = 'reserved'
|
|
548
|
+
AND order_id IN (
|
|
549
|
+
SELECT authorization_id FROM scrappy_final_cart_authorizations
|
|
550
|
+
WHERE tenant_id = ? AND stage = ? AND state = 'active'
|
|
551
|
+
AND (? = '' OR authorization_id = ?)
|
|
552
|
+
AND (expires_at <= ? OR ? = 1)
|
|
553
|
+
)`,
|
|
554
|
+
[input.tenantId, input.stage, ...due],
|
|
555
|
+
);
|
|
556
|
+
const sync =
|
|
557
|
+
expiring.length > 0 ? allocationSync({ tenantId: input.tenantId, stage: input.stage, now: input.now, scope: rowsScope(expiring) }) : null;
|
|
532
558
|
const results = await runner.batch([
|
|
533
559
|
{
|
|
534
560
|
sql: `UPDATE scrappy_final_cart_authorizations
|
|
@@ -565,7 +591,9 @@ export async function settleExpired(
|
|
|
565
591
|
RETURNING order_id`,
|
|
566
592
|
params: [input.tenantId, input.stage, ...due],
|
|
567
593
|
},
|
|
594
|
+
...(sync?.statements ?? []),
|
|
568
595
|
]);
|
|
596
|
+
if (sync) await notifyAllocationSync(runner, input.tenantId, sync.token);
|
|
569
597
|
return sumQuantity(results[1] ?? []);
|
|
570
598
|
}
|
|
571
599
|
|
|
@@ -573,13 +601,7 @@ export async function releaseOrphanAllocations(
|
|
|
573
601
|
runner: StatementRunner,
|
|
574
602
|
input: { tenantId: string; stage: CommerceStage },
|
|
575
603
|
): Promise<number> {
|
|
576
|
-
const
|
|
577
|
-
{
|
|
578
|
-
sql: `UPDATE scrappy_allocations
|
|
579
|
-
SET state = 'released'
|
|
580
|
-
WHERE tenant_id = ? AND stage = ?
|
|
581
|
-
AND state IN ('reserved', 'confirmed')
|
|
582
|
-
AND NOT EXISTS (
|
|
604
|
+
const orphaned = `NOT EXISTS (
|
|
583
605
|
SELECT 1 FROM scrappy_final_cart_authorizations AS auth
|
|
584
606
|
WHERE auth.tenant_id = scrappy_allocations.tenant_id
|
|
585
607
|
AND auth.stage = scrappy_allocations.stage
|
|
@@ -589,11 +611,30 @@ export async function releaseOrphanAllocations(
|
|
|
589
611
|
AND admission.linked_order_id=scrappy_allocations.order_id
|
|
590
612
|
))
|
|
591
613
|
AND auth.state IN ('active', 'consumed')
|
|
592
|
-
)
|
|
614
|
+
)`;
|
|
615
|
+
// Read before the batch; a pair orphaned between the read and the batch stays counted until its next sync.
|
|
616
|
+
const releasing = await runner.all(
|
|
617
|
+
`SELECT DISTINCT sku, location_id FROM scrappy_allocations
|
|
618
|
+
WHERE tenant_id = ? AND stage = ? AND state IN ('reserved', 'confirmed') AND ${orphaned}`,
|
|
619
|
+
[input.tenantId, input.stage],
|
|
620
|
+
);
|
|
621
|
+
const sync =
|
|
622
|
+
releasing.length > 0
|
|
623
|
+
? allocationSync({ tenantId: input.tenantId, stage: input.stage, now: new Date().toISOString(), scope: rowsScope(releasing) })
|
|
624
|
+
: null;
|
|
625
|
+
const results = await runner.batch([
|
|
626
|
+
{
|
|
627
|
+
sql: `UPDATE scrappy_allocations
|
|
628
|
+
SET state = 'released'
|
|
629
|
+
WHERE tenant_id = ? AND stage = ?
|
|
630
|
+
AND state IN ('reserved', 'confirmed')
|
|
631
|
+
AND ${orphaned}
|
|
593
632
|
RETURNING quantity`,
|
|
594
633
|
params: [input.tenantId, input.stage],
|
|
595
634
|
},
|
|
635
|
+
...(sync?.statements ?? []),
|
|
596
636
|
]);
|
|
637
|
+
if (sync) await notifyAllocationSync(runner, input.tenantId, sync.token);
|
|
597
638
|
return sumQuantity(results[0] ?? []);
|
|
598
639
|
}
|
|
599
640
|
|
|
@@ -653,13 +694,51 @@ function commandFinding(reason: string): string {
|
|
|
653
694
|
}
|
|
654
695
|
|
|
655
696
|
import {
|
|
697
|
+
availabilitySyncStatements,
|
|
698
|
+
availabilityToken,
|
|
699
|
+
itemScope,
|
|
656
700
|
mirrorMovementDeliveryId,
|
|
657
701
|
mirrorMovementEventId,
|
|
702
|
+
notifyInventoryDeliveries,
|
|
658
703
|
ORDER_DECREMENT_SOURCE,
|
|
659
704
|
readEffectiveMirrorBalance,
|
|
660
705
|
recordMirrorInventoryChanged,
|
|
706
|
+
type AvailabilityScope,
|
|
661
707
|
} from "./mirrorStock.js";
|
|
662
708
|
|
|
709
|
+
/**
|
|
710
|
+
* The availability sync appended to an allocation transition's own batch: recomputes availability
|
|
711
|
+
* for the scoped skus and emits `inventory.changed` (with pending deliveries) where it moved.
|
|
712
|
+
*/
|
|
713
|
+
function allocationSync(input: { tenantId: string; stage: CommerceStage; now: string; scope: AvailabilityScope }): {
|
|
714
|
+
statements: SqlStatement[];
|
|
715
|
+
token: string;
|
|
716
|
+
} {
|
|
717
|
+
const token = availabilityToken();
|
|
718
|
+
return { statements: availabilitySyncStatements({ ...input, emit: true, token }), token };
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/** Best-effort dispatch of the deliveries a committed allocation sync wrote. */
|
|
722
|
+
async function notifyAllocationSync(runner: StatementRunner, tenantId: string, token: string): Promise<void> {
|
|
723
|
+
await notifyInventoryDeliveries(async (sql, params) => [...(await runner.all(sql, params))], {
|
|
724
|
+
tenantId,
|
|
725
|
+
idEquals: "",
|
|
726
|
+
idPrefix: `${token}.`,
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/** The (sku, location) pairs of one order's allocations, read when the sync runs. */
|
|
731
|
+
function orderScope(tenantId: string, stage: CommerceStage, orderId: string): AvailabilityScope {
|
|
732
|
+
return {
|
|
733
|
+
sql: `SELECT sku, location_id FROM scrappy_allocations WHERE tenant_id = ? AND stage = ? AND order_id = ?`,
|
|
734
|
+
params: [tenantId, stage, orderId],
|
|
735
|
+
};
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
function rowsScope(rows: readonly Record<string, unknown>[]): AvailabilityScope {
|
|
739
|
+
return itemScope(rows.map((row) => ({ sku: text(row, "sku"), locationId: text(row, "location_id") })));
|
|
740
|
+
}
|
|
741
|
+
|
|
663
742
|
/** Move reserved units to confirmed once. A second call decrements nothing. */
|
|
664
743
|
export async function confirmHoldOnce(
|
|
665
744
|
runner: StatementRunner,
|