@tokenoftrust/storefront-runner 6.12.3 → 6.12.5

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.
@@ -3,6 +3,7 @@ import type { Queryable } from "../catalog/d1/catalog.js";
3
3
  import { appInstallEnvForStage, type CommerceStage } from "@tot/public-runtime";
4
4
  import { isStoredSku } from "@tot/public-runtime/sku";
5
5
  import type { MirrorStockAuthority } from "./allocations.js";
6
+ import { mirrorBalanceKey, serializeMirrorBalances } from "./mirrorBalanceProjection.js";
6
7
 
7
8
  const ID = /^[A-Za-z0-9._:-]{1,128}$/;
8
9
  const INVENTORY_CHANGED_TOPIC = "inventory.changed";
@@ -21,6 +22,281 @@ export function setInventoryChangedNotify(notify: InventoryChangedNotify | undef
21
22
  defaultInventoryNotify = notify;
22
23
  }
23
24
 
25
+ export const LOCATION_KINDS = ["warehouse", "3pl", "dropship_vendor", "retail"] as const;
26
+ export type LocationKind = (typeof LOCATION_KINDS)[number];
27
+ export const LOCATION_STATUSES = ["active", "archived"] as const;
28
+ export type LocationStatus = (typeof LOCATION_STATUSES)[number];
29
+ /** WMS movement reasons an app may post. `reconcile` is reserved for absolute on-hand levels. */
30
+ export const MOVEMENT_REASONS = ["received", "picked", "restock", "cycle_count", "damaged", "transfer", "adjustment"] as const;
31
+ export type MovementReason = (typeof MOVEMENT_REASONS)[number];
32
+ export const RECONCILE_REASON = "reconcile";
33
+ /** The name of the CHECK constraint a refused batch trips to roll back its whole transaction. */
34
+ export const BATCH_REFUSED_CONSTRAINT = "inventory_batch_refused";
35
+
36
+ export interface SqlStatement {
37
+ sql: string;
38
+ params: unknown[];
39
+ }
40
+
41
+ /**
42
+ * SQL condition: `location` (an SQL expression) names a location a write may target — `unspecified`,
43
+ * or one the tenant declared for the stage and has not archived. Binds tenant, stage.
44
+ */
45
+ export function locationAdmittedSql(location: string): string {
46
+ return `(${location} = '${MIRROR_LOCATION_UNSPECIFIED}' OR EXISTS (
47
+ SELECT 1 FROM commerce_inventory_locations AS adm
48
+ WHERE adm.tenant_id = ? AND adm.stage = ? AND adm.location_id = ${location} AND adm.status = 'active'))`;
49
+ }
50
+
51
+ /**
52
+ * SQL condition: the row aliased `alias` sits at an active fulfillable location of its own tenant
53
+ * and stage. `unspecified` is that until the tenant declares it otherwise.
54
+ */
55
+ function fulfillableSql(alias: string): string {
56
+ return `(EXISTS (SELECT 1 FROM commerce_inventory_locations AS ful
57
+ WHERE ful.tenant_id = ${alias}.tenant_id AND ful.stage = ${alias}.stage AND ful.location_id = ${alias}.location_id
58
+ AND ful.status = 'active' AND ful.is_fulfillable = 1)
59
+ OR (${alias}.location_id = '${MIRROR_LOCATION_UNSPECIFIED}' AND NOT EXISTS (SELECT 1 FROM commerce_inventory_locations AS ful
60
+ WHERE ful.tenant_id = ${alias}.tenant_id AND ful.stage = ${alias}.stage AND ful.location_id = ${alias}.location_id)))`;
61
+ }
62
+
63
+ /**
64
+ * SQL expression: available units of `sku` — the ledger summed over active fulfillable locations,
65
+ * minus reserved and confirmed allocations at those locations. Binds tenant, stage, tenant, stage.
66
+ */
67
+ export function availableSql(sku: string): string {
68
+ return `(COALESCE((SELECT SUM(am.quantity_delta) FROM commerce_inventory_movements AS am
69
+ WHERE am.tenant_id = ? AND am.stage = ? AND am.sku = ${sku} AND ${fulfillableSql("am")}), 0)
70
+ - COALESCE((SELECT SUM(aa.quantity) FROM scrappy_allocations AS aa
71
+ WHERE aa.tenant_id = ? AND aa.stage = ? AND aa.sku = ${sku} AND aa.state IN ('reserved', 'confirmed')
72
+ AND ${fulfillableSql("aa")}), 0))`;
73
+ }
74
+
75
+ /** SQL expression: one location's balance (ledger minus confirmed allocations). Binds tenant, stage, tenant, stage. */
76
+ export function locationBalanceSql(sku: string, location: string): string {
77
+ return `(COALESCE((SELECT SUM(lm.quantity_delta) FROM commerce_inventory_movements AS lm
78
+ WHERE lm.tenant_id = ? AND lm.stage = ? AND lm.sku = ${sku} AND lm.location_id = ${location}), 0)
79
+ - COALESCE((SELECT SUM(la.quantity) FROM scrappy_allocations AS la
80
+ WHERE la.tenant_id = ? AND la.stage = ? AND la.sku = ${sku} AND la.location_id = ${location} AND la.state = 'confirmed'), 0))`;
81
+ }
82
+
83
+ const twice = (tenantId: string, stage: CommerceStage) => [tenantId, stage, tenantId, stage];
84
+
85
+ /** Rows `(sku, location_id)` an availability sync recomputes. */
86
+ export interface AvailabilityScope {
87
+ sql: string;
88
+ params: readonly unknown[];
89
+ }
90
+
91
+ export function itemScope(items: readonly { sku: string; locationId: string }[]): AvailabilityScope {
92
+ return {
93
+ sql: `SELECT json_extract(value, '$.sku') AS sku, json_extract(value, '$.locationId') AS location_id FROM json_each(?)`,
94
+ params: [JSON.stringify(items.map((item) => ({ sku: item.sku, locationId: item.locationId })))],
95
+ };
96
+ }
97
+
98
+ /** A fresh id prefix for the availability events one transaction emits. */
99
+ export function availabilityToken(): string {
100
+ return `invav.${crypto.randomUUID().replaceAll("-", "")}`;
101
+ }
102
+
103
+ /**
104
+ * SQL condition: `column` equals `exact` or starts with `prefix` (which ends in "."), written as a
105
+ * key range so the column's index serves it. Binds exact, prefix, upper bound.
106
+ */
107
+ function idMatchSql(column: string): string {
108
+ return `(${column} = ? OR (${column} >= ? AND ${column} < ?))`;
109
+ }
110
+
111
+ function idMatchParams(exact: string, prefix: string): string[] {
112
+ if (!prefix.endsWith(".")) throw new Error("id-prefix-must-end-with-dot");
113
+ return [exact, prefix, `${prefix.slice(0, -1)}/`];
114
+ }
115
+
116
+ /** Inserts a pending delivery for every eligible install of each `inventory.changed` event whose id matches. */
117
+ function deliveryStatement(input: { tenantId: string; stage: CommerceStage; now: string; idEquals: string; idPrefix: string }): SqlStatement {
118
+ return {
119
+ sql: `INSERT INTO webhook_deliveries
120
+ (delivery_id, event_id, install_id, tenant_id, topic, state, attempts, created_at, updated_at)
121
+ SELECT e.id || ':' || i.install_id, e.id, i.install_id, i.tenant_id, '${INVENTORY_CHANGED_TOPIC}', 'pending', 0, ?, ?
122
+ FROM webhook_events AS e JOIN app_installs AS i ON ${ELIGIBLE_INVENTORY_INSTALL_SQL}
123
+ WHERE ${idMatchSql("e.id")} AND e.tenant_id = ? AND e.topic = '${INVENTORY_CHANGED_TOPIC}'
124
+ ON CONFLICT DO NOTHING`,
125
+ params: [
126
+ input.now,
127
+ input.now,
128
+ input.tenantId,
129
+ appInstallEnvForStage(input.stage),
130
+ ...idMatchParams(input.idEquals, input.idPrefix),
131
+ input.tenantId,
132
+ ],
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Statements appended to the same D1 batch as a state change that can move availability. For each
138
+ * scoped sku the tenant's ledger holds, they recompute availability and store it in
139
+ * `commerce_inventory_availability`, bumping `version` when it changed. With `emit`, a sku whose
140
+ * availability changed (or crossed 0) also gets one `inventory.changed` event, keyed `token.<n>`,
141
+ * and a pending delivery per eligible install — inside the same transaction, so a committed change
142
+ * always carries its event. `locationId` in the payload is the lowest scoped location of the sku.
143
+ */
144
+ export function availabilitySyncStatements(input: {
145
+ tenantId: string;
146
+ stage: CommerceStage;
147
+ now: string;
148
+ scope: AvailabilityScope;
149
+ emit: boolean;
150
+ token: string;
151
+ /** Runs the sync only when this condition holds inside the transaction (e.g. the write committed a row). */
152
+ when?: SqlCondition;
153
+ }): SqlStatement[] {
154
+ const { tenantId, stage } = input;
155
+ const when = input.when ?? { sql: "1 = 1", params: [] };
156
+ const computed = `WITH scoped AS (
157
+ SELECT sku, MIN(location_id) AS location_id FROM (${input.scope.sql}) WHERE sku IS NOT NULL AND (${when.sql}) GROUP BY sku
158
+ ), computed AS (
159
+ SELECT scoped.sku AS sku, scoped.location_id AS location_id,
160
+ ${availableSql("scoped.sku")} AS available,
161
+ (SELECT MAX(lm.as_of) FROM commerce_inventory_movements AS lm
162
+ WHERE lm.tenant_id = ? AND lm.stage = ? AND lm.sku = scoped.sku) AS as_of
163
+ FROM scoped
164
+ )`;
165
+ const computedParams = [...input.scope.params, ...when.params, ...twice(tenantId, stage), tenantId, stage];
166
+ const statements: SqlStatement[] = [];
167
+ if (input.emit) {
168
+ statements.push(
169
+ {
170
+ sql: `${computed}
171
+ INSERT INTO webhook_events (id, tenant_id, topic, dataschema_version, payload, created_at)
172
+ SELECT ? || '.' || ROW_NUMBER() OVER (ORDER BY computed.sku), ?, '${INVENTORY_CHANGED_TOPIC}', '${INVENTORY_DATASCHEMA_VERSION}',
173
+ json_object('sku', computed.sku, 'locationId', computed.location_id,
174
+ 'balance', ${locationBalanceSql("computed.sku", "computed.location_id")},
175
+ 'available', computed.available, 'asOf', ?), ?
176
+ FROM computed
177
+ WHERE computed.as_of IS NOT NULL
178
+ AND computed.available IS NOT (SELECT av.available FROM commerce_inventory_availability AS av
179
+ WHERE av.tenant_id = ? AND av.stage = ? AND av.sku = computed.sku)`,
180
+ params: [...computedParams, input.token, tenantId, ...twice(tenantId, stage), input.now, input.now, tenantId, stage],
181
+ },
182
+ deliveryStatement({ tenantId, stage, now: input.now, idEquals: "", idPrefix: `${input.token}.` }),
183
+ );
184
+ }
185
+ statements.push({
186
+ sql: `${computed}
187
+ INSERT INTO commerce_inventory_availability (tenant_id, stage, sku, available, version, as_of)
188
+ SELECT ?, ?, computed.sku, computed.available, 1, computed.as_of FROM computed WHERE computed.as_of IS NOT NULL
189
+ ON CONFLICT (tenant_id, stage, sku) DO UPDATE SET
190
+ version = CASE WHEN commerce_inventory_availability.available != excluded.available
191
+ THEN commerce_inventory_availability.version + 1 ELSE commerce_inventory_availability.version END,
192
+ available = excluded.available,
193
+ as_of = excluded.as_of`,
194
+ params: [...computedParams, tenantId, stage],
195
+ });
196
+ return statements;
197
+ }
198
+
199
+ /**
200
+ * The `inventory.changed` event for each movement row this transaction wrote under `source` with
201
+ * source event id `sourceEventId` or `sourceEventId.<n>`, plus pending deliveries. A zero-delta
202
+ * movement (a reconcile that changed nothing) has no event. The payload carries the location's
203
+ * balance and the sku's availability as of the transaction.
204
+ */
205
+ export function movementEventStatements(input: {
206
+ tenantId: string;
207
+ stage: CommerceStage;
208
+ source: string;
209
+ sourceEventId: string;
210
+ now: string;
211
+ }): SqlStatement[] {
212
+ const { tenantId, stage } = input;
213
+ const prefix = `${input.sourceEventId}.`;
214
+ return [
215
+ {
216
+ sql: `INSERT INTO webhook_events (id, tenant_id, topic, dataschema_version, payload, created_at)
217
+ SELECT 'inv.' || m.source_event_id, m.tenant_id, '${INVENTORY_CHANGED_TOPIC}', '${INVENTORY_DATASCHEMA_VERSION}',
218
+ json_object('sku', m.sku, 'locationId', m.location_id,
219
+ 'balance', ${locationBalanceSql("m.sku", "m.location_id")},
220
+ 'available', ${availableSql("m.sku")}, 'asOf', m.as_of), m.as_of
221
+ FROM commerce_inventory_movements AS m
222
+ WHERE m.tenant_id = ? AND m.stage = ? AND m.source = ?
223
+ AND ${idMatchSql("m.source_event_id")}
224
+ AND m.quantity_delta != 0
225
+ AND NOT EXISTS (SELECT 1 FROM webhook_events WHERE id = 'inv.' || m.source_event_id)`,
226
+ params: [
227
+ ...twice(tenantId, stage),
228
+ ...twice(tenantId, stage),
229
+ tenantId,
230
+ stage,
231
+ input.source,
232
+ ...idMatchParams(input.sourceEventId, prefix),
233
+ ],
234
+ },
235
+ deliveryStatement({ tenantId, stage, now: input.now, idEquals: `inv.${input.sourceEventId}`, idPrefix: `inv.${prefix}` }),
236
+ ];
237
+ }
238
+
239
+ /** Best-effort dispatch of the pending deliveries a committed transaction wrote for events whose id matches. */
240
+ export async function notifyInventoryDeliveries(
241
+ all: (sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>,
242
+ input: { tenantId: string; idEquals: string; idPrefix: string; notify?: InventoryChangedNotify },
243
+ ): Promise<void> {
244
+ const notify = input.notify ?? defaultInventoryNotify;
245
+ if (!notify) return;
246
+ try {
247
+ const rows = await all(
248
+ `SELECT delivery_id FROM webhook_deliveries
249
+ WHERE tenant_id = ? AND state = 'pending' AND ${idMatchSql("event_id")}
250
+ ORDER BY created_at ASC, delivery_id ASC`,
251
+ [input.tenantId, ...idMatchParams(input.idEquals, input.idPrefix)],
252
+ );
253
+ const ids = rows.map((row) => String(row.delivery_id));
254
+ if (ids.length > 0) await notify(input.tenantId, ids);
255
+ } catch {
256
+ // Pending rows remain in webhook_deliveries for the commerce alarm.
257
+ }
258
+ }
259
+
260
+ /** Runs `statements` as one transaction where the seam offers it, else in order. */
261
+ async function runStatements(db: Queryable, statements: readonly SqlStatement[]): Promise<void> {
262
+ if (db.batch) {
263
+ await db.batch(statements);
264
+ return;
265
+ }
266
+ for (const statement of statements) await db.run(statement.sql, ...statement.params);
267
+ }
268
+
269
+ /** Projected availability per sku for the tenant and stage, in the KV projection's shape. */
270
+ export async function readAvailabilityBalances(
271
+ db: Queryable,
272
+ input: { tenantId: string; stage: CommerceStage },
273
+ ): Promise<Map<string, MirrorBalance>> {
274
+ const rows = await db.all<{ sku: string; available: number; as_of: string }>(
275
+ `SELECT sku, available, as_of FROM commerce_inventory_availability WHERE tenant_id = ? AND stage = ? ORDER BY sku`,
276
+ input.tenantId,
277
+ input.stage,
278
+ );
279
+ const balances = new Map<string, MirrorBalance>();
280
+ for (const row of rows) {
281
+ if (!Number.isSafeInteger(Number(row.available)) || !row.as_of) continue;
282
+ balances.set(row.sku, { balance: Number(row.available), asOf: row.as_of });
283
+ }
284
+ return balances;
285
+ }
286
+
287
+ /**
288
+ * Rewrites the whole TENANT_CACHE projection for the tenant and stage from stored availability.
289
+ * Unconditional: a retried or no-op write repairs a put that failed after an earlier commit.
290
+ */
291
+ export async function writeAvailabilityProjection(
292
+ db: Queryable,
293
+ kv: { put(key: string, value: string): Promise<unknown> },
294
+ input: { tenantId: string; stage: CommerceStage },
295
+ ): Promise<void> {
296
+ const balances = await readAvailabilityBalances(db, input);
297
+ await kv.put(mirrorBalanceKey(input.tenantId, input.stage), serializeMirrorBalances(balances));
298
+ }
299
+
24
300
  async function digestId(prefix: string, parts: readonly string[]): Promise<string> {
25
301
  const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(parts.join("\n"))));
26
302
  const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
@@ -66,10 +342,20 @@ export async function recordMirrorInventoryChanged(
66
342
  ): Promise<{ eventId: string; deliveryIds: string[] } | null> {
67
343
  const eventId = await mirrorMovementEventId(input);
68
344
  const installEnv = appInstallEnvForStage(input.stage);
345
+ const availability = await db.first<{ available: number }>(
346
+ `SELECT ${availableSql("?")} AS available`,
347
+ input.tenantId,
348
+ input.stage,
349
+ input.sku,
350
+ input.tenantId,
351
+ input.stage,
352
+ input.sku,
353
+ );
69
354
  const payload = JSON.stringify({
70
355
  sku: input.sku,
71
356
  locationId: input.locationId,
72
357
  balance: input.balance,
358
+ available: Number(availability?.available ?? 0),
73
359
  asOf: input.asOf,
74
360
  });
75
361
  const installs = await db.all<{ install_id: string }>(
@@ -179,7 +465,35 @@ export interface MirrorMovement {
179
465
  quantityDelta: number;
180
466
  asOf: string;
181
467
  actorId: string;
468
+ reason?: MovementReason | typeof RECONCILE_REASON | null;
469
+ }
470
+
471
+ /**
472
+ * For the operator and import paths: declares the movement's location (a fulfillable warehouse)
473
+ * when the tenant has not, then syncs the sku's availability without an event, since those paths
474
+ * emit their own per-movement event.
475
+ */
476
+ function movementSync(input: { tenantId: string; stage: CommerceStage; sku: string; locationId: string; asOf: string }): SqlStatement[] {
477
+ const declare: SqlStatement[] =
478
+ input.locationId === MIRROR_LOCATION_UNSPECIFIED
479
+ ? []
480
+ : [
481
+ {
482
+ sql: `INSERT INTO commerce_inventory_locations (tenant_id, stage, location_id, name, kind, is_fulfillable, status, updated_at)
483
+ VALUES (?, ?, ?, ?, 'warehouse', 1, 'active', ?) ON CONFLICT DO NOTHING`,
484
+ params: [input.tenantId, input.stage, input.locationId, input.locationId, input.asOf],
485
+ },
486
+ ];
487
+ return [...declare, ...availabilitySyncStatements({
488
+ tenantId: input.tenantId,
489
+ stage: input.stage,
490
+ now: input.asOf,
491
+ scope: itemScope([{ sku: input.sku, locationId: input.locationId }]),
492
+ emit: false,
493
+ token: availabilityToken(),
494
+ })];
182
495
  }
496
+
183
497
  export async function appendMirrorMovement(db: Queryable, input: MirrorMovement): Promise<void> {
184
498
  if (
185
499
  ![input.tenantId, input.source, input.sourceEventId, input.locationId, input.actorId].every((v) =>
@@ -208,20 +522,26 @@ export async function appendMirrorMovement(db: Queryable, input: MirrorMovement)
208
522
  prior.actor_id !== input.actorId)
209
523
  )
210
524
  throw new InventoryMovementError("conflict");
211
- await db.run(
212
- `INSERT INTO commerce_inventory_movements
213
- (tenant_id,stage,source,source_event_id,sku,location_id,quantity_delta,as_of,actor_id)
214
- VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING`,
215
- input.tenantId,
216
- input.stage,
217
- input.source,
218
- input.sourceEventId,
219
- input.sku,
220
- input.locationId,
221
- input.quantityDelta,
222
- input.asOf,
223
- input.actorId,
224
- );
525
+ await runStatements(db, [
526
+ {
527
+ sql: `INSERT INTO commerce_inventory_movements
528
+ (tenant_id,stage,source,source_event_id,sku,location_id,quantity_delta,as_of,actor_id,reason)
529
+ VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING`,
530
+ params: [
531
+ input.tenantId,
532
+ input.stage,
533
+ input.source,
534
+ input.sourceEventId,
535
+ input.sku,
536
+ input.locationId,
537
+ input.quantityDelta,
538
+ input.asOf,
539
+ input.actorId,
540
+ input.reason ?? null,
541
+ ],
542
+ },
543
+ ...movementSync(input),
544
+ ]);
225
545
  const actual = await db.first<{ quantity_delta: number; as_of: string; actor_id: string }>(
226
546
  `SELECT quantity_delta,as_of,actor_id FROM commerce_inventory_movements WHERE tenant_id=? AND stage=? AND source=? AND source_event_id=? AND sku=? AND location_id=?`,
227
547
  input.tenantId,
@@ -409,22 +729,27 @@ export async function appendSourceOnHand(
409
729
  )
410
730
  throw new InventoryMovementError("invalid-movement");
411
731
  const others = [input.tenantId, input.stage, input.sku, input.locationId, input.source, input.sourceEventId];
412
- await db.run(
413
- `INSERT INTO commerce_inventory_movements
414
- (tenant_id,stage,source,source_event_id,sku,location_id,quantity_delta,as_of,actor_id)
415
- SELECT ?,?,?,?,?,?,CAST(? AS INTEGER) - ${OTHER_MOVEMENTS_SUM},?,? WHERE true
416
- ON CONFLICT DO NOTHING`,
417
- input.tenantId,
418
- input.stage,
419
- input.source,
420
- input.sourceEventId,
421
- input.sku,
422
- input.locationId,
423
- input.onHand,
424
- ...others,
425
- input.asOf,
426
- input.actorId,
427
- );
732
+ await runStatements(db, [
733
+ {
734
+ sql: `INSERT INTO commerce_inventory_movements
735
+ (tenant_id,stage,source,source_event_id,sku,location_id,quantity_delta,as_of,actor_id,reason)
736
+ SELECT ?,?,?,?,?,?,CAST(? AS INTEGER) - ${OTHER_MOVEMENTS_SUM},?,?,'${RECONCILE_REASON}' WHERE true
737
+ ON CONFLICT DO NOTHING`,
738
+ params: [
739
+ input.tenantId,
740
+ input.stage,
741
+ input.source,
742
+ input.sourceEventId,
743
+ input.sku,
744
+ input.locationId,
745
+ input.onHand,
746
+ ...others,
747
+ input.asOf,
748
+ input.actorId,
749
+ ],
750
+ },
751
+ ...movementSync(input),
752
+ ]);
428
753
  const actual = await db.first<{ quantity_delta: number; as_of: string; actor_id: string; expected: number }>(
429
754
  `SELECT quantity_delta, as_of, actor_id, CAST(? AS INTEGER) - ${OTHER_MOVEMENTS_SUM} AS expected
430
755
  FROM commerce_inventory_movements
@@ -476,8 +801,8 @@ export interface SqlCondition {
476
801
  * time, inside the statement. The balance after it stays within 0..MIRROR_BALANCE_MAX, except
477
802
  * that a positive delta on a negative balance is admitted because it moves the balance toward
478
803
  * zero; overflow is always refused, never clamped. The location is `unspecified` or one the
479
- * tenant's movements for that stage already name. `guard` is an SQL condition (no leading AND)
480
- * the caller's admission adds. Zero rows changed means refused.
804
+ * tenant declared active for that stage (`locationAdmittedSql`). `guard` is an SQL condition (no
805
+ * leading AND) the caller's admission adds. Zero rows changed means refused.
481
806
  */
482
807
  export function guardedCorrectionStatement(movement: MirrorMovement, guard: SqlCondition): SqlCondition {
483
808
  if (
@@ -494,8 +819,8 @@ export function guardedCorrectionStatement(movement: MirrorMovement, guard: SqlC
494
819
  const delta = movement.quantityDelta;
495
820
  return {
496
821
  sql: `INSERT INTO commerce_inventory_movements
497
- (tenant_id,stage,source,source_event_id,sku,location_id,quantity_delta,as_of,actor_id)
498
- SELECT ?,?,?,?,?,?,CAST(? AS INTEGER),?,?
822
+ (tenant_id,stage,source,source_event_id,sku,location_id,quantity_delta,as_of,actor_id,reason)
823
+ SELECT ?,?,?,?,?,?,CAST(? AS INTEGER),?,?,?
499
824
  FROM (
500
825
  SELECT COALESCE((SELECT SUM(quantity_delta) FROM commerce_inventory_movements
501
826
  WHERE tenant_id=? AND stage=? AND sku=? AND location_id=?), 0)
@@ -504,9 +829,7 @@ export function guardedCorrectionStatement(movement: MirrorMovement, guard: SqlC
504
829
  ) AS current
505
830
  WHERE current.balance + CAST(? AS INTEGER) <= ${MIRROR_BALANCE_MAX}
506
831
  AND (current.balance + CAST(? AS INTEGER) >= 0 OR CAST(? AS INTEGER) > 0)
507
- AND (? = '${MIRROR_LOCATION_UNSPECIFIED}' OR EXISTS (
508
- SELECT 1 FROM commerce_inventory_movements WHERE tenant_id=? AND stage=? AND location_id=?
509
- ))
832
+ AND ${locationAdmittedSql("?")}
510
833
  AND (${guard.sql})`,
511
834
  params: [
512
835
  movement.tenantId,
@@ -518,6 +841,7 @@ export function guardedCorrectionStatement(movement: MirrorMovement, guard: SqlC
518
841
  delta,
519
842
  movement.asOf,
520
843
  movement.actorId,
844
+ movement.reason ?? null,
521
845
  movement.tenantId,
522
846
  movement.stage,
523
847
  movement.sku,
@@ -545,7 +869,7 @@ export async function mirrorLocationKnown(
545
869
  ): Promise<boolean> {
546
870
  if (input.locationId === MIRROR_LOCATION_UNSPECIFIED) return true;
547
871
  const row = await db.first<{ n: number }>(
548
- `SELECT 1 AS n FROM commerce_inventory_movements WHERE tenant_id=? AND stage=? AND location_id=? LIMIT 1`,
872
+ `SELECT 1 AS n FROM commerce_inventory_locations WHERE tenant_id=? AND stage=? AND location_id=? AND status='active'`,
549
873
  input.tenantId,
550
874
  input.stage,
551
875
  input.locationId,
@@ -553,6 +877,86 @@ export async function mirrorLocationKnown(
553
877
  return row !== null;
554
878
  }
555
879
 
880
+ export interface InventoryLocation {
881
+ locationId: string;
882
+ name: string;
883
+ kind: LocationKind;
884
+ isFulfillable: boolean;
885
+ status: LocationStatus;
886
+ updatedAt: string;
887
+ }
888
+
889
+ function locationFromRow(row: Record<string, unknown>): InventoryLocation {
890
+ return {
891
+ locationId: String(row.location_id),
892
+ name: String(row.name),
893
+ kind: String(row.kind) as LocationKind,
894
+ isFulfillable: Number(row.is_fulfillable) === 1,
895
+ status: String(row.status) as LocationStatus,
896
+ updatedAt: String(row.updated_at),
897
+ };
898
+ }
899
+
900
+ /** The tenant's declared locations for the stage, `unspecified` always among them. */
901
+ export async function listInventoryLocations(
902
+ db: Queryable,
903
+ input: { tenantId: string; stage: CommerceStage; now: string },
904
+ ): Promise<InventoryLocation[]> {
905
+ const rows = await db.all<Record<string, unknown>>(
906
+ `SELECT location_id, name, kind, is_fulfillable, status, updated_at FROM commerce_inventory_locations
907
+ WHERE tenant_id = ? AND stage = ? ORDER BY location_id`,
908
+ input.tenantId,
909
+ input.stage,
910
+ );
911
+ const locations = rows.map(locationFromRow);
912
+ if (!locations.some((location) => location.locationId === MIRROR_LOCATION_UNSPECIFIED)) {
913
+ locations.push({
914
+ locationId: MIRROR_LOCATION_UNSPECIFIED,
915
+ name: "Unspecified",
916
+ kind: "warehouse",
917
+ isFulfillable: true,
918
+ status: "active",
919
+ updatedAt: input.now,
920
+ });
921
+ locations.sort((a, b) => (a.locationId < b.locationId ? -1 : a.locationId > b.locationId ? 1 : 0));
922
+ }
923
+ return locations;
924
+ }
925
+
926
+ export async function readInventoryLocation(
927
+ db: Queryable,
928
+ input: { tenantId: string; stage: CommerceStage; locationId: string },
929
+ ): Promise<InventoryLocation | null> {
930
+ const row = await db.first<Record<string, unknown>>(
931
+ `SELECT location_id, name, kind, is_fulfillable, status, updated_at FROM commerce_inventory_locations
932
+ WHERE tenant_id = ? AND stage = ? AND location_id = ?`,
933
+ input.tenantId,
934
+ input.stage,
935
+ input.locationId,
936
+ );
937
+ return row ? locationFromRow(row) : null;
938
+ }
939
+
940
+ /** Scope of a location change: every sku with ledger rows or active allocations at that location. */
941
+ export function locationScope(input: { tenantId: string; stage: CommerceStage; locationId: string }): AvailabilityScope {
942
+ return {
943
+ sql: `SELECT sku, location_id FROM commerce_inventory_movements WHERE tenant_id = ? AND stage = ? AND location_id = ?
944
+ UNION SELECT sku, location_id FROM scrappy_allocations
945
+ WHERE tenant_id = ? AND stage = ? AND location_id = ? AND state IN ('reserved', 'confirmed')`,
946
+ params: [input.tenantId, input.stage, input.locationId, input.tenantId, input.stage, input.locationId],
947
+ };
948
+ }
949
+
950
+ /**
951
+ * SQL expression: the delta that makes one key's ledger equal an absolute on-hand. `onHand`, `sku`
952
+ * and `location` are SQL expressions; binds tenant, stage. Shared by `appendSourceOnHand` and the
953
+ * batch levels reconcile, which writes each key under a new event id, so every existing movement counts.
954
+ */
955
+ export function onHandDeltaSql(onHand: string, sku: string, location: string): string {
956
+ return `CAST(${onHand} AS INTEGER) - COALESCE((SELECT SUM(oh.quantity_delta) FROM commerce_inventory_movements AS oh
957
+ WHERE oh.tenant_id = ? AND oh.stage = ? AND oh.sku = ${sku} AND oh.location_id = ${location}), 0)`;
958
+ }
959
+
556
960
  export async function catalogImportEventId(runId: string, sku: string, onHand: number): Promise<string> {
557
961
  const quantity = onHand < 0 ? `n${-onHand}` : String(onHand);
558
962
  const raw = `import.${runId}.${sku}.${quantity}`;
@@ -13,7 +13,7 @@ import { fromD1, type D1Like } from "@/lib/catalog/d1/catalog";
13
13
  import { readCurrentTenantConsentConfig } from "@/lib/measurement/consent/consentConfigRead";
14
14
  import { loadActiveManagedInstallDeclarations } from "@/lib/integrations/integration/managedInstallDeclarations";
15
15
  import { buildTenantConsentBroker, commerceTenantId, previewContextRefusalResponse, storefrontModeRequiresSignIn } from "@tot/public-runtime";
16
- import { MIRROR_LOCATION_UNSPECIFIED, readMirrorBalances as readLedgerBalances } from "@/lib/inventory/mirrorStock";
16
+ import { readAvailabilityBalances } from "@/lib/inventory/mirrorStock";
17
17
  import { tenantIsDeclaredPublic } from "@/config/tenants";
18
18
  import type {
19
19
  ConsentSnapshot,
@@ -295,11 +295,7 @@ export async function serveControlPlane(input: ControlPlaneInput): Promise<Respo
295
295
  tenant.catalog?.serving === "d1" ? await readD1("CATALOG_DB") : undefined,
296
296
  readMirrorBalances: async (stage) => {
297
297
  if (!appsD1) return null;
298
- return readLedgerBalances(fromD1(appsD1), {
299
- tenantId: commerceTenantId(tenant),
300
- stage,
301
- locationId: MIRROR_LOCATION_UNSPECIFIED,
302
- });
298
+ return readAvailabilityBalances(fromD1(appsD1), { tenantId: commerceTenantId(tenant), stage });
303
299
  },
304
300
  internalContentGrant: input.internalContentGrant,
305
301
  });
@@ -11,7 +11,7 @@ import { fromD1 } from "@/lib/catalog/d1/catalog.js";
11
11
  import { readD1, readEnv, readKv } from "@/lib/publication/shared/env";
12
12
  import { evaluateFinalCart, type RefusedLine, type SeamView } from "@/lib/checkout/commerce/finalCartAuthorization.js";
13
13
  import { d1CommerceRunner, reserveAllocation } from "@/lib/inventory/allocations.js";
14
- import { readMirrorBalance, readMirrorStock } from "@/lib/inventory/mirrorStock.js";
14
+ import { readMirrorBalance, readMirrorStock, writeAvailabilityProjection } from "@/lib/inventory/mirrorStock.js";
15
15
  import { admissionMatches, readCommerceAdmission, admissionSnapshotStatement } from "@/lib/checkout/commerce/commerceAdmission.js";
16
16
  import { evaluatePreflight } from "../compliance/preflight.js";
17
17
  import {
@@ -413,5 +413,12 @@ async function authorize(context: APIContext): Promise<Response> {
413
413
  admissionStatement: admissionSnapshotStatement({ ...snapshot, authorizationId, cartDigest, evidence, provenance, expiresAt: decision.expiresAt, now }),
414
414
  });
415
415
  if (!reserved.ok) return deny(reserved.finding);
416
+ if (kv && !reserved.repeated) {
417
+ try {
418
+ await writeAvailabilityProjection(queryable, kv, { tenantId: decision.tenantId, stage: decision.stage });
419
+ } catch {
420
+ // The reservation is the record. Pages keep the prior projection until the next write.
421
+ }
422
+ }
416
423
  return json({ ok: true, authorizationId: reserved.authorizationId, cartDigest, expiresAt: reserved.expiresAt, repeated: reserved.repeated, stage: snapshot.stage });
417
424
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.12.3",
3
+ "version": "6.12.5",
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",