@tokenoftrust/storefront-runner 7.6.1 → 7.6.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/src/lib/access/auth/brokerAssertion.ts +1 -67
- package/apps/storefront/src/lib/access/auth/session.ts +17 -0
- package/apps/storefront/src/lib/checkout/agent/checkoutSession.ts +26 -17
- package/apps/storefront/src/lib/checkout/commerce/assistantOrderEvidence.ts +215 -0
- package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +1 -1
- package/apps/storefront/src/lib/checkout/proposal/cartProposal.ts +31 -5
- package/apps/storefront/src/lib/checkout/proposal/proposalRoutes.ts +123 -6
- package/apps/storefront/src/lib/checkout/shared/intakeSuspend.ts +21 -0
- package/apps/storefront/src/lib/fulfillment/carrierEvidence.ts +105 -0
- package/apps/storefront/src/lib/fulfillment/readiness.ts +217 -0
- package/apps/storefront/src/lib/orders/data/sourceAuthorityContract.ts +380 -0
- package/apps/storefront/src/lib/orders/data/sourceAuthorityStore.ts +830 -0
- package/apps/storefront/src/pages/api/cart-proposal/confirm.ts +6 -1
- package/package.json +1 -1
|
@@ -26,8 +26,17 @@ import {
|
|
|
26
26
|
type TenantConfig,
|
|
27
27
|
} from "@tot/public-runtime";
|
|
28
28
|
import { addProposalToBoundCart, CART_UNAVAILABLE_MESSAGE, withCartSession } from "@/lib/checkout/commerce/cartSession";
|
|
29
|
-
import { completeCartFields, ledgerSoldOut, trustedReturnUrl } from "@/lib/checkout/commerce/checkoutHandoffRoute";
|
|
29
|
+
import { completeCartFields, ledgerSoldOut, ledgerStage, trustedReturnUrl } from "@/lib/checkout/commerce/checkoutHandoffRoute";
|
|
30
|
+
import {
|
|
31
|
+
attributionEventStatement,
|
|
32
|
+
attributionLogLine,
|
|
33
|
+
originBindingStatement,
|
|
34
|
+
type AttributionMetric,
|
|
35
|
+
} from "@/lib/checkout/commerce/assistantOrderEvidence";
|
|
30
36
|
import { resolveCartSigning, shopperCartDenialMessage, type CartSigningResolution } from "@/lib/checkout/shared/checkoutCommerce";
|
|
37
|
+
import { ASSISTANT_INTAKE_SUSPENDED_MESSAGE, agentIntakeSuspended } from "@/lib/checkout/shared/intakeSuspend";
|
|
38
|
+
import { fromD1, type Queryable } from "@/lib/catalog/d1/catalog";
|
|
39
|
+
import { readD1 } from "@/lib/publication/shared/env";
|
|
31
40
|
import {
|
|
32
41
|
catalogEntries,
|
|
33
42
|
decodeProposalId,
|
|
@@ -40,6 +49,8 @@ import {
|
|
|
40
49
|
validateReviewRequest,
|
|
41
50
|
type ProposalCatalog,
|
|
42
51
|
type ProposalRequestLine,
|
|
52
|
+
type ProposalSource,
|
|
53
|
+
type ProposalToken,
|
|
43
54
|
} from "./cartProposal";
|
|
44
55
|
import { matchList } from "./listMatcher";
|
|
45
56
|
import { renderPasteForm, renderRefusal, renderReview, type ReviewView } from "./reviewHtml";
|
|
@@ -61,9 +72,15 @@ export interface ProposalDeps {
|
|
|
61
72
|
/** The compliance preflight of the reviewed lines; null when it cannot be evaluated. */
|
|
62
73
|
preflight?: (context: APIContext, lines: readonly CartProposalLine[]) => Promise<ProposalCompliance | null>;
|
|
63
74
|
fetch?: typeof fetch;
|
|
75
|
+
/** True when the store has paused assistant and agent intake. Read before any other work. */
|
|
76
|
+
intakeSuspended?: (context: APIContext) => Promise<boolean>;
|
|
77
|
+
/** The apps database the origin and attribution rows live in; null when it is not bound. */
|
|
78
|
+
attributionDb?: () => Promise<Queryable | null>;
|
|
64
79
|
}
|
|
65
80
|
|
|
66
81
|
export interface ConfirmDeps extends ProposalDeps {
|
|
82
|
+
/** Whether the tenant's own compliance declaration requires an adult signature at delivery. */
|
|
83
|
+
adultSignatureRequired: (context: APIContext) => boolean;
|
|
67
84
|
/**
|
|
68
85
|
* The path of a product's own page in the tenant's declared URL form. Supplied by the route so
|
|
69
86
|
* the checkout capability does not import the content capability's URL rules. Confirm signs it as
|
|
@@ -134,6 +151,93 @@ function refuse(context: APIContext, refusal: Refusal, event: string): Response
|
|
|
134
151
|
return htmlReply(renderRefusal(refusal.code, refusal.message), refusal.status);
|
|
135
152
|
}
|
|
136
153
|
|
|
154
|
+
async function suspendedRefusal(context: APIContext, deps: ProposalDeps, event: string): Promise<Response | null> {
|
|
155
|
+
if (!(await (deps.intakeSuspended ?? agentIntakeSuspended)(context))) return null;
|
|
156
|
+
return refuse(context, { status: 503, code: "commerce_unavailable", message: ASSISTANT_INTAKE_SUSPENDED_MESSAGE }, event);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function appsDatabase(deps: ProposalDeps): Promise<Queryable | null> {
|
|
160
|
+
if (deps.attributionDb) return deps.attributionDb();
|
|
161
|
+
const database = await readD1("STOREFRONT_APPS_DB");
|
|
162
|
+
return database ? fromD1(database) : null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Record one proposal-created or checkout-started event. A store with no apps database, or a write
|
|
167
|
+
* that fails, never changes the shopper's response: the failure is logged with a closed code.
|
|
168
|
+
*/
|
|
169
|
+
export async function recordAttribution(
|
|
170
|
+
context: APIContext,
|
|
171
|
+
deps: ProposalDeps,
|
|
172
|
+
input: { metric: AttributionMetric; source: ProposalSource; token: ProposalToken; digest: string },
|
|
173
|
+
): Promise<void> {
|
|
174
|
+
const stage = ledgerStage(context.locals.customizationEnv);
|
|
175
|
+
if (!stage) return;
|
|
176
|
+
try {
|
|
177
|
+
const db = await appsDatabase(deps);
|
|
178
|
+
if (!db) return;
|
|
179
|
+
const now = new Date((deps.now ?? (() => Math.floor(Date.now() / 1000)))() * 1000).toISOString();
|
|
180
|
+
const statement = attributionEventStatement({
|
|
181
|
+
tenantId: commerceTenantId(context.locals.tenant),
|
|
182
|
+
stage,
|
|
183
|
+
metric: input.metric,
|
|
184
|
+
eventKey: await proposalReplayKey(input.token, input.digest),
|
|
185
|
+
source: input.source,
|
|
186
|
+
now,
|
|
187
|
+
});
|
|
188
|
+
await db.run(statement.sql, ...(statement.params ?? []));
|
|
189
|
+
console.info(attributionLogLine({
|
|
190
|
+
tenant: context.locals.tenant.tenant_id,
|
|
191
|
+
stage,
|
|
192
|
+
source: input.source,
|
|
193
|
+
metric: input.metric,
|
|
194
|
+
recorded: true,
|
|
195
|
+
}));
|
|
196
|
+
} catch (error) {
|
|
197
|
+
console.warn(`[storefront] assistant-attribution ${JSON.stringify({
|
|
198
|
+
tenant: context.locals.tenant.tenant_id,
|
|
199
|
+
code: error instanceof Error && error.message.startsWith("invalid-") ? error.message : "write-failed",
|
|
200
|
+
})}`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Bind the provider cart a proposal was confirmed into to its origin. Source and agent label come
|
|
206
|
+
* from the signed proposal token, the adult-signature requirement from the tenant's own declaration
|
|
207
|
+
* and the digest from the reviewed offer; nothing comes from the request. A failed write is logged
|
|
208
|
+
* with a closed code and does not change the shopper's response.
|
|
209
|
+
*/
|
|
210
|
+
async function bindOrigin(
|
|
211
|
+
context: APIContext,
|
|
212
|
+
deps: ConfirmDeps,
|
|
213
|
+
input: { token: ProposalToken; digest: string; providerCartId: string },
|
|
214
|
+
): Promise<void> {
|
|
215
|
+
const stage = ledgerStage(context.locals.customizationEnv);
|
|
216
|
+
if (!stage) return;
|
|
217
|
+
try {
|
|
218
|
+
const db = await appsDatabase(deps);
|
|
219
|
+
if (!db) return;
|
|
220
|
+
const now = new Date((deps.now ?? (() => Math.floor(Date.now() / 1000)))() * 1000).toISOString();
|
|
221
|
+
const statement = originBindingStatement({
|
|
222
|
+
tenantId: commerceTenantId(context.locals.tenant),
|
|
223
|
+
stage,
|
|
224
|
+
provider: "foxycart",
|
|
225
|
+
providerCartId: input.providerCartId,
|
|
226
|
+
source: input.token.source,
|
|
227
|
+
...(input.token.agentLabel ? { agentLabel: input.token.agentLabel } : {}),
|
|
228
|
+
approvedCartDigest: input.digest,
|
|
229
|
+
adultSignatureRequired: deps.adultSignatureRequired(context),
|
|
230
|
+
now,
|
|
231
|
+
});
|
|
232
|
+
await db.run(statement.sql, ...(statement.params ?? []));
|
|
233
|
+
} catch (error) {
|
|
234
|
+
console.warn(`[storefront] assistant-origin ${JSON.stringify({
|
|
235
|
+
tenant: context.locals.tenant.tenant_id,
|
|
236
|
+
code: error instanceof Error && error.message.startsWith("invalid-") ? error.message : "write-failed",
|
|
237
|
+
})}`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
137
241
|
/** The parsed request body: JSON or a urlencoded form, bounded. `null` is an unreadable body. */
|
|
138
242
|
export async function readBody(request: Request): Promise<Record<string, unknown> | unknown[] | null> {
|
|
139
243
|
const type = request.headers.get("content-type") ?? "";
|
|
@@ -245,6 +349,8 @@ export function cartProposalForm(context: APIContext): Response {
|
|
|
245
349
|
* availability. Reads only: confirming stays the same-origin POST.
|
|
246
350
|
*/
|
|
247
351
|
export async function cartProposalOpen(context: APIContext, deps: ProposalDeps = {}): Promise<Response> {
|
|
352
|
+
const suspended = await suspendedRefusal(context, deps, "open-suspended");
|
|
353
|
+
if (suspended) return suspended;
|
|
248
354
|
const id = new URL(context.request.url).searchParams.get(CART_PROPOSAL_ID_PARAM);
|
|
249
355
|
if (id === null) return cartProposalForm(context);
|
|
250
356
|
const { tenant, commerce } = context.locals;
|
|
@@ -311,6 +417,8 @@ export async function cartProposalOpen(context: APIContext, deps: ProposalDeps =
|
|
|
311
417
|
|
|
312
418
|
/** POST: resolve an assistant's lines into a reviewable offer. Reads only; changes no cart. */
|
|
313
419
|
export async function cartProposalReview(context: APIContext, deps: ProposalDeps = {}): Promise<Response> {
|
|
420
|
+
const suspended = await suspendedRefusal(context, deps, "review-suspended");
|
|
421
|
+
if (suspended) return suspended;
|
|
314
422
|
const { tenant, commerce } = context.locals;
|
|
315
423
|
if (!commerce) {
|
|
316
424
|
return refuse(context, { status: 409, code: "commerce_unavailable", message: NO_COMMERCE_MESSAGE }, "review-refused");
|
|
@@ -357,13 +465,15 @@ export async function cartProposalReview(context: APIContext, deps: ProposalDeps
|
|
|
357
465
|
...(sourceText ? { text: sourceText[item.index] ?? "" } : {}),
|
|
358
466
|
}));
|
|
359
467
|
const issuedAt = (deps.now ?? (() => Math.floor(Date.now() / 1000)))();
|
|
468
|
+
const minted: ProposalToken = {
|
|
469
|
+
tenant: tenant.tot_data_scope,
|
|
470
|
+
issuedAt,
|
|
471
|
+
lines: resolved.lines.map((line) => ({ variantId: line.variantId, quantity: line.quantity })),
|
|
472
|
+
source: "assistant",
|
|
473
|
+
};
|
|
360
474
|
const proposal = resolved.lines.length > 0
|
|
361
475
|
? {
|
|
362
|
-
id: await encodeProposalId(
|
|
363
|
-
tenant: tenant.tot_data_scope,
|
|
364
|
-
issuedAt,
|
|
365
|
-
lines: resolved.lines.map((line) => ({ variantId: line.variantId, quantity: line.quantity })),
|
|
366
|
-
}, proposalIdKey(signing.secret)),
|
|
476
|
+
id: await encodeProposalId(minted, proposalIdKey(signing.secret)),
|
|
367
477
|
digest: resolved.digest,
|
|
368
478
|
issuedAt,
|
|
369
479
|
expiresAt: issuedAt + CART_PROPOSAL_TTL_SECONDS,
|
|
@@ -388,6 +498,9 @@ export async function cartProposalReview(context: APIContext, deps: ProposalDeps
|
|
|
388
498
|
refused: resolved.refused.length,
|
|
389
499
|
unmatched: unmatched.length,
|
|
390
500
|
});
|
|
501
|
+
if (proposal) {
|
|
502
|
+
await recordAttribution(context, deps, { metric: "proposals-created", source: "assistant", token: minted, digest: proposal.digest });
|
|
503
|
+
}
|
|
391
504
|
|
|
392
505
|
const status = proposal ? 200 : 422;
|
|
393
506
|
if (wantsJson(context.request)) {
|
|
@@ -407,6 +520,8 @@ export async function cartProposalReview(context: APIContext, deps: ProposalDeps
|
|
|
407
520
|
|
|
408
521
|
/** POST: hand a reviewed proposal into the signed cart. Takes only `{proposalId, digest}`. */
|
|
409
522
|
export async function cartProposalConfirm(context: APIContext, deps: ConfirmDeps): Promise<Response> {
|
|
523
|
+
const suspended = await suspendedRefusal(context, deps, "confirm-suspended");
|
|
524
|
+
if (suspended) return suspended;
|
|
410
525
|
const { tenant, commerce } = context.locals;
|
|
411
526
|
if (!sameOrigin(context)) {
|
|
412
527
|
return refuse(context, { status: 403, code: "cross_origin", message: "This request cannot be accepted." }, "confirm-refused");
|
|
@@ -508,6 +623,8 @@ export async function cartProposalConfirm(context: APIContext, deps: ConfirmDeps
|
|
|
508
623
|
if (!added) {
|
|
509
624
|
return refuse(context, { status: 503, code: "cart_unavailable", message: CART_UNAVAILABLE_MESSAGE }, "confirm-refused");
|
|
510
625
|
}
|
|
626
|
+
await bindOrigin(context, deps, { token, digest: validated.digest, providerCartId: added.id });
|
|
627
|
+
await recordAttribution(context, deps, { metric: "checkouts-started", source: token.source, token, digest: validated.digest });
|
|
511
628
|
const location = withCartSession(commerce.cartUrl, added.id);
|
|
512
629
|
logProposal(context, "confirmed", { lines: live.lines.length, replayed: added.replayed });
|
|
513
630
|
if (wantsJson(context.request)) {
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ops stop control for assistant and agent order intake: one declared binding, read per request
|
|
3
|
+
* before any other work. While it reads `suspended`, new assistant proposals and agent checkout
|
|
4
|
+
* sessions are refused with a shopper message. The ordinary product page, cart and checkout path
|
|
5
|
+
* never read it.
|
|
6
|
+
*/
|
|
7
|
+
import { readEnv } from "@/lib/publication/shared/runtimeEnv";
|
|
8
|
+
|
|
9
|
+
export const AGENT_INTAKE_SUSPENDED_MESSAGE = "This store is not accepting agent checkout requests right now.";
|
|
10
|
+
export const ASSISTANT_INTAKE_SUSPENDED_MESSAGE =
|
|
11
|
+
"This store is not accepting assistant order requests right now. You can still order from the store's product pages.";
|
|
12
|
+
|
|
13
|
+
/** True when the store has paused assistant and agent intake. A binding that cannot be read refuses. */
|
|
14
|
+
export async function agentIntakeSuspended(): Promise<boolean> {
|
|
15
|
+
try {
|
|
16
|
+
return (await readEnv("AGENT_CHECKOUT_INTAKE")) === "suspended";
|
|
17
|
+
} catch (error) {
|
|
18
|
+
console.warn("[storefront] intake-suspend binding unreadable; refusing intake", error instanceof Error ? error.name : "error");
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Carrier evidence a fulfillment processor reports, from one declarative carrier catalog.
|
|
3
|
+
*
|
|
4
|
+
* `trackingHosts` are carrier-owned tracking domains, used only as a fail-closed allowlist for
|
|
5
|
+
* app-supplied tracking URLs; the same allowlist validates an app's write and gates the merchant
|
|
6
|
+
* desk's tracking link. Tracking URLs are never fetched.
|
|
7
|
+
*
|
|
8
|
+
* `pactEligible` is statutory eligibility only: whether the carrier may carry ENDS parcels at all
|
|
9
|
+
* (the POSTAL Act's mailability ban rules out USPS). Carrier contract terms for regulated parcels
|
|
10
|
+
* belong to the tenant's carrier account, not to this catalog.
|
|
11
|
+
*/
|
|
12
|
+
export type CarrierAdultSignature = "required" | "supported" | "unsupported";
|
|
13
|
+
|
|
14
|
+
export interface CarrierCatalogEntry {
|
|
15
|
+
readonly code: string;
|
|
16
|
+
readonly name: string;
|
|
17
|
+
readonly region: "US";
|
|
18
|
+
readonly pactEligible: boolean;
|
|
19
|
+
readonly adultSignature: CarrierAdultSignature;
|
|
20
|
+
readonly trackingHosts: readonly string[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const CARRIER_CATALOG = [
|
|
24
|
+
{ code: "UPS", name: "UPS", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.ups.com"] },
|
|
25
|
+
{ code: "FEDEX", name: "FedEx", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.fedex.com"] },
|
|
26
|
+
{ code: "USPS", name: "USPS", region: "US", pactEligible: false, adultSignature: "supported", trackingHosts: ["tools.usps.com"] },
|
|
27
|
+
{ code: "DHL", name: "DHL", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.dhl.com"] },
|
|
28
|
+
{ code: "ONTRAC", name: "OnTrac", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.ontrac.com"] },
|
|
29
|
+
{ code: "LSO", name: "Lone Star Overnight", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.lso.com"] },
|
|
30
|
+
{ code: "BETTER_TRUCKS", name: "Better Trucks", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.bettertrucks.com"] },
|
|
31
|
+
{ code: "GLS_US", name: "GLS US", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.gls-us.com"] },
|
|
32
|
+
{ code: "SPEE_DEE", name: "Spee-Dee Delivery", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.speedeedelivery.com"] },
|
|
33
|
+
{ code: "STAT_OVERNIGHT", name: "Stat Overnight", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.statovernight.com"] },
|
|
34
|
+
] as const satisfies readonly CarrierCatalogEntry[];
|
|
35
|
+
|
|
36
|
+
export type CarrierCode = (typeof CARRIER_CATALOG)[number]["code"];
|
|
37
|
+
|
|
38
|
+
export const CARRIER_CODES: readonly CarrierCode[] = Object.freeze(CARRIER_CATALOG.map((entry) => entry.code));
|
|
39
|
+
|
|
40
|
+
export const CARRIER_TRACKING_HOSTS: Readonly<Record<CarrierCode, readonly string[]>> = Object.freeze(
|
|
41
|
+
Object.fromEntries(CARRIER_CATALOG.map((entry): [string, readonly string[]] => [entry.code, entry.trackingHosts])) as Record<
|
|
42
|
+
CarrierCode,
|
|
43
|
+
readonly string[]
|
|
44
|
+
>,
|
|
45
|
+
);
|
|
46
|
+
|
|
47
|
+
export const TRACKING_NUMBER = /^[A-Z0-9]{6,40}$/;
|
|
48
|
+
export const CARRIER_SERVICE = /^[A-Z0-9_]{1,40}$/;
|
|
49
|
+
export const TRACKING_URL_MAX = 2048;
|
|
50
|
+
export const TRACKING_PART_MAX = 512;
|
|
51
|
+
|
|
52
|
+
/** The canonical form every carrier comparison uses: trimmed and uppercased. */
|
|
53
|
+
export function canonicalCarrier(value: string): string {
|
|
54
|
+
return value.trim().toUpperCase();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A supplied carrier as its canonical code, or null when it is not in the closed set. */
|
|
58
|
+
export function parseCarrierCode(value: unknown): CarrierCode | null {
|
|
59
|
+
if (typeof value !== "string") return null;
|
|
60
|
+
const canonical = canonicalCarrier(value);
|
|
61
|
+
return (CARRIER_CODES as readonly string[]).includes(canonical) ? (canonical as CarrierCode) : null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The tracking hosts allowed for `carrier`; none for a value outside the closed set. */
|
|
65
|
+
export function trackingHostsFor(carrier: unknown): readonly string[] {
|
|
66
|
+
const code = parseCarrierCode(carrier);
|
|
67
|
+
return code ? CARRIER_TRACKING_HOSTS[code] : [];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* True when `url` is an https URL on one of `carrier`'s tracking hosts: at most 2048 characters,
|
|
72
|
+
* printable ASCII only, the authority exactly an allowed host (so no userinfo, port or IP literal),
|
|
73
|
+
* no fragment, and a path and query of at most 512 characters each.
|
|
74
|
+
*/
|
|
75
|
+
export function trackingUrlAllowed(carrier: unknown, url: unknown): url is string {
|
|
76
|
+
if (typeof url !== "string" || url.length > TRACKING_URL_MAX) return false;
|
|
77
|
+
if (!/^[\x21-\x7e]+$/.test(url) || url.includes("#") || url.includes("\\")) return false;
|
|
78
|
+
if (!url.startsWith("https://")) return false;
|
|
79
|
+
const authority = url.slice("https://".length).split(/[/?]/, 1)[0] ?? "";
|
|
80
|
+
if (!trackingHostsFor(carrier).includes(authority)) return false;
|
|
81
|
+
let parsed: URL;
|
|
82
|
+
try {
|
|
83
|
+
parsed = new URL(url);
|
|
84
|
+
} catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
if (parsed.protocol !== "https:" || parsed.username !== "" || parsed.password !== "" || parsed.port !== "") return false;
|
|
88
|
+
if (parsed.host !== authority || parsed.hash !== "") return false;
|
|
89
|
+
return parsed.pathname.length <= TRACKING_PART_MAX && parsed.search.replace(/^\?/, "").length <= TRACKING_PART_MAX;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The catalog entry for `carrier` in canonical form, or null when the catalog does not declare it. */
|
|
93
|
+
export function carrierCatalogEntry(
|
|
94
|
+
carrier: string,
|
|
95
|
+
catalog: readonly CarrierCatalogEntry[] = CARRIER_CATALOG,
|
|
96
|
+
): CarrierCatalogEntry | null {
|
|
97
|
+
const canonical = canonicalCarrier(carrier);
|
|
98
|
+
return catalog.find((entry) => entry.code === canonical) ?? null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** True when `carrier` is in either prohibited set, both compared in canonical form. */
|
|
102
|
+
export function carrierProhibited(carrier: string, ...prohibited: ReadonlyArray<readonly string[]>): boolean {
|
|
103
|
+
const canonical = canonicalCarrier(carrier);
|
|
104
|
+
return prohibited.some((set) => set.some((item) => canonicalCarrier(item) === canonical));
|
|
105
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Release and hand-off gates for whole-order fulfillment.
|
|
3
|
+
*
|
|
4
|
+
* Evidence, payment, stock, refund, and cancel are rechecked from stored source
|
|
5
|
+
* truth. Compliance `fresh` is not evidence. A carrier account is tenant
|
|
6
|
+
* configuration: its absence is not a hold, and this module does not select a vendor.
|
|
7
|
+
*/
|
|
8
|
+
import {
|
|
9
|
+
decideCommerceCommand,
|
|
10
|
+
paymentIsCaptured,
|
|
11
|
+
type CommerceEvidence,
|
|
12
|
+
type ComplianceRuleProfile,
|
|
13
|
+
type EvidenceState,
|
|
14
|
+
type FulfillmentState,
|
|
15
|
+
type LabelState,
|
|
16
|
+
type PaymentState,
|
|
17
|
+
type ProviderOutcome,
|
|
18
|
+
type StockState,
|
|
19
|
+
type OrderContactState,
|
|
20
|
+
} from "@tot/public-runtime";
|
|
21
|
+
import type { SourceReadiness } from "../orders/data/sourceAuthorityStore.js";
|
|
22
|
+
import { COMPLIANCE_RULE_PROFILES } from "@/config/compliance/rulesets";
|
|
23
|
+
import {
|
|
24
|
+
CARRIER_CATALOG,
|
|
25
|
+
canonicalCarrier,
|
|
26
|
+
carrierCatalogEntry,
|
|
27
|
+
carrierProhibited,
|
|
28
|
+
type CarrierCatalogEntry,
|
|
29
|
+
type CarrierCode,
|
|
30
|
+
} from "./carrierEvidence.js";
|
|
31
|
+
|
|
32
|
+
export const RELEASE_HOLDS = [
|
|
33
|
+
"source-check-pending",
|
|
34
|
+
"source-ledger-conflict",
|
|
35
|
+
"source-authority-unreadable",
|
|
36
|
+
"source-authority-unavailable",
|
|
37
|
+
"source-sync-pending",
|
|
38
|
+
"evidence-unknown",
|
|
39
|
+
"evidence-stale",
|
|
40
|
+
"evidence-unreadable",
|
|
41
|
+
"evidence-absent",
|
|
42
|
+
"operator-hold",
|
|
43
|
+
"payment-pending",
|
|
44
|
+
"payment-unknown",
|
|
45
|
+
"payment-not-captured",
|
|
46
|
+
"refund-pending",
|
|
47
|
+
"refunded",
|
|
48
|
+
"refund-unknown",
|
|
49
|
+
"cancel-pending",
|
|
50
|
+
"cancelled",
|
|
51
|
+
"stock-unknown",
|
|
52
|
+
"stock-unconfirmed",
|
|
53
|
+
"fulfillment-unknown",
|
|
54
|
+
"ship-to-absent",
|
|
55
|
+
"ship-to-expired",
|
|
56
|
+
"ship-to-erased",
|
|
57
|
+
"ship-to-unreadable",
|
|
58
|
+
] as const;
|
|
59
|
+
|
|
60
|
+
export type ReleaseHold = (typeof RELEASE_HOLDS)[number];
|
|
61
|
+
|
|
62
|
+
export interface CarrierPolicy {
|
|
63
|
+
adultSignatureRequired: boolean;
|
|
64
|
+
/** The tenant's compliance profile enables PACT: only statutorily eligible carriers may carry its parcels. */
|
|
65
|
+
pactEnabled: boolean;
|
|
66
|
+
prohibitedCarriers: readonly string[];
|
|
67
|
+
/** Null when the tenant has not configured an account. Absence is not a hold. */
|
|
68
|
+
carrierAccountId: string | null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface ReadinessInput {
|
|
72
|
+
shipTo?: OrderContactState;
|
|
73
|
+
sourceHolds?: readonly SourceReadiness[];
|
|
74
|
+
payment: PaymentState;
|
|
75
|
+
stock: StockState;
|
|
76
|
+
fulfillment: FulfillmentState;
|
|
77
|
+
label: LabelState;
|
|
78
|
+
evidence: CommerceEvidence;
|
|
79
|
+
operatorHold: boolean;
|
|
80
|
+
cancelPending: boolean;
|
|
81
|
+
providerOutcome: ProviderOutcome | null;
|
|
82
|
+
adultSignature: "accepted" | "refused" | "absent";
|
|
83
|
+
adultSignatureRequired: boolean;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const EVIDENCE_HOLDS: Record<EvidenceState, ReleaseHold | null> = {
|
|
87
|
+
fresh: null,
|
|
88
|
+
"not-required": null,
|
|
89
|
+
"not-computed": null,
|
|
90
|
+
UNKNOWN: "evidence-unknown",
|
|
91
|
+
stale: "evidence-stale",
|
|
92
|
+
unreadable: "evidence-unreadable",
|
|
93
|
+
absent: "evidence-absent",
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
function add(holds: ReleaseHold[], hold: ReleaseHold | null): void {
|
|
97
|
+
if (hold && !holds.includes(hold)) holds.push(hold);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Holds that forbid creating a shipment intent. Compliance is not an input. */
|
|
101
|
+
export function releaseHolds(input: ReadinessInput): ReleaseHold[] {
|
|
102
|
+
const holds: ReleaseHold[] = [...(input.sourceHolds ?? [])];
|
|
103
|
+
for (const field of ["verification", "tax", "risk", "stock"] as const) {
|
|
104
|
+
const value = input.evidence[field];
|
|
105
|
+
add(holds, value in EVIDENCE_HOLDS ? EVIDENCE_HOLDS[value as EvidenceState] : "evidence-unreadable");
|
|
106
|
+
}
|
|
107
|
+
if (input.operatorHold) add(holds, "operator-hold");
|
|
108
|
+
if (input.cancelPending) add(holds, "cancel-pending");
|
|
109
|
+
if (input.fulfillment === "cancelled") add(holds, "cancelled");
|
|
110
|
+
if (input.fulfillment === "UNKNOWN") add(holds, "fulfillment-unknown");
|
|
111
|
+
if (input.payment === "pending" || input.payment === "authorized") add(holds, "payment-pending");
|
|
112
|
+
else if (input.payment === "UNKNOWN" || input.payment === "capture_unknown") add(holds, "payment-unknown");
|
|
113
|
+
else if (input.payment === "refund_requested") add(holds, "refund-pending");
|
|
114
|
+
else if (input.payment === "refunded") add(holds, "refunded");
|
|
115
|
+
else if (input.payment === "refund_unknown") add(holds, "refund-unknown");
|
|
116
|
+
else if (input.payment === "voided") add(holds, "cancelled");
|
|
117
|
+
else if (!paymentIsCaptured(input.payment)) add(holds, "payment-not-captured");
|
|
118
|
+
if (input.stock === "UNKNOWN") add(holds, "stock-unknown");
|
|
119
|
+
else if (input.stock !== "confirmed") add(holds, "stock-unconfirmed");
|
|
120
|
+
if (input.shipTo !== "present" && input.shipTo !== "restricted") {
|
|
121
|
+
add(holds, input.shipTo === "absent" ? "ship-to-absent" : input.shipTo === "expired" ? "ship-to-expired" :
|
|
122
|
+
input.shipTo === "erased" ? "ship-to-erased" : "ship-to-unreadable");
|
|
123
|
+
}
|
|
124
|
+
return holds;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function canRelease(input: ReadinessInput): boolean {
|
|
128
|
+
return input.fulfillment === "ready" && releaseHolds(input).length === 0;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function handoffRefusal(input: ReadinessInput): ReleaseHold | "adult-signature" | "label" | "reconcile" | "fulfillment" | "evidence" | "payment" | "stock" | "reuse" | "ship-to" | null {
|
|
132
|
+
const holds = releaseHolds(input);
|
|
133
|
+
if (holds.length > 0) return holds[0] ?? "fulfillment";
|
|
134
|
+
const decision = decideCommerceCommand({
|
|
135
|
+
command: "hand-off",
|
|
136
|
+
payment: input.payment,
|
|
137
|
+
stock: input.stock,
|
|
138
|
+
fulfillment: input.fulfillment,
|
|
139
|
+
label: input.label,
|
|
140
|
+
evidence: input.evidence,
|
|
141
|
+
providerOutcome: input.providerOutcome,
|
|
142
|
+
shipTo: input.shipTo,
|
|
143
|
+
});
|
|
144
|
+
if (!decision.admit) return decision.reason === "admitted" ? "fulfillment" : decision.reason;
|
|
145
|
+
if (input.adultSignatureRequired && input.adultSignature !== "accepted") return "adult-signature";
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function carrierPolicyForTenant(tenant: {
|
|
150
|
+
tenant_id: string;
|
|
151
|
+
compliance?: { ruleProfile?: string };
|
|
152
|
+
carrierAccountId?: unknown;
|
|
153
|
+
}): CarrierPolicy {
|
|
154
|
+
const profile = tenant.compliance?.ruleProfile;
|
|
155
|
+
const build =
|
|
156
|
+
profile && Object.hasOwn(COMPLIANCE_RULE_PROFILES, profile)
|
|
157
|
+
? COMPLIANCE_RULE_PROFILES[profile as ComplianceRuleProfile]
|
|
158
|
+
: undefined;
|
|
159
|
+
const ruleset = build ? build(tenant.tenant_id) : null;
|
|
160
|
+
const raw = tenant.carrierAccountId;
|
|
161
|
+
const carrierAccountId = typeof raw === "string" && raw.trim() !== "" ? raw.trim() : null;
|
|
162
|
+
const enabled = ruleset?.pactAct.enabled === true;
|
|
163
|
+
return {
|
|
164
|
+
adultSignatureRequired: enabled && ruleset.pactAct.adultSignatureRequired === true,
|
|
165
|
+
pactEnabled: enabled,
|
|
166
|
+
prohibitedCarriers: enabled ? [...ruleset.pactAct.prohibitedCarriers] : [],
|
|
167
|
+
carrierAccountId,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* The tenant's compliance intersected with the carrier catalog. Prohibited when the carrier is in
|
|
173
|
+
* the policy's prohibited set, when PACT is enabled and the carrier is not statutorily eligible,
|
|
174
|
+
* or when adult signature is required and the carrier does not support it. A carrier the catalog
|
|
175
|
+
* does not declare has no eligibility and no adult-signature support, so it fails closed.
|
|
176
|
+
*/
|
|
177
|
+
export function carrierPolicyRefusal(
|
|
178
|
+
carrier: string,
|
|
179
|
+
policy: CarrierPolicy,
|
|
180
|
+
catalog: readonly CarrierCatalogEntry[] = CARRIER_CATALOG,
|
|
181
|
+
): "carrier-prohibited" | null {
|
|
182
|
+
if (carrierProhibited(carrier, policy.prohibitedCarriers)) return "carrier-prohibited";
|
|
183
|
+
const entry = carrierCatalogEntry(carrier, catalog);
|
|
184
|
+
if (policy.pactEnabled && !entry?.pactEligible) return "carrier-prohibited";
|
|
185
|
+
if (policy.adultSignatureRequired && (!entry || entry.adultSignature === "unsupported")) return "carrier-prohibited";
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** A supplied carrier is never a selection. A carrier the tenant's policy refuses answers carrier-prohibited. */
|
|
190
|
+
export function carrierSelectionRefusal(
|
|
191
|
+
policy: CarrierPolicy,
|
|
192
|
+
carrier: string | undefined,
|
|
193
|
+
catalog: readonly CarrierCatalogEntry[] = CARRIER_CATALOG,
|
|
194
|
+
): "carrier-prohibited" | "vendor-not-selected" | null {
|
|
195
|
+
if (carrier === undefined) return null;
|
|
196
|
+
if (canonicalCarrier(carrier) === "") return "vendor-not-selected";
|
|
197
|
+
return carrierPolicyRefusal(carrier, policy, catalog) ?? "vendor-not-selected";
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* A processor's reported carrier. Prohibited when the current policy refuses it or the order's
|
|
202
|
+
* label-intent snapshot prohibits it; a handoff carrier must equal the carrier its label was bought with.
|
|
203
|
+
*/
|
|
204
|
+
export function carrierEvidenceRefusal(input: {
|
|
205
|
+
carrier: CarrierCode;
|
|
206
|
+
policy: CarrierPolicy;
|
|
207
|
+
snapshotProhibited: readonly string[];
|
|
208
|
+
labelCarrier?: string | null;
|
|
209
|
+
catalog?: readonly CarrierCatalogEntry[];
|
|
210
|
+
}): "carrier-prohibited" | "carrier-mismatch" | null {
|
|
211
|
+
if (carrierPolicyRefusal(input.carrier, input.policy, input.catalog)) return "carrier-prohibited";
|
|
212
|
+
if (carrierProhibited(input.carrier, input.snapshotProhibited)) return "carrier-prohibited";
|
|
213
|
+
if (input.labelCarrier !== undefined && (input.labelCarrier === null || canonicalCarrier(input.labelCarrier) !== input.carrier)) {
|
|
214
|
+
return "carrier-mismatch";
|
|
215
|
+
}
|
|
216
|
+
return null;
|
|
217
|
+
}
|