@tokenoftrust/storefront-runner 7.5.3 → 7.6.0
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/checkout/commerce/cartSession.ts +71 -14
- package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +47 -5
- package/apps/storefront/src/lib/checkout/shared/cartState.ts +147 -1
- package/apps/storefront/src/lib/inventory/allocations.ts +70 -36
- package/apps/storefront/wrangler.json +7 -0
- package/package.json +1 -1
- package/packages/public-runtime/src/checkout-orders.ts +13 -0
|
@@ -210,6 +210,15 @@ function cartErrors(body: unknown): number {
|
|
|
210
210
|
}
|
|
211
211
|
|
|
212
212
|
const COUPON_CODE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
213
|
+
const RESERVED_EXCISE_COUPON = "tot_excise_tax";
|
|
214
|
+
|
|
215
|
+
export function isPromoCouponCode(value: unknown): value is string {
|
|
216
|
+
return (
|
|
217
|
+
typeof value === "string" &&
|
|
218
|
+
COUPON_CODE.test(value) &&
|
|
219
|
+
value.toLowerCase() !== RESERVED_EXCISE_COUPON
|
|
220
|
+
);
|
|
221
|
+
}
|
|
213
222
|
|
|
214
223
|
/** Coupon codes a cart holds, whether Foxy keys them by code or lists them. */
|
|
215
224
|
export function cartCouponCodes(body: unknown): string[] {
|
|
@@ -223,7 +232,16 @@ export function cartCouponCodes(body: unknown): string[] {
|
|
|
223
232
|
: coupons && typeof coupons === "object"
|
|
224
233
|
? Object.entries(coupons as Record<string, unknown>).map(([key, coupon]) => codeOf(coupon, key))
|
|
225
234
|
: [];
|
|
226
|
-
|
|
235
|
+
const seen = new Set<string>();
|
|
236
|
+
const valid: string[] = [];
|
|
237
|
+
for (const code of codes) {
|
|
238
|
+
if (!isPromoCouponCode(code)) continue;
|
|
239
|
+
const key = code.toLowerCase();
|
|
240
|
+
if (seen.has(key)) continue;
|
|
241
|
+
seen.add(key);
|
|
242
|
+
valid.push(code);
|
|
243
|
+
}
|
|
244
|
+
return valid;
|
|
227
245
|
}
|
|
228
246
|
|
|
229
247
|
function wholeQuantity(value: unknown): number {
|
|
@@ -292,6 +310,7 @@ export async function addToTenantCart(input: {
|
|
|
292
310
|
add: readonly CartLineField[];
|
|
293
311
|
sign: CartLineSigner;
|
|
294
312
|
fetch?: typeof fetch;
|
|
313
|
+
coupon?: string | null;
|
|
295
314
|
}): Promise<string | null> {
|
|
296
315
|
const { add, ...rest } = input;
|
|
297
316
|
return addLinesToTenantCart({ ...rest, lines: [add] });
|
|
@@ -309,11 +328,25 @@ export async function addLinesToTenantCart(input: {
|
|
|
309
328
|
lines: readonly (readonly CartLineField[])[];
|
|
310
329
|
sign: CartLineSigner;
|
|
311
330
|
fetch?: typeof fetch;
|
|
331
|
+
coupon?: string | null;
|
|
312
332
|
}): Promise<string | null> {
|
|
313
333
|
if (!input.tenantId || input.lines.length === 0) return null;
|
|
314
334
|
const fetchImpl = input.fetch ?? fetch;
|
|
335
|
+
const requestedCoupons: string[] = [];
|
|
336
|
+
for (const line of input.lines) {
|
|
337
|
+
for (const field of line) {
|
|
338
|
+
if ((field.name.split("||")[0] ?? "").toLowerCase() === "coupon") {
|
|
339
|
+
const trimmed = field.value.trim();
|
|
340
|
+
if (isPromoCouponCode(trimmed)) requestedCoupons.push(trimmed);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
if (typeof input.coupon === "string") {
|
|
345
|
+
const trimmed = input.coupon.trim();
|
|
346
|
+
if (isPromoCouponCode(trimmed)) requestedCoupons.push(trimmed);
|
|
347
|
+
}
|
|
315
348
|
const adds = input.lines.map((line) =>
|
|
316
|
-
line.filter((field) => !["fcsid", "output", "coupon"].includes(field.name.split("||")[0] ?? "")));
|
|
349
|
+
line.filter((field) => !["fcsid", "output", "coupon"].includes((field.name.split("||")[0] ?? "").toLowerCase())));
|
|
317
350
|
let addedQuantity = 0;
|
|
318
351
|
for (const add of adds) {
|
|
319
352
|
const quantity = wholeQuantity(add.find((field) => field.name.split("||")[0] === "quantity")?.value ?? "1");
|
|
@@ -321,7 +354,7 @@ export async function addLinesToTenantCart(input: {
|
|
|
321
354
|
addedQuantity += quantity;
|
|
322
355
|
}
|
|
323
356
|
let carried: CarriedCartLine[] = [];
|
|
324
|
-
let
|
|
357
|
+
let existingCoupons: string[] = [];
|
|
325
358
|
const existing = saneSessionId(input.existing) ? input.existing : null;
|
|
326
359
|
if (existing) {
|
|
327
360
|
const read = await readCart(input.cartUrl, existing, fetchImpl);
|
|
@@ -330,11 +363,21 @@ export async function addLinesToTenantCart(input: {
|
|
|
330
363
|
const lines = itemsOf(read.body).map(carriedCartLine);
|
|
331
364
|
if (lines.some((line) => line === null)) return null;
|
|
332
365
|
carried = lines as CarriedCartLine[];
|
|
333
|
-
|
|
366
|
+
existingCoupons = cartCouponCodes(read.body);
|
|
334
367
|
}
|
|
335
368
|
}
|
|
369
|
+
const existingCouponSet = new Set(existingCoupons.map((code) => code.toLowerCase()));
|
|
370
|
+
const newCoupons: string[] = [];
|
|
371
|
+
const newCouponSet = new Set<string>();
|
|
372
|
+
for (const code of requestedCoupons) {
|
|
373
|
+
const key = code.toLowerCase();
|
|
374
|
+
if (existingCouponSet.has(key) || newCouponSet.has(key)) continue;
|
|
375
|
+
newCouponSet.add(key);
|
|
376
|
+
newCoupons.push(code);
|
|
377
|
+
}
|
|
378
|
+
const mergedCoupons = [...existingCoupons, ...newCoupons];
|
|
336
379
|
const addVerification = adds.flat().find((field) => field.name.split("||")[0] === "verification")?.value;
|
|
337
|
-
const
|
|
380
|
+
const itemFields: CartLineField[] = [];
|
|
338
381
|
for (const [index, line] of carried.entries()) {
|
|
339
382
|
const toSign = addVerification
|
|
340
383
|
? {
|
|
@@ -345,21 +388,33 @@ export async function addLinesToTenantCart(input: {
|
|
|
345
388
|
],
|
|
346
389
|
}
|
|
347
390
|
: line;
|
|
348
|
-
for (const field of await input.sign(toSign))
|
|
391
|
+
for (const field of await input.sign(toSign)) itemFields.push({ name: `${index + 1}:${field.name}`, value: field.value });
|
|
349
392
|
}
|
|
350
393
|
const numbered = carried.length + adds.length > 1;
|
|
351
394
|
for (const [offset, add] of adds.entries()) {
|
|
352
395
|
const prefix = numbered ? `${carried.length + offset + 1}:` : "";
|
|
353
|
-
for (const field of add)
|
|
396
|
+
for (const field of add) itemFields.push({ name: `${prefix}${field.name}`, value: field.value });
|
|
354
397
|
}
|
|
355
|
-
for (const code of coupons) fields.push({ name: "coupon", value: code });
|
|
356
398
|
const before = carried.reduce((sum, line) => sum + wholeQuantity(line.fields.find((f) => f.name === "quantity")?.value), 0);
|
|
357
|
-
const
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
399
|
+
const withCoupons = (codes: readonly string[]): CartLineField[] => [
|
|
400
|
+
...itemFields,
|
|
401
|
+
...codes.map((code) => ({ name: "coupon", value: code })),
|
|
402
|
+
];
|
|
403
|
+
const validOpenedSession = (opened: CartRead): string | null => {
|
|
404
|
+
if (opened.status !== "cart" || cartErrors(opened.body) > 0) return null;
|
|
405
|
+
const id = sessionIdOf(opened.body);
|
|
406
|
+
if (!id || id === existing || !cartAcceptsTenant(opened.body, input.tenantId)) return null;
|
|
407
|
+
if (totalQuantity(opened.body) !== before + addedQuantity) return null;
|
|
408
|
+
return id;
|
|
409
|
+
};
|
|
410
|
+
const opened = await readCart(input.cartUrl, null, fetchImpl, withCoupons(mergedCoupons));
|
|
411
|
+
const id = validOpenedSession(opened);
|
|
412
|
+
if (id) return id;
|
|
413
|
+
if (newCoupons.length > 0) {
|
|
414
|
+
const retried = await readCart(input.cartUrl, null, fetchImpl, withCoupons(existingCoupons));
|
|
415
|
+
return validOpenedSession(retried);
|
|
416
|
+
}
|
|
417
|
+
return null;
|
|
363
418
|
}
|
|
364
419
|
|
|
365
420
|
function storeCartSession(context: CartSessionBinding, id: string): void {
|
|
@@ -380,6 +435,7 @@ export async function addToBoundCart(
|
|
|
380
435
|
add: readonly CartLineField[],
|
|
381
436
|
sign: CartLineSigner,
|
|
382
437
|
fetchImpl?: typeof fetch,
|
|
438
|
+
coupon?: string | null,
|
|
383
439
|
): Promise<string | null> {
|
|
384
440
|
const id = await addToTenantCart({
|
|
385
441
|
cartUrl: commerce.cartUrl,
|
|
@@ -388,6 +444,7 @@ export async function addToBoundCart(
|
|
|
388
444
|
add,
|
|
389
445
|
sign,
|
|
390
446
|
fetch: fetchImpl,
|
|
447
|
+
coupon,
|
|
391
448
|
});
|
|
392
449
|
if (id) storeCartSession(context, id);
|
|
393
450
|
return id;
|
|
@@ -45,7 +45,12 @@ import {
|
|
|
45
45
|
type ResolvedManagedCheckout,
|
|
46
46
|
} from "@tot/public-runtime";
|
|
47
47
|
import { resolveCheckoutHandoffCorrelation } from "@/lib/checkout/commerce/checkoutHandoffCorrelation";
|
|
48
|
-
import {
|
|
48
|
+
import {
|
|
49
|
+
addToBoundCart,
|
|
50
|
+
CART_UNAVAILABLE_MESSAGE,
|
|
51
|
+
isPromoCouponCode,
|
|
52
|
+
withCartSession,
|
|
53
|
+
} from "@/lib/checkout/commerce/cartSession";
|
|
49
54
|
import { resolveCartSigning, shopperCartDenialMessage } from "@/lib/checkout/shared/checkoutCommerce";
|
|
50
55
|
import { effectiveExcise } from "@/lib/checkout/commerce/checkoutExcise";
|
|
51
56
|
import { fromD1 } from "@/lib/catalog/d1/catalog";
|
|
@@ -119,6 +124,34 @@ async function boundShippingPolicy(
|
|
|
119
124
|
}
|
|
120
125
|
}
|
|
121
126
|
|
|
127
|
+
function normalizePromoCoupon(raw: string | null | undefined): string | null {
|
|
128
|
+
if (typeof raw !== "string") return null;
|
|
129
|
+
const trimmed = raw.trim();
|
|
130
|
+
return isPromoCouponCode(trimmed) ? trimmed : null;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function takePromoCoupon(
|
|
134
|
+
entries: Iterable<[string, string]>,
|
|
135
|
+
requestUrl: string,
|
|
136
|
+
): { entries: Array<[string, string]>; coupon: string | null } {
|
|
137
|
+
const kept: Array<[string, string]> = [];
|
|
138
|
+
let formCoupon: string | null = null;
|
|
139
|
+
for (const [name, value] of entries) {
|
|
140
|
+
const base = (name.split("||")[0] ?? "").trim().toLowerCase();
|
|
141
|
+
if (base !== "coupon") {
|
|
142
|
+
kept.push([name, value]);
|
|
143
|
+
} else if (name.trim().toLowerCase() === "coupon" && formCoupon === null) {
|
|
144
|
+
formCoupon = normalizePromoCoupon(value);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
let queryCoupon: string | null = null;
|
|
148
|
+
if (URL.canParse(requestUrl)) {
|
|
149
|
+
const params = new URL(requestUrl).searchParams;
|
|
150
|
+
queryCoupon = normalizePromoCoupon(params.get("coupon") ?? params.get("promo"));
|
|
151
|
+
}
|
|
152
|
+
return { entries: kept, coupon: formCoupon ?? queryCoupon };
|
|
153
|
+
}
|
|
154
|
+
|
|
122
155
|
/**
|
|
123
156
|
* Add the enforced line to this tenant's Foxy cart from the server, and return the cart view of
|
|
124
157
|
* the session that holds it. The location carries no cart fields, so following it adds nothing.
|
|
@@ -129,9 +162,17 @@ async function sessionedCartLocation(
|
|
|
129
162
|
tenant: TenantConfig,
|
|
130
163
|
fields: readonly CartSubmissionField[],
|
|
131
164
|
secret: string | undefined,
|
|
165
|
+
coupon: string | null = null,
|
|
132
166
|
): Promise<string | null> {
|
|
133
|
-
const fcsid = await addToBoundCart(
|
|
134
|
-
|
|
167
|
+
const fcsid = await addToBoundCart(
|
|
168
|
+
context,
|
|
169
|
+
commerce,
|
|
170
|
+
commerceTenantId(tenant),
|
|
171
|
+
fields,
|
|
172
|
+
(line) => signCartLine(line.fields, { mode: commerce.mode, secret, code: line.code }),
|
|
173
|
+
undefined,
|
|
174
|
+
coupon,
|
|
175
|
+
);
|
|
135
176
|
return fcsid ? withCartSession(commerce.cartUrl, fcsid) : null;
|
|
136
177
|
}
|
|
137
178
|
|
|
@@ -263,7 +304,8 @@ async function cartFormPost(context: APIContext): Promise<Response> {
|
|
|
263
304
|
submitted.push([name, value]);
|
|
264
305
|
}
|
|
265
306
|
// The compliance gate adds the shopper's verification ref; it rides to the cart signed.
|
|
266
|
-
const { entries, ref } = takeVerificationRef(submitted);
|
|
307
|
+
const { entries: withoutVerification, ref } = takeVerificationRef(submitted);
|
|
308
|
+
const { entries, coupon } = takePromoCoupon(withoutVerification, context.request.url);
|
|
267
309
|
const result = await enforceCartSubmission({
|
|
268
310
|
entries,
|
|
269
311
|
mode: commerce.mode,
|
|
@@ -281,7 +323,7 @@ async function cartFormPost(context: APIContext): Promise<Response> {
|
|
|
281
323
|
ref, returnUrl: submittedFromUrl(context.request, tenant),
|
|
282
324
|
});
|
|
283
325
|
if (!imaged) return cartDenial("shipping", SHIPPING_UNAVAILABLE_CART_MESSAGE, 409);
|
|
284
|
-
const location = await sessionedCartLocation(context, commerce, tenant, imaged, signing.secret);
|
|
326
|
+
const location = await sessionedCartLocation(context, commerce, tenant, imaged, signing.secret, coupon);
|
|
285
327
|
if (!location) return cartDenial("signing-unavailable", CART_UNAVAILABLE_MESSAGE, 503);
|
|
286
328
|
// The page reads the cart that now holds the line (cartState.ts) and asks for its URL as data.
|
|
287
329
|
if ((context.request.headers.get("accept") ?? "").includes("application/json")) {
|
|
@@ -38,10 +38,12 @@ export const INTERNAL_CART_OPTIONS: readonly string[] = [
|
|
|
38
38
|
"excise",
|
|
39
39
|
];
|
|
40
40
|
|
|
41
|
-
const MANAGED_CART_FORM = "form[data-managed-cart]";
|
|
41
|
+
const MANAGED_CART_FORM = "form[data-managed-cart], form[data-tot-cart-form]";
|
|
42
42
|
const COUNT_SELECTOR = "[data-cart-count], .cart .count";
|
|
43
43
|
const JSONP_TIMEOUT_MS = 8000;
|
|
44
44
|
const SESSION_TIMEOUT_MS = 5000;
|
|
45
|
+
export const PROMO_COUPON_CODE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
46
|
+
const RESERVED_EXCISE_COUPON = "tot_excise_tax";
|
|
45
47
|
|
|
46
48
|
export interface CartStateConfig {
|
|
47
49
|
/** `https://<checkout origin>/cart`. */
|
|
@@ -216,6 +218,121 @@ export function writeStoredCount(
|
|
|
216
218
|
}
|
|
217
219
|
}
|
|
218
220
|
|
|
221
|
+
type StorageLike = Pick<Storage, "getItem" | "setItem" | "removeItem">;
|
|
222
|
+
|
|
223
|
+
export type CouponStorageHost =
|
|
224
|
+
| { sessionStorage?: StorageLike | null; localStorage?: StorageLike | null }
|
|
225
|
+
| StorageLike
|
|
226
|
+
| null
|
|
227
|
+
| undefined;
|
|
228
|
+
|
|
229
|
+
function normalizeCookiePath(cookiePath: string): string {
|
|
230
|
+
const trimmed = cookiePath.trim();
|
|
231
|
+
if (trimmed === "" || trimmed === "/") return "/";
|
|
232
|
+
const withLead = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
|
|
233
|
+
return `${withLead.replace(/\/+$/, "")}/`;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export function pendingCouponKey(cookiePath: string): string {
|
|
237
|
+
return `tot_pending_coupon:${normalizeCookiePath(cookiePath)}`;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export function normalizePromoCoupon(raw: unknown): string | null {
|
|
241
|
+
if (typeof raw !== "string") return null;
|
|
242
|
+
const code = raw.trim();
|
|
243
|
+
if (!PROMO_COUPON_CODE.test(code)) return null;
|
|
244
|
+
if (code.toLowerCase() === RESERVED_EXCISE_COUPON) return null;
|
|
245
|
+
return code;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function resolveCouponStorages(host: CouponStorageHost): StorageLike[] {
|
|
249
|
+
if (!host || typeof host !== "object") return [];
|
|
250
|
+
if ("getItem" in host && typeof host.getItem === "function") {
|
|
251
|
+
return [host];
|
|
252
|
+
}
|
|
253
|
+
const out: StorageLike[] = [];
|
|
254
|
+
const winHost = host as { sessionStorage?: StorageLike | null; localStorage?: StorageLike | null };
|
|
255
|
+
try {
|
|
256
|
+
if (winHost.sessionStorage) out.push(winHost.sessionStorage);
|
|
257
|
+
} catch {
|
|
258
|
+
/* sessionStorage unavailable */
|
|
259
|
+
}
|
|
260
|
+
try {
|
|
261
|
+
if (winHost.localStorage && !out.includes(winHost.localStorage)) out.push(winHost.localStorage);
|
|
262
|
+
} catch {
|
|
263
|
+
/* localStorage unavailable */
|
|
264
|
+
}
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function readPendingCoupon(host: CouponStorageHost, cookiePath = "/"): string | null {
|
|
269
|
+
const key = pendingCouponKey(cookiePath);
|
|
270
|
+
for (const storage of resolveCouponStorages(host)) {
|
|
271
|
+
try {
|
|
272
|
+
const valid = normalizePromoCoupon(storage.getItem(key));
|
|
273
|
+
if (valid) return valid;
|
|
274
|
+
} catch {
|
|
275
|
+
/* storage disabled */
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return null;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export function writePendingCoupon(
|
|
282
|
+
host: CouponStorageHost,
|
|
283
|
+
cookiePath: string,
|
|
284
|
+
code: string | null,
|
|
285
|
+
): string | null {
|
|
286
|
+
const key = pendingCouponKey(cookiePath);
|
|
287
|
+
const storages = resolveCouponStorages(host);
|
|
288
|
+
if (code === null || code === "") {
|
|
289
|
+
for (const storage of storages) {
|
|
290
|
+
try {
|
|
291
|
+
storage.removeItem(key);
|
|
292
|
+
} catch {
|
|
293
|
+
/* storage disabled */
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return null;
|
|
297
|
+
}
|
|
298
|
+
const valid = normalizePromoCoupon(code);
|
|
299
|
+
if (!valid) return null;
|
|
300
|
+
for (const storage of storages) {
|
|
301
|
+
try {
|
|
302
|
+
storage.setItem(key, valid);
|
|
303
|
+
} catch {
|
|
304
|
+
/* storage disabled */
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return valid;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export function captureCouponFromUrl(
|
|
311
|
+
win: ({ location?: { search?: string } } & CouponStorageHost) | null | undefined,
|
|
312
|
+
cookiePath = "/",
|
|
313
|
+
): string | null {
|
|
314
|
+
const search = win?.location?.search;
|
|
315
|
+
if (typeof search !== "string" || !search) return null;
|
|
316
|
+
const params = new URLSearchParams(search);
|
|
317
|
+
const raw = params.get("coupon") ?? params.get("promo");
|
|
318
|
+
const valid = normalizePromoCoupon(raw);
|
|
319
|
+
if (!valid) return null;
|
|
320
|
+
return writePendingCoupon(win, cookiePath, valid);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function attachPendingCouponToForm(form: HTMLFormElement, doc: Document, coupon: string): void {
|
|
324
|
+
const existing = form.querySelector<HTMLInputElement>('input[name="coupon"]');
|
|
325
|
+
if (existing) {
|
|
326
|
+
if (!normalizePromoCoupon(existing.value)) existing.value = coupon;
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
const input = doc.createElement("input");
|
|
330
|
+
input.type = "hidden";
|
|
331
|
+
input.name = "coupon";
|
|
332
|
+
input.value = coupon;
|
|
333
|
+
form.appendChild(input);
|
|
334
|
+
}
|
|
335
|
+
|
|
219
336
|
export interface CartEnv {
|
|
220
337
|
doc: Document;
|
|
221
338
|
win: Window;
|
|
@@ -389,7 +506,21 @@ export async function addFromForm(
|
|
|
389
506
|
env: CartEnv,
|
|
390
507
|
): Promise<boolean> {
|
|
391
508
|
const cartOrigin = new URL(config.cartUrl).origin;
|
|
509
|
+
const pendingCoupon =
|
|
510
|
+
readPendingCoupon(env.win, config.cookiePath) ??
|
|
511
|
+
readPendingCoupon(env.storage, config.cookiePath) ??
|
|
512
|
+
captureCouponFromUrl(env.win, config.cookiePath);
|
|
513
|
+
if (pendingCoupon) {
|
|
514
|
+
attachPendingCouponToForm(form, env.doc, pendingCoupon);
|
|
515
|
+
}
|
|
392
516
|
const data = new FormData(form);
|
|
517
|
+
const existingCoupon = data.get("coupon");
|
|
518
|
+
if (existingCoupon !== null && !normalizePromoCoupon(existingCoupon)) {
|
|
519
|
+
data.delete("coupon");
|
|
520
|
+
}
|
|
521
|
+
if (pendingCoupon && !normalizePromoCoupon(data.get("coupon"))) {
|
|
522
|
+
data.set("coupon", pendingCoupon);
|
|
523
|
+
}
|
|
393
524
|
let location: string;
|
|
394
525
|
try {
|
|
395
526
|
const res = await env.fetch(form.action, {
|
|
@@ -455,6 +586,21 @@ export function bootCartStateFromDom(win: Window): void {
|
|
|
455
586
|
* over released add-to-cart submits.
|
|
456
587
|
*/
|
|
457
588
|
export function bootCartState(config: CartStateConfig, env: CartEnv): () => void {
|
|
589
|
+
const capturedCoupon = captureCouponFromUrl(env.win, config.cookiePath);
|
|
590
|
+
if (capturedCoupon && env.storage) {
|
|
591
|
+
writePendingCoupon(env.storage, config.cookiePath, capturedCoupon);
|
|
592
|
+
}
|
|
593
|
+
const activeCoupon =
|
|
594
|
+
capturedCoupon ??
|
|
595
|
+
readPendingCoupon(env.win, config.cookiePath) ??
|
|
596
|
+
readPendingCoupon(env.storage, config.cookiePath);
|
|
597
|
+
if (activeCoupon) {
|
|
598
|
+
const stateEl = env.doc.querySelector<HTMLElement>("[data-cart-state]");
|
|
599
|
+
if (stateEl) stateEl.dataset.pendingCoupon = activeCoupon;
|
|
600
|
+
for (const form of env.doc.querySelectorAll<HTMLFormElement>(MANAGED_CART_FORM)) {
|
|
601
|
+
attachPendingCouponToForm(form, env.doc, activeCoupon);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
458
604
|
const key = storedCountKey(config.cookiePath);
|
|
459
605
|
const known = () => readStoredCount(env.storage, key);
|
|
460
606
|
renderCartCount(env.doc, known());
|
|
@@ -485,52 +485,90 @@ export async function reserveAllocation(runner: StatementRunner, input: ReserveI
|
|
|
485
485
|
return { ok: false, finding: "stock-unavailable" };
|
|
486
486
|
}
|
|
487
487
|
|
|
488
|
-
export
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
488
|
+
export interface ReleaseHoldInput {
|
|
489
|
+
tenantId: string;
|
|
490
|
+
stage: CommerceStage;
|
|
491
|
+
orderId: string;
|
|
492
|
+
allocationState: "released" | "expired";
|
|
493
|
+
authState: "denied" | "expired";
|
|
494
|
+
orderStock: StockState;
|
|
495
|
+
/** A predicate every statement also requires, so a caller's own transaction can fence the release. */
|
|
496
|
+
gate?: { sql: string; params: readonly unknown[] };
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* The statements that release one order's hold: authorization, allocation rows, the order's
|
|
501
|
+
* `stock_state` (this module owns that column) and the availability sync. `notify` dispatches the
|
|
502
|
+
* deliveries the committed sync wrote.
|
|
503
|
+
*/
|
|
504
|
+
export function releaseHoldStatements(input: ReleaseHoldInput): {
|
|
505
|
+
statements: SqlStatement[];
|
|
506
|
+
resultIndex: number;
|
|
507
|
+
notify: (runner: StatementRunner) => Promise<void>;
|
|
508
|
+
} {
|
|
499
509
|
const scope = [input.tenantId, input.stage, input.orderId];
|
|
510
|
+
const gateSql = input.gate ? ` AND ${input.gate.sql}` : "";
|
|
511
|
+
const gateParams = input.gate ? [...input.gate.params] : [];
|
|
500
512
|
const sync = allocationSync({
|
|
501
513
|
tenantId: input.tenantId,
|
|
502
514
|
stage: input.stage,
|
|
503
515
|
now: new Date().toISOString(),
|
|
504
516
|
scope: orderScope(input.tenantId, input.stage, input.orderId),
|
|
505
517
|
});
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
518
|
+
return {
|
|
519
|
+
statements: [
|
|
520
|
+
{
|
|
521
|
+
sql: `UPDATE scrappy_final_cart_authorizations
|
|
509
522
|
SET state = ?
|
|
510
523
|
WHERE tenant_id = ? AND stage = ? AND (authorization_id = ? OR authorization_id IN (
|
|
511
524
|
SELECT authorization_id FROM commerce_admission_snapshots WHERE tenant_id=? AND stage=? AND linked_order_id=?
|
|
512
|
-
)) AND state IN ('active', 'consumed')
|
|
525
|
+
)) AND state IN ('active', 'consumed')${gateSql}
|
|
513
526
|
RETURNING authorization_id`,
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
527
|
+
params: [input.authState, ...scope, ...scope, ...gateParams],
|
|
528
|
+
},
|
|
529
|
+
{
|
|
530
|
+
sql: `UPDATE scrappy_allocations
|
|
518
531
|
SET state = ?
|
|
519
|
-
WHERE tenant_id = ? AND stage = ? AND order_id = ? AND state IN ('reserved', 'confirmed')
|
|
532
|
+
WHERE tenant_id = ? AND stage = ? AND order_id = ? AND state IN ('reserved', 'confirmed')${gateSql}
|
|
520
533
|
RETURNING quantity`,
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
534
|
+
params: [input.allocationState, ...scope, ...gateParams],
|
|
535
|
+
},
|
|
536
|
+
{
|
|
537
|
+
sql: `UPDATE scrappy_commerce_orders
|
|
525
538
|
SET stock_state = ?
|
|
526
|
-
WHERE tenant_id = ? AND stage = ? AND order_id = ? AND stock_state IN ('reserved', 'confirmed')
|
|
539
|
+
WHERE tenant_id = ? AND stage = ? AND order_id = ? AND stock_state IN ('reserved', 'confirmed')${gateSql}
|
|
527
540
|
RETURNING order_id`,
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
541
|
+
params: [input.orderStock, ...scope, ...gateParams],
|
|
542
|
+
},
|
|
543
|
+
...sync.statements,
|
|
544
|
+
],
|
|
545
|
+
resultIndex: 1,
|
|
546
|
+
notify: (runner) => notifyAllocationSync(runner, input.tenantId, sync.token),
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
export async function releaseHoldOnce(runner: StatementRunner, input: ReleaseHoldInput): Promise<number> {
|
|
551
|
+
const release = releaseHoldStatements(input);
|
|
552
|
+
const results = await runner.batch(release.statements);
|
|
553
|
+
await release.notify(runner);
|
|
554
|
+
return sumQuantity(results[release.resultIndex] ?? []);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* A trusted, captured source snapshot confirms the order's stock under the event version the
|
|
559
|
+
* caller's own statement just wrote. Any other snapshot leaves `stock_state` alone.
|
|
560
|
+
*/
|
|
561
|
+
export function sourceConfirmStockStatement(
|
|
562
|
+
key: { tenantId: string; stage: CommerceStage; orderId: string },
|
|
563
|
+
eventVersion: number,
|
|
564
|
+
): SqlStatement {
|
|
565
|
+
return {
|
|
566
|
+
sql: `UPDATE scrappy_commerce_orders
|
|
567
|
+
SET stock_state = 'confirmed'
|
|
568
|
+
WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
|
|
569
|
+
AND stock_state IN ('unallocated', 'reserved', 'UNKNOWN')`,
|
|
570
|
+
params: [key.tenantId, key.stage, key.orderId, eventVersion],
|
|
571
|
+
};
|
|
534
572
|
}
|
|
535
573
|
|
|
536
574
|
export async function settleExpired(
|
|
@@ -776,11 +814,7 @@ export async function confirmHoldOnce(
|
|
|
776
814
|
},
|
|
777
815
|
{
|
|
778
816
|
sql: `UPDATE scrappy_commerce_orders
|
|
779
|
-
SET
|
|
780
|
-
WHEN payment_state IN ('pending', 'authorized') THEN 'captured'
|
|
781
|
-
ELSE payment_state
|
|
782
|
-
END,
|
|
783
|
-
stock_state = 'confirmed'
|
|
817
|
+
SET stock_state = 'confirmed'
|
|
784
818
|
WHERE tenant_id = ? AND stage = ? AND order_id = ?
|
|
785
819
|
AND fulfillment_state IN ('held', 'ready')
|
|
786
820
|
AND payment_state IN ('pending', 'authorized', 'captured')
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.6.0",
|
|
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",
|
|
@@ -36,6 +36,11 @@ export interface OrderContactAvailability {
|
|
|
36
36
|
shipTo: OrderContactState;
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
export interface CheckoutOrderDiscount {
|
|
40
|
+
code: string;
|
|
41
|
+
amountMinor: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
39
44
|
/** A row in the orders list. All fields populated by U1 EXCEPT `verification`. */
|
|
40
45
|
export interface CheckoutOrderSummary {
|
|
41
46
|
/** Order / transaction id (string). */
|
|
@@ -59,6 +64,7 @@ export interface CheckoutOrderSummary {
|
|
|
59
64
|
* Verification summary. Null is absent evidence, not a pass and not clearance.
|
|
60
65
|
*/
|
|
61
66
|
verification: CheckoutOrderVerification | null;
|
|
67
|
+
discounts?: readonly CheckoutOrderDiscount[];
|
|
62
68
|
}
|
|
63
69
|
|
|
64
70
|
/** Verification summary carried on the admin list. Null stays null. */
|
|
@@ -80,6 +86,7 @@ export interface CheckoutOrderTotals {
|
|
|
80
86
|
shipping: number;
|
|
81
87
|
estimatedTax: number;
|
|
82
88
|
taxesAndFees: number;
|
|
89
|
+
discount?: number;
|
|
83
90
|
total: number;
|
|
84
91
|
}
|
|
85
92
|
|
|
@@ -106,6 +113,7 @@ export interface CheckoutOrderDetail extends CheckoutOrderSummary {
|
|
|
106
113
|
totals: CheckoutOrderTotals;
|
|
107
114
|
shippingAddress: CheckoutOrderShippingAddress | null;
|
|
108
115
|
verificationDetail: CheckoutOrderVerificationDetail;
|
|
116
|
+
discounts?: readonly CheckoutOrderDiscount[];
|
|
109
117
|
}
|
|
110
118
|
|
|
111
119
|
export interface CheckoutOrderPage {
|
|
@@ -345,6 +353,7 @@ export interface PublicCommerceEvent {
|
|
|
345
353
|
label: LabelState;
|
|
346
354
|
totals: MinorTotals;
|
|
347
355
|
verificationDetail: CommerceEvidence;
|
|
356
|
+
discounts?: readonly CheckoutOrderDiscount[];
|
|
348
357
|
}
|
|
349
358
|
|
|
350
359
|
export type CommerceRole = "owner" | "caller" | "denied";
|
|
@@ -774,6 +783,7 @@ export function publicCommerceEvent(
|
|
|
774
783
|
label: LabelState;
|
|
775
784
|
totals: MinorTotals;
|
|
776
785
|
verificationDetail: CommerceEvidence;
|
|
786
|
+
discounts?: readonly CheckoutOrderDiscount[];
|
|
777
787
|
} & Record<string, unknown>,
|
|
778
788
|
): PublicCommerceEvent {
|
|
779
789
|
if (!Number.isSafeInteger(input.eventVersion) || input.eventVersion < 1) {
|
|
@@ -805,6 +815,9 @@ export function publicCommerceEvent(
|
|
|
805
815
|
risk: input.verificationDetail.risk,
|
|
806
816
|
stock: input.verificationDetail.stock,
|
|
807
817
|
},
|
|
818
|
+
...(Array.isArray(input.discounts) && input.discounts.length > 0
|
|
819
|
+
? { discounts: input.discounts.map((d) => ({ code: d.code, amountMinor: d.amountMinor })) }
|
|
820
|
+
: {}),
|
|
808
821
|
};
|
|
809
822
|
}
|
|
810
823
|
|