@tokenoftrust/storefront-runner 6.11.4 → 6.11.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/src/lib/fulfillment/commerceProjection.ts +16 -23
- package/apps/storefront/src/lib/integrations/apps/inventoryWrite.ts +32 -17
- package/apps/storefront/src/lib/integrations/apps/registryAccess.ts +10 -1
- package/apps/storefront/src/lib/integrations/webhooks/emit.ts +16 -2
- package/apps/storefront/src/lib/inventory/allocations.ts +22 -41
- package/apps/storefront/src/lib/inventory/mirrorStock.ts +92 -80
- package/package.json +1 -1
|
@@ -6,7 +6,11 @@ import { admissionBindsOrder, currentCartEvent, readCommerceAdmission } from "..
|
|
|
6
6
|
import { FulfillmentService } from "./fulfillmentService.js";
|
|
7
7
|
import { fulfillmentDbFromQueryable } from "./store.js";
|
|
8
8
|
import { dispatchCommerceDeliveries } from "./commerceRuntime.js";
|
|
9
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
ORDER_DECREMENT_SOURCE,
|
|
11
|
+
readEffectiveMirrorBalance,
|
|
12
|
+
recordMirrorInventoryChanged,
|
|
13
|
+
} from "../inventory/mirrorStock.js";
|
|
10
14
|
const UNKNOWN: CommerceEvidence = { verification: "UNKNOWN", tax: "UNKNOWN", risk: "UNKNOWN", stock: "UNKNOWN" };
|
|
11
15
|
|
|
12
16
|
export async function projectCommerceOrder(
|
|
@@ -83,35 +87,24 @@ export async function projectCommerceOrder(
|
|
|
83
87
|
input.orderId,
|
|
84
88
|
],
|
|
85
89
|
},
|
|
90
|
+
{
|
|
91
|
+
sql: `SELECT DISTINCT sku, location_id FROM scrappy_allocations
|
|
92
|
+
WHERE tenant_id=? AND stage=? AND order_id=? AND state='confirmed'`,
|
|
93
|
+
params: [input.tenantId, input.stage, input.orderId],
|
|
94
|
+
},
|
|
86
95
|
]);
|
|
87
96
|
trusted = Boolean(results[0]?.results.length);
|
|
88
|
-
const confirmedAllocations = results[
|
|
97
|
+
const confirmedAllocations = trusted ? (results[3]?.results ?? []) : [];
|
|
89
98
|
for (const row of confirmedAllocations) {
|
|
90
99
|
const sku = typeof row.sku === "string" ? row.sku : "";
|
|
91
100
|
const locationId = typeof row.location_id === "string" && row.location_id ? row.location_id : "unspecified";
|
|
92
101
|
if (!sku) continue;
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?) AS ledger_sum,
|
|
97
|
-
(SELECT COUNT(*) FROM commerce_inventory_movements
|
|
98
|
-
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?) AS ledger_count,
|
|
99
|
-
(SELECT COALESCE(SUM(quantity), 0) FROM scrappy_allocations
|
|
100
|
-
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ? AND state = 'confirmed') AS confirmed_sum`,
|
|
101
|
-
input.tenantId,
|
|
102
|
-
input.stage,
|
|
103
|
-
sku,
|
|
104
|
-
locationId,
|
|
105
|
-
input.tenantId,
|
|
106
|
-
input.stage,
|
|
107
|
-
sku,
|
|
108
|
-
locationId,
|
|
109
|
-
input.tenantId,
|
|
110
|
-
input.stage,
|
|
102
|
+
const reading = await readEffectiveMirrorBalance(db, {
|
|
103
|
+
tenantId: input.tenantId,
|
|
104
|
+
stage: input.stage,
|
|
111
105
|
sku,
|
|
112
106
|
locationId,
|
|
113
|
-
);
|
|
114
|
-
const balance = Number(stat?.ledger_count ?? 0) > 0 ? Number(stat?.ledger_sum ?? 0) - Number(stat?.confirmed_sum ?? 0) : 0;
|
|
107
|
+
});
|
|
115
108
|
await recordMirrorInventoryChanged(db, {
|
|
116
109
|
tenantId: input.tenantId,
|
|
117
110
|
stage: input.stage,
|
|
@@ -119,7 +112,7 @@ export async function projectCommerceOrder(
|
|
|
119
112
|
sourceEventId: input.orderId,
|
|
120
113
|
sku,
|
|
121
114
|
locationId,
|
|
122
|
-
balance,
|
|
115
|
+
balance: reading.balance,
|
|
123
116
|
asOf: input.now,
|
|
124
117
|
notify: dispatchCommerceDeliveries,
|
|
125
118
|
gate: {
|
|
@@ -178,6 +178,27 @@ async function priorAnswer(db: Queryable, installId: string, key: string, bodyHa
|
|
|
178
178
|
return receiptFrom(check.responseBody) ?? inventoryRefusal("idempotency-conflict");
|
|
179
179
|
}
|
|
180
180
|
|
|
181
|
+
async function ensureReceiptEmitted(
|
|
182
|
+
db: Queryable,
|
|
183
|
+
actor: InventoryWriteActor,
|
|
184
|
+
answer: InventoryWriteResponse,
|
|
185
|
+
): Promise<InventoryWriteResponse> {
|
|
186
|
+
if ("receiptId" in answer.body) {
|
|
187
|
+
const source = await appSource(actor.appId);
|
|
188
|
+
await emitInventoryChanged(db, {
|
|
189
|
+
tenantId: actor.tenantId,
|
|
190
|
+
stage: actor.stage,
|
|
191
|
+
source,
|
|
192
|
+
sourceEventId: answer.body.receiptId,
|
|
193
|
+
sku: answer.body.sku,
|
|
194
|
+
locationId: answer.body.locationId,
|
|
195
|
+
balance: answer.body.balance,
|
|
196
|
+
asOf: answer.body.asOf,
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
return answer;
|
|
200
|
+
}
|
|
201
|
+
|
|
181
202
|
export interface InventoryWriteRequest {
|
|
182
203
|
actor: InventoryWriteActor;
|
|
183
204
|
idempotencyKey: string;
|
|
@@ -195,7 +216,7 @@ export async function applyAppInventoryDelta(db: Queryable, request: InventoryWr
|
|
|
195
216
|
const key = namespacedKey(actor, request.idempotencyKey);
|
|
196
217
|
const bodyHash = await computeBodyHash({ operation: "inventory.write", ...delta });
|
|
197
218
|
const prior = await priorAnswer(db, actor.installId, key, bodyHash);
|
|
198
|
-
if (prior) return prior;
|
|
219
|
+
if (prior) return ensureReceiptEmitted(db, actor, prior);
|
|
199
220
|
|
|
200
221
|
const sku = await request.resolveSku(delta.sku);
|
|
201
222
|
if (sku === null || !isStoredSku(sku)) return inventoryRefusal("unknown-sku");
|
|
@@ -229,8 +250,10 @@ export async function applyAppInventoryDelta(db: Queryable, request: InventoryWr
|
|
|
229
250
|
sql: `INSERT INTO idempotency_keys (install_id, idempotency_key, body_hash, response_body, created_at)
|
|
230
251
|
SELECT ?, ?, ?, json_object('status', 201, 'body', json_object(
|
|
231
252
|
'receiptId', ?, 'sku', ?, 'locationId', ?, 'quantityDelta', CAST(? AS INTEGER), 'asOf', ?,
|
|
232
|
-
'balance', (SELECT SUM(quantity_delta) FROM commerce_inventory_movements
|
|
233
|
-
|
|
253
|
+
'balance', COALESCE((SELECT SUM(quantity_delta) FROM commerce_inventory_movements
|
|
254
|
+
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?), 0)
|
|
255
|
+
- COALESCE((SELECT SUM(quantity) FROM scrappy_allocations
|
|
256
|
+
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ? AND state = 'confirmed'), 0))), ?
|
|
234
257
|
WHERE changes() = 1`,
|
|
235
258
|
params: [
|
|
236
259
|
actor.installId,
|
|
@@ -245,6 +268,10 @@ export async function applyAppInventoryDelta(db: Queryable, request: InventoryWr
|
|
|
245
268
|
actor.stage,
|
|
246
269
|
sku,
|
|
247
270
|
delta.locationId,
|
|
271
|
+
actor.tenantId,
|
|
272
|
+
actor.stage,
|
|
273
|
+
sku,
|
|
274
|
+
delta.locationId,
|
|
248
275
|
asOf,
|
|
249
276
|
],
|
|
250
277
|
},
|
|
@@ -252,19 +279,7 @@ export async function applyAppInventoryDelta(db: Queryable, request: InventoryWr
|
|
|
252
279
|
if ((changes[0] ?? 0) === 1 && (changes[2] ?? 0) === 1) {
|
|
253
280
|
const answer = await priorAnswer(db, actor.installId, key, bodyHash);
|
|
254
281
|
if (!answer) return inventoryRefusal("unavailable");
|
|
255
|
-
|
|
256
|
-
await emitInventoryChanged(db, {
|
|
257
|
-
tenantId: actor.tenantId,
|
|
258
|
-
stage: actor.stage,
|
|
259
|
-
source,
|
|
260
|
-
sourceEventId: receiptId,
|
|
261
|
-
sku: answer.body.sku,
|
|
262
|
-
locationId: answer.body.locationId,
|
|
263
|
-
balance: answer.body.balance,
|
|
264
|
-
asOf: answer.body.asOf,
|
|
265
|
-
});
|
|
266
|
-
}
|
|
267
|
-
return answer;
|
|
282
|
+
return ensureReceiptEmitted(db, actor, answer);
|
|
268
283
|
}
|
|
269
284
|
return classifyRefused(db, actor, delta, key, bodyHash);
|
|
270
285
|
}
|
|
@@ -278,7 +293,7 @@ async function classifyRefused(
|
|
|
278
293
|
bodyHash: string,
|
|
279
294
|
): Promise<InventoryWriteResponse> {
|
|
280
295
|
const prior = await priorAnswer(db, actor.installId, key, bodyHash);
|
|
281
|
-
if (prior) return prior;
|
|
296
|
+
if (prior) return ensureReceiptEmitted(db, actor, prior);
|
|
282
297
|
const install = await db.first<{ tenant_id: string; env: string; status: string; scopes: string }>(
|
|
283
298
|
`SELECT tenant_id, env, status, scopes FROM app_installs WHERE install_id = ?`,
|
|
284
299
|
actor.installId,
|
|
@@ -17,7 +17,7 @@ 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
19
|
import { fromD1 } from "../../catalog/d1/catalog.js";
|
|
20
|
-
import { readD1, readEnv } from "../../publication/shared/env.js";
|
|
20
|
+
import { readD1, readEnv, readKv } from "../../publication/shared/env.js";
|
|
21
21
|
|
|
22
22
|
/**
|
|
23
23
|
* No-store JSON response — install/rotate bodies carry a one-time client
|
|
@@ -43,3 +43,12 @@ export async function getRegistryService(): Promise<AppRegistryService | Respons
|
|
|
43
43
|
const credentials = new D1CredentialStore(db, activeKid);
|
|
44
44
|
return new AppRegistryService(db, credentials);
|
|
45
45
|
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Read the Worker's `TENANT_CACHE` KV binding used by the fixed-window
|
|
49
|
+
* per-install rate limiter (`kvWindow.ts`). Returns `undefined` when unconfigured
|
|
50
|
+
* so `checkRateLimit` fails closed.
|
|
51
|
+
*/
|
|
52
|
+
export async function getAppRateLimitKv(): Promise<KVNamespace | undefined> {
|
|
53
|
+
return readKv("TENANT_CACHE");
|
|
54
|
+
}
|
|
@@ -273,6 +273,19 @@ export async function emitInventoryChanged(
|
|
|
273
273
|
deliveryId: await inventoryDeliveryId(eventId, row.install_id),
|
|
274
274
|
})),
|
|
275
275
|
);
|
|
276
|
+
const existingEvent = await db.first<{ ok: number }>(`SELECT 1 AS ok FROM webhook_events WHERE id = ?`, eventId);
|
|
277
|
+
const existingDeliveries =
|
|
278
|
+
targets.length > 0
|
|
279
|
+
? await db.all<{ delivery_id: string }>(
|
|
280
|
+
`SELECT delivery_id FROM webhook_deliveries WHERE event_id = ?`,
|
|
281
|
+
eventId,
|
|
282
|
+
)
|
|
283
|
+
: [];
|
|
284
|
+
const existingDeliveryIds = new Set(existingDeliveries.map((row) => row.delivery_id));
|
|
285
|
+
const missingTargets = targets.filter((target) => !existingDeliveryIds.has(target.deliveryId));
|
|
286
|
+
if (existingEvent && missingTargets.length === 0) {
|
|
287
|
+
return { eventId, deliveryIds: targets.map((target) => target.deliveryId) };
|
|
288
|
+
}
|
|
276
289
|
const baseGate: CommerceEventStatement = input.gate ?? {
|
|
277
290
|
sql: `EXISTS (
|
|
278
291
|
SELECT 1 FROM commerce_inventory_movements
|
|
@@ -308,10 +321,11 @@ export async function emitInventoryChanged(
|
|
|
308
321
|
)
|
|
309
322
|
: [];
|
|
310
323
|
const deliveryIds = committed.map((row) => row.delivery_id);
|
|
311
|
-
|
|
324
|
+
const newDeliveryIds = deliveryIds.filter((id) => !existingDeliveryIds.has(id));
|
|
325
|
+
if (newDeliveryIds.length > 0) {
|
|
312
326
|
const notify = input.notify ?? dispatchInventoryDeliveries;
|
|
313
327
|
try {
|
|
314
|
-
await notify(input.tenantId,
|
|
328
|
+
await notify(input.tenantId, newDeliveryIds);
|
|
315
329
|
} catch {
|
|
316
330
|
// Pending rows remain durable in webhook_deliveries.
|
|
317
331
|
}
|
|
@@ -656,6 +656,7 @@ import {
|
|
|
656
656
|
mirrorMovementDeliveryId,
|
|
657
657
|
mirrorMovementEventId,
|
|
658
658
|
ORDER_DECREMENT_SOURCE,
|
|
659
|
+
readEffectiveMirrorBalance,
|
|
659
660
|
recordMirrorInventoryChanged,
|
|
660
661
|
} from "./mirrorStock.js";
|
|
661
662
|
|
|
@@ -712,13 +713,22 @@ export async function confirmHoldOnce(
|
|
|
712
713
|
params: [...scope, ...scope],
|
|
713
714
|
},
|
|
714
715
|
{
|
|
715
|
-
sql: `SELECT state FROM scrappy_allocations
|
|
716
|
+
sql: `SELECT state, sku, location_id FROM scrappy_allocations
|
|
716
717
|
WHERE tenant_id = ? AND stage = ? AND order_id = ?`,
|
|
717
718
|
params: scope,
|
|
718
719
|
},
|
|
719
720
|
]);
|
|
720
721
|
const confirmedRows = results[0] ?? [];
|
|
721
|
-
|
|
722
|
+
const allAllocations = results[3] ?? [];
|
|
723
|
+
const confirmedTargets = new Map<string, { sku: string; locationId: string }>();
|
|
724
|
+
for (const row of allAllocations) {
|
|
725
|
+
if (text(row, "state") !== "confirmed") continue;
|
|
726
|
+
const sku = text(row, "sku");
|
|
727
|
+
const locationId = text(row, "location_id") || "unspecified";
|
|
728
|
+
if (!sku) continue;
|
|
729
|
+
confirmedTargets.set(`${sku}\n${locationId}`, { sku, locationId });
|
|
730
|
+
}
|
|
731
|
+
if (confirmedTargets.size > 0) {
|
|
722
732
|
const orderRows = await runner.all(
|
|
723
733
|
`SELECT placed_at FROM scrappy_commerce_orders WHERE tenant_id = ? AND stage = ? AND order_id = ?`,
|
|
724
734
|
scope,
|
|
@@ -735,43 +745,14 @@ export async function confirmHoldOnce(
|
|
|
735
745
|
await runner.batch(statements);
|
|
736
746
|
},
|
|
737
747
|
};
|
|
738
|
-
for (const
|
|
739
|
-
const
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
(SELECT COUNT(*) FROM commerce_inventory_movements
|
|
747
|
-
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?) AS ledger_count,
|
|
748
|
-
(SELECT MAX(as_of) FROM commerce_inventory_movements
|
|
749
|
-
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?) AS max_as_of,
|
|
750
|
-
(SELECT COALESCE(SUM(quantity), 0) FROM scrappy_allocations
|
|
751
|
-
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ? AND state = 'confirmed') AS confirmed_sum`,
|
|
752
|
-
[
|
|
753
|
-
input.tenantId,
|
|
754
|
-
input.stage,
|
|
755
|
-
sku,
|
|
756
|
-
locationId,
|
|
757
|
-
input.tenantId,
|
|
758
|
-
input.stage,
|
|
759
|
-
sku,
|
|
760
|
-
locationId,
|
|
761
|
-
input.tenantId,
|
|
762
|
-
input.stage,
|
|
763
|
-
sku,
|
|
764
|
-
locationId,
|
|
765
|
-
input.tenantId,
|
|
766
|
-
input.stage,
|
|
767
|
-
sku,
|
|
768
|
-
locationId,
|
|
769
|
-
],
|
|
770
|
-
);
|
|
771
|
-
const stat = stats[0] ?? {};
|
|
772
|
-
const ledgerCount = Number(stat.ledger_count ?? 0);
|
|
773
|
-
const balance = ledgerCount > 0 ? Number(stat.ledger_sum ?? 0) - Number(stat.confirmed_sum ?? 0) : 0;
|
|
774
|
-
const asOf = text(stat, "max_as_of") || placedAt;
|
|
748
|
+
for (const { sku, locationId } of confirmedTargets.values()) {
|
|
749
|
+
const reading = await readEffectiveMirrorBalance(runnerQueryable, {
|
|
750
|
+
tenantId: input.tenantId,
|
|
751
|
+
stage: input.stage,
|
|
752
|
+
sku,
|
|
753
|
+
locationId,
|
|
754
|
+
});
|
|
755
|
+
const asOf = reading.asOf && reading.asOf > placedAt ? reading.asOf : placedAt;
|
|
775
756
|
await recordMirrorInventoryChanged(runnerQueryable, {
|
|
776
757
|
tenantId: input.tenantId,
|
|
777
758
|
stage: input.stage,
|
|
@@ -779,7 +760,7 @@ export async function confirmHoldOnce(
|
|
|
779
760
|
sourceEventId: input.orderId,
|
|
780
761
|
sku,
|
|
781
762
|
locationId,
|
|
782
|
-
balance,
|
|
763
|
+
balance: reading.balance,
|
|
783
764
|
asOf,
|
|
784
765
|
gate: {
|
|
785
766
|
sql: `EXISTS (
|
|
@@ -793,7 +774,7 @@ export async function confirmHoldOnce(
|
|
|
793
774
|
}
|
|
794
775
|
return {
|
|
795
776
|
decremented: sumQuantity(confirmedRows),
|
|
796
|
-
states:
|
|
777
|
+
states: allAllocations.map((row) => text(row, "state")),
|
|
797
778
|
};
|
|
798
779
|
}
|
|
799
780
|
|
|
@@ -82,6 +82,19 @@ export async function recordMirrorInventoryChanged(
|
|
|
82
82
|
deliveryId: await mirrorMovementDeliveryId(eventId, row.install_id),
|
|
83
83
|
})),
|
|
84
84
|
);
|
|
85
|
+
const existingEvent = await db.first<{ ok: number }>(`SELECT 1 AS ok FROM webhook_events WHERE id = ?`, eventId);
|
|
86
|
+
const existingDeliveries =
|
|
87
|
+
targets.length > 0
|
|
88
|
+
? await db.all<{ delivery_id: string }>(
|
|
89
|
+
`SELECT delivery_id FROM webhook_deliveries WHERE event_id = ?`,
|
|
90
|
+
eventId,
|
|
91
|
+
)
|
|
92
|
+
: [];
|
|
93
|
+
const existingDeliveryIds = new Set(existingDeliveries.map((row) => row.delivery_id));
|
|
94
|
+
const missingTargets = targets.filter((target) => !existingDeliveryIds.has(target.deliveryId));
|
|
95
|
+
if (existingEvent && missingTargets.length === 0) {
|
|
96
|
+
return { eventId, deliveryIds: targets.map((target) => target.deliveryId) };
|
|
97
|
+
}
|
|
85
98
|
const baseGate: SqlCondition = input.gate ?? {
|
|
86
99
|
sql: `EXISTS (
|
|
87
100
|
SELECT 1 FROM commerce_inventory_movements
|
|
@@ -133,10 +146,11 @@ export async function recordMirrorInventoryChanged(
|
|
|
133
146
|
)
|
|
134
147
|
: [];
|
|
135
148
|
const deliveryIds = committed.map((row) => row.delivery_id);
|
|
149
|
+
const newDeliveryIds = deliveryIds.filter((id) => !existingDeliveryIds.has(id));
|
|
136
150
|
const notify = input.notify ?? defaultInventoryNotify;
|
|
137
|
-
if (
|
|
151
|
+
if (newDeliveryIds.length > 0 && notify) {
|
|
138
152
|
try {
|
|
139
|
-
await notify(input.tenantId,
|
|
153
|
+
await notify(input.tenantId, newDeliveryIds);
|
|
140
154
|
} catch {
|
|
141
155
|
// Pending rows remain in webhook_deliveries for the commerce alarm.
|
|
142
156
|
}
|
|
@@ -220,24 +234,22 @@ export async function appendMirrorMovement(db: Queryable, input: MirrorMovement)
|
|
|
220
234
|
actual.actor_id !== input.actorId
|
|
221
235
|
)
|
|
222
236
|
throw new InventoryMovementError("conflict");
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
});
|
|
240
|
-
}
|
|
237
|
+
const reading = await readEffectiveMirrorBalance(db, {
|
|
238
|
+
tenantId: input.tenantId,
|
|
239
|
+
stage: input.stage,
|
|
240
|
+
sku: input.sku,
|
|
241
|
+
locationId: input.locationId,
|
|
242
|
+
});
|
|
243
|
+
await recordMirrorInventoryChanged(db, {
|
|
244
|
+
tenantId: input.tenantId,
|
|
245
|
+
stage: input.stage,
|
|
246
|
+
source: input.source,
|
|
247
|
+
sourceEventId: input.sourceEventId,
|
|
248
|
+
sku: input.sku,
|
|
249
|
+
locationId: input.locationId,
|
|
250
|
+
balance: reading.balance,
|
|
251
|
+
asOf: actual.as_of,
|
|
252
|
+
});
|
|
241
253
|
}
|
|
242
254
|
export async function readMirrorStock(
|
|
243
255
|
db: Queryable,
|
|
@@ -283,36 +295,6 @@ export const MIRROR_LOCATION_UNSPECIFIED = "unspecified";
|
|
|
283
295
|
export const CATALOG_IMPORT_ACTOR_ID = "catalog-import";
|
|
284
296
|
export const CATALOG_IMPORT_SOURCE = "catalog-import";
|
|
285
297
|
export const ORDER_DECREMENT_SOURCE = "order-decrement";
|
|
286
|
-
export const ORDER_DECREMENT_ACTOR_ID = "commerce-order";
|
|
287
|
-
|
|
288
|
-
/** Records an order stock decrement in the mirror ledger and emits `inventory.changed` once. */
|
|
289
|
-
export async function appendOrderDecrement(
|
|
290
|
-
db: Queryable,
|
|
291
|
-
input: {
|
|
292
|
-
tenantId: string;
|
|
293
|
-
stage: CommerceStage;
|
|
294
|
-
orderId: string;
|
|
295
|
-
sku: string;
|
|
296
|
-
locationId?: string;
|
|
297
|
-
quantity: number;
|
|
298
|
-
asOf: string;
|
|
299
|
-
},
|
|
300
|
-
): Promise<void> {
|
|
301
|
-
if (!Number.isSafeInteger(input.quantity) || input.quantity <= 0) {
|
|
302
|
-
throw new InventoryMovementError("invalid-movement");
|
|
303
|
-
}
|
|
304
|
-
await appendMirrorMovement(db, {
|
|
305
|
-
tenantId: input.tenantId,
|
|
306
|
-
stage: input.stage,
|
|
307
|
-
source: ORDER_DECREMENT_SOURCE,
|
|
308
|
-
sourceEventId: input.orderId,
|
|
309
|
-
sku: input.sku,
|
|
310
|
-
locationId: input.locationId ?? MIRROR_LOCATION_UNSPECIFIED,
|
|
311
|
-
quantityDelta: -input.quantity,
|
|
312
|
-
asOf: input.asOf,
|
|
313
|
-
actorId: ORDER_DECREMENT_ACTOR_ID,
|
|
314
|
-
});
|
|
315
|
-
}
|
|
316
298
|
|
|
317
299
|
export interface MirrorBalance {
|
|
318
300
|
balance: number;
|
|
@@ -332,6 +314,40 @@ interface BalanceKey {
|
|
|
332
314
|
locationId: string;
|
|
333
315
|
}
|
|
334
316
|
|
|
317
|
+
/**
|
|
318
|
+
* Net mirror balance for `inventory.changed` and app inventory receipts:
|
|
319
|
+
* summed ledger movements (`commerce_inventory_movements`) minus confirmed order
|
|
320
|
+
* allocations (`scrappy_allocations WHERE state = 'confirmed'`) for the same key.
|
|
321
|
+
*/
|
|
322
|
+
export async function readEffectiveMirrorBalance(
|
|
323
|
+
db: Queryable,
|
|
324
|
+
input: BalanceKey,
|
|
325
|
+
): Promise<{ balance: number; asOf: string | null }> {
|
|
326
|
+
const row = await db.first<{ ledger_sum: number; confirmed_sum: number; as_of: string | null }>(
|
|
327
|
+
`SELECT
|
|
328
|
+
COALESCE((SELECT SUM(quantity_delta) FROM commerce_inventory_movements
|
|
329
|
+
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?), 0) AS ledger_sum,
|
|
330
|
+
COALESCE((SELECT SUM(quantity) FROM scrappy_allocations
|
|
331
|
+
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ? AND state = 'confirmed'), 0) AS confirmed_sum,
|
|
332
|
+
(SELECT MAX(as_of) FROM commerce_inventory_movements
|
|
333
|
+
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?) AS as_of`,
|
|
334
|
+
input.tenantId,
|
|
335
|
+
input.stage,
|
|
336
|
+
input.sku,
|
|
337
|
+
input.locationId,
|
|
338
|
+
input.tenantId,
|
|
339
|
+
input.stage,
|
|
340
|
+
input.sku,
|
|
341
|
+
input.locationId,
|
|
342
|
+
input.tenantId,
|
|
343
|
+
input.stage,
|
|
344
|
+
input.sku,
|
|
345
|
+
input.locationId,
|
|
346
|
+
);
|
|
347
|
+
const balance = Number(row?.ledger_sum ?? 0) - Number(row?.confirmed_sum ?? 0);
|
|
348
|
+
return { balance: Number.isSafeInteger(balance) ? balance : 0, asOf: row?.as_of ?? null };
|
|
349
|
+
}
|
|
350
|
+
|
|
335
351
|
/** Sum of movements, including a non-positive or stale balance. No rows is null, not zero. */
|
|
336
352
|
export async function readMirrorBalance(db: Queryable, input: BalanceKey): Promise<MirrorBalance | null> {
|
|
337
353
|
const row = await db.first<{ balance: number | null; as_of: string | null }>(
|
|
@@ -388,16 +404,6 @@ export async function appendSourceOnHand(
|
|
|
388
404
|
!["preview", "publication"].includes(input.stage)
|
|
389
405
|
)
|
|
390
406
|
throw new InventoryMovementError("invalid-movement");
|
|
391
|
-
const prior = await db.first<{ one: number }>(
|
|
392
|
-
`SELECT 1 AS one FROM commerce_inventory_movements
|
|
393
|
-
WHERE tenant_id=? AND stage=? AND source=? AND source_event_id=? AND sku=? AND location_id=?`,
|
|
394
|
-
input.tenantId,
|
|
395
|
-
input.stage,
|
|
396
|
-
input.source,
|
|
397
|
-
input.sourceEventId,
|
|
398
|
-
input.sku,
|
|
399
|
-
input.locationId,
|
|
400
|
-
);
|
|
401
407
|
const others = [input.tenantId, input.stage, input.sku, input.locationId, input.source, input.sourceEventId];
|
|
402
408
|
await db.run(
|
|
403
409
|
`INSERT INTO commerce_inventory_movements
|
|
@@ -435,24 +441,22 @@ export async function appendSourceOnHand(
|
|
|
435
441
|
actual.actor_id !== input.actorId
|
|
436
442
|
)
|
|
437
443
|
throw new InventoryMovementError("conflict");
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
});
|
|
455
|
-
}
|
|
444
|
+
const reading = await readEffectiveMirrorBalance(db, {
|
|
445
|
+
tenantId: input.tenantId,
|
|
446
|
+
stage: input.stage,
|
|
447
|
+
sku: input.sku,
|
|
448
|
+
locationId: input.locationId,
|
|
449
|
+
});
|
|
450
|
+
await recordMirrorInventoryChanged(db, {
|
|
451
|
+
tenantId: input.tenantId,
|
|
452
|
+
stage: input.stage,
|
|
453
|
+
source: input.source,
|
|
454
|
+
sourceEventId: input.sourceEventId,
|
|
455
|
+
sku: input.sku,
|
|
456
|
+
locationId: input.locationId,
|
|
457
|
+
balance: reading.balance,
|
|
458
|
+
asOf: actual.as_of,
|
|
459
|
+
});
|
|
456
460
|
}
|
|
457
461
|
|
|
458
462
|
/** The largest balance a key may hold: the mirror ledger never stores or reports an unsafe integer. */
|
|
@@ -488,8 +492,12 @@ export function guardedCorrectionStatement(movement: MirrorMovement, guard: SqlC
|
|
|
488
492
|
sql: `INSERT INTO commerce_inventory_movements
|
|
489
493
|
(tenant_id,stage,source,source_event_id,sku,location_id,quantity_delta,as_of,actor_id)
|
|
490
494
|
SELECT ?,?,?,?,?,?,CAST(? AS INTEGER),?,?
|
|
491
|
-
FROM (
|
|
492
|
-
|
|
495
|
+
FROM (
|
|
496
|
+
SELECT COALESCE((SELECT SUM(quantity_delta) FROM commerce_inventory_movements
|
|
497
|
+
WHERE tenant_id=? AND stage=? AND sku=? AND location_id=?), 0)
|
|
498
|
+
- COALESCE((SELECT SUM(quantity) FROM scrappy_allocations
|
|
499
|
+
WHERE tenant_id=? AND stage=? AND sku=? AND location_id=? AND state='confirmed'), 0) AS balance
|
|
500
|
+
) AS current
|
|
493
501
|
WHERE current.balance + CAST(? AS INTEGER) <= ${MIRROR_BALANCE_MAX}
|
|
494
502
|
AND (current.balance + CAST(? AS INTEGER) >= 0 OR CAST(? AS INTEGER) > 0)
|
|
495
503
|
AND (? = '${MIRROR_LOCATION_UNSPECIFIED}' OR EXISTS (
|
|
@@ -510,6 +518,10 @@ export function guardedCorrectionStatement(movement: MirrorMovement, guard: SqlC
|
|
|
510
518
|
movement.stage,
|
|
511
519
|
movement.sku,
|
|
512
520
|
movement.locationId,
|
|
521
|
+
movement.tenantId,
|
|
522
|
+
movement.stage,
|
|
523
|
+
movement.sku,
|
|
524
|
+
movement.locationId,
|
|
513
525
|
delta,
|
|
514
526
|
delta,
|
|
515
527
|
delta,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "6.11.
|
|
3
|
+
"version": "6.11.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",
|