@thorprovider/storefront 0.6.3 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -2
- package/assets/templates/AGENTS.md +14 -2
- package/assets/templates/app/app/[[...slug]]/page.tsx +9 -2
- package/assets/templates/app/lib/__STOREFRONT__/account-address.ts +129 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-lifecycle.client.tsx +2 -2
- package/assets/templates/app/lib/__STOREFRONT__/account-private.core.ts +143 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-profile.ts +220 -0
- package/assets/templates/app/lib/__STOREFRONT__/actions.ts +1234 -75
- package/assets/templates/app/lib/__STOREFRONT__/addresses-port.ts +107 -0
- package/assets/templates/app/lib/__STOREFRONT__/checkout-shipping.core.ts +37 -0
- package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +460 -35
- package/assets/templates/app/lib/__STOREFRONT__/confirmation.core.ts +240 -0
- package/assets/templates/app/lib/__STOREFRONT__/customer-profile-port.ts +103 -0
- package/assets/templates/app/lib/__STOREFRONT__/order-detail-port.ts +26 -0
- package/assets/templates/app/lib/__STOREFRONT__/orders-port.ts +30 -0
- package/assets/templates/app/lib/__STOREFRONT__/ports.ts +18 -0
- package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.client.tsx +4 -4
- package/assets/templates/app/lib/__STOREFRONT__/session.ts +24 -6
- package/assets/templates/app/lib/__STOREFRONT__/state.core.ts +28 -1
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/address-book-advanced.client.tsx +29 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.client.tsx +19 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.tsx +16 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/customer-profile.client.tsx +27 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/index.ts +5 -1
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/marketplace-product-card.client.tsx +19 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/marketplace-product-card.tsx +16 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.client.tsx +19 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.tsx +16 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.address-book-advanced.ts +437 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.checkout-commerce-v1.ts +398 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.customer-profile.ts +138 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.marketplace-product-card.ts +67 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.mega-menu-universal.ts +76 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.universal-banner.ts +217 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.client.tsx +24 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.tsx +16 -0
- package/assets/templates/features/checkout/handlers.ts +348 -33
- package/assets/templates/features/checkout/state.ts +79 -3
- package/assets/templates/features/customer-addresses/handlers.ts +11 -0
- package/assets/templates/features/customer-addresses/state.ts +33 -0
- package/assets/templates/features/customer-auth/state.ts +10 -0
- package/assets/templates/features/customer-profile/handlers.ts +11 -0
- package/assets/templates/features/customer-profile/state.ts +18 -0
- package/assets/templates/views/account/address-book-advanced.defaults.ts +534 -0
- package/assets/templates/views/account/assembly/assembly.json +41 -0
- package/assets/templates/views/account/assembly/index.skeleton.tsx +229 -0
- package/assets/templates/views/account/assembly/registry.skeleton.tsx +1116 -0
- package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/binding.json +5 -0
- package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/catalog.part +4 -0
- package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/element.part +5 -0
- package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/registry.part +1 -0
- package/assets/templates/views/account/assembly/slots/addresses/cards/catalog.part +5 -0
- package/assets/templates/views/account/assembly/slots/addresses/cards/element.part +10 -0
- package/assets/templates/views/account/assembly/slots/addresses/cards/registry.part +1 -0
- package/assets/templates/views/account/assembly/slots/boot/AccountBoot/catalog.part +5 -0
- package/assets/templates/views/account/assembly/slots/boot/AccountBoot/element.part +5 -0
- package/assets/templates/views/account/assembly/slots/boot/AccountBoot/registry.part +1 -0
- package/assets/templates/views/account/assembly/slots/login/card/catalog.part +4 -0
- package/assets/templates/views/account/assembly/slots/login/card/element.part +13 -0
- package/assets/templates/views/account/assembly/slots/login/card/registry.part +1 -0
- package/assets/templates/views/account/assembly/slots/orders/OrderHistory/catalog.part +5 -0
- package/assets/templates/views/account/assembly/slots/orders/OrderHistory/element.part +5 -0
- package/assets/templates/views/account/assembly/slots/orders/OrderHistory/registry.part +2 -0
- package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/binding.json +5 -0
- package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/catalog.part +5 -0
- package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/element.part +5 -0
- package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/registry.part +1 -0
- package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/binding.json +5 -0
- package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/catalog.part +4 -0
- package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/element.part +5 -0
- package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/registry.part +1 -0
- package/assets/templates/views/account/assembly/slots/profile/form/catalog.part +5 -0
- package/assets/templates/views/account/assembly/slots/profile/form/element.part +10 -0
- package/assets/templates/views/account/assembly/slots/profile/form/registry.part +1 -0
- package/assets/templates/views/account/assembly/slots/register/SignUpPage1/catalog.part +4 -0
- package/assets/templates/views/account/assembly/slots/register/SignUpPage1/element.part +13 -0
- package/assets/templates/views/account/assembly/slots/register/SignUpPage1/registry.part +1 -0
- package/assets/templates/views/account/assembly/slots/summary/stack/catalog.part +5 -0
- package/assets/templates/views/account/assembly/slots/summary/stack/element.part +5 -0
- package/assets/templates/views/account/assembly/slots/summary/stack/registry.part +1 -0
- package/assets/templates/views/account/assembly/slots/summary/tabs/catalog.part +5 -0
- package/assets/templates/views/account/assembly/slots/summary/tabs/element.part +5 -0
- package/assets/templates/views/account/assembly/slots/summary/tabs/registry.part +1 -0
- package/assets/templates/views/account/content.ts +326 -0
- package/assets/templates/views/account/customer-profile.defaults.ts +136 -0
- package/assets/templates/views/account/index.tsx +218 -35
- package/assets/templates/views/account/order-detail.client.tsx +35 -0
- package/assets/templates/views/account/order-detail.defaults.ts +457 -0
- package/assets/templates/views/account/orders-advanced.client.tsx +166 -0
- package/assets/templates/views/account/orders-advanced.defaults.ts +230 -0
- package/assets/templates/views/account/registry.tsx +944 -369
- package/assets/templates/views/account/schema.ts +50 -0
- package/assets/templates/views/account/sections-data.ts +2 -0
- package/assets/templates/views/cart/content.ts +1 -0
- package/assets/templates/views/category/assembly/index.skeleton.tsx +1 -0
- package/assets/templates/views/category/assembly/slots/filter/CategoryListing/element.part +1 -0
- package/assets/templates/views/category/content.ts +2 -0
- package/assets/templates/views/category/index.tsx +2 -0
- package/assets/templates/views/category/sections-data.ts +2 -0
- package/assets/templates/views/checkout/checkout-commerce-hosted.tsx +1089 -0
- package/assets/templates/views/checkout/content.ts +114 -2
- package/assets/templates/views/checkout/index.tsx +7 -1
- package/assets/templates/views/checkout/props.ts +70 -22
- package/assets/templates/views/checkout/registry.tsx +400 -71
- package/assets/templates/views/checkout/schema.ts +260 -9
- package/assets/templates/views/home/assembly/assembly.json +28 -0
- package/assets/templates/views/home/assembly/index.skeleton.tsx +1 -0
- package/assets/templates/views/home/content.ts +2 -0
- package/assets/templates/views/home/index.tsx +1 -0
- package/assets/templates/views/home/sections-data.ts +2 -0
- package/assets/templates/views/product/content.ts +1 -0
- package/assets/templates/views/static/content.ts +1 -0
- package/bin/storefront.js +343 -13
- package/package.json +2 -1
- package/recipes/adapter-surface.json +158 -0
- package/recipes/archetypes.json +38 -3
- package/recipes/catalog.json +138 -1
- package/recipes/feature.schema.json +9 -0
- package/recipes/features.json +72 -1
- package/recipes/manifest.schema.json +5 -0
- package/recipes/recipe.schema.json +14 -2
- package/recipes/recipes.json +35 -5
- package/recipes/section.schema.json +112 -0
- package/recipes/sections.json +289 -3
- package/recipes/validate.mjs +83 -1
- package/scripts/adapter-surface.mjs +41 -0
- package/scripts/agent-blocks.mjs +700 -0
- package/scripts/block-validator.mjs +45 -0
- package/scripts/candidate.mjs +5 -4
- package/scripts/composers.mjs +7 -2
- package/scripts/default-sections.mjs +78 -0
- package/scripts/file-classes.mjs +15 -0
- package/scripts/generate-adapter-surface.mjs +148 -0
- package/scripts/operations.mjs +100 -0
- package/scripts/reconcile.mjs +67 -39
- package/scripts/section-configure.mjs +316 -0
- package/scripts/sync-assets.mjs +1 -0
- package/scripts/view-assembly.mjs +101 -14
- package/skills/sf-feature/SKILL.md +19 -0
- package/skills/sf-view-gen/SKILL.md +79 -7
- package/skills/sf-view-gen/assets/recipes/archetypes.json +38 -3
- package/skills/sf-view-gen/assets/recipes/catalog.json +138 -1
- package/skills/sf-view-gen/assets/recipes/features.json +72 -1
- package/skills/sf-view-gen/assets/recipes/recipes.json +35 -5
- package/skills/sf-view-gen/assets/recipes/section.schema.json +112 -0
- package/skills/sf-view-gen/assets/recipes/sections.json +289 -3
- package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.client.tsx +19 -0
- package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.tsx +16 -0
- package/skills/sf-view-gen/assets/templates/views/sections/marketplace-product-card.client.tsx +19 -0
- package/skills/sf-view-gen/assets/templates/views/sections/marketplace-product-card.tsx +16 -0
- package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.client.tsx +19 -0
- package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.tsx +16 -0
- package/skills/sf-view-gen/assets/templates/views/sections/schema.checkout-commerce-v1.ts +398 -0
- package/skills/sf-view-gen/assets/templates/views/sections/schema.marketplace-product-card.ts +67 -0
- package/skills/sf-view-gen/assets/templates/views/sections/schema.mega-menu-universal.ts +76 -0
- package/skills/sf-view-gen/assets/templates/views/sections/schema.universal-banner.ts +217 -0
- package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.client.tsx +24 -0
- package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.tsx +16 -0
- package/skills/sf-view-gen/scripts/validate.mjs +83 -1
- package/skills/storefront-workflow/SKILL.md +5 -0
- package/skills/storefront-workflow/references/mobile-responsiveness.md +1 -1
|
@@ -0,0 +1,1089 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { CheckoutCommerceV1Hosted } from '@thorprovider/blocks';
|
|
4
|
+
import type {
|
|
5
|
+
CheckoutAddressValues,
|
|
6
|
+
CheckoutLocationOptions,
|
|
7
|
+
CheckoutReadState,
|
|
8
|
+
CheckoutShippingGroup,
|
|
9
|
+
} from '@thorprovider/blocks';
|
|
10
|
+
import type { CheckoutCommerceV1HostData } from '@thorprovider/blocks';
|
|
11
|
+
import type { Money, PaymentMethod } from '@thorprovider/types';
|
|
12
|
+
import { Button } from '@thorprovider/blocks/ui/button';
|
|
13
|
+
import { useRef, useState } from 'react';
|
|
14
|
+
import { useStateStore } from '@json-render/react';
|
|
15
|
+
import { checkoutPropsSchema, type CheckoutProps } from './schema';
|
|
16
|
+
|
|
17
|
+
type CheckoutViewModel = CheckoutCommerceV1HostData;
|
|
18
|
+
type CheckoutAddress = CheckoutViewModel['addresses'][number];
|
|
19
|
+
type CheckoutCopy = CheckoutViewModel['labels'];
|
|
20
|
+
type CheckoutFieldError = NonNullable<CheckoutViewModel['errors']>[number];
|
|
21
|
+
type CheckoutGroup = CheckoutViewModel['groups'][number];
|
|
22
|
+
type CheckoutGroupItem = CheckoutGroup['lines'][number];
|
|
23
|
+
type CheckoutLine = CheckoutViewModel['lines'][number];
|
|
24
|
+
type CheckoutPaymentOption = CheckoutViewModel['paymentMethods'][number];
|
|
25
|
+
type CheckoutPickupPoint = CheckoutGroup['pickupPoints'][number];
|
|
26
|
+
type CheckoutShippingOption = CheckoutGroup['shippingOptions'][number];
|
|
27
|
+
type CheckoutLocationLevel = 'countries' | 'provinces' | 'cities';
|
|
28
|
+
type CheckoutGroupMode = 'shipping' | 'pickup';
|
|
29
|
+
type CheckoutGroupModeOverrides = Record<string, CheckoutGroupMode>;
|
|
30
|
+
type CheckoutLocationOption = CheckoutLocationOptions['countries'][number];
|
|
31
|
+
type HostedLocationRequest = {
|
|
32
|
+
kind: 'shipping';
|
|
33
|
+
level: 'provinces' | 'cities';
|
|
34
|
+
countryCode: string;
|
|
35
|
+
provinceCode?: string;
|
|
36
|
+
};
|
|
37
|
+
type HostedLocationResult =
|
|
38
|
+
| { ok: true; options: CheckoutLocationOption[] }
|
|
39
|
+
| { ok: false; error: string };
|
|
40
|
+
type HostedLocationLoader = (input: HostedLocationRequest) => Promise<HostedLocationResult>;
|
|
41
|
+
type CheckoutLocationDraft = { countryCode?: string; provinceCode?: string };
|
|
42
|
+
type SetCheckoutLocationDraft = (draft: CheckoutLocationDraft) => void;
|
|
43
|
+
type CheckoutLocationRequestTokens = { provinces: number; cities: number };
|
|
44
|
+
const missingLocationLoader: HostedLocationLoader = async () => ({
|
|
45
|
+
ok: false,
|
|
46
|
+
error: 'Location options could not be loaded.',
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
export type HostedCheckoutState = {
|
|
50
|
+
cartQuantity: number;
|
|
51
|
+
cartCompleted: boolean;
|
|
52
|
+
cartPending: boolean;
|
|
53
|
+
cartError: string | null;
|
|
54
|
+
checkoutPending: boolean;
|
|
55
|
+
checkoutError: string | null;
|
|
56
|
+
checkoutErrorKind: 'error' | 'cart-error' | 'unresolved' | null;
|
|
57
|
+
orderStatus: 'idle' | 'pending' | 'error' | 'unresolved' | 'complete';
|
|
58
|
+
checkoutShippingState: CheckoutReadState;
|
|
59
|
+
checkoutPaymentState: CheckoutReadState;
|
|
60
|
+
checkoutFieldErrors?: Record<string, unknown>;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
type HostedSetter = (path: string, value: unknown) => void;
|
|
64
|
+
type HostedEmit = (event: string) => void;
|
|
65
|
+
|
|
66
|
+
const EMPTY_LOCATIONS: CheckoutLocationOptions = { countries: [], provinces: [], cities: [] };
|
|
67
|
+
const CURRENT_SHIPPING_ADDRESS_ID = 'checkout-current-shipping-address';
|
|
68
|
+
const CURRENT_BILLING_ADDRESS_ID = 'checkout-current-billing-address';
|
|
69
|
+
|
|
70
|
+
/** Convert canonical decimal Money to the presentational view's integer cents. */
|
|
71
|
+
export function moneyToDisplayCents(value: Money | null | undefined): number | undefined {
|
|
72
|
+
if (!value || !value.currencyCode.trim()) return undefined;
|
|
73
|
+
const match = /^(-?)(\d+)(?:\.(\d+))?$/.exec(value.amount.trim());
|
|
74
|
+
if (!match) return undefined;
|
|
75
|
+
const [, sign, whole, fraction = ''] = match;
|
|
76
|
+
let cents = BigInt(whole) * BigInt(100) + BigInt((fraction + '00').slice(0, 2));
|
|
77
|
+
if (fraction.length > 2 && fraction[2]! >= '5') cents += BigInt(1);
|
|
78
|
+
if (sign === '-') cents = -cents;
|
|
79
|
+
if (cents > BigInt(Number.MAX_SAFE_INTEGER) || cents < BigInt(Number.MIN_SAFE_INTEGER)) {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
return Number(cents);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function joinName(firstName: string | undefined, lastName: string | undefined): string {
|
|
86
|
+
return [firstName, lastName]
|
|
87
|
+
.map((part) => part?.trim())
|
|
88
|
+
.filter((part): part is string => Boolean(part))
|
|
89
|
+
.join(' ');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function splitName(value: string): { firstName: string; lastName: string } {
|
|
93
|
+
const [firstName = '', ...rest] = value.trim().split(/\s+/).filter(Boolean);
|
|
94
|
+
return { firstName, lastName: rest.join(' ') };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function optionalText(value: string | undefined): string | undefined {
|
|
98
|
+
const trimmed = value?.trim();
|
|
99
|
+
return trimmed || undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function toAddress(
|
|
103
|
+
address: CheckoutAddressValues,
|
|
104
|
+
id: string,
|
|
105
|
+
label: string | undefined,
|
|
106
|
+
isDefault: boolean,
|
|
107
|
+
): CheckoutAddress {
|
|
108
|
+
const line2 = optionalText(address.address2);
|
|
109
|
+
const company = optionalText(address.company);
|
|
110
|
+
const province = optionalText(address.province);
|
|
111
|
+
const postalCode = optionalText(address.postalCode);
|
|
112
|
+
const phone = optionalText(address.phone);
|
|
113
|
+
const countryCode = optionalText(address.countryCode);
|
|
114
|
+
return {
|
|
115
|
+
id,
|
|
116
|
+
label:
|
|
117
|
+
optionalText(label) ||
|
|
118
|
+
[address.city, address.province].filter(Boolean).join(', ') ||
|
|
119
|
+
address.address1,
|
|
120
|
+
recipient: joinName(address.firstName, address.lastName),
|
|
121
|
+
line1: address.address1,
|
|
122
|
+
...(line2 ? { line2 } : {}),
|
|
123
|
+
...(company ? { company } : {}),
|
|
124
|
+
city: address.city,
|
|
125
|
+
...(province ? { province } : {}),
|
|
126
|
+
...(countryCode ? { countryCode } : {}),
|
|
127
|
+
...(postalCode ? { postalCode } : {}),
|
|
128
|
+
...(phone ? { phone } : {}),
|
|
129
|
+
isDefault,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function sameAddress(left: CheckoutAddressValues, right: CheckoutAddressValues): boolean {
|
|
134
|
+
return (
|
|
135
|
+
left.firstName === right.firstName &&
|
|
136
|
+
left.lastName === right.lastName &&
|
|
137
|
+
left.address1 === right.address1 &&
|
|
138
|
+
left.address2 === right.address2 &&
|
|
139
|
+
left.company === right.company &&
|
|
140
|
+
left.city === right.city &&
|
|
141
|
+
left.province === right.province &&
|
|
142
|
+
left.postalCode === right.postalCode &&
|
|
143
|
+
left.countryCode === right.countryCode &&
|
|
144
|
+
left.phone === right.phone
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function uniqueAddressId(base: string, addresses: CheckoutAddress[]): string {
|
|
149
|
+
const ids = new Set(addresses.map((address) => address.id));
|
|
150
|
+
let candidate = base;
|
|
151
|
+
let suffix = 1;
|
|
152
|
+
while (ids.has(candidate)) candidate = `${base}-${suffix++}`;
|
|
153
|
+
return candidate;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function displayAddresses(props: CheckoutProps): {
|
|
157
|
+
addresses: CheckoutAddress[];
|
|
158
|
+
selectedShippingAddressId?: string;
|
|
159
|
+
billingAddressId?: string;
|
|
160
|
+
} {
|
|
161
|
+
const saved = (props.savedAddresses ?? []).map((entry) =>
|
|
162
|
+
toAddress(entry.address, entry.id, entry.label, Boolean(entry.isDefaultShipping)),
|
|
163
|
+
);
|
|
164
|
+
const addresses = [...saved];
|
|
165
|
+
const findSavedId = (value: CheckoutAddressValues) =>
|
|
166
|
+
(props.savedAddresses ?? []).find((entry) => sameAddress(entry.address, value))?.id;
|
|
167
|
+
|
|
168
|
+
let selectedShippingAddressId = findSavedId(props.shippingAddress);
|
|
169
|
+
if (!selectedShippingAddressId && props.shippingAddress.address1.trim()) {
|
|
170
|
+
selectedShippingAddressId = uniqueAddressId(CURRENT_SHIPPING_ADDRESS_ID, addresses);
|
|
171
|
+
addresses.push(toAddress(props.shippingAddress, selectedShippingAddressId, undefined, false));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
let billingAddressId = findSavedId(props.billingAddress ?? props.shippingAddress);
|
|
175
|
+
if (!props.sameAsShipping && props.billingAddress?.address1.trim() && !billingAddressId) {
|
|
176
|
+
billingAddressId = uniqueAddressId(CURRENT_BILLING_ADDRESS_ID, addresses);
|
|
177
|
+
addresses.push(toAddress(props.billingAddress, billingAddressId, undefined, false));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return { addresses, selectedShippingAddressId, billingAddressId };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function toLocationOptions(options: CheckoutLocationOptions | undefined) {
|
|
184
|
+
const source = options ?? EMPTY_LOCATIONS;
|
|
185
|
+
const states: NonNullable<CheckoutViewModel['locationOptions']>['states'] = {};
|
|
186
|
+
const errors: NonNullable<CheckoutViewModel['locationOptions']>['errors'] = {};
|
|
187
|
+
|
|
188
|
+
for (const level of ['countries', 'provinces', 'cities'] as const) {
|
|
189
|
+
const state = source[`${level}State`];
|
|
190
|
+
const error = source[`${level}Error`];
|
|
191
|
+
if (state) states[level] = state;
|
|
192
|
+
if (error) errors[level] = error;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
return {
|
|
196
|
+
countries: source.countries,
|
|
197
|
+
provinces: source.provinces,
|
|
198
|
+
cities: source.cities,
|
|
199
|
+
...(Object.keys(states).length ? { states } : {}),
|
|
200
|
+
...(Object.keys(errors).length ? { errors } : {}),
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function toFieldErrors(value: Record<string, unknown> | undefined): CheckoutFieldError[] {
|
|
205
|
+
if (!value) return [];
|
|
206
|
+
const result: CheckoutFieldError[] = [];
|
|
207
|
+
const contactAliases: Record<string, string> = {
|
|
208
|
+
email: 'contactEmail',
|
|
209
|
+
firstName: 'contactName',
|
|
210
|
+
lastName: 'contactName',
|
|
211
|
+
phone: 'contactPhone',
|
|
212
|
+
};
|
|
213
|
+
const addressAliases: Record<string, string> = {
|
|
214
|
+
address1: 'line1',
|
|
215
|
+
};
|
|
216
|
+
const rootAliases: Record<string, string> = {
|
|
217
|
+
paymentMethod: 'paymentMethod',
|
|
218
|
+
promoCode: 'promoCode',
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
const append = (path: string, errors: unknown) => {
|
|
222
|
+
if (!Array.isArray(errors)) return;
|
|
223
|
+
for (const error of errors) {
|
|
224
|
+
if (error && typeof error === 'object' && 'message' in error) {
|
|
225
|
+
const message = (error as { message?: unknown }).message;
|
|
226
|
+
if (typeof message === 'string') result.push({ path, message });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
for (const [group, fields] of Object.entries(value)) {
|
|
232
|
+
if (fields && typeof fields === 'object' && !Array.isArray(fields)) {
|
|
233
|
+
for (const [field, errors] of Object.entries(fields as Record<string, unknown>)) {
|
|
234
|
+
const path =
|
|
235
|
+
group === 'contact' ? contactAliases[field] ?? field : addressAliases[field] ?? field;
|
|
236
|
+
append(path, errors);
|
|
237
|
+
}
|
|
238
|
+
} else {
|
|
239
|
+
append(rootAliases[group] ?? group, fields);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return result;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function copyFor(props: CheckoutProps): CheckoutCopy {
|
|
246
|
+
const source = props.labels ?? {};
|
|
247
|
+
const label = (key: string, fallback: string) => source[key] ?? fallback;
|
|
248
|
+
return {
|
|
249
|
+
title: optionalText(props.title) ?? 'Finalizar compra',
|
|
250
|
+
loadingLabel: label('deliveryLoadingLabel', 'Cargando checkout…'),
|
|
251
|
+
sessionLoading: 'Cargando la información de tu cuenta…',
|
|
252
|
+
sessionError: 'No se pudo cargar la información de tu cuenta.',
|
|
253
|
+
contactName: label('firstNameLabel', 'Nombre y apellidos'),
|
|
254
|
+
contactEmail: label('emailLabel', 'Email'),
|
|
255
|
+
contactPhone: label('phoneLabel', 'Teléfono'),
|
|
256
|
+
contactNameMissing: 'Ingresa tu nombre.',
|
|
257
|
+
contactMissing: 'Ingresa un email válido.',
|
|
258
|
+
contactPhoneMissing: 'Ingresa tu teléfono.',
|
|
259
|
+
buyerTitleGuest: 'Datos de contacto',
|
|
260
|
+
buyerTitleAuth: 'Tu cuenta',
|
|
261
|
+
buyerContinue: label('continueLabel', 'Continuar'),
|
|
262
|
+
buyerSavePhone: 'Guardar teléfono',
|
|
263
|
+
buyerPhoneHint: 'Usaremos este teléfono para coordinar la entrega.',
|
|
264
|
+
contactEdit: 'Editar',
|
|
265
|
+
summaryTitle: label('orderSummaryTitle', 'Resumen del pedido'),
|
|
266
|
+
summaryItemOne: '1 artículo',
|
|
267
|
+
summaryItems: '{count} artículos',
|
|
268
|
+
purchaseBreakdown: '{items} · {deliveries}',
|
|
269
|
+
deliveriesOne: '1 entrega',
|
|
270
|
+
deliveriesMany: '{count} entregas',
|
|
271
|
+
addressTitle: label('shippingHeading', 'Dirección de envío'),
|
|
272
|
+
addressDelivery: label('shippingHeading', 'Dirección de envío'),
|
|
273
|
+
addressSelectTitle: label('savedAddressesLabel', 'Direcciones guardadas'),
|
|
274
|
+
addressCancel: label('cancelAddressLabel', 'Cancelar'),
|
|
275
|
+
addressDefaultBadge: label('defaultAddressLabel', 'Predeterminada'),
|
|
276
|
+
addressRequired: 'Este campo es obligatorio.',
|
|
277
|
+
addressFormTitle: label('newAddressLabel', 'Nueva dirección'),
|
|
278
|
+
addressFirstName: label('firstNameLabel', 'Nombre'),
|
|
279
|
+
addressLastName: label('lastNameLabel', 'Apellidos'),
|
|
280
|
+
addressPhone: label('phoneLabel', 'Teléfono'),
|
|
281
|
+
addressCountry: label('countryLabel', 'País'),
|
|
282
|
+
addressProvince: label('stateLabel', 'Provincia'),
|
|
283
|
+
addressCity: label('cityLabel', 'Ciudad'),
|
|
284
|
+
addressLine1: label('addressLabel', 'Dirección'),
|
|
285
|
+
addressLine2: label('address2Label', 'Complemento'),
|
|
286
|
+
addressPostal: label('zipCodeLabel', 'Código postal'),
|
|
287
|
+
addressSelectPlaceholder: label('countryPlaceholder', 'Selecciona una opción'),
|
|
288
|
+
addressCountryPlaceholder: label('countryPlaceholder', 'Selecciona un país'),
|
|
289
|
+
addressProvincePlaceholder: label('provincePlaceholder', 'Selecciona una provincia o estado'),
|
|
290
|
+
addressCityPlaceholder: label('cityPlaceholder', 'Selecciona una ciudad'),
|
|
291
|
+
addressNewLabel: 'Dirección de {city}',
|
|
292
|
+
addressTemporary: 'Dirección de entrega',
|
|
293
|
+
addressSaveAccount: label('saveAddressLabel', 'Guardar en mis direcciones'),
|
|
294
|
+
addressSavePending: label('savingAddressLabel', 'Guardando dirección…'),
|
|
295
|
+
addressUseOnce: 'Usar solo para este pedido.',
|
|
296
|
+
addressSave: label('saveAddressLabel', 'Usar esta dirección'),
|
|
297
|
+
addressNew: label('newAddressLabel', 'Añadir dirección'),
|
|
298
|
+
groupsTitle: label('shippingMethodLegend', 'Opciones de entrega'),
|
|
299
|
+
groupNeedsAddress: 'Añade una dirección de entrega.',
|
|
300
|
+
groupAddAddress: label('addAddressLabel', 'Añadir dirección'),
|
|
301
|
+
groupDelivery: 'Entrega {n}',
|
|
302
|
+
groupPickup: 'Recogida {n}',
|
|
303
|
+
modeShipping: 'Envío',
|
|
304
|
+
modePickup: 'Recogida',
|
|
305
|
+
groupFree: 'Gratis',
|
|
306
|
+
groupSpecial: 'Especial',
|
|
307
|
+
groupRatePending: label('deliveryLoadingLabel', 'Cargando tarifas…'),
|
|
308
|
+
groupRateError: label('deliveryErrorLabel', 'No se pudieron cargar las tarifas.'),
|
|
309
|
+
rateError: label('deliveryErrorLabel', 'No se pudieron cargar las tarifas.'),
|
|
310
|
+
groupNoCoverage: label('noShippingOptionsLabel', 'No hay opciones de entrega.'),
|
|
311
|
+
...(source.deliveryUnavailableLabel
|
|
312
|
+
? { groupNoCoverageHint: source.deliveryUnavailableLabel }
|
|
313
|
+
: {}),
|
|
314
|
+
groupShippingOptions: label('shippingMethodLegend', 'Opciones de envío'),
|
|
315
|
+
groupPickupPoints: 'Puntos de recogida',
|
|
316
|
+
groupPickupAvailable: 'Ver recogida',
|
|
317
|
+
groupChangeAddress: 'Cambiar dirección',
|
|
318
|
+
modeTitle: 'Método de entrega',
|
|
319
|
+
changeAction: label('changeActionLabel', 'Cambiar'),
|
|
320
|
+
done: 'Listo',
|
|
321
|
+
groupNoAddress: 'Añade una dirección para ver la entrega disponible.',
|
|
322
|
+
groupRetryRate: label('retryLabel', 'Reintentar'),
|
|
323
|
+
overviewPending: label('totalsPendingLabel', 'Actualizando…'),
|
|
324
|
+
pickupOnlyAddress: 'No hace falta una dirección para recoger el pedido.',
|
|
325
|
+
paymentTitle: label('paymentHeading', 'Método de pago'),
|
|
326
|
+
paymentChoose: label('paymentChooseLabel', 'Selecciona un método de pago'),
|
|
327
|
+
paymentSelectAction: label('paymentSelectActionLabel', 'Seleccionar'),
|
|
328
|
+
paymentUnavailable: label('noPaymentMethodsLabel', 'No hay métodos de pago disponibles.'),
|
|
329
|
+
paymentProviderNote: label(
|
|
330
|
+
'paymentDescription',
|
|
331
|
+
'Selecciona un método de pago para continuar.',
|
|
332
|
+
),
|
|
333
|
+
paymentErrorTitle: label('paymentErrorLabel', 'No se pudo cargar el pago.'),
|
|
334
|
+
paymentErrorBody: label('paymentUnavailableLabel', 'El pago no está disponible.'),
|
|
335
|
+
paymentRetry: label('retryLabel', 'Reintentar'),
|
|
336
|
+
interruptionAcknowledgeLabel: label('interruptionAcknowledgeLabel', 'Entendido'),
|
|
337
|
+
interruptionRefreshLabel: label('interruptionRefreshLabel', 'Actualizar'),
|
|
338
|
+
interruptionReturnToCartLabel: label('interruptionReturnToCartLabel', 'Volver al carrito'),
|
|
339
|
+
interruptionRetryLabel: label('interruptionRetryLabel', 'Reintentar'),
|
|
340
|
+
billingTitle: label('billingHeading', 'Dirección de facturación'),
|
|
341
|
+
billingSame: label('billingSameAsShippingLabel', 'Igual que el envío'),
|
|
342
|
+
billingChoose: label('billingHeading', 'Selecciona una dirección de facturación'),
|
|
343
|
+
addressDefaultBadgeLabel: label('defaultAddressLabel', 'Predeterminada'),
|
|
344
|
+
each: label('eachLabel', 'c/u {amount}'),
|
|
345
|
+
subtotal: label('subtotalLabel', 'Subtotal'),
|
|
346
|
+
tax: label('taxLabel', 'Impuestos'),
|
|
347
|
+
shippingCost: label('shippingLabel', 'Envío'),
|
|
348
|
+
pickupCost: 'Recogida',
|
|
349
|
+
total: label('totalLabel', 'Total'),
|
|
350
|
+
totalPending: label('totalsPendingLabel', 'Actualizando totales…'),
|
|
351
|
+
totalPendingNote: label('totalsPendingLabel', 'Estamos actualizando los importes.'),
|
|
352
|
+
totalUnavailable: label('totalsUnavailableLabel', 'Totales no disponibles.'),
|
|
353
|
+
totalPendingLabel: label('totalsPendingLabel', 'Actualizando totales…'),
|
|
354
|
+
totalUnavailableLabel: label('totalsUnavailableLabel', 'Totales no disponibles.'),
|
|
355
|
+
confirm: label('completeOrderLabel', 'Confirmar pedido'),
|
|
356
|
+
confirmationCreating: label('processingLabel', 'Procesando pedido…'),
|
|
357
|
+
confirmationCreatingNote: 'No cierres esta página mientras confirmamos el pedido.',
|
|
358
|
+
confirmNote: label('reviewDescription', 'Revisa los datos antes de confirmar el pedido.'),
|
|
359
|
+
emptyTitle: 'Tu carrito está vacío.',
|
|
360
|
+
emptyBody: 'Añade productos antes de finalizar la compra.',
|
|
361
|
+
emptyCta: label('continueLabel', 'Seguir comprando'),
|
|
362
|
+
footerNote: optionalText(props.description) ?? 'Completa tus datos para recibir tu pedido.',
|
|
363
|
+
retryAction: label('retryLabel', 'Reintentar'),
|
|
364
|
+
orderRetry: source.submitErrorActionLabel ?? label('retryLabel', 'Reintentar'),
|
|
365
|
+
decrease: 'Reducir cantidad de {name}',
|
|
366
|
+
increase: 'Aumentar cantidad de {name}',
|
|
367
|
+
decreaseSymbol: '−',
|
|
368
|
+
increaseSymbol: '+',
|
|
369
|
+
ellipsis: '…',
|
|
370
|
+
lineDiscount: '{label}: {amount}',
|
|
371
|
+
addressLabel: label('addressLabel', 'Dirección'),
|
|
372
|
+
countryLabel: label('countryLabel', 'País'),
|
|
373
|
+
taxLabel: label('taxLabel', 'Impuestos'),
|
|
374
|
+
shippingLabel: label('shippingLabel', 'Envío'),
|
|
375
|
+
subtotalLabel: label('subtotalLabel', 'Subtotal'),
|
|
376
|
+
discountLabel: label('discountLabel', 'Descuento'),
|
|
377
|
+
free: 'Gratis',
|
|
378
|
+
paymentUnavailableLabel: label(
|
|
379
|
+
'paymentUnavailableLabel',
|
|
380
|
+
'No hay métodos de pago disponibles.',
|
|
381
|
+
),
|
|
382
|
+
promoLabel: label('promoCodeLabel', 'Código promocional'),
|
|
383
|
+
promoPlaceholder: label('promoPlaceholder', 'Ingresa el código'),
|
|
384
|
+
promoApply: label('promoApplyLabel', 'Aplicar'),
|
|
385
|
+
promoOpen: label('promoCodeLabel', 'Código promocional'),
|
|
386
|
+
remove: label('removeLabel', 'Quitar'),
|
|
387
|
+
removeNamed: 'Quitar {name}',
|
|
388
|
+
checkSymbol: '✓',
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function toPaymentOption(method: PaymentMethod, props: CheckoutProps): CheckoutPaymentOption {
|
|
393
|
+
const enabled = method.isEnabled && !method.requiresSetup;
|
|
394
|
+
return {
|
|
395
|
+
id: method.id,
|
|
396
|
+
label: method.name,
|
|
397
|
+
...(optionalText(method.description) ? { detail: optionalText(method.description) } : {}),
|
|
398
|
+
kind: method.type,
|
|
399
|
+
enabled,
|
|
400
|
+
disabled: !enabled,
|
|
401
|
+
...(method.requiresSetup
|
|
402
|
+
? { reason: props.labels?.requiresSetupLabel ?? 'Requiere configuración adicional.' }
|
|
403
|
+
: !method.isEnabled
|
|
404
|
+
? { reason: props.labels?.unavailableMethodLabel ?? 'No disponible.' }
|
|
405
|
+
: {}),
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function toLine(
|
|
410
|
+
item: NonNullable<CheckoutProps['orderSummary']>['items'][number],
|
|
411
|
+
groupId?: string,
|
|
412
|
+
): CheckoutLine {
|
|
413
|
+
const quantity = item.quantity;
|
|
414
|
+
const image = optionalText(item.image);
|
|
415
|
+
const variant = optionalText(item.variant);
|
|
416
|
+
return {
|
|
417
|
+
lineId: String(item.id),
|
|
418
|
+
...(groupId ? { groupId } : {}),
|
|
419
|
+
title: item.name,
|
|
420
|
+
...(variant ? { variant } : {}),
|
|
421
|
+
...(image ? { image } : {}),
|
|
422
|
+
removable: false,
|
|
423
|
+
...(moneyToDisplayCents(item.unitPrice) !== undefined
|
|
424
|
+
? { unitCents: moneyToDisplayCents(item.unitPrice) }
|
|
425
|
+
: {}),
|
|
426
|
+
quantity,
|
|
427
|
+
...(moneyToDisplayCents(item.lineTotal) !== undefined
|
|
428
|
+
? { netTotalCents: moneyToDisplayCents(item.lineTotal) }
|
|
429
|
+
: {}),
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function toShippingOption(
|
|
434
|
+
option: NonNullable<CheckoutShippingGroup['options']>[number],
|
|
435
|
+
): CheckoutShippingOption {
|
|
436
|
+
const feeCents = moneyToDisplayCents(option.price);
|
|
437
|
+
const disabledReason = optionalText(option.disabledReason);
|
|
438
|
+
return {
|
|
439
|
+
id: option.id,
|
|
440
|
+
label: option.name,
|
|
441
|
+
...(feeCents !== undefined ? { feeCents } : {}),
|
|
442
|
+
...(optionalText(option.estimatedDays) ? { eta: optionalText(option.estimatedDays) } : {}),
|
|
443
|
+
...(optionalText(option.description) ? { note: optionalText(option.description) } : {}),
|
|
444
|
+
...(option.disabled !== undefined ? { disabled: option.disabled } : {}),
|
|
445
|
+
...(disabledReason ? { disabledReason } : {}),
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function toPickupPoint(
|
|
450
|
+
option: NonNullable<CheckoutShippingGroup['options']>[number],
|
|
451
|
+
): CheckoutPickupPoint {
|
|
452
|
+
const feeCents = moneyToDisplayCents(option.price);
|
|
453
|
+
const disabledReason = optionalText(option.disabledReason);
|
|
454
|
+
return {
|
|
455
|
+
id: option.id,
|
|
456
|
+
label: option.name,
|
|
457
|
+
...(optionalText(option.locationName) ? { address: optionalText(option.locationName) } : {}),
|
|
458
|
+
...(feeCents !== undefined ? { feeCents } : {}),
|
|
459
|
+
...(optionalText(option.description) ? { note: optionalText(option.description) } : {}),
|
|
460
|
+
...(option.disabled !== undefined
|
|
461
|
+
? { disabled: option.disabled, available: !option.disabled }
|
|
462
|
+
: {}),
|
|
463
|
+
...(disabledReason
|
|
464
|
+
? { disabledReason, unavailableReason: disabledReason }
|
|
465
|
+
: {}),
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function toGroupItem(
|
|
470
|
+
line: CheckoutLine,
|
|
471
|
+
groupId: string,
|
|
472
|
+
groupQuantity: number | undefined,
|
|
473
|
+
): CheckoutGroupItem {
|
|
474
|
+
const { quantity: cartQuantity, netTotalCents, ...projection } = line;
|
|
475
|
+
return {
|
|
476
|
+
...projection,
|
|
477
|
+
groupId,
|
|
478
|
+
...(groupQuantity !== undefined ? { quantity: groupQuantity } : {}),
|
|
479
|
+
...(groupQuantity !== undefined &&
|
|
480
|
+
groupQuantity === cartQuantity &&
|
|
481
|
+
netTotalCents !== undefined
|
|
482
|
+
? { netTotalCents }
|
|
483
|
+
: {}),
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function toGroup(
|
|
488
|
+
source: CheckoutShippingGroup,
|
|
489
|
+
lineById: Map<string, CheckoutLine>,
|
|
490
|
+
shippingState: CheckoutReadState,
|
|
491
|
+
modeOverride?: CheckoutGroupMode,
|
|
492
|
+
): CheckoutGroup {
|
|
493
|
+
const shipping = source.options.filter((option) => !option.pickup);
|
|
494
|
+
const pickup = source.options.filter((option) => option.pickup);
|
|
495
|
+
const backendSelected = source.options.find((option) => option.id === source.selectedOptionId);
|
|
496
|
+
const usableModeOverride =
|
|
497
|
+
modeOverride === 'pickup' && pickup.length > 0
|
|
498
|
+
? modeOverride
|
|
499
|
+
: modeOverride === 'shipping' && shipping.length > 0
|
|
500
|
+
? modeOverride
|
|
501
|
+
: undefined;
|
|
502
|
+
const mode =
|
|
503
|
+
usableModeOverride ??
|
|
504
|
+
(backendSelected
|
|
505
|
+
? backendSelected.pickup
|
|
506
|
+
? 'pickup'
|
|
507
|
+
: 'shipping'
|
|
508
|
+
: shipping.length === 0 && pickup.length > 0
|
|
509
|
+
? 'pickup'
|
|
510
|
+
: 'shipping');
|
|
511
|
+
const selected =
|
|
512
|
+
backendSelected && Boolean(backendSelected.pickup) === (mode === 'pickup')
|
|
513
|
+
? backendSelected
|
|
514
|
+
: undefined;
|
|
515
|
+
const items = (source.items ?? []).flatMap((item) => {
|
|
516
|
+
const line = lineById.get(item.lineId);
|
|
517
|
+
return line ? [toGroupItem(line, source.id, item.quantity)] : [];
|
|
518
|
+
});
|
|
519
|
+
const groupRateState =
|
|
520
|
+
shippingState === 'pending'
|
|
521
|
+
? 'pending'
|
|
522
|
+
: shippingState === 'error' || shippingState === 'unavailable'
|
|
523
|
+
? 'error'
|
|
524
|
+
: source.options.length > 0
|
|
525
|
+
? 'ready'
|
|
526
|
+
: 'none';
|
|
527
|
+
const selectedAvailable = Boolean(selected && !selected.disabled);
|
|
528
|
+
const selectedViewOption = selected && !selected.pickup ? toShippingOption(selected) : undefined;
|
|
529
|
+
const selectedPickup = selected?.pickup ? toPickupPoint(selected) : undefined;
|
|
530
|
+
|
|
531
|
+
return {
|
|
532
|
+
id: source.id,
|
|
533
|
+
...(optionalText(source.label) ? { title: optionalText(source.label) } : {}),
|
|
534
|
+
modes: [...(shipping.length ? ['shipping'] : []), ...(pickup.length ? ['pickup'] : [])],
|
|
535
|
+
...(source.items ? { items } : {}),
|
|
536
|
+
shippingOptions: shipping.map(toShippingOption),
|
|
537
|
+
pickupPoints: pickup.map(toPickupPoint),
|
|
538
|
+
rateState: groupRateState,
|
|
539
|
+
...(source.unavailableReason ? { note: source.unavailableReason } : {}),
|
|
540
|
+
state: {
|
|
541
|
+
mode,
|
|
542
|
+
...(selected && !selected.pickup ? { shippingOptionId: selected.id } : {}),
|
|
543
|
+
...(selected?.pickup ? { pickupPointId: selected.id } : {}),
|
|
544
|
+
rateState: groupRateState,
|
|
545
|
+
},
|
|
546
|
+
lines: items,
|
|
547
|
+
...(selectedViewOption ? { selectedShippingOption: selectedViewOption } : {}),
|
|
548
|
+
...(selectedPickup ? { selectedPickupPoint: selectedPickup } : {}),
|
|
549
|
+
...(selected ? { selectedMode: mode } : {}),
|
|
550
|
+
...(selected && !selected.pickup ? { selectedShippingOptionId: selected.id } : {}),
|
|
551
|
+
...(selected?.pickup ? { selectedPickupPointId: selected.id } : {}),
|
|
552
|
+
ready: selectedAvailable,
|
|
553
|
+
...(selectedAvailable ? { feeCents: moneyToDisplayCents(selected?.price) ?? null } : { feeCents: null }),
|
|
554
|
+
shippingAvailable: shipping.length > 0,
|
|
555
|
+
pickupAvailable: pickup.length > 0,
|
|
556
|
+
bothModesAvailable: shipping.length > 0 && pickup.length > 0,
|
|
557
|
+
currentModeAvailable: mode === 'pickup' ? pickup.length > 0 : shipping.length > 0,
|
|
558
|
+
currentChoiceCount: mode === 'pickup' ? pickup.length : shipping.length,
|
|
559
|
+
canChange: source.options.length > 1 || !selected || selected.disabled === true,
|
|
560
|
+
panelMode: mode,
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
function mapAreaState(
|
|
565
|
+
state: CheckoutReadState | undefined,
|
|
566
|
+
): 'idle' | 'loading' | 'ready' | 'error' {
|
|
567
|
+
if (state === 'pending') return 'loading';
|
|
568
|
+
if (state === 'error' || state === 'unavailable') return 'error';
|
|
569
|
+
return state === 'idle' ? 'idle' : 'ready';
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
export function toHostedCheckoutModel(
|
|
573
|
+
props: CheckoutProps,
|
|
574
|
+
state: HostedCheckoutState,
|
|
575
|
+
modeOverrides: CheckoutGroupModeOverrides = {},
|
|
576
|
+
): CheckoutViewModel | null {
|
|
577
|
+
const summary = props.orderSummary;
|
|
578
|
+
const totals = summary?.totals;
|
|
579
|
+
const subtotalCents = moneyToDisplayCents(totals?.subtotal);
|
|
580
|
+
const totalCents = moneyToDisplayCents(totals?.total);
|
|
581
|
+
const currencyCode = totals?.total.currencyCode.trim() || totals?.subtotal.currencyCode.trim();
|
|
582
|
+
if (subtotalCents === undefined || totalCents === undefined || !currencyCode) return null;
|
|
583
|
+
const sourceLines = summary?.items ?? [];
|
|
584
|
+
const initialLines = sourceLines.map((line) => toLine(line));
|
|
585
|
+
const lineById = new Map(initialLines.map((line) => [line.lineId, line]));
|
|
586
|
+
const sourceGroups = props.shippingGroups ?? [];
|
|
587
|
+
const groups = sourceGroups.map((group) =>
|
|
588
|
+
toGroup(group, lineById, props.shippingState ?? 'idle', modeOverrides[group.id]),
|
|
589
|
+
);
|
|
590
|
+
const addressModel = displayAddresses(props);
|
|
591
|
+
const savedAddressState = {
|
|
592
|
+
...(props.savedAddressState?.pendingId
|
|
593
|
+
? { pendingId: props.savedAddressState.pendingId }
|
|
594
|
+
: {}),
|
|
595
|
+
...(props.savedAddressState?.error
|
|
596
|
+
? { error: props.savedAddressState.error.message }
|
|
597
|
+
: {}),
|
|
598
|
+
...(props.savedAddressState?.lastSavedId
|
|
599
|
+
? { lastSavedId: props.savedAddressState.lastSavedId }
|
|
600
|
+
: {}),
|
|
601
|
+
...(props.savedAddressState?.lastAction
|
|
602
|
+
? { lastAction: props.savedAddressState.lastAction }
|
|
603
|
+
: {}),
|
|
604
|
+
};
|
|
605
|
+
const shippingRequired = sourceGroups.some(
|
|
606
|
+
(group) => group.options.length === 0 || group.options.some((option) => !option.pickup),
|
|
607
|
+
);
|
|
608
|
+
const requirements = {
|
|
609
|
+
contactPhone: props.requireContactPhone === true,
|
|
610
|
+
shippingPhone: props.requireShippingPhone === true,
|
|
611
|
+
province: false,
|
|
612
|
+
postalCode: false,
|
|
613
|
+
};
|
|
614
|
+
const addressComplete =
|
|
615
|
+
props.shippingAddress.firstName.trim() !== '' &&
|
|
616
|
+
props.shippingAddress.lastName.trim() !== '' &&
|
|
617
|
+
props.shippingAddress.address1.trim() !== '' &&
|
|
618
|
+
props.shippingAddress.city.trim() !== '' &&
|
|
619
|
+
props.shippingAddress.countryCode.trim() !== '' &&
|
|
620
|
+
(!requirements.shippingPhone || Boolean(props.shippingAddress.phone?.trim())) &&
|
|
621
|
+
(!requirements.province || Boolean(props.shippingAddress.province?.trim())) &&
|
|
622
|
+
(!requirements.postalCode || Boolean(props.shippingAddress.postalCode?.trim()));
|
|
623
|
+
const missingAddress = shippingRequired && !addressComplete;
|
|
624
|
+
const selectedOptionsReady = sourceGroups.every(
|
|
625
|
+
(group) => {
|
|
626
|
+
const selected = group.options.find((option) => option.id === group.selectedOptionId);
|
|
627
|
+
return group.options.length > 0 && Boolean(selected) && selected?.disabled !== true;
|
|
628
|
+
},
|
|
629
|
+
);
|
|
630
|
+
const shippingState = mapAreaState(props.shippingState ?? state.checkoutShippingState);
|
|
631
|
+
const paymentState = mapAreaState(props.paymentState ?? state.checkoutPaymentState);
|
|
632
|
+
const paymentMethods = (props.paymentMethods ?? []).map((method) =>
|
|
633
|
+
toPaymentOption(method, props),
|
|
634
|
+
);
|
|
635
|
+
const selectedPayment = paymentMethods.find((method) => method.id === props.paymentMethod);
|
|
636
|
+
const paymentReady =
|
|
637
|
+
Boolean(selectedPayment?.enabled) && paymentState !== 'loading' && paymentState !== 'error';
|
|
638
|
+
const discountCents = moneyToDisplayCents(totals?.discount);
|
|
639
|
+
const totalsPending = state.cartPending || props.totalsState === 'pending';
|
|
640
|
+
const cartState = totalsPending
|
|
641
|
+
? 'loading'
|
|
642
|
+
: state.cartError || props.totalsState === 'error'
|
|
643
|
+
? 'error'
|
|
644
|
+
: sourceLines.length === 0
|
|
645
|
+
? 'empty'
|
|
646
|
+
: 'ready';
|
|
647
|
+
const unresolved = state.checkoutErrorKind === 'unresolved' || state.orderStatus === 'unresolved';
|
|
648
|
+
const orderFailed = Boolean(state.checkoutError) || state.orderStatus === 'error' || unresolved;
|
|
649
|
+
const orderPending =
|
|
650
|
+
state.orderStatus === 'pending' || (state.checkoutPending && state.cartCompleted);
|
|
651
|
+
const blockingInterruption = props.interruption?.severity === 'blocking';
|
|
652
|
+
const errors = toFieldErrors(props.fieldErrors);
|
|
653
|
+
if (state.checkoutError) errors.push({ path: 'order', message: state.checkoutError });
|
|
654
|
+
if (state.cartError) errors.push({ path: 'cart', message: state.cartError });
|
|
655
|
+
|
|
656
|
+
return {
|
|
657
|
+
labels: copyFor(props),
|
|
658
|
+
locale: 'es-ES',
|
|
659
|
+
currencyCode,
|
|
660
|
+
countries: (props.shippingLocations?.countries ?? [])
|
|
661
|
+
.filter((country) => country.value.trim() !== '' && country.label.trim() !== '')
|
|
662
|
+
.map(({ value, label }) => ({
|
|
663
|
+
code: value,
|
|
664
|
+
name: label,
|
|
665
|
+
// The host has flat dynamic location options but no country-specific
|
|
666
|
+
// postal requirement. Show the field as optional rather than hiding it
|
|
667
|
+
// or claiming a requirement the backend has not supplied.
|
|
668
|
+
postalCode: 'optional',
|
|
669
|
+
provinces: [],
|
|
670
|
+
})),
|
|
671
|
+
locationOptions: toLocationOptions(props.shippingLocations),
|
|
672
|
+
paymentMethods,
|
|
673
|
+
lines: initialLines,
|
|
674
|
+
groups,
|
|
675
|
+
addresses: addressModel.addresses,
|
|
676
|
+
savedAddressState,
|
|
677
|
+
...(addressModel.selectedShippingAddressId
|
|
678
|
+
? { selectedShippingAddressId: addressModel.selectedShippingAddressId }
|
|
679
|
+
: {}),
|
|
680
|
+
contact: {
|
|
681
|
+
name: joinName(props.contact.firstName, props.contact.lastName),
|
|
682
|
+
email: props.contact.email,
|
|
683
|
+
phone: props.contact.phone,
|
|
684
|
+
},
|
|
685
|
+
session: props.customer ? 'authenticated' : 'guest',
|
|
686
|
+
...(selectedPayment ? { selectedPaymentId: selectedPayment.id } : {}),
|
|
687
|
+
billing: {
|
|
688
|
+
sameAsShipping: props.sameAsShipping,
|
|
689
|
+
...(addressModel.billingAddressId ? { addressId: addressModel.billingAddressId } : {}),
|
|
690
|
+
},
|
|
691
|
+
requirements,
|
|
692
|
+
promotions:
|
|
693
|
+
discountCents === undefined
|
|
694
|
+
? []
|
|
695
|
+
: [
|
|
696
|
+
{
|
|
697
|
+
id: 'cart-discount',
|
|
698
|
+
label: props.labels?.discountLabel ?? 'Descuento',
|
|
699
|
+
kind: 'discount',
|
|
700
|
+
amountCents: discountCents,
|
|
701
|
+
},
|
|
702
|
+
],
|
|
703
|
+
totals: {
|
|
704
|
+
subtotalCents,
|
|
705
|
+
...(moneyToDisplayCents(totals?.discount) !== undefined
|
|
706
|
+
? { promotionsCents: moneyToDisplayCents(totals?.discount) }
|
|
707
|
+
: {}),
|
|
708
|
+
...(moneyToDisplayCents(totals?.tax) !== undefined
|
|
709
|
+
? { taxCents: moneyToDisplayCents(totals?.tax) }
|
|
710
|
+
: {}),
|
|
711
|
+
...(moneyToDisplayCents(totals?.shipping) !== undefined
|
|
712
|
+
? { shippingCents: moneyToDisplayCents(totals?.shipping) }
|
|
713
|
+
: {}),
|
|
714
|
+
totalCents,
|
|
715
|
+
...(typeof state.cartQuantity === 'number' ? { unitCount: state.cartQuantity } : {}),
|
|
716
|
+
pending: totalsPending,
|
|
717
|
+
hasUnavailable: props.availability?.status === 'unavailable',
|
|
718
|
+
canConfirm:
|
|
719
|
+
cartState === 'ready' &&
|
|
720
|
+
!state.checkoutPending &&
|
|
721
|
+
!orderPending &&
|
|
722
|
+
!orderFailed &&
|
|
723
|
+
!blockingInterruption &&
|
|
724
|
+
shippingState !== 'loading' &&
|
|
725
|
+
shippingState !== 'error' &&
|
|
726
|
+
(!requirements.contactPhone || Boolean(props.contact.phone.trim())) &&
|
|
727
|
+
selectedOptionsReady &&
|
|
728
|
+
!missingAddress &&
|
|
729
|
+
paymentReady &&
|
|
730
|
+
props.availability?.status !== 'unavailable' &&
|
|
731
|
+
props.availability?.status !== 'error',
|
|
732
|
+
blockedMessage: missingAddress
|
|
733
|
+
? 'Añade una dirección para continuar.'
|
|
734
|
+
: props.shippingState === 'error' || props.shippingState === 'unavailable'
|
|
735
|
+
? props.labels?.deliveryErrorLabel ?? 'No se pudieron cargar las opciones de entrega.'
|
|
736
|
+
: props.availability?.status === 'error' || props.availability?.status === 'unavailable'
|
|
737
|
+
? props.availability.reason ??
|
|
738
|
+
props.labels?.availabilityUnavailableLabel ??
|
|
739
|
+
'El checkout no está disponible.'
|
|
740
|
+
: !paymentReady
|
|
741
|
+
? props.labels?.noPaymentMethodsLabel ?? 'Selecciona un método de pago.'
|
|
742
|
+
: '',
|
|
743
|
+
requiresShipping: shippingRequired,
|
|
744
|
+
missingAddress,
|
|
745
|
+
},
|
|
746
|
+
states: {
|
|
747
|
+
cart: cartState,
|
|
748
|
+
shipping: shippingState,
|
|
749
|
+
payment: paymentState,
|
|
750
|
+
order: blockingInterruption
|
|
751
|
+
? 'interrupted'
|
|
752
|
+
: orderPending
|
|
753
|
+
? 'submitting'
|
|
754
|
+
: orderFailed
|
|
755
|
+
? 'error'
|
|
756
|
+
: state.orderStatus === 'complete'
|
|
757
|
+
? 'confirmed'
|
|
758
|
+
: 'idle',
|
|
759
|
+
},
|
|
760
|
+
...(props.interruption ? { interruption: props.interruption } : {}),
|
|
761
|
+
...(errors.length ? { errors } : {}),
|
|
762
|
+
capabilities: {
|
|
763
|
+
associates: false,
|
|
764
|
+
pickupPoints: sourceGroups.some((group) => group.options.some((option) => option.pickup)),
|
|
765
|
+
coupons: false,
|
|
766
|
+
},
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
function flatAddressWrites(address: CheckoutAddressValues, set: HostedSetter): void {
|
|
771
|
+
set('/checkout/address', address.address1);
|
|
772
|
+
set('/checkout/firstName', address.firstName);
|
|
773
|
+
set('/checkout/lastName', address.lastName);
|
|
774
|
+
set('/checkout/city', address.city);
|
|
775
|
+
set('/checkout/state', address.province ?? '');
|
|
776
|
+
set('/checkout/zipCode', address.postalCode ?? '');
|
|
777
|
+
set('/checkout/country', address.countryCode);
|
|
778
|
+
set('/checkout/phone', address.phone ?? '');
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
function clearPhoneFieldError(
|
|
782
|
+
errors: Record<string, unknown>,
|
|
783
|
+
groupName: 'contact' | 'shippingAddress',
|
|
784
|
+
): Record<string, unknown> {
|
|
785
|
+
const next = { ...errors };
|
|
786
|
+
const group = next[groupName];
|
|
787
|
+
if (group && typeof group === 'object' && !Array.isArray(group)) {
|
|
788
|
+
const fields = { ...(group as Record<string, unknown>) };
|
|
789
|
+
delete fields.phone;
|
|
790
|
+
next[groupName] = fields;
|
|
791
|
+
}
|
|
792
|
+
return next;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
function addressValues(address: CheckoutAddress): CheckoutAddressValues | undefined {
|
|
796
|
+
const countryCode = optionalText(address.countryCode);
|
|
797
|
+
if (!countryCode) return undefined;
|
|
798
|
+
const name = splitName(address.recipient);
|
|
799
|
+
const address2 = optionalText(address.line2);
|
|
800
|
+
const company = optionalText(address.company);
|
|
801
|
+
const province = optionalText(address.province);
|
|
802
|
+
const postalCode = optionalText(address.postalCode);
|
|
803
|
+
const phone = optionalText(address.phone);
|
|
804
|
+
return {
|
|
805
|
+
...name,
|
|
806
|
+
address1: address.line1,
|
|
807
|
+
...(address2 ? { address2 } : {}),
|
|
808
|
+
...(company ? { company } : {}),
|
|
809
|
+
city: address.city,
|
|
810
|
+
...(province ? { province } : {}),
|
|
811
|
+
...(postalCode ? { postalCode } : {}),
|
|
812
|
+
countryCode,
|
|
813
|
+
...(phone ? { phone } : {}),
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
export function createHostedCheckoutActions(
|
|
818
|
+
props: CheckoutProps,
|
|
819
|
+
state: HostedCheckoutState,
|
|
820
|
+
set: HostedSetter,
|
|
821
|
+
emit: HostedEmit,
|
|
822
|
+
onGroupModeChange: (groupId: string, mode: CheckoutGroupMode) => void = () => undefined,
|
|
823
|
+
loadLocations: HostedLocationLoader = missingLocationLoader,
|
|
824
|
+
locationDraft: CheckoutLocationDraft = {},
|
|
825
|
+
setLocationDraft: SetCheckoutLocationDraft = () => undefined,
|
|
826
|
+
locationRequestTokens: CheckoutLocationRequestTokens = { provinces: 0, cities: 0 },
|
|
827
|
+
) {
|
|
828
|
+
const groups = props.shippingGroups ?? [];
|
|
829
|
+
const savedAddresses = props.savedAddresses ?? [];
|
|
830
|
+
const presentedAddresses = displayAddresses(props);
|
|
831
|
+
const currentShippingAddressId = presentedAddresses.selectedShippingAddressId;
|
|
832
|
+
|
|
833
|
+
return {
|
|
834
|
+
onContactChange(patch: { name?: string; email?: string; phone?: string }) {
|
|
835
|
+
if (patch.name !== undefined) {
|
|
836
|
+
const name = splitName(patch.name);
|
|
837
|
+
set('/checkoutContact/firstName', name.firstName);
|
|
838
|
+
set('/checkoutContact/lastName', name.lastName);
|
|
839
|
+
set('/checkout/firstName', name.firstName);
|
|
840
|
+
set('/checkout/lastName', name.lastName);
|
|
841
|
+
}
|
|
842
|
+
if (patch.email !== undefined) {
|
|
843
|
+
set('/checkoutContact/email', patch.email);
|
|
844
|
+
set('/checkout/email', patch.email);
|
|
845
|
+
}
|
|
846
|
+
if (patch.phone !== undefined) {
|
|
847
|
+
set('/checkoutContact/phone', patch.phone);
|
|
848
|
+
set('/checkout/phone', patch.phone);
|
|
849
|
+
set(
|
|
850
|
+
'/checkoutFieldErrors',
|
|
851
|
+
clearPhoneFieldError(state.checkoutFieldErrors ?? {}, 'contact'),
|
|
852
|
+
);
|
|
853
|
+
}
|
|
854
|
+
},
|
|
855
|
+
onSelectAddress(
|
|
856
|
+
id: string,
|
|
857
|
+
target: 'shipping' | 'billing' = 'shipping',
|
|
858
|
+
sameAsShipping?: boolean,
|
|
859
|
+
) {
|
|
860
|
+
if (target === 'billing') {
|
|
861
|
+
if (sameAsShipping) {
|
|
862
|
+
set('/checkoutSameAsShipping', true);
|
|
863
|
+
} else {
|
|
864
|
+
set('/checkoutSameAsShipping', false);
|
|
865
|
+
const saved = savedAddresses.find((entry) => entry.id === id);
|
|
866
|
+
if (saved) {
|
|
867
|
+
set('/checkoutBillingAddress', saved.address);
|
|
868
|
+
} else if (id === currentShippingAddressId) {
|
|
869
|
+
set('/checkoutBillingAddress', props.shippingAddress);
|
|
870
|
+
} else if (id === presentedAddresses.billingAddressId && props.billingAddress) {
|
|
871
|
+
set('/checkoutBillingAddress', props.billingAddress);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
emit('syncCheckoutAddress');
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
if (id === currentShippingAddressId && !savedAddresses.some((address) => address.id === id)) {
|
|
879
|
+
emit('syncCheckoutAddress');
|
|
880
|
+
return;
|
|
881
|
+
}
|
|
882
|
+
const saved = savedAddresses.find((entry) => entry.id === id);
|
|
883
|
+
if (!saved) return;
|
|
884
|
+
set('/checkoutShippingAddress', saved.address);
|
|
885
|
+
flatAddressWrites(saved.address, set);
|
|
886
|
+
emit('syncCheckoutAddress');
|
|
887
|
+
},
|
|
888
|
+
onCreateAddress(address: CheckoutAddress, saveToAccount: boolean) {
|
|
889
|
+
const values = addressValues(address);
|
|
890
|
+
if (!values) return;
|
|
891
|
+
set('/checkoutShippingAddress', values);
|
|
892
|
+
flatAddressWrites(values, set);
|
|
893
|
+
setLocationDraft({});
|
|
894
|
+
if (saveToAccount) emit('createSavedAddress');
|
|
895
|
+
emit('syncCheckoutAddress');
|
|
896
|
+
},
|
|
897
|
+
onSelectShippingOption(groupId: string, optionId?: string, requestedMode?: string) {
|
|
898
|
+
const sourceGroup = groups.find((group) => group.id === groupId);
|
|
899
|
+
if (!sourceGroup) return;
|
|
900
|
+
if (!optionId) {
|
|
901
|
+
if (requestedMode === 'shipping' && sourceGroup.options.some((option) => !option.pickup)) {
|
|
902
|
+
onGroupModeChange(groupId, 'shipping');
|
|
903
|
+
} else if (
|
|
904
|
+
requestedMode === 'pickup' &&
|
|
905
|
+
sourceGroup.options.some((option) => option.pickup)
|
|
906
|
+
) {
|
|
907
|
+
onGroupModeChange(groupId, 'pickup');
|
|
908
|
+
}
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
const option = sourceGroup.options.find((entry) => entry.id === optionId);
|
|
912
|
+
if (!option || option.disabled) return;
|
|
913
|
+
onGroupModeChange(groupId, option.pickup ? 'pickup' : 'shipping');
|
|
914
|
+
const next = groups.map((group) =>
|
|
915
|
+
group.id === groupId ? { ...group, selectedOptionId: optionId } : group,
|
|
916
|
+
);
|
|
917
|
+
set('/checkoutShippingGroups', next);
|
|
918
|
+
set('/checkoutSelectedShippingOptionId', optionId);
|
|
919
|
+
emit('selectShippingMethod');
|
|
920
|
+
},
|
|
921
|
+
onLocationChange(level: CheckoutLocationLevel, value: string) {
|
|
922
|
+
const current = props.shippingLocations ?? EMPTY_LOCATIONS;
|
|
923
|
+
if (level === 'cities') return;
|
|
924
|
+
|
|
925
|
+
if (level === 'countries') {
|
|
926
|
+
const requestToken = ++locationRequestTokens.provinces;
|
|
927
|
+
locationRequestTokens.cities += 1;
|
|
928
|
+
const nextDraft = { countryCode: optionalText(value), provinceCode: undefined };
|
|
929
|
+
setLocationDraft(nextDraft);
|
|
930
|
+
const pendingOptions = {
|
|
931
|
+
...current,
|
|
932
|
+
provinces: [],
|
|
933
|
+
provincesState: value ? ('pending' as const) : ('idle' as const),
|
|
934
|
+
provincesError: undefined,
|
|
935
|
+
cities: [],
|
|
936
|
+
citiesState: 'idle' as const,
|
|
937
|
+
citiesError: undefined,
|
|
938
|
+
};
|
|
939
|
+
set('/checkoutShippingLocations', pendingOptions);
|
|
940
|
+
if (!nextDraft.countryCode) return;
|
|
941
|
+
return loadLocations({
|
|
942
|
+
kind: 'shipping',
|
|
943
|
+
level: 'provinces',
|
|
944
|
+
countryCode: nextDraft.countryCode,
|
|
945
|
+
}).then((result) => {
|
|
946
|
+
if (locationRequestTokens.provinces !== requestToken) return;
|
|
947
|
+
set('/checkoutShippingLocations', {
|
|
948
|
+
...pendingOptions,
|
|
949
|
+
provinces: result.ok ? result.options : [],
|
|
950
|
+
provincesState: result.ok ? 'idle' : 'error',
|
|
951
|
+
provincesError: result.ok ? undefined : result.error,
|
|
952
|
+
});
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
const countryCode = locationDraft.countryCode ?? props.shippingAddress.countryCode;
|
|
957
|
+
const requestToken = ++locationRequestTokens.cities;
|
|
958
|
+
const nextDraft = {
|
|
959
|
+
...locationDraft,
|
|
960
|
+
...(countryCode ? { countryCode } : {}),
|
|
961
|
+
provinceCode: optionalText(value),
|
|
962
|
+
};
|
|
963
|
+
setLocationDraft(nextDraft);
|
|
964
|
+
const pendingOptions = {
|
|
965
|
+
...current,
|
|
966
|
+
cities: [],
|
|
967
|
+
citiesState: value && countryCode ? ('pending' as const) : ('idle' as const),
|
|
968
|
+
citiesError: undefined,
|
|
969
|
+
};
|
|
970
|
+
set('/checkoutShippingLocations', pendingOptions);
|
|
971
|
+
if (!value || !countryCode) return;
|
|
972
|
+
return loadLocations({
|
|
973
|
+
kind: 'shipping',
|
|
974
|
+
level: 'cities',
|
|
975
|
+
countryCode,
|
|
976
|
+
provinceCode: value,
|
|
977
|
+
}).then((result) => {
|
|
978
|
+
if (locationRequestTokens.cities !== requestToken) return;
|
|
979
|
+
set('/checkoutShippingLocations', {
|
|
980
|
+
...pendingOptions,
|
|
981
|
+
cities: result.ok ? result.options : [],
|
|
982
|
+
citiesState: result.ok ? 'idle' : 'error',
|
|
983
|
+
citiesError: result.ok ? undefined : result.error,
|
|
984
|
+
});
|
|
985
|
+
});
|
|
986
|
+
},
|
|
987
|
+
onSelectPayment(paymentId: string) {
|
|
988
|
+
set('/checkout/paymentMethod', paymentId);
|
|
989
|
+
set('/checkoutSelectedPaymentMethod', paymentId);
|
|
990
|
+
},
|
|
991
|
+
onSubmit() {
|
|
992
|
+
set('/orderStatus', 'pending');
|
|
993
|
+
emit('placeOrder');
|
|
994
|
+
},
|
|
995
|
+
onRetry(area: 'session' | 'shipping' | 'payment' | 'order') {
|
|
996
|
+
if (area === 'shipping') {
|
|
997
|
+
emit('syncCheckoutAddress');
|
|
998
|
+
} else if (area === 'order') {
|
|
999
|
+
set('/orderStatus', 'pending');
|
|
1000
|
+
const unresolved =
|
|
1001
|
+
state.checkoutErrorKind === 'unresolved' || state.orderStatus === 'unresolved';
|
|
1002
|
+
const shippingFailed =
|
|
1003
|
+
state.checkoutShippingState === 'error' || state.checkoutShippingState === 'unavailable';
|
|
1004
|
+
emit(
|
|
1005
|
+
unresolved
|
|
1006
|
+
? 'reconcileOrder'
|
|
1007
|
+
: shippingFailed
|
|
1008
|
+
? 'syncCheckoutAddress'
|
|
1009
|
+
: 'placeOrder',
|
|
1010
|
+
);
|
|
1011
|
+
}
|
|
1012
|
+
},
|
|
1013
|
+
onInterruptionAction(action: NonNullable<CheckoutProps['interruption']>['actions'][number]) {
|
|
1014
|
+
if (!props.interruption?.actions.includes(action)) return;
|
|
1015
|
+
set('/checkoutInterruption', undefined);
|
|
1016
|
+
},
|
|
1017
|
+
onContinueShopping() {
|
|
1018
|
+
emit('continueShopping');
|
|
1019
|
+
},
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
export function CheckoutCommerceHostedAdapter({
|
|
1024
|
+
props: rawProps,
|
|
1025
|
+
emit,
|
|
1026
|
+
loadLocations,
|
|
1027
|
+
}: {
|
|
1028
|
+
props: Record<string, unknown>;
|
|
1029
|
+
emit: HostedEmit;
|
|
1030
|
+
loadLocations: HostedLocationLoader;
|
|
1031
|
+
}) {
|
|
1032
|
+
const { state, set } = useStateStore();
|
|
1033
|
+
const [modeOverrides, setModeOverrides] = useState<CheckoutGroupModeOverrides>({});
|
|
1034
|
+
const [locationDraft, setLocationDraft] = useState<CheckoutLocationDraft>({});
|
|
1035
|
+
const locationRequestTokens = useRef<CheckoutLocationRequestTokens>({
|
|
1036
|
+
provinces: 0,
|
|
1037
|
+
cities: 0,
|
|
1038
|
+
});
|
|
1039
|
+
const props = checkoutPropsSchema.parse(rawProps);
|
|
1040
|
+
const hostState = state as unknown as HostedCheckoutState;
|
|
1041
|
+
const model = toHostedCheckoutModel(props, hostState, modeOverrides);
|
|
1042
|
+
if (
|
|
1043
|
+
!model ||
|
|
1044
|
+
hostState.cartError ||
|
|
1045
|
+
props.totalsState === 'error' ||
|
|
1046
|
+
props.availability?.status === 'error' ||
|
|
1047
|
+
props.availability?.status === 'unavailable'
|
|
1048
|
+
) {
|
|
1049
|
+
const message =
|
|
1050
|
+
hostState.cartError ||
|
|
1051
|
+
props.availability?.reason ||
|
|
1052
|
+
(props.availability?.status === 'unavailable'
|
|
1053
|
+
? props.labels?.availabilityUnavailableLabel
|
|
1054
|
+
: props.labels?.availabilityErrorLabel) ||
|
|
1055
|
+
props.labels?.totalsErrorLabel ||
|
|
1056
|
+
props.labels?.totalsUnavailableLabel ||
|
|
1057
|
+
'Totales no disponibles.';
|
|
1058
|
+
return hostState.cartPending || props.totalsState === 'pending' ? (
|
|
1059
|
+
<p role="status" aria-busy="true">
|
|
1060
|
+
{props.labels?.totalsPendingLabel ?? 'Cargando checkout…'}
|
|
1061
|
+
</p>
|
|
1062
|
+
) : (
|
|
1063
|
+
<div role="alert">
|
|
1064
|
+
<p>{message}</p>
|
|
1065
|
+
<Button
|
|
1066
|
+
type="button"
|
|
1067
|
+
variant="outline"
|
|
1068
|
+
size="sm"
|
|
1069
|
+
onClick={() => emit('syncCheckoutAddress')}
|
|
1070
|
+
>
|
|
1071
|
+
{props.labels?.retryLabel ?? 'Reintentar'}
|
|
1072
|
+
</Button>
|
|
1073
|
+
</div>
|
|
1074
|
+
);
|
|
1075
|
+
}
|
|
1076
|
+
const actions = createHostedCheckoutActions(
|
|
1077
|
+
props,
|
|
1078
|
+
hostState,
|
|
1079
|
+
set as unknown as HostedSetter,
|
|
1080
|
+
emit,
|
|
1081
|
+
(groupId, mode) => setModeOverrides((current) => ({ ...current, [groupId]: mode })),
|
|
1082
|
+
loadLocations,
|
|
1083
|
+
locationDraft,
|
|
1084
|
+
setLocationDraft,
|
|
1085
|
+
locationRequestTokens.current,
|
|
1086
|
+
);
|
|
1087
|
+
|
|
1088
|
+
return <CheckoutCommerceV1Hosted data={model} {...actions} />;
|
|
1089
|
+
}
|