@tokenoftrust/storefront-runner 7.8.7 → 7.8.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/storefront/src/components/compliance/storefront/islands/CheckoutComplianceGate.tsx +47 -2
- package/apps/storefront/src/lib/access/auth/agentSessionGate.ts +1 -0
- package/apps/storefront/src/lib/checkout/commerce/finalCartAuthorization.ts +36 -18
- package/apps/storefront/src/lib/compliance/browser/checkoutVerificationFlow.ts +49 -0
- package/apps/storefront/src/lib/fulfillment/readiness.ts +6 -3
- package/apps/storefront/src/lib/inventory/allocations.ts +34 -12
- package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +1 -5
- package/package.json +1 -1
package/apps/storefront/src/components/compliance/storefront/islands/CheckoutComplianceGate.tsx
CHANGED
|
@@ -29,10 +29,12 @@ import {
|
|
|
29
29
|
carryCheckoutVerification,
|
|
30
30
|
checkoutLineFromForm,
|
|
31
31
|
clearStoredRef,
|
|
32
|
+
isGuestShopper,
|
|
32
33
|
isStoreNotPublicRefusal,
|
|
33
34
|
parsePreflightResponse,
|
|
34
35
|
pollVerification,
|
|
35
36
|
readStoredRef,
|
|
37
|
+
requestFastTrackAccountSave,
|
|
36
38
|
verificationPhase,
|
|
37
39
|
verificationRefKey,
|
|
38
40
|
verifiedRefKey,
|
|
@@ -63,6 +65,7 @@ const STORE_NOT_PUBLIC_MESSAGE =
|
|
|
63
65
|
|
|
64
66
|
export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props) {
|
|
65
67
|
const [pending, setPending] = useState<PendingLine | null>(null);
|
|
68
|
+
const activeDialogLine = useRef<PendingLine | null>(null);
|
|
66
69
|
const [region, setRegion] = useState("");
|
|
67
70
|
const [affirmed, setAffirmed] = useState(false);
|
|
68
71
|
const [loading, setLoading] = useState(false);
|
|
@@ -75,6 +78,9 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
|
|
|
75
78
|
const [email, setEmail] = useState("");
|
|
76
79
|
const [givenName, setGivenName] = useState("");
|
|
77
80
|
const [familyName, setFamilyName] = useState("");
|
|
81
|
+
const [guestShopper, setGuestShopper] = useState(false);
|
|
82
|
+
const [saveForFastTrack, setSaveForFastTrack] = useState(true);
|
|
83
|
+
const fastTrackSentRef = useRef(false);
|
|
78
84
|
const [verificationRef, setVerificationRef] = useState<string | null>(null);
|
|
79
85
|
const [continuationUrl, setContinuationUrl] = useState<string | null>(null);
|
|
80
86
|
const [popupBlocked, setPopupBlocked] = useState(false);
|
|
@@ -129,12 +135,18 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
|
|
|
129
135
|
}
|
|
130
136
|
}
|
|
131
137
|
function open(line: PendingLine) {
|
|
138
|
+
stopPolling();
|
|
139
|
+
activeDialogLine.current = line;
|
|
132
140
|
setPending(line);
|
|
133
141
|
setDecision(null);
|
|
134
142
|
setError(null);
|
|
143
|
+
setLoading(false);
|
|
135
144
|
setPhase("none");
|
|
136
145
|
setContinuationUrl(null);
|
|
137
146
|
setPopupBlocked(false);
|
|
147
|
+
setGuestShopper(false);
|
|
148
|
+
setSaveForFastTrack(true);
|
|
149
|
+
fastTrackSentRef.current = false;
|
|
138
150
|
// A reload mid-trip must not lose the correlation: replay the stored ref so
|
|
139
151
|
// the server re-reads THIS attempt's verification instead of starting over.
|
|
140
152
|
setVerificationRef(line.shopperCart ? null :
|
|
@@ -150,10 +162,21 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
|
|
|
150
162
|
}
|
|
151
163
|
document.addEventListener("submit", onSubmit, true);
|
|
152
164
|
return () => document.removeEventListener("submit", onSubmit, true);
|
|
153
|
-
}, [preflightUrl]);
|
|
165
|
+
}, [preflightUrl, stopPolling]);
|
|
166
|
+
|
|
167
|
+
useEffect(() => {
|
|
168
|
+
if (phase !== "collect" || !pending || pending.shopperCart) return;
|
|
169
|
+
// An open store uses the managed cart for signed-in shoppers too.
|
|
170
|
+
let cancelled = false;
|
|
171
|
+
void isGuestShopper(preflightUrl).then((guest) => {
|
|
172
|
+
if (!cancelled && activeDialogLine.current === pending) setGuestShopper(guest);
|
|
173
|
+
});
|
|
174
|
+
return () => { cancelled = true; };
|
|
175
|
+
}, [pending, phase, preflightUrl]);
|
|
154
176
|
|
|
155
177
|
const close = useCallback(() => {
|
|
156
178
|
stopPolling();
|
|
179
|
+
activeDialogLine.current = null;
|
|
157
180
|
setPending(null);
|
|
158
181
|
setDecision(null);
|
|
159
182
|
setError(null);
|
|
@@ -183,6 +206,7 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
|
|
|
183
206
|
line.form.dataset.complianceCleared = "1";
|
|
184
207
|
line.form.dataset.paymentAuthority = "none";
|
|
185
208
|
document.documentElement.style.overflow = "";
|
|
209
|
+
activeDialogLine.current = null;
|
|
186
210
|
setPending(null);
|
|
187
211
|
if (typeof line.form.requestSubmit === "function") line.form.requestSubmit();
|
|
188
212
|
else line.form.submit();
|
|
@@ -353,14 +377,22 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
|
|
|
353
377
|
ref: verificationRef,
|
|
354
378
|
includeShopper: phase === "collect" || phase === "stalled",
|
|
355
379
|
});
|
|
380
|
+
if (activeDialogLine.current !== pending) return;
|
|
356
381
|
setLoading(false);
|
|
357
382
|
if (!res) {
|
|
358
383
|
// Fail closed: a regulated tenant never proceeds on an unreadable result.
|
|
359
384
|
setError(gateRefused.current ? STORE_NOT_PUBLIC_MESSAGE : FAIL_CLOSED_MESSAGE);
|
|
360
385
|
return;
|
|
361
386
|
}
|
|
387
|
+
if (phase === "collect" && guestShopper && !fastTrackSentRef.current && saveForFastTrack && email.trim()) {
|
|
388
|
+
const next = verificationPhase(res);
|
|
389
|
+
if (next === "continue" || next === "waiting" || next === "cleared") {
|
|
390
|
+
fastTrackSentRef.current = true;
|
|
391
|
+
void requestFastTrackAccountSave({ preflightUrl, email, saveForFastTrack, shopperCart: pending.shopperCart });
|
|
392
|
+
}
|
|
393
|
+
}
|
|
362
394
|
apply(pending, res);
|
|
363
|
-
}, [pending, send, apply, verificationRef, phase, stopPolling]);
|
|
395
|
+
}, [pending, send, apply, verificationRef, phase, stopPolling, guestShopper, email, saveForFastTrack, preflightUrl]);
|
|
364
396
|
|
|
365
397
|
/** Abandon a denied attempt and start a brand-new verification (new ref). */
|
|
366
398
|
const restartVerification = useCallback(() => {
|
|
@@ -501,6 +533,19 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
|
|
|
501
533
|
/>
|
|
502
534
|
</label>
|
|
503
535
|
</div>
|
|
536
|
+
{guestShopper && (
|
|
537
|
+
<label class="flex items-start gap-2.5 text-sm text-[var(--color-text)]">
|
|
538
|
+
<input
|
|
539
|
+
type="checkbox"
|
|
540
|
+
name="tot-save-fast-track"
|
|
541
|
+
class="mt-0.5 h-4 w-4"
|
|
542
|
+
checked={saveForFastTrack}
|
|
543
|
+
disabled={loading}
|
|
544
|
+
onChange={(e) => setSaveForFastTrack((e.target as HTMLInputElement).checked)}
|
|
545
|
+
/>
|
|
546
|
+
<span>Save my verified info for 1-click fast-track checkout & order history.</span>
|
|
547
|
+
</label>
|
|
548
|
+
)}
|
|
504
549
|
</div>
|
|
505
550
|
)}
|
|
506
551
|
</div>
|
|
@@ -63,6 +63,7 @@ export const AGENT_ALLOWED_ROUTES: ReadonlyArray<{ method: string; path: string
|
|
|
63
63
|
*/
|
|
64
64
|
export const AGENT_ROLE_ROUTES: ReadonlyArray<{ method: string; path: string; role: AgentRoleId }> = [
|
|
65
65
|
{ method: "GET", path: "/api/admin/orders", role: ADMIN_READ_ROLE },
|
|
66
|
+
{ method: "GET", path: "/api/admin/orders/manual", role: ADMIN_READ_ROLE },
|
|
66
67
|
{ method: "GET", path: "/api/admin/orders/:id", role: ADMIN_READ_ROLE },
|
|
67
68
|
{ method: "GET", path: "/api/admin/inventory/levels", role: ADMIN_READ_ROLE },
|
|
68
69
|
{ method: "GET", path: "/api/admin/inventory/history", role: ADMIN_READ_ROLE },
|
|
@@ -31,6 +31,11 @@ import {
|
|
|
31
31
|
} from "@tot/public-runtime";
|
|
32
32
|
import { readMirrorAuthority, VERIFICATION_PROVIDER_OWNER, type ReserveHold } from "@/lib/inventory/allocations.js";
|
|
33
33
|
|
|
34
|
+
/** Checkout authorization window for reservation and payment completion. */
|
|
35
|
+
export const CHECKOUT_ADMISSION_TTL_MS = 5 * 60_000;
|
|
36
|
+
/** Fulfillment evidence validity after accepting a checkout or approved invoice. */
|
|
37
|
+
export const FULFILLMENT_EVIDENCE_TTL_MS = 30 * 24 * 60 * 60_000;
|
|
38
|
+
|
|
34
39
|
/**
|
|
35
40
|
* Whether the signed excise carrier reconciles with the signed payment totals.
|
|
36
41
|
* When `totals.exciseMinor` is present, the carrier must be `computed` with `amountMinor`
|
|
@@ -157,7 +162,7 @@ function seamRuleFinding(seam: SeamView | null): { finding: string } | null {
|
|
|
157
162
|
return code ? { finding: `verification-refused:${code}` } : null;
|
|
158
163
|
}
|
|
159
164
|
|
|
160
|
-
function seamFinding(seam: SeamView | null): { finding: string; owner?: string } | null {
|
|
165
|
+
export function seamFinding(seam: SeamView | null): { finding: string; owner?: string } | null {
|
|
161
166
|
if (!seam || seam.status === "absent") return { finding: "verification-seam-absent" };
|
|
162
167
|
if (seam.status === "clear") return null;
|
|
163
168
|
const codes = (seam.codes ?? []).filter((code) => /^[a-z0-9_-]+$/.test(code));
|
|
@@ -185,7 +190,7 @@ export function exciseUnavailableReason(
|
|
|
185
190
|
return undefined;
|
|
186
191
|
}
|
|
187
192
|
|
|
188
|
-
function exciseFinding(
|
|
193
|
+
export function exciseFinding(
|
|
189
194
|
exciseRequired: boolean | undefined,
|
|
190
195
|
excise: ExciseCarrier | undefined,
|
|
191
196
|
evidence: CommerceEvidence | null,
|
|
@@ -308,8 +313,32 @@ export async function evaluateFinalCart(input: FinalCartRequest): Promise<FinalC
|
|
|
308
313
|
});
|
|
309
314
|
if (!command.admit) return { ok: false, finding: commandFinding(command.reason) };
|
|
310
315
|
|
|
316
|
+
const stock = finalCartStockHolds(input.presented.lines, input.stockTracked, input.authorities, input.catalogAvailable);
|
|
317
|
+
if (!stock.ok) return stock;
|
|
318
|
+
|
|
319
|
+
if (input.token.scheme !== "asymmetric-jwks") return { ok: false, finding: "shared-secret" };
|
|
320
|
+
return {
|
|
321
|
+
ok: true,
|
|
322
|
+
digest,
|
|
323
|
+
expiresAt,
|
|
324
|
+
amountMinor,
|
|
325
|
+
holds: stock.holds,
|
|
326
|
+
issuer: input.token.issuer,
|
|
327
|
+
jti: input.token.jti,
|
|
328
|
+
tenantId: input.routedTenantId,
|
|
329
|
+
stage: input.presented.stage,
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** The allocation quantities and balance checks shared by both final-cart entry points. */
|
|
334
|
+
export function finalCartStockHolds(
|
|
335
|
+
lines: readonly { sku: string; quantity: number }[],
|
|
336
|
+
stockTracked: boolean,
|
|
337
|
+
authorities: readonly unknown[],
|
|
338
|
+
catalogAvailable: boolean,
|
|
339
|
+
): { ok: true; holds: ReserveHold[] } | { ok: false; finding: string } {
|
|
311
340
|
const quantities = new Map<string, number>();
|
|
312
|
-
for (const line of
|
|
341
|
+
for (const line of lines) {
|
|
313
342
|
quantities.set(line.sku, (quantities.get(line.sku) ?? 0) + line.quantity);
|
|
314
343
|
}
|
|
315
344
|
const holds: ReserveHold[] = [];
|
|
@@ -320,31 +349,20 @@ export async function evaluateFinalCart(input: FinalCartRequest): Promise<FinalC
|
|
|
320
349
|
continue;
|
|
321
350
|
}
|
|
322
351
|
const named =
|
|
323
|
-
|
|
352
|
+
authorities.find((value) => {
|
|
324
353
|
if (!value || typeof value !== "object") return false;
|
|
325
354
|
return (value as { sku?: unknown }).sku === sku;
|
|
326
|
-
}) ?? (quantities.size === 1 ? (
|
|
355
|
+
}) ?? (quantities.size === 1 ? (authorities[0] ?? null) : null);
|
|
327
356
|
if (named && typeof named === "object" && "provider" in named && (named as { provider: unknown }).provider !== "mirror") {
|
|
328
357
|
return { ok: false, finding: "authority-unavailable" };
|
|
329
358
|
}
|
|
330
359
|
const mirror = readMirrorAuthority(named);
|
|
331
360
|
if (!mirror || mirror.sku !== sku) {
|
|
332
|
-
return { ok: false, finding:
|
|
361
|
+
return { ok: false, finding: catalogAvailable && isCatalogShape(named) ? "catalog-not-authority" : "authority-unavailable" };
|
|
333
362
|
}
|
|
334
363
|
if (mirror.onHand < quantity) return { ok: false, finding: "stock-unavailable" };
|
|
335
364
|
holds.push({ sku, locationId: mirror.locationId, quantity, onHand: mirror.onHand });
|
|
336
365
|
}
|
|
337
366
|
|
|
338
|
-
|
|
339
|
-
return {
|
|
340
|
-
ok: true,
|
|
341
|
-
digest,
|
|
342
|
-
expiresAt,
|
|
343
|
-
amountMinor,
|
|
344
|
-
holds,
|
|
345
|
-
issuer: input.token.issuer,
|
|
346
|
-
jti: input.token.jti,
|
|
347
|
-
tenantId: input.routedTenantId,
|
|
348
|
-
stage: input.presented.stage,
|
|
349
|
-
};
|
|
367
|
+
return { ok: true, holds };
|
|
350
368
|
}
|
|
@@ -134,6 +134,55 @@ export function bypassesComplianceGate(res: PreflightResponse | null): boolean {
|
|
|
134
134
|
return res !== null && res.gate === "not-required" && res.decision.status === "clear";
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
+
function shopperAccountUrl(preflightUrl: string, endpoint: string): string {
|
|
138
|
+
return preflightUrl.replace(/\/api\/compliance\/preflight$/, `/api/account/${endpoint}`);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function shopperAuthSendUrl(preflightUrl: string): string {
|
|
142
|
+
return shopperAccountUrl(preflightUrl, "auth/send");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export async function isGuestShopper(preflightUrl: string): Promise<boolean> {
|
|
146
|
+
const url = shopperAccountUrl(preflightUrl, "me");
|
|
147
|
+
if (url === preflightUrl) return false;
|
|
148
|
+
|
|
149
|
+
try {
|
|
150
|
+
const response = await fetch(url, { credentials: "same-origin" });
|
|
151
|
+
return response.status === 401 && (await response.json())?.signedIn === false;
|
|
152
|
+
} catch {
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export async function requestFastTrackAccountSave(opts: {
|
|
158
|
+
preflightUrl: string;
|
|
159
|
+
email: string;
|
|
160
|
+
saveForFastTrack: boolean;
|
|
161
|
+
shopperCart: boolean;
|
|
162
|
+
fetchImpl?: typeof fetch;
|
|
163
|
+
}): Promise<boolean> {
|
|
164
|
+
const identifier = opts.email.trim().toLowerCase();
|
|
165
|
+
if (!opts.saveForFastTrack || opts.shopperCart || !identifier) return false;
|
|
166
|
+
|
|
167
|
+
const url = shopperAuthSendUrl(opts.preflightUrl);
|
|
168
|
+
if (url === opts.preflightUrl) return false;
|
|
169
|
+
|
|
170
|
+
try {
|
|
171
|
+
const response = await (opts.fetchImpl ?? fetch)(url, {
|
|
172
|
+
method: "POST",
|
|
173
|
+
headers: { "content-type": "application/json" },
|
|
174
|
+
credentials: "same-origin",
|
|
175
|
+
keepalive: true,
|
|
176
|
+
body: JSON.stringify({ identifier }),
|
|
177
|
+
});
|
|
178
|
+
if (!response.ok) return false;
|
|
179
|
+
await response.json();
|
|
180
|
+
return true;
|
|
181
|
+
} catch {
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
137
186
|
export interface PendingLine {
|
|
138
187
|
form: HTMLFormElement;
|
|
139
188
|
shopperCart: boolean;
|
|
@@ -72,6 +72,8 @@ export interface ReadinessInput {
|
|
|
72
72
|
shipTo?: OrderContactState;
|
|
73
73
|
sourceHolds?: readonly SourceReadiness[];
|
|
74
74
|
payment: PaymentState;
|
|
75
|
+
/** Set only from the current native invoice release receipt. */
|
|
76
|
+
approvedNetTerms?: boolean;
|
|
75
77
|
stock: StockState;
|
|
76
78
|
fulfillment: FulfillmentState;
|
|
77
79
|
label: LabelState;
|
|
@@ -108,13 +110,14 @@ export function releaseHolds(input: ReadinessInput): ReleaseHold[] {
|
|
|
108
110
|
if (input.cancelPending) add(holds, "cancel-pending");
|
|
109
111
|
if (input.fulfillment === "cancelled") add(holds, "cancelled");
|
|
110
112
|
if (input.fulfillment === "UNKNOWN") add(holds, "fulfillment-unknown");
|
|
111
|
-
|
|
113
|
+
const netTerms = input.payment === "authorized" && input.approvedNetTerms === true;
|
|
114
|
+
if (input.payment === "pending" || (input.payment === "authorized" && !netTerms)) add(holds, "payment-pending");
|
|
112
115
|
else if (input.payment === "UNKNOWN" || input.payment === "capture_unknown") add(holds, "payment-unknown");
|
|
113
116
|
else if (input.payment === "refund_requested") add(holds, "refund-pending");
|
|
114
117
|
else if (input.payment === "refunded") add(holds, "refunded");
|
|
115
118
|
else if (input.payment === "refund_unknown") add(holds, "refund-unknown");
|
|
116
119
|
else if (input.payment === "voided") add(holds, "cancelled");
|
|
117
|
-
else if (!paymentIsCaptured(input.payment)) add(holds, "payment-not-captured");
|
|
120
|
+
else if (!netTerms && !paymentIsCaptured(input.payment)) add(holds, "payment-not-captured");
|
|
118
121
|
if (input.stock === "UNKNOWN") add(holds, "stock-unknown");
|
|
119
122
|
else if (input.stock !== "confirmed") add(holds, "stock-unconfirmed");
|
|
120
123
|
if (input.shipTo !== "present" && input.shipTo !== "restricted") {
|
|
@@ -133,7 +136,7 @@ export function handoffRefusal(input: ReadinessInput): ReleaseHold | "adult-sign
|
|
|
133
136
|
if (holds.length > 0) return holds[0] ?? "fulfillment";
|
|
134
137
|
const decision = decideCommerceCommand({
|
|
135
138
|
command: "hand-off",
|
|
136
|
-
payment: input.payment,
|
|
139
|
+
payment: input.payment === "authorized" && input.approvedNetTerms ? "captured" : input.payment,
|
|
137
140
|
stock: input.stock,
|
|
138
141
|
fulfillment: input.fulfillment,
|
|
139
142
|
label: input.label,
|
|
@@ -95,6 +95,8 @@ export interface ReserveInput {
|
|
|
95
95
|
* confirmation and release work unchanged, but no balance bounds it.
|
|
96
96
|
*/
|
|
97
97
|
stockUntracked?: boolean;
|
|
98
|
+
/** A native invoice can renew only an expired reservation, under its scoped purchase guard. */
|
|
99
|
+
manualInvoice?: true;
|
|
98
100
|
}
|
|
99
101
|
|
|
100
102
|
export type ReserveResult =
|
|
@@ -262,10 +264,11 @@ function reserveShape(input: ReserveInput): ReserveResult | null {
|
|
|
262
264
|
}
|
|
263
265
|
|
|
264
266
|
function allocationInsert(input: ReserveInput, hold: ReserveHold, seenAt: string): SqlStatement {
|
|
267
|
+
const currentMirror = Boolean(input.admissionStatement || input.manualInvoice);
|
|
265
268
|
const bound = input.stockUntracked ? "" : `(
|
|
266
269
|
SELECT COALESCE(SUM(quantity), 0) FROM scrappy_allocations
|
|
267
270
|
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ? AND state IN ('reserved', 'confirmed')
|
|
268
|
-
) + ? <= ${
|
|
271
|
+
) + ? <= ${currentMirror
|
|
269
272
|
? `(SELECT COALESCE(SUM(quantity_delta), 0) FROM commerce_inventory_movements
|
|
270
273
|
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?)`
|
|
271
274
|
: "?"}
|
|
@@ -276,7 +279,7 @@ function allocationInsert(input: ReserveInput, hold: ReserveHold, seenAt: string
|
|
|
276
279
|
hold.sku,
|
|
277
280
|
hold.locationId,
|
|
278
281
|
hold.quantity,
|
|
279
|
-
...(
|
|
282
|
+
...(currentMirror
|
|
280
283
|
? [input.tenantId, input.stage, hold.sku, hold.locationId]
|
|
281
284
|
: [hold.onHand]),
|
|
282
285
|
];
|
|
@@ -301,7 +304,9 @@ function allocationInsert(input: ReserveInput, hold: ReserveHold, seenAt: string
|
|
|
301
304
|
WHERE tenant_id = ? AND stage = ? AND order_id = ?
|
|
302
305
|
)
|
|
303
306
|
${input.providerCart ? `AND EXISTS (SELECT 1 FROM commerce_provider_carts WHERE tenant_id=? AND stage=? AND provider=? AND provider_cart_id=? AND authorization_id=? AND provider_cart_digest=?)` : ""}
|
|
304
|
-
ON CONFLICT
|
|
307
|
+
${input.manualInvoice ? `ON CONFLICT(tenant_id,stage,order_id,sku,location_id)
|
|
308
|
+
DO UPDATE SET quantity=excluded.quantity,state='reserved' WHERE scrappy_allocations.state IN ('expired','released')`
|
|
309
|
+
: "ON CONFLICT DO NOTHING"}
|
|
305
310
|
RETURNING order_id`,
|
|
306
311
|
params: [
|
|
307
312
|
input.tenantId,
|
|
@@ -337,7 +342,9 @@ export async function reserveAllocation(runner: StatementRunner, input: ReserveI
|
|
|
337
342
|
const malformed = reserveShape(input);
|
|
338
343
|
if (malformed) return malformed;
|
|
339
344
|
const cart = input.providerCart;
|
|
340
|
-
if (!!cart !== !!input.admissionStatement
|
|
345
|
+
if (!!cart !== !!input.admissionStatement || (input.manualInvoice && (!input.authorizationGuard || cart))) {
|
|
346
|
+
return { ok: false, finding: "malformed-request" };
|
|
347
|
+
}
|
|
341
348
|
if (cart && (!input.admissionStatement || cart.provider !== "foxycart" || !/^[a-zA-Z0-9._:-]{1,128}$/.test(cart.id) || !DIGEST_RE.test(cart.digest) ||
|
|
342
349
|
(cart.expectedAuthorizationId !== undefined && !ID_RE.test(cart.expectedAuthorizationId)))) return { ok: false, finding: "malformed-request" };
|
|
343
350
|
const seen = await runner.all(
|
|
@@ -392,7 +399,10 @@ export async function reserveAllocation(runner: StatementRunner, input: ReserveI
|
|
|
392
399
|
SELECT 1 FROM scrappy_caller_replay
|
|
393
400
|
WHERE tenant_id = ? AND stage = ? AND issuer = ? AND jti = ? AND seen_at = ?
|
|
394
401
|
)
|
|
395
|
-
ON CONFLICT
|
|
402
|
+
${input.manualInvoice ? `ON CONFLICT(tenant_id,stage,authorization_id)
|
|
403
|
+
DO UPDATE SET cart_digest=excluded.cart_digest,expires_at=excluded.expires_at,state='active'
|
|
404
|
+
WHERE scrappy_final_cart_authorizations.state='expired'`
|
|
405
|
+
: "ON CONFLICT DO NOTHING"}
|
|
396
406
|
RETURNING authorization_id`,
|
|
397
407
|
params: [
|
|
398
408
|
input.tenantId,
|
|
@@ -780,13 +790,12 @@ function rowsScope(rows: readonly Record<string, unknown>[]): AvailabilityScope
|
|
|
780
790
|
return itemScope(rows.map((row) => ({ sku: text(row, "sku"), locationId: text(row, "location_id") })));
|
|
781
791
|
}
|
|
782
792
|
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
): Promise<{ decremented: number; states: string[] }> {
|
|
793
|
+
type ConfirmHoldInput = { tenantId: string; stage: CommerceStage; orderId: string; requireUnexpired?: true };
|
|
794
|
+
|
|
795
|
+
/** The stock writes callers can compose into the transaction that authorizes payment. */
|
|
796
|
+
export function confirmHoldStatements(input: ConfirmHoldInput): SqlStatement[] {
|
|
788
797
|
const scope = [input.tenantId, input.stage, input.orderId];
|
|
789
|
-
|
|
798
|
+
return [
|
|
790
799
|
{
|
|
791
800
|
sql: `UPDATE scrappy_allocations
|
|
792
801
|
SET state = 'confirmed'
|
|
@@ -800,6 +809,7 @@ export async function confirmHoldOnce(
|
|
|
800
809
|
AND EXISTS (
|
|
801
810
|
SELECT 1 FROM scrappy_final_cart_authorizations
|
|
802
811
|
WHERE tenant_id = ? AND stage = ? AND authorization_id = ? AND state = 'active'
|
|
812
|
+
${input.requireUnexpired ? "AND julianday(expires_at) > julianday('now')" : ""}
|
|
803
813
|
)
|
|
804
814
|
RETURNING sku, location_id, quantity`,
|
|
805
815
|
params: [...scope, ...scope, ...scope],
|
|
@@ -828,6 +838,18 @@ export async function confirmHoldOnce(
|
|
|
828
838
|
RETURNING order_id`,
|
|
829
839
|
params: [...scope, ...scope],
|
|
830
840
|
},
|
|
841
|
+
];
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
/** Move reserved units to confirmed once. A second call decrements nothing. */
|
|
845
|
+
export async function confirmHoldOnce(
|
|
846
|
+
runner: StatementRunner,
|
|
847
|
+
input: ConfirmHoldInput,
|
|
848
|
+
): Promise<{ decremented: number; states: string[] }> {
|
|
849
|
+
const scope = [input.tenantId, input.stage, input.orderId];
|
|
850
|
+
const statements = confirmHoldStatements(input);
|
|
851
|
+
const results = await runner.batch([
|
|
852
|
+
...statements,
|
|
831
853
|
{
|
|
832
854
|
sql: `SELECT state, sku, location_id FROM scrappy_allocations
|
|
833
855
|
WHERE tenant_id = ? AND stage = ? AND order_id = ?`,
|
|
@@ -835,7 +857,7 @@ export async function confirmHoldOnce(
|
|
|
835
857
|
},
|
|
836
858
|
]);
|
|
837
859
|
const confirmedRows = results[0] ?? [];
|
|
838
|
-
const allAllocations = results[
|
|
860
|
+
const allAllocations = results[statements.length] ?? [];
|
|
839
861
|
const confirmedTargets = new Map<string, { sku: string; locationId: string }>();
|
|
840
862
|
for (const row of allAllocations) {
|
|
841
863
|
if (text(row, "state") !== "confirmed") continue;
|
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
import { skuFromToken } from "@tot/public-runtime/sku";
|
|
10
10
|
import { fromD1 } from "@/lib/catalog/d1/catalog.js";
|
|
11
11
|
import { readD1, readEnv, readKv } from "@/lib/publication/shared/env";
|
|
12
|
-
import { evaluateFinalCart, type RefusedLine, type SeamView } from "@/lib/checkout/commerce/finalCartAuthorization.js";
|
|
12
|
+
import { CHECKOUT_ADMISSION_TTL_MS, FULFILLMENT_EVIDENCE_TTL_MS, evaluateFinalCart, type RefusedLine, type SeamView } from "@/lib/checkout/commerce/finalCartAuthorization.js";
|
|
13
13
|
import { d1CommerceRunner, reserveAllocation } from "@/lib/inventory/allocations.js";
|
|
14
14
|
import { readMirrorBalance, readMirrorStock, writeAvailabilityProjection } from "@/lib/inventory/mirrorStock.js";
|
|
15
15
|
import { publicAvailabilityPublisher } from "@/lib/inventory/publicAvailabilityRuntime";
|
|
@@ -35,10 +35,6 @@ import { shopperVariantPrice } from "@/lib/customers/accounts/pricing";
|
|
|
35
35
|
import { resolveShopperAccessPolicy } from "@tot/public-runtime/declared-tenant-config";
|
|
36
36
|
export const prerender = false;
|
|
37
37
|
const HEX = /^[a-f0-9]{64}$/;
|
|
38
|
-
/** Checkout authorization window (reservation + payment completion). */
|
|
39
|
-
const CHECKOUT_ADMISSION_TTL_MS = 5 * 60_000;
|
|
40
|
-
/** Post-capture compliance evidence validity horizon for order fulfillment. */
|
|
41
|
-
const FULFILLMENT_EVIDENCE_TTL_MS = 30 * 24 * 60 * 60_000;
|
|
42
38
|
/** The shopper's verification correlation handle, as the signed `verification` cart option carries it. */
|
|
43
39
|
const VERIFICATION_REF = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,199}$/;
|
|
44
40
|
function json(body: unknown, status = 200): Response {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "7.8.
|
|
3
|
+
"version": "7.8.9",
|
|
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",
|