@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.
@@ -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,292 @@ 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
+ // Freshness of the stored availability: a recompute that moves the number (or first stores it) is
186
+ // as of the later of the newest ledger observation and this transition, so an accepted location or
187
+ // reservation change reads as fresh; an unchanged recompute keeps the later of the stored and ledger
188
+ // stamps, so a no-op write never refreshes stale mirror data.
189
+ statements.push({
190
+ sql: `${computed}
191
+ INSERT INTO commerce_inventory_availability (tenant_id, stage, sku, available, version, as_of)
192
+ SELECT ?, ?, computed.sku, computed.available, 1,
193
+ CASE WHEN av.sku IS NOT NULL AND av.available = computed.available
194
+ THEN CASE WHEN julianday(av.as_of) >= julianday(computed.as_of) THEN av.as_of ELSE computed.as_of END
195
+ ELSE CASE WHEN julianday(computed.as_of) >= julianday(?) THEN computed.as_of ELSE ? END
196
+ END
197
+ FROM computed LEFT JOIN commerce_inventory_availability AS av
198
+ ON av.tenant_id = ? AND av.stage = ? AND av.sku = computed.sku
199
+ WHERE computed.as_of IS NOT NULL
200
+ ON CONFLICT (tenant_id, stage, sku) DO UPDATE SET
201
+ version = CASE WHEN commerce_inventory_availability.available != excluded.available
202
+ THEN commerce_inventory_availability.version + 1 ELSE commerce_inventory_availability.version END,
203
+ available = excluded.available,
204
+ as_of = excluded.as_of`,
205
+ params: [...computedParams, tenantId, stage, input.now, input.now, tenantId, stage],
206
+ });
207
+ return statements;
208
+ }
209
+
210
+ /**
211
+ * The `inventory.changed` event for each movement row this transaction wrote under `source` with
212
+ * source event id `sourceEventId` or `sourceEventId.<n>`, plus pending deliveries. A zero-delta
213
+ * movement (a reconcile that changed nothing) has no event. The payload carries the location's
214
+ * balance and the sku's availability as of the transaction.
215
+ */
216
+ export function movementEventStatements(input: {
217
+ tenantId: string;
218
+ stage: CommerceStage;
219
+ source: string;
220
+ sourceEventId: string;
221
+ now: string;
222
+ }): SqlStatement[] {
223
+ const { tenantId, stage } = input;
224
+ const prefix = `${input.sourceEventId}.`;
225
+ return [
226
+ {
227
+ sql: `INSERT INTO webhook_events (id, tenant_id, topic, dataschema_version, payload, created_at)
228
+ SELECT 'inv.' || m.source_event_id, m.tenant_id, '${INVENTORY_CHANGED_TOPIC}', '${INVENTORY_DATASCHEMA_VERSION}',
229
+ json_object('sku', m.sku, 'locationId', m.location_id,
230
+ 'balance', ${locationBalanceSql("m.sku", "m.location_id")},
231
+ 'available', ${availableSql("m.sku")}, 'asOf', m.as_of), m.as_of
232
+ FROM commerce_inventory_movements AS m
233
+ WHERE m.tenant_id = ? AND m.stage = ? AND m.source = ?
234
+ AND ${idMatchSql("m.source_event_id")}
235
+ AND m.quantity_delta != 0
236
+ AND NOT EXISTS (SELECT 1 FROM webhook_events WHERE id = 'inv.' || m.source_event_id)`,
237
+ params: [
238
+ ...twice(tenantId, stage),
239
+ ...twice(tenantId, stage),
240
+ tenantId,
241
+ stage,
242
+ input.source,
243
+ ...idMatchParams(input.sourceEventId, prefix),
244
+ ],
245
+ },
246
+ deliveryStatement({ tenantId, stage, now: input.now, idEquals: `inv.${input.sourceEventId}`, idPrefix: `inv.${prefix}` }),
247
+ ];
248
+ }
249
+
250
+ /** Best-effort dispatch of the pending deliveries a committed transaction wrote for events whose id matches. */
251
+ export async function notifyInventoryDeliveries(
252
+ all: (sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>,
253
+ input: { tenantId: string; idEquals: string; idPrefix: string; notify?: InventoryChangedNotify },
254
+ ): Promise<void> {
255
+ const notify = input.notify ?? defaultInventoryNotify;
256
+ if (!notify) return;
257
+ try {
258
+ const rows = await all(
259
+ `SELECT delivery_id FROM webhook_deliveries
260
+ WHERE tenant_id = ? AND state = 'pending' AND ${idMatchSql("event_id")}
261
+ ORDER BY created_at ASC, delivery_id ASC`,
262
+ [input.tenantId, ...idMatchParams(input.idEquals, input.idPrefix)],
263
+ );
264
+ const ids = rows.map((row) => String(row.delivery_id));
265
+ if (ids.length > 0) await notify(input.tenantId, ids);
266
+ } catch {
267
+ // Pending rows remain in webhook_deliveries for the commerce alarm.
268
+ }
269
+ }
270
+
271
+ /** Runs `statements` as one transaction where the seam offers it, else in order. */
272
+ async function runStatements(db: Queryable, statements: readonly SqlStatement[]): Promise<void> {
273
+ if (db.batch) {
274
+ await db.batch(statements);
275
+ return;
276
+ }
277
+ for (const statement of statements) await db.run(statement.sql, ...statement.params);
278
+ }
279
+
280
+ /** Projected availability per sku for the tenant and stage, in the KV projection's shape. */
281
+ export async function readAvailabilityBalances(
282
+ db: Queryable,
283
+ input: { tenantId: string; stage: CommerceStage },
284
+ ): Promise<Map<string, MirrorBalance>> {
285
+ const rows = await db.all<{ sku: string; available: number; as_of: string }>(
286
+ `SELECT sku, available, as_of FROM commerce_inventory_availability WHERE tenant_id = ? AND stage = ? ORDER BY sku`,
287
+ input.tenantId,
288
+ input.stage,
289
+ );
290
+ const balances = new Map<string, MirrorBalance>();
291
+ for (const row of rows) {
292
+ if (!Number.isSafeInteger(Number(row.available)) || !row.as_of) continue;
293
+ balances.set(row.sku, { balance: Number(row.available), asOf: row.as_of });
294
+ }
295
+ return balances;
296
+ }
297
+
298
+ /**
299
+ * Rewrites the whole TENANT_CACHE projection for the tenant and stage from stored availability.
300
+ * Unconditional: a retried or no-op write repairs a put that failed after an earlier commit.
301
+ */
302
+ export async function writeAvailabilityProjection(
303
+ db: Queryable,
304
+ kv: { put(key: string, value: string): Promise<unknown> },
305
+ input: { tenantId: string; stage: CommerceStage },
306
+ ): Promise<void> {
307
+ const balances = await readAvailabilityBalances(db, input);
308
+ await kv.put(mirrorBalanceKey(input.tenantId, input.stage), serializeMirrorBalances(balances));
309
+ }
310
+
24
311
  async function digestId(prefix: string, parts: readonly string[]): Promise<string> {
25
312
  const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(parts.join("\n"))));
26
313
  const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
@@ -66,10 +353,20 @@ export async function recordMirrorInventoryChanged(
66
353
  ): Promise<{ eventId: string; deliveryIds: string[] } | null> {
67
354
  const eventId = await mirrorMovementEventId(input);
68
355
  const installEnv = appInstallEnvForStage(input.stage);
356
+ const availability = await db.first<{ available: number }>(
357
+ `SELECT ${availableSql("?")} AS available`,
358
+ input.tenantId,
359
+ input.stage,
360
+ input.sku,
361
+ input.tenantId,
362
+ input.stage,
363
+ input.sku,
364
+ );
69
365
  const payload = JSON.stringify({
70
366
  sku: input.sku,
71
367
  locationId: input.locationId,
72
368
  balance: input.balance,
369
+ available: Number(availability?.available ?? 0),
73
370
  asOf: input.asOf,
74
371
  });
75
372
  const installs = await db.all<{ install_id: string }>(
@@ -179,7 +476,35 @@ export interface MirrorMovement {
179
476
  quantityDelta: number;
180
477
  asOf: string;
181
478
  actorId: string;
479
+ reason?: MovementReason | typeof RECONCILE_REASON | null;
480
+ }
481
+
482
+ /**
483
+ * For the operator and import paths: declares the movement's location (a fulfillable warehouse)
484
+ * when the tenant has not, then syncs the sku's availability without an event, since those paths
485
+ * emit their own per-movement event.
486
+ */
487
+ function movementSync(input: { tenantId: string; stage: CommerceStage; sku: string; locationId: string; asOf: string }): SqlStatement[] {
488
+ const declare: SqlStatement[] =
489
+ input.locationId === MIRROR_LOCATION_UNSPECIFIED
490
+ ? []
491
+ : [
492
+ {
493
+ sql: `INSERT INTO commerce_inventory_locations (tenant_id, stage, location_id, name, kind, is_fulfillable, status, updated_at)
494
+ VALUES (?, ?, ?, ?, 'warehouse', 1, 'active', ?) ON CONFLICT DO NOTHING`,
495
+ params: [input.tenantId, input.stage, input.locationId, input.locationId, input.asOf],
496
+ },
497
+ ];
498
+ return [...declare, ...availabilitySyncStatements({
499
+ tenantId: input.tenantId,
500
+ stage: input.stage,
501
+ now: input.asOf,
502
+ scope: itemScope([{ sku: input.sku, locationId: input.locationId }]),
503
+ emit: false,
504
+ token: availabilityToken(),
505
+ })];
182
506
  }
507
+
183
508
  export async function appendMirrorMovement(db: Queryable, input: MirrorMovement): Promise<void> {
184
509
  if (
185
510
  ![input.tenantId, input.source, input.sourceEventId, input.locationId, input.actorId].every((v) =>
@@ -208,20 +533,26 @@ export async function appendMirrorMovement(db: Queryable, input: MirrorMovement)
208
533
  prior.actor_id !== input.actorId)
209
534
  )
210
535
  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
- );
536
+ await runStatements(db, [
537
+ {
538
+ sql: `INSERT INTO commerce_inventory_movements
539
+ (tenant_id,stage,source,source_event_id,sku,location_id,quantity_delta,as_of,actor_id,reason)
540
+ VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING`,
541
+ params: [
542
+ input.tenantId,
543
+ input.stage,
544
+ input.source,
545
+ input.sourceEventId,
546
+ input.sku,
547
+ input.locationId,
548
+ input.quantityDelta,
549
+ input.asOf,
550
+ input.actorId,
551
+ input.reason ?? null,
552
+ ],
553
+ },
554
+ ...movementSync(input),
555
+ ]);
225
556
  const actual = await db.first<{ quantity_delta: number; as_of: string; actor_id: string }>(
226
557
  `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
558
  input.tenantId,
@@ -409,22 +740,27 @@ export async function appendSourceOnHand(
409
740
  )
410
741
  throw new InventoryMovementError("invalid-movement");
411
742
  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
- );
743
+ await runStatements(db, [
744
+ {
745
+ sql: `INSERT INTO commerce_inventory_movements
746
+ (tenant_id,stage,source,source_event_id,sku,location_id,quantity_delta,as_of,actor_id,reason)
747
+ SELECT ?,?,?,?,?,?,CAST(? AS INTEGER) - ${OTHER_MOVEMENTS_SUM},?,?,'${RECONCILE_REASON}' WHERE true
748
+ ON CONFLICT DO NOTHING`,
749
+ params: [
750
+ input.tenantId,
751
+ input.stage,
752
+ input.source,
753
+ input.sourceEventId,
754
+ input.sku,
755
+ input.locationId,
756
+ input.onHand,
757
+ ...others,
758
+ input.asOf,
759
+ input.actorId,
760
+ ],
761
+ },
762
+ ...movementSync(input),
763
+ ]);
428
764
  const actual = await db.first<{ quantity_delta: number; as_of: string; actor_id: string; expected: number }>(
429
765
  `SELECT quantity_delta, as_of, actor_id, CAST(? AS INTEGER) - ${OTHER_MOVEMENTS_SUM} AS expected
430
766
  FROM commerce_inventory_movements
@@ -476,8 +812,8 @@ export interface SqlCondition {
476
812
  * time, inside the statement. The balance after it stays within 0..MIRROR_BALANCE_MAX, except
477
813
  * that a positive delta on a negative balance is admitted because it moves the balance toward
478
814
  * 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.
815
+ * tenant declared active for that stage (`locationAdmittedSql`). `guard` is an SQL condition (no
816
+ * leading AND) the caller's admission adds. Zero rows changed means refused.
481
817
  */
482
818
  export function guardedCorrectionStatement(movement: MirrorMovement, guard: SqlCondition): SqlCondition {
483
819
  if (
@@ -494,8 +830,8 @@ export function guardedCorrectionStatement(movement: MirrorMovement, guard: SqlC
494
830
  const delta = movement.quantityDelta;
495
831
  return {
496
832
  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),?,?
833
+ (tenant_id,stage,source,source_event_id,sku,location_id,quantity_delta,as_of,actor_id,reason)
834
+ SELECT ?,?,?,?,?,?,CAST(? AS INTEGER),?,?,?
499
835
  FROM (
500
836
  SELECT COALESCE((SELECT SUM(quantity_delta) FROM commerce_inventory_movements
501
837
  WHERE tenant_id=? AND stage=? AND sku=? AND location_id=?), 0)
@@ -504,9 +840,7 @@ export function guardedCorrectionStatement(movement: MirrorMovement, guard: SqlC
504
840
  ) AS current
505
841
  WHERE current.balance + CAST(? AS INTEGER) <= ${MIRROR_BALANCE_MAX}
506
842
  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
- ))
843
+ AND ${locationAdmittedSql("?")}
510
844
  AND (${guard.sql})`,
511
845
  params: [
512
846
  movement.tenantId,
@@ -518,6 +852,7 @@ export function guardedCorrectionStatement(movement: MirrorMovement, guard: SqlC
518
852
  delta,
519
853
  movement.asOf,
520
854
  movement.actorId,
855
+ movement.reason ?? null,
521
856
  movement.tenantId,
522
857
  movement.stage,
523
858
  movement.sku,
@@ -545,7 +880,7 @@ export async function mirrorLocationKnown(
545
880
  ): Promise<boolean> {
546
881
  if (input.locationId === MIRROR_LOCATION_UNSPECIFIED) return true;
547
882
  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`,
883
+ `SELECT 1 AS n FROM commerce_inventory_locations WHERE tenant_id=? AND stage=? AND location_id=? AND status='active'`,
549
884
  input.tenantId,
550
885
  input.stage,
551
886
  input.locationId,
@@ -553,6 +888,86 @@ export async function mirrorLocationKnown(
553
888
  return row !== null;
554
889
  }
555
890
 
891
+ export interface InventoryLocation {
892
+ locationId: string;
893
+ name: string;
894
+ kind: LocationKind;
895
+ isFulfillable: boolean;
896
+ status: LocationStatus;
897
+ updatedAt: string;
898
+ }
899
+
900
+ function locationFromRow(row: Record<string, unknown>): InventoryLocation {
901
+ return {
902
+ locationId: String(row.location_id),
903
+ name: String(row.name),
904
+ kind: String(row.kind) as LocationKind,
905
+ isFulfillable: Number(row.is_fulfillable) === 1,
906
+ status: String(row.status) as LocationStatus,
907
+ updatedAt: String(row.updated_at),
908
+ };
909
+ }
910
+
911
+ /** The tenant's declared locations for the stage, `unspecified` always among them. */
912
+ export async function listInventoryLocations(
913
+ db: Queryable,
914
+ input: { tenantId: string; stage: CommerceStage; now: string },
915
+ ): Promise<InventoryLocation[]> {
916
+ const rows = await db.all<Record<string, unknown>>(
917
+ `SELECT location_id, name, kind, is_fulfillable, status, updated_at FROM commerce_inventory_locations
918
+ WHERE tenant_id = ? AND stage = ? ORDER BY location_id`,
919
+ input.tenantId,
920
+ input.stage,
921
+ );
922
+ const locations = rows.map(locationFromRow);
923
+ if (!locations.some((location) => location.locationId === MIRROR_LOCATION_UNSPECIFIED)) {
924
+ locations.push({
925
+ locationId: MIRROR_LOCATION_UNSPECIFIED,
926
+ name: "Unspecified",
927
+ kind: "warehouse",
928
+ isFulfillable: true,
929
+ status: "active",
930
+ updatedAt: input.now,
931
+ });
932
+ locations.sort((a, b) => (a.locationId < b.locationId ? -1 : a.locationId > b.locationId ? 1 : 0));
933
+ }
934
+ return locations;
935
+ }
936
+
937
+ export async function readInventoryLocation(
938
+ db: Queryable,
939
+ input: { tenantId: string; stage: CommerceStage; locationId: string },
940
+ ): Promise<InventoryLocation | null> {
941
+ const row = await db.first<Record<string, unknown>>(
942
+ `SELECT location_id, name, kind, is_fulfillable, status, updated_at FROM commerce_inventory_locations
943
+ WHERE tenant_id = ? AND stage = ? AND location_id = ?`,
944
+ input.tenantId,
945
+ input.stage,
946
+ input.locationId,
947
+ );
948
+ return row ? locationFromRow(row) : null;
949
+ }
950
+
951
+ /** Scope of a location change: every sku with ledger rows or active allocations at that location. */
952
+ export function locationScope(input: { tenantId: string; stage: CommerceStage; locationId: string }): AvailabilityScope {
953
+ return {
954
+ sql: `SELECT sku, location_id FROM commerce_inventory_movements WHERE tenant_id = ? AND stage = ? AND location_id = ?
955
+ UNION SELECT sku, location_id FROM scrappy_allocations
956
+ WHERE tenant_id = ? AND stage = ? AND location_id = ? AND state IN ('reserved', 'confirmed')`,
957
+ params: [input.tenantId, input.stage, input.locationId, input.tenantId, input.stage, input.locationId],
958
+ };
959
+ }
960
+
961
+ /**
962
+ * SQL expression: the delta that makes one key's ledger equal an absolute on-hand. `onHand`, `sku`
963
+ * and `location` are SQL expressions; binds tenant, stage. Shared by `appendSourceOnHand` and the
964
+ * batch levels reconcile, which writes each key under a new event id, so every existing movement counts.
965
+ */
966
+ export function onHandDeltaSql(onHand: string, sku: string, location: string): string {
967
+ return `CAST(${onHand} AS INTEGER) - COALESCE((SELECT SUM(oh.quantity_delta) FROM commerce_inventory_movements AS oh
968
+ WHERE oh.tenant_id = ? AND oh.stage = ? AND oh.sku = ${sku} AND oh.location_id = ${location}), 0)`;
969
+ }
970
+
556
971
  export async function catalogImportEventId(runId: string, sku: string, onHand: number): Promise<string> {
557
972
  const quantity = onHand < 0 ? `n${-onHand}` : String(onHand);
558
973
  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.4",
3
+ "version": "6.12.6",
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",