@tokenoftrust/storefront-runner 6.12.2 → 6.12.3
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/0030_assignment_split_shipments.sql +103 -0
- package/apps/storefront/src/lib/access/auth/loginGate.ts +2 -0
- package/apps/storefront/src/lib/customers/contactVault/dataKeys.ts +28 -1
- package/apps/storefront/src/lib/fulfillment/admin/commerceDesk.ts +13 -0
- package/apps/storefront/src/lib/fulfillment/appShipmentEvidence.ts +6 -2
- package/apps/storefront/src/lib/fulfillment/assignmentStore.ts +136 -30
- package/apps/storefront/src/lib/fulfillment/fulfillmentService.ts +323 -9
- package/apps/storefront/src/lib/fulfillment/splitShipments.ts +388 -0
- package/apps/storefront/src/lib/integrations/webhooks/commercePayloads.ts +9 -5
- package/apps/storefront/src/lib/integrations/webhooks/deliveryStore.ts +1 -0
- package/apps/storefront/src/lib/integrations/webhooks/events.ts +1 -0
- package/apps/storefront/src/lib/orders/vault/orderContactVault.ts +25 -14
- package/package.json +1 -1
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Assignment-keyed shipments and exceptions: the closed request schemas a processor posts against
|
|
3
|
+
* one assignment, the per-line quantity ledger (assigned, shipped, cancelled), and the statements a
|
|
4
|
+
* shipment or exception writes. Every statement here is gated on the order having committed at the
|
|
5
|
+
* new event version in the same batch, so the order's compare-and-set serializes every write to
|
|
6
|
+
* the assignment and its lines.
|
|
7
|
+
*/
|
|
8
|
+
import type { CommerceStage } from "@tot/public-runtime";
|
|
9
|
+
import type { FulfillmentDatabase, SqlStatement } from "./store.js";
|
|
10
|
+
import {
|
|
11
|
+
CARRIER_CODES,
|
|
12
|
+
CARRIER_SERVICE,
|
|
13
|
+
TRACKING_NUMBER,
|
|
14
|
+
carrierProhibited,
|
|
15
|
+
parseCarrierCode,
|
|
16
|
+
trackingUrlAllowed,
|
|
17
|
+
type CarrierCode,
|
|
18
|
+
} from "./carrierEvidence.js";
|
|
19
|
+
|
|
20
|
+
export const EXCEPTION_CODES = [
|
|
21
|
+
"vendor_rejected",
|
|
22
|
+
"backordered",
|
|
23
|
+
"out_of_stock",
|
|
24
|
+
"damaged",
|
|
25
|
+
"address_undeliverable",
|
|
26
|
+
"carrier_refused",
|
|
27
|
+
"other",
|
|
28
|
+
] as const;
|
|
29
|
+
export type ExceptionCode = (typeof EXCEPTION_CODES)[number];
|
|
30
|
+
|
|
31
|
+
export interface ShipmentLine {
|
|
32
|
+
sku: string;
|
|
33
|
+
quantity: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface AssignmentShipmentEvidence {
|
|
37
|
+
kind: "shipment";
|
|
38
|
+
assignmentId: string;
|
|
39
|
+
lines: ShipmentLine[];
|
|
40
|
+
/** The carrier code as posted; plan time refuses one outside the allowed set. */
|
|
41
|
+
carrier: string;
|
|
42
|
+
service?: string;
|
|
43
|
+
trackingNumber: string;
|
|
44
|
+
trackingUrl?: string;
|
|
45
|
+
adultSignature: "accepted" | "refused" | "absent";
|
|
46
|
+
expectedVersion?: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface AssignmentExceptionEvidence {
|
|
50
|
+
kind: "exception";
|
|
51
|
+
assignmentId: string;
|
|
52
|
+
lines: ShipmentLine[];
|
|
53
|
+
code: ExceptionCode;
|
|
54
|
+
note?: string;
|
|
55
|
+
expectedVersion?: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface AssignmentShipmentView {
|
|
59
|
+
assignmentId: string;
|
|
60
|
+
shipmentId: string;
|
|
61
|
+
fulfilledLines: ShipmentLine[];
|
|
62
|
+
complete: boolean;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface AssignmentExceptionView {
|
|
66
|
+
assignmentId: string;
|
|
67
|
+
exceptionId: string;
|
|
68
|
+
code: ExceptionCode;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** One assignment line as stored. */
|
|
72
|
+
export interface AssignmentLineState {
|
|
73
|
+
lineId: string;
|
|
74
|
+
sku: string;
|
|
75
|
+
locationId: string;
|
|
76
|
+
assigned: number;
|
|
77
|
+
shipped: number;
|
|
78
|
+
cancelled: number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** An open exception as the operator desk reads it. */
|
|
82
|
+
export interface AssignmentExceptionRecord {
|
|
83
|
+
exceptionId: string;
|
|
84
|
+
assignmentId: string;
|
|
85
|
+
code: ExceptionCode;
|
|
86
|
+
lines: ShipmentLine[];
|
|
87
|
+
note: string | null;
|
|
88
|
+
createdAt: string;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const SHIPMENT_KEYS = new Set(["lines", "carrier", "service", "trackingNumber", "trackingUrl", "adultSignature"]);
|
|
92
|
+
const EXCEPTION_KEYS = new Set(["lines", "code", "note"]);
|
|
93
|
+
const LINE_KEYS = new Set(["sku", "quantity"]);
|
|
94
|
+
const CARRIER_PATTERN = /^[A-Z0-9_]{2,40}$/;
|
|
95
|
+
const SKU_MAX = 256;
|
|
96
|
+
const LINES_MAX = 500;
|
|
97
|
+
const NOTE_MAX = 500;
|
|
98
|
+
/** A note is free text, never contact data: no address sign and no run of seven or more digits. */
|
|
99
|
+
const NOTE_CONTACT = /@|\d[\d\s().-]{5,}\d/;
|
|
100
|
+
|
|
101
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
102
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The request lines: one entry per sku, each quantity a positive safe integer. Null when malformed. */
|
|
106
|
+
function parseLines(value: unknown): ShipmentLine[] | null {
|
|
107
|
+
if (!Array.isArray(value) || value.length === 0 || value.length > LINES_MAX) return null;
|
|
108
|
+
const seen = new Set<string>();
|
|
109
|
+
const lines: ShipmentLine[] = [];
|
|
110
|
+
for (const item of value) {
|
|
111
|
+
if (!isRecord(item) || Object.keys(item).some((key) => !LINE_KEYS.has(key))) return null;
|
|
112
|
+
const { sku, quantity } = item;
|
|
113
|
+
if (typeof sku !== "string" || sku.length === 0 || sku.length > SKU_MAX || sku.trim() !== sku) return null;
|
|
114
|
+
if (!Number.isSafeInteger(quantity) || Number(quantity) < 1) return null;
|
|
115
|
+
if (seen.has(sku)) return null;
|
|
116
|
+
seen.add(sku);
|
|
117
|
+
lines.push({ sku, quantity: Number(quantity) });
|
|
118
|
+
}
|
|
119
|
+
return lines;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function closedKeys(body: Record<string, unknown>, allowed: ReadonlySet<string>): boolean {
|
|
123
|
+
return Object.keys(body).every((key) => allowed.has(key)) && Object.values(body).every((value) => value !== null);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** `AssignmentShipmentWrite` in its closed schema, or null (400 malformed). */
|
|
127
|
+
export function parseAssignmentShipment(assignmentId: string, body: unknown): AssignmentShipmentEvidence | null {
|
|
128
|
+
if (!isRecord(body) || !closedKeys(body, SHIPMENT_KEYS)) return null;
|
|
129
|
+
const lines = parseLines(body.lines);
|
|
130
|
+
if (!lines) return null;
|
|
131
|
+
if (typeof body.carrier !== "string" || !CARRIER_PATTERN.test(body.carrier)) return null;
|
|
132
|
+
if (typeof body.trackingNumber !== "string" || !TRACKING_NUMBER.test(body.trackingNumber)) return null;
|
|
133
|
+
if (body.service !== undefined && (typeof body.service !== "string" || !CARRIER_SERVICE.test(body.service))) return null;
|
|
134
|
+
const known = parseCarrierCode(body.carrier);
|
|
135
|
+
if (body.trackingUrl !== undefined && (known === null || !trackingUrlAllowed(known, body.trackingUrl))) return null;
|
|
136
|
+
const adult = body.adultSignature ?? "absent";
|
|
137
|
+
if (adult !== "accepted" && adult !== "refused" && adult !== "absent") return null;
|
|
138
|
+
return {
|
|
139
|
+
kind: "shipment",
|
|
140
|
+
assignmentId,
|
|
141
|
+
lines,
|
|
142
|
+
carrier: body.carrier,
|
|
143
|
+
trackingNumber: body.trackingNumber,
|
|
144
|
+
adultSignature: adult,
|
|
145
|
+
...(typeof body.service === "string" ? { service: body.service } : {}),
|
|
146
|
+
...(typeof body.trackingUrl === "string" ? { trackingUrl: body.trackingUrl } : {}),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** `AssignmentExceptionWrite` in its closed schema, or null (400 malformed). */
|
|
151
|
+
export function parseAssignmentException(assignmentId: string, body: unknown): AssignmentExceptionEvidence | null {
|
|
152
|
+
if (!isRecord(body) || !closedKeys(body, EXCEPTION_KEYS)) return null;
|
|
153
|
+
const lines = parseLines(body.lines);
|
|
154
|
+
if (!lines) return null;
|
|
155
|
+
if (typeof body.code !== "string" || !(EXCEPTION_CODES as readonly string[]).includes(body.code)) return null;
|
|
156
|
+
if (body.note !== undefined) {
|
|
157
|
+
if (typeof body.note !== "string" || body.note.length === 0 || body.note.length > NOTE_MAX) return null;
|
|
158
|
+
if (NOTE_CONTACT.test(body.note) || /[\u0000-\u001f\u007f]/.test(body.note)) return null;
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
kind: "exception",
|
|
162
|
+
assignmentId,
|
|
163
|
+
lines,
|
|
164
|
+
code: body.code as ExceptionCode,
|
|
165
|
+
...(typeof body.note === "string" ? { note: body.note } : {}),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The carriers an order may ship with: the closed set minus the policy's and the order's prohibited carriers. */
|
|
170
|
+
export function allowedCarriers(policyProhibited: readonly string[], snapshotProhibited: readonly string[]): CarrierCode[] {
|
|
171
|
+
return CARRIER_CODES.filter((code) => !carrierProhibited(code, policyProhibited, snapshotProhibited));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Why `carrier` may not carry this order, or null. */
|
|
175
|
+
export function shipmentCarrierRefusal(
|
|
176
|
+
carrier: string,
|
|
177
|
+
policyProhibited: readonly string[],
|
|
178
|
+
snapshotProhibited: readonly string[],
|
|
179
|
+
): "carrier-prohibited" | "carrier-unsupported" | null {
|
|
180
|
+
if (carrierProhibited(carrier, policyProhibited, snapshotProhibited)) return "carrier-prohibited";
|
|
181
|
+
return parseCarrierCode(carrier) === null ? "carrier-unsupported" : null;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function remainingQuantity(line: AssignmentLineState): number {
|
|
185
|
+
return line.assigned - line.shipped - line.cancelled;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Why `requested` cannot be taken from `lines`, or null: an unknown sku, or more than a line's remainder. */
|
|
189
|
+
export function lineRefusal(
|
|
190
|
+
lines: readonly AssignmentLineState[],
|
|
191
|
+
requested: readonly ShipmentLine[],
|
|
192
|
+
): "line-unknown" | "quantity-exceeded" | null {
|
|
193
|
+
for (const want of requested) {
|
|
194
|
+
const line = lines.find((item) => item.sku === want.sku);
|
|
195
|
+
if (!line) return "line-unknown";
|
|
196
|
+
if (want.quantity > remainingQuantity(line)) return "quantity-exceeded";
|
|
197
|
+
}
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** True when shipping `requested` leaves every line with nothing remaining. */
|
|
202
|
+
export function completesLines(lines: readonly AssignmentLineState[], requested: readonly ShipmentLine[]): boolean {
|
|
203
|
+
return lines.every((line) => remainingQuantity(line) - (requested.find((item) => item.sku === line.sku)?.quantity ?? 0) === 0);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Each line's whole remainder, the shipment a whole-order handoff records. Lines with none are omitted. */
|
|
207
|
+
export function remainingLines(lines: readonly AssignmentLineState[]): ShipmentLine[] {
|
|
208
|
+
return lines.filter((line) => remainingQuantity(line) > 0).map((line) => ({ sku: line.sku, quantity: remainingQuantity(line) }));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** The assignment's stored lines in line order. */
|
|
212
|
+
export async function readAssignmentLines(db: Pick<FulfillmentDatabase, "all">, assignmentId: string): Promise<AssignmentLineState[]> {
|
|
213
|
+
const rows = await db.all<{
|
|
214
|
+
line_id: string;
|
|
215
|
+
sku: string;
|
|
216
|
+
location_id: string;
|
|
217
|
+
quantity_assigned: number;
|
|
218
|
+
quantity_shipped: number;
|
|
219
|
+
quantity_cancelled: number;
|
|
220
|
+
}>(
|
|
221
|
+
`SELECT line_id, sku, location_id, quantity_assigned, quantity_shipped, quantity_cancelled
|
|
222
|
+
FROM fulfillment_assignment_lines WHERE assignment_id = ?
|
|
223
|
+
ORDER BY CAST(line_id AS INTEGER) ASC, line_id ASC`,
|
|
224
|
+
[assignmentId],
|
|
225
|
+
);
|
|
226
|
+
return rows.map((row) => ({
|
|
227
|
+
lineId: row.line_id,
|
|
228
|
+
sku: row.sku,
|
|
229
|
+
locationId: row.location_id,
|
|
230
|
+
assigned: Number(row.quantity_assigned),
|
|
231
|
+
shipped: Number(row.quantity_shipped),
|
|
232
|
+
cancelled: Number(row.quantity_cancelled),
|
|
233
|
+
}));
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** SQL condition: the order committed at `version` in this batch. */
|
|
237
|
+
export function orderCommittedAt(scope: { tenantId: string; stage: CommerceStage; orderId: string }, version: number): SqlStatement {
|
|
238
|
+
return {
|
|
239
|
+
sql: `EXISTS (
|
|
240
|
+
SELECT 1 FROM scrappy_commerce_orders
|
|
241
|
+
WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
|
|
242
|
+
)`,
|
|
243
|
+
params: [scope.tenantId, scope.stage, scope.orderId, version],
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Adds `requested` to each line's shipped quantity, from the quantity read at the planned version.
|
|
249
|
+
* The table's CHECK aborts the batch if shipped plus cancelled would exceed assigned.
|
|
250
|
+
*/
|
|
251
|
+
export function consumeLinesStatements(
|
|
252
|
+
assignmentId: string,
|
|
253
|
+
lines: readonly AssignmentLineState[],
|
|
254
|
+
requested: readonly ShipmentLine[],
|
|
255
|
+
gate: SqlStatement,
|
|
256
|
+
): SqlStatement[] {
|
|
257
|
+
return requested.map((want) => {
|
|
258
|
+
const line = lines.find((item) => item.sku === want.sku)!;
|
|
259
|
+
return {
|
|
260
|
+
sql: `UPDATE fulfillment_assignment_lines SET quantity_shipped = quantity_shipped + ?
|
|
261
|
+
WHERE assignment_id = ? AND line_id = ? AND quantity_shipped = ? AND quantity_cancelled = ? AND ${gate.sql}`,
|
|
262
|
+
params: [want.quantity, assignmentId, line.lineId, line.shipped, line.cancelled, ...gate.params],
|
|
263
|
+
};
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export function insertShipmentStatement(
|
|
268
|
+
input: {
|
|
269
|
+
shipmentId: string;
|
|
270
|
+
assignmentId: string;
|
|
271
|
+
tenantId: string;
|
|
272
|
+
stage: CommerceStage;
|
|
273
|
+
orderId: string;
|
|
274
|
+
installId: string;
|
|
275
|
+
carrier: string;
|
|
276
|
+
service: string | null;
|
|
277
|
+
trackingNumber: string;
|
|
278
|
+
trackingUrl: string | null;
|
|
279
|
+
adultSignature: "accepted" | "refused" | "absent";
|
|
280
|
+
lines: readonly ShipmentLine[];
|
|
281
|
+
now: string;
|
|
282
|
+
},
|
|
283
|
+
gate: SqlStatement,
|
|
284
|
+
): SqlStatement {
|
|
285
|
+
return {
|
|
286
|
+
sql: `INSERT INTO fulfillment_shipments (
|
|
287
|
+
shipment_id, assignment_id, tenant_id, stage, order_id, install_id, carrier, service,
|
|
288
|
+
tracking_number, tracking_url, adult_signature, shipped_items, created_at
|
|
289
|
+
) SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE ${gate.sql}`,
|
|
290
|
+
params: [
|
|
291
|
+
input.shipmentId,
|
|
292
|
+
input.assignmentId,
|
|
293
|
+
input.tenantId,
|
|
294
|
+
input.stage,
|
|
295
|
+
input.orderId,
|
|
296
|
+
input.installId,
|
|
297
|
+
input.carrier,
|
|
298
|
+
input.service,
|
|
299
|
+
input.trackingNumber,
|
|
300
|
+
input.trackingUrl,
|
|
301
|
+
input.adultSignature,
|
|
302
|
+
JSON.stringify(input.lines.map((line) => ({ sku: line.sku, quantity: line.quantity }))),
|
|
303
|
+
input.now,
|
|
304
|
+
...gate.params,
|
|
305
|
+
],
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Event gate: the shipment row exists — the shipment it reports committed. */
|
|
310
|
+
export function shipmentCommittedGate(shipmentId: string): SqlStatement {
|
|
311
|
+
return { sql: `EXISTS (SELECT 1 FROM fulfillment_shipments WHERE shipment_id = ?)`, params: [shipmentId] };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export function insertExceptionStatement(
|
|
315
|
+
input: {
|
|
316
|
+
exceptionId: string;
|
|
317
|
+
assignmentId: string;
|
|
318
|
+
tenantId: string;
|
|
319
|
+
stage: CommerceStage;
|
|
320
|
+
orderId: string;
|
|
321
|
+
installId: string;
|
|
322
|
+
code: ExceptionCode;
|
|
323
|
+
lines: readonly ShipmentLine[];
|
|
324
|
+
note: string | null;
|
|
325
|
+
now: string;
|
|
326
|
+
},
|
|
327
|
+
gate: SqlStatement,
|
|
328
|
+
): SqlStatement {
|
|
329
|
+
return {
|
|
330
|
+
sql: `INSERT INTO fulfillment_assignment_exceptions (
|
|
331
|
+
exception_id, assignment_id, tenant_id, stage, order_id, install_id, code, lines, note, state, created_at
|
|
332
|
+
) SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ? WHERE ${gate.sql}`,
|
|
333
|
+
params: [
|
|
334
|
+
input.exceptionId,
|
|
335
|
+
input.assignmentId,
|
|
336
|
+
input.tenantId,
|
|
337
|
+
input.stage,
|
|
338
|
+
input.orderId,
|
|
339
|
+
input.installId,
|
|
340
|
+
input.code,
|
|
341
|
+
JSON.stringify(input.lines.map((line) => ({ sku: line.sku, quantity: line.quantity }))),
|
|
342
|
+
input.note,
|
|
343
|
+
input.now,
|
|
344
|
+
...gate.params,
|
|
345
|
+
],
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** The order's open exceptions, oldest first. Rows whose stored shape fails validation are skipped. */
|
|
350
|
+
export async function readOpenExceptions(
|
|
351
|
+
db: Pick<FulfillmentDatabase, "all">,
|
|
352
|
+
scope: { tenantId: string; stage: CommerceStage; orderId: string },
|
|
353
|
+
): Promise<AssignmentExceptionRecord[]> {
|
|
354
|
+
const rows = await db.all<{
|
|
355
|
+
exception_id: string;
|
|
356
|
+
assignment_id: string;
|
|
357
|
+
code: string;
|
|
358
|
+
lines: string;
|
|
359
|
+
note: string | null;
|
|
360
|
+
created_at: string;
|
|
361
|
+
}>(
|
|
362
|
+
`SELECT exception_id, assignment_id, code, lines, note, created_at FROM fulfillment_assignment_exceptions
|
|
363
|
+
WHERE tenant_id = ? AND stage = ? AND order_id = ? AND state = 'open'
|
|
364
|
+
ORDER BY created_at ASC, exception_id ASC`,
|
|
365
|
+
[scope.tenantId, scope.stage, scope.orderId],
|
|
366
|
+
);
|
|
367
|
+
const records: AssignmentExceptionRecord[] = [];
|
|
368
|
+
for (const row of rows) {
|
|
369
|
+
if (!(EXCEPTION_CODES as readonly string[]).includes(row.code)) continue;
|
|
370
|
+
let parsed: unknown;
|
|
371
|
+
try {
|
|
372
|
+
parsed = JSON.parse(row.lines);
|
|
373
|
+
} catch {
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
const lines = parseLines(parsed);
|
|
377
|
+
if (!lines) continue;
|
|
378
|
+
records.push({
|
|
379
|
+
exceptionId: row.exception_id,
|
|
380
|
+
assignmentId: row.assignment_id,
|
|
381
|
+
code: row.code as ExceptionCode,
|
|
382
|
+
lines,
|
|
383
|
+
note: typeof row.note === "string" ? row.note : null,
|
|
384
|
+
createdAt: row.created_at,
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
return records;
|
|
388
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Payload admission for the commerce topics the single commerce emitter writes:
|
|
3
|
-
* `fulfillment.assignment.created`, `fulfillment.assignment.updated`, `order.fulfilled
|
|
4
|
-
* and `inventory.changed`.
|
|
3
|
+
* `fulfillment.assignment.created`, `fulfillment.assignment.updated`, `order.fulfilled`,
|
|
4
|
+
* `order.partially_fulfilled` and `inventory.changed`.
|
|
5
5
|
*
|
|
6
6
|
* Each topic has a closed key set (`asyncapi.yaml` `FulfillmentAssignmentData`, `OrderData`
|
|
7
7
|
* and `InventoryChangedData`) and every payload also passes the private-identity check. Both
|
|
@@ -13,12 +13,14 @@ export type CommerceTopic =
|
|
|
13
13
|
| "fulfillment.assignment.created"
|
|
14
14
|
| "fulfillment.assignment.updated"
|
|
15
15
|
| "order.fulfilled"
|
|
16
|
+
| "order.partially_fulfilled"
|
|
16
17
|
| "inventory.changed";
|
|
17
18
|
|
|
18
19
|
export const COMMERCE_TOPICS: readonly CommerceTopic[] = [
|
|
19
20
|
"fulfillment.assignment.created",
|
|
20
21
|
"fulfillment.assignment.updated",
|
|
21
22
|
"order.fulfilled",
|
|
23
|
+
"order.partially_fulfilled",
|
|
22
24
|
"inventory.changed",
|
|
23
25
|
];
|
|
24
26
|
|
|
@@ -82,9 +84,10 @@ function assignmentAdmissible(topic: CommerceTopic, payload: Record<string, unkn
|
|
|
82
84
|
return typeof payload.occurredAt === "string" && Number.isFinite(Date.parse(payload.occurredAt));
|
|
83
85
|
}
|
|
84
86
|
|
|
85
|
-
|
|
87
|
+
/** `OrderData` with `status` exactly `status`: `fulfilled` for order.fulfilled, `created` while lines remain unshipped. */
|
|
88
|
+
function orderDataAdmissible(payload: Record<string, unknown>, status: "fulfilled" | "created"): boolean {
|
|
86
89
|
if (Object.keys(payload).some((key) => !ORDER_DATA_KEYS.has(key))) return false;
|
|
87
|
-
if (!nonEmptyString(payload.id) || payload.status !==
|
|
90
|
+
if (!nonEmptyString(payload.id) || payload.status !== status || !nonEmptyString(payload.currency)) return false;
|
|
88
91
|
if (payload.customerHash !== undefined && typeof payload.customerHash !== "string") return false;
|
|
89
92
|
for (const key of ["subtotal", "total"] as const) {
|
|
90
93
|
if (payload[key] !== undefined && (typeof payload[key] !== "number" || !Number.isFinite(payload[key]))) return false;
|
|
@@ -117,7 +120,8 @@ export function inventoryChangedAdmissible(payload: unknown): boolean {
|
|
|
117
120
|
/** True when `payload` is exactly the closed shape `topic` allows and carries no private identity. */
|
|
118
121
|
export function commercePayloadAdmissible(topic: CommerceTopic, payload: unknown): boolean {
|
|
119
122
|
if (!isRecord(payload) || commercePayloadHasPrivateIdentity(payload)) return false;
|
|
120
|
-
if (topic === "order.fulfilled") return
|
|
123
|
+
if (topic === "order.fulfilled") return orderDataAdmissible(payload, "fulfilled");
|
|
124
|
+
if (topic === "order.partially_fulfilled") return orderDataAdmissible(payload, "created");
|
|
121
125
|
if (topic === "inventory.changed") return inventoryChangedAdmissible(payload);
|
|
122
126
|
return assignmentAdmissible(topic, payload);
|
|
123
127
|
}
|
|
@@ -27,6 +27,7 @@ export const TOPIC_REQUIRED_SCOPE: Record<WebhookTopic, string | null> = {
|
|
|
27
27
|
"inventory.changed": "inventory:read",
|
|
28
28
|
"order.created": "orders:webhook",
|
|
29
29
|
"order.fulfilled": "orders:webhook",
|
|
30
|
+
"order.partially_fulfilled": "orders:webhook",
|
|
30
31
|
"customer.marketing_consent.updated": "customers:read:minimal",
|
|
31
32
|
"attribution.finalized": "attribution:write",
|
|
32
33
|
"fulfillment.assignment.created": "fulfillment:process",
|
|
@@ -27,6 +27,7 @@ import {
|
|
|
27
27
|
cleanupStatement,
|
|
28
28
|
deleteUnreferencedRetiredKeys,
|
|
29
29
|
keyForKid,
|
|
30
|
+
keyRowRestore,
|
|
30
31
|
rotateDueKeys,
|
|
31
32
|
type ActiveDataKey,
|
|
32
33
|
} from "@/lib/customers/contactVault/dataKeys.js";
|
|
@@ -352,10 +353,7 @@ export interface SealInput {
|
|
|
352
353
|
regulated: boolean;
|
|
353
354
|
now: Date;
|
|
354
355
|
policy?: RetentionPolicy;
|
|
355
|
-
/**
|
|
356
|
-
* Key material from {@link prepareOrderContactKeys}. The first attempt seals under it without
|
|
357
|
-
* reading the active key; a retry after a concurrent change reads the active key afresh.
|
|
358
|
-
*/
|
|
356
|
+
/** Key material from {@link prepareOrderContactKeys}; every attempt seals under it without reading the active key. */
|
|
359
357
|
keys?: PreparedOrderContactKeys;
|
|
360
358
|
}
|
|
361
359
|
|
|
@@ -404,6 +402,8 @@ function placedMonth(placedAt: Date): string {
|
|
|
404
402
|
export interface PreparedOrderContactKeys {
|
|
405
403
|
readonly order: ActiveDataKey;
|
|
406
404
|
readonly bidx: ActiveDataKey;
|
|
405
|
+
/** Puts each key's row back, retired, if rotation swept it before the seal; first in the seal batch. */
|
|
406
|
+
readonly restore: readonly QueryStatement[];
|
|
407
407
|
}
|
|
408
408
|
|
|
409
409
|
/**
|
|
@@ -411,8 +411,9 @@ export interface PreparedOrderContactKeys {
|
|
|
411
411
|
* refuse before its own writes when the vault cannot seal. Returns null when a key cannot be opened or
|
|
412
412
|
* generated, leaving no key row of its own behind. Otherwise any newly generated key is stored (the
|
|
413
413
|
* insert yields to an active key another writer stored first, which is opened instead) and the
|
|
414
|
-
* returned material goes to {@link sealOrderContact} as `keys`:
|
|
415
|
-
* active key or calling KMS
|
|
414
|
+
* returned material goes to {@link sealOrderContact} as `keys`: every seal attempt uses it without
|
|
415
|
+
* reading the active key or calling KMS, and its batch first restores a key row rotation retired and
|
|
416
|
+
* swept in between, so neither a KMS outage nor a rotation after the caller's writes stops the seal.
|
|
416
417
|
*/
|
|
417
418
|
export async function prepareOrderContactKeys(
|
|
418
419
|
db: Queryable, kms: KmsClient, tenantId: string, stage: VaultStage, now: Date,
|
|
@@ -429,15 +430,24 @@ export async function prepareOrderContactKeys(
|
|
|
429
430
|
throw error;
|
|
430
431
|
}
|
|
431
432
|
const generated = ([[orderCtx, order], [bidxCtx, bidx]] as const).filter(([, key]) => key.pending.length > 0);
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
try {
|
|
435
|
-
return { order: await storedKey(db, kms, orderCtx, order, now), bidx: await storedKey(db, kms, bidxCtx, bidx, now) };
|
|
436
|
-
} catch (error) {
|
|
437
|
-
if (!(error instanceof VaultKeyUnavailableError)) throw error;
|
|
438
|
-
await requireBatch(db)(generated.map(([ctx, key]) => unreferencedKeyCleanup(ctx, key.kid)));
|
|
433
|
+
const refuse = async (): Promise<null> => {
|
|
434
|
+
if (generated.length > 0) await requireBatch(db)(generated.map(([ctx, key]) => unreferencedKeyCleanup(ctx, key.kid)));
|
|
439
435
|
return null;
|
|
436
|
+
};
|
|
437
|
+
if (generated.length > 0) {
|
|
438
|
+
await requireBatch(db)(generated.flatMap(([, key]) => key.pending));
|
|
439
|
+
try {
|
|
440
|
+
order = await storedKey(db, kms, orderCtx, order, now);
|
|
441
|
+
bidx = await storedKey(db, kms, bidxCtx, bidx, now);
|
|
442
|
+
} catch (error) {
|
|
443
|
+
if (!(error instanceof VaultKeyUnavailableError)) throw error;
|
|
444
|
+
return refuse();
|
|
445
|
+
}
|
|
440
446
|
}
|
|
447
|
+
const orderRestore = await keyRowRestore(db, orderCtx, order.kid, now);
|
|
448
|
+
const bidxRestore = await keyRowRestore(db, bidxCtx, bidx.kid, now);
|
|
449
|
+
if (!orderRestore || !bidxRestore) return refuse();
|
|
450
|
+
return { order, bidx, restore: [orderRestore, bidxRestore] };
|
|
441
451
|
}
|
|
442
452
|
|
|
443
453
|
/** The key to seal under after storing `mine`: itself when its insert landed, else the active winner. */
|
|
@@ -550,6 +560,7 @@ async function sealAttempt(db: Queryable, kms: KmsClient, input: SealInput, atte
|
|
|
550
560
|
const vaultRowSql = `SELECT 1 FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND order_id = ? AND sealed_jti = ?`;
|
|
551
561
|
const vaultRowParams = [tenantId, stage, orderId, sealedJti];
|
|
552
562
|
const statements: QueryStatement[] = [
|
|
563
|
+
...(input.keys?.restore ?? []),
|
|
553
564
|
...orderKey.pending,
|
|
554
565
|
...bidxKey.pending,
|
|
555
566
|
{
|
|
@@ -605,7 +616,7 @@ async function sealAttempt(db: Queryable, kms: KmsClient, input: SealInput, atte
|
|
|
605
616
|
if (after) return after;
|
|
606
617
|
// Nothing committed: the order's retention snapshot or the active key changed underneath. Re-read
|
|
607
618
|
// and re-seal, bounded.
|
|
608
|
-
if (attempts > 1) return sealAttempt(db, kms,
|
|
619
|
+
if (attempts > 1) return sealAttempt(db, kms, input, attempts - 1);
|
|
609
620
|
throw new Error("contact-retention-changed");
|
|
610
621
|
}
|
|
611
622
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "6.12.
|
|
3
|
+
"version": "6.12.3",
|
|
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",
|