@tokenoftrust/storefront-runner 6.12.2 → 6.12.4
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 +149 -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 +165 -30
- package/apps/storefront/src/lib/fulfillment/fulfillmentService.ts +330 -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,149 @@
|
|
|
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
|
+
-- Open assignments carry the lines of their order's latest line snapshot, read and routed as the
|
|
48
|
+
-- service reads and routes them: a snapshot with any malformed entry carries no lines; otherwise
|
|
49
|
+
-- one line per sku in first-seen order, at the sku's single confirmed allocation location, else '*'.
|
|
50
|
+
WITH `latest` AS (
|
|
51
|
+
SELECT `audit`.`tenant_id`, `audit`.`stage`, `audit`.`order_id`, `audit`.`to_state`
|
|
52
|
+
FROM `scrappy_shipment_audit` AS `audit`
|
|
53
|
+
WHERE `audit`.`kind` = 'lines' AND json_valid(`audit`.`to_state`)
|
|
54
|
+
AND NOT EXISTS (
|
|
55
|
+
SELECT 1 FROM `scrappy_shipment_audit` AS `later`
|
|
56
|
+
WHERE `later`.`tenant_id` = `audit`.`tenant_id` AND `later`.`stage` = `audit`.`stage`
|
|
57
|
+
AND `later`.`order_id` = `audit`.`order_id` AND `later`.`kind` = 'lines'
|
|
58
|
+
AND (`later`.`at` > `audit`.`at` OR (`later`.`at` = `audit`.`at` AND `later`.`audit_id` > `audit`.`audit_id`))
|
|
59
|
+
)
|
|
60
|
+
), `items` AS (
|
|
61
|
+
SELECT `a`.`assignment_id`, `a`.`tenant_id`, `a`.`stage`, `a`.`order_id`,
|
|
62
|
+
json_extract(`item`.`value`, '$.sku') AS `sku`,
|
|
63
|
+
json_extract(`item`.`value`, '$.quantity') AS `quantity`,
|
|
64
|
+
CAST(`item`.`key` AS INTEGER) AS `position`
|
|
65
|
+
FROM `fulfillment_assignments` AS `a`
|
|
66
|
+
JOIN `latest` ON `latest`.`tenant_id` = `a`.`tenant_id` AND `latest`.`stage` = `a`.`stage` AND `latest`.`order_id` = `a`.`order_id`
|
|
67
|
+
JOIN json_each(`latest`.`to_state`) AS `item`
|
|
68
|
+
WHERE `a`.`state` IN ('active', 'held') AND json_type(`latest`.`to_state`) = 'array'
|
|
69
|
+
), `malformed` AS (
|
|
70
|
+
SELECT DISTINCT `assignment_id` FROM `items`
|
|
71
|
+
WHERE typeof(`sku`) <> 'text' OR length(`sku`) NOT BETWEEN 1 AND 128 OR `sku` GLOB '*[^A-Za-z0-9._:-]*'
|
|
72
|
+
OR typeof(`quantity`) <> 'integer' OR `quantity` < 1
|
|
73
|
+
), `grouped` AS (
|
|
74
|
+
SELECT `assignment_id`, `tenant_id`, `stage`, `order_id`, `sku`, SUM(`quantity`) AS `quantity`, MIN(`position`) AS `first`
|
|
75
|
+
FROM `items`
|
|
76
|
+
WHERE `assignment_id` NOT IN (SELECT `assignment_id` FROM `malformed`)
|
|
77
|
+
GROUP BY `assignment_id`, `sku`
|
|
78
|
+
)
|
|
79
|
+
INSERT INTO `fulfillment_assignment_lines` (`assignment_id`, `line_id`, `sku`, `location_id`, `quantity_assigned`)
|
|
80
|
+
SELECT `g`.`assignment_id`,
|
|
81
|
+
CAST(ROW_NUMBER() OVER (PARTITION BY `g`.`assignment_id` ORDER BY `g`.`first`) AS TEXT),
|
|
82
|
+
`g`.`sku`,
|
|
83
|
+
COALESCE((
|
|
84
|
+
SELECT MIN(`al`.`location_id`) FROM `scrappy_allocations` AS `al`
|
|
85
|
+
WHERE `al`.`tenant_id` = `g`.`tenant_id` AND `al`.`stage` = `g`.`stage` AND `al`.`order_id` = `g`.`order_id`
|
|
86
|
+
AND `al`.`sku` = `g`.`sku` AND `al`.`state` = 'confirmed' AND `al`.`location_id` <> 'unspecified'
|
|
87
|
+
AND (`al`.`location_id` = '*' OR (length(`al`.`location_id`) BETWEEN 1 AND 128 AND `al`.`location_id` NOT GLOB '*[^A-Za-z0-9._:-]*'))
|
|
88
|
+
HAVING COUNT(DISTINCT `al`.`location_id`) = 1
|
|
89
|
+
), '*'),
|
|
90
|
+
`g`.`quantity`
|
|
91
|
+
FROM `grouped` AS `g`;
|
|
92
|
+
--> statement-breakpoint
|
|
93
|
+
-- A shipment the processor reported against an assignment. Rows are never updated or deleted.
|
|
94
|
+
CREATE TABLE `fulfillment_shipments` (
|
|
95
|
+
`shipment_id` text PRIMARY KEY NOT NULL,
|
|
96
|
+
`assignment_id` text NOT NULL,
|
|
97
|
+
`tenant_id` text NOT NULL,
|
|
98
|
+
`stage` text NOT NULL CHECK (`stage` IN ('preview', 'publication')),
|
|
99
|
+
`order_id` text NOT NULL,
|
|
100
|
+
`install_id` text NOT NULL,
|
|
101
|
+
`carrier` text NOT NULL,
|
|
102
|
+
`service` text,
|
|
103
|
+
`tracking_number` text NOT NULL,
|
|
104
|
+
`tracking_url` text,
|
|
105
|
+
`adult_signature` text NOT NULL CHECK (`adult_signature` IN ('accepted', 'refused', 'absent')),
|
|
106
|
+
`shipped_items` text NOT NULL CHECK (json_valid(`shipped_items`)),
|
|
107
|
+
`created_at` text NOT NULL,
|
|
108
|
+
FOREIGN KEY (`assignment_id`) REFERENCES `fulfillment_assignments` (`assignment_id`)
|
|
109
|
+
);
|
|
110
|
+
--> statement-breakpoint
|
|
111
|
+
CREATE INDEX `fulfillment_shipments_assignment`
|
|
112
|
+
ON `fulfillment_shipments` (`assignment_id`, `created_at`);
|
|
113
|
+
--> statement-breakpoint
|
|
114
|
+
CREATE TRIGGER `fulfillment_shipments_no_update`
|
|
115
|
+
BEFORE UPDATE ON `fulfillment_shipments`
|
|
116
|
+
BEGIN
|
|
117
|
+
SELECT RAISE(ABORT, 'append-only');
|
|
118
|
+
END;
|
|
119
|
+
--> statement-breakpoint
|
|
120
|
+
CREATE TRIGGER `fulfillment_shipments_no_delete`
|
|
121
|
+
BEFORE DELETE ON `fulfillment_shipments`
|
|
122
|
+
BEGIN
|
|
123
|
+
SELECT RAISE(ABORT, 'append-only');
|
|
124
|
+
END;
|
|
125
|
+
--> statement-breakpoint
|
|
126
|
+
-- Lines a processor reports it cannot ship. The operator desk resolves them; nothing here
|
|
127
|
+
-- cancels or refunds.
|
|
128
|
+
CREATE TABLE `fulfillment_assignment_exceptions` (
|
|
129
|
+
`exception_id` text PRIMARY KEY NOT NULL,
|
|
130
|
+
`assignment_id` text NOT NULL,
|
|
131
|
+
`tenant_id` text NOT NULL,
|
|
132
|
+
`stage` text NOT NULL CHECK (`stage` IN ('preview', 'publication')),
|
|
133
|
+
`order_id` text NOT NULL,
|
|
134
|
+
`install_id` text NOT NULL,
|
|
135
|
+
`code` text NOT NULL CHECK (`code` IN (
|
|
136
|
+
'vendor_rejected', 'backordered', 'out_of_stock', 'damaged',
|
|
137
|
+
'address_undeliverable', 'carrier_refused', 'other'
|
|
138
|
+
)),
|
|
139
|
+
`lines` text NOT NULL CHECK (json_valid(`lines`)),
|
|
140
|
+
`note` text,
|
|
141
|
+
`state` text NOT NULL CHECK (`state` IN ('open', 'resolved')),
|
|
142
|
+
`created_at` text NOT NULL,
|
|
143
|
+
`resolved_at` text,
|
|
144
|
+
`resolved_by` text,
|
|
145
|
+
FOREIGN KEY (`assignment_id`) REFERENCES `fulfillment_assignments` (`assignment_id`)
|
|
146
|
+
);
|
|
147
|
+
--> statement-breakpoint
|
|
148
|
+
CREATE INDEX `fulfillment_assignment_exceptions_order`
|
|
149
|
+
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:
|
|
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
|
|
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
|
|
5
|
-
*
|
|
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
|
|
45
|
-
|
|
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
|
|
64
|
-
* install's active and held assignments on that stage in
|
|
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({
|
|
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(
|
|
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,50 @@ export function insertAssignmentStatement(input: {
|
|
|
202
284
|
};
|
|
203
285
|
}
|
|
204
286
|
|
|
287
|
+
/**
|
|
288
|
+
* Writes the assignment's lines, only when its assignment row was written at `version` in this
|
|
289
|
+
* batch. Each line carries what the order's earlier assignments have not shipped or cancelled; a
|
|
290
|
+
* line with nothing left is not written.
|
|
291
|
+
*/
|
|
292
|
+
export function insertAssignmentLinesStatements(input: {
|
|
293
|
+
assignmentId: string;
|
|
294
|
+
tenantId: string;
|
|
295
|
+
stage: CommerceStage;
|
|
296
|
+
orderId: string;
|
|
297
|
+
version: number;
|
|
298
|
+
lines: readonly RoutedLine[];
|
|
299
|
+
}): SqlStatement[] {
|
|
300
|
+
return input.lines.map((line) => ({
|
|
301
|
+
sql: `INSERT INTO fulfillment_assignment_lines (assignment_id, line_id, sku, location_id, quantity_assigned)
|
|
302
|
+
SELECT ?, ?, ?, ?, rest.quantity FROM (
|
|
303
|
+
SELECT ? - COALESCE((
|
|
304
|
+
SELECT SUM(prior.quantity_shipped + prior.quantity_cancelled)
|
|
305
|
+
FROM fulfillment_assignment_lines AS prior
|
|
306
|
+
JOIN fulfillment_assignments AS earlier ON earlier.assignment_id = prior.assignment_id
|
|
307
|
+
WHERE earlier.tenant_id = ? AND earlier.stage = ? AND earlier.order_id = ?
|
|
308
|
+
AND earlier.assignment_id <> ? AND prior.sku = ?
|
|
309
|
+
), 0) AS quantity
|
|
310
|
+
) AS rest
|
|
311
|
+
WHERE rest.quantity > 0 AND EXISTS (
|
|
312
|
+
SELECT 1 FROM fulfillment_assignments WHERE assignment_id = ? AND state = 'active' AND event_version = ?
|
|
313
|
+
)`,
|
|
314
|
+
params: [
|
|
315
|
+
input.assignmentId,
|
|
316
|
+
line.lineId,
|
|
317
|
+
line.sku,
|
|
318
|
+
line.locationId,
|
|
319
|
+
line.quantity,
|
|
320
|
+
input.tenantId,
|
|
321
|
+
input.stage,
|
|
322
|
+
input.orderId,
|
|
323
|
+
input.assignmentId,
|
|
324
|
+
line.sku,
|
|
325
|
+
input.assignmentId,
|
|
326
|
+
input.version,
|
|
327
|
+
],
|
|
328
|
+
}));
|
|
329
|
+
}
|
|
330
|
+
|
|
205
331
|
/** Moves one assignment from any of `from` to `to` when the order committed at `version`, and `guard` holds. */
|
|
206
332
|
export function moveAssignmentStatement(input: {
|
|
207
333
|
assignmentId: string;
|
|
@@ -245,21 +371,30 @@ export function assignmentAtGate(assignmentId: string, state: AssignmentState, v
|
|
|
245
371
|
};
|
|
246
372
|
}
|
|
247
373
|
|
|
248
|
-
/** Releases every open assignment `installId` holds on `tenantId` (optionally one stage). No event. */
|
|
374
|
+
/** Releases every open assignment `installId` holds on `tenantId` (optionally one stage and routing location). No event. */
|
|
249
375
|
export function releaseInstallAssignmentsStatement(input: {
|
|
250
376
|
tenantId: string;
|
|
251
377
|
installId: string;
|
|
252
378
|
now: string;
|
|
253
379
|
stage?: CommerceStage;
|
|
380
|
+
locationId?: string;
|
|
254
381
|
}): SqlStatement {
|
|
255
382
|
return {
|
|
256
383
|
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
|
-
|
|
384
|
+
WHERE tenant_id = ? AND install_id = ? AND state IN ('active', 'held')${input.stage ? " AND stage = ?" : ""}${
|
|
385
|
+
input.locationId ? " AND location_id = ?" : ""
|
|
386
|
+
}`,
|
|
387
|
+
params: [
|
|
388
|
+
input.now,
|
|
389
|
+
input.tenantId,
|
|
390
|
+
input.installId,
|
|
391
|
+
...(input.stage ? [input.stage] : []),
|
|
392
|
+
...(input.locationId ? [input.locationId] : []),
|
|
393
|
+
],
|
|
259
394
|
};
|
|
260
395
|
}
|
|
261
396
|
|
|
262
|
-
/** Clears every active processor config naming `installId` on `tenantId
|
|
397
|
+
/** Clears every active processor config naming `installId` on `tenantId`, at every location. */
|
|
263
398
|
export function clearInstallProcessorStatement(input: {
|
|
264
399
|
tenantId: string;
|
|
265
400
|
installId: string;
|