@thorprovider/storefront 0.6.3 → 0.7.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/assets/templates/app/lib/__STOREFRONT__/actions.ts +649 -31
- package/assets/templates/app/lib/__STOREFRONT__/checkout-shipping.core.ts +37 -0
- package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +117 -0
- package/assets/templates/app/lib/__STOREFRONT__/state.core.ts +7 -1
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/index.ts +2 -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/schema.marketplace-product-card.ts +67 -0
- package/assets/templates/features/checkout/handlers.ts +326 -31
- package/assets/templates/features/checkout/state.ts +79 -3
- package/assets/templates/views/checkout/content.ts +63 -2
- package/assets/templates/views/checkout/index.tsx +6 -0
- package/assets/templates/views/checkout/props.ts +61 -21
- package/assets/templates/views/checkout/registry.tsx +300 -33
- package/assets/templates/views/checkout/schema.ts +184 -8
- package/assets/templates/views/home/assembly/assembly.json +7 -0
- package/package.json +1 -1
- package/recipes/recipe.schema.json +1 -1
- package/recipes/recipes.json +2 -1
- package/recipes/sections.json +9 -0
- package/scripts/file-classes.mjs +1 -0
- package/skills/sf-view-gen/SKILL.md +6 -0
- package/skills/sf-view-gen/assets/recipes/recipes.json +2 -1
- package/skills/sf-view-gen/assets/recipes/sections.json +9 -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/schema.marketplace-product-card.ts +67 -0
- package/skills/storefront-workflow/SKILL.md +5 -0
- package/skills/storefront-workflow/references/mobile-responsiveness.md +1 -1
|
@@ -15,34 +15,60 @@
|
|
|
15
15
|
// blindly retried; reconciliation uses the active cart id when no completed
|
|
16
16
|
// receipt cookie exists yet.
|
|
17
17
|
|
|
18
|
-
import type { AccountOrderView,
|
|
19
|
-
import type {
|
|
18
|
+
import type { AccountOrderView, CartLineState } from './state.core'
|
|
19
|
+
import type {
|
|
20
|
+
Address,
|
|
21
|
+
CheckoutAddressOption,
|
|
22
|
+
CreateAddressData,
|
|
23
|
+
Customer,
|
|
24
|
+
PaymentMethod,
|
|
25
|
+
ShippingGroupSelection,
|
|
26
|
+
} from '@thorprovider/types'
|
|
27
|
+
import type {
|
|
28
|
+
CheckoutAddressValues,
|
|
29
|
+
CheckoutContactValues,
|
|
30
|
+
CheckoutCustomerIdentity,
|
|
31
|
+
CheckoutLocationOptions,
|
|
32
|
+
CheckoutSavedAddress,
|
|
33
|
+
CheckoutShippingGroup,
|
|
34
|
+
} from '@thorprovider/blocks'
|
|
20
35
|
import {
|
|
21
36
|
EMPTY_CART_STATE,
|
|
22
37
|
addVariant,
|
|
38
|
+
applyCheckoutShippingGroups,
|
|
23
39
|
applyLineDelta,
|
|
24
40
|
applyPayment,
|
|
25
41
|
authenticate,
|
|
26
42
|
completeOrder,
|
|
27
43
|
createGuestCart,
|
|
44
|
+
createCustomerAddress,
|
|
45
|
+
deleteCustomerAddress,
|
|
28
46
|
endSession,
|
|
29
47
|
loadCheckoutCountries,
|
|
48
|
+
loadCheckoutShippingGroups,
|
|
49
|
+
loadCustomer,
|
|
50
|
+
loadCustomerAddresses,
|
|
51
|
+
loadGeoCities,
|
|
52
|
+
loadGeoProvinces,
|
|
30
53
|
loadOrders,
|
|
31
54
|
loadOrdersPage,
|
|
32
55
|
loadPaymentMethods,
|
|
33
56
|
loadProductDetail,
|
|
34
|
-
loadShippingMethods,
|
|
35
57
|
readCart,
|
|
36
58
|
reconcileOrder,
|
|
59
|
+
prefillCheckoutFromCustomer,
|
|
37
60
|
registerShopper,
|
|
38
61
|
removeLine,
|
|
39
62
|
resolveProductCartTarget,
|
|
63
|
+
saveBillingAddress,
|
|
40
64
|
saveShippingAddress,
|
|
41
65
|
selectShipping,
|
|
42
66
|
setLineQuantity,
|
|
43
67
|
toCheckoutFieldErrors,
|
|
44
|
-
|
|
68
|
+
toCheckoutShippingGroups,
|
|
69
|
+
updateCustomerAddress,
|
|
45
70
|
validateAddress,
|
|
71
|
+
validateCustomerAddress,
|
|
46
72
|
type AddressInput,
|
|
47
73
|
type CartStatePatch,
|
|
48
74
|
type PlaceOrderResult,
|
|
@@ -70,6 +96,13 @@ type CartActionResult =
|
|
|
70
96
|
| { ok: true; cart: CartStatePatch }
|
|
71
97
|
| { ok: false; error: string }
|
|
72
98
|
|
|
99
|
+
/**
|
|
100
|
+
* The delivery state a failed grouped-shipping operation reports: `error` is a
|
|
101
|
+
* recoverable failure (retry the quote/apply), `unavailable` is a provider that
|
|
102
|
+
* cannot serve grouped delivery at all (no retry promise).
|
|
103
|
+
*/
|
|
104
|
+
type CheckoutShippingState = 'error' | 'unavailable'
|
|
105
|
+
|
|
73
106
|
/** Structured result for a checkout action. */
|
|
74
107
|
type CheckoutActionResult =
|
|
75
108
|
| {
|
|
@@ -77,10 +110,26 @@ type CheckoutActionResult =
|
|
|
77
110
|
cart: CartStatePatch
|
|
78
111
|
countries?: { value: string; label: string }[]
|
|
79
112
|
paymentMethods?: PaymentMethod[]
|
|
80
|
-
|
|
81
|
-
|
|
113
|
+
/** The backend group quote mapped 1:1 to the presentation contract. */
|
|
114
|
+
shippingGroups?: CheckoutShippingGroup[]
|
|
115
|
+
/** Presentation group id -> the backend `products` to submit on apply. */
|
|
116
|
+
shippingGroupProducts?: Record<string, string[]>
|
|
117
|
+
/**
|
|
118
|
+
* A grouped-shipping load failure is reported here WITHOUT failing the
|
|
119
|
+
* whole checkout load (design D7). No flat group is invented instead.
|
|
120
|
+
*/
|
|
121
|
+
shippingError?: string
|
|
122
|
+
/** The delivery state that accompanies `shippingError`. */
|
|
123
|
+
shippingState?: CheckoutShippingState
|
|
124
|
+
fieldErrors?: Record<string, unknown>
|
|
125
|
+
}
|
|
126
|
+
| {
|
|
127
|
+
ok: false
|
|
128
|
+
error: string
|
|
129
|
+
fieldErrors?: Record<string, unknown>
|
|
130
|
+
/** Set by a failed grouped apply so the UI can distinguish unsupported. */
|
|
131
|
+
shippingState?: CheckoutShippingState
|
|
82
132
|
}
|
|
83
|
-
| { ok: false; error: string; fieldErrors?: CheckoutFieldErrors }
|
|
84
133
|
|
|
85
134
|
/**
|
|
86
135
|
* Structured result for a login/register auth action. It carries ONLY the
|
|
@@ -120,14 +169,34 @@ type OrdersPageActionResult =
|
|
|
120
169
|
/** Basic email shape check; a boundary guard, not a full RFC validation. */
|
|
121
170
|
const EMAIL_PATTERN = /\S+@\S+\.\S+/
|
|
122
171
|
|
|
172
|
+
/** The runtime/provider code for a provider without grouped-shipping support. */
|
|
173
|
+
const UNSUPPORTED_SHIPPING_GROUPS_CODE = 'CHECKOUT_SHIPPING_GROUPS_UNSUPPORTED'
|
|
174
|
+
|
|
175
|
+
/** The fixed, user-safe copy for each grouped-shipping failure. */
|
|
176
|
+
const quoteShippingErrorMessage = 'No se pudieron cargar las opciones de envío. Reintenta.'
|
|
177
|
+
const applyShippingErrorMessage = 'No se pudo aplicar el envío seleccionado. Reintenta.'
|
|
178
|
+
const unsupportedShippingMessage = 'El envío agrupado no está disponible en esta tienda.'
|
|
179
|
+
|
|
180
|
+
/** The typed code carried by a runtime/provider error, when it has one. */
|
|
181
|
+
function errorCode(error: unknown): string | undefined {
|
|
182
|
+
if (!error || typeof error !== 'object' || !('code' in error)) return undefined
|
|
183
|
+
const code = (error as { code?: unknown }).code
|
|
184
|
+
return typeof code === 'string' ? code : undefined
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Map a grouped-shipping failure to the delivery state the checkout must show:
|
|
189
|
+
* a provider without the capability is `unavailable` (no retry can fix it),
|
|
190
|
+
* every other failure is a recoverable `error`.
|
|
191
|
+
*/
|
|
192
|
+
function toShippingState(error: unknown): CheckoutShippingState {
|
|
193
|
+
return errorCode(error) === UNSUPPORTED_SHIPPING_GROUPS_CODE ? 'unavailable' : 'error'
|
|
194
|
+
}
|
|
195
|
+
|
|
123
196
|
/** Log a non-secret context line for a caught server error (never a secret). */
|
|
124
197
|
function logServerError(scope: string, error: unknown): void {
|
|
125
198
|
const message = error instanceof Error ? error.message : String(error)
|
|
126
|
-
|
|
127
|
-
error && typeof error === 'object' && 'code' in error && typeof (error as { code?: unknown }).code === 'string'
|
|
128
|
-
? (error as { code: string }).code
|
|
129
|
-
: undefined
|
|
130
|
-
console.error(`[storefront/actions] ${scope} failed`, { message, code })
|
|
199
|
+
console.error(`[storefront/actions] ${scope} failed`, { message, code: errorCode(error) })
|
|
131
200
|
}
|
|
132
201
|
|
|
133
202
|
function toError(error: unknown, fallback: string): string {
|
|
@@ -279,6 +348,35 @@ export async function loadCartStateAction(): Promise<CartStatePatch> {
|
|
|
279
348
|
}
|
|
280
349
|
}
|
|
281
350
|
|
|
351
|
+
const CONTACT_FIELD_NAMES = new Set(['email', 'firstName', 'lastName', 'phone'])
|
|
352
|
+
const ADDRESS_FIELD_NAMES = new Set([
|
|
353
|
+
'address1',
|
|
354
|
+
'address2',
|
|
355
|
+
'company',
|
|
356
|
+
'city',
|
|
357
|
+
'province',
|
|
358
|
+
'postalCode',
|
|
359
|
+
'countryCode',
|
|
360
|
+
'phone',
|
|
361
|
+
])
|
|
362
|
+
|
|
363
|
+
function toStructuredFieldErrors(
|
|
364
|
+
errors: Array<{ field: string; message: string }>,
|
|
365
|
+
): Record<string, unknown> {
|
|
366
|
+
const contact: Record<string, Array<{ message: string }>> = {}
|
|
367
|
+
const shippingAddress: Record<string, Array<{ message: string }>> = {}
|
|
368
|
+
const root: Record<string, Array<{ message: string }>> = {}
|
|
369
|
+
for (const error of errors) {
|
|
370
|
+
const bucket = CONTACT_FIELD_NAMES.has(error.field)
|
|
371
|
+
? contact
|
|
372
|
+
: ADDRESS_FIELD_NAMES.has(error.field)
|
|
373
|
+
? shippingAddress
|
|
374
|
+
: root
|
|
375
|
+
bucket[error.field] = [...(bucket[error.field] ?? []), { message: error.message }]
|
|
376
|
+
}
|
|
377
|
+
return { contact, shippingAddress, ...root }
|
|
378
|
+
}
|
|
379
|
+
|
|
282
380
|
function toAddressInput(values: Record<string, unknown>): AddressInput {
|
|
283
381
|
const str = (key: string) => (typeof values[key] === 'string' ? (values[key] as string) : '')
|
|
284
382
|
return {
|
|
@@ -294,11 +392,58 @@ function toAddressInput(values: Record<string, unknown>): AddressInput {
|
|
|
294
392
|
}
|
|
295
393
|
}
|
|
296
394
|
|
|
395
|
+
/** The mapped grouped-shipping surface of a checkout load. */
|
|
396
|
+
interface CheckoutShippingGroupsLoad {
|
|
397
|
+
groups: CheckoutShippingGroup[]
|
|
398
|
+
productsByGroup: Record<string, string[]>
|
|
399
|
+
error?: string
|
|
400
|
+
shippingState?: CheckoutShippingState
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Request the backend grouped-shipping quote and map it to the presentation
|
|
405
|
+
* groups, resolving line membership against the CURRENT cart lines and keeping
|
|
406
|
+
* the shopper's previous selection when the group identity and option survive.
|
|
407
|
+
*
|
|
408
|
+
* A quote failure is not fatal for the checkout load (design D7): the caller
|
|
409
|
+
* still receives the cart and an explicit `error` plus the delivery state to
|
|
410
|
+
* show, and no flat group is invented as a substitute. A provider without the
|
|
411
|
+
* grouped capability reports `unavailable`, not a retryable `error`.
|
|
412
|
+
*/
|
|
413
|
+
async function loadMappedShippingGroups(
|
|
414
|
+
cartId: string,
|
|
415
|
+
cartLines: CartLineState[],
|
|
416
|
+
previous: CheckoutShippingGroup[] | undefined,
|
|
417
|
+
context: ReturnType<typeof getStoreContext>,
|
|
418
|
+
): Promise<CheckoutShippingGroupsLoad> {
|
|
419
|
+
try {
|
|
420
|
+
const quote = await loadCheckoutShippingGroups(cartId, context)
|
|
421
|
+
const mapped = toCheckoutShippingGroups(quote, cartLines, previous)
|
|
422
|
+
return { groups: mapped.groups, productsByGroup: mapped.productsByGroup }
|
|
423
|
+
} catch (error) {
|
|
424
|
+
// The provider message is logged server-side and never forwarded across the
|
|
425
|
+
// Server Action boundary: it can carry backend/transport detail the shopper
|
|
426
|
+
// must not see. The UI gets one fixed, user-safe message.
|
|
427
|
+
logServerError('loadCheckoutShippingGroups', error)
|
|
428
|
+
const shippingState = toShippingState(error)
|
|
429
|
+
return {
|
|
430
|
+
groups: [],
|
|
431
|
+
productsByGroup: {},
|
|
432
|
+
error:
|
|
433
|
+
shippingState === 'unavailable' ? unsupportedShippingMessage : quoteShippingErrorMessage,
|
|
434
|
+
shippingState,
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
297
439
|
/**
|
|
298
440
|
* Validate and persist the checkout address against the cart region's eligible
|
|
299
|
-
* countries, then load the
|
|
300
|
-
* A malformed or ineligible address returns structured per-field errors
|
|
301
|
-
* never advances.
|
|
441
|
+
* countries, then load the backend's grouped delivery quote and the recalculated
|
|
442
|
+
* totals. A malformed or ineligible address returns structured per-field errors
|
|
443
|
+
* and never advances.
|
|
444
|
+
*
|
|
445
|
+
* Delivery groups come from the grouped quote, mapped 1:1 — the flat option list
|
|
446
|
+
* is never wrapped into a single group (design D7).
|
|
302
447
|
*/
|
|
303
448
|
export async function syncCheckoutAddressAction(
|
|
304
449
|
values: Record<string, unknown>,
|
|
@@ -315,14 +460,26 @@ export async function syncCheckoutAddressAction(
|
|
|
315
460
|
}
|
|
316
461
|
}
|
|
317
462
|
const cart = await saveShippingAddress(cartId, validation.address, context)
|
|
318
|
-
const
|
|
319
|
-
return {
|
|
463
|
+
const shipping = await loadMappedShippingGroups(cartId, cart.cart, undefined, context)
|
|
464
|
+
return {
|
|
465
|
+
ok: true,
|
|
466
|
+
cart,
|
|
467
|
+
shippingGroups: shipping.groups,
|
|
468
|
+
shippingGroupProducts: shipping.productsByGroup,
|
|
469
|
+
...(shipping.error
|
|
470
|
+
? { shippingError: shipping.error, shippingState: shipping.shippingState ?? 'error' }
|
|
471
|
+
: {}),
|
|
472
|
+
}
|
|
320
473
|
} catch (error) {
|
|
321
474
|
return { ok: false, error: toError(error, 'No se pudo validar la dirección.') }
|
|
322
475
|
}
|
|
323
476
|
}
|
|
324
477
|
|
|
325
|
-
/**
|
|
478
|
+
/**
|
|
479
|
+
* Apply ONE flat shipping method. Retained for hosts that still select a single
|
|
480
|
+
* method directly; the checkout consumes the grouped contract through
|
|
481
|
+
* `applyCheckoutShippingGroupsAction` instead. No checkout handler calls it.
|
|
482
|
+
*/
|
|
326
483
|
export async function selectShippingMethodAction(input: {
|
|
327
484
|
methodId: string
|
|
328
485
|
}): Promise<CheckoutActionResult> {
|
|
@@ -335,28 +492,456 @@ export async function selectShippingMethodAction(input: {
|
|
|
335
492
|
}
|
|
336
493
|
}
|
|
337
494
|
|
|
338
|
-
/**
|
|
339
|
-
|
|
495
|
+
/**
|
|
496
|
+
* Apply one selected option per backend group and return the RE-READ cart.
|
|
497
|
+
* The selections carry the backend group identity (`products`) plus the chosen
|
|
498
|
+
* `option_id`; the backend validates them and the cart totals stay
|
|
499
|
+
* authoritative. A rejected set is a recoverable error, never an invented
|
|
500
|
+
* shipment split.
|
|
501
|
+
*/
|
|
502
|
+
export async function applyCheckoutShippingGroupsAction(input: {
|
|
503
|
+
shippingGroups: ShippingGroupSelection[]
|
|
504
|
+
}): Promise<CheckoutActionResult> {
|
|
340
505
|
try {
|
|
506
|
+
if (!Array.isArray(input?.shippingGroups)) {
|
|
507
|
+
return { ok: false, error: 'No se recibieron opciones de envío.' }
|
|
508
|
+
}
|
|
341
509
|
const { cartId, context } = await ensureActiveCartId()
|
|
342
|
-
const
|
|
510
|
+
const cart = await applyCheckoutShippingGroups(cartId, input.shippingGroups, context)
|
|
511
|
+
return { ok: true, cart }
|
|
512
|
+
} catch (error) {
|
|
513
|
+
// Same boundary policy as the quote path: the provider/backend detail is
|
|
514
|
+
// logged server-side and the shopper gets one fixed, user-safe message. An
|
|
515
|
+
// unsupported provider is `unavailable` (retrying cannot help).
|
|
516
|
+
logServerError('applyCheckoutShippingGroupsAction', error)
|
|
517
|
+
const shippingState = toShippingState(error)
|
|
518
|
+
return {
|
|
519
|
+
ok: false,
|
|
520
|
+
error: shippingState === 'unavailable' ? unsupportedShippingMessage : applyShippingErrorMessage,
|
|
521
|
+
shippingState,
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Load the checkout data (countries, payment methods, cart) for the form.
|
|
528
|
+
*
|
|
529
|
+
* Delivery groups come from the backend grouped-shipping quote, mapped 1:1 —
|
|
530
|
+
* never from a local wrapper around the flat option list. A quote failure keeps
|
|
531
|
+
* the page usable: the cart still loads and `shippingError` reports the grouped
|
|
532
|
+
* delivery problem explicitly. `previousShippingGroups` keeps the shopper's
|
|
533
|
+
* per-group selections when the same group identity and option still exist.
|
|
534
|
+
*/
|
|
535
|
+
export async function loadCheckoutAction(
|
|
536
|
+
input: { previousShippingGroups?: CheckoutShippingGroup[] } = {},
|
|
537
|
+
): Promise<CheckoutActionResult> {
|
|
538
|
+
try {
|
|
539
|
+
const { cartId, context } = await ensureActiveCartId()
|
|
540
|
+
const [regionCountries, paymentMethods, cart] = await Promise.all([
|
|
343
541
|
loadCheckoutCountries(cartId, context),
|
|
344
542
|
loadPaymentMethods(context),
|
|
345
|
-
loadShippingMethods(cartId, context),
|
|
346
543
|
readCart(cartId, context),
|
|
347
544
|
])
|
|
545
|
+
const patch = cart ?? EMPTY_CART_STATE
|
|
546
|
+
const shipping = await loadMappedShippingGroups(
|
|
547
|
+
cartId,
|
|
548
|
+
patch.cart,
|
|
549
|
+
input?.previousShippingGroups,
|
|
550
|
+
context,
|
|
551
|
+
)
|
|
348
552
|
return {
|
|
349
553
|
ok: true,
|
|
350
|
-
cart:
|
|
554
|
+
cart: patch,
|
|
351
555
|
countries: regionCountries.map((country) => ({ value: country.code, label: country.name })),
|
|
352
556
|
paymentMethods,
|
|
353
|
-
|
|
557
|
+
shippingGroups: shipping.groups,
|
|
558
|
+
shippingGroupProducts: shipping.productsByGroup,
|
|
559
|
+
...(shipping.error
|
|
560
|
+
? { shippingError: shipping.error, shippingState: shipping.shippingState ?? 'error' }
|
|
561
|
+
: {}),
|
|
354
562
|
}
|
|
355
563
|
} catch (error) {
|
|
356
564
|
return { ok: false, error: toError(error, 'No se pudo cargar el checkout.') }
|
|
357
565
|
}
|
|
358
566
|
}
|
|
359
567
|
|
|
568
|
+
type CheckoutPrefillPayload = ReturnType<typeof prefillCheckoutFromCustomer> & {
|
|
569
|
+
shippingLocations: CheckoutLocationOptions
|
|
570
|
+
billingLocations: CheckoutLocationOptions
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
type CheckoutPrefillActionResult =
|
|
574
|
+
| ({ ok: true } & CheckoutPrefillPayload)
|
|
575
|
+
| { ok: false; error: string }
|
|
576
|
+
|
|
577
|
+
type CheckoutLocationsActionResult =
|
|
578
|
+
| { ok: true; options: CheckoutAddressOption[] }
|
|
579
|
+
| { ok: false; error: string }
|
|
580
|
+
|
|
581
|
+
type CheckoutSavedAddressActionResult =
|
|
582
|
+
| {
|
|
583
|
+
ok: true
|
|
584
|
+
savedAddresses: CheckoutSavedAddress[]
|
|
585
|
+
savedAddressId?: string
|
|
586
|
+
}
|
|
587
|
+
| { ok: false; error: string; fieldErrors?: Record<string, unknown> }
|
|
588
|
+
|
|
589
|
+
function toSavedAddress(address: Address, index: number): CheckoutSavedAddress {
|
|
590
|
+
const optional = (value: string | undefined): string | undefined => {
|
|
591
|
+
const trimmed = value?.trim()
|
|
592
|
+
return trimmed ? value : undefined
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
return {
|
|
596
|
+
id: address.id ?? `saved-${index}`,
|
|
597
|
+
...(optional(address.label) ? { label: address.label } : {}),
|
|
598
|
+
address: {
|
|
599
|
+
firstName: address.firstName,
|
|
600
|
+
lastName: address.lastName,
|
|
601
|
+
company: optional(address.company),
|
|
602
|
+
address1: address.address1 ?? '',
|
|
603
|
+
address2: optional(address.address2),
|
|
604
|
+
city: address.city,
|
|
605
|
+
province: optional(address.province),
|
|
606
|
+
postalCode: optional(address.postalCode),
|
|
607
|
+
countryCode: address.countryCode,
|
|
608
|
+
phone: optional(address.phone),
|
|
609
|
+
},
|
|
610
|
+
isDefaultShipping: address.isDefaultShipping,
|
|
611
|
+
isDefaultBilling: address.isDefaultBilling,
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
function toCreateAddressData(address: CheckoutAddressValues): CreateAddressData {
|
|
616
|
+
return {
|
|
617
|
+
firstName: address.firstName,
|
|
618
|
+
lastName: address.lastName,
|
|
619
|
+
company: address.company,
|
|
620
|
+
address1: address.address1,
|
|
621
|
+
address2: address.address2,
|
|
622
|
+
city: address.city,
|
|
623
|
+
province: address.province,
|
|
624
|
+
postalCode: address.postalCode,
|
|
625
|
+
countryCode: address.countryCode,
|
|
626
|
+
phone: address.phone,
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* Create an address in the authenticated customer's address book. The token is
|
|
632
|
+
* required, the payload is validated against the cart region, and the first
|
|
633
|
+
* saved address becomes the default shipping address by host policy.
|
|
634
|
+
*/
|
|
635
|
+
export async function createCheckoutAddressAction(
|
|
636
|
+
address: CheckoutAddressValues,
|
|
637
|
+
): Promise<CheckoutSavedAddressActionResult> {
|
|
638
|
+
try {
|
|
639
|
+
const context = getStoreContext()
|
|
640
|
+
const token = await readAuthToken(context)
|
|
641
|
+
if (!token) {
|
|
642
|
+
return { ok: false, error: 'Inicia sesión para guardar direcciones.' }
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
const { cartId } = await ensureActiveCartId()
|
|
646
|
+
const countries = await loadCheckoutCountries(cartId, context)
|
|
647
|
+
const validation = validateCustomerAddress(address, countries)
|
|
648
|
+
if (!validation.success) {
|
|
649
|
+
return {
|
|
650
|
+
ok: false,
|
|
651
|
+
error: 'Revisa la dirección antes de guardarla.',
|
|
652
|
+
fieldErrors: toStructuredFieldErrors(validation.errors),
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const existing = await loadCustomerAddresses(token)
|
|
657
|
+
const created = await createCustomerAddress(token, {
|
|
658
|
+
...toCreateAddressData(validation.address),
|
|
659
|
+
isDefaultShipping: existing.length === 0,
|
|
660
|
+
})
|
|
661
|
+
const savedAddresses = (await loadCustomerAddresses(token)).map(toSavedAddress)
|
|
662
|
+
|
|
663
|
+
return {
|
|
664
|
+
ok: true,
|
|
665
|
+
savedAddresses,
|
|
666
|
+
...(created.id ? { savedAddressId: created.id } : {}),
|
|
667
|
+
}
|
|
668
|
+
} catch (error) {
|
|
669
|
+
logServerError('createCheckoutAddressAction', error)
|
|
670
|
+
return {
|
|
671
|
+
ok: false,
|
|
672
|
+
error: toError(error, 'No se pudo guardar la dirección.'),
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/** Update a saved address; omitted optional values are preserved by the adapter. */
|
|
678
|
+
export async function updateCheckoutAddressAction(input: {
|
|
679
|
+
id: string
|
|
680
|
+
address: CheckoutAddressValues
|
|
681
|
+
}): Promise<CheckoutSavedAddressActionResult> {
|
|
682
|
+
try {
|
|
683
|
+
const context = getStoreContext()
|
|
684
|
+
const token = await readAuthToken(context)
|
|
685
|
+
if (!token) {
|
|
686
|
+
return { ok: false, error: 'Inicia sesión para actualizar direcciones.' }
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
const { cartId } = await ensureActiveCartId()
|
|
690
|
+
const countries = await loadCheckoutCountries(cartId, context)
|
|
691
|
+
const validation = validateCustomerAddress(input.address, countries)
|
|
692
|
+
if (!validation.success) {
|
|
693
|
+
return {
|
|
694
|
+
ok: false,
|
|
695
|
+
error: 'Revisa la dirección antes de guardarla.',
|
|
696
|
+
fieldErrors: toStructuredFieldErrors(validation.errors),
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
await updateCustomerAddress(token, input.id, toCreateAddressData(validation.address))
|
|
701
|
+
const savedAddresses = (await loadCustomerAddresses(token)).map(toSavedAddress)
|
|
702
|
+
|
|
703
|
+
return { ok: true, savedAddresses, savedAddressId: input.id }
|
|
704
|
+
} catch (error) {
|
|
705
|
+
logServerError('updateCheckoutAddressAction', error)
|
|
706
|
+
return {
|
|
707
|
+
ok: false,
|
|
708
|
+
error: toError(error, 'No se pudo actualizar la dirección.'),
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/** Delete a saved address; the backend ownership check is authoritative. */
|
|
714
|
+
export async function deleteCheckoutAddressAction(input: {
|
|
715
|
+
id: string
|
|
716
|
+
}): Promise<CheckoutSavedAddressActionResult> {
|
|
717
|
+
try {
|
|
718
|
+
const context = getStoreContext()
|
|
719
|
+
const token = await readAuthToken(context)
|
|
720
|
+
if (!token) {
|
|
721
|
+
return { ok: false, error: 'Inicia sesión para eliminar direcciones.' }
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
await deleteCustomerAddress(token, input.id)
|
|
725
|
+
const savedAddresses = (await loadCustomerAddresses(token)).map(toSavedAddress)
|
|
726
|
+
|
|
727
|
+
return { ok: true, savedAddresses, savedAddressId: input.id }
|
|
728
|
+
} catch (error) {
|
|
729
|
+
logServerError('deleteCheckoutAddressAction', error)
|
|
730
|
+
return {
|
|
731
|
+
ok: false,
|
|
732
|
+
error: toError(error, 'No se pudo eliminar la dirección.'),
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* Resolve the authenticated customer's profile and saved addresses and map
|
|
739
|
+
* them to checkout prefill. Cart/shopper values supplied by the caller win;
|
|
740
|
+
* a customer-read failure returns a non-blocking `customerUnavailable` result
|
|
741
|
+
* without claiming prefill.
|
|
742
|
+
*/
|
|
743
|
+
export async function loadCheckoutPrefillAction(
|
|
744
|
+
input: {
|
|
745
|
+
contact?: CheckoutContactValues
|
|
746
|
+
shippingAddress?: CheckoutAddressValues
|
|
747
|
+
billingAddress?: CheckoutAddressValues
|
|
748
|
+
sameAsShipping?: boolean
|
|
749
|
+
} = {},
|
|
750
|
+
): Promise<CheckoutPrefillActionResult> {
|
|
751
|
+
try {
|
|
752
|
+
const { cartId, context } = await ensureActiveCartId()
|
|
753
|
+
const regionCountries = await loadCheckoutCountries(cartId, context)
|
|
754
|
+
const countries = regionCountries.map((country) => ({
|
|
755
|
+
value: country.code,
|
|
756
|
+
label: country.name,
|
|
757
|
+
}))
|
|
758
|
+
const shippingLocations: CheckoutLocationOptions = {
|
|
759
|
+
countries,
|
|
760
|
+
provinces: [],
|
|
761
|
+
cities: [],
|
|
762
|
+
}
|
|
763
|
+
const billingLocations: CheckoutLocationOptions = {
|
|
764
|
+
countries,
|
|
765
|
+
provinces: [],
|
|
766
|
+
cities: [],
|
|
767
|
+
}
|
|
768
|
+
const cartInput = {
|
|
769
|
+
contact: input.contact,
|
|
770
|
+
shippingAddress: input.shippingAddress,
|
|
771
|
+
billingAddress: input.billingAddress,
|
|
772
|
+
sameAsShipping: input.sameAsShipping,
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
const token = await readAuthToken(context)
|
|
776
|
+
if (!token) {
|
|
777
|
+
const result = prefillCheckoutFromCustomer({
|
|
778
|
+
cart: cartInput,
|
|
779
|
+
shippingLocations,
|
|
780
|
+
billingLocations,
|
|
781
|
+
})
|
|
782
|
+
return { ok: true, ...result, shippingLocations, billingLocations }
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
try {
|
|
786
|
+
const customer = await loadCustomer(token)
|
|
787
|
+
if (!customer) {
|
|
788
|
+
const result = prefillCheckoutFromCustomer({
|
|
789
|
+
cart: cartInput,
|
|
790
|
+
shippingLocations,
|
|
791
|
+
billingLocations,
|
|
792
|
+
})
|
|
793
|
+
return { ok: true, ...result, shippingLocations, billingLocations }
|
|
794
|
+
}
|
|
795
|
+
const addresses = await loadCustomerAddresses(token)
|
|
796
|
+
const savedAddresses = addresses.map(toSavedAddress)
|
|
797
|
+
const result = prefillCheckoutFromCustomer({
|
|
798
|
+
cart: cartInput,
|
|
799
|
+
customer: {
|
|
800
|
+
id: customer.id,
|
|
801
|
+
email: customer.email,
|
|
802
|
+
firstName: customer.firstName,
|
|
803
|
+
lastName: customer.lastName,
|
|
804
|
+
phone: customer.phone,
|
|
805
|
+
},
|
|
806
|
+
savedAddresses,
|
|
807
|
+
shippingLocations,
|
|
808
|
+
billingLocations,
|
|
809
|
+
})
|
|
810
|
+
return { ok: true, ...result, shippingLocations, billingLocations }
|
|
811
|
+
} catch (error) {
|
|
812
|
+
logServerError('loadCheckoutPrefillAction', error)
|
|
813
|
+
const result = prefillCheckoutFromCustomer({
|
|
814
|
+
cart: cartInput,
|
|
815
|
+
customerState: 'unavailable',
|
|
816
|
+
shippingLocations,
|
|
817
|
+
billingLocations,
|
|
818
|
+
})
|
|
819
|
+
return { ok: true, ...result, shippingLocations, billingLocations }
|
|
820
|
+
}
|
|
821
|
+
} catch (error) {
|
|
822
|
+
return {
|
|
823
|
+
ok: false,
|
|
824
|
+
error: toError(error, 'No se pudo cargar la información del cliente.'),
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/** Load the backend geo-reference options for a province or city level. */
|
|
830
|
+
export async function loadCheckoutLocationsAction(input: {
|
|
831
|
+
kind: 'shipping' | 'billing'
|
|
832
|
+
level: 'countries' | 'provinces' | 'cities'
|
|
833
|
+
countryCode?: string
|
|
834
|
+
provinceCode?: string
|
|
835
|
+
}): Promise<CheckoutLocationsActionResult> {
|
|
836
|
+
try {
|
|
837
|
+
if (input.level === 'provinces') {
|
|
838
|
+
if (!input.countryCode) return { ok: false, error: 'Selecciona un país.' }
|
|
839
|
+
return {
|
|
840
|
+
ok: true,
|
|
841
|
+
options: await loadGeoProvinces(input.countryCode.toLowerCase()),
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
if (input.level === 'cities') {
|
|
845
|
+
if (!input.provinceCode) return { ok: false, error: 'Selecciona una provincia.' }
|
|
846
|
+
return {
|
|
847
|
+
ok: true,
|
|
848
|
+
options: await loadGeoCities(
|
|
849
|
+
input.provinceCode,
|
|
850
|
+
input.countryCode?.toLowerCase(),
|
|
851
|
+
),
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
return { ok: false, error: 'Selecciona un país.' }
|
|
855
|
+
} catch (error) {
|
|
856
|
+
return { ok: false, error: toError(error, 'No se pudieron cargar las opciones.') }
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/**
|
|
861
|
+
* Validate and persist the structured checkout address (and a distinct billing
|
|
862
|
+
* address) against the cart region, then return the recalculated cart and the
|
|
863
|
+
* backend's grouped delivery options.
|
|
864
|
+
*
|
|
865
|
+
* The delivery groups are requested again after the address change (they depend
|
|
866
|
+
* on it) and mapped 1:1. `previousShippingGroups` reconciles the shopper's
|
|
867
|
+
* per-group selections by stable group identity. A quote failure keeps the
|
|
868
|
+
* address result usable and reports `shippingError` instead of failing the
|
|
869
|
+
* whole sync or falling back to one flat group.
|
|
870
|
+
*/
|
|
871
|
+
export async function syncCheckoutAddressStructuredAction(input: {
|
|
872
|
+
contact: CheckoutContactValues
|
|
873
|
+
shippingAddress: CheckoutAddressValues
|
|
874
|
+
billingAddress?: CheckoutAddressValues
|
|
875
|
+
sameAsShipping: boolean
|
|
876
|
+
previousShippingGroups?: CheckoutShippingGroup[]
|
|
877
|
+
}): Promise<CheckoutActionResult> {
|
|
878
|
+
try {
|
|
879
|
+
const { cartId, context } = await ensureActiveCartId()
|
|
880
|
+
const countries = await loadCheckoutCountries(cartId, context)
|
|
881
|
+
const validation = validateAddress(
|
|
882
|
+
{
|
|
883
|
+
email: input.contact.email,
|
|
884
|
+
firstName: input.shippingAddress.firstName,
|
|
885
|
+
lastName: input.shippingAddress.lastName,
|
|
886
|
+
address1: input.shippingAddress.address1,
|
|
887
|
+
address2: input.shippingAddress.address2,
|
|
888
|
+
company: input.shippingAddress.company,
|
|
889
|
+
city: input.shippingAddress.city,
|
|
890
|
+
province: input.shippingAddress.province ?? '',
|
|
891
|
+
postalCode: input.shippingAddress.postalCode ?? '',
|
|
892
|
+
countryCode: input.shippingAddress.countryCode,
|
|
893
|
+
phone: input.shippingAddress.phone ?? '',
|
|
894
|
+
},
|
|
895
|
+
countries,
|
|
896
|
+
)
|
|
897
|
+
if (!validation.success) {
|
|
898
|
+
return {
|
|
899
|
+
ok: false,
|
|
900
|
+
error: 'Revisa los datos de la dirección.',
|
|
901
|
+
fieldErrors: toStructuredFieldErrors(validation.errors),
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
const cart = await saveShippingAddress(cartId, validation.address, context)
|
|
906
|
+
if (!input.sameAsShipping && input.billingAddress) {
|
|
907
|
+
await saveBillingAddress(
|
|
908
|
+
cartId,
|
|
909
|
+
{
|
|
910
|
+
firstName: input.billingAddress.firstName,
|
|
911
|
+
lastName: input.billingAddress.lastName,
|
|
912
|
+
address1: input.billingAddress.address1,
|
|
913
|
+
address2: input.billingAddress.address2,
|
|
914
|
+
company: input.billingAddress.company,
|
|
915
|
+
city: input.billingAddress.city,
|
|
916
|
+
province: input.billingAddress.province ?? '',
|
|
917
|
+
postalCode: input.billingAddress.postalCode,
|
|
918
|
+
countryCode: input.billingAddress.countryCode,
|
|
919
|
+
phone: input.billingAddress.phone ?? '',
|
|
920
|
+
},
|
|
921
|
+
context,
|
|
922
|
+
)
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
const shipping = await loadMappedShippingGroups(
|
|
926
|
+
cartId,
|
|
927
|
+
cart.cart,
|
|
928
|
+
input.previousShippingGroups,
|
|
929
|
+
context,
|
|
930
|
+
)
|
|
931
|
+
return {
|
|
932
|
+
ok: true,
|
|
933
|
+
cart,
|
|
934
|
+
shippingGroups: shipping.groups,
|
|
935
|
+
shippingGroupProducts: shipping.productsByGroup,
|
|
936
|
+
...(shipping.error
|
|
937
|
+
? { shippingError: shipping.error, shippingState: shipping.shippingState ?? 'error' }
|
|
938
|
+
: {}),
|
|
939
|
+
}
|
|
940
|
+
} catch (error) {
|
|
941
|
+
return { ok: false, error: toError(error, 'No se pudo validar la dirección.') }
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
|
|
360
945
|
/**
|
|
361
946
|
* Clear the active cart after a confirmed order. A cookie-write failure must
|
|
362
947
|
* NOT be reported as an ordinary failure — the order already exists — so it is
|
|
@@ -377,14 +962,22 @@ async function clearConfirmedSession(
|
|
|
377
962
|
}
|
|
378
963
|
|
|
379
964
|
/**
|
|
380
|
-
* Place the order exactly once.
|
|
381
|
-
*
|
|
382
|
-
*
|
|
383
|
-
*
|
|
384
|
-
*
|
|
385
|
-
* the
|
|
965
|
+
* Place the order exactly once.
|
|
966
|
+
*
|
|
967
|
+
* When the shopper's per-group selections are supplied, every selected group is
|
|
968
|
+
* applied to the cart FIRST and the runtime re-reads the authoritative cart
|
|
969
|
+
* (design D6); a rejected group set is a recoverable error and never completes
|
|
970
|
+
* the order, and an explicitly EMPTY set is refused before payment. The approved
|
|
971
|
+
* manual TEST payment is then applied after shipping
|
|
972
|
+
* totals are final, and the cart is completed with its native discriminator. On
|
|
973
|
+
* a confirmed order the active cart is cleared and the receipt recorded. If the
|
|
974
|
+
* order committed but the session cookie could not be updated, the result is
|
|
975
|
+
* `unresolved` (reconcile the active committed cart) so the client never treats
|
|
976
|
+
* a committed order as a retryable failure.
|
|
386
977
|
*/
|
|
387
|
-
export async function placeOrderAction(
|
|
978
|
+
export async function placeOrderAction(
|
|
979
|
+
input: { shippingGroups?: ShippingGroupSelection[] } = {},
|
|
980
|
+
): Promise<PlaceOrderResult> {
|
|
388
981
|
try {
|
|
389
982
|
const context = getStoreContext()
|
|
390
983
|
const session = await readHostSession(context)
|
|
@@ -392,6 +985,31 @@ export async function placeOrderAction(): Promise<PlaceOrderResult> {
|
|
|
392
985
|
return { status: 'error', message: 'No hay un carrito activo.' }
|
|
393
986
|
}
|
|
394
987
|
const cartId = session.cartId
|
|
988
|
+
const shippingGroups = input?.shippingGroups
|
|
989
|
+
if (shippingGroups) {
|
|
990
|
+
// An explicitly empty selection set means the delivery step was not
|
|
991
|
+
// completed: block the order before payment (design D6) instead of
|
|
992
|
+
// paying for an unselected shipment. Omitting the input entirely keeps
|
|
993
|
+
// the pre-grouped callers working.
|
|
994
|
+
if (shippingGroups.length === 0) {
|
|
995
|
+
return {
|
|
996
|
+
status: 'error',
|
|
997
|
+
message: 'Selecciona una opción de envío para cada grupo antes de pagar.',
|
|
998
|
+
code: 'SHIPPING_GROUPS_REQUIRED',
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
try {
|
|
1002
|
+
await applyCheckoutShippingGroups(cartId, shippingGroups, context)
|
|
1003
|
+
} catch (error) {
|
|
1004
|
+
// Logged server-side only; the shopper gets a fixed recoverable message.
|
|
1005
|
+
logServerError('applyCheckoutShippingGroups', error)
|
|
1006
|
+
return {
|
|
1007
|
+
status: 'error',
|
|
1008
|
+
message: 'No se pudo aplicar el envío seleccionado. Reintenta.',
|
|
1009
|
+
code: 'SHIPPING_GROUPS_REJECTED',
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
395
1013
|
try {
|
|
396
1014
|
await applyPayment(cartId, context)
|
|
397
1015
|
} catch (error) {
|