@tokenoftrust/storefront-runner 7.5.4 → 7.6.1
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/checkout/storefront/islands/CartAddedDialog.tsx +8 -0
- 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 +192 -2
- package/apps/storefront/src/lib/inventory/allocations.ts +70 -36
- package/package.json +1 -1
- package/packages/public-runtime/src/checkout-orders.ts +15 -0
|
@@ -117,6 +117,14 @@ export default function CartAddedDialog() {
|
|
|
117
117
|
</dl>
|
|
118
118
|
)}
|
|
119
119
|
<p class="mt-1 text-sm text-[var(--color-muted)]">Quantity: {detail.quantity}</p>
|
|
120
|
+
{detail.appliedCoupon && (
|
|
121
|
+
<p
|
|
122
|
+
data-cart-added-coupon={detail.appliedCoupon}
|
|
123
|
+
class="mt-2 inline-flex items-center rounded-full border border-[var(--color-border)] bg-[var(--color-bg)] px-3 py-1 text-xs font-medium text-[var(--color-text)]"
|
|
124
|
+
>
|
|
125
|
+
Promo code applied: {detail.appliedCoupon}
|
|
126
|
+
</p>
|
|
127
|
+
)}
|
|
120
128
|
</div>
|
|
121
129
|
</div>
|
|
122
130
|
) : (
|
|
@@ -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`. */
|
|
@@ -71,6 +73,8 @@ export interface ParsedCart {
|
|
|
71
73
|
lines: CartLine[];
|
|
72
74
|
/** Messages the provider refused the request with. Empty when it accepted. */
|
|
73
75
|
errors: string[];
|
|
76
|
+
/** Promotional coupon codes active on the cart. */
|
|
77
|
+
coupons?: string[];
|
|
74
78
|
}
|
|
75
79
|
|
|
76
80
|
export type CartAddedDetail =
|
|
@@ -82,6 +86,7 @@ export type CartAddedDetail =
|
|
|
82
86
|
image: string | null;
|
|
83
87
|
count: number;
|
|
84
88
|
cartHref: string;
|
|
89
|
+
appliedCoupon?: string;
|
|
85
90
|
}
|
|
86
91
|
| { status: "error"; cartHref: string };
|
|
87
92
|
|
|
@@ -132,6 +137,37 @@ function wholeNumber(raw: unknown): number {
|
|
|
132
137
|
return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
|
|
133
138
|
}
|
|
134
139
|
|
|
140
|
+
/** Valid promotional coupon codes present on a FoxyCart JSONcart `coupons` payload. */
|
|
141
|
+
export function parseCartCoupons(body: unknown): string[] {
|
|
142
|
+
const cart = record(body);
|
|
143
|
+
if (!cart) return [];
|
|
144
|
+
const rawCoupons = cart.coupons;
|
|
145
|
+
const out: string[] = [];
|
|
146
|
+
const push = (candidate: unknown) => {
|
|
147
|
+
const valid = normalizePromoCoupon(candidate);
|
|
148
|
+
if (valid && !out.includes(valid)) out.push(valid);
|
|
149
|
+
};
|
|
150
|
+
if (Array.isArray(rawCoupons)) {
|
|
151
|
+
for (const entry of rawCoupons) {
|
|
152
|
+
if (typeof entry === "string") {
|
|
153
|
+
push(entry);
|
|
154
|
+
} else {
|
|
155
|
+
const obj = record(entry);
|
|
156
|
+
if (obj) push(obj.code);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
} else {
|
|
160
|
+
const map = record(rawCoupons);
|
|
161
|
+
if (map) {
|
|
162
|
+
for (const [key, value] of Object.entries(map)) {
|
|
163
|
+
const obj = record(value);
|
|
164
|
+
push(obj?.code ?? key);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return out;
|
|
169
|
+
}
|
|
170
|
+
|
|
135
171
|
/** The provider's cart JSON as a typed cart, or null when the body is not a cart. */
|
|
136
172
|
export function parseCart(body: unknown): ParsedCart | null {
|
|
137
173
|
const cart = record(body);
|
|
@@ -161,11 +197,13 @@ export function parseCart(body: unknown): ParsedCart | null {
|
|
|
161
197
|
})
|
|
162
198
|
: [];
|
|
163
199
|
const session = cart.session_id;
|
|
200
|
+
const coupons = parseCartCoupons(cart);
|
|
164
201
|
return {
|
|
165
202
|
count,
|
|
166
203
|
sessionId: typeof session === "string" && /^[a-z0-9]{10,64}$/.test(session) ? session : null,
|
|
167
204
|
lines,
|
|
168
205
|
errors,
|
|
206
|
+
...(coupons.length > 0 ? { coupons } : {}),
|
|
169
207
|
};
|
|
170
208
|
}
|
|
171
209
|
|
|
@@ -216,6 +254,121 @@ export function writeStoredCount(
|
|
|
216
254
|
}
|
|
217
255
|
}
|
|
218
256
|
|
|
257
|
+
type StorageLike = Pick<Storage, "getItem" | "setItem" | "removeItem">;
|
|
258
|
+
|
|
259
|
+
export type CouponStorageHost =
|
|
260
|
+
| { sessionStorage?: StorageLike | null; localStorage?: StorageLike | null }
|
|
261
|
+
| StorageLike
|
|
262
|
+
| null
|
|
263
|
+
| undefined;
|
|
264
|
+
|
|
265
|
+
function normalizeCookiePath(cookiePath: string): string {
|
|
266
|
+
const trimmed = cookiePath.trim();
|
|
267
|
+
if (trimmed === "" || trimmed === "/") return "/";
|
|
268
|
+
const withLead = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
|
|
269
|
+
return `${withLead.replace(/\/+$/, "")}/`;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export function pendingCouponKey(cookiePath: string): string {
|
|
273
|
+
return `tot_pending_coupon:${normalizeCookiePath(cookiePath)}`;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export function normalizePromoCoupon(raw: unknown): string | null {
|
|
277
|
+
if (typeof raw !== "string") return null;
|
|
278
|
+
const code = raw.trim();
|
|
279
|
+
if (!PROMO_COUPON_CODE.test(code)) return null;
|
|
280
|
+
if (code.toLowerCase() === RESERVED_EXCISE_COUPON) return null;
|
|
281
|
+
return code;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function resolveCouponStorages(host: CouponStorageHost): StorageLike[] {
|
|
285
|
+
if (!host || typeof host !== "object") return [];
|
|
286
|
+
if ("getItem" in host && typeof host.getItem === "function") {
|
|
287
|
+
return [host];
|
|
288
|
+
}
|
|
289
|
+
const out: StorageLike[] = [];
|
|
290
|
+
const winHost = host as { sessionStorage?: StorageLike | null; localStorage?: StorageLike | null };
|
|
291
|
+
try {
|
|
292
|
+
if (winHost.sessionStorage) out.push(winHost.sessionStorage);
|
|
293
|
+
} catch {
|
|
294
|
+
/* sessionStorage unavailable */
|
|
295
|
+
}
|
|
296
|
+
try {
|
|
297
|
+
if (winHost.localStorage && !out.includes(winHost.localStorage)) out.push(winHost.localStorage);
|
|
298
|
+
} catch {
|
|
299
|
+
/* localStorage unavailable */
|
|
300
|
+
}
|
|
301
|
+
return out;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export function readPendingCoupon(host: CouponStorageHost, cookiePath = "/"): string | null {
|
|
305
|
+
const key = pendingCouponKey(cookiePath);
|
|
306
|
+
for (const storage of resolveCouponStorages(host)) {
|
|
307
|
+
try {
|
|
308
|
+
const valid = normalizePromoCoupon(storage.getItem(key));
|
|
309
|
+
if (valid) return valid;
|
|
310
|
+
} catch {
|
|
311
|
+
/* storage disabled */
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export function writePendingCoupon(
|
|
318
|
+
host: CouponStorageHost,
|
|
319
|
+
cookiePath: string,
|
|
320
|
+
code: string | null,
|
|
321
|
+
): string | null {
|
|
322
|
+
const key = pendingCouponKey(cookiePath);
|
|
323
|
+
const storages = resolveCouponStorages(host);
|
|
324
|
+
if (code === null || code === "") {
|
|
325
|
+
for (const storage of storages) {
|
|
326
|
+
try {
|
|
327
|
+
storage.removeItem(key);
|
|
328
|
+
} catch {
|
|
329
|
+
/* storage disabled */
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
const valid = normalizePromoCoupon(code);
|
|
335
|
+
if (!valid) return null;
|
|
336
|
+
for (const storage of storages) {
|
|
337
|
+
try {
|
|
338
|
+
storage.setItem(key, valid);
|
|
339
|
+
} catch {
|
|
340
|
+
/* storage disabled */
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return valid;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export function captureCouponFromUrl(
|
|
347
|
+
win: ({ location?: { search?: string } } & CouponStorageHost) | null | undefined,
|
|
348
|
+
cookiePath = "/",
|
|
349
|
+
): string | null {
|
|
350
|
+
const search = win?.location?.search;
|
|
351
|
+
if (typeof search !== "string" || !search) return null;
|
|
352
|
+
const params = new URLSearchParams(search);
|
|
353
|
+
const raw = params.get("coupon") ?? params.get("promo");
|
|
354
|
+
const valid = normalizePromoCoupon(raw);
|
|
355
|
+
if (!valid) return null;
|
|
356
|
+
return writePendingCoupon(win, cookiePath, valid);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function attachPendingCouponToForm(form: HTMLFormElement, doc: Document, coupon: string): void {
|
|
360
|
+
const existing = form.querySelector<HTMLInputElement>('input[name="coupon"]');
|
|
361
|
+
if (existing) {
|
|
362
|
+
if (!normalizePromoCoupon(existing.value)) existing.value = coupon;
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
const input = doc.createElement("input");
|
|
366
|
+
input.type = "hidden";
|
|
367
|
+
input.name = "coupon";
|
|
368
|
+
input.value = coupon;
|
|
369
|
+
form.appendChild(input);
|
|
370
|
+
}
|
|
371
|
+
|
|
219
372
|
export interface CartEnv {
|
|
220
373
|
doc: Document;
|
|
221
374
|
win: Window;
|
|
@@ -352,8 +505,10 @@ export function describeAdded(
|
|
|
352
505
|
cart: ParsedCart,
|
|
353
506
|
form: { title: string; code: string; quantity: number },
|
|
354
507
|
cartHref: string,
|
|
508
|
+
appliedCoupon?: string | null,
|
|
355
509
|
): CartAddedDetail {
|
|
356
510
|
const line = addedLine(cart, form.code);
|
|
511
|
+
const coupon = normalizePromoCoupon(appliedCoupon ?? cart.coupons?.[0]);
|
|
357
512
|
return {
|
|
358
513
|
status: "added",
|
|
359
514
|
title: form.title || line?.name || "Item",
|
|
@@ -362,6 +517,7 @@ export function describeAdded(
|
|
|
362
517
|
image: line?.image ?? null,
|
|
363
518
|
count: cart.count,
|
|
364
519
|
cartHref,
|
|
520
|
+
...(coupon ? { appliedCoupon: coupon } : {}),
|
|
365
521
|
};
|
|
366
522
|
}
|
|
367
523
|
|
|
@@ -389,7 +545,21 @@ export async function addFromForm(
|
|
|
389
545
|
env: CartEnv,
|
|
390
546
|
): Promise<boolean> {
|
|
391
547
|
const cartOrigin = new URL(config.cartUrl).origin;
|
|
548
|
+
const pendingCoupon =
|
|
549
|
+
readPendingCoupon(env.win, config.cookiePath) ??
|
|
550
|
+
readPendingCoupon(env.storage, config.cookiePath) ??
|
|
551
|
+
captureCouponFromUrl(env.win, config.cookiePath);
|
|
552
|
+
if (pendingCoupon) {
|
|
553
|
+
attachPendingCouponToForm(form, env.doc, pendingCoupon);
|
|
554
|
+
}
|
|
392
555
|
const data = new FormData(form);
|
|
556
|
+
const existingCoupon = data.get("coupon");
|
|
557
|
+
if (existingCoupon !== null && !normalizePromoCoupon(existingCoupon)) {
|
|
558
|
+
data.delete("coupon");
|
|
559
|
+
}
|
|
560
|
+
if (pendingCoupon && !normalizePromoCoupon(data.get("coupon"))) {
|
|
561
|
+
data.set("coupon", pendingCoupon);
|
|
562
|
+
}
|
|
393
563
|
let location: string;
|
|
394
564
|
try {
|
|
395
565
|
const res = await env.fetch(form.action, {
|
|
@@ -408,19 +578,24 @@ export async function addFromForm(
|
|
|
408
578
|
const key = storedCountKey(config.cookiePath);
|
|
409
579
|
const quantity = wholeNumber(submittedField(data, "quantity")) || 1;
|
|
410
580
|
try {
|
|
411
|
-
const
|
|
581
|
+
const rawBody = await loadCartJsonp(location, cartOrigin, env);
|
|
582
|
+
const cart = parseCart(rawBody);
|
|
412
583
|
if (!cart || cart.errors.length > 0 || cart.count === 0) {
|
|
413
584
|
announce(env, { status: "error", cartHref: config.cartUrl });
|
|
414
585
|
return true;
|
|
415
586
|
}
|
|
416
587
|
writeStoredCount(env.storage, key, cart.count);
|
|
417
588
|
renderCartCount(env.doc, cart.count);
|
|
589
|
+
const submittedCoupon = normalizePromoCoupon(data.get("coupon"));
|
|
590
|
+
const appliedCoupon =
|
|
591
|
+
parseCartCoupons(rawBody)[0] ?? pendingCoupon ?? submittedCoupon ?? undefined;
|
|
418
592
|
announce(
|
|
419
593
|
env,
|
|
420
594
|
describeAdded(
|
|
421
595
|
cart,
|
|
422
596
|
{ title: form.dataset.productTitle ?? "", code: submittedField(data, "code"), quantity },
|
|
423
597
|
cartHrefFor(config, cart.sessionId),
|
|
598
|
+
appliedCoupon,
|
|
424
599
|
),
|
|
425
600
|
);
|
|
426
601
|
} catch {
|
|
@@ -455,6 +630,21 @@ export function bootCartStateFromDom(win: Window): void {
|
|
|
455
630
|
* over released add-to-cart submits.
|
|
456
631
|
*/
|
|
457
632
|
export function bootCartState(config: CartStateConfig, env: CartEnv): () => void {
|
|
633
|
+
const capturedCoupon = captureCouponFromUrl(env.win, config.cookiePath);
|
|
634
|
+
if (capturedCoupon && env.storage) {
|
|
635
|
+
writePendingCoupon(env.storage, config.cookiePath, capturedCoupon);
|
|
636
|
+
}
|
|
637
|
+
const activeCoupon =
|
|
638
|
+
capturedCoupon ??
|
|
639
|
+
readPendingCoupon(env.win, config.cookiePath) ??
|
|
640
|
+
readPendingCoupon(env.storage, config.cookiePath);
|
|
641
|
+
if (activeCoupon) {
|
|
642
|
+
const stateEl = env.doc.querySelector<HTMLElement>("[data-cart-state]");
|
|
643
|
+
if (stateEl) stateEl.dataset.pendingCoupon = activeCoupon;
|
|
644
|
+
for (const form of env.doc.querySelectorAll<HTMLFormElement>(MANAGED_CART_FORM)) {
|
|
645
|
+
attachPendingCouponToForm(form, env.doc, activeCoupon);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
458
648
|
const key = storedCountKey(config.cookiePath);
|
|
459
649
|
const known = () => readStoredCount(env.storage, key);
|
|
460
650
|
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.1",
|
|
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 {
|
|
@@ -132,6 +140,8 @@ export interface CheckoutOrderDetailResponse {
|
|
|
132
140
|
export interface CheckoutOrderListFilters {
|
|
133
141
|
queue?: string;
|
|
134
142
|
status?: string;
|
|
143
|
+
/** Optional redeemed coupon code filter (case-insensitive). */
|
|
144
|
+
coupon?: string;
|
|
135
145
|
/** ISO datetime lower bound. */
|
|
136
146
|
from?: string;
|
|
137
147
|
/** ISO datetime upper bound. */
|
|
@@ -345,6 +355,7 @@ export interface PublicCommerceEvent {
|
|
|
345
355
|
label: LabelState;
|
|
346
356
|
totals: MinorTotals;
|
|
347
357
|
verificationDetail: CommerceEvidence;
|
|
358
|
+
discounts?: readonly CheckoutOrderDiscount[];
|
|
348
359
|
}
|
|
349
360
|
|
|
350
361
|
export type CommerceRole = "owner" | "caller" | "denied";
|
|
@@ -774,6 +785,7 @@ export function publicCommerceEvent(
|
|
|
774
785
|
label: LabelState;
|
|
775
786
|
totals: MinorTotals;
|
|
776
787
|
verificationDetail: CommerceEvidence;
|
|
788
|
+
discounts?: readonly CheckoutOrderDiscount[];
|
|
777
789
|
} & Record<string, unknown>,
|
|
778
790
|
): PublicCommerceEvent {
|
|
779
791
|
if (!Number.isSafeInteger(input.eventVersion) || input.eventVersion < 1) {
|
|
@@ -805,6 +817,9 @@ export function publicCommerceEvent(
|
|
|
805
817
|
risk: input.verificationDetail.risk,
|
|
806
818
|
stock: input.verificationDetail.stock,
|
|
807
819
|
},
|
|
820
|
+
...(Array.isArray(input.discounts) && input.discounts.length > 0
|
|
821
|
+
? { discounts: input.discounts.map((d) => ({ code: d.code, amountMinor: d.amountMinor })) }
|
|
822
|
+
: {}),
|
|
808
823
|
};
|
|
809
824
|
}
|
|
810
825
|
|