@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.
@@ -0,0 +1,103 @@
1
+ -- Location-keyed processor config, assignment lines, 1:N shipments per assignment, and the
2
+ -- exceptions a processor reports for lines it cannot ship.
3
+ --
4
+ -- allow-destructive: fulfillment_processor_config is rebuilt to add location_id to its primary
5
+ -- key. Every row is copied under location '*' before the old table is dropped, and the file is
6
+ -- applied atomically, so a failure at any statement restores the original table and rows.
7
+ CREATE TABLE `new_fulfillment_processor_config` (
8
+ `tenant_id` text NOT NULL,
9
+ `stage` text NOT NULL CHECK (`stage` IN ('preview', 'publication')),
10
+ `location_id` text NOT NULL DEFAULT '*',
11
+ `install_id` text NOT NULL,
12
+ `state` text NOT NULL CHECK (`state` IN ('active', 'cleared')),
13
+ `updated_by` text NOT NULL,
14
+ `updated_at` text NOT NULL,
15
+ PRIMARY KEY (`tenant_id`, `stage`, `location_id`)
16
+ );
17
+ --> statement-breakpoint
18
+ INSERT INTO `new_fulfillment_processor_config`
19
+ (`tenant_id`, `stage`, `location_id`, `install_id`, `state`, `updated_by`, `updated_at`)
20
+ SELECT `tenant_id`, `stage`, '*', `install_id`, `state`, `updated_by`, `updated_at`
21
+ FROM `fulfillment_processor_config`;
22
+ --> statement-breakpoint
23
+ DROP TABLE `fulfillment_processor_config`;
24
+ --> statement-breakpoint
25
+ ALTER TABLE `new_fulfillment_processor_config` RENAME TO `fulfillment_processor_config`;
26
+ --> statement-breakpoint
27
+ -- The processor-config location the assignment was routed through ('*' for the catch-all).
28
+ ALTER TABLE `fulfillment_assignments` ADD COLUMN `location_id` text NOT NULL DEFAULT '*';
29
+ --> statement-breakpoint
30
+ -- One row per sku an assignment carries. Shipped and cancelled never exceed assigned.
31
+ CREATE TABLE `fulfillment_assignment_lines` (
32
+ `assignment_id` text NOT NULL,
33
+ `line_id` text NOT NULL,
34
+ `sku` text NOT NULL,
35
+ `location_id` text NOT NULL,
36
+ `quantity_assigned` integer NOT NULL CHECK (`quantity_assigned` > 0),
37
+ `quantity_shipped` integer NOT NULL DEFAULT 0 CHECK (`quantity_shipped` >= 0),
38
+ `quantity_cancelled` integer NOT NULL DEFAULT 0 CHECK (`quantity_cancelled` >= 0),
39
+ CHECK (`quantity_shipped` + `quantity_cancelled` <= `quantity_assigned`),
40
+ PRIMARY KEY (`assignment_id`, `line_id`),
41
+ FOREIGN KEY (`assignment_id`) REFERENCES `fulfillment_assignments` (`assignment_id`)
42
+ );
43
+ --> statement-breakpoint
44
+ CREATE UNIQUE INDEX `fulfillment_assignment_lines_sku`
45
+ ON `fulfillment_assignment_lines` (`assignment_id`, `sku`);
46
+ --> statement-breakpoint
47
+ -- A shipment the processor reported against an assignment. Rows are never updated or deleted.
48
+ CREATE TABLE `fulfillment_shipments` (
49
+ `shipment_id` text PRIMARY KEY NOT NULL,
50
+ `assignment_id` text NOT NULL,
51
+ `tenant_id` text NOT NULL,
52
+ `stage` text NOT NULL CHECK (`stage` IN ('preview', 'publication')),
53
+ `order_id` text NOT NULL,
54
+ `install_id` text NOT NULL,
55
+ `carrier` text NOT NULL,
56
+ `service` text,
57
+ `tracking_number` text NOT NULL,
58
+ `tracking_url` text,
59
+ `adult_signature` text NOT NULL CHECK (`adult_signature` IN ('accepted', 'refused', 'absent')),
60
+ `shipped_items` text NOT NULL CHECK (json_valid(`shipped_items`)),
61
+ `created_at` text NOT NULL,
62
+ FOREIGN KEY (`assignment_id`) REFERENCES `fulfillment_assignments` (`assignment_id`)
63
+ );
64
+ --> statement-breakpoint
65
+ CREATE INDEX `fulfillment_shipments_assignment`
66
+ ON `fulfillment_shipments` (`assignment_id`, `created_at`);
67
+ --> statement-breakpoint
68
+ CREATE TRIGGER `fulfillment_shipments_no_update`
69
+ BEFORE UPDATE ON `fulfillment_shipments`
70
+ BEGIN
71
+ SELECT RAISE(ABORT, 'append-only');
72
+ END;
73
+ --> statement-breakpoint
74
+ CREATE TRIGGER `fulfillment_shipments_no_delete`
75
+ BEFORE DELETE ON `fulfillment_shipments`
76
+ BEGIN
77
+ SELECT RAISE(ABORT, 'append-only');
78
+ END;
79
+ --> statement-breakpoint
80
+ -- Lines a processor reports it cannot ship. The operator desk resolves them; nothing here
81
+ -- cancels or refunds.
82
+ CREATE TABLE `fulfillment_assignment_exceptions` (
83
+ `exception_id` text PRIMARY KEY NOT NULL,
84
+ `assignment_id` text NOT NULL,
85
+ `tenant_id` text NOT NULL,
86
+ `stage` text NOT NULL CHECK (`stage` IN ('preview', 'publication')),
87
+ `order_id` text NOT NULL,
88
+ `install_id` text NOT NULL,
89
+ `code` text NOT NULL CHECK (`code` IN (
90
+ 'vendor_rejected', 'backordered', 'out_of_stock', 'damaged',
91
+ 'address_undeliverable', 'carrier_refused', 'other'
92
+ )),
93
+ `lines` text NOT NULL CHECK (json_valid(`lines`)),
94
+ `note` text,
95
+ `state` text NOT NULL CHECK (`state` IN ('open', 'resolved')),
96
+ `created_at` text NOT NULL,
97
+ `resolved_at` text,
98
+ `resolved_by` text,
99
+ FOREIGN KEY (`assignment_id`) REFERENCES `fulfillment_assignments` (`assignment_id`)
100
+ );
101
+ --> statement-breakpoint
102
+ CREATE INDEX `fulfillment_assignment_exceptions_order`
103
+ ON `fulfillment_assignment_exceptions` (`tenant_id`, `stage`, `order_id`, `state`);
@@ -372,6 +372,8 @@ const PREVIEW_APP_ROUTES: ReadonlyArray<{ method: string; path: RegExp }> = [
372
372
  { method: "GET", path: /^\/api\/apps\/v1\/fulfillment\/assignments$/ },
373
373
  { method: "GET", path: new RegExp(`^/api/apps/v1/fulfillment/orders/${PREVIEW_APP_ORDER_SEGMENT}/recipient$`) },
374
374
  { method: "POST", path: new RegExp(`^/api/apps/v1/fulfillment/orders/${PREVIEW_APP_ORDER_SEGMENT}/shipment-evidence$`) },
375
+ { method: "POST", path: new RegExp(`^/api/apps/v1/fulfillment/assignments/${PREVIEW_APP_ORDER_SEGMENT}/shipments$`) },
376
+ { method: "POST", path: new RegExp(`^/api/apps/v1/fulfillment/assignments/${PREVIEW_APP_ORDER_SEGMENT}/exceptions$`) },
375
377
  ];
376
378
 
377
379
  export function isPreviewAppBootstrapRoute(method: string | undefined, renderPath: string | undefined): boolean {
@@ -13,7 +13,8 @@
13
13
  * 3. the caller's other writes;
14
14
  * 4. {@link cleanupStatement} — DELETE this kid WHERE NOT EXISTS a row referencing it.
15
15
  * A refused or losing batch therefore commits no key row; the loser re-reads the winner's key and
16
- * re-seals. Rotation is the only other writer of key rows.
16
+ * re-seals. Rotation is the only other writer of key rows, apart from {@link keyRowRestore}, which
17
+ * puts back a stored key's own row, retired, for a caller sealing under a key it opened earlier.
17
18
  */
18
19
 
19
20
  /** One statement of a D1 batch. */
@@ -178,6 +179,32 @@ export function cleanupStatement(
178
179
  };
179
180
  }
180
181
 
182
+ /**
183
+ * For a caller that opened `kid` before its own writes and seals under it afterwards: a statement for
184
+ * its sealing batch that puts the key's stored row back, retired, when rotation has retired and swept
185
+ * it in between, so the record insert still finds the kid. A no-op while the row exists. Reads the
186
+ * stored row now; null when it is already gone.
187
+ */
188
+ export async function keyRowRestore(db: Queryable, ctx: EncryptionContext, kid: string, now: Date): Promise<QueryStatement | null> {
189
+ const row = await db.first<{ wrapped_key: string; kms_key_arn: string; created_at: string }>(
190
+ `SELECT wrapped_key, kms_key_arn, created_at FROM contact_vault_data_keys
191
+ WHERE tenant_id = ? AND stage = ? AND purpose = ? AND kid = ?`,
192
+ ctx.tenantId, ctx.stage, ctx.purpose, kid,
193
+ );
194
+ if (!row) return null;
195
+ return {
196
+ sql: `INSERT INTO contact_vault_data_keys (tenant_id, stage, purpose, kid, wrapped_key, kms_key_arn, created_at, retired_at)
197
+ SELECT ?, ?, ?, ?, ?, ?, ?, ?
198
+ WHERE NOT EXISTS (
199
+ SELECT 1 FROM contact_vault_data_keys WHERE tenant_id = ? AND stage = ? AND purpose = ? AND kid = ?
200
+ )`,
201
+ params: [
202
+ ctx.tenantId, ctx.stage, ctx.purpose, kid, row.wrapped_key, row.kms_key_arn, row.created_at, now.toISOString(),
203
+ ctx.tenantId, ctx.stage, ctx.purpose, kid,
204
+ ],
205
+ };
206
+ }
207
+
181
208
  /**
182
209
  * The key for opening a record sealed under `kid`, active or retired. Reads the row on every call;
183
210
  * null when it is absent, so a deleted wrapped key stops opening immediately.
@@ -56,6 +56,18 @@ export function mountCommerceDesk(root: HTMLElement): void {
56
56
  }
57
57
  }
58
58
  }
59
+ /** Lines the processor reported it cannot ship, oldest first. Text only. */
60
+ function renderExceptions(exceptions: FulfillmentView["exceptions"], card: HTMLElement): void {
61
+ const block = document.createElement("div");
62
+ block.dataset.exceptions = "";
63
+ card.append(block);
64
+ for (const exception of exceptions) {
65
+ const lines = exception.lines.map((line) => `${line.sku} × ${line.quantity}`).join(", ");
66
+ const row = text("p", `Processor exception ${exception.code.replace(/_/g, " ")}: ${lines}`, block);
67
+ row.dataset.exceptionCode = exception.code;
68
+ if (exception.note) text("p", exception.note, block);
69
+ }
70
+ }
59
71
  function render(order: FulfillmentView): void {
60
72
  const card = document.createElement("section");
61
73
  card.dataset.orderId = order.orderId;
@@ -69,6 +81,7 @@ export function mountCommerceDesk(root: HTMLElement): void {
69
81
  owner.dataset.assignmentState = order.assignment.state;
70
82
  }
71
83
  if (order.shipment) renderShipment(order.shipment, card);
84
+ if (order.exceptions?.length) renderExceptions(order.exceptions, card);
72
85
  const actions = order.batch
73
86
  ? [
74
87
  ["pick", "Confirm pick"],
@@ -7,6 +7,7 @@ import type { LabelState } from "@tot/public-runtime";
7
7
  import { PROCESSOR_SCOPE } from "./assignmentStore.js";
8
8
  import type { SqlStatement } from "./store.js";
9
9
  import { CARRIER_SERVICE, TRACKING_NUMBER, parseCarrierCode, trackingUrlAllowed, type CarrierCode } from "./carrierEvidence.js";
10
+ import type { AssignmentExceptionView, AssignmentShipmentView } from "./splitShipments.js";
10
11
 
11
12
  /** The calling install and the assignment it writes under. Every app write requires both. */
12
13
  export interface AppAssignmentBinding {
@@ -55,9 +56,12 @@ export interface AppRefusalBody {
55
56
  holds?: readonly string[];
56
57
  }
57
58
 
59
+ /** Every view an app write answers with: the whole-order view, an assignment shipment or an exception. */
60
+ export type AppWriteView = AppShipmentView | AssignmentShipmentView | AssignmentExceptionView;
61
+
58
62
  export interface AppEvidenceResponse {
59
63
  status: number;
60
- body: AppShipmentView | AppRefusalBody;
64
+ body: AppWriteView | AppRefusalBody;
61
65
  }
62
66
 
63
67
  /** The facts a label-outcome audit row stores, read back by the desk and the app view. */
@@ -227,7 +231,7 @@ export function idempotencyRecord(response: AppEvidenceResponse): string {
227
231
  /** A recorded response, or null when the record is not one this route wrote. */
228
232
  export function replayedResponse(recorded: unknown): AppEvidenceResponse | null {
229
233
  if (!isRecord(recorded) || !Number.isSafeInteger(recorded.status) || !isRecord(recorded.body)) return null;
230
- return { status: Number(recorded.status), body: recorded.body as unknown as AppShipmentView | AppRefusalBody };
234
+ return { status: Number(recorded.status), body: recorded.body as unknown as AppWriteView | AppRefusalBody };
231
235
  }
232
236
 
233
237
  /** The batch key insert: a plain INSERT, so a same-key race rolls the whole batch back. */
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * Processor configuration and fulfillment assignments.
3
3
  *
4
- * A (tenant, stage) names at most one processor install. Operator release writes the order's
5
- * assignment to that install; hold, cancel and refund move it by state; switching or clearing the
4
+ * A (tenant, stage, location) names at most one processor install; location `*` is the catch-all an
5
+ * order routes through when its location has no config of its own. Operator release writes the
6
+ * order's assignment, and one line per sku, to that install; hold, cancel and refund move it by state; switching or clearing the
6
7
  * processor, and suspending, uninstalling or descoping its install, release it. Rows are never
7
8
  * deleted: assignments keep their history and a config clears by state.
8
9
  */
@@ -11,10 +12,18 @@ import type { FulfillmentDatabase, SqlStatement } from "./store.js";
11
12
 
12
13
  export const PROCESSOR_SCOPE = "fulfillment:process";
13
14
 
15
+ /** The catch-all processor-config location. */
16
+ export const DEFAULT_LOCATION = "*";
17
+
18
+ /** A location id: `*`, or the opaque id inventory and allocations carry. */
19
+ export const LOCATION_ID = /^(?:\*|[A-Za-z0-9._:-]{1,128})$/;
20
+
14
21
  export type AssignmentState = "active" | "held" | "cancelled" | "released";
15
22
 
16
23
  export interface ProcessorConfig {
17
24
  installId: string;
25
+ /** The config location this processor was read from. */
26
+ locationId: string;
18
27
  /** The install is active on this tenant, has an endpoint and holds `fulfillment:process`. */
19
28
  notifiable: boolean;
20
29
  }
@@ -25,6 +34,7 @@ export interface OpenAssignment {
25
34
  state: "active" | "held";
26
35
  eventVersion: number;
27
36
  assignedAt: string;
37
+ locationId: string;
28
38
  }
29
39
 
30
40
  /** SQL condition: install `?` is active on tenant `?`, has an endpoint and holds the processor scope. */
@@ -35,18 +45,72 @@ const NOTIFIABLE_INSTALL = `EXISTS (
35
45
  AND EXISTS (SELECT 1 FROM json_each(pi.scopes) WHERE json_each.value = '${PROCESSOR_SCOPE}')
36
46
  )`;
37
47
 
48
+ /** The active processor configured at exactly `locationId` (default the catch-all). */
38
49
  export async function readProcessor(
39
50
  db: Pick<FulfillmentDatabase, "get">,
40
51
  tenantId: string,
41
52
  stage: CommerceStage,
53
+ locationId: string = DEFAULT_LOCATION,
42
54
  ): Promise<ProcessorConfig | null> {
43
55
  const config = await db.get<{ install_id: string }>(
44
- `SELECT install_id FROM fulfillment_processor_config WHERE tenant_id = ? AND stage = ? AND state = 'active'`,
45
- [tenantId, stage],
56
+ `SELECT install_id FROM fulfillment_processor_config
57
+ WHERE tenant_id = ? AND stage = ? AND location_id = ? AND state = 'active'`,
58
+ [tenantId, stage, locationId],
46
59
  );
47
60
  if (!config) return null;
48
61
  const notifiable = await db.get<{ ok: number }>(`SELECT 1 AS ok WHERE ${NOTIFIABLE_INSTALL}`, [config.install_id, tenantId]);
49
- return { installId: config.install_id, notifiable: notifiable?.ok === 1 };
62
+ return { installId: config.install_id, locationId, notifiable: notifiable?.ok === 1 };
63
+ }
64
+
65
+ /** The processor an order at `locationId` routes to: that location's config, else the catch-all. */
66
+ export async function resolveProcessor(
67
+ db: Pick<FulfillmentDatabase, "get">,
68
+ tenantId: string,
69
+ stage: CommerceStage,
70
+ locationId: string,
71
+ ): Promise<ProcessorConfig | null> {
72
+ if (locationId !== DEFAULT_LOCATION) {
73
+ const exact = await readProcessor(db, tenantId, stage, locationId);
74
+ if (exact) return exact;
75
+ }
76
+ return readProcessor(db, tenantId, stage, DEFAULT_LOCATION);
77
+ }
78
+
79
+ /** One sku of an order and the inventory location its confirmed allocation names (`*` when none or several). */
80
+ export interface RoutedLine {
81
+ lineId: string;
82
+ sku: string;
83
+ quantity: number;
84
+ locationId: string;
85
+ }
86
+
87
+ /**
88
+ * The order's routing: each sku summed across its lines, located by its confirmed allocations, and
89
+ * the order's location — the one location every line shares, else `*`.
90
+ */
91
+ export async function routeOrderLines(
92
+ db: Pick<FulfillmentDatabase, "all">,
93
+ scope: { tenantId: string; stage: CommerceStage; orderId: string },
94
+ lines: readonly { sku: string; quantity: number }[],
95
+ ): Promise<{ locationId: string; lines: RoutedLine[] }> {
96
+ const allocations = await db.all<{ sku: string; location_id: string }>(
97
+ `SELECT DISTINCT sku, location_id FROM scrappy_allocations
98
+ WHERE tenant_id = ? AND stage = ? AND order_id = ? AND state = 'confirmed'`,
99
+ [scope.tenantId, scope.stage, scope.orderId],
100
+ );
101
+ const located = new Map<string, Set<string>>();
102
+ for (const row of allocations) {
103
+ if (!LOCATION_ID.test(row.location_id) || row.location_id === "unspecified") continue;
104
+ located.set(row.sku, (located.get(row.sku) ?? new Set()).add(row.location_id));
105
+ }
106
+ const quantities = new Map<string, number>();
107
+ for (const line of lines) quantities.set(line.sku, (quantities.get(line.sku) ?? 0) + line.quantity);
108
+ const routed: RoutedLine[] = [...quantities].map(([sku, quantity], index) => {
109
+ const locations = located.get(sku);
110
+ return { lineId: String(index + 1), sku, quantity, locationId: locations?.size === 1 ? [...locations][0]! : DEFAULT_LOCATION };
111
+ });
112
+ const shared = new Set(routed.map((line) => line.locationId));
113
+ return { locationId: shared.size === 1 ? [...shared][0]! : DEFAULT_LOCATION, lines: routed };
50
114
  }
51
115
 
52
116
  /** True when `installId` could be the processor for `tenantId`: active there, with an endpoint and the scope. */
@@ -60,16 +124,19 @@ export async function installMayProcess(
60
124
  }
61
125
 
62
126
  /**
63
- * Sets or clears the (tenant, stage) processor. Switching or clearing releases the previous
64
- * install's active and held assignments on that stage in the same batch; the config write is the
127
+ * Sets or clears the (tenant, stage, location) processor. Switching or clearing releases the
128
+ * previous install's active and held assignments routed through that location on that stage in
129
+ * the same batch; the config write is the
65
130
  * batch's compare-and-set, so a concurrent change aborts it.
66
131
  */
67
132
  export async function setProcessor(
68
133
  db: FulfillmentDatabase,
69
- input: { tenantId: string; stage: CommerceStage; installId: string | null; actorId: string; now: string },
70
- ): Promise<{ ok: true; installId: string | null } | { ok: false; code: "install-not-found" | "conflict" }> {
134
+ input: { tenantId: string; stage: CommerceStage; locationId?: string; installId: string | null; actorId: string; now: string },
135
+ ): Promise<{ ok: true; installId: string | null } | { ok: false; code: "install-not-found" | "conflict" | "location-invalid" }> {
136
+ const locationId = input.locationId ?? DEFAULT_LOCATION;
137
+ if (!LOCATION_ID.test(locationId)) return { ok: false, code: "location-invalid" };
71
138
  for (let attempt = 0; attempt < 3; attempt++) {
72
- const current = await readProcessor(db, input.tenantId, input.stage);
139
+ const current = await readProcessor(db, input.tenantId, input.stage, locationId);
73
140
  if ((current?.installId ?? null) === input.installId) return { ok: true, installId: input.installId };
74
141
  if (input.installId !== null && !(await installMayProcess(db, input.tenantId, input.installId))) {
75
142
  return { ok: false, code: "install-not-found" };
@@ -78,23 +145,23 @@ export async function setProcessor(
78
145
  if (input.installId === null) {
79
146
  first = {
80
147
  sql: `UPDATE fulfillment_processor_config SET state = 'cleared', updated_by = ?, updated_at = ?
81
- WHERE tenant_id = ? AND stage = ? AND state = 'active' AND install_id = ?`,
82
- params: [input.actorId, input.now, input.tenantId, input.stage, current!.installId],
148
+ WHERE tenant_id = ? AND stage = ? AND location_id = ? AND state = 'active' AND install_id = ?`,
149
+ params: [input.actorId, input.now, input.tenantId, input.stage, locationId, current!.installId],
83
150
  };
84
151
  } else if (current) {
85
152
  first = {
86
153
  sql: `UPDATE fulfillment_processor_config SET install_id = ?, updated_by = ?, updated_at = ?
87
- WHERE tenant_id = ? AND stage = ? AND state = 'active' AND install_id = ? AND ${NOTIFIABLE_INSTALL}`,
88
- params: [input.installId, input.actorId, input.now, input.tenantId, input.stage, current.installId, input.installId, input.tenantId],
154
+ WHERE tenant_id = ? AND stage = ? AND location_id = ? AND state = 'active' AND install_id = ? AND ${NOTIFIABLE_INSTALL}`,
155
+ params: [input.installId, input.actorId, input.now, input.tenantId, input.stage, locationId, current.installId, input.installId, input.tenantId],
89
156
  };
90
157
  } else {
91
158
  first = {
92
- sql: `INSERT INTO fulfillment_processor_config (tenant_id, stage, install_id, state, updated_by, updated_at)
93
- SELECT ?, ?, ?, 'active', ?, ? WHERE ${NOTIFIABLE_INSTALL}
94
- ON CONFLICT (tenant_id, stage) DO UPDATE SET
159
+ sql: `INSERT INTO fulfillment_processor_config (tenant_id, stage, location_id, install_id, state, updated_by, updated_at)
160
+ SELECT ?, ?, ?, ?, 'active', ?, ? WHERE ${NOTIFIABLE_INSTALL}
161
+ ON CONFLICT (tenant_id, stage, location_id) DO UPDATE SET
95
162
  install_id = excluded.install_id, state = 'active', updated_by = excluded.updated_by, updated_at = excluded.updated_at
96
163
  WHERE fulfillment_processor_config.state = 'cleared'`,
97
- params: [input.tenantId, input.stage, input.installId, input.actorId, input.now, input.installId, input.tenantId],
164
+ params: [input.tenantId, input.stage, locationId, input.installId, input.actorId, input.now, input.installId, input.tenantId],
98
165
  };
99
166
  }
100
167
  const statements: SqlStatement[] = [
@@ -103,7 +170,13 @@ export async function setProcessor(
103
170
  ];
104
171
  if (current) {
105
172
  statements.push(
106
- releaseInstallAssignmentsStatement({ tenantId: input.tenantId, installId: current.installId, now: input.now, stage: input.stage }),
173
+ releaseInstallAssignmentsStatement({
174
+ tenantId: input.tenantId,
175
+ installId: current.installId,
176
+ now: input.now,
177
+ stage: input.stage,
178
+ locationId,
179
+ }),
107
180
  );
108
181
  }
109
182
  try {
@@ -136,8 +209,9 @@ export async function readOpenAssignment(
136
209
  state: string;
137
210
  event_version: number;
138
211
  assigned_at: string;
212
+ location_id: string;
139
213
  }>(
140
- `SELECT assignment_id, install_id, state, event_version, assigned_at
214
+ `SELECT assignment_id, install_id, state, event_version, assigned_at, location_id
141
215
  FROM fulfillment_assignments
142
216
  WHERE tenant_id = ? AND stage = ? AND order_id = ? AND state IN ('active', 'held')`,
143
217
  [tenantId, stage, orderId],
@@ -149,17 +223,23 @@ export async function readOpenAssignment(
149
223
  state: row.state,
150
224
  eventVersion: Number(row.event_version),
151
225
  assignedAt: row.assigned_at,
226
+ locationId: row.location_id,
152
227
  };
153
228
  }
154
229
 
155
- /** SQL condition (no leading AND): the (tenant, stage) config names `installId` and that install is notifiable. */
156
- export function processorGuard(tenantId: string, stage: CommerceStage, installId: string): SqlStatement {
230
+ /** SQL condition (no leading AND): the (tenant, stage, location) config names `installId` and that install is notifiable. */
231
+ export function processorGuard(
232
+ tenantId: string,
233
+ stage: CommerceStage,
234
+ installId: string,
235
+ locationId: string = DEFAULT_LOCATION,
236
+ ): SqlStatement {
157
237
  return {
158
238
  sql: `EXISTS (
159
239
  SELECT 1 FROM fulfillment_processor_config AS pc
160
- WHERE pc.tenant_id = ? AND pc.stage = ? AND pc.install_id = ? AND pc.state = 'active'
240
+ WHERE pc.tenant_id = ? AND pc.stage = ? AND pc.location_id = ? AND pc.install_id = ? AND pc.state = 'active'
161
241
  ) AND ${NOTIFIABLE_INSTALL}`,
162
- params: [tenantId, stage, installId, installId, tenantId],
242
+ params: [tenantId, stage, locationId, installId, installId, tenantId],
163
243
  };
164
244
  }
165
245
 
@@ -180,20 +260,22 @@ export function insertAssignmentStatement(input: {
180
260
  stage: CommerceStage;
181
261
  orderId: string;
182
262
  installId: string;
263
+ locationId: string;
183
264
  version: number;
184
265
  now: string;
185
266
  }): SqlStatement {
186
267
  const gate = orderAtVersion(input.tenantId, input.stage, input.orderId, input.version);
187
268
  return {
188
269
  sql: `INSERT INTO fulfillment_assignments
189
- (assignment_id, tenant_id, stage, order_id, install_id, state, event_version, assigned_at, updated_at)
190
- SELECT ?, ?, ?, ?, ?, 'active', ?, ?, ? WHERE ${gate.sql}`,
270
+ (assignment_id, tenant_id, stage, order_id, install_id, location_id, state, event_version, assigned_at, updated_at)
271
+ SELECT ?, ?, ?, ?, ?, ?, 'active', ?, ?, ? WHERE ${gate.sql}`,
191
272
  params: [
192
273
  input.assignmentId,
193
274
  input.tenantId,
194
275
  input.stage,
195
276
  input.orderId,
196
277
  input.installId,
278
+ input.locationId,
197
279
  input.version,
198
280
  input.now,
199
281
  input.now,
@@ -202,6 +284,21 @@ export function insertAssignmentStatement(input: {
202
284
  };
203
285
  }
204
286
 
287
+ /** Writes the assignment's lines, only when its assignment row was written at `version` in this batch. */
288
+ export function insertAssignmentLinesStatements(input: {
289
+ assignmentId: string;
290
+ version: number;
291
+ lines: readonly RoutedLine[];
292
+ }): SqlStatement[] {
293
+ return input.lines.map((line) => ({
294
+ sql: `INSERT INTO fulfillment_assignment_lines (assignment_id, line_id, sku, location_id, quantity_assigned)
295
+ SELECT ?, ?, ?, ?, ? WHERE EXISTS (
296
+ SELECT 1 FROM fulfillment_assignments WHERE assignment_id = ? AND state = 'active' AND event_version = ?
297
+ )`,
298
+ params: [input.assignmentId, line.lineId, line.sku, line.locationId, line.quantity, input.assignmentId, input.version],
299
+ }));
300
+ }
301
+
205
302
  /** Moves one assignment from any of `from` to `to` when the order committed at `version`, and `guard` holds. */
206
303
  export function moveAssignmentStatement(input: {
207
304
  assignmentId: string;
@@ -245,21 +342,30 @@ export function assignmentAtGate(assignmentId: string, state: AssignmentState, v
245
342
  };
246
343
  }
247
344
 
248
- /** Releases every open assignment `installId` holds on `tenantId` (optionally one stage). No event. */
345
+ /** Releases every open assignment `installId` holds on `tenantId` (optionally one stage and routing location). No event. */
249
346
  export function releaseInstallAssignmentsStatement(input: {
250
347
  tenantId: string;
251
348
  installId: string;
252
349
  now: string;
253
350
  stage?: CommerceStage;
351
+ locationId?: string;
254
352
  }): SqlStatement {
255
353
  return {
256
354
  sql: `UPDATE fulfillment_assignments SET state = 'released', updated_at = ?
257
- WHERE tenant_id = ? AND install_id = ? AND state IN ('active', 'held')${input.stage ? " AND stage = ?" : ""}`,
258
- params: [input.now, input.tenantId, input.installId, ...(input.stage ? [input.stage] : [])],
355
+ WHERE tenant_id = ? AND install_id = ? AND state IN ('active', 'held')${input.stage ? " AND stage = ?" : ""}${
356
+ input.locationId ? " AND location_id = ?" : ""
357
+ }`,
358
+ params: [
359
+ input.now,
360
+ input.tenantId,
361
+ input.installId,
362
+ ...(input.stage ? [input.stage] : []),
363
+ ...(input.locationId ? [input.locationId] : []),
364
+ ],
259
365
  };
260
366
  }
261
367
 
262
- /** Clears every active processor config naming `installId` on `tenantId`. */
368
+ /** Clears every active processor config naming `installId` on `tenantId`, at every location. */
263
369
  export function clearInstallProcessorStatement(input: {
264
370
  tenantId: string;
265
371
  installId: string;