@wikala/spmkt 4.0.0-alpha.1 → 4.0.0-alpha.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/dist/core/api/address.d.ts +6 -1
- package/dist/core/api/address.js +6 -1
- package/dist/core/api/address.js.map +1 -1
- package/dist/core/api/cart.d.ts +2 -21
- package/dist/core/api/cart.js +4 -30
- package/dist/core/api/cart.js.map +1 -1
- package/dist/core/api/checkout.d.ts +2 -9
- package/dist/core/api/checkout.js +3 -10
- package/dist/core/api/checkout.js.map +1 -1
- package/dist/core/api/index.d.ts +4 -4
- package/dist/core/api/product.d.ts +2 -10
- package/dist/core/api/product.js +0 -12
- package/dist/core/api/product.js.map +1 -1
- package/dist/core/events.d.ts +4 -3
- package/dist/core/events.js.map +1 -1
- package/dist/core/index.d.ts +4 -4
- package/dist/core/index.js +17 -13
- package/dist/core/money.d.ts +2 -0
- package/dist/core/money.js +5 -0
- package/dist/core/money.js.map +1 -1
- package/dist/core/page-events.d.ts +17 -0
- package/dist/core/page-events.js +37 -3
- package/dist/core/page-events.js.map +1 -1
- package/dist/core/state.d.ts +8 -1
- package/dist/core/state.js +75 -3
- package/dist/core/state.js.map +1 -1
- package/dist/core/stores/cart.d.ts +19 -20
- package/dist/core/stores/cart.js +38 -46
- package/dist/core/stores/cart.js.map +1 -1
- package/dist/core/stores/checkout.d.ts +10 -12
- package/dist/core/stores/checkout.js +19 -24
- package/dist/core/stores/checkout.js.map +1 -1
- package/dist/core/stores/index.d.ts +2 -2
- package/dist/core/types.d.ts +29 -7
- package/dist/elements/add-to-cart/add-to-cart.d.ts +23 -8
- package/dist/elements/add-to-cart/add-to-cart.js +62 -28
- package/dist/elements/add-to-cart/add-to-cart.js.map +1 -1
- package/dist/elements/add-to-cart/index.d.ts +1 -1
- package/dist/elements/address-book/address-book.d.ts +20 -15
- package/dist/elements/address-book/address-book.js +98 -34
- package/dist/elements/address-book/address-book.js.map +1 -1
- package/dist/elements/carousel/carousel.d.ts +11 -1
- package/dist/elements/carousel/carousel.js +22 -5
- package/dist/elements/carousel/carousel.js.map +1 -1
- package/dist/elements/cart/cart.d.ts +27 -27
- package/dist/elements/cart/cart.js +195 -80
- package/dist/elements/cart/cart.js.map +1 -1
- package/dist/elements/checkout/checkout.d.ts +13 -20
- package/dist/elements/checkout/checkout.js +73 -40
- package/dist/elements/checkout/checkout.js.map +1 -1
- package/dist/elements/checkout-delivery/checkout-delivery.d.ts +2 -9
- package/dist/elements/checkout-delivery/checkout-delivery.js +1 -8
- package/dist/elements/checkout-delivery/checkout-delivery.js.map +1 -1
- package/dist/elements/checkout-payment/checkout-payment.d.ts +2 -9
- package/dist/elements/checkout-payment/checkout-payment.js +2 -9
- package/dist/elements/checkout-payment/checkout-payment.js.map +1 -1
- package/dist/elements/collection/collection.d.ts +5 -9
- package/dist/elements/collection/collection.js +20 -20
- package/dist/elements/collection/collection.js.map +1 -1
- package/dist/elements/dialog/dialog.d.ts +7 -3
- package/dist/elements/dialog/dialog.js +12 -4
- package/dist/elements/dialog/dialog.js.map +1 -1
- package/dist/elements/mini-cart/mini-cart.d.ts +15 -15
- package/dist/elements/mini-cart/mini-cart.js +74 -62
- package/dist/elements/mini-cart/mini-cart.js.map +1 -1
- package/dist/elements/order-confirmation/index.d.ts +3 -0
- package/dist/elements/order-confirmation/index.js +7 -0
- package/dist/elements/order-confirmation/index.js.map +1 -0
- package/dist/elements/order-confirmation/order-confirmation.d.ts +35 -0
- package/dist/elements/order-confirmation/order-confirmation.js +123 -0
- package/dist/elements/order-confirmation/order-confirmation.js.map +1 -0
- package/dist/elements/quick-view/quick-view.d.ts +10 -7
- package/dist/elements/quick-view/quick-view.js +11 -5
- package/dist/elements/quick-view/quick-view.js.map +1 -1
- package/dist/elements/related/related.d.ts +8 -13
- package/dist/elements/related/related.js +20 -17
- package/dist/elements/related/related.js.map +1 -1
- package/dist/elements/shared/paged-section.js +1 -1
- package/dist/elements/shared/paged-section.js.map +1 -1
- package/dist/elements/shared/totals.d.ts +53 -0
- package/dist/elements/shared/totals.js +82 -0
- package/dist/elements/shared/totals.js.map +1 -0
- package/dist/elements/variant-picker/variant-picker.d.ts +5 -3
- package/dist/elements/variant-picker/variant-picker.js +6 -4
- package/dist/elements/variant-picker/variant-picker.js.map +1 -1
- package/dist/lit/fragments.d.ts +11 -10
- package/dist/lit/fragments.js +9 -10
- package/dist/lit/fragments.js.map +1 -1
- package/dist/locales/en.json +48 -3
- package/dist/locales/sr.json +49 -3
- package/package.json +1 -1
|
@@ -3,12 +3,12 @@ import { validateGuestEmail, hasAccount, validateAddress, fetchDeliveryOptions,
|
|
|
3
3
|
import { HttpError } from "../errors.js";
|
|
4
4
|
import { dispatch } from "../events.js";
|
|
5
5
|
import { storefront } from "../state.js";
|
|
6
|
-
import { cartCount, cartLineToItem, takeCart, cartEmptied } from "./cart.js";
|
|
6
|
+
import { cart, cartCount, cartLineToItem, takeCart, cartEmptied } from "./cart.js";
|
|
7
7
|
import { checkoutDraft, firstBeginOf, updateDraft, clearCheckoutDraft } from "./checkout-draft.js";
|
|
8
8
|
import { EMPTY_DRAFT } from "./checkout-draft.js";
|
|
9
9
|
import { customerSignedIn } from "./customer.js";
|
|
10
10
|
const checkoutPending = signal(false);
|
|
11
|
-
const
|
|
11
|
+
const summaryPriced = signal(false);
|
|
12
12
|
function deliveryComplete(draft = checkoutDraft.value, signedIn = customerSignedIn.value) {
|
|
13
13
|
if (!draft.delivery) return false;
|
|
14
14
|
if (draft.delivery.reservations && !draft.slot) return false;
|
|
@@ -47,18 +47,21 @@ function confirmIdentity(identity, signal2) {
|
|
|
47
47
|
function chooseKind(kind) {
|
|
48
48
|
if (checkoutDraft.value.kind !== kind) {
|
|
49
49
|
updateDraft({ kind, delivery: null, slot: null });
|
|
50
|
+
summaryPriced.value = false;
|
|
50
51
|
}
|
|
51
52
|
}
|
|
52
53
|
function confirmAddress(address, signal2) {
|
|
53
54
|
return pending(async () => {
|
|
54
55
|
const validated = await validateAddress(address, signal2);
|
|
55
56
|
updateDraft({ address: { ...address, ...validated, id: void 0 }, delivery: null, slot: null });
|
|
57
|
+
summaryPriced.value = false;
|
|
56
58
|
return validated;
|
|
57
59
|
});
|
|
58
60
|
}
|
|
59
61
|
function chooseAddress(addressId) {
|
|
60
62
|
if (checkoutDraft.value.addressId !== addressId) {
|
|
61
63
|
updateDraft({ addressId, delivery: null, slot: null });
|
|
64
|
+
summaryPriced.value = false;
|
|
62
65
|
}
|
|
63
66
|
}
|
|
64
67
|
function loadDeliveryOptions(signal2) {
|
|
@@ -75,7 +78,7 @@ function chooseDelivery(choice, options = {}) {
|
|
|
75
78
|
return pending(async () => {
|
|
76
79
|
const draft = checkoutDraft.value;
|
|
77
80
|
const where = draft.addressId !== null && customerSignedIn.value ? { address_id: draft.addressId } : { country_id: draft.address?.country_id, state_id: draft.address?.state_id ?? null };
|
|
78
|
-
const
|
|
81
|
+
const summary = await fetchSummary(
|
|
79
82
|
{
|
|
80
83
|
delivery_method_id: choice.methodId,
|
|
81
84
|
delivery_cost_id: choice.costId,
|
|
@@ -92,9 +95,9 @@ function chooseDelivery(choice, options = {}) {
|
|
|
92
95
|
delivery: choice,
|
|
93
96
|
slot: choice.methodId === latest.delivery?.methodId ? latest.slot : null
|
|
94
97
|
});
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
return
|
|
98
|
+
const priced = takeCart(summary);
|
|
99
|
+
summaryPriced.value = true;
|
|
100
|
+
return priced;
|
|
98
101
|
});
|
|
99
102
|
}
|
|
100
103
|
function chooseSlot(slot) {
|
|
@@ -117,20 +120,16 @@ function loadPaymentMethods(signal2) {
|
|
|
117
120
|
);
|
|
118
121
|
}
|
|
119
122
|
function analytics() {
|
|
120
|
-
const
|
|
121
|
-
const currency = cart?.items[0]?.currency || storefront().currency;
|
|
123
|
+
const current = cart.value;
|
|
122
124
|
return {
|
|
123
|
-
currency,
|
|
124
|
-
value:
|
|
125
|
-
items:
|
|
126
|
-
...
|
|
125
|
+
currency: current.items[0]?.currency || storefront().currency,
|
|
126
|
+
value: current.total,
|
|
127
|
+
items: current.items.map((line) => cartLineToItem(line)),
|
|
128
|
+
...current.coupon_code ? { coupon: current.coupon_code } : {}
|
|
127
129
|
};
|
|
128
130
|
}
|
|
129
|
-
function setCheckoutCart(cart) {
|
|
130
|
-
checkoutCart.value = cart;
|
|
131
|
-
}
|
|
132
131
|
function beginCheckout() {
|
|
133
|
-
const lines =
|
|
132
|
+
const lines = cart.value.items;
|
|
134
133
|
const signature = lines.map((line) => `${line.id}:${line.qty}`).sort().join(",");
|
|
135
134
|
if (!firstBeginOf(signature)) return;
|
|
136
135
|
dispatch(document, "spmkt:begin-checkout", analytics());
|
|
@@ -159,7 +158,7 @@ function writeAttempt(attempt) {
|
|
|
159
158
|
}
|
|
160
159
|
function orderFingerprint(body) {
|
|
161
160
|
const { idempotency_key: _key, recaptcha_token: _token, ...order } = body;
|
|
162
|
-
const lines =
|
|
161
|
+
const lines = cart.value.items.map((line) => `${line.id}x${line.qty}`);
|
|
163
162
|
return JSON.stringify([order, lines]);
|
|
164
163
|
}
|
|
165
164
|
function idempotencyKey(body) {
|
|
@@ -237,14 +236,11 @@ async function submitOrder(input) {
|
|
|
237
236
|
});
|
|
238
237
|
return pending(async () => {
|
|
239
238
|
try {
|
|
240
|
-
const result = await placeOrder(body, {
|
|
241
|
-
guest: !signedIn,
|
|
242
|
-
fragments: input.fragments,
|
|
243
|
-
signal: input.signal
|
|
244
|
-
});
|
|
239
|
+
const result = await placeOrder(body, { guest: !signedIn, signal: input.signal });
|
|
245
240
|
writeAttempt(null);
|
|
246
241
|
if (result.kind === "order") {
|
|
247
242
|
clearCheckoutDraft();
|
|
243
|
+
summaryPriced.value = false;
|
|
248
244
|
cartEmptied();
|
|
249
245
|
}
|
|
250
246
|
return result;
|
|
@@ -274,7 +270,6 @@ export {
|
|
|
274
270
|
EMPTY_DRAFT,
|
|
275
271
|
addOrderCheck,
|
|
276
272
|
beginCheckout,
|
|
277
|
-
checkoutCart,
|
|
278
273
|
checkoutDraft,
|
|
279
274
|
checkoutPending,
|
|
280
275
|
chooseAddress,
|
|
@@ -291,9 +286,9 @@ export {
|
|
|
291
286
|
orderInput,
|
|
292
287
|
passOrderChecks,
|
|
293
288
|
postToGateway,
|
|
294
|
-
setCheckoutCart,
|
|
295
289
|
stepToShow,
|
|
296
290
|
submitOrder,
|
|
291
|
+
summaryPriced,
|
|
297
292
|
updateDraft
|
|
298
293
|
};
|
|
299
294
|
//# sourceMappingURL=checkout.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkout.js","sources":["../../../src/core/stores/checkout.ts"],"sourcesContent":["import { signal } from '@preact/signals-core'\nimport {\n fetchDeliveryOptions,\n fetchPaymentMethods,\n fetchSummary,\n hasAccount,\n placeOrder,\n validateAddress,\n validateGuestEmail,\n type GatewayRedirect,\n type OrderInput,\n type OrderPlaced,\n} from '../api/checkout'\nimport type { Fragments } from '../api/cart'\nimport { HttpError } from '../errors'\nimport { dispatch, type Ga4Item } from '../events'\nimport { storefront } from '../state'\nimport type { Cart, CheckoutAddress, DeliveryOption, PaymentMethodOption } from '../types'\nimport { cartCount, cartEmptied, cartLineToItem, takeCart } from './cart'\nimport {\n checkoutDraft,\n clearCheckoutDraft,\n firstBeginOf,\n updateDraft,\n type CheckoutDraft,\n type CheckoutIdentity,\n type DeliveryChoice,\n} from './checkout-draft'\nimport { customerSignedIn } from './customer'\n\nexport { checkoutDraft, clearCheckoutDraft, updateDraft, reloadDraft, EMPTY_DRAFT } from './checkout-draft'\nexport type { CheckoutDraft, CheckoutIdentity, DeliveryChoice } from './checkout-draft'\n\nexport type CheckoutStep = 'cart' | 'delivery' | 'payment' | 'done'\n\n/** True while a checkout request is in flight; placing an order is refused meanwhile */\nexport const checkoutPending = signal(false)\n/** The cart as the last summary returned it (tax and shipping included) */\nexport const checkoutCart = signal<Cart | null>(null)\n\n/** The delivery step is complete: who, where, how, and when for a method that takes reservations. */\nexport function deliveryComplete(\n draft: CheckoutDraft = checkoutDraft.value,\n signedIn = customerSignedIn.value,\n): boolean {\n if (!draft.delivery) return false\n if (draft.delivery.reservations && !draft.slot) return false\n // Whoever collects a pickup gives their contact details, customers too: the order needs a name and phone\n if (draft.delivery.kind === 'pickup') return draft.identity !== null\n return signedIn ? draft.addressId !== null : draft.identity !== null && draft.address !== null\n}\n\n/**\n * The step to show for a requested one: an empty cart shows the cart, and payment needs a complete delivery\n * step (a later step opened directly, or after the draft was lost, lands on the first incomplete one).\n */\nexport function stepToShow(requested: CheckoutStep): CheckoutStep {\n if (requested === 'done') return 'done'\n if (cartCount.value === 0) return 'cart'\n if (requested === 'payment' && !deliveryComplete()) return 'delivery'\n return requested\n}\n\n/** Checkout requests in flight; checkoutPending stays set until the last of them ends. */\nlet inFlight = 0\n\n/** Run an action with checkoutPending set. */\nasync function pending<T>(action: () => Promise<T>): Promise<T> {\n inFlight++\n checkoutPending.value = true\n try {\n return await action()\n } finally {\n inFlight--\n checkoutPending.value = inFlight > 0\n }\n}\n\n/**\n * Contact details: a guest's e-mail is validated (422 ValidationError per field) and kept. `hasAccount` tells\n * whether that e-mail has an account, so the page can offer to sign in; it does not block. A signed-in\n * customer's (the contact for a pickup) are kept as they are: the account has the e-mail.\n */\nexport function confirmIdentity(\n identity: CheckoutIdentity,\n signal?: AbortSignal,\n): Promise<{ hasAccount: boolean }> {\n if (customerSignedIn.value) {\n updateDraft({ identity })\n return Promise.resolve({ hasAccount: true })\n }\n return pending(async () => {\n await validateGuestEmail(identity.email, signal)\n const exists = await hasAccount(identity.email, signal).catch(() => false)\n updateDraft({ identity })\n return { hasAccount: exists }\n })\n}\n\n/** Delivery to an address, or pickup at the store; another kind drops the chosen method. */\nexport function chooseKind(kind: CheckoutDraft['kind']): void {\n if (checkoutDraft.value.kind !== kind) {\n updateDraft({ kind, delivery: null, slot: null })\n }\n}\n\n/** A guest's delivery address, validated on the server (422 per field). A new address resets the delivery choice. */\nexport function confirmAddress(address: CheckoutAddress, signal?: AbortSignal): Promise<CheckoutAddress> {\n return pending(async () => {\n const validated = await validateAddress(address, signal)\n updateDraft({ address: { ...address, ...validated, id: undefined }, delivery: null, slot: null })\n return validated\n })\n}\n\n/** A signed-in customer's saved address. */\nexport function chooseAddress(addressId: number): void {\n if (checkoutDraft.value.addressId !== addressId) {\n updateDraft({ addressId, delivery: null, slot: null })\n }\n}\n\n/** The delivery options for the draft's address. */\nexport function loadDeliveryOptions(signal?: AbortSignal): Promise<DeliveryOption[]> {\n const draft = checkoutDraft.value\n const target = draft.addressId !== null && customerSignedIn.value ? { id: draft.addressId } : draft.address\n if (!target) {\n return Promise.reject(new Error('No delivery address yet'))\n }\n return pending(() => fetchDeliveryOptions(target, signal))\n}\n\n/** Counts chooseDelivery calls, so an answer overtaken by a later choice is not applied. */\nlet choosing = 0\n\n/**\n * Chooses a delivery and asks the server for the summary with its shipping and tax; `fragments` (e.g.\n * ['cart-summary']) come back rendered with it. The choice is kept only once it is priced: a failed summary\n * leaves the draft's earlier choice (so payment never opens on an unpriced delivery). A choice overtaken by a\n * later one rejects with an AbortError.\n */\nexport function chooseDelivery(\n choice: DeliveryChoice,\n options: { fragments?: readonly string[]; signal?: AbortSignal } = {},\n): Promise<Fragments> {\n const call = ++choosing\n return pending(async () => {\n const draft = checkoutDraft.value\n const where =\n draft.addressId !== null && customerSignedIn.value\n ? { address_id: draft.addressId }\n : { country_id: draft.address?.country_id, state_id: draft.address?.state_id ?? null }\n const { cart, fragments } = await fetchSummary(\n {\n delivery_method_id: choice.methodId,\n delivery_cost_id: choice.costId,\n ...(choice.kind === 'pickup' ? {} : where),\n },\n options,\n )\n if (call !== choosing) {\n throw new DOMException('A later delivery choice replaced this one', 'AbortError')\n }\n const latest = checkoutDraft.value\n updateDraft({\n kind: choice.kind,\n delivery: choice,\n slot: choice.methodId === latest.delivery?.methodId ? latest.slot : null,\n })\n checkoutCart.value = cart\n takeCart(cart)\n return fragments\n })\n}\n\nexport function chooseSlot(slot: string | null): void {\n updateDraft({ slot })\n}\n\n/** Payment methods for the chosen delivery; business customers may see more (bank transfer). */\nexport function loadPaymentMethods(signal?: AbortSignal): Promise<PaymentMethodOption[]> {\n const draft = checkoutDraft.value\n if (!draft.delivery) {\n return Promise.reject(new Error('No delivery chosen yet'))\n }\n return pending(() =>\n fetchPaymentMethods(\n {\n method: draft.delivery!.kind,\n rate_id: draft.delivery!.costId,\n address_type: draft.business ? 'business' : 'personal',\n },\n signal,\n ),\n )\n}\n\n/** The cart in GA4 terms, from the last summary (or the cart the page handed over). */\nfunction analytics(): { currency: string; value: number; items: Ga4Item[]; coupon?: string } {\n const cart = checkoutCart.value\n const currency = cart?.items[0]?.currency || storefront().currency\n return {\n currency,\n value: cart ? cart.total : 0,\n items: cart ? cart.items.map((line) => cartLineToItem(line)) : [],\n ...(cart?.coupon_code ? { coupon: cart.coupon_code } : {}),\n }\n}\n\n/** The page hands over the cart it rendered, so analytics has the items before any summary request. */\nexport function setCheckoutCart(cart: Cart): void {\n checkoutCart.value = cart\n}\n\n/** Announces the checkout as begun, once per cart in this tab: not again when the page is reloaded. */\nexport function beginCheckout(): void {\n const lines = checkoutCart.value?.items ?? []\n const signature = lines\n .map((line) => `${line.id}:${line.qty}`)\n .sort()\n .join(',')\n if (!firstBeginOf(signature)) return\n dispatch(document, 'spmkt:begin-checkout', analytics())\n}\n\nexport function completeDelivery(): void {\n const tier = checkoutDraft.value.delivery?.name\n dispatch(document, 'spmkt:add-shipping-info', { ...analytics(), ...(tier ? { shipping_tier: tier } : {}) })\n}\n\nexport interface PlaceOrderInput {\n paymentMethodId: number\n /** For analytics */\n paymentName?: string\n note?: string | null\n recaptchaToken?: string | null\n fragments?: readonly string[]\n signal?: AbortSignal\n}\n\n/**\n * The idempotency key of an order attempt whose outcome is unknown, with the order it was for. It is kept\n * (in sessionStorage, so a reload keeps it too) until the server answers for sure: a placed order or a\n * refusal (4xx). Until then, sending the same order again reuses the key, so the server places it once.\n * Another order (changed cart, delivery, payment...) gets a new key.\n */\ninterface Attempt {\n key: string\n order: string\n}\n\nconst ATTEMPT_KEY = 'spmkt:order-attempt'\nlet memoryAttempt: Attempt | null = null\n\nfunction readAttempt(): Attempt | null {\n try {\n const raw = sessionStorage.getItem(ATTEMPT_KEY)\n return raw ? (JSON.parse(raw) as Attempt) : null\n } catch {\n return memoryAttempt\n }\n}\n\nfunction writeAttempt(attempt: Attempt | null): void {\n memoryAttempt = attempt\n try {\n if (attempt) sessionStorage.setItem(ATTEMPT_KEY, JSON.stringify(attempt))\n else sessionStorage.removeItem(ATTEMPT_KEY)\n } catch {\n // storage blocked: the key lives for this page only\n }\n}\n\n/** What makes two attempts the same order: the body without its key and token, and the cart's lines. */\nfunction orderFingerprint(body: OrderInput): string {\n const { idempotency_key: _key, recaptcha_token: _token, ...order } = body\n const lines = (checkoutCart.value?.items ?? []).map((line) => `${line.id}x${line.qty}`)\n return JSON.stringify([order, lines])\n}\n\nfunction idempotencyKey(body: OrderInput): string {\n const order = orderFingerprint(body)\n const kept = readAttempt()\n if (kept && kept.order === order) return kept.key\n const key = globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`\n writeAttempt({ key, order })\n return key\n}\n\n/** The server answered for sure: refused (4xx, except a conflict with an attempt still being processed). */\nfunction refused(error: unknown): boolean {\n return error instanceof HttpError && error.status >= 400 && error.status < 500 && error.status !== 409\n}\n\n/** The request body for the draft (guest or signed in, delivery or pickup). */\nexport function orderInput(draft: CheckoutDraft, input: PlaceOrderInput, signedIn: boolean): OrderInput {\n const delivery = draft.delivery\n if (!delivery) throw new Error('No delivery chosen yet')\n const company = draft.business && draft.company ? { type: 'business' as const, ...draft.company } : {}\n const base: OrderInput = {\n idempotency_key: '',\n payment_method_id: input.paymentMethodId,\n delivery_method_id: delivery.methodId,\n delivery_cost_id: delivery.costId,\n reservation_slot: draft.slot,\n note: input.note ?? null,\n recaptcha_token: input.recaptchaToken ?? null,\n }\n if (signedIn && delivery.kind === 'delivery') {\n return {\n ...base,\n shipping_address_id: draft.addressId ?? undefined,\n billing_address_id: draft.billingAddressId ?? draft.addressId ?? undefined,\n }\n }\n const identity = draft.identity\n if (delivery.kind === 'pickup' && !identity) throw new Error('No contact details for the pickup yet')\n const contact = {\n first_name: identity?.first_name ?? draft.address?.first_name ?? '',\n last_name: identity?.last_name ?? draft.address?.last_name ?? '',\n phone: identity?.phone ?? draft.address?.phone ?? null,\n }\n const shipping: CheckoutAddress =\n delivery.kind === 'pickup'\n ? { type: 'customer.contact', ...contact }\n : { ...(draft.address as CheckoutAddress) }\n // A signed-in customer's pickup bills a saved address when one was chosen\n if (signedIn && draft.billingAddressId !== null) {\n return { ...base, shipping_address: shipping, billing_address_id: draft.billingAddressId }\n }\n const billingSource = draft.billingAddress ?? shipping\n // A business order bills the company; otherwise a pickup contact stays a contact, and an address is personal\n const billingType = draft.business\n ? 'business'\n : billingSource.type === 'customer.contact'\n ? 'customer.contact'\n : 'personal'\n return {\n ...base,\n ...(signedIn ? {} : { email: identity?.email }),\n shipping_address: shipping,\n billing_address: { ...billingSource, ...company, type: billingType },\n }\n}\n\n/**\n * A check that must pass before an order is placed (e.g. the age check): resolves false to stop, after telling\n * the visitor why. Checks run in the order they were added, after the page's own (method, terms).\n */\nexport type OrderCheck = () => Promise<boolean>\n\nconst orderChecks = new Set<OrderCheck>()\n\n/** Adds a check before placing the order; returns its removal (call it when the element leaves the page). */\nexport function addOrderCheck(check: OrderCheck): () => void {\n orderChecks.add(check)\n return () => orderChecks.delete(check)\n}\n\n/** Runs the checks in turn and stops at the first that does not pass. */\nexport async function passOrderChecks(): Promise<boolean> {\n for (const check of [...orderChecks]) {\n if (!(await check())) return false\n }\n return true\n}\n\n/**\n * Places the order. A two-step payment method answers with the gateway's URL and payload (post them; see\n * postToGateway); an instant one with the order. Refused while another checkout request is in flight. The\n * same order sent again after an answer that did not settle it (no answer, a timeout, a 5xx, an abort) reuses\n * the idempotency key, so a retry cannot order twice.\n */\nexport async function submitOrder(input: PlaceOrderInput): Promise<GatewayRedirect | OrderPlaced> {\n if (checkoutPending.value) {\n throw new Error('A checkout request is already in flight')\n }\n const signedIn = customerSignedIn.value\n const order = orderInput(checkoutDraft.value, input, signedIn)\n const body = { ...order, idempotency_key: idempotencyKey(order) }\n dispatch(document, 'spmkt:add-payment-info', {\n ...analytics(),\n ...(input.paymentName ? { payment_type: input.paymentName } : {}),\n })\n return pending(async () => {\n try {\n const result = await placeOrder(body, {\n guest: !signedIn,\n fragments: input.fragments,\n signal: input.signal,\n })\n writeAttempt(null)\n if (result.kind === 'order') {\n clearCheckoutDraft()\n cartEmptied()\n }\n return result\n } catch (error) {\n if (refused(error)) writeAttempt(null)\n throw error\n }\n })\n}\n\n/**\n * Sends the browser to a two-step gateway: a form POST of exactly the server's payload to exactly its URL, as\n * spmkt 3 does. Nothing is added or changed.\n */\nexport function postToGateway(\n redirect: Pick<GatewayRedirect, 'url' | 'payload'>,\n root: ParentNode = document.body,\n): HTMLFormElement {\n const form = document.createElement('form')\n form.method = 'post'\n form.action = redirect.url\n form.hidden = true\n for (const [name, value] of Object.entries(redirect.payload)) {\n const input = document.createElement('input')\n input.type = 'hidden'\n input.name = name\n input.value = String(value)\n form.append(input)\n }\n root.append(form)\n form.submit()\n return form\n}\n\nexport type { GatewayRedirect, OrderPlaced }\n"],"names":["signal"],"mappings":";;;;;;;;;AAoCO,MAAM,kBAAkB,OAAO,KAAK;AAEpC,MAAM,eAAe,OAAoB,IAAI;AAG7C,SAAS,iBACd,QAAuB,cAAc,OACrC,WAAW,iBAAiB,OACnB;AACT,MAAI,CAAC,MAAM,SAAU,QAAO;AAC5B,MAAI,MAAM,SAAS,gBAAgB,CAAC,MAAM,KAAM,QAAO;AAEvD,MAAI,MAAM,SAAS,SAAS,SAAU,QAAO,MAAM,aAAa;AAChE,SAAO,WAAW,MAAM,cAAc,OAAO,MAAM,aAAa,QAAQ,MAAM,YAAY;AAC5F;AAMO,SAAS,WAAW,WAAuC;AAChE,MAAI,cAAc,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;AAClC,QAAM,QAAQ,WAAW,cAAc,OAAO,OAAO,QAAQ;AAC7D,QAAM,OAAO,EAAE,GAAG,OAAO,iBAAiB,eAAe,KAAK,EAAA;AAC9D,WAAS,UAAU,0BAA0B;AAAA,IAC3C,GAAG,UAAA;AAAA,IACH,GAAI,MAAM,cAAc,EAAE,cAAc,MAAM,YAAA,IAAgB,CAAA;AAAA,EAAC,CAChE;AACD,SAAO,QAAQ,YAAY;AACzB,QAAI;AACF,YAAM,SAAS,MAAM,WAAW,MAAM;AAAA,QACpC,OAAO,CAAC;AAAA,QACR,WAAW,MAAM;AAAA,QACjB,QAAQ,MAAM;AAAA,MAAA,CACf;AACD,mBAAa,IAAI;AACjB,UAAI,OAAO,SAAS,SAAS;AAC3B,2BAAA;AACA,oBAAA;AAAA,MACF;AACA,aAAO;AAAA,IACT,SAAS,OAAO;AACd,UAAI,QAAQ,KAAK,EAAG,cAAa,IAAI;AACrC,YAAM;AAAA,IACR;AAAA,EACF,CAAC;AACH;AAMO,SAAS,cACd,UACA,OAAmB,SAAS,MACX;AACjB,QAAM,OAAO,SAAS,cAAc,MAAM;AAC1C,OAAK,SAAS;AACd,OAAK,SAAS,SAAS;AACvB,OAAK,SAAS;AACd,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,SAAS,OAAO,GAAG;AAC5D,UAAM,QAAQ,SAAS,cAAc,OAAO;AAC5C,UAAM,OAAO;AACb,UAAM,OAAO;AACb,UAAM,QAAQ,OAAO,KAAK;AAC1B,SAAK,OAAO,KAAK;AAAA,EACnB;AACA,OAAK,OAAO,IAAI;AAChB,OAAK,OAAA;AACL,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"checkout.js","sources":["../../../src/core/stores/checkout.ts"],"sourcesContent":["import { signal } from '@preact/signals-core'\nimport {\n fetchDeliveryOptions,\n fetchPaymentMethods,\n fetchSummary,\n hasAccount,\n placeOrder,\n validateAddress,\n validateGuestEmail,\n type GatewayRedirect,\n type OrderInput,\n type OrderPlaced,\n} from '../api/checkout'\nimport { HttpError } from '../errors'\nimport { dispatch, type Ga4Item } from '../events'\nimport { storefront } from '../state'\nimport type { Cart, CheckoutAddress, DeliveryOption, PaymentMethodOption } from '../types'\nimport { cart, cartCount, cartEmptied, cartLineToItem, takeCart } from './cart'\nimport {\n checkoutDraft,\n clearCheckoutDraft,\n firstBeginOf,\n updateDraft,\n type CheckoutDraft,\n type CheckoutIdentity,\n type DeliveryChoice,\n} from './checkout-draft'\nimport { customerSignedIn } from './customer'\n\nexport { checkoutDraft, clearCheckoutDraft, updateDraft, reloadDraft, EMPTY_DRAFT } from './checkout-draft'\nexport type { CheckoutDraft, CheckoutIdentity, DeliveryChoice } from './checkout-draft'\n\nexport type CheckoutStep = 'cart' | 'delivery' | 'payment' | 'done'\n\n/** True while a checkout request is in flight; placing an order is refused meanwhile */\nexport const checkoutPending = signal(false)\n/**\n * The cart signal holds a summary for the current delivery choice (its shipping and tax): set once a summary\n * returned, cleared when the choice is dropped. Until then, the summary shows shipping as \"by the choice\".\n */\nexport const summaryPriced = signal(false)\n\n/** The delivery step is complete: who, where, how, and when for a method that takes reservations. */\nexport function deliveryComplete(\n draft: CheckoutDraft = checkoutDraft.value,\n signedIn = customerSignedIn.value,\n): boolean {\n if (!draft.delivery) return false\n if (draft.delivery.reservations && !draft.slot) return false\n // Whoever collects a pickup gives their contact details, customers too: the order needs a name and phone\n if (draft.delivery.kind === 'pickup') return draft.identity !== null\n return signedIn ? draft.addressId !== null : draft.identity !== null && draft.address !== null\n}\n\n/**\n * The step to show for a requested one: an empty cart shows the cart, and payment needs a complete delivery\n * step (a later step opened directly, or after the draft was lost, lands on the first incomplete one).\n */\nexport function stepToShow(requested: CheckoutStep): CheckoutStep {\n if (requested === 'done') return 'done'\n if (cartCount.value === 0) return 'cart'\n if (requested === 'payment' && !deliveryComplete()) return 'delivery'\n return requested\n}\n\n/** Checkout requests in flight; checkoutPending stays set until the last of them ends. */\nlet inFlight = 0\n\n/** Run an action with checkoutPending set. */\nasync function pending<T>(action: () => Promise<T>): Promise<T> {\n inFlight++\n checkoutPending.value = true\n try {\n return await action()\n } finally {\n inFlight--\n checkoutPending.value = inFlight > 0\n }\n}\n\n/**\n * Contact details: a guest's e-mail is validated (422 ValidationError per field) and kept. `hasAccount` tells\n * whether that e-mail has an account, so the page can offer to sign in; it does not block. A signed-in\n * customer's (the contact for a pickup) are kept as they are: the account has the e-mail.\n */\nexport function confirmIdentity(\n identity: CheckoutIdentity,\n signal?: AbortSignal,\n): Promise<{ hasAccount: boolean }> {\n if (customerSignedIn.value) {\n updateDraft({ identity })\n return Promise.resolve({ hasAccount: true })\n }\n return pending(async () => {\n await validateGuestEmail(identity.email, signal)\n const exists = await hasAccount(identity.email, signal).catch(() => false)\n updateDraft({ identity })\n return { hasAccount: exists }\n })\n}\n\n/** Delivery to an address, or pickup at the store; another kind drops the chosen method. */\nexport function chooseKind(kind: CheckoutDraft['kind']): void {\n if (checkoutDraft.value.kind !== kind) {\n updateDraft({ kind, delivery: null, slot: null })\n summaryPriced.value = false\n }\n}\n\n/** A guest's delivery address, validated on the server (422 per field). A new address resets the delivery choice. */\nexport function confirmAddress(address: CheckoutAddress, signal?: AbortSignal): Promise<CheckoutAddress> {\n return pending(async () => {\n const validated = await validateAddress(address, signal)\n updateDraft({ address: { ...address, ...validated, id: undefined }, delivery: null, slot: null })\n summaryPriced.value = false\n return validated\n })\n}\n\n/** A signed-in customer's saved address. */\nexport function chooseAddress(addressId: number): void {\n if (checkoutDraft.value.addressId !== addressId) {\n updateDraft({ addressId, delivery: null, slot: null })\n summaryPriced.value = false\n }\n}\n\n/** The delivery options for the draft's address. */\nexport function loadDeliveryOptions(signal?: AbortSignal): Promise<DeliveryOption[]> {\n const draft = checkoutDraft.value\n const target = draft.addressId !== null && customerSignedIn.value ? { id: draft.addressId } : draft.address\n if (!target) {\n return Promise.reject(new Error('No delivery address yet'))\n }\n return pending(() => fetchDeliveryOptions(target, signal))\n}\n\n/** Counts chooseDelivery calls, so an answer overtaken by a later choice is not applied. */\nlet choosing = 0\n\n/**\n * Chooses a delivery and asks the server for the summary with its shipping and tax, which becomes the cart\n * (summaryPriced). The choice is kept only once it is priced: a failed summary leaves the draft's earlier\n * choice (so payment never opens on an unpriced delivery). A choice overtaken by a later one rejects with an\n * AbortError.\n */\nexport function chooseDelivery(\n choice: DeliveryChoice,\n options: { signal?: AbortSignal } = {},\n): Promise<Cart> {\n const call = ++choosing\n return pending(async () => {\n const draft = checkoutDraft.value\n const where =\n draft.addressId !== null && customerSignedIn.value\n ? { address_id: draft.addressId }\n : { country_id: draft.address?.country_id, state_id: draft.address?.state_id ?? null }\n const summary = await fetchSummary(\n {\n delivery_method_id: choice.methodId,\n delivery_cost_id: choice.costId,\n ...(choice.kind === 'pickup' ? {} : where),\n },\n options,\n )\n if (call !== choosing) {\n throw new DOMException('A later delivery choice replaced this one', 'AbortError')\n }\n const latest = checkoutDraft.value\n updateDraft({\n kind: choice.kind,\n delivery: choice,\n slot: choice.methodId === latest.delivery?.methodId ? latest.slot : null,\n })\n const priced = takeCart(summary)\n summaryPriced.value = true\n return priced\n })\n}\n\nexport function chooseSlot(slot: string | null): void {\n updateDraft({ slot })\n}\n\n/** Payment methods for the chosen delivery; business customers may see more (bank transfer). */\nexport function loadPaymentMethods(signal?: AbortSignal): Promise<PaymentMethodOption[]> {\n const draft = checkoutDraft.value\n if (!draft.delivery) {\n return Promise.reject(new Error('No delivery chosen yet'))\n }\n return pending(() =>\n fetchPaymentMethods(\n {\n method: draft.delivery!.kind,\n rate_id: draft.delivery!.costId,\n address_type: draft.business ? 'business' : 'personal',\n },\n signal,\n ),\n )\n}\n\n/** The cart in GA4 terms (with the last summary's shipping and tax, once there is one). */\nfunction analytics(): { currency: string; value: number; items: Ga4Item[]; coupon?: string } {\n const current = cart.value\n return {\n currency: current.items[0]?.currency || storefront().currency,\n value: current.total,\n items: current.items.map((line) => cartLineToItem(line)),\n ...(current.coupon_code ? { coupon: current.coupon_code } : {}),\n }\n}\n\n/** Announces the checkout as begun, once per cart in this tab: not again when the page is reloaded. */\nexport function beginCheckout(): void {\n const lines = cart.value.items\n const signature = lines\n .map((line) => `${line.id}:${line.qty}`)\n .sort()\n .join(',')\n if (!firstBeginOf(signature)) return\n dispatch(document, 'spmkt:begin-checkout', analytics())\n}\n\nexport function completeDelivery(): void {\n const tier = checkoutDraft.value.delivery?.name\n dispatch(document, 'spmkt:add-shipping-info', { ...analytics(), ...(tier ? { shipping_tier: tier } : {}) })\n}\n\nexport interface PlaceOrderInput {\n paymentMethodId: number\n /** For analytics */\n paymentName?: string\n note?: string | null\n recaptchaToken?: string | null\n signal?: AbortSignal\n}\n\n/**\n * The idempotency key of an order attempt whose outcome is unknown, with the order it was for. It is kept\n * (in sessionStorage, so a reload keeps it too) until the server answers for sure: a placed order or a\n * refusal (4xx). Until then, sending the same order again reuses the key, so the server places it once.\n * Another order (changed cart, delivery, payment...) gets a new key.\n */\ninterface Attempt {\n key: string\n order: string\n}\n\nconst ATTEMPT_KEY = 'spmkt:order-attempt'\nlet memoryAttempt: Attempt | null = null\n\nfunction readAttempt(): Attempt | null {\n try {\n const raw = sessionStorage.getItem(ATTEMPT_KEY)\n return raw ? (JSON.parse(raw) as Attempt) : null\n } catch {\n return memoryAttempt\n }\n}\n\nfunction writeAttempt(attempt: Attempt | null): void {\n memoryAttempt = attempt\n try {\n if (attempt) sessionStorage.setItem(ATTEMPT_KEY, JSON.stringify(attempt))\n else sessionStorage.removeItem(ATTEMPT_KEY)\n } catch {\n // storage blocked: the key lives for this page only\n }\n}\n\n/** What makes two attempts the same order: the body without its key and token, and the cart's lines. */\nfunction orderFingerprint(body: OrderInput): string {\n const { idempotency_key: _key, recaptcha_token: _token, ...order } = body\n const lines = cart.value.items.map((line) => `${line.id}x${line.qty}`)\n return JSON.stringify([order, lines])\n}\n\nfunction idempotencyKey(body: OrderInput): string {\n const order = orderFingerprint(body)\n const kept = readAttempt()\n if (kept && kept.order === order) return kept.key\n const key = globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`\n writeAttempt({ key, order })\n return key\n}\n\n/** The server answered for sure: refused (4xx, except a conflict with an attempt still being processed). */\nfunction refused(error: unknown): boolean {\n return error instanceof HttpError && error.status >= 400 && error.status < 500 && error.status !== 409\n}\n\n/** The request body for the draft (guest or signed in, delivery or pickup). */\nexport function orderInput(draft: CheckoutDraft, input: PlaceOrderInput, signedIn: boolean): OrderInput {\n const delivery = draft.delivery\n if (!delivery) throw new Error('No delivery chosen yet')\n const company = draft.business && draft.company ? { type: 'business' as const, ...draft.company } : {}\n const base: OrderInput = {\n idempotency_key: '',\n payment_method_id: input.paymentMethodId,\n delivery_method_id: delivery.methodId,\n delivery_cost_id: delivery.costId,\n reservation_slot: draft.slot,\n note: input.note ?? null,\n recaptcha_token: input.recaptchaToken ?? null,\n }\n if (signedIn && delivery.kind === 'delivery') {\n return {\n ...base,\n shipping_address_id: draft.addressId ?? undefined,\n billing_address_id: draft.billingAddressId ?? draft.addressId ?? undefined,\n }\n }\n const identity = draft.identity\n if (delivery.kind === 'pickup' && !identity) throw new Error('No contact details for the pickup yet')\n const contact = {\n first_name: identity?.first_name ?? draft.address?.first_name ?? '',\n last_name: identity?.last_name ?? draft.address?.last_name ?? '',\n phone: identity?.phone ?? draft.address?.phone ?? null,\n }\n const shipping: CheckoutAddress =\n delivery.kind === 'pickup'\n ? { type: 'customer.contact', ...contact }\n : { ...(draft.address as CheckoutAddress) }\n // A signed-in customer's pickup bills a saved address when one was chosen\n if (signedIn && draft.billingAddressId !== null) {\n return { ...base, shipping_address: shipping, billing_address_id: draft.billingAddressId }\n }\n const billingSource = draft.billingAddress ?? shipping\n // A business order bills the company; otherwise a pickup contact stays a contact, and an address is personal\n const billingType = draft.business\n ? 'business'\n : billingSource.type === 'customer.contact'\n ? 'customer.contact'\n : 'personal'\n return {\n ...base,\n ...(signedIn ? {} : { email: identity?.email }),\n shipping_address: shipping,\n billing_address: { ...billingSource, ...company, type: billingType },\n }\n}\n\n/**\n * A check that must pass before an order is placed (e.g. the age check): resolves false to stop, after telling\n * the visitor why. Checks run in the order they were added, after the page's own (method, terms).\n */\nexport type OrderCheck = () => Promise<boolean>\n\nconst orderChecks = new Set<OrderCheck>()\n\n/** Adds a check before placing the order; returns its removal (call it when the element leaves the page). */\nexport function addOrderCheck(check: OrderCheck): () => void {\n orderChecks.add(check)\n return () => orderChecks.delete(check)\n}\n\n/** Runs the checks in turn and stops at the first that does not pass. */\nexport async function passOrderChecks(): Promise<boolean> {\n for (const check of [...orderChecks]) {\n if (!(await check())) return false\n }\n return true\n}\n\n/**\n * Places the order. A two-step payment method answers with the gateway's URL and payload (post them; see\n * postToGateway); an instant one with the order. Refused while another checkout request is in flight. The\n * same order sent again after an answer that did not settle it (no answer, a timeout, a 5xx, an abort) reuses\n * the idempotency key, so a retry cannot order twice.\n */\nexport async function submitOrder(input: PlaceOrderInput): Promise<GatewayRedirect | OrderPlaced> {\n if (checkoutPending.value) {\n throw new Error('A checkout request is already in flight')\n }\n const signedIn = customerSignedIn.value\n const order = orderInput(checkoutDraft.value, input, signedIn)\n const body = { ...order, idempotency_key: idempotencyKey(order) }\n dispatch(document, 'spmkt:add-payment-info', {\n ...analytics(),\n ...(input.paymentName ? { payment_type: input.paymentName } : {}),\n })\n return pending(async () => {\n try {\n const result = await placeOrder(body, { guest: !signedIn, signal: input.signal })\n writeAttempt(null)\n if (result.kind === 'order') {\n clearCheckoutDraft()\n summaryPriced.value = false\n cartEmptied()\n }\n return result\n } catch (error) {\n if (refused(error)) writeAttempt(null)\n throw error\n }\n })\n}\n\n/**\n * Sends the browser to a two-step gateway: a form POST of exactly the server's payload to exactly its URL, as\n * spmkt 3 does. Nothing is added or changed.\n */\nexport function postToGateway(\n redirect: Pick<GatewayRedirect, 'url' | 'payload'>,\n root: ParentNode = document.body,\n): HTMLFormElement {\n const form = document.createElement('form')\n form.method = 'post'\n form.action = redirect.url\n form.hidden = true\n for (const [name, value] of Object.entries(redirect.payload)) {\n const input = document.createElement('input')\n input.type = 'hidden'\n input.name = name\n input.value = String(value)\n form.append(input)\n }\n root.append(form)\n form.submit()\n return form\n}\n\nexport type { GatewayRedirect, OrderPlaced }\n"],"names":["signal"],"mappings":";;;;;;;;;AAmCO,MAAM,kBAAkB,OAAO,KAAK;AAKpC,MAAM,gBAAgB,OAAO,KAAK;AAGlC,SAAS,iBACd,QAAuB,cAAc,OACrC,WAAW,iBAAiB,OACnB;AACT,MAAI,CAAC,MAAM,SAAU,QAAO;AAC5B,MAAI,MAAM,SAAS,gBAAgB,CAAC,MAAM,KAAM,QAAO;AAEvD,MAAI,MAAM,SAAS,SAAS,SAAU,QAAO,MAAM,aAAa;AAChE,SAAO,WAAW,MAAM,cAAc,OAAO,MAAM,aAAa,QAAQ,MAAM,YAAY;AAC5F;AAMO,SAAS,WAAW,WAAuC;AAChE,MAAI,cAAc,OAAQ,QAAO;AACjC,MAAI,UAAU,UAAU,EAAG,QAAO;AAClC,MAAI,cAAc,aAAa,CAAC,iBAAA,EAAoB,QAAO;AAC3D,SAAO;AACT;AAGA,IAAI,WAAW;AAGf,eAAe,QAAW,QAAsC;AAC9D;AACA,kBAAgB,QAAQ;AACxB,MAAI;AACF,WAAO,MAAM,OAAA;AAAA,EACf,UAAA;AACE;AACA,oBAAgB,QAAQ,WAAW;AAAA,EACrC;AACF;AAOO,SAAS,gBACd,UACAA,SACkC;AAClC,MAAI,iBAAiB,OAAO;AAC1B,gBAAY,EAAE,UAAU;AACxB,WAAO,QAAQ,QAAQ,EAAE,YAAY,MAAM;AAAA,EAC7C;AACA,SAAO,QAAQ,YAAY;AACzB,UAAM,mBAAmB,SAAS,OAAOA,OAAM;AAC/C,UAAM,SAAS,MAAM,WAAW,SAAS,OAAOA,OAAM,EAAE,MAAM,MAAM,KAAK;AACzE,gBAAY,EAAE,UAAU;AACxB,WAAO,EAAE,YAAY,OAAA;AAAA,EACvB,CAAC;AACH;AAGO,SAAS,WAAW,MAAmC;AA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AAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,SAAS,OAAO,GAAG;AAC5D,UAAM,QAAQ,SAAS,cAAc,OAAO;AAC5C,UAAM,OAAO;AACb,UAAM,OAAO;AACb,UAAM,QAAQ,OAAO,KAAK;AAC1B,SAAK,OAAO,KAAK;AAAA,EACnB;AACA,OAAK,OAAO,IAAI;AAChB,OAAK,OAAA;AACL,SAAO;AACT;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { cart, cartCount, cartSubtotal, cartLines, cartPending, addToCart, cartLineToItem, setQuantity, applyCoupon, takeCart, cartEmptied, } from './cart';
|
|
2
2
|
export type { QuantityChange } from './cart';
|
|
3
|
-
export { checkoutDraft, checkoutPending,
|
|
3
|
+
export { checkoutDraft, checkoutPending, summaryPriced, updateDraft, clearCheckoutDraft, deliveryComplete, stepToShow, confirmIdentity, confirmAddress, chooseAddress, chooseKind, loadDeliveryOptions, chooseDelivery, chooseSlot, loadPaymentMethods, beginCheckout, completeDelivery, orderInput, submitOrder, postToGateway, addOrderCheck, passOrderChecks, EMPTY_DRAFT, } from './checkout';
|
|
4
4
|
export type { CheckoutStep, CheckoutIdentity, DeliveryChoice, CheckoutDraft, PlaceOrderInput, OrderCheck, } from './checkout';
|
|
5
5
|
export { customerSignedIn, customerName } from './customer';
|
|
6
6
|
export { preferredLocation, retailLocations, locationPending, changeLocation } from './location';
|
package/dist/core/types.d.ts
CHANGED
|
@@ -16,10 +16,10 @@ export interface StorefrontState {
|
|
|
16
16
|
/** ISO code, for analytics */
|
|
17
17
|
currency: string;
|
|
18
18
|
money: MoneyFormat;
|
|
19
|
-
cart
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
19
|
+
/** The whole cart, as the cart endpoints answer (Cart::jsonSerialize()) */
|
|
20
|
+
cart: Cart;
|
|
21
|
+
/** Shop prices include tax (site.price_includes_tax): the tax row says "included" instead of adding it */
|
|
22
|
+
pricesIncludeTax: boolean;
|
|
23
23
|
customer: {
|
|
24
24
|
signedIn: boolean;
|
|
25
25
|
name: string | null;
|
|
@@ -50,7 +50,7 @@ export interface CheckoutFlags {
|
|
|
50
50
|
/** An age check before placing an order (spmkt-age-check; the page gives it the rules by region) */
|
|
51
51
|
ageVerification: boolean;
|
|
52
52
|
}
|
|
53
|
-
/** A cart line as CartController returns it (
|
|
53
|
+
/** A cart line as CartController returns it (CartItem::jsonSerialize()). */
|
|
54
54
|
export interface CartLine {
|
|
55
55
|
id: number;
|
|
56
56
|
name: string;
|
|
@@ -72,7 +72,7 @@ export interface CartLine {
|
|
|
72
72
|
parent_name: string;
|
|
73
73
|
storefront_visibility: boolean;
|
|
74
74
|
}
|
|
75
|
-
/** GET/POST /cart */
|
|
75
|
+
/** GET/POST /cart, POST /cart/coupon and /cart/summary (Cart::jsonSerialize()); the page state's cart too */
|
|
76
76
|
export interface Cart {
|
|
77
77
|
items: CartLine[];
|
|
78
78
|
sumQty: number;
|
|
@@ -226,7 +226,9 @@ export interface PaymentMethodOption {
|
|
|
226
226
|
/** An item of a placed order, already in GA4's shape (CheckoutController::sendResponse). */
|
|
227
227
|
export interface OrderItem {
|
|
228
228
|
item_id: number;
|
|
229
|
+
/** The order line's name: a variant's includes its options */
|
|
229
230
|
item_name: string;
|
|
231
|
+
/** The price paid per unit (after the line's discount) */
|
|
230
232
|
price: number;
|
|
231
233
|
item_brand: string | null;
|
|
232
234
|
item_category: string;
|
|
@@ -235,17 +237,37 @@ export interface OrderItem {
|
|
|
235
237
|
parent_id: number;
|
|
236
238
|
parent_name: string;
|
|
237
239
|
}
|
|
238
|
-
/**
|
|
240
|
+
/**
|
|
241
|
+
* A placed order (CheckoutController::sendResponse): the answer of POST /checkout for an instant payment method,
|
|
242
|
+
* and the JSON the gateway's success page embeds.
|
|
243
|
+
*/
|
|
239
244
|
export interface PlacedOrder {
|
|
240
245
|
id: number;
|
|
246
|
+
/** "YYYY-MM-DD HH:MM:SS", the shop's local time */
|
|
241
247
|
date: string;
|
|
242
248
|
total: number;
|
|
243
249
|
email: string;
|
|
244
250
|
taxAmount: number;
|
|
245
251
|
shippingAmount: number;
|
|
252
|
+
/** "delivery" or "pickup" (the delivery method's type) */
|
|
246
253
|
delivery_type: string;
|
|
247
254
|
couponCode: string | null;
|
|
248
255
|
currency: string;
|
|
256
|
+
/** The reserved slot as the shop words it; "" without one */
|
|
249
257
|
reservation_slot: string;
|
|
250
258
|
items: OrderItem[];
|
|
251
259
|
}
|
|
260
|
+
/** A saved address of the signed-in customer (AddressResource, as GET /api/addresses lists them). */
|
|
261
|
+
export interface SavedAddress extends CheckoutAddress {
|
|
262
|
+
id: number;
|
|
263
|
+
is_default: boolean;
|
|
264
|
+
/** Loaded with the list; absent from a single address the API saved */
|
|
265
|
+
country?: {
|
|
266
|
+
id: number;
|
|
267
|
+
name: string;
|
|
268
|
+
} | null;
|
|
269
|
+
state?: {
|
|
270
|
+
id: number;
|
|
271
|
+
name: string;
|
|
272
|
+
} | null;
|
|
273
|
+
}
|
|
@@ -1,43 +1,58 @@
|
|
|
1
|
+
import { type TemplateResult } from 'lit';
|
|
1
2
|
import { SpmktElement } from '../../lit/spmkt-element';
|
|
3
|
+
import type { Cart, CartLine } from '../../core/types';
|
|
2
4
|
/**
|
|
3
5
|
* Parts of <spmkt-add-to-cart> (around the theme's add to cart form, which posts to /cart without JavaScript):
|
|
4
6
|
* - form (required): fields `id` (a product, or the chosen variant) and `qty`
|
|
5
7
|
* - submit (optional): busy while adding
|
|
8
|
+
* - buy-now (optional): a second submit button in the form; busy while adding
|
|
6
9
|
* - error (optional): the reason an add failed; render it hidden
|
|
7
10
|
*
|
|
8
|
-
* After an add, the
|
|
9
|
-
* in the
|
|
11
|
+
* After an add, the <spmkt-dialog> whose id is `dialog` opens with what was added (renderAdded(), from the line
|
|
12
|
+
* in the cart's answer: no further request); without that dialog, a toast says so. An add submitted through
|
|
13
|
+
* `buy-now` shows neither: it goes on to `checkout-url` (the checkout's first step by default).
|
|
10
14
|
*/
|
|
11
15
|
export interface AddToCartParts {
|
|
12
16
|
form: HTMLFormElement;
|
|
13
17
|
submit?: HTMLButtonElement;
|
|
18
|
+
'buy-now'?: HTMLButtonElement;
|
|
14
19
|
error?: HTMLElement;
|
|
15
20
|
}
|
|
21
|
+
export interface AddOptions {
|
|
22
|
+
/** Go on to the checkout after a successful add, instead of showing what was added */
|
|
23
|
+
buyNow?: boolean;
|
|
24
|
+
}
|
|
16
25
|
/** Adds to the cart without leaving the page. */
|
|
17
26
|
export declare class SpmktAddToCart extends SpmktElement {
|
|
18
27
|
static properties: {
|
|
19
28
|
dialog: {
|
|
20
29
|
type: StringConstructor;
|
|
21
30
|
};
|
|
22
|
-
|
|
31
|
+
productName: {
|
|
23
32
|
type: StringConstructor;
|
|
33
|
+
attribute: string;
|
|
24
34
|
};
|
|
25
|
-
|
|
35
|
+
checkoutUrl: {
|
|
26
36
|
type: StringConstructor;
|
|
27
37
|
attribute: string;
|
|
28
38
|
};
|
|
29
39
|
};
|
|
30
40
|
/** Id of the <spmkt-dialog> that shows the result */
|
|
31
41
|
dialog: string;
|
|
32
|
-
/** Theme fragment the dialog shows */
|
|
33
|
-
fragment: string;
|
|
34
42
|
/** For the toast when there is no dialog */
|
|
35
43
|
productName: string;
|
|
44
|
+
/** Where buy now goes after the add; empty: the checkout's first step */
|
|
45
|
+
checkoutUrl: string;
|
|
36
46
|
private busy;
|
|
37
47
|
connectedCallback(): void;
|
|
38
|
-
/** Adds what the form says; resolves once the result is shown. */
|
|
39
|
-
add(): Promise<void>;
|
|
48
|
+
/** Adds what the form says; resolves once the result is shown, or once buy now has started to leave. */
|
|
49
|
+
add({ buyNow }?: AddOptions): Promise<void>;
|
|
50
|
+
/** Sends the browser to the checkout after buy now; replaceable (tests, themes). */
|
|
51
|
+
navigate: (url: string) => void;
|
|
52
|
+
private idle;
|
|
40
53
|
private confirm;
|
|
54
|
+
/** The dialog's content after an add: the line added, how much of it, and what the cart holds now. */
|
|
55
|
+
protected renderAdded(line: CartLine, qty: number, cart: Cart): TemplateResult;
|
|
41
56
|
private messageFor;
|
|
42
57
|
private showError;
|
|
43
58
|
}
|
|
@@ -1,25 +1,29 @@
|
|
|
1
|
+
import { nothing, html } from "lit";
|
|
1
2
|
import { SpmktElement } from "../../lit/spmkt-element.js";
|
|
2
|
-
import { fetchFragments } from "../../lit/fragments.js";
|
|
3
3
|
import { addToCart } from "../../core/stores/cart.js";
|
|
4
|
-
import { productUrl } from "../../core/api/product.js";
|
|
5
4
|
import { ValidationError, SessionExpiredError, TimeoutError, NetworkError, HttpError } from "../../core/errors.js";
|
|
6
|
-
import { t } from "../../core/i18n.js";
|
|
5
|
+
import { t, plural } from "../../core/i18n.js";
|
|
7
6
|
import { shopUrl } from "../../core/config.js";
|
|
7
|
+
import { formatMoney } from "../../core/money.js";
|
|
8
8
|
import { showToast } from "../toaster/toaster.js";
|
|
9
9
|
import { SpmktDialog } from "../dialog/dialog.js";
|
|
10
|
+
import { lineName, hasImage } from "../shared/totals.js";
|
|
10
11
|
class SpmktAddToCart extends SpmktElement {
|
|
11
12
|
constructor() {
|
|
12
13
|
super(...arguments);
|
|
13
14
|
this.dialog = "added-to-cart";
|
|
14
|
-
this.fragment = "added-to-cart";
|
|
15
15
|
this.productName = "";
|
|
16
|
+
this.checkoutUrl = "";
|
|
16
17
|
this.busy = false;
|
|
18
|
+
this.navigate = (url) => {
|
|
19
|
+
location.assign(url);
|
|
20
|
+
};
|
|
17
21
|
}
|
|
18
22
|
static {
|
|
19
23
|
this.properties = {
|
|
20
24
|
dialog: { type: String },
|
|
21
|
-
|
|
22
|
-
|
|
25
|
+
productName: { type: String, attribute: "product-name" },
|
|
26
|
+
checkoutUrl: { type: String, attribute: "checkout-url" }
|
|
23
27
|
};
|
|
24
28
|
}
|
|
25
29
|
connectedCallback() {
|
|
@@ -27,51 +31,81 @@ class SpmktAddToCart extends SpmktElement {
|
|
|
27
31
|
const form = this.requirePart("form");
|
|
28
32
|
this.listen(form, "submit", (event) => {
|
|
29
33
|
event.preventDefault();
|
|
30
|
-
|
|
34
|
+
const buyNow = this.findPart("buy-now");
|
|
35
|
+
const submitter = event.submitter;
|
|
36
|
+
void this.add({ buyNow: buyNow !== null && submitter === buyNow });
|
|
37
|
+
});
|
|
38
|
+
this.listen(window, "pageshow", (event) => {
|
|
39
|
+
if (event.persisted) this.idle();
|
|
31
40
|
});
|
|
32
41
|
}
|
|
33
|
-
/** Adds what the form says; resolves once the result is shown. */
|
|
34
|
-
async add() {
|
|
42
|
+
/** Adds what the form says; resolves once the result is shown, or once buy now has started to leave. */
|
|
43
|
+
async add({ buyNow = false } = {}) {
|
|
35
44
|
if (this.busy) {
|
|
36
45
|
return;
|
|
37
46
|
}
|
|
38
47
|
const data = new FormData(this.requirePart("form"));
|
|
39
48
|
const id = Number(data.get("id"));
|
|
40
49
|
const qty = Math.max(1, Number(data.get("qty") ?? 1) || 1);
|
|
41
|
-
const
|
|
50
|
+
const button = this.findPart(buyNow ? "buy-now" : "submit");
|
|
42
51
|
this.busy = true;
|
|
43
52
|
this.showError(null);
|
|
44
|
-
|
|
53
|
+
button?.setAttribute("aria-busy", "true");
|
|
54
|
+
let leaving = false;
|
|
45
55
|
try {
|
|
46
|
-
await addToCart({ id, qty });
|
|
47
|
-
|
|
56
|
+
const cart = await addToCart({ id, qty });
|
|
57
|
+
if (buyNow) {
|
|
58
|
+
leaving = true;
|
|
59
|
+
this.navigate(this.checkoutUrl || shopUrl("/shopping-cart?step=delivery"));
|
|
60
|
+
} else {
|
|
61
|
+
this.confirm(cart, id, qty);
|
|
62
|
+
}
|
|
48
63
|
} catch (error) {
|
|
49
64
|
this.showError(this.messageFor(error));
|
|
50
65
|
} finally {
|
|
51
|
-
this.
|
|
52
|
-
submit?.removeAttribute("aria-busy");
|
|
66
|
+
if (!leaving) this.idle();
|
|
53
67
|
}
|
|
54
68
|
}
|
|
55
|
-
|
|
69
|
+
idle() {
|
|
70
|
+
this.busy = false;
|
|
71
|
+
this.findPart("submit")?.removeAttribute("aria-busy");
|
|
72
|
+
this.findPart("buy-now")?.removeAttribute("aria-busy");
|
|
73
|
+
}
|
|
74
|
+
confirm(cart, id, qty) {
|
|
56
75
|
const host = document.getElementById(this.dialog);
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
this.closest("dialog")?.close();
|
|
63
|
-
host.open(html);
|
|
64
|
-
return;
|
|
65
|
-
}
|
|
66
|
-
} catch {
|
|
67
|
-
}
|
|
76
|
+
const line = cart.items.find((item) => item.id === id);
|
|
77
|
+
if (host instanceof SpmktDialog && line) {
|
|
78
|
+
this.closest("dialog")?.close();
|
|
79
|
+
host.open(this.renderAdded(line, qty, cart));
|
|
80
|
+
return;
|
|
68
81
|
}
|
|
69
82
|
showToast({
|
|
70
|
-
message: t("cart.added", { name: this.productName }),
|
|
83
|
+
message: t("cart.added", { name: this.productName || (line ? lineName(line) : "") }),
|
|
71
84
|
tone: "success",
|
|
72
85
|
action: { label: t("cart.viewCart"), href: shopUrl("/shopping-cart") }
|
|
73
86
|
});
|
|
74
87
|
}
|
|
88
|
+
/** The dialog's content after an add: the line added, how much of it, and what the cart holds now. */
|
|
89
|
+
renderAdded(line, qty, cart) {
|
|
90
|
+
return html`<div class="added-to-cart">
|
|
91
|
+
<h2 class="added-to-cart__title">${t("cart.addedTitle")}</h2>
|
|
92
|
+
<div class="added-to-cart__product">
|
|
93
|
+
${hasImage(line) ? html`<img src=${line.image_url} alt="" width="80" height="80" />` : nothing}
|
|
94
|
+
<div>
|
|
95
|
+
<p class="added-to-cart__name">${lineName(line)}</p>
|
|
96
|
+
${line.variant ? html`<p class="added-to-cart__variant">${line.variant}</p>` : nothing}
|
|
97
|
+
<p class="added-to-cart__price">${qty} × ${formatMoney(line.price)}</p>
|
|
98
|
+
</div>
|
|
99
|
+
</div>
|
|
100
|
+
<p class="added-to-cart__summary">${plural("cart.inCart", cart.sumQty)}</p>
|
|
101
|
+
<div class="added-to-cart__actions">
|
|
102
|
+
<button type="button" class="button" data-part="close">${t("cart.continue")}</button>
|
|
103
|
+
<a class="button button--primary" href=${shopUrl("/shopping-cart")} data-test="buy-now-btn"
|
|
104
|
+
>${t("cart.viewCart")}</a
|
|
105
|
+
>
|
|
106
|
+
</div>
|
|
107
|
+
</div>`;
|
|
108
|
+
}
|
|
75
109
|
messageFor(error) {
|
|
76
110
|
if (error instanceof ValidationError) {
|
|
77
111
|
return error.first("qty") ?? error.first("id") ?? error.message ?? t("cart.addFailed");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"add-to-cart.js","sources":["../../../src/elements/add-to-cart/add-to-cart.ts"],"sourcesContent":["import { SpmktElement } from '../../lit/spmkt-element'\nimport { fetchFragments } from '../../lit/fragments'\nimport { addToCart } from '../../core/stores/cart'\nimport { productUrl } from '../../core/api/product'\nimport {\n HttpError,\n SessionExpiredError,\n ValidationError,\n NetworkError,\n TimeoutError,\n} from '../../core/errors'\nimport { t } from '../../core/i18n'\nimport { shopUrl } from '../../core/config'\nimport { showToast } from '../toaster/toaster'\nimport { SpmktDialog } from '../dialog/dialog'\n\n/**\n * Parts of <spmkt-add-to-cart> (around the theme's add to cart form, which posts to /cart without JavaScript):\n * - form (required): fields `id` (a product, or the chosen variant) and `qty`\n * - submit (optional): busy while adding\n * - error (optional): the reason an add failed; render it hidden\n *\n * After an add, the theme fragment `fragment` of the added product (GET /products/{id}?fragments=...&qty=N) opens\n * in the <spmkt-dialog> whose id is `dialog`; without either, a toast says so.\n */\nexport interface AddToCartParts {\n form: HTMLFormElement\n submit?: HTMLButtonElement\n error?: HTMLElement\n}\n\n/** Adds to the cart without leaving the page. */\nexport class SpmktAddToCart extends SpmktElement {\n static override properties = {\n dialog: { type: String },\n fragment: { type: String },\n productName: { type: String, attribute: 'product-name' },\n }\n /** Id of the <spmkt-dialog> that shows the result */\n dialog = 'added-to-cart'\n /** Theme fragment the dialog shows */\n fragment = 'added-to-cart'\n /** For the toast when there is no dialog */\n productName = ''\n\n private busy = false\n\n override connectedCallback(): void {\n super.connectedCallback()\n const form = this.requirePart<HTMLFormElement>('form')\n this.listen(form, 'submit', (event) => {\n event.preventDefault()\n void this.add()\n })\n }\n\n /** Adds what the form says; resolves once the result is shown. */\n async add(): Promise<void> {\n if (this.busy) {\n return\n }\n const data = new FormData(this.requirePart<HTMLFormElement>('form'))\n const id = Number(data.get('id'))\n const qty = Math.max(1, Number(data.get('qty') ?? 1) || 1)\n const submit = this.findPart<HTMLButtonElement>('submit')\n this.busy = true\n this.showError(null)\n submit?.setAttribute('aria-busy', 'true')\n try {\n await addToCart({ id, qty })\n await this.confirm(id, qty)\n } catch (error) {\n this.showError(this.messageFor(error))\n } finally {\n this.busy = false\n submit?.removeAttribute('aria-busy')\n }\n }\n\n private async confirm(id: number, qty: number): Promise<void> {\n const host = document.getElementById(this.dialog)\n if (host instanceof SpmktDialog && this.fragment) {\n try {\n const response = await fetchFragments(`${productUrl(id)}?qty=${qty}`, { fragments: [this.fragment] })\n const html = response.fragments[this.fragment]\n if (html) {\n // A dialog this form sits in (a quick view) makes way for the result\n this.closest('dialog')?.close()\n host.open(html)\n return\n }\n } catch {\n // The product is in the cart; the toast below says so\n }\n }\n showToast({\n message: t('cart.added', { name: this.productName }),\n tone: 'success',\n action: { label: t('cart.viewCart'), href: shopUrl('/shopping-cart') },\n })\n }\n\n private messageFor(error: unknown): string {\n if (error instanceof ValidationError) {\n return error.first('qty') ?? error.first('id') ?? error.message ?? t('cart.addFailed')\n }\n if (error instanceof SessionExpiredError) return t('common.sessionExpired')\n if (error instanceof TimeoutError) return t('common.timeout')\n if (error instanceof NetworkError) return t('common.network')\n // A sold-out product or an expired store choice: the server's own words\n if (error instanceof HttpError && error.status < 500 && error.message) return error.message\n return t('cart.addFailed')\n }\n\n private showError(message: string | null): void {\n const part = this.findPart('error')\n if (part) {\n part.textContent = message ?? ''\n part.hidden = message === null\n }\n if (message !== null) {\n showToast({ message, tone: 'error' })\n }\n }\n}\n"],"names":[],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to-cart.ts"],"sourcesContent":["import { html, nothing, type TemplateResult } from 'lit'\nimport { SpmktElement } from '../../lit/spmkt-element'\nimport { addToCart } from '../../core/stores/cart'\nimport {\n HttpError,\n SessionExpiredError,\n ValidationError,\n NetworkError,\n TimeoutError,\n} from '../../core/errors'\nimport { plural, t } from '../../core/i18n'\nimport { shopUrl } from '../../core/config'\nimport { formatMoney } from '../../core/money'\nimport type { Cart, CartLine } from '../../core/types'\nimport { showToast } from '../toaster/toaster'\nimport { SpmktDialog } from '../dialog/dialog'\nimport { hasImage, lineName } from '../shared/totals'\n\n/**\n * Parts of <spmkt-add-to-cart> (around the theme's add to cart form, which posts to /cart without JavaScript):\n * - form (required): fields `id` (a product, or the chosen variant) and `qty`\n * - submit (optional): busy while adding\n * - buy-now (optional): a second submit button in the form; busy while adding\n * - error (optional): the reason an add failed; render it hidden\n *\n * After an add, the <spmkt-dialog> whose id is `dialog` opens with what was added (renderAdded(), from the line\n * in the cart's answer: no further request); without that dialog, a toast says so. An add submitted through\n * `buy-now` shows neither: it goes on to `checkout-url` (the checkout's first step by default).\n */\nexport interface AddToCartParts {\n form: HTMLFormElement\n submit?: HTMLButtonElement\n 'buy-now'?: HTMLButtonElement\n error?: HTMLElement\n}\n\nexport interface AddOptions {\n /** Go on to the checkout after a successful add, instead of showing what was added */\n buyNow?: boolean\n}\n\n/** Adds to the cart without leaving the page. */\nexport class SpmktAddToCart extends SpmktElement {\n static override properties = {\n dialog: { type: String },\n productName: { type: String, attribute: 'product-name' },\n checkoutUrl: { type: String, attribute: 'checkout-url' },\n }\n /** Id of the <spmkt-dialog> that shows the result */\n dialog = 'added-to-cart'\n /** For the toast when there is no dialog */\n productName = ''\n /** Where buy now goes after the add; empty: the checkout's first step */\n checkoutUrl = ''\n\n private busy = false\n\n override connectedCallback(): void {\n super.connectedCallback()\n const form = this.requirePart<HTMLFormElement>('form')\n this.listen(form, 'submit', (event) => {\n event.preventDefault()\n const buyNow = this.findPart('buy-now')\n const submitter = (event as SubmitEvent).submitter\n void this.add({ buyNow: buyNow !== null && submitter === buyNow })\n })\n // Back from the checkout (the back/forward cache restores the page as it was left): usable again\n this.listen(window, 'pageshow', (event) => {\n if ((event as PageTransitionEvent).persisted) this.idle()\n })\n }\n\n /** Adds what the form says; resolves once the result is shown, or once buy now has started to leave. */\n async add({ buyNow = false }: AddOptions = {}): Promise<void> {\n if (this.busy) {\n return\n }\n const data = new FormData(this.requirePart<HTMLFormElement>('form'))\n const id = Number(data.get('id'))\n const qty = Math.max(1, Number(data.get('qty') ?? 1) || 1)\n const button = this.findPart<HTMLButtonElement>(buyNow ? 'buy-now' : 'submit')\n this.busy = true\n this.showError(null)\n button?.setAttribute('aria-busy', 'true')\n let leaving = false\n try {\n const cart = await addToCart({ id, qty })\n if (buyNow) {\n leaving = true\n this.navigate(this.checkoutUrl || shopUrl('/shopping-cart?step=delivery'))\n } else {\n this.confirm(cart, id, qty)\n }\n } catch (error) {\n this.showError(this.messageFor(error))\n } finally {\n // Stay busy while the browser leaves for the checkout (pageshow undoes it if the visitor comes Back)\n if (!leaving) this.idle()\n }\n }\n\n /** Sends the browser to the checkout after buy now; replaceable (tests, themes). */\n navigate: (url: string) => void = (url) => {\n location.assign(url)\n }\n\n private idle(): void {\n this.busy = false\n this.findPart('submit')?.removeAttribute('aria-busy')\n this.findPart('buy-now')?.removeAttribute('aria-busy')\n }\n\n private confirm(cart: Cart, id: number, qty: number): void {\n const host = document.getElementById(this.dialog)\n const line = cart.items.find((item) => item.id === id)\n if (host instanceof SpmktDialog && line) {\n // A dialog this form sits in (a quick view) makes way for the result\n this.closest('dialog')?.close()\n host.open(this.renderAdded(line, qty, cart))\n return\n }\n showToast({\n message: t('cart.added', { name: this.productName || (line ? lineName(line) : '') }),\n tone: 'success',\n action: { label: t('cart.viewCart'), href: shopUrl('/shopping-cart') },\n })\n }\n\n /** The dialog's content after an add: the line added, how much of it, and what the cart holds now. */\n protected renderAdded(line: CartLine, qty: number, cart: Cart): TemplateResult {\n return html`<div class=\"added-to-cart\">\n <h2 class=\"added-to-cart__title\">${t('cart.addedTitle')}</h2>\n <div class=\"added-to-cart__product\">\n ${hasImage(line) ? html`<img src=${line.image_url} alt=\"\" width=\"80\" height=\"80\" />` : nothing}\n <div>\n <p class=\"added-to-cart__name\">${lineName(line)}</p>\n ${line.variant ? html`<p class=\"added-to-cart__variant\">${line.variant}</p>` : nothing}\n <p class=\"added-to-cart__price\">${qty} × ${formatMoney(line.price)}</p>\n </div>\n </div>\n <p class=\"added-to-cart__summary\">${plural('cart.inCart', cart.sumQty)}</p>\n <div class=\"added-to-cart__actions\">\n <button type=\"button\" class=\"button\" data-part=\"close\">${t('cart.continue')}</button>\n <a class=\"button button--primary\" href=${shopUrl('/shopping-cart')} data-test=\"buy-now-btn\"\n >${t('cart.viewCart')}</a\n >\n </div>\n </div>`\n }\n\n private messageFor(error: unknown): string {\n if (error instanceof ValidationError) {\n return error.first('qty') ?? error.first('id') ?? error.message ?? t('cart.addFailed')\n }\n if (error instanceof SessionExpiredError) return t('common.sessionExpired')\n if (error instanceof TimeoutError) return t('common.timeout')\n if (error instanceof NetworkError) return t('common.network')\n // A sold-out product or an expired store choice: the server's own words\n if (error instanceof HttpError && error.status < 500 && error.message) return error.message\n return t('cart.addFailed')\n }\n\n private showError(message: string | null): void {\n const part = this.findPart('error')\n if (part) {\n part.textContent = message ?? ''\n part.hidden = message === null\n }\n if (message !== null) {\n showToast({ message, tone: 'error' })\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;AA0CO,MAAM,uBAAuB,aAAa;AAAA,EAA1C,cAAA;AAAA,UAAA,GAAA,SAAA;AAOL,SAAA,SAAS;AAET,SAAA,cAAc;AAEd,SAAA,cAAc;AAEd,SAAQ,OAAO;AA+Cf,SAAA,WAAkC,CAAC,QAAQ;AACzC,eAAS,OAAO,GAAG;AAAA,IACrB;AAAA,EAAA;AAAA,EA7DA,OAAA;AAAA,SAAgB,aAAa;AAAA,MAC3B,QAAQ,EAAE,MAAM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