@tokenoftrust/storefront-runner 6.12.4 → 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.
- 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 +442 -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
|
@@ -1,39 +1,72 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
2
|
+
* Private Apps inventory writes. An installed app with scope `inventory:write` reports stock into
|
|
3
|
+
* the tenant's mirror ledger (`commerce_inventory_movements`, ADR 0033) and declares the locations
|
|
4
|
+
* it reports for. It is a merchant-consented mirror: it never decrements for an order, never
|
|
5
|
+
* reserves, and is never an authoritative provider.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* holds the receipt) insert only when that movement inserted. Zero rows means refused: no
|
|
12
|
-
* movement, no audit, no receipt.
|
|
7
|
+
* - `applyAppInventoryDelta`: one per-sku, per-location delta (optionally with a WMS reason).
|
|
8
|
+
* - `applyAppInventoryMovements`: a batch of 1..250 WMS movements, each with its reason.
|
|
9
|
+
* - `applyAppInventoryLevels`: a batch of 1..250 absolute on-hand levels (reason `reconcile`).
|
|
10
|
+
* - `upsertAppInventoryLocation`: declares or updates one location.
|
|
13
11
|
*
|
|
14
|
-
*
|
|
15
|
-
* `
|
|
12
|
+
* Each write is one D1 transaction holding admission, the ledger rows, the audit row, the
|
|
13
|
+
* idempotency receipt, the `inventory.changed` events with their pending deliveries, and the
|
|
14
|
+
* recomputed availability per sku. A refused batch item rolls the whole transaction back: nothing
|
|
15
|
+
* is written. Every field the caller could forge is derived here: `asOf` is the server receive
|
|
16
|
+
* time, `source` the app namespace of the install, `sourceEventId` a digest of the namespaced
|
|
16
17
|
* idempotency key, `actorId` the authenticated install.
|
|
17
18
|
*/
|
|
18
19
|
import { isStoredSku, parseSku, skuKey } from "@tot/public-runtime/sku";
|
|
19
20
|
import type { CatalogProduct, CommerceStage } from "@tot/public-runtime";
|
|
20
21
|
import type { Queryable, QueryStatement } from "../../catalog/d1/catalog.js";
|
|
21
22
|
import {
|
|
23
|
+
availabilitySyncStatements,
|
|
24
|
+
availabilityToken,
|
|
25
|
+
BATCH_REFUSED_CONSTRAINT,
|
|
22
26
|
guardedCorrectionStatement,
|
|
23
|
-
|
|
27
|
+
itemScope,
|
|
28
|
+
LOCATION_KINDS,
|
|
29
|
+
LOCATION_STATUSES,
|
|
30
|
+
locationAdmittedSql,
|
|
31
|
+
locationBalanceSql,
|
|
32
|
+
locationScope,
|
|
33
|
+
MIRROR_BALANCE_MAX,
|
|
24
34
|
MIRROR_LOCATION_UNSPECIFIED,
|
|
35
|
+
mirrorLocationKnown,
|
|
36
|
+
MOVEMENT_REASONS,
|
|
37
|
+
movementEventStatements,
|
|
38
|
+
notifyInventoryDeliveries,
|
|
39
|
+
onHandDeltaSql,
|
|
40
|
+
readInventoryLocation,
|
|
41
|
+
RECONCILE_REASON,
|
|
42
|
+
type InventoryChangedNotify,
|
|
43
|
+
type InventoryLocation,
|
|
44
|
+
type LocationKind,
|
|
45
|
+
type LocationStatus,
|
|
46
|
+
type MovementReason,
|
|
25
47
|
type SqlCondition,
|
|
48
|
+
type SqlStatement,
|
|
26
49
|
} from "../../inventory/mirrorStock.js";
|
|
27
50
|
import { checkIdempotency, computeBodyHash } from "./orders/idempotency.js";
|
|
28
|
-
import { emitInventoryChanged } from "../webhooks/emit.js";
|
|
29
51
|
import { appInstallEnvForStage } from "./appInstallEnv.js";
|
|
30
52
|
|
|
31
53
|
export const INVENTORY_WRITE_SCOPE = "inventory:write";
|
|
32
54
|
export const INVENTORY_AUDIT_EVENT = "inventory.corrected";
|
|
55
|
+
export const INVENTORY_BATCH_AUDIT_EVENT = "inventory.movements.recorded";
|
|
56
|
+
export const INVENTORY_LEVELS_AUDIT_EVENT = "inventory.levels.reconciled";
|
|
57
|
+
export const INVENTORY_LOCATION_AUDIT_EVENT = "inventory.location.declared";
|
|
58
|
+
/** Most items one movements or levels batch may carry. */
|
|
59
|
+
export const INVENTORY_BATCH_MAX = 250;
|
|
60
|
+
/** How far ahead of the server clock an `observedAt` may be. */
|
|
61
|
+
export const OBSERVED_AT_SKEW_MS = 5 * 60 * 1000;
|
|
33
62
|
|
|
34
63
|
const ID = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
35
64
|
const IDEMPOTENCY_KEY = /^[\x21-\x7e]{8,128}$/;
|
|
36
|
-
const
|
|
65
|
+
const DELTA_KEYS = new Set(["sku", "locationId", "quantityDelta", "reason"]);
|
|
66
|
+
const BATCH_MOVEMENT_KEYS = new Set(["sku", "locationId", "quantityDelta", "reason"]);
|
|
67
|
+
const LEVEL_KEYS = new Set(["sku", "locationId", "onHand", "observedAt"]);
|
|
68
|
+
const LOCATION_KEYS = new Set(["name", "kind", "isFulfillable", "status"]);
|
|
69
|
+
const NAME_MAX = 200;
|
|
37
70
|
/** Fields the platform derives; a body naming any of them is refused, never trusted or ignored. */
|
|
38
71
|
export const SERVER_DERIVED_FIELDS = ["asOf", "source", "sourceEventId", "actorId"] as const;
|
|
39
72
|
|
|
@@ -45,6 +78,7 @@ export type InventoryRefusalCode =
|
|
|
45
78
|
| "denied"
|
|
46
79
|
| "unknown-sku"
|
|
47
80
|
| "unknown-location"
|
|
81
|
+
| "location-protected"
|
|
48
82
|
| "balance-out-of-range"
|
|
49
83
|
| "idempotency-conflict"
|
|
50
84
|
| "unavailable";
|
|
@@ -57,11 +91,19 @@ const STATUS: Record<InventoryRefusalCode, number> = {
|
|
|
57
91
|
denied: 403,
|
|
58
92
|
"unknown-sku": 422,
|
|
59
93
|
"unknown-location": 422,
|
|
94
|
+
"location-protected": 409,
|
|
60
95
|
"balance-out-of-range": 409,
|
|
61
96
|
"idempotency-conflict": 409,
|
|
62
97
|
unavailable: 503,
|
|
63
98
|
};
|
|
64
99
|
|
|
100
|
+
export interface InventoryRefusal {
|
|
101
|
+
code: InventoryRefusalCode;
|
|
102
|
+
error: string;
|
|
103
|
+
/** The batch item the refusal names, when it names one. */
|
|
104
|
+
index?: number;
|
|
105
|
+
}
|
|
106
|
+
|
|
65
107
|
export interface InventoryReceipt {
|
|
66
108
|
receiptId: string;
|
|
67
109
|
sku: string;
|
|
@@ -71,15 +113,49 @@ export interface InventoryReceipt {
|
|
|
71
113
|
balance: number;
|
|
72
114
|
}
|
|
73
115
|
|
|
74
|
-
export interface
|
|
116
|
+
export interface InventoryMovementsReceipt {
|
|
117
|
+
receiptId: string;
|
|
118
|
+
asOf: string;
|
|
119
|
+
items: { sku: string; locationId: string; quantityDelta: number; reason: MovementReason; balance: number }[];
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface InventoryLevelsReceipt {
|
|
123
|
+
receiptId: string;
|
|
124
|
+
asOf: string;
|
|
125
|
+
items: { sku: string; locationId: string; onHand: number; observedAt: string; quantityDelta: number; balance: number }[];
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export interface InventoryWriteResponse<T = InventoryReceipt> {
|
|
75
129
|
status: number;
|
|
76
|
-
body:
|
|
130
|
+
body: T | InventoryRefusal;
|
|
77
131
|
}
|
|
78
132
|
|
|
79
133
|
export interface AppInventoryDelta {
|
|
80
134
|
sku: string;
|
|
81
135
|
locationId: string;
|
|
82
136
|
quantityDelta: number;
|
|
137
|
+
reason?: MovementReason;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export interface AppInventoryMovement {
|
|
141
|
+
sku: string;
|
|
142
|
+
locationId: string;
|
|
143
|
+
quantityDelta: number;
|
|
144
|
+
reason: MovementReason;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export interface AppInventoryLevel {
|
|
148
|
+
sku: string;
|
|
149
|
+
locationId: string;
|
|
150
|
+
onHand: number;
|
|
151
|
+
observedAt: string;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export interface AppInventoryLocationInput {
|
|
155
|
+
name: string;
|
|
156
|
+
kind: LocationKind;
|
|
157
|
+
isFulfillable: boolean;
|
|
158
|
+
status: LocationStatus;
|
|
83
159
|
}
|
|
84
160
|
|
|
85
161
|
/** The authenticated install a write runs as. Built by the route from the verified token, never from the body. */
|
|
@@ -90,28 +166,142 @@ export interface InventoryWriteActor {
|
|
|
90
166
|
appId: string;
|
|
91
167
|
}
|
|
92
168
|
|
|
93
|
-
export function inventoryRefusal(code: InventoryRefusalCode): InventoryWriteResponse {
|
|
169
|
+
export function inventoryRefusal(code: InventoryRefusalCode, index?: number): InventoryWriteResponse<never> {
|
|
94
170
|
if (code === "invalid_token") return { status: 401, body: { code, error: "Unauthorized" } };
|
|
95
|
-
return { status: STATUS[code], body: { code, error: code } };
|
|
171
|
+
return { status: STATUS[code], body: index === undefined ? { code, error: code } : { code, error: code, index } };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function isInventoryRefusal(body: unknown): body is InventoryRefusal {
|
|
175
|
+
return isRecord(body) && typeof body.code === "string" && typeof body.error === "string";
|
|
96
176
|
}
|
|
97
177
|
|
|
98
178
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
99
179
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
100
180
|
}
|
|
101
181
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
182
|
+
type ParseRefusal = "malformed" | "server-derived-field";
|
|
183
|
+
|
|
184
|
+
function isParseRefusal(value: unknown): value is ParseRefusal {
|
|
185
|
+
return value === "malformed" || value === "server-derived-field";
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function closedKeys(body: Record<string, unknown>, allowed: ReadonlySet<string>): ParseRefusal | null {
|
|
105
189
|
const keys = Object.keys(body);
|
|
106
190
|
if (keys.some((key) => (SERVER_DERIVED_FIELDS as readonly string[]).includes(key))) return "server-derived-field";
|
|
107
|
-
if (keys.some((key) => !
|
|
191
|
+
if (keys.some((key) => !allowed.has(key))) return "malformed";
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function parseLocation(value: unknown): string | null {
|
|
196
|
+
const location = value ?? MIRROR_LOCATION_UNSPECIFIED;
|
|
197
|
+
return typeof location === "string" && ID.test(location) ? location : null;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function parseReason(value: unknown): MovementReason | null {
|
|
201
|
+
return typeof value === "string" && (MOVEMENT_REASONS as readonly string[]).includes(value) ? (value as MovementReason) : null;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The body in the closed schema, or the refusal code. */
|
|
205
|
+
export function parseInventoryDelta(body: unknown): AppInventoryDelta | ParseRefusal {
|
|
206
|
+
if (!isRecord(body)) return "malformed";
|
|
207
|
+
const refused = closedKeys(body, DELTA_KEYS);
|
|
208
|
+
if (refused) return refused;
|
|
108
209
|
const sku = parseSku(body.sku);
|
|
109
210
|
if (!sku.ok) return "malformed";
|
|
110
211
|
const delta = body.quantityDelta;
|
|
111
212
|
if (typeof delta !== "number" || !Number.isSafeInteger(delta) || delta === 0) return "malformed";
|
|
112
|
-
const location = body.locationId
|
|
113
|
-
if (
|
|
114
|
-
return { sku: sku.sku, locationId: location, quantityDelta: delta };
|
|
213
|
+
const location = parseLocation(body.locationId);
|
|
214
|
+
if (location === null) return "malformed";
|
|
215
|
+
if (body.reason === undefined) return { sku: sku.sku, locationId: location, quantityDelta: delta };
|
|
216
|
+
const reason = parseReason(body.reason);
|
|
217
|
+
if (reason === null) return "malformed";
|
|
218
|
+
return { sku: sku.sku, locationId: location, quantityDelta: delta, reason };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** True when the body is the batch form (`{ items: [...] }`) rather than one delta. */
|
|
222
|
+
export function isInventoryBatchBody(body: unknown): boolean {
|
|
223
|
+
return isRecord(body) && "items" in body;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function parseItems<T>(
|
|
227
|
+
body: unknown,
|
|
228
|
+
parseItem: (item: Record<string, unknown>) => T | ParseRefusal,
|
|
229
|
+
): { items: T[] } | { refused: ParseRefusal; index?: number } {
|
|
230
|
+
if (!isRecord(body)) return { refused: "malformed" };
|
|
231
|
+
const refused = closedKeys(body, new Set(["items"]));
|
|
232
|
+
if (refused) return { refused };
|
|
233
|
+
const raw = body.items;
|
|
234
|
+
if (!Array.isArray(raw) || raw.length < 1 || raw.length > INVENTORY_BATCH_MAX) return { refused: "malformed" };
|
|
235
|
+
const items: T[] = [];
|
|
236
|
+
for (const [index, entry] of raw.entries()) {
|
|
237
|
+
if (!isRecord(entry)) return { refused: "malformed", index };
|
|
238
|
+
const parsed = parseItem(entry);
|
|
239
|
+
if (isParseRefusal(parsed)) return { refused: parsed, index };
|
|
240
|
+
items.push(parsed);
|
|
241
|
+
}
|
|
242
|
+
return { items };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** A movements batch in the closed schema: 1..250 items, each with a WMS reason. */
|
|
246
|
+
export function parseInventoryMovements(body: unknown): { items: AppInventoryMovement[] } | { refused: ParseRefusal; index?: number } {
|
|
247
|
+
return parseItems(body, (entry) => {
|
|
248
|
+
const refused = closedKeys(entry, BATCH_MOVEMENT_KEYS);
|
|
249
|
+
if (refused) return refused;
|
|
250
|
+
const sku = parseSku(entry.sku);
|
|
251
|
+
const delta = entry.quantityDelta;
|
|
252
|
+
const location = parseLocation(entry.locationId);
|
|
253
|
+
const reason = parseReason(entry.reason);
|
|
254
|
+
if (!sku.ok || typeof delta !== "number" || !Number.isSafeInteger(delta) || delta === 0) return "malformed";
|
|
255
|
+
if (Math.abs(delta) > MIRROR_BALANCE_MAX || location === null || reason === null) return "malformed";
|
|
256
|
+
return { sku: sku.sku, locationId: location, quantityDelta: delta, reason };
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** A levels batch in the closed schema: 1..250 absolute on-hand readings, one per (sku, location). */
|
|
261
|
+
export function parseInventoryLevels(
|
|
262
|
+
body: unknown,
|
|
263
|
+
nowMs: number,
|
|
264
|
+
): { items: AppInventoryLevel[] } | { refused: ParseRefusal; index?: number } {
|
|
265
|
+
const parsed = parseItems<AppInventoryLevel>(body, (entry) => {
|
|
266
|
+
const refused = closedKeys(entry, LEVEL_KEYS);
|
|
267
|
+
if (refused) return refused;
|
|
268
|
+
const sku = parseSku(entry.sku);
|
|
269
|
+
const onHand = entry.onHand;
|
|
270
|
+
const location = parseLocation(entry.locationId);
|
|
271
|
+
const observedAt = entry.observedAt;
|
|
272
|
+
if (!sku.ok || location === null || typeof onHand !== "number" || !Number.isSafeInteger(onHand)) return "malformed";
|
|
273
|
+
if (onHand < 0 || onHand > MIRROR_BALANCE_MAX || typeof observedAt !== "string" || observedAt.length > 64) return "malformed";
|
|
274
|
+
const observedMs = Date.parse(observedAt);
|
|
275
|
+
if (!Number.isFinite(observedMs) || observedMs > nowMs + OBSERVED_AT_SKEW_MS) return "malformed";
|
|
276
|
+
return { sku: sku.sku, locationId: location, onHand, observedAt };
|
|
277
|
+
});
|
|
278
|
+
if (!("items" in parsed)) return parsed;
|
|
279
|
+
const seen = new Set<string>();
|
|
280
|
+
for (const [index, item] of parsed.items.entries()) {
|
|
281
|
+
const key = `${skuKey(item.sku)}\n${item.locationId}`;
|
|
282
|
+
if (seen.has(key)) return { refused: "malformed", index };
|
|
283
|
+
seen.add(key);
|
|
284
|
+
}
|
|
285
|
+
return parsed;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** A location declaration in the closed schema. */
|
|
289
|
+
export function parseInventoryLocation(body: unknown): AppInventoryLocationInput | ParseRefusal {
|
|
290
|
+
if (!isRecord(body)) return "malformed";
|
|
291
|
+
const refused = closedKeys(body, LOCATION_KEYS);
|
|
292
|
+
if (refused) return refused;
|
|
293
|
+
const { name, kind } = body;
|
|
294
|
+
const isFulfillable = body.isFulfillable ?? true;
|
|
295
|
+
const status = body.status ?? "active";
|
|
296
|
+
if (typeof name !== "string" || name.trim() === "" || name.length > NAME_MAX || /[\u0000-\u001f]/.test(name)) return "malformed";
|
|
297
|
+
if (typeof kind !== "string" || !(LOCATION_KINDS as readonly string[]).includes(kind)) return "malformed";
|
|
298
|
+
if (typeof isFulfillable !== "boolean") return "malformed";
|
|
299
|
+
if (typeof status !== "string" || !(LOCATION_STATUSES as readonly string[]).includes(status)) return "malformed";
|
|
300
|
+
return { name, kind: kind as LocationKind, isFulfillable, status: status as LocationStatus };
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export function isLocationId(value: unknown): value is string {
|
|
304
|
+
return typeof value === "string" && ID.test(value);
|
|
115
305
|
}
|
|
116
306
|
|
|
117
307
|
async function hex(text: string): Promise<string> {
|
|
@@ -142,13 +332,16 @@ export function installAdmissionCondition(actor: InventoryWriteActor): SqlCondit
|
|
|
142
332
|
};
|
|
143
333
|
}
|
|
144
334
|
|
|
145
|
-
function
|
|
335
|
+
function errorIncludes(error: unknown, text: string): boolean {
|
|
146
336
|
for (let cause: unknown = error, depth = 0; cause instanceof Error && depth < 4; depth++, cause = cause.cause) {
|
|
147
|
-
if (cause.message.includes(
|
|
337
|
+
if (cause.message.includes(text)) return true;
|
|
148
338
|
}
|
|
149
339
|
return false;
|
|
150
340
|
}
|
|
151
341
|
|
|
342
|
+
const lostRace = (error: unknown) => errorIncludes(error, "UNIQUE constraint failed");
|
|
343
|
+
const batchRefused = (error: unknown) => errorIncludes(error, BATCH_REFUSED_CONSTRAINT);
|
|
344
|
+
|
|
152
345
|
/** Runs the statements as one transaction and returns each one's changed-row count; a unique-key loss is all zeros. */
|
|
153
346
|
async function transact(db: Queryable, statements: readonly QueryStatement[]): Promise<number[]> {
|
|
154
347
|
if (!db.batchResults) throw new Error("transaction-results-required");
|
|
@@ -162,62 +355,96 @@ async function transact(db: Queryable, statements: readonly QueryStatement[]): P
|
|
|
162
355
|
return statements.map((_, index) => Number(results[index * 2 + 1]?.results[0]?.affected ?? 0));
|
|
163
356
|
}
|
|
164
357
|
|
|
165
|
-
function receiptFrom(recorded: unknown): InventoryWriteResponse | null {
|
|
358
|
+
function receiptFrom<T>(recorded: unknown): InventoryWriteResponse<T> | null {
|
|
166
359
|
if (!isRecord(recorded) || !Number.isSafeInteger(recorded.status) || !isRecord(recorded.body)) return null;
|
|
167
|
-
return { status: Number(recorded.status), body: recorded.body as unknown as
|
|
360
|
+
return { status: Number(recorded.status), body: recorded.body as unknown as T };
|
|
168
361
|
}
|
|
169
362
|
|
|
170
|
-
async function priorAnswer(db: Queryable, installId: string, key: string, bodyHash: string): Promise<InventoryWriteResponse | null> {
|
|
363
|
+
async function priorAnswer<T>(db: Queryable, installId: string, key: string, bodyHash: string): Promise<InventoryWriteResponse<T> | null> {
|
|
171
364
|
const check = await checkIdempotency(db, installId, key, bodyHash);
|
|
172
365
|
if (check.status === "proceed") return null;
|
|
173
366
|
if (check.status === "conflict") return inventoryRefusal("idempotency-conflict");
|
|
174
|
-
return receiptFrom(check.responseBody) ?? inventoryRefusal("idempotency-conflict");
|
|
367
|
+
return receiptFrom<T>(check.responseBody) ?? inventoryRefusal("idempotency-conflict");
|
|
175
368
|
}
|
|
176
369
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
locationId: answer.body.locationId,
|
|
191
|
-
balance: answer.body.balance,
|
|
192
|
-
asOf: answer.body.asOf,
|
|
193
|
-
});
|
|
370
|
+
/** The install's standing, read after a refused write: null when it may write. */
|
|
371
|
+
async function installRefusal(db: Queryable, actor: InventoryWriteActor): Promise<InventoryWriteResponse<never> | null> {
|
|
372
|
+
const install = await db.first<{ tenant_id: string; env: string; status: string; scopes: string }>(
|
|
373
|
+
`SELECT tenant_id, env, status, scopes FROM app_installs WHERE install_id = ?`,
|
|
374
|
+
actor.installId,
|
|
375
|
+
);
|
|
376
|
+
if (!install || install.tenant_id !== actor.tenantId || install.status !== "active") return inventoryRefusal("invalid_token");
|
|
377
|
+
if (install.env !== appInstallEnvForStage(actor.stage)) return inventoryRefusal("denied");
|
|
378
|
+
let scopes: unknown = null;
|
|
379
|
+
try {
|
|
380
|
+
scopes = JSON.parse(install.scopes);
|
|
381
|
+
} catch {
|
|
382
|
+
scopes = null;
|
|
194
383
|
}
|
|
195
|
-
return
|
|
384
|
+
if (!Array.isArray(scopes) || !scopes.includes(INVENTORY_WRITE_SCOPE)) return inventoryRefusal("scope_denied");
|
|
385
|
+
return null;
|
|
196
386
|
}
|
|
197
387
|
|
|
198
|
-
|
|
388
|
+
/** Common request shape for the ledger writes. */
|
|
389
|
+
interface LedgerWriteRequest {
|
|
199
390
|
actor: InventoryWriteActor;
|
|
200
391
|
idempotencyKey: string;
|
|
201
|
-
delta: AppInventoryDelta;
|
|
202
392
|
/** The tenant catalog's stored form of `sku`, or null when the catalog has no such sku. */
|
|
203
393
|
resolveSku: (sku: string) => Promise<string | null>;
|
|
204
394
|
now: () => string;
|
|
395
|
+
notify?: InventoryChangedNotify;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
export interface InventoryWriteRequest extends LedgerWriteRequest {
|
|
399
|
+
delta: AppInventoryDelta;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
export interface InventoryMovementsRequest extends LedgerWriteRequest {
|
|
403
|
+
items: readonly AppInventoryMovement[];
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
export interface InventoryLevelsRequest extends LedgerWriteRequest {
|
|
407
|
+
items: readonly AppInventoryLevel[];
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function preflight(request: LedgerWriteRequest): InventoryWriteResponse<never> | null {
|
|
411
|
+
if (!IDEMPOTENCY_KEY.test(request.idempotencyKey)) return inventoryRefusal("malformed");
|
|
412
|
+
if (!ID.test(request.actor.installId) || !request.actor.tenantId) return inventoryRefusal("invalid_token");
|
|
413
|
+
return null;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
async function receiptIdFor(actor: InventoryWriteActor, key: string): Promise<string> {
|
|
417
|
+
return `app.${(await hex(`${actor.installId}\n${key}`)).slice(0, 48)}`;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** Resolves every item's sku to the catalog's stored form, or names the first unknown item. */
|
|
421
|
+
async function resolveItems<T extends { sku: string }>(
|
|
422
|
+
items: readonly T[],
|
|
423
|
+
resolveSku: (sku: string) => Promise<string | null>,
|
|
424
|
+
): Promise<T[] | InventoryWriteResponse<never>> {
|
|
425
|
+
const resolved: T[] = [];
|
|
426
|
+
for (const [index, item] of items.entries()) {
|
|
427
|
+
const sku = await resolveSku(item.sku);
|
|
428
|
+
if (sku === null || !isStoredSku(sku)) return inventoryRefusal("unknown-sku", index);
|
|
429
|
+
resolved.push({ ...item, sku });
|
|
430
|
+
}
|
|
431
|
+
return resolved;
|
|
205
432
|
}
|
|
206
433
|
|
|
207
434
|
/** Applies one app delta; every answer is a receipt or a coded refusal. */
|
|
208
435
|
export async function applyAppInventoryDelta(db: Queryable, request: InventoryWriteRequest): Promise<InventoryWriteResponse> {
|
|
436
|
+
const refused = preflight(request);
|
|
437
|
+
if (refused) return refused;
|
|
209
438
|
const { actor, delta } = request;
|
|
210
|
-
if (!IDEMPOTENCY_KEY.test(request.idempotencyKey)) return inventoryRefusal("malformed");
|
|
211
|
-
if (!ID.test(actor.installId) || !actor.tenantId) return inventoryRefusal("invalid_token");
|
|
212
439
|
const key = namespacedKey(actor, request.idempotencyKey);
|
|
213
440
|
const bodyHash = await computeBodyHash({ operation: "inventory.write", ...delta });
|
|
214
|
-
const prior = await priorAnswer(db, actor.installId, key, bodyHash);
|
|
215
|
-
if (prior) return
|
|
441
|
+
const prior = await priorAnswer<InventoryReceipt>(db, actor.installId, key, bodyHash);
|
|
442
|
+
if (prior) return prior;
|
|
216
443
|
|
|
217
444
|
const sku = await request.resolveSku(delta.sku);
|
|
218
445
|
if (sku === null || !isStoredSku(sku)) return inventoryRefusal("unknown-sku");
|
|
219
446
|
const asOf = request.now();
|
|
220
|
-
const receiptId =
|
|
447
|
+
const receiptId = await receiptIdFor(actor, key);
|
|
221
448
|
const actorId = `app:${actor.installId}`;
|
|
222
449
|
const source = await appSource(actor.appId);
|
|
223
450
|
const movement = guardedCorrectionStatement(
|
|
@@ -231,10 +458,21 @@ export async function applyAppInventoryDelta(db: Queryable, request: InventoryWr
|
|
|
231
458
|
quantityDelta: delta.quantityDelta,
|
|
232
459
|
asOf,
|
|
233
460
|
actorId,
|
|
461
|
+
reason: delta.reason ?? null,
|
|
234
462
|
},
|
|
235
463
|
installAdmissionCondition(actor),
|
|
236
464
|
);
|
|
237
|
-
const detail = JSON.stringify({
|
|
465
|
+
const detail = JSON.stringify({
|
|
466
|
+
receiptId,
|
|
467
|
+
sku,
|
|
468
|
+
locationId: delta.locationId,
|
|
469
|
+
quantityDelta: delta.quantityDelta,
|
|
470
|
+
...(delta.reason ? { reason: delta.reason } : {}),
|
|
471
|
+
});
|
|
472
|
+
const committed: SqlCondition = {
|
|
473
|
+
sql: `EXISTS (SELECT 1 FROM commerce_inventory_movements WHERE tenant_id = ? AND stage = ? AND source = ? AND source_event_id = ?)`,
|
|
474
|
+
params: [actor.tenantId, actor.stage, source, receiptId],
|
|
475
|
+
};
|
|
238
476
|
const changes = await transact(db, [
|
|
239
477
|
{ sql: movement.sql, params: movement.params },
|
|
240
478
|
{
|
|
@@ -246,10 +484,7 @@ export async function applyAppInventoryDelta(db: Queryable, request: InventoryWr
|
|
|
246
484
|
sql: `INSERT INTO idempotency_keys (install_id, idempotency_key, body_hash, response_body, created_at)
|
|
247
485
|
SELECT ?, ?, ?, json_object('status', 201, 'body', json_object(
|
|
248
486
|
'receiptId', ?, 'sku', ?, 'locationId', ?, 'quantityDelta', CAST(? AS INTEGER), 'asOf', ?,
|
|
249
|
-
'balance',
|
|
250
|
-
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?), 0)
|
|
251
|
-
- COALESCE((SELECT SUM(quantity) FROM scrappy_allocations
|
|
252
|
-
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ? AND state = 'confirmed'), 0))), ?
|
|
487
|
+
'balance', ${locationBalanceSql("?", "?")})), ?
|
|
253
488
|
WHERE changes() = 1`,
|
|
254
489
|
params: [
|
|
255
490
|
actor.installId,
|
|
@@ -271,42 +506,352 @@ export async function applyAppInventoryDelta(db: Queryable, request: InventoryWr
|
|
|
271
506
|
asOf,
|
|
272
507
|
],
|
|
273
508
|
},
|
|
509
|
+
...movementEventStatements({ tenantId: actor.tenantId, stage: actor.stage, source, sourceEventId: receiptId, now: asOf }),
|
|
510
|
+
...availabilitySyncStatements({
|
|
511
|
+
tenantId: actor.tenantId,
|
|
512
|
+
stage: actor.stage,
|
|
513
|
+
now: asOf,
|
|
514
|
+
scope: itemScope([{ sku, locationId: delta.locationId }]),
|
|
515
|
+
emit: false,
|
|
516
|
+
token: availabilityToken(),
|
|
517
|
+
when: committed,
|
|
518
|
+
}),
|
|
274
519
|
]);
|
|
275
520
|
if ((changes[0] ?? 0) === 1 && (changes[2] ?? 0) === 1) {
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
521
|
+
await notifyInventoryDeliveries(sqlAll(db), {
|
|
522
|
+
tenantId: actor.tenantId,
|
|
523
|
+
idEquals: `inv.${receiptId}`,
|
|
524
|
+
idPrefix: `inv.${receiptId}.`,
|
|
525
|
+
notify: request.notify,
|
|
526
|
+
});
|
|
527
|
+
return (await priorAnswer<InventoryReceipt>(db, actor.installId, key, bodyHash)) ?? inventoryRefusal("unavailable");
|
|
279
528
|
}
|
|
280
|
-
|
|
529
|
+
const winner = await priorAnswer<InventoryReceipt>(db, actor.installId, key, bodyHash);
|
|
530
|
+
if (winner) return winner;
|
|
531
|
+
const install = await installRefusal(db, actor);
|
|
532
|
+
if (install) return install;
|
|
533
|
+
if (!(await mirrorLocationKnown(db, { tenantId: actor.tenantId, stage: actor.stage, locationId: delta.locationId }))) {
|
|
534
|
+
return inventoryRefusal("unknown-location");
|
|
535
|
+
}
|
|
536
|
+
return inventoryRefusal("balance-out-of-range");
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
function sqlAll(db: Queryable) {
|
|
540
|
+
return (sql: string, params: unknown[]) => db.all<Record<string, unknown>>(sql, ...params);
|
|
281
541
|
}
|
|
282
542
|
|
|
283
|
-
/**
|
|
284
|
-
|
|
543
|
+
/** Inserts into the guard table (aborting the transaction) when `violation` holds. */
|
|
544
|
+
function guardStatement(violation: SqlCondition): SqlStatement {
|
|
545
|
+
return {
|
|
546
|
+
sql: `INSERT INTO commerce_inventory_batch_guard (refused) SELECT 1 WHERE ${violation.sql}`,
|
|
547
|
+
params: [...violation.params],
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
const ITEMS = `(SELECT CAST(key AS INTEGER) AS idx, json_extract(value, '$.sku') AS sku,
|
|
552
|
+
json_extract(value, '$.locationId') AS location_id, value AS item FROM json_each(?))`;
|
|
553
|
+
|
|
554
|
+
/** Runs a batch transaction; a guard abort answers "refused", a same-key race answers "raced". */
|
|
555
|
+
async function runBatch(db: Queryable, statements: readonly SqlStatement[]): Promise<"committed" | "refused" | "raced"> {
|
|
556
|
+
if (!db.batch) throw new Error("transaction-required");
|
|
557
|
+
try {
|
|
558
|
+
await db.batch(statements);
|
|
559
|
+
return "committed";
|
|
560
|
+
} catch (error) {
|
|
561
|
+
if (batchRefused(error)) return "refused";
|
|
562
|
+
if (lostRace(error)) return "raced";
|
|
563
|
+
throw error;
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** Why a batch was refused, read after the rollback: the install, then the first unknown location, then the first out-of-range key. */
|
|
568
|
+
async function classifyBatchRefusal(
|
|
285
569
|
db: Queryable,
|
|
286
570
|
actor: InventoryWriteActor,
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
)
|
|
291
|
-
const
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
actor.installId,
|
|
296
|
-
);
|
|
297
|
-
if (!install || install.tenant_id !== actor.tenantId || install.status !== "active") return inventoryRefusal("invalid_token");
|
|
298
|
-
if (install.env !== appInstallEnvForStage(actor.stage)) return inventoryRefusal("denied");
|
|
299
|
-
let scopes: unknown = null;
|
|
300
|
-
try {
|
|
301
|
-
scopes = JSON.parse(install.scopes);
|
|
302
|
-
} catch {
|
|
303
|
-
scopes = null;
|
|
571
|
+
items: readonly { sku: string; locationId: string; quantityDelta?: number }[],
|
|
572
|
+
): Promise<InventoryWriteResponse<never>> {
|
|
573
|
+
const install = await installRefusal(db, actor);
|
|
574
|
+
if (install) return install;
|
|
575
|
+
for (const [index, item] of items.entries()) {
|
|
576
|
+
if (!(await mirrorLocationKnown(db, { tenantId: actor.tenantId, stage: actor.stage, locationId: item.locationId }))) {
|
|
577
|
+
return inventoryRefusal("unknown-location", index);
|
|
578
|
+
}
|
|
304
579
|
}
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
580
|
+
const nets = new Map<string, { index: number; net: number; sku: string; locationId: string }>();
|
|
581
|
+
for (const [index, item] of items.entries()) {
|
|
582
|
+
const key = `${item.sku}\n${item.locationId}`;
|
|
583
|
+
const entry = nets.get(key) ?? { index, net: 0, sku: item.sku, locationId: item.locationId };
|
|
584
|
+
entry.net += item.quantityDelta ?? 0;
|
|
585
|
+
nets.set(key, entry);
|
|
308
586
|
}
|
|
309
|
-
|
|
587
|
+
for (const entry of nets.values()) {
|
|
588
|
+
const row = await db.first<{ balance: number }>(
|
|
589
|
+
`SELECT ${locationBalanceSql("?", "?")} AS balance`,
|
|
590
|
+
actor.tenantId,
|
|
591
|
+
actor.stage,
|
|
592
|
+
entry.sku,
|
|
593
|
+
entry.locationId,
|
|
594
|
+
actor.tenantId,
|
|
595
|
+
actor.stage,
|
|
596
|
+
entry.sku,
|
|
597
|
+
entry.locationId,
|
|
598
|
+
);
|
|
599
|
+
const after = Number(row?.balance ?? 0) + entry.net;
|
|
600
|
+
if (after > MIRROR_BALANCE_MAX || (after < 0 && entry.net < 0)) return inventoryRefusal("balance-out-of-range", entry.index);
|
|
601
|
+
}
|
|
602
|
+
return inventoryRefusal("unavailable");
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/** Statements shared by both batch forms after the movement insert: events, deliveries, availability. */
|
|
606
|
+
function batchTail(actor: InventoryWriteActor, input: { source: string; receiptId: string; asOf: string; scope: { sku: string; locationId: string }[] }): SqlStatement[] {
|
|
607
|
+
return [
|
|
608
|
+
...movementEventStatements({
|
|
609
|
+
tenantId: actor.tenantId,
|
|
610
|
+
stage: actor.stage,
|
|
611
|
+
source: input.source,
|
|
612
|
+
sourceEventId: input.receiptId,
|
|
613
|
+
now: input.asOf,
|
|
614
|
+
}),
|
|
615
|
+
...availabilitySyncStatements({
|
|
616
|
+
tenantId: actor.tenantId,
|
|
617
|
+
stage: actor.stage,
|
|
618
|
+
now: input.asOf,
|
|
619
|
+
scope: itemScope(input.scope),
|
|
620
|
+
emit: false,
|
|
621
|
+
token: availabilityToken(),
|
|
622
|
+
}),
|
|
623
|
+
];
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
async function finishBatch<T>(
|
|
627
|
+
db: Queryable,
|
|
628
|
+
request: LedgerWriteRequest,
|
|
629
|
+
outcome: "committed" | "refused" | "raced",
|
|
630
|
+
ctx: { key: string; bodyHash: string; receiptId: string; items: readonly { sku: string; locationId: string; quantityDelta?: number }[] },
|
|
631
|
+
): Promise<InventoryWriteResponse<T>> {
|
|
632
|
+
const { actor } = request;
|
|
633
|
+
if (outcome === "committed") {
|
|
634
|
+
await notifyInventoryDeliveries(sqlAll(db), {
|
|
635
|
+
tenantId: actor.tenantId,
|
|
636
|
+
idEquals: `inv.${ctx.receiptId}`,
|
|
637
|
+
idPrefix: `inv.${ctx.receiptId}.`,
|
|
638
|
+
notify: request.notify,
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
const answer = await priorAnswer<T>(db, actor.installId, ctx.key, ctx.bodyHash);
|
|
642
|
+
if (answer) return answer;
|
|
643
|
+
if (outcome === "committed") return inventoryRefusal("unavailable");
|
|
644
|
+
return classifyBatchRefusal(db, actor, ctx.items);
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/** Applies a batch of WMS movements as one transaction: every item commits, or none does. */
|
|
648
|
+
export async function applyAppInventoryMovements(
|
|
649
|
+
db: Queryable,
|
|
650
|
+
request: InventoryMovementsRequest,
|
|
651
|
+
): Promise<InventoryWriteResponse<InventoryMovementsReceipt>> {
|
|
652
|
+
const refused = preflight(request);
|
|
653
|
+
if (refused) return refused;
|
|
654
|
+
const { actor } = request;
|
|
655
|
+
const key = namespacedKey(actor, request.idempotencyKey);
|
|
656
|
+
const bodyHash = await computeBodyHash({ operation: "inventory.movements", items: request.items });
|
|
657
|
+
const prior = await priorAnswer<InventoryMovementsReceipt>(db, actor.installId, key, bodyHash);
|
|
658
|
+
if (prior) return prior;
|
|
659
|
+
const items = await resolveItems(request.items, request.resolveSku);
|
|
660
|
+
if (!Array.isArray(items)) return items;
|
|
661
|
+
|
|
662
|
+
const asOf = request.now();
|
|
663
|
+
const receiptId = await receiptIdFor(actor, key);
|
|
664
|
+
const actorId = `app:${actor.installId}`;
|
|
665
|
+
const source = await appSource(actor.appId);
|
|
666
|
+
const itemsJson = JSON.stringify(items);
|
|
667
|
+
const t = actor.tenantId;
|
|
668
|
+
const s = actor.stage;
|
|
669
|
+
const admission = installAdmissionCondition(actor);
|
|
670
|
+
const violation: SqlCondition = {
|
|
671
|
+
sql: `(NOT ${admission.sql}
|
|
672
|
+
OR EXISTS (SELECT 1 FROM ${ITEMS} AS it WHERE NOT ${locationAdmittedSql("it.location_id")})
|
|
673
|
+
OR EXISTS (SELECT 1 FROM (
|
|
674
|
+
SELECT it.sku AS sku, it.location_id AS location_id, SUM(json_extract(it.item, '$.quantityDelta')) AS net
|
|
675
|
+
FROM ${ITEMS} AS it GROUP BY it.sku, it.location_id
|
|
676
|
+
) AS g
|
|
677
|
+
WHERE ${locationBalanceSql("g.sku", "g.location_id")} + g.net > ${MIRROR_BALANCE_MAX}
|
|
678
|
+
OR (${locationBalanceSql("g.sku", "g.location_id")} + g.net < 0 AND g.net < 0)))`,
|
|
679
|
+
params: [...admission.params, itemsJson, t, s, itemsJson, t, s, t, s, t, s, t, s],
|
|
680
|
+
};
|
|
681
|
+
const detail = JSON.stringify({ receiptId, items: items.length });
|
|
682
|
+
const outcome = await runBatch(db, [
|
|
683
|
+
guardStatement(violation),
|
|
684
|
+
{
|
|
685
|
+
sql: `INSERT INTO commerce_inventory_movements
|
|
686
|
+
(tenant_id, stage, source, source_event_id, sku, location_id, quantity_delta, as_of, actor_id, reason)
|
|
687
|
+
SELECT ?, ?, ?, ? || '.' || it.idx, it.sku, it.location_id, CAST(json_extract(it.item, '$.quantityDelta') AS INTEGER), ?, ?,
|
|
688
|
+
json_extract(it.item, '$.reason')
|
|
689
|
+
FROM ${ITEMS} AS it WHERE true
|
|
690
|
+
ON CONFLICT DO NOTHING`,
|
|
691
|
+
params: [t, s, source, receiptId, asOf, actorId, itemsJson],
|
|
692
|
+
},
|
|
693
|
+
{
|
|
694
|
+
sql: `INSERT INTO app_audit_log (id, install_id, tenant_id, event, actor, trace_id, detail, at)
|
|
695
|
+
VALUES (?, ?, ?, '${INVENTORY_BATCH_AUDIT_EVENT}', ?, NULL, ?, ?)`,
|
|
696
|
+
params: [crypto.randomUUID(), actor.installId, t, actorId, detail, asOf],
|
|
697
|
+
},
|
|
698
|
+
{
|
|
699
|
+
sql: `INSERT INTO idempotency_keys (install_id, idempotency_key, body_hash, response_body, created_at)
|
|
700
|
+
SELECT ?, ?, ?, json_object('status', 201, 'body', json_object('receiptId', ?, 'asOf', ?, 'items', json((
|
|
701
|
+
SELECT json_group_array(json(line)) FROM (
|
|
702
|
+
SELECT json_object('sku', it.sku, 'locationId', it.location_id,
|
|
703
|
+
'quantityDelta', CAST(json_extract(it.item, '$.quantityDelta') AS INTEGER),
|
|
704
|
+
'reason', json_extract(it.item, '$.reason'),
|
|
705
|
+
'balance', ${locationBalanceSql("it.sku", "it.location_id")}) AS line
|
|
706
|
+
FROM ${ITEMS} AS it ORDER BY it.idx))))), ?`,
|
|
707
|
+
params: [actor.installId, key, bodyHash, receiptId, asOf, t, s, t, s, itemsJson, asOf],
|
|
708
|
+
},
|
|
709
|
+
...batchTail(actor, { source, receiptId, asOf, scope: items }),
|
|
710
|
+
]);
|
|
711
|
+
return finishBatch<InventoryMovementsReceipt>(db, request, outcome, { key, bodyHash, receiptId, items });
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/**
|
|
715
|
+
* Reconciles a batch of absolute on-hand levels as one transaction. Each item writes the movement
|
|
716
|
+
* that makes its (sku, location) ledger equal `onHand` (reason `reconcile`); an item already at its
|
|
717
|
+
* level writes a zero movement, which refreshes freshness and emits no event.
|
|
718
|
+
*/
|
|
719
|
+
export async function applyAppInventoryLevels(
|
|
720
|
+
db: Queryable,
|
|
721
|
+
request: InventoryLevelsRequest,
|
|
722
|
+
): Promise<InventoryWriteResponse<InventoryLevelsReceipt>> {
|
|
723
|
+
const refused = preflight(request);
|
|
724
|
+
if (refused) return refused;
|
|
725
|
+
const { actor } = request;
|
|
726
|
+
const key = namespacedKey(actor, request.idempotencyKey);
|
|
727
|
+
const bodyHash = await computeBodyHash({ operation: "inventory.levels", items: request.items });
|
|
728
|
+
const prior = await priorAnswer<InventoryLevelsReceipt>(db, actor.installId, key, bodyHash);
|
|
729
|
+
if (prior) return prior;
|
|
730
|
+
const items = await resolveItems(request.items, request.resolveSku);
|
|
731
|
+
if (!Array.isArray(items)) return items;
|
|
732
|
+
const seen = new Set<string>();
|
|
733
|
+
for (const [index, item] of items.entries()) {
|
|
734
|
+
const pair = `${item.sku}\n${item.locationId}`;
|
|
735
|
+
if (seen.has(pair)) return inventoryRefusal("malformed", index);
|
|
736
|
+
seen.add(pair);
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
const asOf = request.now();
|
|
740
|
+
const receiptId = await receiptIdFor(actor, key);
|
|
741
|
+
const actorId = `app:${actor.installId}`;
|
|
742
|
+
const source = await appSource(actor.appId);
|
|
743
|
+
const itemsJson = JSON.stringify(items);
|
|
744
|
+
const t = actor.tenantId;
|
|
745
|
+
const s = actor.stage;
|
|
746
|
+
const admission = installAdmissionCondition(actor);
|
|
747
|
+
const violation: SqlCondition = {
|
|
748
|
+
sql: `(NOT ${admission.sql} OR EXISTS (SELECT 1 FROM ${ITEMS} AS it WHERE NOT ${locationAdmittedSql("it.location_id")}))`,
|
|
749
|
+
params: [...admission.params, itemsJson, t, s],
|
|
750
|
+
};
|
|
751
|
+
const detail = JSON.stringify({ receiptId, items: items.length });
|
|
752
|
+
const outcome = await runBatch(db, [
|
|
753
|
+
guardStatement(violation),
|
|
754
|
+
{
|
|
755
|
+
sql: `INSERT INTO commerce_inventory_movements
|
|
756
|
+
(tenant_id, stage, source, source_event_id, sku, location_id, quantity_delta, as_of, actor_id, reason)
|
|
757
|
+
SELECT ?, ?, ?, ? || '.' || it.idx, it.sku, it.location_id,
|
|
758
|
+
${onHandDeltaSql("json_extract(it.item, '$.onHand')", "it.sku", "it.location_id")}, ?, ?, '${RECONCILE_REASON}'
|
|
759
|
+
FROM ${ITEMS} AS it WHERE true
|
|
760
|
+
ON CONFLICT DO NOTHING`,
|
|
761
|
+
params: [t, s, source, receiptId, t, s, asOf, actorId, itemsJson],
|
|
762
|
+
},
|
|
763
|
+
{
|
|
764
|
+
sql: `INSERT INTO app_audit_log (id, install_id, tenant_id, event, actor, trace_id, detail, at)
|
|
765
|
+
VALUES (?, ?, ?, '${INVENTORY_LEVELS_AUDIT_EVENT}', ?, NULL, ?, ?)`,
|
|
766
|
+
params: [crypto.randomUUID(), actor.installId, t, actorId, detail, asOf],
|
|
767
|
+
},
|
|
768
|
+
{
|
|
769
|
+
sql: `INSERT INTO idempotency_keys (install_id, idempotency_key, body_hash, response_body, created_at)
|
|
770
|
+
SELECT ?, ?, ?, json_object('status', 200, 'body', json_object('receiptId', ?, 'asOf', ?, 'items', json((
|
|
771
|
+
SELECT json_group_array(json(line)) FROM (
|
|
772
|
+
SELECT json_object('sku', it.sku, 'locationId', it.location_id,
|
|
773
|
+
'onHand', CAST(json_extract(it.item, '$.onHand') AS INTEGER),
|
|
774
|
+
'observedAt', json_extract(it.item, '$.observedAt'),
|
|
775
|
+
'quantityDelta', (SELECT m.quantity_delta FROM commerce_inventory_movements AS m
|
|
776
|
+
WHERE m.tenant_id = ? AND m.stage = ? AND m.source = ? AND m.source_event_id = ? || '.' || it.idx),
|
|
777
|
+
'balance', ${locationBalanceSql("it.sku", "it.location_id")}) AS line
|
|
778
|
+
FROM ${ITEMS} AS it ORDER BY it.idx))))), ?`,
|
|
779
|
+
params: [actor.installId, key, bodyHash, receiptId, asOf, t, s, source, receiptId, t, s, t, s, itemsJson, asOf],
|
|
780
|
+
},
|
|
781
|
+
...batchTail(actor, { source, receiptId, asOf, scope: items }),
|
|
782
|
+
]);
|
|
783
|
+
return finishBatch<InventoryLevelsReceipt>(db, request, outcome, { key, bodyHash, receiptId, items });
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
export interface InventoryLocationRequest {
|
|
787
|
+
actor: InventoryWriteActor;
|
|
788
|
+
locationId: string;
|
|
789
|
+
location: AppInventoryLocationInput;
|
|
790
|
+
now: () => string;
|
|
791
|
+
notify?: InventoryChangedNotify;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/**
|
|
795
|
+
* Declares or updates one location. Archiving keeps its history and stops new writes to it;
|
|
796
|
+
* `unspecified` is never archived. Availability for every sku held at the location is
|
|
797
|
+
* recomputed in the same transaction, emitting `inventory.changed` where it moved.
|
|
798
|
+
*/
|
|
799
|
+
export async function upsertAppInventoryLocation(
|
|
800
|
+
db: Queryable,
|
|
801
|
+
request: InventoryLocationRequest,
|
|
802
|
+
): Promise<InventoryWriteResponse<InventoryLocation>> {
|
|
803
|
+
const { actor, locationId, location } = request;
|
|
804
|
+
if (!ID.test(actor.installId) || !actor.tenantId) return inventoryRefusal("invalid_token");
|
|
805
|
+
if (!ID.test(locationId)) return inventoryRefusal("malformed");
|
|
806
|
+
if (locationId === MIRROR_LOCATION_UNSPECIFIED && location.status !== "active") return inventoryRefusal("location-protected");
|
|
807
|
+
const now = request.now();
|
|
808
|
+
const admission = installAdmissionCondition(actor);
|
|
809
|
+
const actorId = `app:${actor.installId}`;
|
|
810
|
+
const token = availabilityToken();
|
|
811
|
+
const detail = JSON.stringify({ locationId, ...location });
|
|
812
|
+
const changes = await transact(db, [
|
|
813
|
+
{
|
|
814
|
+
sql: `INSERT INTO commerce_inventory_locations (tenant_id, stage, location_id, name, kind, is_fulfillable, status, updated_at)
|
|
815
|
+
SELECT ?, ?, ?, ?, ?, ?, ?, ? WHERE ${admission.sql}
|
|
816
|
+
ON CONFLICT (tenant_id, stage, location_id) DO UPDATE SET
|
|
817
|
+
name = excluded.name, kind = excluded.kind, is_fulfillable = excluded.is_fulfillable,
|
|
818
|
+
status = excluded.status, updated_at = excluded.updated_at`,
|
|
819
|
+
params: [
|
|
820
|
+
actor.tenantId,
|
|
821
|
+
actor.stage,
|
|
822
|
+
locationId,
|
|
823
|
+
location.name,
|
|
824
|
+
location.kind,
|
|
825
|
+
location.isFulfillable ? 1 : 0,
|
|
826
|
+
location.status,
|
|
827
|
+
now,
|
|
828
|
+
...admission.params,
|
|
829
|
+
],
|
|
830
|
+
},
|
|
831
|
+
{
|
|
832
|
+
sql: `INSERT INTO app_audit_log (id, install_id, tenant_id, event, actor, trace_id, detail, at)
|
|
833
|
+
SELECT ?, ?, ?, '${INVENTORY_LOCATION_AUDIT_EVENT}', ?, NULL, ?, ? WHERE changes() = 1`,
|
|
834
|
+
params: [crypto.randomUUID(), actor.installId, actor.tenantId, actorId, detail, now],
|
|
835
|
+
},
|
|
836
|
+
...availabilitySyncStatements({
|
|
837
|
+
tenantId: actor.tenantId,
|
|
838
|
+
stage: actor.stage,
|
|
839
|
+
now,
|
|
840
|
+
scope: locationScope({ tenantId: actor.tenantId, stage: actor.stage, locationId }),
|
|
841
|
+
emit: true,
|
|
842
|
+
token,
|
|
843
|
+
when: admission,
|
|
844
|
+
}),
|
|
845
|
+
]);
|
|
846
|
+
if ((changes[0] ?? 0) !== 1) return (await installRefusal(db, actor)) ?? inventoryRefusal("unavailable");
|
|
847
|
+
await notifyInventoryDeliveries(sqlAll(db), {
|
|
848
|
+
tenantId: actor.tenantId,
|
|
849
|
+
idEquals: "",
|
|
850
|
+
idPrefix: `${token}.`,
|
|
851
|
+
notify: request.notify,
|
|
852
|
+
});
|
|
853
|
+
const stored = await readInventoryLocation(db, { tenantId: actor.tenantId, stage: actor.stage, locationId });
|
|
854
|
+
return stored ? { status: 200, body: stored } : inventoryRefusal("unavailable");
|
|
310
855
|
}
|
|
311
856
|
|
|
312
857
|
/** Every stored sku of the catalog's variants: the skus an app may write for this tenant. */
|