@wikala/spmkt 4.0.0-alpha.5 → 4.0.0-alpha.7
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/account.d.ts +7 -0
- package/dist/core/api/account.js +2 -0
- package/dist/core/api/account.js.map +1 -1
- package/dist/core/api/index.d.ts +1 -1
- package/dist/core/index.js +5 -2
- package/dist/core/stores/checkout.d.ts +26 -0
- package/dist/core/stores/checkout.js +36 -1
- package/dist/core/stores/checkout.js.map +1 -1
- package/dist/core/stores/index.d.ts +2 -2
- package/dist/core/types.d.ts +2 -0
- package/dist/elements/cart/cart.js +10 -38
- package/dist/elements/cart/cart.js.map +1 -1
- package/dist/elements/checkout/checkout.d.ts +17 -1
- package/dist/elements/checkout/checkout.js +53 -10
- package/dist/elements/checkout/checkout.js.map +1 -1
- package/dist/elements/checkout-address/checkout-address.d.ts +4 -2
- package/dist/elements/checkout-address/checkout-address.js +6 -3
- package/dist/elements/checkout-address/checkout-address.js.map +1 -1
- package/dist/elements/checkout-identity/checkout-identity.d.ts +20 -1
- package/dist/elements/checkout-identity/checkout-identity.js +51 -1
- package/dist/elements/checkout-identity/checkout-identity.js.map +1 -1
- package/dist/elements/order-confirmation/order-confirmation.d.ts +5 -1
- package/dist/elements/order-confirmation/order-confirmation.js +8 -0
- package/dist/elements/order-confirmation/order-confirmation.js.map +1 -1
- package/dist/elements/shared/coupon.d.ts +20 -0
- package/dist/elements/shared/coupon.js +47 -0
- package/dist/elements/shared/coupon.js.map +1 -0
- package/package.json +1 -1
|
@@ -23,3 +23,10 @@ export declare const changeDateOfBirth: (values: {
|
|
|
23
23
|
}, signal?: AbortSignal) => Promise<unknown>;
|
|
24
24
|
/** POST /account/resend-verification: a new verification link (204; throttled to 6 a minute). */
|
|
25
25
|
export declare const resendVerification: (signal?: AbortSignal) => Promise<unknown>;
|
|
26
|
+
/**
|
|
27
|
+
* POST /register: a new account from a storefront form (first_name, last_name, email, password,
|
|
28
|
+
* password_confirmation, terms_of_service, recaptcha_token). The platform signs the visitor in; 422 per field.
|
|
29
|
+
*/
|
|
30
|
+
export declare const registerAccount: (values: Record<string, string>, signal?: AbortSignal) => Promise<{
|
|
31
|
+
message?: string;
|
|
32
|
+
}>;
|
package/dist/core/api/account.js
CHANGED
|
@@ -16,11 +16,13 @@ const changeEmail = (values, signal) => sendAccountForm("/api/account/email", va
|
|
|
16
16
|
const changePassword = (values, signal) => sendAccountForm("/api/account/password", values, signal);
|
|
17
17
|
const changeDateOfBirth = (values, signal) => sendAccountForm("/api/account/dob", values, signal);
|
|
18
18
|
const resendVerification = (signal) => sendAccountForm("/account/resend-verification", {}, signal);
|
|
19
|
+
const registerAccount = (values, signal) => post("/register", values, { signal });
|
|
19
20
|
export {
|
|
20
21
|
changeDateOfBirth,
|
|
21
22
|
changeEmail,
|
|
22
23
|
changeName,
|
|
23
24
|
changePassword,
|
|
25
|
+
registerAccount,
|
|
24
26
|
resendVerification,
|
|
25
27
|
sendAccountForm
|
|
26
28
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"account.js","sources":["../../../src/core/api/account.ts"],"sourcesContent":["import { HttpError, ValidationError } from '../errors'\nimport { fieldErrors, post } from '../request'\n\n/**\n * The signed-in customer's account endpoints (the session cookie authenticates). A wrong current password\n * comes back as 403 with the field's message (ApiError on the platform); it is thrown as a ValidationError, so\n * forms show it next to the field like any 422.\n */\nexport async function sendAccountForm<T = unknown>(\n endpoint: string,\n values: Record<string, unknown>,\n signal?: AbortSignal,\n): Promise<T> {\n try {\n return await post<T>(endpoint, values, { signal })\n } catch (error) {\n if (error instanceof HttpError && error.status === 403) {\n const errors = fieldErrors(error.body)\n if (Object.keys(errors).length) throw new ValidationError(error.message, errors, error.body)\n }\n throw error\n }\n}\n\nexport const changeName = (values: { first_name: string; last_name: string }, signal?: AbortSignal) =>\n sendAccountForm('/api/account/name', values, signal)\n\nexport const changeEmail = (\n values: { email: string; email_confirmation: string; current_password: string },\n signal?: AbortSignal,\n) => sendAccountForm('/api/account/email', values, signal)\n\nexport const changePassword = (\n values: { current_password: string; new_password: string; new_password_confirmation: string },\n signal?: AbortSignal,\n) => sendAccountForm('/api/account/password', values, signal)\n\nexport const changeDateOfBirth = (values: { date_of_birth: string }, signal?: AbortSignal) =>\n sendAccountForm('/api/account/dob', values, signal)\n\n/** POST /account/resend-verification: a new verification link (204; throttled to 6 a minute). */\nexport const resendVerification = (signal?: AbortSignal) =>\n sendAccountForm('/account/resend-verification', {}, signal)\n"],"names":[],"mappings":";;AAQA,eAAsB,gBACpB,UACA,QACA,QACY;AACZ,MAAI;AACF,WAAO,MAAM,KAAQ,UAAU,QAAQ,EAAE,QAAQ;AAAA,EACnD,SAAS,OAAO;AACd,QAAI,iBAAiB,aAAa,MAAM,WAAW,KAAK;AACtD,YAAM,SAAS,YAAY,MAAM,IAAI;AACrC,UAAI,OAAO,KAAK,MAAM,EAAE,OAAQ,OAAM,IAAI,gBAAgB,MAAM,SAAS,QAAQ,MAAM,IAAI;AAAA,IAC7F;AACA,UAAM;AAAA,EACR;AACF;AAEO,MAAM,aAAa,CAAC,QAAmD,WAC5E,gBAAgB,qBAAqB,QAAQ,MAAM;AAE9C,MAAM,cAAc,CACzB,QACA,WACG,gBAAgB,sBAAsB,QAAQ,MAAM;AAElD,MAAM,iBAAiB,CAC5B,QACA,WACG,gBAAgB,yBAAyB,QAAQ,MAAM;AAErD,MAAM,oBAAoB,CAAC,QAAmC,WACnE,gBAAgB,oBAAoB,QAAQ,MAAM;AAG7C,MAAM,qBAAqB,CAAC,WACjC,gBAAgB,gCAAgC,CAAA,GAAI,MAAM;"}
|
|
1
|
+
{"version":3,"file":"account.js","sources":["../../../src/core/api/account.ts"],"sourcesContent":["import { HttpError, ValidationError } from '../errors'\nimport { fieldErrors, post } from '../request'\n\n/**\n * The signed-in customer's account endpoints (the session cookie authenticates). A wrong current password\n * comes back as 403 with the field's message (ApiError on the platform); it is thrown as a ValidationError, so\n * forms show it next to the field like any 422.\n */\nexport async function sendAccountForm<T = unknown>(\n endpoint: string,\n values: Record<string, unknown>,\n signal?: AbortSignal,\n): Promise<T> {\n try {\n return await post<T>(endpoint, values, { signal })\n } catch (error) {\n if (error instanceof HttpError && error.status === 403) {\n const errors = fieldErrors(error.body)\n if (Object.keys(errors).length) throw new ValidationError(error.message, errors, error.body)\n }\n throw error\n }\n}\n\nexport const changeName = (values: { first_name: string; last_name: string }, signal?: AbortSignal) =>\n sendAccountForm('/api/account/name', values, signal)\n\nexport const changeEmail = (\n values: { email: string; email_confirmation: string; current_password: string },\n signal?: AbortSignal,\n) => sendAccountForm('/api/account/email', values, signal)\n\nexport const changePassword = (\n values: { current_password: string; new_password: string; new_password_confirmation: string },\n signal?: AbortSignal,\n) => sendAccountForm('/api/account/password', values, signal)\n\nexport const changeDateOfBirth = (values: { date_of_birth: string }, signal?: AbortSignal) =>\n sendAccountForm('/api/account/dob', values, signal)\n\n/** POST /account/resend-verification: a new verification link (204; throttled to 6 a minute). */\nexport const resendVerification = (signal?: AbortSignal) =>\n sendAccountForm('/account/resend-verification', {}, signal)\n\n/**\n * POST /register: a new account from a storefront form (first_name, last_name, email, password,\n * password_confirmation, terms_of_service, recaptcha_token). The platform signs the visitor in; 422 per field.\n */\nexport const registerAccount = (values: Record<string, string>, signal?: AbortSignal) =>\n post<{ message?: string }>('/register', values, { signal })\n"],"names":[],"mappings":";;AAQA,eAAsB,gBACpB,UACA,QACA,QACY;AACZ,MAAI;AACF,WAAO,MAAM,KAAQ,UAAU,QAAQ,EAAE,QAAQ;AAAA,EACnD,SAAS,OAAO;AACd,QAAI,iBAAiB,aAAa,MAAM,WAAW,KAAK;AACtD,YAAM,SAAS,YAAY,MAAM,IAAI;AACrC,UAAI,OAAO,KAAK,MAAM,EAAE,OAAQ,OAAM,IAAI,gBAAgB,MAAM,SAAS,QAAQ,MAAM,IAAI;AAAA,IAC7F;AACA,UAAM;AAAA,EACR;AACF;AAEO,MAAM,aAAa,CAAC,QAAmD,WAC5E,gBAAgB,qBAAqB,QAAQ,MAAM;AAE9C,MAAM,cAAc,CACzB,QACA,WACG,gBAAgB,sBAAsB,QAAQ,MAAM;AAElD,MAAM,iBAAiB,CAC5B,QACA,WACG,gBAAgB,yBAAyB,QAAQ,MAAM;AAErD,MAAM,oBAAoB,CAAC,QAAmC,WACnE,gBAAgB,oBAAoB,QAAQ,MAAM;AAG7C,MAAM,qBAAqB,CAAC,WACjC,gBAAgB,gCAAgC,CAAA,GAAI,MAAM;AAMrD,MAAM,kBAAkB,CAAC,QAAgC,WAC9D,KAA2B,aAAa,QAAQ,EAAE,OAAA,CAAQ;"}
|
package/dist/core/api/index.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ export type { AddToCartInput } from './cart';
|
|
|
3
3
|
export { hasAccount, validateGuestEmail, validateAddress, fetchDeliveryOptions, fetchReservationSlots, fetchSummary, fetchPaymentMethods, fetchDeliveryTypes, placeOrder, checkAge, } from './checkout';
|
|
4
4
|
export type { SummaryInput, PaymentMethodsInput, OrderInput, GatewayRedirect, OrderPlaced, AgeCheckInput, } from './checkout';
|
|
5
5
|
export { fetchAddresses, saveAddress, deleteAddress, setDefaultAddress } from './address';
|
|
6
|
-
export { sendAccountForm, changeName, changeEmail, changePassword, changeDateOfBirth, resendVerification, } from './account';
|
|
6
|
+
export { sendAccountForm, changeName, registerAccount, changeEmail, changePassword, changeDateOfBirth, resendVerification, } from './account';
|
|
7
7
|
export { suggest } from './search';
|
|
8
8
|
export { productUrl } from './product';
|
|
9
9
|
export { submitReview, voteOnReview, uploadReviewImage, deleteReviewImage } from './reviews';
|
package/dist/core/index.js
CHANGED
|
@@ -13,11 +13,11 @@ import { installSignOutCleanup } from "./session.js";
|
|
|
13
13
|
import { installBusyForms, installRecaptchaForms } from "./forms.js";
|
|
14
14
|
import { COMPARE_COOKIE, clearCompare, compareIds, compareItems, compareMax, compareUrl, removeFromCompare, toggleCompare } from "./stores/compare.js";
|
|
15
15
|
import { EMPTY_DRAFT, checkoutDraft, clearCheckoutDraft, updateDraft } from "./stores/checkout-draft.js";
|
|
16
|
-
import { addOrderCheck, beginCheckout, checkoutPending, chooseAddress, chooseDelivery, chooseKind, chooseSlot, completeDelivery, confirmAddress, confirmIdentity, deliveryComplete, loadDeliveryOptions, loadPaymentMethods, orderInput, passOrderChecks, postToGateway, stepToShow, submitOrder, summaryPriced } from "./stores/checkout.js";
|
|
16
|
+
import { addOrderCheck, applyCheckoutCoupon, beginCheckout, checkoutPending, chooseAddress, chooseDelivery, chooseKind, chooseSlot, completeDelivery, confirmAddress, confirmIdentity, createAccount, deliveryComplete, loadDeliveryOptions, loadPaymentMethods, orderInput, passOrderChecks, postToGateway, stepToShow, submitOrder, summaryPriced } from "./stores/checkout.js";
|
|
17
17
|
import { addToCart, applyCoupon, cart, cartCount, cartEmptied, cartLineToItem, cartLines, cartPending, cartSubtotal, setQuantity, takeCart } from "./stores/cart.js";
|
|
18
18
|
import { askQuestion } from "./api/questions.js";
|
|
19
19
|
import { availabilityByLocation, setPreferredLocation } from "./api/location.js";
|
|
20
|
-
import { changeDateOfBirth, changeEmail, changeName, changePassword, resendVerification, sendAccountForm } from "./api/account.js";
|
|
20
|
+
import { changeDateOfBirth, changeEmail, changeName, changePassword, registerAccount, resendVerification, sendAccountForm } from "./api/account.js";
|
|
21
21
|
import { changeLocation, locationPending, preferredLocation, retailLocations } from "./stores/location.js";
|
|
22
22
|
import { checkAge, fetchDeliveryOptions, fetchDeliveryTypes, fetchPaymentMethods, fetchReservationSlots, fetchSummary, hasAccount, placeOrder, validateAddress, validateGuestEmail } from "./api/checkout.js";
|
|
23
23
|
import { customerName, customerSignedIn } from "./stores/customer.js";
|
|
@@ -41,6 +41,7 @@ export {
|
|
|
41
41
|
ValidationError,
|
|
42
42
|
addOrderCheck,
|
|
43
43
|
addToCart,
|
|
44
|
+
applyCheckoutCoupon,
|
|
44
45
|
applyCoupon,
|
|
45
46
|
askQuestion,
|
|
46
47
|
availabilityByLocation,
|
|
@@ -75,6 +76,7 @@ export {
|
|
|
75
76
|
configureI18n,
|
|
76
77
|
confirmAddress,
|
|
77
78
|
confirmIdentity,
|
|
79
|
+
createAccount,
|
|
78
80
|
currentLocale,
|
|
79
81
|
customerName,
|
|
80
82
|
customerSignedIn,
|
|
@@ -129,6 +131,7 @@ export {
|
|
|
129
131
|
readCookie,
|
|
130
132
|
readState,
|
|
131
133
|
recaptchaToken,
|
|
134
|
+
registerAccount,
|
|
132
135
|
removeFromCompare,
|
|
133
136
|
request,
|
|
134
137
|
resendVerification,
|
|
@@ -26,6 +26,22 @@ export declare function stepToShow(requested: CheckoutStep): CheckoutStep;
|
|
|
26
26
|
export declare function confirmIdentity(identity: CheckoutIdentity, signal?: AbortSignal): Promise<{
|
|
27
27
|
hasAccount: boolean;
|
|
28
28
|
}>;
|
|
29
|
+
/** What a guest adds to the contact details to have an account made at the checkout. */
|
|
30
|
+
export interface NewAccount {
|
|
31
|
+
password: string;
|
|
32
|
+
password_confirmation: string;
|
|
33
|
+
/** "1" once the terms are accepted (the platform requires it) */
|
|
34
|
+
terms_of_service: string;
|
|
35
|
+
/** Y-m-d, when the shop checks the age (the platform then requires it) */
|
|
36
|
+
date_of_birth?: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* A guest has an account made from the contact details (name and e-mail) and a password: the platform registers
|
|
40
|
+
* and signs them in (with a reCAPTCHA token for "register", when the shop has reCAPTCHA). The contact details
|
|
41
|
+
* are kept in the draft. The visitor goes on signed in only after the page loads again (a new session); the
|
|
42
|
+
* caller does that. 422 per field (the e-mail already has an account, a short password, the terms).
|
|
43
|
+
*/
|
|
44
|
+
export declare function createAccount(identity: CheckoutIdentity, account: NewAccount, signal?: AbortSignal): Promise<void>;
|
|
29
45
|
/** Delivery to an address, or pickup at the store; another kind drops the chosen method. */
|
|
30
46
|
export declare function chooseKind(kind: CheckoutDraft['kind']): void;
|
|
31
47
|
/** A guest's delivery address, validated on the server (422 per field). A new address resets the delivery choice. */
|
|
@@ -43,6 +59,16 @@ export declare function loadDeliveryOptions(signal?: AbortSignal): Promise<Deliv
|
|
|
43
59
|
export declare function chooseDelivery(choice: DeliveryChoice, options?: {
|
|
44
60
|
signal?: AbortSignal;
|
|
45
61
|
}): Promise<Cart>;
|
|
62
|
+
/**
|
|
63
|
+
* Applies a coupon code during the checkout. The cart's answer carries no delivery, so a delivery already
|
|
64
|
+
* chosen is priced again (its shipping and tax after the discount); until then the summary shows shipping "by
|
|
65
|
+
* the choice", never the cart's. An unusable code is re-thrown (HttpError with the server's message) and leaves
|
|
66
|
+
* the summary as it was. A later delivery choice overtaking the repricing rejects it with an AbortError: the code
|
|
67
|
+
* is applied all the same.
|
|
68
|
+
*/
|
|
69
|
+
export declare function applyCheckoutCoupon(code: string, options?: {
|
|
70
|
+
signal?: AbortSignal;
|
|
71
|
+
}): Promise<Cart>;
|
|
46
72
|
export declare function chooseSlot(slot: string | null): void;
|
|
47
73
|
/** Payment methods for the chosen delivery; business customers may see more (bank transfer). */
|
|
48
74
|
export declare function loadPaymentMethods(signal?: AbortSignal): Promise<PaymentMethodOption[]>;
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { signal } from "@preact/signals-core";
|
|
2
2
|
import { validateGuestEmail, hasAccount, validateAddress, fetchDeliveryOptions, fetchSummary, fetchPaymentMethods, placeOrder } from "../api/checkout.js";
|
|
3
|
+
import { registerAccount } from "../api/account.js";
|
|
3
4
|
import { HttpError } from "../errors.js";
|
|
5
|
+
import { recaptchaToken } from "../recaptcha.js";
|
|
4
6
|
import { dispatch } from "../events.js";
|
|
5
7
|
import { storefront } from "../state.js";
|
|
6
|
-
import { cart, cartCount, cartLineToItem, takeCart, cartEmptied } from "./cart.js";
|
|
8
|
+
import { cart, cartCount, cartLineToItem, takeCart, applyCoupon, cartEmptied } from "./cart.js";
|
|
7
9
|
import { checkoutDraft, firstBeginOf, updateDraft, clearCheckoutDraft } from "./checkout-draft.js";
|
|
8
10
|
import { EMPTY_DRAFT } from "./checkout-draft.js";
|
|
9
11
|
import { customerSignedIn } from "./customer.js";
|
|
@@ -44,6 +46,22 @@ function confirmIdentity(identity, signal2) {
|
|
|
44
46
|
return { hasAccount: exists };
|
|
45
47
|
});
|
|
46
48
|
}
|
|
49
|
+
function createAccount(identity, account, signal2) {
|
|
50
|
+
return pending(async () => {
|
|
51
|
+
const token = await recaptchaToken("register");
|
|
52
|
+
await registerAccount(
|
|
53
|
+
{
|
|
54
|
+
first_name: identity.first_name,
|
|
55
|
+
last_name: identity.last_name,
|
|
56
|
+
email: identity.email,
|
|
57
|
+
...account,
|
|
58
|
+
...token ? { recaptcha_token: token } : {}
|
|
59
|
+
},
|
|
60
|
+
signal2
|
|
61
|
+
);
|
|
62
|
+
updateDraft({ identity });
|
|
63
|
+
});
|
|
64
|
+
}
|
|
47
65
|
function chooseKind(kind) {
|
|
48
66
|
if (checkoutDraft.value.kind !== kind) {
|
|
49
67
|
updateDraft({ kind, delivery: null, slot: null });
|
|
@@ -100,6 +118,21 @@ function chooseDelivery(choice, options = {}) {
|
|
|
100
118
|
return priced;
|
|
101
119
|
});
|
|
102
120
|
}
|
|
121
|
+
function applyCheckoutCoupon(code, options = {}) {
|
|
122
|
+
return pending(async () => {
|
|
123
|
+
const choice = checkoutDraft.value.delivery;
|
|
124
|
+
const priced = summaryPriced.value;
|
|
125
|
+
if (choice) summaryPriced.value = false;
|
|
126
|
+
let applied;
|
|
127
|
+
try {
|
|
128
|
+
applied = await applyCoupon(code, options);
|
|
129
|
+
} catch (error) {
|
|
130
|
+
summaryPriced.value = priced;
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
return choice ? chooseDelivery(choice, options) : applied;
|
|
134
|
+
});
|
|
135
|
+
}
|
|
103
136
|
function chooseSlot(slot) {
|
|
104
137
|
updateDraft({ slot });
|
|
105
138
|
}
|
|
@@ -269,6 +302,7 @@ function postToGateway(redirect, root = document.body) {
|
|
|
269
302
|
export {
|
|
270
303
|
EMPTY_DRAFT,
|
|
271
304
|
addOrderCheck,
|
|
305
|
+
applyCheckoutCoupon,
|
|
272
306
|
beginCheckout,
|
|
273
307
|
checkoutDraft,
|
|
274
308
|
checkoutPending,
|
|
@@ -280,6 +314,7 @@ export {
|
|
|
280
314
|
completeDelivery,
|
|
281
315
|
confirmAddress,
|
|
282
316
|
confirmIdentity,
|
|
317
|
+
createAccount,
|
|
283
318
|
deliveryComplete,
|
|
284
319
|
loadDeliveryOptions,
|
|
285
320
|
loadPaymentMethods,
|
|
@@ -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 { 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,WA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,EAAE,cAAc,MAAM,YAAA,IAAgB,CAAA;AAAA,EAAC,CAChE;AACD,SAAO,QAAQ,YAAY;AACzB,QAAI;AACF,YAAM,SAAS,MAAM,WAAW,MAAM,EAAE,OAAO,CAAC,UAAU,QAAQ,MAAM,QAAQ;AAChF,mBAAa,IAAI;AACjB,UAAI,OAAO,SAAS,SAAS;AAC3B,2BAAA;AACA,sBAAc,QAAQ;AACtB,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 { registerAccount } from '../api/account'\nimport { HttpError } from '../errors'\nimport { recaptchaToken } from '../recaptcha'\nimport { dispatch, type Ga4Item } from '../events'\nimport { storefront } from '../state'\nimport type { Cart, CheckoutAddress, DeliveryOption, PaymentMethodOption } from '../types'\nimport { applyCoupon, 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/** What a guest adds to the contact details to have an account made at the checkout. */\nexport interface NewAccount {\n password: string\n password_confirmation: string\n /** \"1\" once the terms are accepted (the platform requires it) */\n terms_of_service: string\n /** Y-m-d, when the shop checks the age (the platform then requires it) */\n date_of_birth?: string\n}\n\n/**\n * A guest has an account made from the contact details (name and e-mail) and a password: the platform registers\n * and signs them in (with a reCAPTCHA token for \"register\", when the shop has reCAPTCHA). The contact details\n * are kept in the draft. The visitor goes on signed in only after the page loads again (a new session); the\n * caller does that. 422 per field (the e-mail already has an account, a short password, the terms).\n */\nexport function createAccount(\n identity: CheckoutIdentity,\n account: NewAccount,\n signal?: AbortSignal,\n): Promise<void> {\n return pending(async () => {\n const token = await recaptchaToken('register')\n await registerAccount(\n {\n first_name: identity.first_name,\n last_name: identity.last_name,\n email: identity.email,\n ...account,\n ...(token ? { recaptcha_token: token } : {}),\n },\n signal,\n )\n updateDraft({ identity })\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\n/**\n * Applies a coupon code during the checkout. The cart's answer carries no delivery, so a delivery already\n * chosen is priced again (its shipping and tax after the discount); until then the summary shows shipping \"by\n * the choice\", never the cart's. An unusable code is re-thrown (HttpError with the server's message) and leaves\n * the summary as it was. A later delivery choice overtaking the repricing rejects it with an AbortError: the code\n * is applied all the same.\n */\nexport function applyCheckoutCoupon(code: string, options: { signal?: AbortSignal } = {}): Promise<Cart> {\n return pending(async () => {\n const choice = checkoutDraft.value.delivery\n const priced = summaryPriced.value\n if (choice) summaryPriced.value = false\n let applied: Cart\n try {\n applied = await applyCoupon(code, options)\n } catch (error) {\n summaryPriced.value = priced\n throw error\n }\n return choice ? chooseDelivery(choice, options) : applied\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":";;;;;;;;;;;AAqCO,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,Q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AA;AACA,sBAAc,QAAQ;AACtB,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,7 +1,7 @@
|
|
|
1
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, 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
|
-
export type { CheckoutStep, CheckoutIdentity, DeliveryChoice, CheckoutDraft, PlaceOrderInput, OrderCheck, } from './checkout';
|
|
3
|
+
export { checkoutDraft, checkoutPending, summaryPriced, updateDraft, clearCheckoutDraft, deliveryComplete, stepToShow, confirmIdentity, createAccount, confirmAddress, chooseAddress, chooseKind, loadDeliveryOptions, chooseDelivery, chooseSlot, applyCheckoutCoupon, loadPaymentMethods, beginCheckout, completeDelivery, orderInput, submitOrder, postToGateway, addOrderCheck, passOrderChecks, EMPTY_DRAFT, } from './checkout';
|
|
4
|
+
export type { CheckoutStep, CheckoutIdentity, DeliveryChoice, CheckoutDraft, PlaceOrderInput, NewAccount, OrderCheck, } from './checkout';
|
|
5
5
|
export { customerSignedIn, customerName } from './customer';
|
|
6
6
|
export { preferredLocation, retailLocations, locationPending, changeLocation } from './location';
|
|
7
7
|
export type { ChangeLocationOptions } from './location';
|
package/dist/core/types.d.ts
CHANGED
|
@@ -251,6 +251,8 @@ export interface PlacedOrder {
|
|
|
251
251
|
shippingAmount: number;
|
|
252
252
|
/** "delivery" or "pickup" (the delivery method's type) */
|
|
253
253
|
delivery_type: string;
|
|
254
|
+
/** The theme's text for an order delivered to an address (e.g. when it should arrive); null for a pickup or none */
|
|
255
|
+
delivery_note?: string | null;
|
|
254
256
|
couponCode: string | null;
|
|
255
257
|
currency: string;
|
|
256
258
|
/** The reserved slot as the shop words it; "" without one */
|
|
@@ -10,7 +10,8 @@ import { phpRound, formatMoney } from "../../core/money.js";
|
|
|
10
10
|
import { shopUrl } from "../../core/config.js";
|
|
11
11
|
import { storefront } from "../../core/state.js";
|
|
12
12
|
import { showToast } from "../toaster/toaster.js";
|
|
13
|
-
import { lineUrl, lineName, hasImage, renderTotals, cartBlocked
|
|
13
|
+
import { lineUrl, lineName, hasImage, renderTotals, cartBlocked } from "../shared/totals.js";
|
|
14
|
+
import { renderCouponForm, couponCode } from "../shared/coupon.js";
|
|
14
15
|
class SpmktCart extends SpmktElement {
|
|
15
16
|
constructor() {
|
|
16
17
|
super(...arguments);
|
|
@@ -157,37 +158,12 @@ class SpmktCart extends SpmktElement {
|
|
|
157
158
|
</div>`;
|
|
158
159
|
}
|
|
159
160
|
renderCoupon(current) {
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
void this.applyCoupon(event.target);
|
|
167
|
-
}}
|
|
168
|
-
>
|
|
169
|
-
<label for="cart-coupon-code">${t("cart.coupon")}</label>
|
|
170
|
-
<div class="cart-coupon__field">
|
|
171
|
-
<input
|
|
172
|
-
class="input"
|
|
173
|
-
id="cart-coupon-code"
|
|
174
|
-
name="coupon_code"
|
|
175
|
-
autocomplete="off"
|
|
176
|
-
data-test="coupon-input"
|
|
177
|
-
aria-invalid=${error ? "true" : nothing}
|
|
178
|
-
aria-describedby=${error ? "cart-coupon-error" : nothing}
|
|
179
|
-
/>
|
|
180
|
-
<button type="submit" class="button button--small" data-test="coupon-apply">
|
|
181
|
-
${t("cart.applyCoupon")}
|
|
182
|
-
</button>
|
|
183
|
-
</div>
|
|
184
|
-
<p class="field-error" id="cart-coupon-error" data-part="coupon-error" ?hidden=${!error}>
|
|
185
|
-
${error ?? ""}
|
|
186
|
-
</p>
|
|
187
|
-
${current.coupon_code ? html`<p class="cart-coupon__applied" data-test="coupon-applied">
|
|
188
|
-
${withStrong("cart.couponApplied", "code", current.coupon_code)}
|
|
189
|
-
</p>` : nothing}
|
|
190
|
-
</form>`;
|
|
161
|
+
return renderCouponForm({
|
|
162
|
+
prefix: "cart-coupon",
|
|
163
|
+
error: this.couponError,
|
|
164
|
+
applied: current.coupon_code,
|
|
165
|
+
onSubmit: (form) => void this.applyCoupon(form)
|
|
166
|
+
});
|
|
191
167
|
}
|
|
192
168
|
onQuantity(line, select) {
|
|
193
169
|
const qty = Number(select.value);
|
|
@@ -201,12 +177,8 @@ class SpmktCart extends SpmktElement {
|
|
|
201
177
|
await this.run(() => setQuantity({ id, qty }), t("cart.updateFailed"), void 0, undo);
|
|
202
178
|
}
|
|
203
179
|
async applyCoupon(form) {
|
|
204
|
-
const input = form
|
|
205
|
-
|
|
206
|
-
if (code === "") {
|
|
207
|
-
input?.focus();
|
|
208
|
-
return;
|
|
209
|
-
}
|
|
180
|
+
const { input, code } = couponCode(form);
|
|
181
|
+
if (code === "") return;
|
|
210
182
|
this.setCouponError(null);
|
|
211
183
|
await this.run(
|
|
212
184
|
async () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cart.js","sources":["../../../src/elements/cart/cart.ts"],"sourcesContent":["import { html, nothing, type TemplateResult } from 'lit'\nimport { repeat } from 'lit/directives/repeat.js'\nimport { SpmktElement } from '../../lit/spmkt-element'\nimport { SignalController } from '../../lit/signal-controller'\nimport { errorMessage } from '../../lit/forms'\nimport { applyCoupon, cart, cartLineToItem, setQuantity } from '../../core/stores/cart'\nimport { HttpError, ValidationError } from '../../core/errors'\nimport { t } from '../../core/i18n'\nimport { formatMoney, phpRound } from '../../core/money'\nimport { shopUrl } from '../../core/config'\nimport { storefront } from '../../core/state'\nimport type { Cart, CartLine } from '../../core/types'\nimport { showToast } from '../toaster/toaster'\nimport { cartBlocked, hasImage, lineName, lineUrl, renderTotals, withStrong } from '../shared/totals'\n\n/**\n * Parts of <spmkt-cart> (the cart page; the element renders the lines and the summary from the cart store):\n * - lines (required): empty in the theme's markup (aria-busy=\"true\" shows a skeleton until the first render)\n * - summary (required): the same; totals, the coupon form when the `coupon` attribute is set, and the way on\n * to checkout\n * - error (optional): why a change failed; render it hidden\n *\n * Every view of the cart renders from the same store, so a change here shows in the header's drawer and count\n * at once, and a change made there shows here. The element is busy (aria-busy) while its own change is in\n * flight and ignores further input. A theme changes the markup by overriding the render methods in a\n * subclass registered under the same tag.\n */\nexport interface CartParts {\n lines: HTMLElement\n summary: HTMLElement\n error?: HTMLElement\n}\n\nexport class SpmktCart extends SpmktElement {\n static override properties = {\n coupon: { type: Boolean },\n }\n /** Offer the coupon form (the theme's setting) */\n coupon = false\n\n private readonly cart = new SignalController(this, () => cart.value)\n private busy = false\n private couponError: string | null = null\n private viewed = false\n\n override connectedCallback(): void {\n super.connectedCallback()\n this.requirePart('lines')\n this.requirePart('summary')\n // Once per element: a reconnect (a section swap) is not another view of the cart\n if (!this.viewed && this.cart.value.items.length) {\n this.viewed = true\n const current = this.cart.value\n this.emit('spmkt:view-cart', {\n currency: current.items[0]?.currency || storefront().currency,\n value: phpRound(current.total, 2),\n items: current.items.map((line) => cartLineToItem(line)),\n })\n }\n }\n\n protected override updated(): void {\n const lines = this.requirePart('lines')\n const hadFocus = lines.contains(document.activeElement)\n this.renderPart('lines', this.renderLines(this.cart.value))\n this.renderPart('summary', this.renderSummary(this.cart.value))\n lines.removeAttribute('aria-busy')\n this.requirePart('summary').removeAttribute('aria-busy')\n // A removed line took the focus with it: keep the visitor in the list\n if (hadFocus && !lines.contains(document.activeElement)) {\n lines.tabIndex = -1\n lines.focus()\n }\n }\n\n protected renderLines(current: Cart): TemplateResult {\n if (!current.items.length) {\n return html`<div class=\"cart__empty\" data-test=\"cart-empty\">\n <p>${t('cart.empty')}</p>\n <a class=\"button button--primary\" href=${shopUrl('/')}>${t('cart.continue')}</a>\n </div>`\n }\n return html`<ul role=\"list\" class=\"cart-lines\">\n ${repeat(\n current.items,\n (line) => line.id,\n (line) => this.renderLine(line),\n )}\n </ul>`\n }\n\n protected renderLine(line: CartLine): TemplateResult {\n const url = lineUrl(line, shopUrl)\n const name = lineName(line)\n const id = `cart-qty-${line.id}`\n const quantities = Array.from({ length: Math.max(10, line.qty) }, (_, i) => i + 1)\n return html`<li\n class=\"cart-line${line.error ? ' cart-line--error' : ''}\"\n data-test=\"cart-line\"\n data-line=${line.id}\n >\n <a class=\"cart-line__image\" href=${url} tabindex=\"-1\" aria-hidden=\"true\">\n ${\n hasImage(line)\n ? html`<img src=${line.image_url} alt=\"\" width=\"96\" height=\"96\" loading=\"lazy\" />`\n : nothing\n }\n </a>\n <div class=\"cart-line__info\">\n <a class=\"cart-line__name\" href=${url} data-test=\"cart-item-name\">${name}</a>\n ${line.variant ? html`<p class=\"cart-line__variant\">${line.variant}</p>` : nothing}\n <p class=\"cart-line__price\">\n ${formatMoney(line.price)}\n ${\n line.original_price > line.price\n ? html`<s class=\"price__compare\"\n ><span class=\"visually-hidden\">${t('cart.oldPrice')}</span>\n ${formatMoney(line.original_price)}</s\n >`\n : nothing\n }\n </p>\n </div>\n <form class=\"cart-line__qty\" data-part=\"quantity\" @submit=${(event: Event) => event.preventDefault()}>\n <label class=\"visually-hidden\" for=${id}>${t('cart.quantity')}</label>\n <select\n class=\"select\"\n id=${id}\n name=\"qty\"\n data-test=\"cart-item-qty\"\n @change=${(event: Event) => this.onQuantity(line, event.target as HTMLSelectElement)}\n >\n ${quantities.map((qty) => html`<option value=${qty} ?selected=${qty === line.qty}>${qty}</option>`)}\n </select>\n </form>\n <p class=\"cart-line__total\" data-test=\"cart-line-total\">\n ${formatMoney(phpRound(line.price * line.qty, 2))}\n </p>\n <form\n class=\"cart-line__remove\"\n data-part=\"remove\"\n @submit=${(event: Event) => {\n event.preventDefault()\n void this.changeQuantity(line.id, 0)\n }}\n >\n <button\n type=\"submit\"\n class=\"link-button\"\n data-test=\"cart-item-remove\"\n aria-label=${t('cart.removeNamed', { name })}\n >\n ${t('cart.remove')}\n </button>\n </form>\n ${\n line.error\n ? html`<p class=\"cart-line__error\" role=\"alert\" data-test=\"cart-line-error\">${line.error}</p>`\n : nothing\n }\n </li>`\n }\n\n protected renderSummary(current: Cart): TemplateResult | typeof nothing {\n if (!current.items.length) return nothing\n return html`<div class=\"cart-summary\">\n ${this.coupon ? this.renderCoupon(current) : nothing}\n ${renderTotals(\n {\n subtotal: current.subtotal,\n discount: current.discount,\n shipping: current.shipping,\n taxAmount: current.tax_amount,\n taxPercent: current.tax_percent,\n total: current.total,\n },\n { shipping: 'charged', testId: 'cart-totals', totalTestId: 'cart-total' },\n )}\n ${\n cartBlocked(current.items)\n ? html`<button\n type=\"button\"\n class=\"button button--primary button--block\"\n disabled\n data-test=\"to-checkout-btn\"\n >\n ${t('cart.toCheckout')}\n </button>\n <p class=\"cart-summary__note\">${t('cart.blocked')}</p>`\n : html`<a\n class=\"button button--primary button--block\"\n href=${shopUrl('/shopping-cart?step=delivery')}\n data-test=\"to-checkout-btn\"\n >${t('cart.toCheckout')}</a\n >`\n }\n </div>`\n }\n\n protected renderCoupon(current: Cart): TemplateResult {\n const error = this.couponError\n return html`<form\n class=\"cart-coupon\"\n data-part=\"coupon\"\n @submit=${(event: Event) => {\n event.preventDefault()\n void this.applyCoupon(event.target as HTMLFormElement)\n }}\n >\n <label for=\"cart-coupon-code\">${t('cart.coupon')}</label>\n <div class=\"cart-coupon__field\">\n <input\n class=\"input\"\n id=\"cart-coupon-code\"\n name=\"coupon_code\"\n autocomplete=\"off\"\n data-test=\"coupon-input\"\n aria-invalid=${error ? 'true' : nothing}\n aria-describedby=${error ? 'cart-coupon-error' : nothing}\n />\n <button type=\"submit\" class=\"button button--small\" data-test=\"coupon-apply\">\n ${t('cart.applyCoupon')}\n </button>\n </div>\n <p class=\"field-error\" id=\"cart-coupon-error\" data-part=\"coupon-error\" ?hidden=${!error}>\n ${error ?? ''}\n </p>\n ${\n current.coupon_code\n ? html`<p class=\"cart-coupon__applied\" data-test=\"coupon-applied\">\n ${withStrong('cart.couponApplied', 'code', current.coupon_code)}\n </p>`\n : nothing\n }\n </form>`\n }\n\n private onQuantity(line: CartLine, select: HTMLSelectElement): void {\n const qty = Number(select.value)\n // Choosing the quantity already shown sends nothing: a request in flight while the visitor goes on to\n // checkout races the next page for the cart\n if (!Number.isInteger(qty) || qty === line.qty) return\n void this.changeQuantity(line.id, qty, () => {\n select.value = String(line.qty)\n })\n }\n\n /** Sets a line's quantity (0 removes it); `undo` puts the control back when the change fails. */\n async changeQuantity(id: number, qty: number, undo?: () => void): Promise<void> {\n await this.run(() => setQuantity({ id, qty }), t('cart.updateFailed'), undefined, undo)\n }\n\n async applyCoupon(form: HTMLFormElement): Promise<void> {\n const input = form.querySelector<HTMLInputElement>('[name=\"coupon_code\"]')\n const code = (input?.value ?? '').trim()\n if (code === '') {\n input?.focus()\n return\n }\n this.setCouponError(null)\n await this.run(\n async () => {\n await applyCoupon(code)\n if (input) input.value = ''\n },\n t('cart.couponFailed'),\n (message) => {\n // An unusable code is the visitor's to fix: say it next to the field\n this.setCouponError(message)\n input?.focus()\n return true\n },\n )\n }\n\n private setCouponError(message: string | null): void {\n this.couponError = message\n this.requestUpdate()\n }\n\n /**\n * Runs a change with the element busy. A refusal is shown by `inline` when it can (e.g. next to the coupon\n * field), otherwise in the error part and as a toast.\n */\n private async run(\n action: () => Promise<unknown>,\n fallback: string,\n inline?: (message: string) => boolean,\n undo?: () => void,\n ): Promise<void> {\n if (this.busy) {\n undo?.()\n return\n }\n this.busy = true\n this.setAttribute('aria-busy', 'true')\n this.showError(null)\n try {\n await action()\n } catch (error) {\n undo?.()\n const message = errorMessage(error, fallback)\n const refused = error instanceof HttpError && (error.status === 400 || error instanceof ValidationError)\n if (!(refused && inline?.(message))) {\n this.showError(message)\n }\n } finally {\n this.busy = false\n this.removeAttribute('aria-busy')\n }\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":";;;;;;;;;;;;;AAiCO,MAAM,kBAAkB,aAAa;AAAA,EAArC,cAAA;AAAA,UAAA,GAAA,SAAA;AAKL,SAAA,SAAS;AAET,SAAiB,OAAO,IAAI,iBAAiB,MAAM,MAAM,KAAK,KAAK;AACnE,SAAQ,OAAO;AACf,SAAQ,cAA6B;AACrC,SAAQ,SAAS;AAAA,EAAA;AAAA,EATjB,OAAA;AAAA,SAAgB,aAAa;AAAA,MAC3B,QAAQ,EAAE,MAAM,QAAA;AAAA,IAAQ;AAAA,EAC1B;AAAA,EASS,oBAA0B;AACjC,UAAM,kBAAA;AACN,SAAK,YAAY,OAAO;AACxB,SAAK,YAAY,SAAS;AAE1B,QAAI,CAAC,KAAK,UAAU,KAAK,KAAK,MAAM,MAAM,QAAQ;AAChD,WAAK,SAAS;AACd,YAAM,UAAU,KAAK,KAAK;AAC1B,WAAK,KAAK,mBAAmB;AAAA,QAC3B,UAAU,QAAQ,MAAM,CAAC,GAAG,YAAY,aAAa;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F;AAAA,EAEQ,UAAU,SAA8B;AAC9C,UAAM,OAAO,KAAK,SAAS,OAAO;AAClC,QAAI,MAAM;AACR,WAAK,cAAc,WAAW;AAC9B,WAAK,SAAS,YAAY;AAAA,IAC5B;AACA,QAAI,YAAY,MAAM;AACpB,gBAAU,EAAE,SAAS,MAAM,QAAA,CAAS;AAAA,IACtC;AAAA,EACF;AACF;"}
|
|
1
|
+
{"version":3,"file":"cart.js","sources":["../../../src/elements/cart/cart.ts"],"sourcesContent":["import { html, nothing, type TemplateResult } from 'lit'\nimport { repeat } from 'lit/directives/repeat.js'\nimport { SpmktElement } from '../../lit/spmkt-element'\nimport { SignalController } from '../../lit/signal-controller'\nimport { errorMessage } from '../../lit/forms'\nimport { applyCoupon, cart, cartLineToItem, setQuantity } from '../../core/stores/cart'\nimport { HttpError, ValidationError } from '../../core/errors'\nimport { t } from '../../core/i18n'\nimport { formatMoney, phpRound } from '../../core/money'\nimport { shopUrl } from '../../core/config'\nimport { storefront } from '../../core/state'\nimport type { Cart, CartLine } from '../../core/types'\nimport { showToast } from '../toaster/toaster'\nimport { cartBlocked, hasImage, lineName, lineUrl, renderTotals } from '../shared/totals'\nimport { couponCode, renderCouponForm } from '../shared/coupon'\n\n/**\n * Parts of <spmkt-cart> (the cart page; the element renders the lines and the summary from the cart store):\n * - lines (required): empty in the theme's markup (aria-busy=\"true\" shows a skeleton until the first render)\n * - summary (required): the same; totals, the coupon form when the `coupon` attribute is set, and the way on\n * to checkout\n * - error (optional): why a change failed; render it hidden\n *\n * Every view of the cart renders from the same store, so a change here shows in the header's drawer and count\n * at once, and a change made there shows here. The element is busy (aria-busy) while its own change is in\n * flight and ignores further input. A theme changes the markup by overriding the render methods in a\n * subclass registered under the same tag.\n */\nexport interface CartParts {\n lines: HTMLElement\n summary: HTMLElement\n error?: HTMLElement\n}\n\nexport class SpmktCart extends SpmktElement {\n static override properties = {\n coupon: { type: Boolean },\n }\n /** Offer the coupon form (the theme's setting) */\n coupon = false\n\n private readonly cart = new SignalController(this, () => cart.value)\n private busy = false\n private couponError: string | null = null\n private viewed = false\n\n override connectedCallback(): void {\n super.connectedCallback()\n this.requirePart('lines')\n this.requirePart('summary')\n // Once per element: a reconnect (a section swap) is not another view of the cart\n if (!this.viewed && this.cart.value.items.length) {\n this.viewed = true\n const current = this.cart.value\n this.emit('spmkt:view-cart', {\n currency: current.items[0]?.currency || storefront().currency,\n value: phpRound(current.total, 2),\n items: current.items.map((line) => cartLineToItem(line)),\n })\n }\n }\n\n protected override updated(): void {\n const lines = this.requirePart('lines')\n const hadFocus = lines.contains(document.activeElement)\n this.renderPart('lines', this.renderLines(this.cart.value))\n this.renderPart('summary', this.renderSummary(this.cart.value))\n lines.removeAttribute('aria-busy')\n this.requirePart('summary').removeAttribute('aria-busy')\n // A removed line took the focus with it: keep the visitor in the list\n if (hadFocus && !lines.contains(document.activeElement)) {\n lines.tabIndex = -1\n lines.focus()\n }\n }\n\n protected renderLines(current: Cart): TemplateResult {\n if (!current.items.length) {\n return html`<div class=\"cart__empty\" data-test=\"cart-empty\">\n <p>${t('cart.empty')}</p>\n <a class=\"button button--primary\" href=${shopUrl('/')}>${t('cart.continue')}</a>\n </div>`\n }\n return html`<ul role=\"list\" class=\"cart-lines\">\n ${repeat(\n current.items,\n (line) => line.id,\n (line) => this.renderLine(line),\n )}\n </ul>`\n }\n\n protected renderLine(line: CartLine): TemplateResult {\n const url = lineUrl(line, shopUrl)\n const name = lineName(line)\n const id = `cart-qty-${line.id}`\n const quantities = Array.from({ length: Math.max(10, line.qty) }, (_, i) => i + 1)\n return html`<li\n class=\"cart-line${line.error ? ' cart-line--error' : ''}\"\n data-test=\"cart-line\"\n data-line=${line.id}\n >\n <a class=\"cart-line__image\" href=${url} tabindex=\"-1\" aria-hidden=\"true\">\n ${\n hasImage(line)\n ? html`<img src=${line.image_url} alt=\"\" width=\"96\" height=\"96\" loading=\"lazy\" />`\n : nothing\n }\n </a>\n <div class=\"cart-line__info\">\n <a class=\"cart-line__name\" href=${url} data-test=\"cart-item-name\">${name}</a>\n ${line.variant ? html`<p class=\"cart-line__variant\">${line.variant}</p>` : nothing}\n <p class=\"cart-line__price\">\n ${formatMoney(line.price)}\n ${\n line.original_price > line.price\n ? html`<s class=\"price__compare\"\n ><span class=\"visually-hidden\">${t('cart.oldPrice')}</span>\n ${formatMoney(line.original_price)}</s\n >`\n : nothing\n }\n </p>\n </div>\n <form class=\"cart-line__qty\" data-part=\"quantity\" @submit=${(event: Event) => event.preventDefault()}>\n <label class=\"visually-hidden\" for=${id}>${t('cart.quantity')}</label>\n <select\n class=\"select\"\n id=${id}\n name=\"qty\"\n data-test=\"cart-item-qty\"\n @change=${(event: Event) => this.onQuantity(line, event.target as HTMLSelectElement)}\n >\n ${quantities.map((qty) => html`<option value=${qty} ?selected=${qty === line.qty}>${qty}</option>`)}\n </select>\n </form>\n <p class=\"cart-line__total\" data-test=\"cart-line-total\">\n ${formatMoney(phpRound(line.price * line.qty, 2))}\n </p>\n <form\n class=\"cart-line__remove\"\n data-part=\"remove\"\n @submit=${(event: Event) => {\n event.preventDefault()\n void this.changeQuantity(line.id, 0)\n }}\n >\n <button\n type=\"submit\"\n class=\"link-button\"\n data-test=\"cart-item-remove\"\n aria-label=${t('cart.removeNamed', { name })}\n >\n ${t('cart.remove')}\n </button>\n </form>\n ${\n line.error\n ? html`<p class=\"cart-line__error\" role=\"alert\" data-test=\"cart-line-error\">${line.error}</p>`\n : nothing\n }\n </li>`\n }\n\n protected renderSummary(current: Cart): TemplateResult | typeof nothing {\n if (!current.items.length) return nothing\n return html`<div class=\"cart-summary\">\n ${this.coupon ? this.renderCoupon(current) : nothing}\n ${renderTotals(\n {\n subtotal: current.subtotal,\n discount: current.discount,\n shipping: current.shipping,\n taxAmount: current.tax_amount,\n taxPercent: current.tax_percent,\n total: current.total,\n },\n { shipping: 'charged', testId: 'cart-totals', totalTestId: 'cart-total' },\n )}\n ${\n cartBlocked(current.items)\n ? html`<button\n type=\"button\"\n class=\"button button--primary button--block\"\n disabled\n data-test=\"to-checkout-btn\"\n >\n ${t('cart.toCheckout')}\n </button>\n <p class=\"cart-summary__note\">${t('cart.blocked')}</p>`\n : html`<a\n class=\"button button--primary button--block\"\n href=${shopUrl('/shopping-cart?step=delivery')}\n data-test=\"to-checkout-btn\"\n >${t('cart.toCheckout')}</a\n >`\n }\n </div>`\n }\n\n protected renderCoupon(current: Cart): TemplateResult {\n return renderCouponForm({\n prefix: 'cart-coupon',\n error: this.couponError,\n applied: current.coupon_code,\n onSubmit: (form) => void this.applyCoupon(form),\n })\n }\n\n private onQuantity(line: CartLine, select: HTMLSelectElement): void {\n const qty = Number(select.value)\n // Choosing the quantity already shown sends nothing: a request in flight while the visitor goes on to\n // checkout races the next page for the cart\n if (!Number.isInteger(qty) || qty === line.qty) return\n void this.changeQuantity(line.id, qty, () => {\n select.value = String(line.qty)\n })\n }\n\n /** Sets a line's quantity (0 removes it); `undo` puts the control back when the change fails. */\n async changeQuantity(id: number, qty: number, undo?: () => void): Promise<void> {\n await this.run(() => setQuantity({ id, qty }), t('cart.updateFailed'), undefined, undo)\n }\n\n async applyCoupon(form: HTMLFormElement): Promise<void> {\n const { input, code } = couponCode(form)\n if (code === '') return\n this.setCouponError(null)\n await this.run(\n async () => {\n await applyCoupon(code)\n if (input) input.value = ''\n },\n t('cart.couponFailed'),\n (message) => {\n // An unusable code is the visitor's to fix: say it next to the field\n this.setCouponError(message)\n input?.focus()\n return true\n },\n )\n }\n\n private setCouponError(message: string | null): void {\n this.couponError = message\n this.requestUpdate()\n }\n\n /**\n * Runs a change with the element busy. A refusal is shown by `inline` when it can (e.g. next to the coupon\n * field), otherwise in the error part and as a toast.\n */\n private async run(\n action: () => Promise<unknown>,\n fallback: string,\n inline?: (message: string) => boolean,\n undo?: () => void,\n ): Promise<void> {\n if (this.busy) {\n undo?.()\n return\n }\n this.busy = true\n this.setAttribute('aria-busy', 'true')\n this.showError(null)\n try {\n await action()\n } catch (error) {\n undo?.()\n const message = errorMessage(error, fallback)\n const refused = error instanceof HttpError && (error.status === 400 || error instanceof ValidationError)\n if (!(refused && inline?.(message))) {\n this.showError(message)\n }\n } finally {\n this.busy = false\n this.removeAttribute('aria-busy')\n }\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":";;;;;;;;;;;;;;AAkCO,MAAM,kBAAkB,aAAa;AAAA,EAArC,cAAA;AAAA,UAAA,GAAA,SAAA;AAKL,SAAA,SAAS;AAET,SAAiB,OAAO,IAAI,iBAAiB,MAAM,MAAM,KAAK,KAAK;AACnE,SAAQ,OAAO;AACf,SAAQ,cAA6B;AACrC,SAAQ,SAAS;AAAA,EAAA;AAAA,EATjB,OAAA;AAAA,SAAgB,aAAa;AAAA,MAC3B,QAAQ,EAAE,MAAM,QAAA;AAAA,IAAQ;AAAA,EAC1B;AAAA,EASS,oBAA0B;AACjC,UAAM,kBAAA;AACN,SAAK,YAAY,OAAO;AACxB,SAAK,YAAY,SAAS;AAE1B,QAAI,CAAC,KAAK,UAAU,KAAK,KAAK,MAAM,MAAM,QAAQ;AAChD,WAAK,SAAS;AACd,YAAM,UAAU,KAAK,KAAK;AAC1B,WAAK,KAAK,mBAAmB;AAAA,QAC3B,UAAU,QAAQ,MAAM,CAAC,GAAG,YAAY,aAAa;AAAA,QACrD,OAAO,SAAS,QAAQ,OAAO,CAAC;AAAA,QAChC,OAAO,QAAQ,MAAM,IAAI,CAAC,SAAS,eAAe,IAAI,CAAC;AAAA,MAAA,CACxD;AAAA,IACH;AAAA,EACF;AAAA,EAEmB,UAAgB;AACjC,UAAM,QAAQ,KAAK,YAAY,OAAO;AACtC,UAAM,WAAW,MAAM,SAAS,SAAS,aAAa;AACtD,SAAK,WAAW,SAAS,KAAK,YAAY,KAAK,KAAK,KAAK,CAAC;AAC1D,SAAK,WAAW,WAAW,KAAK,cAAc,KAA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,QACA,MACe;AACf,QAAI,KAAK,MAAM;AACb,aAAA;AACA;AAAA,IACF;AACA,SAAK,OAAO;AACZ,SAAK,aAAa,aAAa,MAAM;AACrC,SAAK,UAAU,IAAI;AACnB,QAAI;AACF,YAAM,OAAA;AAAA,IACR,SAAS,OAAO;AACd,aAAA;AACA,YAAM,UAAU,aAAa,OAAO,QAAQ;AAC5C,YAAM,UAAU,iBAAiB,cAAc,MAAM,WAAW,OAAO,iBAAiB;AACxF,UAAI,EAAE,WAAW,SAAS,OAAO,IAAI;AACnC,aAAK,UAAU,OAAO;AAAA,MACxB;AAAA,IACF,UAAA;AACE,WAAK,OAAO;AACZ,WAAK,gBAAgB,WAAW;AAAA,IAClC;AAAA,EACF;AAAA,EAEQ,UAAU,SAA8B;AAC9C,UAAM,OAAO,KAAK,SAAS,OAAO;AAClC,QAAI,MAAM;AACR,WAAK,cAAc,WAAW;AAC9B,WAAK,SAAS,YAAY;AAAA,IAC5B;AACA,QAAI,YAAY,MAAM;AACpB,gBAAU,EAAE,SAAS,MAAM,QAAA,CAAS;AAAA,IACtC;AAAA,EACF;AACF;"}
|
|
@@ -10,7 +10,9 @@ import type { Cart, CartLine } from '../../core/types';
|
|
|
10
10
|
* - go (optional, any number): buttons with data-go="<step>"; those leading to payment stay disabled until the
|
|
11
11
|
* delivery step is complete and no checkout request is in flight (the choice is priced)
|
|
12
12
|
* - summary (optional): empty in the theme's markup; the element renders the order's lines and totals from the
|
|
13
|
-
* cart store, so a priced delivery choice (summaryPriced) shows at once
|
|
13
|
+
* cart store, so a priced delivery choice (summaryPriced) shows at once. With the `coupon` attribute (the
|
|
14
|
+
* theme's setting) the coupon form comes first, as in the cart; a code applied here prices the chosen delivery
|
|
15
|
+
* again (applyCheckoutCoupon)
|
|
14
16
|
*
|
|
15
17
|
* When an instant payment places the order (spmkt:order-placed), a <spmkt-order-confirmation> with that order
|
|
16
18
|
* takes the element's place, and the URL becomes ?step=done.
|
|
@@ -31,9 +33,16 @@ export declare class SpmktCheckout extends SpmktElement {
|
|
|
31
33
|
step: {
|
|
32
34
|
type: StringConstructor;
|
|
33
35
|
};
|
|
36
|
+
coupon: {
|
|
37
|
+
type: BooleanConstructor;
|
|
38
|
+
};
|
|
34
39
|
};
|
|
35
40
|
/** The step the server rendered (from ?step=) */
|
|
36
41
|
step: Step;
|
|
42
|
+
/** Offer the coupon form beside the steps (the theme's setting) */
|
|
43
|
+
coupon: boolean;
|
|
44
|
+
private couponError;
|
|
45
|
+
private couponBusy;
|
|
37
46
|
private current;
|
|
38
47
|
private begun;
|
|
39
48
|
private readonly summary;
|
|
@@ -42,6 +51,13 @@ export declare class SpmktCheckout extends SpmktElement {
|
|
|
42
51
|
protected updated(): void;
|
|
43
52
|
/** The order beside the steps: its lines and totals; shipping is "by the choice" until one is priced. */
|
|
44
53
|
protected renderSummary(current: Cart, priced: boolean): TemplateResult;
|
|
54
|
+
protected renderCoupon(current: Cart): TemplateResult;
|
|
55
|
+
/**
|
|
56
|
+
* Applies the code typed in the coupon form, once at a time. A refused code is said under the field; a failure
|
|
57
|
+
* after it applied (pricing the delivery again) under the field too, since the totals wait for it.
|
|
58
|
+
*/
|
|
59
|
+
applyCoupon(form: HTMLFormElement): Promise<void>;
|
|
60
|
+
private setCouponError;
|
|
45
61
|
protected renderLine(line: CartLine): TemplateResult;
|
|
46
62
|
/** Moves to a step (recording it in the history) if it can be entered. */
|
|
47
63
|
go(step: Step): void;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { nothing, html } from "lit";
|
|
2
2
|
import { repeat } from "lit/directives/repeat.js";
|
|
3
3
|
import { SpmktElement } from "../../lit/spmkt-element.js";
|
|
4
4
|
import { SignalController } from "../../lit/signal-controller.js";
|
|
@@ -7,9 +7,12 @@ import { shopUrl } from "../../core/config.js";
|
|
|
7
7
|
import { t } from "../../core/i18n.js";
|
|
8
8
|
import { formatMoney, phpRound } from "../../core/money.js";
|
|
9
9
|
import { cart } from "../../core/stores/cart.js";
|
|
10
|
-
import {
|
|
10
|
+
import { errorMessage } from "../../lit/forms.js";
|
|
11
|
+
import { HttpError, ValidationError } from "../../core/errors.js";
|
|
12
|
+
import { summaryPriced, deliveryComplete, checkoutPending, applyCheckoutCoupon, completeDelivery, stepToShow, beginCheckout } from "../../core/stores/checkout.js";
|
|
11
13
|
import { customerSignedIn } from "../../core/stores/customer.js";
|
|
12
14
|
import { renderTotals, lineName } from "../shared/totals.js";
|
|
15
|
+
import { renderCouponForm, couponCode } from "../shared/coupon.js";
|
|
13
16
|
import { checkoutDraft } from "../../core/stores/checkout-draft.js";
|
|
14
17
|
const CONFIRMATION_TAG = "spmkt-order-confirmation";
|
|
15
18
|
const STEPS = ["delivery", "payment"];
|
|
@@ -17,6 +20,9 @@ class SpmktCheckout extends SpmktElement {
|
|
|
17
20
|
constructor() {
|
|
18
21
|
super();
|
|
19
22
|
this.step = "delivery";
|
|
23
|
+
this.coupon = false;
|
|
24
|
+
this.couponError = null;
|
|
25
|
+
this.couponBusy = false;
|
|
20
26
|
this.current = null;
|
|
21
27
|
this.begun = false;
|
|
22
28
|
this.summary = new SignalController(this, () => ({
|
|
@@ -39,7 +45,8 @@ class SpmktCheckout extends SpmktElement {
|
|
|
39
45
|
}
|
|
40
46
|
static {
|
|
41
47
|
this.properties = {
|
|
42
|
-
step: { type: String }
|
|
48
|
+
step: { type: String },
|
|
49
|
+
coupon: { type: Boolean }
|
|
43
50
|
};
|
|
44
51
|
}
|
|
45
52
|
connectedCallback() {
|
|
@@ -66,16 +73,17 @@ class SpmktCheckout extends SpmktElement {
|
|
|
66
73
|
}
|
|
67
74
|
/** The order beside the steps: its lines and totals; shipping is "by the choice" until one is priced. */
|
|
68
75
|
renderSummary(current, priced) {
|
|
69
|
-
return html
|
|
70
|
-
<
|
|
71
|
-
|
|
72
|
-
|
|
76
|
+
return html`${this.coupon ? this.renderCoupon(current) : nothing}
|
|
77
|
+
<div class="checkout-summary">
|
|
78
|
+
<h2 class="checkout-summary__title">${t("checkout.summaryTitle")}</h2>
|
|
79
|
+
<ul role="list" class="checkout-summary__lines">
|
|
80
|
+
${repeat(
|
|
73
81
|
current.items,
|
|
74
82
|
(line) => line.id,
|
|
75
83
|
(line) => this.renderLine(line)
|
|
76
84
|
)}
|
|
77
|
-
|
|
78
|
-
|
|
85
|
+
</ul>
|
|
86
|
+
${renderTotals(
|
|
79
87
|
{
|
|
80
88
|
subtotal: current.subtotal,
|
|
81
89
|
discount: current.discount,
|
|
@@ -92,7 +100,42 @@ class SpmktCheckout extends SpmktElement {
|
|
|
92
100
|
shippingTestId: "checkout-shipping"
|
|
93
101
|
}
|
|
94
102
|
)}
|
|
95
|
-
|
|
103
|
+
</div>`;
|
|
104
|
+
}
|
|
105
|
+
renderCoupon(current) {
|
|
106
|
+
return renderCouponForm({
|
|
107
|
+
prefix: "checkout-coupon",
|
|
108
|
+
error: this.couponError,
|
|
109
|
+
applied: current.coupon_code,
|
|
110
|
+
onSubmit: (form) => void this.applyCoupon(form)
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Applies the code typed in the coupon form, once at a time. A refused code is said under the field; a failure
|
|
115
|
+
* after it applied (pricing the delivery again) under the field too, since the totals wait for it.
|
|
116
|
+
*/
|
|
117
|
+
async applyCoupon(form) {
|
|
118
|
+
const { input, code } = couponCode(form);
|
|
119
|
+
if (code === "" || this.couponBusy) return;
|
|
120
|
+
this.couponBusy = true;
|
|
121
|
+
form.setAttribute("aria-busy", "true");
|
|
122
|
+
this.setCouponError(null);
|
|
123
|
+
try {
|
|
124
|
+
await applyCheckoutCoupon(code);
|
|
125
|
+
if (input) input.value = "";
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (error instanceof DOMException && error.name === "AbortError") return;
|
|
128
|
+
const refused = error instanceof HttpError && (error.status === 400 || error instanceof ValidationError);
|
|
129
|
+
this.setCouponError(errorMessage(error, refused ? t("cart.couponFailed") : t("checkout.failed")));
|
|
130
|
+
input?.focus();
|
|
131
|
+
} finally {
|
|
132
|
+
this.couponBusy = false;
|
|
133
|
+
form.removeAttribute("aria-busy");
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
setCouponError(message) {
|
|
137
|
+
this.couponError = message;
|
|
138
|
+
this.requestUpdate();
|
|
96
139
|
}
|
|
97
140
|
renderLine(line) {
|
|
98
141
|
return html`<li class="checkout-summary__line">
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkout.js","sources":["../../../src/elements/checkout/checkout.ts"],"sourcesContent":["import { html, nothing, type LitElement, type TemplateResult } from 'lit'\nimport { repeat } from 'lit/directives/repeat.js'\nimport { SpmktElement } from '../../lit/spmkt-element'\nimport { SignalController } from '../../lit/signal-controller'\nimport { dispatch } from '../../core/events'\nimport { shopUrl } from '../../core/config'\nimport { t } from '../../core/i18n'\nimport { formatMoney, phpRound } from '../../core/money'\nimport { cart } from '../../core/stores/cart'\nimport {\n beginCheckout,\n checkoutDraft,\n checkoutPending,\n completeDelivery,\n deliveryComplete,\n stepToShow,\n summaryPriced,\n type CheckoutStep,\n} from '../../core/stores/checkout'\nimport { customerSignedIn } from '../../core/stores/customer'\nimport type { Cart, CartLine, PlacedOrder } from '../../core/types'\nimport { lineName, renderTotals } from '../shared/totals'\n\n/**\n * Parts of <spmkt-checkout step=\"delivery|payment\"> (the checkout page; the theme renders every step):\n * - panel (required, one per step): a step's region, with data-step; hidden unless it is the current step. Its\n * first heading (tabindex=\"-1\") takes the focus when the step changes.\n * - nav-step (optional, one per step): marked aria-current=\"step\" for the current step\n * - go (optional, any number): buttons with data-go=\"<step>\"; those leading to payment stay disabled until the\n * delivery step is complete and no checkout request is in flight (the choice is priced)\n * - summary (optional): empty in the theme's markup; the element renders the order's lines and totals from the\n * cart store, so a priced delivery choice (summaryPriced) shows at once\n *\n * When an instant payment places the order (spmkt:order-placed), a <spmkt-order-confirmation> with that order\n * takes the element's place, and the URL becomes ?step=done.\n *\n * The step is kept in ?step= (pushState); Back and Forward move between steps. A step that cannot be entered\n * yet (payment before the delivery step is complete, e.g. after a reload in another tab) shows the first one\n * that can; an empty cart goes back to the cart page.\n */\nexport interface CheckoutParts {\n panel: HTMLElement[]\n 'nav-step'?: HTMLElement[]\n go?: HTMLButtonElement[]\n summary?: HTMLElement\n}\n\ntype Step = Exclude<CheckoutStep, 'cart' | 'done'>\nconst CONFIRMATION_TAG = 'spmkt-order-confirmation'\nconst STEPS: readonly Step[] = ['delivery', 'payment']\n\nexport class SpmktCheckout extends SpmktElement {\n static override properties = {\n step: { type: String },\n }\n /** The step the server rendered (from ?step=) */\n step: Step = 'delivery'\n\n private current: Step | null = null\n private begun = false\n private readonly summary = new SignalController(this, () => ({\n cart: cart.value,\n priced: summaryPriced.value,\n }))\n\n constructor() {\n super()\n // The way to payment opens once the delivery step is complete\n new SignalController(\n this,\n () => {\n void checkoutDraft.value\n void customerSignedIn.value\n // Not while a choice is still being priced: payment shows the total\n return deliveryComplete() && !checkoutPending.value\n },\n (complete) => {\n for (const button of this.findParts<HTMLButtonElement>('go')) {\n if (button.dataset.go === 'payment') button.disabled = !complete\n }\n },\n )\n }\n\n override connectedCallback(): void {\n super.connectedCallback()\n this.requirePart('panel')\n\n this.listen(this, 'click', (event) => {\n const button = (event.target as Element).closest<HTMLElement>('[data-part=\"go\"][data-go]')\n if (button && this.contains(button)) {\n event.preventDefault()\n this.go(button.dataset.go as Step)\n }\n })\n this.listen(this, 'spmkt:order-placed', (event) => {\n void this.confirm(event.detail.order)\n })\n this.listen(window, 'popstate', () => this.show(this.fromUrl(), { history: 'none' }))\n\n this.show(this.isStep(this.step) ? this.step : 'delivery', { history: 'replace', focus: false })\n }\n\n protected override updated(): void {\n const part = this.findPart('summary')\n if (!part) return\n this.renderPart('summary', this.renderSummary(this.summary.value.cart, this.summary.value.priced))\n part.removeAttribute('aria-busy')\n }\n\n /** The order beside the steps: its lines and totals; shipping is \"by the choice\" until one is priced. */\n protected renderSummary(current: Cart, priced: boolean): TemplateResult {\n return html`<div class=\"checkout-summary\">\n <h2 class=\"checkout-summary__title\">${t('checkout.summaryTitle')}</h2>\n <ul role=\"list\" class=\"checkout-summary__lines\">\n ${repeat(\n current.items,\n (line) => line.id,\n (line) => this.renderLine(line),\n )}\n </ul>\n ${renderTotals(\n {\n subtotal: current.subtotal,\n discount: current.discount,\n coupon: current.coupon_code,\n shipping: current.shipping,\n taxAmount: current.tax_amount,\n taxPercent: current.tax_percent,\n total: current.total,\n },\n {\n shipping: priced ? 'always' : 'by-choice',\n testId: 'checkout-totals',\n totalTestId: 'checkout-total',\n shippingTestId: 'checkout-shipping',\n },\n )}\n </div>`\n }\n\n protected renderLine(line: CartLine): TemplateResult {\n return html`<li class=\"checkout-summary__line\">\n <span class=\"checkout-summary__name\">\n ${lineName(line)}\n ${line.variant ? html`<span class=\"checkout-summary__variant\">${line.variant}</span>` : nothing}\n <span class=\"checkout-summary__qty\">${line.qty} × ${formatMoney(line.price)}</span>\n </span>\n <span>${formatMoney(phpRound(line.price * line.qty, 2))}</span>\n </li>`\n }\n\n /** Moves to a step (recording it in the history) if it can be entered. */\n go(step: Step): void {\n if (step === 'payment' && this.current === 'delivery' && deliveryComplete()) {\n completeDelivery()\n }\n this.show(step, { history: 'push' })\n }\n\n private show(requested: Step, options: { history: 'push' | 'replace' | 'none'; focus?: boolean }): void {\n const target = stepToShow(requested)\n if (target === 'cart') {\n location.assign(shopUrl('/shopping-cart'))\n return\n }\n const step = target as Step\n if (options.history !== 'none' || step !== requested) {\n const url = new URL(location.href)\n url.searchParams.set('step', step)\n const method = options.history === 'push' && step !== this.current ? 'pushState' : 'replaceState'\n history[method]({ ...(history.state as object), spmktCheckout: step }, '', url)\n }\n if (step === this.current) return\n this.current = step\n for (const panel of this.findParts('panel')) panel.hidden = panel.dataset.step !== step\n for (const item of this.findParts('nav-step')) {\n if (item.dataset.step === step) item.setAttribute('aria-current', 'step')\n else item.removeAttribute('aria-current')\n }\n if (step === 'delivery' && !this.begun) {\n this.begun = true\n beginCheckout()\n }\n if (options.focus !== false) {\n this.findParts('panel')\n .find((panel) => panel.dataset.step === step)\n ?.querySelector<HTMLElement>('h1, h2, h3')\n ?.focus()\n window.scrollTo({ top: 0 })\n }\n this.emit('spmkt:checkout-step', { step })\n }\n\n /**\n * The order is placed: a <spmkt-order-confirmation> with it takes the element's place (it announces the\n * purchase once and forgets the checkout draft), and its heading takes the focus once it has rendered.\n * ?step=done; a reload shows the (now empty) cart.\n */\n private async confirm(order: PlacedOrder): Promise<void> {\n const confirmation = document.createElement(CONFIRMATION_TAG) as HTMLElement & { order?: PlacedOrder }\n const content = document.createElement('div')\n content.dataset.part = 'content'\n confirmation.append(content)\n confirmation.order = order\n this.current = null\n this.replaceWith(confirmation)\n const url = new URL(location.href)\n url.searchParams.set('step', 'done')\n history.replaceState({ ...(history.state as object), spmktCheckout: 'done' }, '', url)\n window.scrollTo({ top: 0 })\n // The element has left the page: tell the document\n dispatch(document, 'spmkt:checkout-step', { step: 'done' })\n await customElements.whenDefined(CONFIRMATION_TAG)\n await (confirmation as unknown as LitElement).updateComplete\n confirmation.querySelector<HTMLElement>('h1, h2')?.focus()\n }\n\n private fromUrl(): Step {\n const step = new URL(location.href).searchParams.get('step')\n return this.isStep(step) ? step : 'delivery'\n }\n\n private isStep(value: unknown): value is Step {\n return STEPS.includes(value as Step)\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;AAgDA,MAAM,mBAAmB;AACzB,MAAM,QAAyB,CAAC,YAAY,SAAS;AAE9C,MAAM,sBAAsB,aAAa;AAAA,EAc9C,cAAc;AACZ,UAAA;AAVF,SAAA,OAAa;AAEb,SAAQ,UAAuB;AAC/B,SAAQ,QAAQ;AAChB,SAAiB,UAAU,IAAI,iBAAiB,MAAM,OAAO;AAAA,MAC3D,MAAM,KAAK;AAAA,MACX,QAAQ,cAAc;AAAA,IAAA,EACtB;AAKA,QAAI;AAAA,MACF;AAAA,MACA,MAAM;AACJ,aAAK,cAAc;AACnB,aAAK,iBAAiB;AAEt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,YAAY,gBAAgB;AACjD,UAAO,aAAuC;AAC9C,iBAAa,cAA2B,QAAQ,GAAG,MAAA;AAAA,EACrD;AAAA,EAEQ,UAAgB;AACtB,UAAM,OAAO,IAAI,IAAI,SAAS,IAAI,EAAE,aAAa,IAAI,MAAM;AAC3D,WAAO,KAAK,OAAO,IAAI,IAAI,OAAO;AAAA,EACpC;AAAA,EAEQ,OAAO,OAA+B;AAC5C,WAAO,MAAM,SAAS,KAAa;AAAA,EACrC;AACF;"}
|
|
1
|
+
{"version":3,"file":"checkout.js","sources":["../../../src/elements/checkout/checkout.ts"],"sourcesContent":["import { html, nothing, type LitElement, type TemplateResult } from 'lit'\nimport { repeat } from 'lit/directives/repeat.js'\nimport { SpmktElement } from '../../lit/spmkt-element'\nimport { SignalController } from '../../lit/signal-controller'\nimport { dispatch } from '../../core/events'\nimport { shopUrl } from '../../core/config'\nimport { t } from '../../core/i18n'\nimport { formatMoney, phpRound } from '../../core/money'\nimport { cart } from '../../core/stores/cart'\nimport { errorMessage } from '../../lit/forms'\nimport { HttpError, ValidationError } from '../../core/errors'\nimport {\n applyCheckoutCoupon,\n beginCheckout,\n checkoutDraft,\n checkoutPending,\n completeDelivery,\n deliveryComplete,\n stepToShow,\n summaryPriced,\n type CheckoutStep,\n} from '../../core/stores/checkout'\nimport { customerSignedIn } from '../../core/stores/customer'\nimport type { Cart, CartLine, PlacedOrder } from '../../core/types'\nimport { lineName, renderTotals } from '../shared/totals'\nimport { couponCode, renderCouponForm } from '../shared/coupon'\n\n/**\n * Parts of <spmkt-checkout step=\"delivery|payment\"> (the checkout page; the theme renders every step):\n * - panel (required, one per step): a step's region, with data-step; hidden unless it is the current step. Its\n * first heading (tabindex=\"-1\") takes the focus when the step changes.\n * - nav-step (optional, one per step): marked aria-current=\"step\" for the current step\n * - go (optional, any number): buttons with data-go=\"<step>\"; those leading to payment stay disabled until the\n * delivery step is complete and no checkout request is in flight (the choice is priced)\n * - summary (optional): empty in the theme's markup; the element renders the order's lines and totals from the\n * cart store, so a priced delivery choice (summaryPriced) shows at once. With the `coupon` attribute (the\n * theme's setting) the coupon form comes first, as in the cart; a code applied here prices the chosen delivery\n * again (applyCheckoutCoupon)\n *\n * When an instant payment places the order (spmkt:order-placed), a <spmkt-order-confirmation> with that order\n * takes the element's place, and the URL becomes ?step=done.\n *\n * The step is kept in ?step= (pushState); Back and Forward move between steps. A step that cannot be entered\n * yet (payment before the delivery step is complete, e.g. after a reload in another tab) shows the first one\n * that can; an empty cart goes back to the cart page.\n */\nexport interface CheckoutParts {\n panel: HTMLElement[]\n 'nav-step'?: HTMLElement[]\n go?: HTMLButtonElement[]\n summary?: HTMLElement\n}\n\ntype Step = Exclude<CheckoutStep, 'cart' | 'done'>\nconst CONFIRMATION_TAG = 'spmkt-order-confirmation'\nconst STEPS: readonly Step[] = ['delivery', 'payment']\n\nexport class SpmktCheckout extends SpmktElement {\n static override properties = {\n step: { type: String },\n coupon: { type: Boolean },\n }\n /** The step the server rendered (from ?step=) */\n step: Step = 'delivery'\n /** Offer the coupon form beside the steps (the theme's setting) */\n coupon = false\n\n private couponError: string | null = null\n private couponBusy = false\n\n private current: Step | null = null\n private begun = false\n private readonly summary = new SignalController(this, () => ({\n cart: cart.value,\n priced: summaryPriced.value,\n }))\n\n constructor() {\n super()\n // The way to payment opens once the delivery step is complete\n new SignalController(\n this,\n () => {\n void checkoutDraft.value\n void customerSignedIn.value\n // Not while a choice is still being priced: payment shows the total\n return deliveryComplete() && !checkoutPending.value\n },\n (complete) => {\n for (const button of this.findParts<HTMLButtonElement>('go')) {\n if (button.dataset.go === 'payment') button.disabled = !complete\n }\n },\n )\n }\n\n override connectedCallback(): void {\n super.connectedCallback()\n this.requirePart('panel')\n\n this.listen(this, 'click', (event) => {\n const button = (event.target as Element).closest<HTMLElement>('[data-part=\"go\"][data-go]')\n if (button && this.contains(button)) {\n event.preventDefault()\n this.go(button.dataset.go as Step)\n }\n })\n this.listen(this, 'spmkt:order-placed', (event) => {\n void this.confirm(event.detail.order)\n })\n this.listen(window, 'popstate', () => this.show(this.fromUrl(), { history: 'none' }))\n\n this.show(this.isStep(this.step) ? this.step : 'delivery', { history: 'replace', focus: false })\n }\n\n protected override updated(): void {\n const part = this.findPart('summary')\n if (!part) return\n this.renderPart('summary', this.renderSummary(this.summary.value.cart, this.summary.value.priced))\n part.removeAttribute('aria-busy')\n }\n\n /** The order beside the steps: its lines and totals; shipping is \"by the choice\" until one is priced. */\n protected renderSummary(current: Cart, priced: boolean): TemplateResult {\n return html`${this.coupon ? this.renderCoupon(current) : nothing}\n <div class=\"checkout-summary\">\n <h2 class=\"checkout-summary__title\">${t('checkout.summaryTitle')}</h2>\n <ul role=\"list\" class=\"checkout-summary__lines\">\n ${repeat(\n current.items,\n (line) => line.id,\n (line) => this.renderLine(line),\n )}\n </ul>\n ${renderTotals(\n {\n subtotal: current.subtotal,\n discount: current.discount,\n coupon: current.coupon_code,\n shipping: current.shipping,\n taxAmount: current.tax_amount,\n taxPercent: current.tax_percent,\n total: current.total,\n },\n {\n shipping: priced ? 'always' : 'by-choice',\n testId: 'checkout-totals',\n totalTestId: 'checkout-total',\n shippingTestId: 'checkout-shipping',\n },\n )}\n </div>`\n }\n\n protected renderCoupon(current: Cart): TemplateResult {\n return renderCouponForm({\n prefix: 'checkout-coupon',\n error: this.couponError,\n applied: current.coupon_code,\n onSubmit: (form) => void this.applyCoupon(form),\n })\n }\n\n /**\n * Applies the code typed in the coupon form, once at a time. A refused code is said under the field; a failure\n * after it applied (pricing the delivery again) under the field too, since the totals wait for it.\n */\n async applyCoupon(form: HTMLFormElement): Promise<void> {\n const { input, code } = couponCode(form)\n if (code === '' || this.couponBusy) return\n this.couponBusy = true\n form.setAttribute('aria-busy', 'true')\n this.setCouponError(null)\n try {\n await applyCheckoutCoupon(code)\n if (input) input.value = ''\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') return\n const refused = error instanceof HttpError && (error.status === 400 || error instanceof ValidationError)\n this.setCouponError(errorMessage(error, refused ? t('cart.couponFailed') : t('checkout.failed')))\n input?.focus()\n } finally {\n this.couponBusy = false\n form.removeAttribute('aria-busy')\n }\n }\n\n private setCouponError(message: string | null): void {\n this.couponError = message\n this.requestUpdate()\n }\n\n protected renderLine(line: CartLine): TemplateResult {\n return html`<li class=\"checkout-summary__line\">\n <span class=\"checkout-summary__name\">\n ${lineName(line)}\n ${line.variant ? html`<span class=\"checkout-summary__variant\">${line.variant}</span>` : nothing}\n <span class=\"checkout-summary__qty\">${line.qty} × ${formatMoney(line.price)}</span>\n </span>\n <span>${formatMoney(phpRound(line.price * line.qty, 2))}</span>\n </li>`\n }\n\n /** Moves to a step (recording it in the history) if it can be entered. */\n go(step: Step): void {\n if (step === 'payment' && this.current === 'delivery' && deliveryComplete()) {\n completeDelivery()\n }\n this.show(step, { history: 'push' })\n }\n\n private show(requested: Step, options: { history: 'push' | 'replace' | 'none'; focus?: boolean }): void {\n const target = stepToShow(requested)\n if (target === 'cart') {\n location.assign(shopUrl('/shopping-cart'))\n return\n }\n const step = target as Step\n if (options.history !== 'none' || step !== requested) {\n const url = new URL(location.href)\n url.searchParams.set('step', step)\n const method = options.history === 'push' && step !== this.current ? 'pushState' : 'replaceState'\n history[method]({ ...(history.state as object), spmktCheckout: step }, '', url)\n }\n if (step === this.current) return\n this.current = step\n for (const panel of this.findParts('panel')) panel.hidden = panel.dataset.step !== step\n for (const item of this.findParts('nav-step')) {\n if (item.dataset.step === step) item.setAttribute('aria-current', 'step')\n else item.removeAttribute('aria-current')\n }\n if (step === 'delivery' && !this.begun) {\n this.begun = true\n beginCheckout()\n }\n if (options.focus !== false) {\n this.findParts('panel')\n .find((panel) => panel.dataset.step === step)\n ?.querySelector<HTMLElement>('h1, h2, h3')\n ?.focus()\n window.scrollTo({ top: 0 })\n }\n this.emit('spmkt:checkout-step', { step })\n }\n\n /**\n * The order is placed: a <spmkt-order-confirmation> with it takes the element's place (it announces the\n * purchase once and forgets the checkout draft), and its heading takes the focus once it has rendered.\n * ?step=done; a reload shows the (now empty) cart.\n */\n private async confirm(order: PlacedOrder): Promise<void> {\n const confirmation = document.createElement(CONFIRMATION_TAG) as HTMLElement & { order?: PlacedOrder }\n const content = document.createElement('div')\n content.dataset.part = 'content'\n confirmation.append(content)\n confirmation.order = order\n this.current = null\n this.replaceWith(confirmation)\n const url = new URL(location.href)\n url.searchParams.set('step', 'done')\n history.replaceState({ ...(history.state as object), spmktCheckout: 'done' }, '', url)\n window.scrollTo({ top: 0 })\n // The element has left the page: tell the document\n dispatch(document, 'spmkt:checkout-step', { step: 'done' })\n await customElements.whenDefined(CONFIRMATION_TAG)\n await (confirmation as unknown as LitElement).updateComplete\n confirmation.querySelector<HTMLElement>('h1, h2')?.focus()\n }\n\n private fromUrl(): Step {\n const step = new URL(location.href).searchParams.get('step')\n return this.isStep(step) ? step : 'delivery'\n }\n\n private isStep(value: unknown): value is Step {\n return STEPS.includes(value as Step)\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAsDA,MAAM,mBAAmB;AACzB,MAAM,QAAyB,CAAC,YAAY,SAAS;AAE9C,MAAM,sBAAsB,aAAa;AAAA,EAoB9C,cAAc;AACZ,UAAA;AAfF,SAAA,OAAa;AAEb,SAAA,SAAS;AAET,SAAQ,cAA6B;AACrC,SAAQ,aAAa;AAErB,SAAQ,UAAuB;AAC/B,SAAQ,QAAQ;AAChB,SAAiB,UAAU,IAAI,iBAAiB,MAAM,OAAO;AAAA,MAC3D,MAAM,KAAK;AAAA,MACX,QAAQ,cAAc;AAAA,IAAA,EACtB;AAKA,QAAI;AAAA,MACF;AAAA,MACA,MAAM;AACJ,aAAK,cAAc;AACnB,aAAK,iBAAiB;AAEtB,eAAO,iBAAA,KAAsB,CAAC,gBAAgB;AAAA,MAChD;AAAA,MACA,CAAC,aAAa;AACZ,mBAAW,UAAU,KAAK,UAA6B,IAAI,GAAG;AAC5D,cAAI,OAAO,QAAQ,OAAO,UAAW,QAAO,WAAW,CAAC;AAAA,QAC1D;AAA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,QAAQ,UAAU,OAAO;AAC3B,WAAK,UAAU,OAAO,EACnB,KAAK,CAAC,UAAU,MAAM,QAAQ,SAAS,IAAI,GAC1C,cAA2B,YAAY,GACvC,MAAA;AACJ,aAAO,SAAS,EAAE,KAAK,EAAA,CAAG;AAAA,IAC5B;AACA,SAAK,KAAK,uBAAuB,EAAE,KAAA,CAAM;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAc,QAAQ,OAAmC;AACvD,UAAM,eAAe,SAAS,cAAc,gBAAgB;AAC5D,UAAM,UAAU,SAAS,cAAc,KAAK;AAC5C,YAAQ,QAAQ,OAAO;AACvB,iBAAa,OAAO,OAAO;AAC3B,iBAAa,QAAQ;AACrB,SAAK,UAAU;AACf,SAAK,YAAY,YAAY;AAC7B,UAAM,MAAM,IAAI,IAAI,SAAS,IAAI;AACjC,QAAI,aAAa,IAAI,QAAQ,MAAM;AACnC,YAAQ,aAAa,EAAE,GAAI,QAAQ,OAAkB,eAAe,OAAA,GAAU,IAAI,GAAG;AACrF,WAAO,SAAS,EAAE,KAAK,EAAA,CAAG;AAE1B,aAAS,UAAU,uBAAuB,EAAE,MAAM,QAAQ;AAC1D,UAAM,eAAe,YAAY,gBAAgB;AACjD,UAAO,aAAuC;AAC9C,iBAAa,cAA2B,QAAQ,GAAG,MAAA;AAAA,EACrD;AAAA,EAEQ,UAAgB;AACtB,UAAM,OAAO,IAAI,IAAI,SAAS,IAAI,EAAE,aAAa,IAAI,MAAM;AAC3D,WAAO,KAAK,OAAO,IAAI,IAAI,OAAO;AAAA,EACpC;AAAA,EAEQ,OAAO,OAA+B;AAC5C,WAAO,MAAM,SAAS,KAAa;AAAA,EACrC;AACF;"}
|
|
@@ -10,8 +10,9 @@ import { FoldingForm } from '../shared/folding-form';
|
|
|
10
10
|
* A guest's address is validated on the server (POST cart/address) and kept in the checkout draft. A
|
|
11
11
|
* signed-in customer chooses a saved address (checkout takes saved ones only); the form saves a new one to
|
|
12
12
|
* the address book (POST /api/addresses) and reloads the page, which lists it, chosen. A saved address the
|
|
13
|
-
* draft names but the page does not list (another customer's, or deleted) is dropped.
|
|
14
|
-
*
|
|
13
|
+
* draft names but the page does not list (another customer's, or deleted) is dropped. A customer without a
|
|
14
|
+
* saved address (one whose account was just made at the checkout) finds the form filled with the draft's contact
|
|
15
|
+
* details, as a guest does. The element is hidden while the order is picked up at the store.
|
|
15
16
|
*/
|
|
16
17
|
export interface CheckoutAddressParts {
|
|
17
18
|
form: HTMLFormElement;
|
|
@@ -36,6 +37,7 @@ export declare class SpmktCheckoutAddress extends FoldingForm {
|
|
|
36
37
|
/** Reloads the page after a customer saved an address; replaceable (tests, themes). */
|
|
37
38
|
reload: () => void;
|
|
38
39
|
private ready;
|
|
40
|
+
private fillRecipient;
|
|
39
41
|
private connectSaved;
|
|
40
42
|
protected accept(values: Record<string, string>): Promise<string | null>;
|
|
41
43
|
}
|
|
@@ -33,6 +33,8 @@ class SpmktCheckoutAddress extends FoldingForm {
|
|
|
33
33
|
super.connectedCallback();
|
|
34
34
|
if (this.mode === "customer") {
|
|
35
35
|
this.connectSaved();
|
|
36
|
+
const identity = checkoutDraft.value.identity;
|
|
37
|
+
if (!this.findPart("saved") && identity) this.fillRecipient(identity);
|
|
36
38
|
}
|
|
37
39
|
}
|
|
38
40
|
ready(ready) {
|
|
@@ -50,12 +52,13 @@ class SpmktCheckoutAddress extends FoldingForm {
|
|
|
50
52
|
this.fill({ ...draft.address }, true);
|
|
51
53
|
this.fold(summary(draft.address));
|
|
52
54
|
} else {
|
|
53
|
-
|
|
54
|
-
if (identity)
|
|
55
|
-
this.fill({ first_name: identity.first_name, last_name: identity.last_name, phone: identity.phone });
|
|
55
|
+
if (draft.identity) this.fillRecipient(draft.identity);
|
|
56
56
|
form.hidden = false;
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
|
+
fillRecipient(identity) {
|
|
60
|
+
this.fill({ first_name: identity.first_name, last_name: identity.last_name, phone: identity.phone });
|
|
61
|
+
}
|
|
59
62
|
connectSaved() {
|
|
60
63
|
const saved = this.findPart("saved");
|
|
61
64
|
if (!saved) return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkout-address.js","sources":["../../../src/elements/checkout-address/checkout-address.ts"],"sourcesContent":["import { FoldingForm } from '../shared/folding-form'\nimport { SignalController } from '../../lit/signal-controller'\nimport { saveAddress } from '../../core/api/address'\nimport { checkoutDraft, chooseAddress, confirmAddress, updateDraft } from '../../core/stores/checkout'\nimport type { CheckoutAddress } from '../../core/types'\n\n/**\n * Parts of <spmkt-checkout-address mode=\"guest|customer\"> (the delivery address in the delivery step):\n * - form (required): the address fields (first_name, last_name, address1, postcode, city, country_id, phone),\n * each with a [data-error-for] slot\n * - submit, error (optional); done, done-text, edit (optional, guest): see FoldingForm\n * - waiting (optional, guest): shown, with the form hidden, until the contact details are in\n * - saved (optional, customer): the saved addresses as radios named address_id; the checked one is chosen\n *\n * A guest's address is validated on the server (POST cart/address) and kept in the checkout draft. A\n * signed-in customer chooses a saved address (checkout takes saved ones only); the form saves a new one to\n * the address book (POST /api/addresses) and reloads the page, which lists it, chosen. A saved address the\n * draft names but the page does not list (another customer's, or deleted) is dropped. The element is hidden
|
|
1
|
+
{"version":3,"file":"checkout-address.js","sources":["../../../src/elements/checkout-address/checkout-address.ts"],"sourcesContent":["import { FoldingForm } from '../shared/folding-form'\nimport { SignalController } from '../../lit/signal-controller'\nimport { saveAddress } from '../../core/api/address'\nimport { checkoutDraft, chooseAddress, confirmAddress, updateDraft } from '../../core/stores/checkout'\nimport type { CheckoutAddress } from '../../core/types'\n\n/**\n * Parts of <spmkt-checkout-address mode=\"guest|customer\"> (the delivery address in the delivery step):\n * - form (required): the address fields (first_name, last_name, address1, postcode, city, country_id, phone),\n * each with a [data-error-for] slot\n * - submit, error (optional); done, done-text, edit (optional, guest): see FoldingForm\n * - waiting (optional, guest): shown, with the form hidden, until the contact details are in\n * - saved (optional, customer): the saved addresses as radios named address_id; the checked one is chosen\n *\n * A guest's address is validated on the server (POST cart/address) and kept in the checkout draft. A\n * signed-in customer chooses a saved address (checkout takes saved ones only); the form saves a new one to\n * the address book (POST /api/addresses) and reloads the page, which lists it, chosen. A saved address the\n * draft names but the page does not list (another customer's, or deleted) is dropped. A customer without a\n * saved address (one whose account was just made at the checkout) finds the form filled with the draft's contact\n * details, as a guest does. The element is hidden while the order is picked up at the store.\n */\nexport interface CheckoutAddressParts {\n form: HTMLFormElement\n submit?: HTMLButtonElement\n error?: HTMLElement\n done?: HTMLElement\n 'done-text'?: HTMLElement\n edit?: HTMLButtonElement\n waiting?: HTMLElement\n saved?: HTMLElement\n}\n\nexport class SpmktCheckoutAddress extends FoldingForm {\n static override properties = {\n mode: { type: String },\n }\n mode: 'guest' | 'customer' = 'guest'\n\n private open: boolean | null = null\n\n constructor() {\n super()\n // Pickup needs no address\n new SignalController(\n this,\n () => checkoutDraft.value.kind === 'pickup',\n (pickup) => (this.hidden = pickup),\n )\n // A guest's address opens once the contact details are in\n new SignalController(\n this,\n () => this.mode === 'guest' && checkoutDraft.value.identity !== null,\n (ready) => {\n if (this.mode !== 'guest' || ready === this.open) return\n this.open = ready\n this.ready(ready)\n },\n )\n }\n\n override connectedCallback(): void {\n super.connectedCallback()\n if (this.mode === 'customer') {\n this.connectSaved()\n // The first address: the contact details are the likely recipient (an account just made at the checkout)\n const identity = checkoutDraft.value.identity\n if (!this.findPart('saved') && identity) this.fillRecipient(identity)\n }\n }\n\n /** Reloads the page after a customer saved an address; replaceable (tests, themes). */\n reload: () => void = () => location.reload()\n\n private ready(ready: boolean): void {\n const waiting = this.findPart('waiting')\n if (waiting) waiting.hidden = ready\n const form = this.requirePart<HTMLFormElement>('form')\n if (!ready) {\n form.hidden = true\n const done = this.findPart('done')\n if (done) done.hidden = true\n return\n }\n const draft = checkoutDraft.value\n if (draft.address) {\n this.fill({ ...draft.address }, true)\n this.fold(summary(draft.address))\n } else {\n // The contact details are the likely recipient\n if (draft.identity) this.fillRecipient(draft.identity)\n form.hidden = false\n }\n }\n\n private fillRecipient(identity: { first_name: string; last_name: string; phone: string }): void {\n this.fill({ first_name: identity.first_name, last_name: identity.last_name, phone: identity.phone })\n }\n\n private connectSaved(): void {\n const saved = this.findPart('saved')\n if (!saved) return\n const radios = Array.from(saved.querySelectorAll<HTMLInputElement>('input[name=\"address_id\"]'))\n const chosen = radios.find((radio) => Number(radio.value) === checkoutDraft.value.addressId)\n if (chosen) chosen.checked = true\n const checked = radios.find((radio) => radio.checked)\n if (checked) chooseAddress(Number(checked.value))\n // Only the customer's own saved addresses, as this page lists them\n else if (checkoutDraft.value.addressId !== null)\n updateDraft({ addressId: null, delivery: null, slot: null })\n this.listen(saved, 'change', (event) => {\n const radio = event.target as HTMLInputElement\n if (radio.name === 'address_id') chooseAddress(Number(radio.value))\n })\n }\n\n protected override async accept(values: Record<string, string>): Promise<string | null> {\n const address: CheckoutAddress = {\n first_name: values.first_name ?? '',\n last_name: values.last_name ?? '',\n address1: values.address1 ?? '',\n city: values.city ?? '',\n postcode: values.postcode ?? '',\n country_id: Number(values.country_id),\n phone: values.phone || null,\n }\n if (this.mode === 'customer') {\n const saved = await saveAddress({ ...address, type: 'personal' })\n if (saved.id) chooseAddress(saved.id)\n this.reload()\n return null\n }\n const validated = await confirmAddress(address)\n return summary({ ...address, ...validated })\n }\n}\n\nfunction summary(address: CheckoutAddress): string {\n return [\n `${address.first_name} ${address.last_name}`.trim(),\n address.address1,\n `${address.postcode ?? ''} ${address.city ?? ''}`.trim(),\n address.phone,\n ]\n .filter(Boolean)\n .join(', ')\n}\n"],"names":[],"mappings":";;;;;AAgCO,MAAM,6BAA6B,YAAY;AAAA,EAQpD,cAAc;AACZ,UAAA;AALF,SAAA,OAA6B;AAE7B,SAAQ,OAAuB;AAiC/B,SAAA,SAAqB,MAAM,SAAS,OAAA;AA5BlC,QAAI;AAAA,MACF;AAAA,MACA,MAAM,cAAc,MAAM,SAAS;AAAA,MACnC,CAAC,WAAY,KAA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AAAA,IACR,GAAG,QAAQ,YAAY,EAAE,IAAI,QAAQ,QAAQ,EAAE,GAAG,KAAA;AAAA,IAClD,QAAQ;AAAA,EAAA,EAEP,OAAO,OAAO,EACd,KAAK,IAAI;AACd;"}
|
|
@@ -4,6 +4,12 @@ import { FoldingForm } from '../shared/folding-form';
|
|
|
4
4
|
* - form (required): email, first_name, last_name, phone, each with a [data-error-for] slot
|
|
5
5
|
* - submit, error (optional); done, done-text, edit (optional): see FoldingForm
|
|
6
6
|
* - account-hint (optional): shown when the e-mail has an account (signing in is offered, not required)
|
|
7
|
+
* - create-account (optional): a checkbox; checked, it shows account-fields (password, password_confirmation,
|
|
8
|
+
* terms_of_service, and date_of_birth when the shop checks the age, each with its [data-error-for] slot), and
|
|
9
|
+
* continuing makes the account (createAccount): the page then loads the checkout's delivery step again,
|
|
10
|
+
* signed in. Unchecked, the fields are disabled, so they are neither sent nor required. Checked, a field the
|
|
11
|
+
* browser finds invalid (a required terms box left empty, a short password) is shown by its slot before
|
|
12
|
+
* anything is sent (no reCAPTCHA round trip for a refusal the page can tell)
|
|
7
13
|
*
|
|
8
14
|
* The e-mail is validated on the server (POST checkout/email). What was entered is kept in the checkout
|
|
9
15
|
* draft, so a reload shows it folded again.
|
|
@@ -19,6 +25,8 @@ export interface CheckoutIdentityParts {
|
|
|
19
25
|
'done-text'?: HTMLElement;
|
|
20
26
|
edit?: HTMLButtonElement;
|
|
21
27
|
'account-hint'?: HTMLElement;
|
|
28
|
+
'create-account'?: HTMLInputElement;
|
|
29
|
+
'account-fields'?: HTMLElement;
|
|
22
30
|
}
|
|
23
31
|
export declare class SpmktCheckoutIdentity extends FoldingForm {
|
|
24
32
|
static properties: {
|
|
@@ -28,7 +36,18 @@ export declare class SpmktCheckoutIdentity extends FoldingForm {
|
|
|
28
36
|
};
|
|
29
37
|
};
|
|
30
38
|
pickupOnly: boolean;
|
|
39
|
+
/** The account is made and the page is loading again: another submit sends nothing */
|
|
40
|
+
private leaving;
|
|
31
41
|
constructor();
|
|
32
42
|
connectedCallback(): void;
|
|
33
|
-
protected accept(values: Record<string, string>): Promise<string>;
|
|
43
|
+
protected accept(values: Record<string, string>): Promise<string | null>;
|
|
44
|
+
/** Loads the delivery step again, now signed in (the account's session). */
|
|
45
|
+
protected continueSignedIn(): void;
|
|
46
|
+
/**
|
|
47
|
+
* Throws the account fields' own constraint failures (required, minlength, max) as the server's would be: the
|
|
48
|
+
* field's [data-error-for] slot's data-message, else the browser's message.
|
|
49
|
+
*/
|
|
50
|
+
private checkAccountFields;
|
|
51
|
+
/** The password and terms show (and are sent) only while the visitor asks for an account. */
|
|
52
|
+
private showAccountFields;
|
|
34
53
|
}
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { FoldingForm } from "../shared/folding-form.js";
|
|
2
2
|
import { SignalController } from "../../lit/signal-controller.js";
|
|
3
|
-
import {
|
|
3
|
+
import { shopUrl } from "../../core/config.js";
|
|
4
|
+
import { createAccount, confirmIdentity } from "../../core/stores/checkout.js";
|
|
5
|
+
import { ValidationError } from "../../core/errors.js";
|
|
4
6
|
import { checkoutDraft } from "../../core/stores/checkout-draft.js";
|
|
5
7
|
class SpmktCheckoutIdentity extends FoldingForm {
|
|
6
8
|
constructor() {
|
|
7
9
|
super();
|
|
8
10
|
this.pickupOnly = false;
|
|
11
|
+
this.leaving = false;
|
|
9
12
|
new SignalController(
|
|
10
13
|
this,
|
|
11
14
|
() => checkoutDraft.value.kind === "pickup",
|
|
@@ -21,6 +24,11 @@ class SpmktCheckoutIdentity extends FoldingForm {
|
|
|
21
24
|
}
|
|
22
25
|
connectedCallback() {
|
|
23
26
|
super.connectedCallback();
|
|
27
|
+
const create = this.findPart("create-account");
|
|
28
|
+
if (create) {
|
|
29
|
+
this.showAccountFields(create.checked);
|
|
30
|
+
this.listen(create, "change", () => this.showAccountFields(create.checked));
|
|
31
|
+
}
|
|
24
32
|
const identity = checkoutDraft.value.identity;
|
|
25
33
|
if (identity) {
|
|
26
34
|
this.fill({ ...identity }, true);
|
|
@@ -28,17 +36,59 @@ class SpmktCheckoutIdentity extends FoldingForm {
|
|
|
28
36
|
}
|
|
29
37
|
}
|
|
30
38
|
async accept(values) {
|
|
39
|
+
if (this.leaving) return null;
|
|
31
40
|
const identity = {
|
|
32
41
|
email: values.email ?? "",
|
|
33
42
|
first_name: values.first_name ?? "",
|
|
34
43
|
last_name: values.last_name ?? "",
|
|
35
44
|
phone: values.phone ?? ""
|
|
36
45
|
};
|
|
46
|
+
if (!this.pickupOnly && this.findPart("create-account")?.checked) {
|
|
47
|
+
this.checkAccountFields();
|
|
48
|
+
await createAccount(identity, {
|
|
49
|
+
password: values.password ?? "",
|
|
50
|
+
password_confirmation: values.password_confirmation ?? "",
|
|
51
|
+
terms_of_service: values.terms_of_service ?? "",
|
|
52
|
+
...values.date_of_birth !== void 0 ? { date_of_birth: values.date_of_birth } : {}
|
|
53
|
+
});
|
|
54
|
+
this.leaving = true;
|
|
55
|
+
this.continueSignedIn();
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
37
58
|
const { hasAccount } = await confirmIdentity(identity);
|
|
38
59
|
const hint = this.findPart("account-hint");
|
|
39
60
|
if (hint) hint.hidden = !hasAccount;
|
|
40
61
|
return summary(identity);
|
|
41
62
|
}
|
|
63
|
+
/** Loads the delivery step again, now signed in (the account's session). */
|
|
64
|
+
continueSignedIn() {
|
|
65
|
+
location.assign(shopUrl("/shopping-cart?step=delivery"));
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Throws the account fields' own constraint failures (required, minlength, max) as the server's would be: the
|
|
69
|
+
* field's [data-error-for] slot's data-message, else the browser's message.
|
|
70
|
+
*/
|
|
71
|
+
checkAccountFields() {
|
|
72
|
+
const fields = this.findPart("account-fields");
|
|
73
|
+
if (!fields) return;
|
|
74
|
+
const errors = {};
|
|
75
|
+
for (const control of fields.querySelectorAll("input, select, textarea")) {
|
|
76
|
+
if (control.name && !control.disabled && !control.checkValidity()) {
|
|
77
|
+
const slot = fields.querySelector(`[data-error-for="${CSS.escape(control.name)}"]`);
|
|
78
|
+
errors[control.name] = [slot?.dataset.message || control.validationMessage];
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (Object.keys(errors).length) throw new ValidationError("", errors, null);
|
|
82
|
+
}
|
|
83
|
+
/** The password and terms show (and are sent) only while the visitor asks for an account. */
|
|
84
|
+
showAccountFields(shown) {
|
|
85
|
+
const fields = this.findPart("account-fields");
|
|
86
|
+
if (!fields) return;
|
|
87
|
+
fields.hidden = !shown;
|
|
88
|
+
for (const control of fields.querySelectorAll("input, select, textarea")) {
|
|
89
|
+
control.disabled = !shown;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
42
92
|
}
|
|
43
93
|
function summary(identity) {
|
|
44
94
|
return [`${identity.first_name} ${identity.last_name}`.trim(), identity.email, identity.phone].filter(Boolean).join(", ");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkout-identity.js","sources":["../../../src/elements/checkout-identity/checkout-identity.ts"],"sourcesContent":["import { FoldingForm } from '../shared/folding-form'\nimport { SignalController } from '../../lit/signal-controller'\nimport { checkoutDraft, confirmIdentity } from '../../core/stores/checkout'\n\n/**\n * Parts of <spmkt-checkout-identity> (a guest's contact details in the delivery step):\n * - form (required): email, first_name, last_name, phone, each with a [data-error-for] slot\n * - submit, error (optional); done, done-text, edit (optional): see FoldingForm\n * - account-hint (optional): shown when the e-mail has an account (signing in is offered, not required)\n *\n * The e-mail is validated on the server (POST checkout/email). What was entered is kept in the checkout\n * draft, so a reload shows it folded again.\n *\n * With `pickup-only`, it asks only while the order is picked up at the store: a signed-in customer's pickup\n * contact (the account has the e-mail, so the form needs first_name, last_name and phone only).\n */\nexport interface CheckoutIdentityParts {\n form: HTMLFormElement\n submit?: HTMLButtonElement\n error?: HTMLElement\n done?: HTMLElement\n 'done-text'?: HTMLElement\n edit?: HTMLButtonElement\n 'account-hint'?: HTMLElement\n}\n\nexport class SpmktCheckoutIdentity extends FoldingForm {\n static override properties = {\n pickupOnly: { type: Boolean, attribute: 'pickup-only' },\n }\n pickupOnly = false\n\n constructor() {\n super()\n new SignalController(\n this,\n () => checkoutDraft.value.kind === 'pickup',\n (pickup) => {\n if (this.pickupOnly) this.hidden = !pickup\n },\n )\n }\n\n override connectedCallback(): void {\n super.connectedCallback()\n const identity = checkoutDraft.value.identity\n if (identity) {\n this.fill({ ...identity }, true)\n this.fold(summary(identity))\n }\n }\n\n protected override async accept(values: Record<string, string>): Promise<string> {\n const identity = {\n email: values.email ?? '',\n first_name: values.first_name ?? '',\n last_name: values.last_name ?? '',\n phone: values.phone ?? '',\n }\n const { hasAccount } = await confirmIdentity(identity)\n const hint = this.findPart('account-hint')\n if (hint) hint.hidden = !hasAccount\n return summary(identity)\n }\n}\n\nfunction summary(identity: { email: string; first_name: string; last_name: string; phone: string }): string {\n return [`${identity.first_name} ${identity.last_name}`.trim(), identity.email, identity.phone]\n .filter(Boolean)\n .join(', ')\n}\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"checkout-identity.js","sources":["../../../src/elements/checkout-identity/checkout-identity.ts"],"sourcesContent":["import { FoldingForm } from '../shared/folding-form'\nimport { SignalController } from '../../lit/signal-controller'\nimport { shopUrl } from '../../core/config'\nimport { checkoutDraft, confirmIdentity, createAccount } from '../../core/stores/checkout'\nimport { ValidationError } from '../../core/errors'\n\n/**\n * Parts of <spmkt-checkout-identity> (a guest's contact details in the delivery step):\n * - form (required): email, first_name, last_name, phone, each with a [data-error-for] slot\n * - submit, error (optional); done, done-text, edit (optional): see FoldingForm\n * - account-hint (optional): shown when the e-mail has an account (signing in is offered, not required)\n * - create-account (optional): a checkbox; checked, it shows account-fields (password, password_confirmation,\n * terms_of_service, and date_of_birth when the shop checks the age, each with its [data-error-for] slot), and\n * continuing makes the account (createAccount): the page then loads the checkout's delivery step again,\n * signed in. Unchecked, the fields are disabled, so they are neither sent nor required. Checked, a field the\n * browser finds invalid (a required terms box left empty, a short password) is shown by its slot before\n * anything is sent (no reCAPTCHA round trip for a refusal the page can tell)\n *\n * The e-mail is validated on the server (POST checkout/email). What was entered is kept in the checkout\n * draft, so a reload shows it folded again.\n *\n * With `pickup-only`, it asks only while the order is picked up at the store: a signed-in customer's pickup\n * contact (the account has the e-mail, so the form needs first_name, last_name and phone only).\n */\nexport interface CheckoutIdentityParts {\n form: HTMLFormElement\n submit?: HTMLButtonElement\n error?: HTMLElement\n done?: HTMLElement\n 'done-text'?: HTMLElement\n edit?: HTMLButtonElement\n 'account-hint'?: HTMLElement\n 'create-account'?: HTMLInputElement\n 'account-fields'?: HTMLElement\n}\n\nexport class SpmktCheckoutIdentity extends FoldingForm {\n static override properties = {\n pickupOnly: { type: Boolean, attribute: 'pickup-only' },\n }\n pickupOnly = false\n\n /** The account is made and the page is loading again: another submit sends nothing */\n private leaving = false\n\n constructor() {\n super()\n new SignalController(\n this,\n () => checkoutDraft.value.kind === 'pickup',\n (pickup) => {\n if (this.pickupOnly) this.hidden = !pickup\n },\n )\n }\n\n override connectedCallback(): void {\n super.connectedCallback()\n const create = this.findPart<HTMLInputElement>('create-account')\n if (create) {\n this.showAccountFields(create.checked)\n this.listen(create, 'change', () => this.showAccountFields(create.checked))\n }\n const identity = checkoutDraft.value.identity\n if (identity) {\n this.fill({ ...identity }, true)\n this.fold(summary(identity))\n }\n }\n\n protected override async accept(values: Record<string, string>): Promise<string | null> {\n if (this.leaving) return null\n const identity = {\n email: values.email ?? '',\n first_name: values.first_name ?? '',\n last_name: values.last_name ?? '',\n phone: values.phone ?? '',\n }\n if (!this.pickupOnly && this.findPart<HTMLInputElement>('create-account')?.checked) {\n this.checkAccountFields()\n await createAccount(identity, {\n password: values.password ?? '',\n password_confirmation: values.password_confirmation ?? '',\n terms_of_service: values.terms_of_service ?? '',\n ...(values.date_of_birth !== undefined ? { date_of_birth: values.date_of_birth } : {}),\n })\n this.leaving = true\n this.continueSignedIn()\n // The form stays open while the page loads signed in\n return null\n }\n const { hasAccount } = await confirmIdentity(identity)\n const hint = this.findPart('account-hint')\n if (hint) hint.hidden = !hasAccount\n return summary(identity)\n }\n\n /** Loads the delivery step again, now signed in (the account's session). */\n protected continueSignedIn(): void {\n location.assign(shopUrl('/shopping-cart?step=delivery'))\n }\n\n /**\n * Throws the account fields' own constraint failures (required, minlength, max) as the server's would be: the\n * field's [data-error-for] slot's data-message, else the browser's message.\n */\n private checkAccountFields(): void {\n const fields = this.findPart('account-fields')\n if (!fields) return\n const errors: Record<string, string[]> = {}\n for (const control of fields.querySelectorAll<HTMLInputElement>('input, select, textarea')) {\n if (control.name && !control.disabled && !control.checkValidity()) {\n const slot = fields.querySelector<HTMLElement>(`[data-error-for=\"${CSS.escape(control.name)}\"]`)\n errors[control.name] = [slot?.dataset.message || control.validationMessage]\n }\n }\n if (Object.keys(errors).length) throw new ValidationError('', errors, null)\n }\n\n /** The password and terms show (and are sent) only while the visitor asks for an account. */\n private showAccountFields(shown: boolean): void {\n const fields = this.findPart('account-fields')\n if (!fields) return\n fields.hidden = !shown\n for (const control of fields.querySelectorAll<HTMLInputElement>('input, select, textarea')) {\n control.disabled = !shown\n }\n }\n}\n\nfunction summary(identity: { email: string; first_name: string; last_name: string; phone: string }): string {\n return [`${identity.first_name} ${identity.last_name}`.trim(), identity.email, identity.phone]\n .filter(Boolean)\n .join(', ')\n}\n"],"names":[],"mappings":";;;;;;AAoCO,MAAM,8BAA8B,YAAY;AAAA,EASrD,cAAc;AACZ,UAAA;AANF,SAAA,aAAa;AAGb,SAAQ,UAAU;AAIhB,QAAI;AAAA,MACF;AAAA,MACA,MAAM,cAAc,MAAM,SAAS;AAAA,MACnC,CAAC,WAAW;AACV,YAAI,KAAK,WAAY,MAAK,SAAS,CAAC;AAAA,MACtC;AAAA,IAAA;AAAA,EAEJ;AAAA,EAjBA,OAAA;AAAA,SAAgB,aAAa;AAAA,MAC3B,YAAY,EAAE,MAAM,SAAS,WAAW,cAAA;AAAA,IAAc;AAAA,EACxD;AAAA,EAiBS,oBAA0B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SAAS,gBAAgB;AAC7C,QAAI,CAAC,OAAQ;AACb,UAAM,SAAmC,CAAA;AACzC,eAAW,WAAW,OAAO,iBAAmC,yBAAyB,GAAG;AAC1F,UAAI,QAAQ,QAAQ,CAAC,QAAQ,YAAY,CAAC,QAAQ,iBAAiB;AACjE,cAAM,OAAO,OAAO,cAA2B,oBAAoB,IAAI,OAAO,QAAQ,IAAI,CAAC,IAAI;AAC/F,eAAO,QAAQ,IAAI,IAAI,CAAC,MAAM,QAAQ,WAAW,QAAQ,iBAAiB;AAAA,MAC5E;AAAA,IACF;AACA,QAAI,OAAO,KAAK,MAAM,EAAE,cAAc,IAAI,gBAAgB,IAAI,QAAQ,IAAI;AAAA,EAC5E;AAAA;AAAA,EAGQ,kBAAkB,OAAsB;AAC9C,UAAM,SAAS,KAAK,SAAS,gBAAgB;AAC7C,QAAI,CAAC,OAAQ;AACb,WAAO,SAAS,CAAC;AACjB,eAAW,WAAW,OAAO,iBAAmC,yBAAyB,GAAG;AAC1F,cAAQ,WAAW,CAAC;AAAA,IACtB;AAAA,EACF;AACF;AAEA,SAAS,QAAQ,UAA2F;AAC1G,SAAO,CAAC,GAAG,SAAS,UAAU,IAAI,SAAS,SAAS,GAAG,KAAA,GAAQ,SAAS,OAAO,SAAS,KAAK,EAC1F,OAAO,OAAO,EACd,KAAK,IAAI;AACd;"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type PropertyValues, type TemplateResult } from 'lit';
|
|
1
|
+
import { nothing, type PropertyValues, type TemplateResult } from 'lit';
|
|
2
2
|
import { SpmktElement } from '../../lit/spmkt-element';
|
|
3
3
|
import type { OrderItem, PlacedOrder } from '../../core/types';
|
|
4
4
|
/**
|
|
@@ -8,6 +8,9 @@ import type { OrderItem, PlacedOrder } from '../../core/types';
|
|
|
8
8
|
* the `order` property takes its place when set (spmkt-checkout sets it)
|
|
9
9
|
* - content (created when missing): where the element renders the confirmation (renderConfirmation)
|
|
10
10
|
*
|
|
11
|
+
* The order's delivery_note (the theme's text, plain; a line break starts a paragraph) shows under the lead, e.g. when
|
|
12
|
+
* the order should arrive. The server sends it only for an order delivered to an address.
|
|
13
|
+
*
|
|
11
14
|
* The purchase is announced (spmkt:purchase) once per order in the tab, whichever page confirms it, and the
|
|
12
15
|
* checkout draft is forgotten with that first announcement.
|
|
13
16
|
*/
|
|
@@ -26,6 +29,7 @@ export declare class SpmktOrderConfirmation extends SpmktElement {
|
|
|
26
29
|
connectedCallback(): void;
|
|
27
30
|
protected updated(changed: PropertyValues<this>): void;
|
|
28
31
|
protected renderConfirmation(order: PlacedOrder, signedIn: boolean): TemplateResult;
|
|
32
|
+
protected renderDeliveryNote(order: PlacedOrder): TemplateResult | typeof nothing;
|
|
29
33
|
protected renderItem(item: OrderItem): TemplateResult;
|
|
30
34
|
/** spmkt:purchase, once per order in this tab; the first announcement also ends the checkout. */
|
|
31
35
|
private announce;
|
|
@@ -44,6 +44,7 @@ class SpmktOrderConfirmation extends SpmktElement {
|
|
|
44
44
|
${withStrong("order.received", "number", `#${order.id}`, "order-number")}
|
|
45
45
|
${order.email ? withStrong("order.emailSent", "email", order.email) : nothing}
|
|
46
46
|
</p>
|
|
47
|
+
${this.renderDeliveryNote(order)}
|
|
47
48
|
<dl class="order-confirmation__facts">
|
|
48
49
|
${order.date ? html`<div>
|
|
49
50
|
<dt>${t("order.date")}</dt>
|
|
@@ -81,6 +82,13 @@ class SpmktOrderConfirmation extends SpmktElement {
|
|
|
81
82
|
</div>
|
|
82
83
|
</section>`;
|
|
83
84
|
}
|
|
85
|
+
renderDeliveryNote(order) {
|
|
86
|
+
const lines = (order.delivery_note ?? "").split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
|
87
|
+
if (!lines.length) return nothing;
|
|
88
|
+
return html`<div class="order-confirmation__note" data-test="order-delivery-note">
|
|
89
|
+
${lines.map((line) => html`<p>${line}</p>`)}
|
|
90
|
+
</div>`;
|
|
91
|
+
}
|
|
84
92
|
renderItem(item) {
|
|
85
93
|
const quantity = Math.trunc(Number(item.quantity) || 0);
|
|
86
94
|
const price = Number(item.price) || 0;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"order-confirmation.js","sources":["../../../src/elements/order-confirmation/order-confirmation.ts"],"sourcesContent":["import { html, nothing, type PropertyValues, type TemplateResult } from 'lit'\nimport { SpmktElement } from '../../lit/spmkt-element'\nimport { SignalController } from '../../lit/signal-controller'\nimport { warnOnce } from '../../core/config'\nimport { shopUrl } from '../../core/config'\nimport { t } from '../../core/i18n'\nimport { formatMoney, phpRound } from '../../core/money'\nimport { firstPurchase, orderToPurchase } from '../../core/page-events'\nimport { clearCheckoutDraft } from '../../core/stores/checkout-draft'\nimport { customerSignedIn } from '../../core/stores/customer'\nimport type { OrderItem, PlacedOrder } from '../../core/types'\nimport { renderTotals, withStrong } from '../shared/totals'\n\n/**\n * Parts of <spmkt-order-confirmation> (a placed order: in place of the checkout after an instant payment, and\n * on the gateway's success page):\n * - order (optional): <script type=\"application/json\"> with the order (CheckoutController::sendResponse());\n * the `order` property takes its place when set (spmkt-checkout sets it)\n * - content (created when missing): where the element renders the confirmation (renderConfirmation)\n *\n * The purchase is announced (spmkt:purchase) once per order in the tab, whichever page confirms it, and the\n * checkout draft is forgotten with that first announcement.\n */\nexport interface OrderConfirmationParts {\n order?: HTMLScriptElement\n content?: HTMLElement\n}\n\nexport class SpmktOrderConfirmation extends SpmktElement {\n static override properties = {\n order: { attribute: false },\n }\n order: PlacedOrder | null = null\n\n private readonly signedIn = new SignalController(this, () => customerSignedIn.value)\n\n override connectedCallback(): void {\n super.connectedCallback()\n if (!this.order) this.order = this.readOrder()\n if (!this.findPart('content')) {\n const content = document.createElement('div')\n content.dataset.part = 'content'\n this.append(content)\n }\n }\n\n protected override updated(changed: PropertyValues<this>): void {\n const order = this.order\n if (!order) return\n this.renderPart('content', this.renderConfirmation(order, this.signedIn.value))\n this.findPart('content')?.removeAttribute('aria-busy')\n if (changed.has('order')) this.announce(order)\n }\n\n protected renderConfirmation(order: PlacedOrder, signedIn: boolean): TemplateResult {\n return html`<section class=\"order-confirmation\" data-test=\"order-confirmation\">\n <h1 class=\"order-confirmation__title\" data-test=\"checkout-success-title\" tabindex=\"-1\">\n ${t('order.title')}\n </h1>\n <p class=\"order-confirmation__lead\">\n ${withStrong('order.received', 'number', `#${order.id}`, 'order-number')}\n ${order.email ? withStrong('order.emailSent', 'email', order.email) : nothing}\n </p>\n <dl class=\"order-confirmation__facts\">\n ${\n order.date\n ? html`<div>\n <dt>${t('order.date')}</dt>\n <dd>${orderDate(order.date)}</dd>\n </div>`\n : nothing\n }\n ${\n order.delivery_type\n ? html`<div>\n <dt>${t('order.handover')}</dt>\n <dd data-test=\"order-delivery\">\n ${order.delivery_type === 'pickup' ? t('order.pickup') : t('order.delivery')}\n </dd>\n </div>`\n : nothing\n }\n ${\n order.reservation_slot\n ? html`<div>\n <dt>${t('order.slot')}</dt>\n <dd>${order.reservation_slot}</dd>\n </div>`\n : nothing\n }\n </dl>\n <ul role=\"list\" class=\"checkout-summary__lines order-confirmation__lines\">\n ${(order.items ?? []).map((item) => this.renderItem(item))}\n </ul>\n ${renderTotals(\n {\n shipping: Number(order.shippingAmount) || 0,\n taxAmount: Number(order.taxAmount) || 0,\n total: Number(order.total) || 0,\n },\n { shipping: 'always', totalTestId: 'order-total', className: 'order-confirmation__totals' },\n )}\n <div class=\"order-confirmation__actions\">\n <a class=\"button button--primary\" href=${shopUrl('/')}>${t('cart.continue')}</a>\n ${\n signedIn\n ? html`<a class=\"button\" href=${shopUrl('/account')} data-test=\"my-orders-link\"\n >${t('order.myOrders')}</a\n >`\n : html`<a class=\"button\" href=${shopUrl('/register')} data-test=\"create-account-link\"\n >${t('order.createAccount')}</a\n >`\n }\n </div>\n </section>`\n }\n\n protected renderItem(item: OrderItem): TemplateResult {\n const quantity = Math.trunc(Number(item.quantity) || 0)\n const price = Number(item.price) || 0\n return html`<li class=\"checkout-summary__line\">\n <span class=\"checkout-summary__name\">\n ${item.parent_name ?? item.item_name}\n ${item.item_variant ? html`<span class=\"checkout-summary__variant\">${item.item_variant}</span>` : nothing}\n <span class=\"checkout-summary__qty\">${quantity} × ${formatMoney(price)}</span>\n </span>\n <span>${formatMoney(phpRound(price * quantity, 2))}</span>\n </li>`\n }\n\n /** spmkt:purchase, once per order in this tab; the first announcement also ends the checkout. */\n private announce(order: PlacedOrder): void {\n const purchase = orderToPurchase(order)\n if (!purchase || !firstPurchase(purchase)) return\n clearCheckoutDraft()\n this.emit('spmkt:purchase', purchase)\n }\n\n private readOrder(): PlacedOrder | null {\n const text = this.findPart('order')?.textContent\n if (!text) return null\n try {\n const order = JSON.parse(text) as PlacedOrder | null\n return order && typeof order === 'object' && order.id ? order : null\n } catch {\n warnOnce('order-confirmation:json', 'The order of <spmkt-order-confirmation> is not valid JSON')\n return null\n }\n }\n}\n\n/** \"2026-11-08 20:15:00\" as \"08.11.2026. 20:15\", the shop's own time as the server sent it. */\nexport function orderDate(date: string): string {\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})[ T](\\d{2}):(\\d{2})/.exec(date)\n return match ? `${match[3]}.${match[2]}.${match[1]}. ${match[4]}:${match[5]}` : date\n}\n"],"names":[],"mappings":";;;;;;;;;;AA4BO,MAAM,+BAA+B,aAAa;AAAA,EAAlD,cAAA;AAAA,UAAA,GAAA,SAAA;AAIL,SAAA,QAA4B;AAE5B,SAAiB,WAAW,IAAI,iBAAiB,MAAM,MAAM,iBAAiB,KAAK;AAAA,EAAA;AAAA,EALnF,OAAA;AAAA,SAAgB,aAAa;AAAA,MAC3B,OAAO,EAAE,WAAW,MAAA;AAAA,IAAM;AAAA,EAC5B;AAAA,EAKS,oBAA0B;AACjC,UAAM,kBAAA;AACN,QAAI,CAAC,KAAK,MAAO,MAAK,QAAQ,KAAK,UAAA;AACnC,QAAI,CAAC,KAAK,SAAS,SAAS,GAAG;AAC7B,YAAM,UAAU,SAAS,cAAc,KAAK;AAC5C,cAAQ,QAAQ,OAAO;AACvB,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,CAAC,IAAI,MAAM,CAAC,CAAC,KAAK,MAAM,CAAC,CAAC,IAAI,MAAM,CAAC,CAAC,KAAK;AAClF;"}
|
|
1
|
+
{"version":3,"file":"order-confirmation.js","sources":["../../../src/elements/order-confirmation/order-confirmation.ts"],"sourcesContent":["import { html, nothing, type PropertyValues, type TemplateResult } from 'lit'\nimport { SpmktElement } from '../../lit/spmkt-element'\nimport { SignalController } from '../../lit/signal-controller'\nimport { warnOnce } from '../../core/config'\nimport { shopUrl } from '../../core/config'\nimport { t } from '../../core/i18n'\nimport { formatMoney, phpRound } from '../../core/money'\nimport { firstPurchase, orderToPurchase } from '../../core/page-events'\nimport { clearCheckoutDraft } from '../../core/stores/checkout-draft'\nimport { customerSignedIn } from '../../core/stores/customer'\nimport type { OrderItem, PlacedOrder } from '../../core/types'\nimport { renderTotals, withStrong } from '../shared/totals'\n\n/**\n * Parts of <spmkt-order-confirmation> (a placed order: in place of the checkout after an instant payment, and\n * on the gateway's success page):\n * - order (optional): <script type=\"application/json\"> with the order (CheckoutController::sendResponse());\n * the `order` property takes its place when set (spmkt-checkout sets it)\n * - content (created when missing): where the element renders the confirmation (renderConfirmation)\n *\n * The order's delivery_note (the theme's text, plain; a line break starts a paragraph) shows under the lead, e.g. when\n * the order should arrive. The server sends it only for an order delivered to an address.\n *\n * The purchase is announced (spmkt:purchase) once per order in the tab, whichever page confirms it, and the\n * checkout draft is forgotten with that first announcement.\n */\nexport interface OrderConfirmationParts {\n order?: HTMLScriptElement\n content?: HTMLElement\n}\n\nexport class SpmktOrderConfirmation extends SpmktElement {\n static override properties = {\n order: { attribute: false },\n }\n order: PlacedOrder | null = null\n\n private readonly signedIn = new SignalController(this, () => customerSignedIn.value)\n\n override connectedCallback(): void {\n super.connectedCallback()\n if (!this.order) this.order = this.readOrder()\n if (!this.findPart('content')) {\n const content = document.createElement('div')\n content.dataset.part = 'content'\n this.append(content)\n }\n }\n\n protected override updated(changed: PropertyValues<this>): void {\n const order = this.order\n if (!order) return\n this.renderPart('content', this.renderConfirmation(order, this.signedIn.value))\n this.findPart('content')?.removeAttribute('aria-busy')\n if (changed.has('order')) this.announce(order)\n }\n\n protected renderConfirmation(order: PlacedOrder, signedIn: boolean): TemplateResult {\n return html`<section class=\"order-confirmation\" data-test=\"order-confirmation\">\n <h1 class=\"order-confirmation__title\" data-test=\"checkout-success-title\" tabindex=\"-1\">\n ${t('order.title')}\n </h1>\n <p class=\"order-confirmation__lead\">\n ${withStrong('order.received', 'number', `#${order.id}`, 'order-number')}\n ${order.email ? withStrong('order.emailSent', 'email', order.email) : nothing}\n </p>\n ${this.renderDeliveryNote(order)}\n <dl class=\"order-confirmation__facts\">\n ${\n order.date\n ? html`<div>\n <dt>${t('order.date')}</dt>\n <dd>${orderDate(order.date)}</dd>\n </div>`\n : nothing\n }\n ${\n order.delivery_type\n ? html`<div>\n <dt>${t('order.handover')}</dt>\n <dd data-test=\"order-delivery\">\n ${order.delivery_type === 'pickup' ? t('order.pickup') : t('order.delivery')}\n </dd>\n </div>`\n : nothing\n }\n ${\n order.reservation_slot\n ? html`<div>\n <dt>${t('order.slot')}</dt>\n <dd>${order.reservation_slot}</dd>\n </div>`\n : nothing\n }\n </dl>\n <ul role=\"list\" class=\"checkout-summary__lines order-confirmation__lines\">\n ${(order.items ?? []).map((item) => this.renderItem(item))}\n </ul>\n ${renderTotals(\n {\n shipping: Number(order.shippingAmount) || 0,\n taxAmount: Number(order.taxAmount) || 0,\n total: Number(order.total) || 0,\n },\n { shipping: 'always', totalTestId: 'order-total', className: 'order-confirmation__totals' },\n )}\n <div class=\"order-confirmation__actions\">\n <a class=\"button button--primary\" href=${shopUrl('/')}>${t('cart.continue')}</a>\n ${\n signedIn\n ? html`<a class=\"button\" href=${shopUrl('/account')} data-test=\"my-orders-link\"\n >${t('order.myOrders')}</a\n >`\n : html`<a class=\"button\" href=${shopUrl('/register')} data-test=\"create-account-link\"\n >${t('order.createAccount')}</a\n >`\n }\n </div>\n </section>`\n }\n\n protected renderDeliveryNote(order: PlacedOrder): TemplateResult | typeof nothing {\n const lines = (order.delivery_note ?? '')\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n if (!lines.length) return nothing\n return html`<div class=\"order-confirmation__note\" data-test=\"order-delivery-note\">\n ${lines.map((line) => html`<p>${line}</p>`)}\n </div>`\n }\n\n protected renderItem(item: OrderItem): TemplateResult {\n const quantity = Math.trunc(Number(item.quantity) || 0)\n const price = Number(item.price) || 0\n return html`<li class=\"checkout-summary__line\">\n <span class=\"checkout-summary__name\">\n ${item.parent_name ?? item.item_name}\n ${item.item_variant ? html`<span class=\"checkout-summary__variant\">${item.item_variant}</span>` : nothing}\n <span class=\"checkout-summary__qty\">${quantity} × ${formatMoney(price)}</span>\n </span>\n <span>${formatMoney(phpRound(price * quantity, 2))}</span>\n </li>`\n }\n\n /** spmkt:purchase, once per order in this tab; the first announcement also ends the checkout. */\n private announce(order: PlacedOrder): void {\n const purchase = orderToPurchase(order)\n if (!purchase || !firstPurchase(purchase)) return\n clearCheckoutDraft()\n this.emit('spmkt:purchase', purchase)\n }\n\n private readOrder(): PlacedOrder | null {\n const text = this.findPart('order')?.textContent\n if (!text) return null\n try {\n const order = JSON.parse(text) as PlacedOrder | null\n return order && typeof order === 'object' && order.id ? order : null\n } catch {\n warnOnce('order-confirmation:json', 'The order of <spmkt-order-confirmation> is not valid JSON')\n return null\n }\n }\n}\n\n/** \"2026-11-08 20:15:00\" as \"08.11.2026. 20:15\", the shop's own time as the server sent it. */\nexport function orderDate(date: string): string {\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})[ T](\\d{2}):(\\d{2})/.exec(date)\n return match ? `${match[3]}.${match[2]}.${match[1]}. ${match[4]}:${match[5]}` : date\n}\n"],"names":[],"mappings":";;;;;;;;;;AA+BO,MAAM,+BAA+B,aAAa;AAAA,EAAlD,cAAA;AAAA,UAAA,GAAA,SAAA;AAIL,SAAA,QAA4B;AAE5B,SAAiB,WAAW,IAAI,iBAAiB,MAA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,YAAY,SAAS,QAAQ,UAAU,CAAC,CAAC,CAAC;AAAA;AAAA,EAEtD;AAAA;AAAA,EAGQ,SAAS,OAA0B;AACzC,UAAM,WAAW,gBAAgB,KAAK;AACtC,QAAI,CAAC,YAAY,CAAC,cAAc,QAAQ,EAAG;AAC3C,uBAAA;AACA,SAAK,KAAK,kBAAkB,QAAQ;AAAA,EACtC;AAAA,EAEQ,YAAgC;AACtC,UAAM,OAAO,KAAK,SAAS,OAAO,GAAG;AACrC,QAAI,CAAC,KAAM,QAAO;AAClB,QAAI;AACF,YAAM,QAAQ,KAAK,MAAM,IAAI;AAC7B,aAAO,SAAS,OAAO,UAAU,YAAY,MAAM,KAAK,QAAQ;AAAA,IAClE,QAAQ;AACN,eAAS,2BAA2B,2DAA2D;AAC/F,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAGO,SAAS,UAAU,MAAsB;AAC9C,QAAM,QAAQ,8CAA8C,KAAK,IAAI;AACrE,SAAO,QAAQ,GAAG,MAAM,CAAC,CAAC,IAAI,MAAM,CAAC,CAAC,IAAI,MAAM,CAAC,CAAC,KAAK,MAAM,CAAC,CAAC,IAAI,MAAM,CAAC,CAAC,KAAK;AAClF;"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type TemplateResult } from 'lit';
|
|
2
|
+
/**
|
|
3
|
+
* The coupon form the cart and the checkout summary share (`form.cart-coupon`, base's markup and data-test
|
|
4
|
+
* attributes): a code field with its apply button, the refusal under it, and the code applied so far.
|
|
5
|
+
*/
|
|
6
|
+
export interface CouponFormOptions {
|
|
7
|
+
/** Unique on the page: the field is `<prefix>-code`, its error `<prefix>-error` */
|
|
8
|
+
prefix: string;
|
|
9
|
+
/** Why the last code was refused, shown under the field */
|
|
10
|
+
error: string | null;
|
|
11
|
+
/** The code the cart has, if any */
|
|
12
|
+
applied: string | null | undefined;
|
|
13
|
+
onSubmit: (form: HTMLFormElement) => void;
|
|
14
|
+
}
|
|
15
|
+
export declare function renderCouponForm(options: CouponFormOptions): TemplateResult;
|
|
16
|
+
/** The code typed in a coupon form, trimmed; empty focuses the field. */
|
|
17
|
+
export declare function couponCode(form: HTMLFormElement): {
|
|
18
|
+
input: HTMLInputElement | null;
|
|
19
|
+
code: string;
|
|
20
|
+
};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { nothing, html } from "lit";
|
|
2
|
+
import { t } from "../../core/i18n.js";
|
|
3
|
+
import { withStrong } from "./totals.js";
|
|
4
|
+
function renderCouponForm(options) {
|
|
5
|
+
const { prefix, error, applied } = options;
|
|
6
|
+
const id = `${prefix}-code`;
|
|
7
|
+
const errorId = `${prefix}-error`;
|
|
8
|
+
return html`<form
|
|
9
|
+
class="cart-coupon"
|
|
10
|
+
data-part="coupon"
|
|
11
|
+
@submit=${(event) => {
|
|
12
|
+
event.preventDefault();
|
|
13
|
+
options.onSubmit(event.target);
|
|
14
|
+
}}
|
|
15
|
+
>
|
|
16
|
+
<label for=${id}>${t("cart.coupon")}</label>
|
|
17
|
+
<div class="cart-coupon__field">
|
|
18
|
+
<input
|
|
19
|
+
class="input"
|
|
20
|
+
id=${id}
|
|
21
|
+
name="coupon_code"
|
|
22
|
+
autocomplete="off"
|
|
23
|
+
data-test="coupon-input"
|
|
24
|
+
aria-invalid=${error ? "true" : nothing}
|
|
25
|
+
aria-describedby=${error ? errorId : nothing}
|
|
26
|
+
/>
|
|
27
|
+
<button type="submit" class="button button--small" data-test="coupon-apply">
|
|
28
|
+
${t("cart.applyCoupon")}
|
|
29
|
+
</button>
|
|
30
|
+
</div>
|
|
31
|
+
<p class="field-error" id=${errorId} data-part="coupon-error" ?hidden=${!error}>${error ?? ""}</p>
|
|
32
|
+
${applied ? html`<p class="cart-coupon__applied" data-test="coupon-applied">
|
|
33
|
+
${withStrong("cart.couponApplied", "code", applied)}
|
|
34
|
+
</p>` : nothing}
|
|
35
|
+
</form>`;
|
|
36
|
+
}
|
|
37
|
+
function couponCode(form) {
|
|
38
|
+
const input = form.querySelector('[name="coupon_code"]');
|
|
39
|
+
const code = (input?.value ?? "").trim();
|
|
40
|
+
if (code === "") input?.focus();
|
|
41
|
+
return { input, code };
|
|
42
|
+
}
|
|
43
|
+
export {
|
|
44
|
+
couponCode,
|
|
45
|
+
renderCouponForm
|
|
46
|
+
};
|
|
47
|
+
//# sourceMappingURL=coupon.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"coupon.js","sources":["../../../src/elements/shared/coupon.ts"],"sourcesContent":["import { html, nothing, type TemplateResult } from 'lit'\nimport { t } from '../../core/i18n'\nimport { withStrong } from './totals'\n\n/**\n * The coupon form the cart and the checkout summary share (`form.cart-coupon`, base's markup and data-test\n * attributes): a code field with its apply button, the refusal under it, and the code applied so far.\n */\nexport interface CouponFormOptions {\n /** Unique on the page: the field is `<prefix>-code`, its error `<prefix>-error` */\n prefix: string\n /** Why the last code was refused, shown under the field */\n error: string | null\n /** The code the cart has, if any */\n applied: string | null | undefined\n onSubmit: (form: HTMLFormElement) => void\n}\n\nexport function renderCouponForm(options: CouponFormOptions): TemplateResult {\n const { prefix, error, applied } = options\n const id = `${prefix}-code`\n const errorId = `${prefix}-error`\n return html`<form\n class=\"cart-coupon\"\n data-part=\"coupon\"\n @submit=${(event: Event) => {\n event.preventDefault()\n options.onSubmit(event.target as HTMLFormElement)\n }}\n >\n <label for=${id}>${t('cart.coupon')}</label>\n <div class=\"cart-coupon__field\">\n <input\n class=\"input\"\n id=${id}\n name=\"coupon_code\"\n autocomplete=\"off\"\n data-test=\"coupon-input\"\n aria-invalid=${error ? 'true' : nothing}\n aria-describedby=${error ? errorId : nothing}\n />\n <button type=\"submit\" class=\"button button--small\" data-test=\"coupon-apply\">\n ${t('cart.applyCoupon')}\n </button>\n </div>\n <p class=\"field-error\" id=${errorId} data-part=\"coupon-error\" ?hidden=${!error}>${error ?? ''}</p>\n ${\n applied\n ? html`<p class=\"cart-coupon__applied\" data-test=\"coupon-applied\">\n ${withStrong('cart.couponApplied', 'code', applied)}\n </p>`\n : nothing\n }\n </form>`\n}\n\n/** The code typed in a coupon form, trimmed; empty focuses the field. */\nexport function couponCode(form: HTMLFormElement): { input: HTMLInputElement | null; code: string } {\n const input = form.querySelector<HTMLInputElement>('[name=\"coupon_code\"]')\n const code = (input?.value ?? '').trim()\n if (code === '') input?.focus()\n return { input, code }\n}\n"],"names":[],"mappings":";;;AAkBO,SAAS,iBAAiB,SAA4C;AAC3E,QAAM,EAAE,QAAQ,OAAO,QAAA,IAAY;AACnC,QAAM,KAAK,GAAG,MAAM;AACpB,QAAM,UAAU,GAAG,MAAM;AACzB,SAAO;AAAA;AAAA;AAAA,cAGK,CAAC,UAAiB;AAC1B,UAAM,eAAA;AACN,YAAQ,SAAS,MAAM,MAAyB;AAAA,EAClD,CAAC;AAAA;AAAA,iBAEY,EAAE,IAAI,EAAE,aAAa,CAAC;AAAA;AAAA;AAAA;AAAA,aAI1B,EAAE;AAAA;AAAA;AAAA;AAAA,uBAIQ,QAAQ,SAAS,OAAO;AAAA,2BACpB,QAAQ,UAAU,OAAO;AAAA;AAAA;AAAA,UAG1C,EAAE,kBAAkB,CAAC;AAAA;AAAA;AAAA,gCAGC,OAAO,qCAAqC,CAAC,KAAK,IAAI,SAAS,EAAE;AAAA,MAE3F,UACI;AAAA,cACI,WAAW,sBAAsB,QAAQ,OAAO,CAAC;AAAA,kBAErD,OACN;AAAA;AAEJ;AAGO,SAAS,WAAW,MAAyE;AAClG,QAAM,QAAQ,KAAK,cAAgC,sBAAsB;AACzE,QAAM,QAAQ,OAAO,SAAS,IAAI,KAAA;AAClC,MAAI,SAAS,GAAI,QAAO,MAAA;AACxB,SAAO,EAAE,OAAO,KAAA;AAClB;"}
|