@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
|
@@ -15,41 +15,74 @@
|
|
|
15
15
|
// blindly retried; reconciliation uses the active cart id when no completed
|
|
16
16
|
// receipt cookie exists yet.
|
|
17
17
|
|
|
18
|
-
import type {
|
|
19
|
-
import type {
|
|
18
|
+
import type { AccountAddressView, 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'
|
|
35
|
+
import type { OrdersPage, OrdersQuery } from '@thorprovider/blocks/ports'
|
|
20
36
|
import {
|
|
21
37
|
EMPTY_CART_STATE,
|
|
22
38
|
addVariant,
|
|
39
|
+
applyCheckoutShippingGroups,
|
|
23
40
|
applyLineDelta,
|
|
24
41
|
applyPayment,
|
|
42
|
+
assignCartToCustomer,
|
|
25
43
|
authenticate,
|
|
26
44
|
completeOrder,
|
|
27
45
|
createGuestCart,
|
|
46
|
+
createCustomerAddress,
|
|
47
|
+
deleteCustomerAddress,
|
|
28
48
|
endSession,
|
|
29
49
|
loadCheckoutCountries,
|
|
50
|
+
loadCartCustomerId,
|
|
51
|
+
loadCheckoutShippingGroups,
|
|
52
|
+
loadCustomer,
|
|
53
|
+
loadCustomerAddresses,
|
|
54
|
+
loadGeoCities,
|
|
55
|
+
loadGeoProvinces,
|
|
56
|
+
loadOrderHistoryPage,
|
|
30
57
|
loadOrders,
|
|
31
58
|
loadOrdersPage,
|
|
32
59
|
loadPaymentMethods,
|
|
33
60
|
loadProductDetail,
|
|
34
|
-
loadShippingMethods,
|
|
35
61
|
readCart,
|
|
36
62
|
reconcileOrder,
|
|
63
|
+
prefillCheckoutFromCustomer,
|
|
37
64
|
registerShopper,
|
|
38
65
|
removeLine,
|
|
39
66
|
resolveProductCartTarget,
|
|
67
|
+
saveBillingAddress,
|
|
40
68
|
saveShippingAddress,
|
|
41
69
|
selectShipping,
|
|
42
70
|
setLineQuantity,
|
|
43
71
|
toCheckoutFieldErrors,
|
|
44
|
-
|
|
72
|
+
toCheckoutShippingGroups,
|
|
73
|
+
updateCustomerAddress,
|
|
74
|
+
updateCustomerProfile,
|
|
75
|
+
getHostCommerceProvider,
|
|
45
76
|
validateAddress,
|
|
77
|
+
validateCustomerAddress,
|
|
46
78
|
type AddressInput,
|
|
47
79
|
type CartStatePatch,
|
|
80
|
+
type HostCommerceProvider,
|
|
48
81
|
type PlaceOrderResult,
|
|
49
82
|
} from './commerce'
|
|
50
83
|
import { readAccountSession } from './account-session'
|
|
51
84
|
import { accountIdentitySchema, type AccountIdentity } from './account-session.core'
|
|
52
|
-
import { getStoreContext } from './store-context'
|
|
85
|
+
import { getDataSource, getStoreContext } from './store-context'
|
|
53
86
|
import {
|
|
54
87
|
bindHostSessionCart,
|
|
55
88
|
clearAuthToken,
|
|
@@ -58,6 +91,7 @@ import {
|
|
|
58
91
|
readHostSession,
|
|
59
92
|
writeAuthToken,
|
|
60
93
|
} from './session'
|
|
94
|
+
import type { AccountProfileMetadataPatch, AccountProfilePayload } from './account-profile'
|
|
61
95
|
|
|
62
96
|
// A `'use server'` module may export ONLY async functions. Next/Turbopack's
|
|
63
97
|
// server-actions transform registers every export as a runtime server
|
|
@@ -70,6 +104,13 @@ type CartActionResult =
|
|
|
70
104
|
| { ok: true; cart: CartStatePatch }
|
|
71
105
|
| { ok: false; error: string }
|
|
72
106
|
|
|
107
|
+
/**
|
|
108
|
+
* The delivery state a failed grouped-shipping operation reports: `error` is a
|
|
109
|
+
* recoverable failure (retry the quote/apply), `unavailable` is a provider that
|
|
110
|
+
* cannot serve grouped delivery at all (no retry promise).
|
|
111
|
+
*/
|
|
112
|
+
type CheckoutShippingState = 'error' | 'unavailable'
|
|
113
|
+
|
|
73
114
|
/** Structured result for a checkout action. */
|
|
74
115
|
type CheckoutActionResult =
|
|
75
116
|
| {
|
|
@@ -77,10 +118,38 @@ type CheckoutActionResult =
|
|
|
77
118
|
cart: CartStatePatch
|
|
78
119
|
countries?: { value: string; label: string }[]
|
|
79
120
|
paymentMethods?: PaymentMethod[]
|
|
80
|
-
|
|
81
|
-
|
|
121
|
+
/** The backend group quote mapped 1:1 to the presentation contract. */
|
|
122
|
+
shippingGroups?: CheckoutShippingGroup[]
|
|
123
|
+
/** Presentation group id -> the backend `products` to submit on apply. */
|
|
124
|
+
shippingGroupProducts?: Record<string, string[]>
|
|
125
|
+
/**
|
|
126
|
+
* A grouped-shipping load failure is reported here WITHOUT failing the
|
|
127
|
+
* whole checkout load (design D7). No flat group is invented instead.
|
|
128
|
+
*/
|
|
129
|
+
shippingError?: string
|
|
130
|
+
/** The delivery state that accompanies `shippingError`. */
|
|
131
|
+
shippingState?: CheckoutShippingState
|
|
132
|
+
fieldErrors?: Record<string, unknown>
|
|
82
133
|
}
|
|
83
|
-
| {
|
|
134
|
+
| {
|
|
135
|
+
ok: false
|
|
136
|
+
error: string
|
|
137
|
+
fieldErrors?: Record<string, unknown>
|
|
138
|
+
/** Stable machine code for a failure the UI must treat specially. */
|
|
139
|
+
code?: string
|
|
140
|
+
/** Set by a failed grouped apply so the UI can distinguish unsupported. */
|
|
141
|
+
shippingState?: CheckoutShippingState
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Raised when a checkout action requires an authenticated customer. */
|
|
145
|
+
class CheckoutAuthError extends Error {
|
|
146
|
+
readonly code = 'AUTH_REQUIRED'
|
|
147
|
+
|
|
148
|
+
constructor() {
|
|
149
|
+
super('Inicia sesión para continuar con el checkout.')
|
|
150
|
+
this.name = 'CheckoutAuthError'
|
|
151
|
+
}
|
|
152
|
+
}
|
|
84
153
|
|
|
85
154
|
/**
|
|
86
155
|
* Structured result for a login/register auth action. It carries ONLY the
|
|
@@ -117,23 +186,59 @@ type OrdersPageActionResult =
|
|
|
117
186
|
| { ok: true; orders: AccountOrderView[]; count: number; limit: number; offset: number }
|
|
118
187
|
| { ok: false; error: string }
|
|
119
188
|
|
|
189
|
+
/** Structured result for one advanced order-history port query. */
|
|
190
|
+
type OrdersQueryPageActionResult =
|
|
191
|
+
| { ok: true; page: OrdersPage }
|
|
192
|
+
| { ok: false; error: string }
|
|
193
|
+
|
|
120
194
|
/** Basic email shape check; a boundary guard, not a full RFC validation. */
|
|
121
195
|
const EMAIL_PATTERN = /\S+@\S+\.\S+/
|
|
122
196
|
|
|
197
|
+
/** The runtime/provider code for a provider without grouped-shipping support. */
|
|
198
|
+
const UNSUPPORTED_SHIPPING_GROUPS_CODE = 'CHECKOUT_SHIPPING_GROUPS_UNSUPPORTED'
|
|
199
|
+
|
|
200
|
+
/** The fixed, user-safe copy for each grouped-shipping failure. */
|
|
201
|
+
const quoteShippingErrorMessage = 'No se pudieron cargar las opciones de envío. Reintenta.'
|
|
202
|
+
const applyShippingErrorMessage = 'No se pudo aplicar el envío seleccionado. Reintenta.'
|
|
203
|
+
const unsupportedShippingMessage = 'El envío agrupado no está disponible en esta tienda.'
|
|
204
|
+
|
|
205
|
+
/** The typed code carried by a runtime/provider error, when it has one. */
|
|
206
|
+
function errorCode(error: unknown): string | undefined {
|
|
207
|
+
if (!error || typeof error !== 'object' || !('code' in error)) return undefined
|
|
208
|
+
const code = (error as { code?: unknown }).code
|
|
209
|
+
return typeof code === 'string' ? code : undefined
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Map a grouped-shipping failure to the delivery state the checkout must show:
|
|
214
|
+
* a provider without the capability is `unavailable` (no retry can fix it),
|
|
215
|
+
* every other failure is a recoverable `error`.
|
|
216
|
+
*/
|
|
217
|
+
function toShippingState(error: unknown): CheckoutShippingState {
|
|
218
|
+
return errorCode(error) === UNSUPPORTED_SHIPPING_GROUPS_CODE ? 'unavailable' : 'error'
|
|
219
|
+
}
|
|
220
|
+
|
|
123
221
|
/** Log a non-secret context line for a caught server error (never a secret). */
|
|
124
222
|
function logServerError(scope: string, error: unknown): void {
|
|
125
223
|
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 })
|
|
224
|
+
console.error(`[storefront/actions] ${scope} failed`, { message, code: errorCode(error) })
|
|
131
225
|
}
|
|
132
226
|
|
|
133
227
|
function toError(error: unknown, fallback: string): string {
|
|
134
228
|
return error instanceof Error && error.message.trim() !== '' ? error.message : fallback
|
|
135
229
|
}
|
|
136
230
|
|
|
231
|
+
/** Preserve the auth code so the checkout boot can send the shopper to login. */
|
|
232
|
+
function toCheckoutActionError(
|
|
233
|
+
error: unknown,
|
|
234
|
+
fallback: string,
|
|
235
|
+
): { ok: false; error: string; code?: string } {
|
|
236
|
+
if (error instanceof CheckoutAuthError) {
|
|
237
|
+
return { ok: false, error: error.message, code: error.code }
|
|
238
|
+
}
|
|
239
|
+
return { ok: false, error: toError(error, fallback) }
|
|
240
|
+
}
|
|
241
|
+
|
|
137
242
|
/**
|
|
138
243
|
* Allowlist a backend customer to the serializable display identity before it
|
|
139
244
|
* crosses the Server Action boundary. Returns `null` for a confirmed anonymous
|
|
@@ -148,30 +253,122 @@ function toDisplayIdentity(customer: Customer | null): AccountIdentity | null |
|
|
|
148
253
|
return parsed.success ? parsed.data : undefined
|
|
149
254
|
}
|
|
150
255
|
|
|
256
|
+
type ActiveCartContext = {
|
|
257
|
+
cartId: string
|
|
258
|
+
context: ReturnType<typeof getStoreContext>
|
|
259
|
+
token: string | null
|
|
260
|
+
provider: HostCommerceProvider
|
|
261
|
+
customerId: string | null
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Read the authenticated customer without letting an expired token break a cart. */
|
|
265
|
+
async function resolveHostCustomer(token: string | null) {
|
|
266
|
+
if (!token) return null
|
|
267
|
+
try {
|
|
268
|
+
return await loadCustomer(token)
|
|
269
|
+
} catch (error) {
|
|
270
|
+
logServerError('resolveHostCustomer', error)
|
|
271
|
+
return null
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
151
275
|
/**
|
|
152
|
-
* Resolve the active cart
|
|
153
|
-
*
|
|
154
|
-
*
|
|
155
|
-
*
|
|
276
|
+
* Resolve the active cart for the current session.
|
|
277
|
+
*
|
|
278
|
+
* When a customer token is present the provider carries it, so a newly created
|
|
279
|
+
* cart belongs to the customer. If the session holds a guest cart, the cart is
|
|
280
|
+
* transferred to the authenticated customer before reuse; a cart that already
|
|
281
|
+
* belongs to a different customer is never reassigned — a new cart is created
|
|
282
|
+
* instead. `requireAuth` is used by checkout actions and fails closed.
|
|
156
283
|
*/
|
|
157
|
-
async function ensureActiveCartId(
|
|
284
|
+
async function ensureActiveCartId(
|
|
285
|
+
options: { requireAuth?: boolean } = {},
|
|
286
|
+
): Promise<ActiveCartContext> {
|
|
158
287
|
const context = getStoreContext()
|
|
288
|
+
const token = await readAuthToken(context)
|
|
289
|
+
const customer = await resolveHostCustomer(token)
|
|
290
|
+
|
|
291
|
+
// Real mode requires an authenticated customer. Mock mode is an explicit,
|
|
292
|
+
// labelled fixture with no auth surface, so it keeps the demo checkout usable.
|
|
293
|
+
const authRequired = options.requireAuth === true && getDataSource() === 'medusa'
|
|
294
|
+
if (authRequired && !customer) throw new CheckoutAuthError()
|
|
295
|
+
|
|
296
|
+
const provider = getHostCommerceProvider(customer ? token : null)
|
|
159
297
|
const session = await readHostSession(context)
|
|
298
|
+
|
|
160
299
|
if (session?.cartId) {
|
|
161
|
-
|
|
162
|
-
|
|
300
|
+
try {
|
|
301
|
+
const existing = await readCart(session.cartId, context, provider)
|
|
302
|
+
if (existing && !existing.cartCompleted) {
|
|
303
|
+
if (!customer) {
|
|
304
|
+
return {
|
|
305
|
+
cartId: session.cartId,
|
|
306
|
+
context,
|
|
307
|
+
token,
|
|
308
|
+
provider,
|
|
309
|
+
customerId: null,
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const owner = await loadCartCustomerId(session.cartId, context, provider)
|
|
314
|
+
if (owner === customer.id) {
|
|
315
|
+
return {
|
|
316
|
+
cartId: session.cartId,
|
|
317
|
+
context,
|
|
318
|
+
token,
|
|
319
|
+
provider,
|
|
320
|
+
customerId: customer.id,
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
if (owner === null) {
|
|
325
|
+
const linked = await assignCartToCustomer(session.cartId, context, provider)
|
|
326
|
+
if (linked.cartId) {
|
|
327
|
+
await bindHostSessionCart(context, linked.cartId)
|
|
328
|
+
return {
|
|
329
|
+
cartId: linked.cartId,
|
|
330
|
+
context,
|
|
331
|
+
token,
|
|
332
|
+
provider,
|
|
333
|
+
customerId: customer.id,
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
} catch (error) {
|
|
339
|
+
// A stale, foreign-channel or otherwise unreadable cart is replaced.
|
|
340
|
+
logServerError('ensureActiveCartId', error)
|
|
341
|
+
}
|
|
163
342
|
}
|
|
164
|
-
|
|
343
|
+
|
|
344
|
+
const created = await createGuestCart(context, provider)
|
|
165
345
|
if (!created.cartId) throw new Error('Cart creation returned no id')
|
|
346
|
+
|
|
347
|
+
if (customer) {
|
|
348
|
+
try {
|
|
349
|
+
await assignCartToCustomer(created.cartId, context, provider)
|
|
350
|
+
} catch (error) {
|
|
351
|
+
// The authenticated create normally links the customer; a transfer failure
|
|
352
|
+
// is logged and the backend ownership check remains authoritative.
|
|
353
|
+
logServerError('assignCartToCustomer', error)
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
166
357
|
await bindHostSessionCart(context, created.cartId)
|
|
167
|
-
return {
|
|
358
|
+
return {
|
|
359
|
+
cartId: created.cartId,
|
|
360
|
+
context,
|
|
361
|
+
token,
|
|
362
|
+
provider,
|
|
363
|
+
customerId: customer?.id ?? null,
|
|
364
|
+
}
|
|
168
365
|
}
|
|
169
366
|
|
|
170
367
|
/** Ensure a guest cart exists and return its authoritative snapshot. */
|
|
171
368
|
export async function ensureCartAction(): Promise<CartActionResult> {
|
|
172
369
|
try {
|
|
173
|
-
const { cartId, context } = await ensureActiveCartId()
|
|
174
|
-
return { ok: true, cart: (await readCart(cartId, context)) ?? EMPTY_CART_STATE }
|
|
370
|
+
const { cartId, context, provider } = await ensureActiveCartId()
|
|
371
|
+
return { ok: true, cart: (await readCart(cartId, context, provider)) ?? EMPTY_CART_STATE }
|
|
175
372
|
} catch (error) {
|
|
176
373
|
return { ok: false, error: toError(error, 'No se pudo iniciar el carrito.') }
|
|
177
374
|
}
|
|
@@ -185,8 +382,11 @@ export async function addToCartAction(input: {
|
|
|
185
382
|
try {
|
|
186
383
|
if (!input?.variantId) return { ok: false, error: 'Selecciona una variante antes de agregar.' }
|
|
187
384
|
const quantity = Number.isFinite(input.quantity) && input.quantity > 0 ? Math.floor(input.quantity) : 1
|
|
188
|
-
const { cartId, context } = await ensureActiveCartId()
|
|
189
|
-
return {
|
|
385
|
+
const { cartId, context, provider } = await ensureActiveCartId()
|
|
386
|
+
return {
|
|
387
|
+
ok: true,
|
|
388
|
+
cart: await addVariant(cartId, input.variantId, quantity, context, provider),
|
|
389
|
+
}
|
|
190
390
|
} catch (error) {
|
|
191
391
|
return { ok: false, error: toError(error, 'No se pudo agregar el producto.') }
|
|
192
392
|
}
|
|
@@ -215,8 +415,11 @@ export async function addToCartByHandleAction(input: {
|
|
|
215
415
|
const { detail } = await loadProductDetail(productHandle)
|
|
216
416
|
const target = resolveProductCartTarget(detail)
|
|
217
417
|
if (!target.ok) return { ok: false, error: target.error }
|
|
218
|
-
const { cartId, context } = await ensureActiveCartId()
|
|
219
|
-
return {
|
|
418
|
+
const { cartId, context, provider } = await ensureActiveCartId()
|
|
419
|
+
return {
|
|
420
|
+
ok: true,
|
|
421
|
+
cart: await addVariant(cartId, target.variantId, quantity, context, provider),
|
|
422
|
+
}
|
|
220
423
|
} catch (error) {
|
|
221
424
|
return { ok: false, error: toError(error, 'No se pudo agregar el producto.') }
|
|
222
425
|
}
|
|
@@ -230,10 +433,17 @@ export async function setLineQuantityAction(input: {
|
|
|
230
433
|
}): Promise<CartActionResult> {
|
|
231
434
|
try {
|
|
232
435
|
const quantity = Math.max(1, Math.floor(input.quantity))
|
|
233
|
-
const { cartId, context } = await ensureActiveCartId()
|
|
436
|
+
const { cartId, context, provider } = await ensureActiveCartId()
|
|
234
437
|
return {
|
|
235
438
|
ok: true,
|
|
236
|
-
cart: await setLineQuantity(
|
|
439
|
+
cart: await setLineQuantity(
|
|
440
|
+
cartId,
|
|
441
|
+
input.lineId,
|
|
442
|
+
input.merchandiseId,
|
|
443
|
+
quantity,
|
|
444
|
+
context,
|
|
445
|
+
provider,
|
|
446
|
+
),
|
|
237
447
|
}
|
|
238
448
|
} catch (error) {
|
|
239
449
|
return { ok: false, error: toError(error, 'No se pudo actualizar la cantidad.') }
|
|
@@ -250,8 +460,11 @@ export async function applyQuantityDeltaAction(input: {
|
|
|
250
460
|
delta: number
|
|
251
461
|
}): Promise<CartActionResult> {
|
|
252
462
|
try {
|
|
253
|
-
const { cartId, context } = await ensureActiveCartId()
|
|
254
|
-
return {
|
|
463
|
+
const { cartId, context, provider } = await ensureActiveCartId()
|
|
464
|
+
return {
|
|
465
|
+
ok: true,
|
|
466
|
+
cart: await applyLineDelta(cartId, input.lineId, input.delta, context, provider),
|
|
467
|
+
}
|
|
255
468
|
} catch (error) {
|
|
256
469
|
return { ok: false, error: toError(error, 'No se pudo actualizar la cantidad.') }
|
|
257
470
|
}
|
|
@@ -260,8 +473,8 @@ export async function applyQuantityDeltaAction(input: {
|
|
|
260
473
|
/** Remove a backend cart line by its line-item id. */
|
|
261
474
|
export async function removeLineAction(input: { lineId: string }): Promise<CartActionResult> {
|
|
262
475
|
try {
|
|
263
|
-
const { cartId, context } = await ensureActiveCartId()
|
|
264
|
-
return { ok: true, cart: await removeLine(cartId, input.lineId, context) }
|
|
476
|
+
const { cartId, context, provider } = await ensureActiveCartId()
|
|
477
|
+
return { ok: true, cart: await removeLine(cartId, input.lineId, context, provider) }
|
|
265
478
|
} catch (error) {
|
|
266
479
|
return { ok: false, error: toError(error, 'No se pudo quitar el producto.') }
|
|
267
480
|
}
|
|
@@ -279,6 +492,35 @@ export async function loadCartStateAction(): Promise<CartStatePatch> {
|
|
|
279
492
|
}
|
|
280
493
|
}
|
|
281
494
|
|
|
495
|
+
const CONTACT_FIELD_NAMES = new Set(['email', 'firstName', 'lastName', 'phone'])
|
|
496
|
+
const ADDRESS_FIELD_NAMES = new Set([
|
|
497
|
+
'address1',
|
|
498
|
+
'address2',
|
|
499
|
+
'company',
|
|
500
|
+
'city',
|
|
501
|
+
'province',
|
|
502
|
+
'postalCode',
|
|
503
|
+
'countryCode',
|
|
504
|
+
'phone',
|
|
505
|
+
])
|
|
506
|
+
|
|
507
|
+
function toStructuredFieldErrors(
|
|
508
|
+
errors: Array<{ field: string; message: string }>,
|
|
509
|
+
): Record<string, unknown> {
|
|
510
|
+
const contact: Record<string, Array<{ message: string }>> = {}
|
|
511
|
+
const shippingAddress: Record<string, Array<{ message: string }>> = {}
|
|
512
|
+
const root: Record<string, Array<{ message: string }>> = {}
|
|
513
|
+
for (const error of errors) {
|
|
514
|
+
const bucket = CONTACT_FIELD_NAMES.has(error.field)
|
|
515
|
+
? contact
|
|
516
|
+
: ADDRESS_FIELD_NAMES.has(error.field)
|
|
517
|
+
? shippingAddress
|
|
518
|
+
: root
|
|
519
|
+
bucket[error.field] = [...(bucket[error.field] ?? []), { message: error.message }]
|
|
520
|
+
}
|
|
521
|
+
return { contact, shippingAddress, ...root }
|
|
522
|
+
}
|
|
523
|
+
|
|
282
524
|
function toAddressInput(values: Record<string, unknown>): AddressInput {
|
|
283
525
|
const str = (key: string) => (typeof values[key] === 'string' ? (values[key] as string) : '')
|
|
284
526
|
return {
|
|
@@ -294,18 +536,66 @@ function toAddressInput(values: Record<string, unknown>): AddressInput {
|
|
|
294
536
|
}
|
|
295
537
|
}
|
|
296
538
|
|
|
539
|
+
/** The mapped grouped-shipping surface of a checkout load. */
|
|
540
|
+
interface CheckoutShippingGroupsLoad {
|
|
541
|
+
groups: CheckoutShippingGroup[]
|
|
542
|
+
productsByGroup: Record<string, string[]>
|
|
543
|
+
error?: string
|
|
544
|
+
shippingState?: CheckoutShippingState
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* Request the backend grouped-shipping quote and map it to the presentation
|
|
549
|
+
* groups, resolving line membership against the CURRENT cart lines and keeping
|
|
550
|
+
* the shopper's previous selection when the group identity and option survive.
|
|
551
|
+
*
|
|
552
|
+
* A quote failure is not fatal for the checkout load (design D7): the caller
|
|
553
|
+
* still receives the cart and an explicit `error` plus the delivery state to
|
|
554
|
+
* show, and no flat group is invented as a substitute. A provider without the
|
|
555
|
+
* grouped capability reports `unavailable`, not a retryable `error`.
|
|
556
|
+
*/
|
|
557
|
+
async function loadMappedShippingGroups(
|
|
558
|
+
cartId: string,
|
|
559
|
+
cartLines: CartLineState[],
|
|
560
|
+
previous: CheckoutShippingGroup[] | undefined,
|
|
561
|
+
context: ReturnType<typeof getStoreContext>,
|
|
562
|
+
provider?: HostCommerceProvider,
|
|
563
|
+
): Promise<CheckoutShippingGroupsLoad> {
|
|
564
|
+
try {
|
|
565
|
+
const quote = await loadCheckoutShippingGroups(cartId, context, provider)
|
|
566
|
+
const mapped = toCheckoutShippingGroups(quote, cartLines, previous)
|
|
567
|
+
return { groups: mapped.groups, productsByGroup: mapped.productsByGroup }
|
|
568
|
+
} catch (error) {
|
|
569
|
+
// The provider message is logged server-side and never forwarded across the
|
|
570
|
+
// Server Action boundary: it can carry backend/transport detail the shopper
|
|
571
|
+
// must not see. The UI gets one fixed, user-safe message.
|
|
572
|
+
logServerError('loadCheckoutShippingGroups', error)
|
|
573
|
+
const shippingState = toShippingState(error)
|
|
574
|
+
return {
|
|
575
|
+
groups: [],
|
|
576
|
+
productsByGroup: {},
|
|
577
|
+
error:
|
|
578
|
+
shippingState === 'unavailable' ? unsupportedShippingMessage : quoteShippingErrorMessage,
|
|
579
|
+
shippingState,
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
297
584
|
/**
|
|
298
585
|
* 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.
|
|
586
|
+
* countries, then load the backend's grouped delivery quote and the recalculated
|
|
587
|
+
* totals. A malformed or ineligible address returns structured per-field errors
|
|
588
|
+
* and never advances.
|
|
589
|
+
*
|
|
590
|
+
* Delivery groups come from the grouped quote, mapped 1:1 — the flat option list
|
|
591
|
+
* is never wrapped into a single group (design D7).
|
|
302
592
|
*/
|
|
303
593
|
export async function syncCheckoutAddressAction(
|
|
304
594
|
values: Record<string, unknown>,
|
|
305
595
|
): Promise<CheckoutActionResult> {
|
|
306
596
|
try {
|
|
307
|
-
const { cartId, context } = await ensureActiveCartId()
|
|
308
|
-
const countries = await loadCheckoutCountries(cartId, context)
|
|
597
|
+
const { cartId, context, provider } = await ensureActiveCartId({ requireAuth: true })
|
|
598
|
+
const countries = await loadCheckoutCountries(cartId, context, provider)
|
|
309
599
|
const validation = validateAddress(toAddressInput(values), countries)
|
|
310
600
|
if (!validation.success) {
|
|
311
601
|
return {
|
|
@@ -314,46 +604,490 @@ export async function syncCheckoutAddressAction(
|
|
|
314
604
|
fieldErrors: toCheckoutFieldErrors(validation.errors),
|
|
315
605
|
}
|
|
316
606
|
}
|
|
317
|
-
const cart = await saveShippingAddress(cartId, validation.address, context)
|
|
318
|
-
const
|
|
319
|
-
|
|
607
|
+
const cart = await saveShippingAddress(cartId, validation.address, context, provider)
|
|
608
|
+
const shipping = await loadMappedShippingGroups(
|
|
609
|
+
cartId,
|
|
610
|
+
cart.cart,
|
|
611
|
+
undefined,
|
|
612
|
+
context,
|
|
613
|
+
provider,
|
|
614
|
+
)
|
|
615
|
+
return {
|
|
616
|
+
ok: true,
|
|
617
|
+
cart,
|
|
618
|
+
shippingGroups: shipping.groups,
|
|
619
|
+
shippingGroupProducts: shipping.productsByGroup,
|
|
620
|
+
...(shipping.error
|
|
621
|
+
? { shippingError: shipping.error, shippingState: shipping.shippingState ?? 'error' }
|
|
622
|
+
: {}),
|
|
623
|
+
}
|
|
320
624
|
} catch (error) {
|
|
321
|
-
return
|
|
625
|
+
return toCheckoutActionError(error, 'No se pudo validar la dirección.')
|
|
322
626
|
}
|
|
323
627
|
}
|
|
324
628
|
|
|
325
|
-
/**
|
|
629
|
+
/**
|
|
630
|
+
* Apply ONE flat shipping method. Retained for hosts that still select a single
|
|
631
|
+
* method directly; the checkout consumes the grouped contract through
|
|
632
|
+
* `applyCheckoutShippingGroupsAction` instead. No checkout handler calls it.
|
|
633
|
+
*/
|
|
326
634
|
export async function selectShippingMethodAction(input: {
|
|
327
635
|
methodId: string
|
|
328
636
|
}): Promise<CheckoutActionResult> {
|
|
329
637
|
try {
|
|
330
|
-
const { cartId, context } = await ensureActiveCartId()
|
|
331
|
-
const cart = await selectShipping(cartId, input.methodId, context)
|
|
638
|
+
const { cartId, context, provider } = await ensureActiveCartId({ requireAuth: true })
|
|
639
|
+
const cart = await selectShipping(cartId, input.methodId, context, provider)
|
|
332
640
|
return { ok: true, cart }
|
|
333
641
|
} catch (error) {
|
|
334
|
-
return
|
|
642
|
+
return toCheckoutActionError(error, 'No se pudo seleccionar el envío.')
|
|
335
643
|
}
|
|
336
644
|
}
|
|
337
645
|
|
|
338
|
-
/**
|
|
339
|
-
|
|
646
|
+
/**
|
|
647
|
+
* Apply one selected option per backend group and return the RE-READ cart.
|
|
648
|
+
* The selections carry the backend group identity (`products`) plus the chosen
|
|
649
|
+
* `option_id`; the backend validates them and the cart totals stay
|
|
650
|
+
* authoritative. A rejected set is a recoverable error, never an invented
|
|
651
|
+
* shipment split.
|
|
652
|
+
*/
|
|
653
|
+
export async function applyCheckoutShippingGroupsAction(input: {
|
|
654
|
+
shippingGroups: ShippingGroupSelection[]
|
|
655
|
+
}): Promise<CheckoutActionResult> {
|
|
340
656
|
try {
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
657
|
+
if (!Array.isArray(input?.shippingGroups)) {
|
|
658
|
+
return { ok: false, error: 'No se recibieron opciones de envío.' }
|
|
659
|
+
}
|
|
660
|
+
const { cartId, context, provider } = await ensureActiveCartId({ requireAuth: true })
|
|
661
|
+
const cart = await applyCheckoutShippingGroups(
|
|
662
|
+
cartId,
|
|
663
|
+
input.shippingGroups,
|
|
664
|
+
context,
|
|
665
|
+
provider,
|
|
666
|
+
)
|
|
667
|
+
return { ok: true, cart }
|
|
668
|
+
} catch (error) {
|
|
669
|
+
if (error instanceof CheckoutAuthError) {
|
|
670
|
+
return { ok: false, error: error.message, code: error.code }
|
|
671
|
+
}
|
|
672
|
+
// Same boundary policy as the quote path: the provider/backend detail is
|
|
673
|
+
// logged server-side and the shopper gets one fixed, user-safe message. An
|
|
674
|
+
// unsupported provider is `unavailable` (retrying cannot help).
|
|
675
|
+
logServerError('applyCheckoutShippingGroupsAction', error)
|
|
676
|
+
const shippingState = toShippingState(error)
|
|
677
|
+
return {
|
|
678
|
+
ok: false,
|
|
679
|
+
error: shippingState === 'unavailable' ? unsupportedShippingMessage : applyShippingErrorMessage,
|
|
680
|
+
shippingState,
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* Load the checkout data (countries, payment methods, cart) for the form.
|
|
687
|
+
*
|
|
688
|
+
* Delivery groups come from the backend grouped-shipping quote, mapped 1:1 —
|
|
689
|
+
* never from a local wrapper around the flat option list. A quote failure keeps
|
|
690
|
+
* the page usable: the cart still loads and `shippingError` reports the grouped
|
|
691
|
+
* delivery problem explicitly. `previousShippingGroups` keeps the shopper's
|
|
692
|
+
* per-group selections when the same group identity and option still exist.
|
|
693
|
+
*/
|
|
694
|
+
export async function loadCheckoutAction(
|
|
695
|
+
input: { previousShippingGroups?: CheckoutShippingGroup[] } = {},
|
|
696
|
+
): Promise<CheckoutActionResult> {
|
|
697
|
+
try {
|
|
698
|
+
const { cartId, context, provider } = await ensureActiveCartId({ requireAuth: true })
|
|
699
|
+
const [regionCountries, paymentMethods, cart] = await Promise.all([
|
|
700
|
+
loadCheckoutCountries(cartId, context, provider),
|
|
701
|
+
loadPaymentMethods(context, provider),
|
|
702
|
+
readCart(cartId, context, provider),
|
|
347
703
|
])
|
|
704
|
+
const patch = cart ?? EMPTY_CART_STATE
|
|
705
|
+
const shipping = await loadMappedShippingGroups(
|
|
706
|
+
cartId,
|
|
707
|
+
patch.cart,
|
|
708
|
+
input?.previousShippingGroups,
|
|
709
|
+
context,
|
|
710
|
+
provider,
|
|
711
|
+
)
|
|
348
712
|
return {
|
|
349
713
|
ok: true,
|
|
350
|
-
cart:
|
|
714
|
+
cart: patch,
|
|
351
715
|
countries: regionCountries.map((country) => ({ value: country.code, label: country.name })),
|
|
352
716
|
paymentMethods,
|
|
353
|
-
|
|
717
|
+
shippingGroups: shipping.groups,
|
|
718
|
+
shippingGroupProducts: shipping.productsByGroup,
|
|
719
|
+
...(shipping.error
|
|
720
|
+
? { shippingError: shipping.error, shippingState: shipping.shippingState ?? 'error' }
|
|
721
|
+
: {}),
|
|
722
|
+
}
|
|
723
|
+
} catch (error) {
|
|
724
|
+
return toCheckoutActionError(error, 'No se pudo cargar el checkout.')
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
type CheckoutPrefillPayload = ReturnType<typeof prefillCheckoutFromCustomer> & {
|
|
729
|
+
shippingLocations: CheckoutLocationOptions
|
|
730
|
+
billingLocations: CheckoutLocationOptions
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
type CheckoutPrefillActionResult =
|
|
734
|
+
| ({ ok: true } & CheckoutPrefillPayload)
|
|
735
|
+
| { ok: false; error: string; code?: string }
|
|
736
|
+
|
|
737
|
+
type CheckoutLocationsActionResult =
|
|
738
|
+
| { ok: true; options: CheckoutAddressOption[] }
|
|
739
|
+
| { ok: false; error: string }
|
|
740
|
+
|
|
741
|
+
type CheckoutSavedAddressActionResult =
|
|
742
|
+
| {
|
|
743
|
+
ok: true
|
|
744
|
+
savedAddresses: CheckoutSavedAddress[]
|
|
745
|
+
savedAddressId?: string
|
|
746
|
+
}
|
|
747
|
+
| { ok: false; error: string; code?: string; fieldErrors?: Record<string, unknown> }
|
|
748
|
+
|
|
749
|
+
function toSavedAddress(address: Address, index: number): CheckoutSavedAddress {
|
|
750
|
+
const optional = (value: string | undefined): string | undefined => {
|
|
751
|
+
const trimmed = value?.trim()
|
|
752
|
+
return trimmed ? value : undefined
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
return {
|
|
756
|
+
id: address.id ?? `saved-${index}`,
|
|
757
|
+
...(optional(address.label) ? { label: address.label } : {}),
|
|
758
|
+
address: {
|
|
759
|
+
firstName: address.firstName,
|
|
760
|
+
lastName: address.lastName,
|
|
761
|
+
company: optional(address.company),
|
|
762
|
+
address1: address.address1 ?? '',
|
|
763
|
+
address2: optional(address.address2),
|
|
764
|
+
city: address.city,
|
|
765
|
+
province: optional(address.province),
|
|
766
|
+
postalCode: optional(address.postalCode),
|
|
767
|
+
countryCode: address.countryCode,
|
|
768
|
+
phone: optional(address.phone),
|
|
769
|
+
},
|
|
770
|
+
isDefaultShipping: address.isDefaultShipping,
|
|
771
|
+
isDefaultBilling: address.isDefaultBilling,
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
function toCreateAddressData(address: CheckoutAddressValues): CreateAddressData {
|
|
776
|
+
return {
|
|
777
|
+
firstName: address.firstName,
|
|
778
|
+
lastName: address.lastName,
|
|
779
|
+
company: address.company,
|
|
780
|
+
address1: address.address1,
|
|
781
|
+
address2: address.address2,
|
|
782
|
+
city: address.city,
|
|
783
|
+
province: address.province,
|
|
784
|
+
postalCode: address.postalCode,
|
|
785
|
+
countryCode: address.countryCode,
|
|
786
|
+
phone: address.phone,
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/**
|
|
791
|
+
* Create an address in the authenticated customer's address book. The token is
|
|
792
|
+
* required, the payload is validated against the cart region, and the first
|
|
793
|
+
* saved address becomes the default shipping address by host policy.
|
|
794
|
+
*/
|
|
795
|
+
export async function createCheckoutAddressAction(
|
|
796
|
+
address: CheckoutAddressValues,
|
|
797
|
+
): Promise<CheckoutSavedAddressActionResult> {
|
|
798
|
+
try {
|
|
799
|
+
const context = getStoreContext()
|
|
800
|
+
const token = await readAuthToken(context)
|
|
801
|
+
if (!token) {
|
|
802
|
+
return { ok: false, error: 'Inicia sesión para guardar direcciones.' }
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
const { cartId, provider } = await ensureActiveCartId({ requireAuth: true })
|
|
806
|
+
const countries = await loadCheckoutCountries(cartId, context, provider)
|
|
807
|
+
const validation = validateCustomerAddress(address, countries)
|
|
808
|
+
if (!validation.success) {
|
|
809
|
+
return {
|
|
810
|
+
ok: false,
|
|
811
|
+
error: 'Revisa la dirección antes de guardarla.',
|
|
812
|
+
fieldErrors: toStructuredFieldErrors(validation.errors),
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
const existing = await loadCustomerAddresses(token)
|
|
817
|
+
const created = await createCustomerAddress(token, {
|
|
818
|
+
...toCreateAddressData(validation.address),
|
|
819
|
+
isDefaultShipping: existing.length === 0,
|
|
820
|
+
})
|
|
821
|
+
const savedAddresses = (await loadCustomerAddresses(token)).map(toSavedAddress)
|
|
822
|
+
|
|
823
|
+
return {
|
|
824
|
+
ok: true,
|
|
825
|
+
savedAddresses,
|
|
826
|
+
...(created.id ? { savedAddressId: created.id } : {}),
|
|
827
|
+
}
|
|
828
|
+
} catch (error) {
|
|
829
|
+
logServerError('createCheckoutAddressAction', error)
|
|
830
|
+
return toCheckoutActionError(error, 'No se pudo guardar la dirección.')
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/** Update a saved address; omitted optional values are preserved by the adapter. */
|
|
835
|
+
export async function updateCheckoutAddressAction(input: {
|
|
836
|
+
id: string
|
|
837
|
+
address: CheckoutAddressValues
|
|
838
|
+
}): Promise<CheckoutSavedAddressActionResult> {
|
|
839
|
+
try {
|
|
840
|
+
const context = getStoreContext()
|
|
841
|
+
const token = await readAuthToken(context)
|
|
842
|
+
if (!token) {
|
|
843
|
+
return { ok: false, error: 'Inicia sesión para actualizar direcciones.' }
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
const { cartId, provider } = await ensureActiveCartId({ requireAuth: true })
|
|
847
|
+
const countries = await loadCheckoutCountries(cartId, context, provider)
|
|
848
|
+
const validation = validateCustomerAddress(input.address, countries)
|
|
849
|
+
if (!validation.success) {
|
|
850
|
+
return {
|
|
851
|
+
ok: false,
|
|
852
|
+
error: 'Revisa la dirección antes de guardarla.',
|
|
853
|
+
fieldErrors: toStructuredFieldErrors(validation.errors),
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
await updateCustomerAddress(token, input.id, toCreateAddressData(validation.address))
|
|
858
|
+
const savedAddresses = (await loadCustomerAddresses(token)).map(toSavedAddress)
|
|
859
|
+
|
|
860
|
+
return { ok: true, savedAddresses, savedAddressId: input.id }
|
|
861
|
+
} catch (error) {
|
|
862
|
+
logServerError('updateCheckoutAddressAction', error)
|
|
863
|
+
return toCheckoutActionError(error, 'No se pudo actualizar la dirección.')
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/** Delete a saved address; the backend ownership check is authoritative. */
|
|
868
|
+
export async function deleteCheckoutAddressAction(input: {
|
|
869
|
+
id: string
|
|
870
|
+
}): Promise<CheckoutSavedAddressActionResult> {
|
|
871
|
+
try {
|
|
872
|
+
const context = getStoreContext()
|
|
873
|
+
const token = await readAuthToken(context)
|
|
874
|
+
if (!token) {
|
|
875
|
+
return { ok: false, error: 'Inicia sesión para eliminar direcciones.' }
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
await deleteCustomerAddress(token, input.id)
|
|
879
|
+
const savedAddresses = (await loadCustomerAddresses(token)).map(toSavedAddress)
|
|
880
|
+
|
|
881
|
+
return { ok: true, savedAddresses, savedAddressId: input.id }
|
|
882
|
+
} catch (error) {
|
|
883
|
+
logServerError('deleteCheckoutAddressAction', error)
|
|
884
|
+
return toCheckoutActionError(error, 'No se pudo eliminar la dirección.')
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
/**
|
|
889
|
+
* Resolve the authenticated customer's profile and saved addresses and map
|
|
890
|
+
* them to checkout prefill. Cart/shopper values supplied by the caller win;
|
|
891
|
+
* a customer-read failure returns a non-blocking `customerUnavailable` result
|
|
892
|
+
* without claiming prefill.
|
|
893
|
+
*/
|
|
894
|
+
export async function loadCheckoutPrefillAction(
|
|
895
|
+
input: {
|
|
896
|
+
contact?: CheckoutContactValues
|
|
897
|
+
shippingAddress?: CheckoutAddressValues
|
|
898
|
+
billingAddress?: CheckoutAddressValues
|
|
899
|
+
sameAsShipping?: boolean
|
|
900
|
+
} = {},
|
|
901
|
+
): Promise<CheckoutPrefillActionResult> {
|
|
902
|
+
try {
|
|
903
|
+
const { cartId, context, provider, token } = await ensureActiveCartId({ requireAuth: true })
|
|
904
|
+
const regionCountries = await loadCheckoutCountries(cartId, context, provider)
|
|
905
|
+
const countries = regionCountries.map((country) => ({
|
|
906
|
+
value: country.code,
|
|
907
|
+
label: country.name,
|
|
908
|
+
}))
|
|
909
|
+
const shippingLocations: CheckoutLocationOptions = {
|
|
910
|
+
countries,
|
|
911
|
+
provinces: [],
|
|
912
|
+
cities: [],
|
|
913
|
+
}
|
|
914
|
+
const billingLocations: CheckoutLocationOptions = {
|
|
915
|
+
countries,
|
|
916
|
+
provinces: [],
|
|
917
|
+
cities: [],
|
|
354
918
|
}
|
|
919
|
+
const cartInput = {
|
|
920
|
+
contact: input.contact,
|
|
921
|
+
shippingAddress: input.shippingAddress,
|
|
922
|
+
billingAddress: input.billingAddress,
|
|
923
|
+
sameAsShipping: input.sameAsShipping,
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
if (!token) {
|
|
927
|
+
const result = prefillCheckoutFromCustomer({
|
|
928
|
+
cart: cartInput,
|
|
929
|
+
shippingLocations,
|
|
930
|
+
billingLocations,
|
|
931
|
+
})
|
|
932
|
+
return { ok: true, ...result, shippingLocations, billingLocations }
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
try {
|
|
936
|
+
const customer = await loadCustomer(token)
|
|
937
|
+
if (!customer) {
|
|
938
|
+
const result = prefillCheckoutFromCustomer({
|
|
939
|
+
cart: cartInput,
|
|
940
|
+
shippingLocations,
|
|
941
|
+
billingLocations,
|
|
942
|
+
})
|
|
943
|
+
return { ok: true, ...result, shippingLocations, billingLocations }
|
|
944
|
+
}
|
|
945
|
+
const addresses = await loadCustomerAddresses(token)
|
|
946
|
+
const savedAddresses = addresses.map(toSavedAddress)
|
|
947
|
+
const result = prefillCheckoutFromCustomer({
|
|
948
|
+
cart: cartInput,
|
|
949
|
+
customer: {
|
|
950
|
+
id: customer.id,
|
|
951
|
+
email: customer.email,
|
|
952
|
+
firstName: customer.firstName,
|
|
953
|
+
lastName: customer.lastName,
|
|
954
|
+
phone: customer.phone,
|
|
955
|
+
},
|
|
956
|
+
savedAddresses,
|
|
957
|
+
shippingLocations,
|
|
958
|
+
billingLocations,
|
|
959
|
+
})
|
|
960
|
+
return { ok: true, ...result, shippingLocations, billingLocations }
|
|
961
|
+
} catch (error) {
|
|
962
|
+
logServerError('loadCheckoutPrefillAction', error)
|
|
963
|
+
const result = prefillCheckoutFromCustomer({
|
|
964
|
+
cart: cartInput,
|
|
965
|
+
customerState: 'unavailable',
|
|
966
|
+
shippingLocations,
|
|
967
|
+
billingLocations,
|
|
968
|
+
})
|
|
969
|
+
return { ok: true, ...result, shippingLocations, billingLocations }
|
|
970
|
+
}
|
|
971
|
+
} catch (error) {
|
|
972
|
+
return toCheckoutActionError(error, 'No se pudo cargar la información del cliente.')
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
/** Load the backend geo-reference options for a province or city level. */
|
|
977
|
+
export async function loadCheckoutLocationsAction(input: {
|
|
978
|
+
kind: 'shipping' | 'billing'
|
|
979
|
+
level: 'countries' | 'provinces' | 'cities'
|
|
980
|
+
countryCode?: string
|
|
981
|
+
provinceCode?: string
|
|
982
|
+
}): Promise<CheckoutLocationsActionResult> {
|
|
983
|
+
try {
|
|
984
|
+
if (input.level === 'provinces') {
|
|
985
|
+
if (!input.countryCode) return { ok: false, error: 'Selecciona un país.' }
|
|
986
|
+
return {
|
|
987
|
+
ok: true,
|
|
988
|
+
options: await loadGeoProvinces(input.countryCode.toLowerCase()),
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
if (input.level === 'cities') {
|
|
992
|
+
if (!input.provinceCode) return { ok: false, error: 'Selecciona una provincia.' }
|
|
993
|
+
return {
|
|
994
|
+
ok: true,
|
|
995
|
+
options: await loadGeoCities(
|
|
996
|
+
input.provinceCode,
|
|
997
|
+
input.countryCode?.toLowerCase(),
|
|
998
|
+
),
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
return { ok: false, error: 'Selecciona un país.' }
|
|
355
1002
|
} catch (error) {
|
|
356
|
-
return { ok: false, error: toError(error, 'No se
|
|
1003
|
+
return { ok: false, error: toError(error, 'No se pudieron cargar las opciones.') }
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
/**
|
|
1008
|
+
* Validate and persist the structured checkout address (and a distinct billing
|
|
1009
|
+
* address) against the cart region, then return the recalculated cart and the
|
|
1010
|
+
* backend's grouped delivery options.
|
|
1011
|
+
*
|
|
1012
|
+
* The delivery groups are requested again after the address change (they depend
|
|
1013
|
+
* on it) and mapped 1:1. `previousShippingGroups` reconciles the shopper's
|
|
1014
|
+
* per-group selections by stable group identity. A quote failure keeps the
|
|
1015
|
+
* address result usable and reports `shippingError` instead of failing the
|
|
1016
|
+
* whole sync or falling back to one flat group.
|
|
1017
|
+
*/
|
|
1018
|
+
export async function syncCheckoutAddressStructuredAction(input: {
|
|
1019
|
+
contact: CheckoutContactValues
|
|
1020
|
+
shippingAddress: CheckoutAddressValues
|
|
1021
|
+
billingAddress?: CheckoutAddressValues
|
|
1022
|
+
sameAsShipping: boolean
|
|
1023
|
+
previousShippingGroups?: CheckoutShippingGroup[]
|
|
1024
|
+
}): Promise<CheckoutActionResult> {
|
|
1025
|
+
try {
|
|
1026
|
+
const { cartId, context, provider } = await ensureActiveCartId({ requireAuth: true })
|
|
1027
|
+
const countries = await loadCheckoutCountries(cartId, context, provider)
|
|
1028
|
+
const validation = validateAddress(
|
|
1029
|
+
{
|
|
1030
|
+
email: input.contact.email,
|
|
1031
|
+
firstName: input.shippingAddress.firstName,
|
|
1032
|
+
lastName: input.shippingAddress.lastName,
|
|
1033
|
+
address1: input.shippingAddress.address1,
|
|
1034
|
+
address2: input.shippingAddress.address2,
|
|
1035
|
+
company: input.shippingAddress.company,
|
|
1036
|
+
city: input.shippingAddress.city,
|
|
1037
|
+
province: input.shippingAddress.province ?? '',
|
|
1038
|
+
postalCode: input.shippingAddress.postalCode ?? '',
|
|
1039
|
+
countryCode: input.shippingAddress.countryCode,
|
|
1040
|
+
phone: input.shippingAddress.phone ?? '',
|
|
1041
|
+
},
|
|
1042
|
+
countries,
|
|
1043
|
+
)
|
|
1044
|
+
if (!validation.success) {
|
|
1045
|
+
return {
|
|
1046
|
+
ok: false,
|
|
1047
|
+
error: 'Revisa los datos de la dirección.',
|
|
1048
|
+
fieldErrors: toStructuredFieldErrors(validation.errors),
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
const cart = await saveShippingAddress(cartId, validation.address, context, provider)
|
|
1053
|
+
if (!input.sameAsShipping && input.billingAddress) {
|
|
1054
|
+
await saveBillingAddress(
|
|
1055
|
+
cartId,
|
|
1056
|
+
{
|
|
1057
|
+
firstName: input.billingAddress.firstName,
|
|
1058
|
+
lastName: input.billingAddress.lastName,
|
|
1059
|
+
address1: input.billingAddress.address1,
|
|
1060
|
+
address2: input.billingAddress.address2,
|
|
1061
|
+
company: input.billingAddress.company,
|
|
1062
|
+
city: input.billingAddress.city,
|
|
1063
|
+
province: input.billingAddress.province ?? '',
|
|
1064
|
+
postalCode: input.billingAddress.postalCode,
|
|
1065
|
+
countryCode: input.billingAddress.countryCode,
|
|
1066
|
+
phone: input.billingAddress.phone ?? '',
|
|
1067
|
+
},
|
|
1068
|
+
context,
|
|
1069
|
+
provider,
|
|
1070
|
+
)
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
const shipping = await loadMappedShippingGroups(
|
|
1074
|
+
cartId,
|
|
1075
|
+
cart.cart,
|
|
1076
|
+
input.previousShippingGroups,
|
|
1077
|
+
context,
|
|
1078
|
+
provider,
|
|
1079
|
+
)
|
|
1080
|
+
return {
|
|
1081
|
+
ok: true,
|
|
1082
|
+
cart,
|
|
1083
|
+
shippingGroups: shipping.groups,
|
|
1084
|
+
shippingGroupProducts: shipping.productsByGroup,
|
|
1085
|
+
...(shipping.error
|
|
1086
|
+
? { shippingError: shipping.error, shippingState: shipping.shippingState ?? 'error' }
|
|
1087
|
+
: {}),
|
|
1088
|
+
}
|
|
1089
|
+
} catch (error) {
|
|
1090
|
+
return toCheckoutActionError(error, 'No se pudo validar la dirección.')
|
|
357
1091
|
}
|
|
358
1092
|
}
|
|
359
1093
|
|
|
@@ -377,28 +1111,84 @@ async function clearConfirmedSession(
|
|
|
377
1111
|
}
|
|
378
1112
|
|
|
379
1113
|
/**
|
|
380
|
-
* Place the order exactly once.
|
|
381
|
-
*
|
|
382
|
-
*
|
|
383
|
-
*
|
|
384
|
-
*
|
|
385
|
-
* the
|
|
1114
|
+
* Place the order exactly once.
|
|
1115
|
+
*
|
|
1116
|
+
* When the shopper's per-group selections are supplied, every selected group is
|
|
1117
|
+
* applied to the cart FIRST and the runtime re-reads the authoritative cart
|
|
1118
|
+
* (design D6); a rejected group set is a recoverable error and never completes
|
|
1119
|
+
* the order, and an explicitly EMPTY set is refused before payment. The approved
|
|
1120
|
+
* manual TEST payment is then applied after shipping
|
|
1121
|
+
* totals are final, and the cart is completed with its native discriminator. On
|
|
1122
|
+
* a confirmed order the active cart is cleared and the receipt recorded. If the
|
|
1123
|
+
* order committed but the session cookie could not be updated, the result is
|
|
1124
|
+
* `unresolved` (reconcile the active committed cart) so the client never treats
|
|
1125
|
+
* a committed order as a retryable failure.
|
|
386
1126
|
*/
|
|
387
|
-
export async function placeOrderAction(
|
|
1127
|
+
export async function placeOrderAction(
|
|
1128
|
+
input: { shippingGroups?: ShippingGroupSelection[]; paymentMethodId?: string } = {},
|
|
1129
|
+
): Promise<PlaceOrderResult> {
|
|
388
1130
|
try {
|
|
389
|
-
const context =
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
1131
|
+
const { cartId, context, provider, customerId } = await ensureActiveCartId({
|
|
1132
|
+
requireAuth: true,
|
|
1133
|
+
})
|
|
1134
|
+
if (!customerId && getDataSource() === 'medusa') {
|
|
1135
|
+
return {
|
|
1136
|
+
status: 'error',
|
|
1137
|
+
message: 'Inicia sesión para completar el pedido.',
|
|
1138
|
+
code: 'AUTH_REQUIRED',
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
const paymentMethodId =
|
|
1143
|
+
typeof input.paymentMethodId === 'string' ? input.paymentMethodId.trim() : ''
|
|
1144
|
+
if (!paymentMethodId) {
|
|
1145
|
+
return {
|
|
1146
|
+
status: 'error',
|
|
1147
|
+
message: 'Selecciona un método de pago antes de confirmar.',
|
|
1148
|
+
code: 'PAYMENT_METHOD_REQUIRED',
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
const shippingGroups = input?.shippingGroups
|
|
1153
|
+
if (shippingGroups) {
|
|
1154
|
+
// An explicitly empty selection set means the delivery step was not
|
|
1155
|
+
// completed: block the order before payment (design D6) instead of
|
|
1156
|
+
// paying for an unselected shipment. Omitting the input entirely keeps
|
|
1157
|
+
// the pre-grouped callers working.
|
|
1158
|
+
if (shippingGroups.length === 0) {
|
|
1159
|
+
return {
|
|
1160
|
+
status: 'error',
|
|
1161
|
+
message: 'Selecciona una opción de envío para cada grupo antes de pagar.',
|
|
1162
|
+
code: 'SHIPPING_GROUPS_REQUIRED',
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
try {
|
|
1166
|
+
await applyCheckoutShippingGroups(cartId, shippingGroups, context, provider)
|
|
1167
|
+
} catch (error) {
|
|
1168
|
+
// Logged server-side only; the shopper gets a fixed recoverable message.
|
|
1169
|
+
logServerError('applyCheckoutShippingGroups', error)
|
|
1170
|
+
return {
|
|
1171
|
+
status: 'error',
|
|
1172
|
+
message: 'No se pudo aplicar el envío seleccionado. Reintenta.',
|
|
1173
|
+
code: 'SHIPPING_GROUPS_REJECTED',
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
393
1176
|
}
|
|
394
|
-
const cartId = session.cartId
|
|
395
1177
|
try {
|
|
396
|
-
await applyPayment(cartId, context)
|
|
1178
|
+
await applyPayment(cartId, paymentMethodId, context, provider)
|
|
397
1179
|
} catch (error) {
|
|
398
1180
|
logServerError('applyPayment', error)
|
|
399
|
-
return {
|
|
1181
|
+
return {
|
|
1182
|
+
status: 'error',
|
|
1183
|
+
message: toError(error, 'No se pudo iniciar el pago.'),
|
|
1184
|
+
code: 'PAYMENT_METHOD_REJECTED',
|
|
1185
|
+
}
|
|
400
1186
|
}
|
|
401
|
-
|
|
1187
|
+
// Thread the request's customer token (design D11) so an authenticated
|
|
1188
|
+
// checkout is attributed to the session customer; guests complete the same
|
|
1189
|
+
// tokenless provider as before.
|
|
1190
|
+
const customerToken = await readAuthToken(context)
|
|
1191
|
+
const result = await completeOrder(cartId, context, customerToken)
|
|
402
1192
|
if (result.status !== 'order') return result
|
|
403
1193
|
if (!(await clearConfirmedSession(context, cartId))) {
|
|
404
1194
|
return {
|
|
@@ -409,6 +1199,9 @@ export async function placeOrderAction(): Promise<PlaceOrderResult> {
|
|
|
409
1199
|
}
|
|
410
1200
|
return result
|
|
411
1201
|
} catch (error) {
|
|
1202
|
+
if (error instanceof CheckoutAuthError) {
|
|
1203
|
+
return { status: 'error', message: error.message, code: error.code }
|
|
1204
|
+
}
|
|
412
1205
|
// An unexpected failure during completion is ambiguous: never a blind retry.
|
|
413
1206
|
logServerError('placeOrderAction', error)
|
|
414
1207
|
return {
|
|
@@ -429,10 +1222,22 @@ export async function placeOrderAction(): Promise<PlaceOrderResult> {
|
|
|
429
1222
|
export async function reconcileReceiptAction(): Promise<PlaceOrderResult> {
|
|
430
1223
|
try {
|
|
431
1224
|
const context = getStoreContext()
|
|
1225
|
+
const token = await readAuthToken(context)
|
|
1226
|
+
if (!token && getDataSource() === 'medusa') {
|
|
1227
|
+
return {
|
|
1228
|
+
status: 'error',
|
|
1229
|
+
message: 'Inicia sesión para recuperar el comprobante.',
|
|
1230
|
+
code: 'AUTH_REQUIRED',
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
const provider = getHostCommerceProvider(token)
|
|
432
1234
|
const session = await readHostSession(context)
|
|
433
1235
|
if (!session) {
|
|
434
1236
|
return { status: 'unresolved', message: 'No hay un comprobante autorizado para esta sesión.' }
|
|
435
1237
|
}
|
|
1238
|
+
// Same threading as the completion (design D11): the reconcile completes
|
|
1239
|
+
// under the session customer when one is signed in.
|
|
1240
|
+
const customerToken = await readAuthToken(context)
|
|
436
1241
|
|
|
437
1242
|
// An active cart is reconciled first: the runtime does a single GET and
|
|
438
1243
|
// only POSTs complete when the backend committed. A cart the backend did
|
|
@@ -441,7 +1246,7 @@ export async function reconcileReceiptAction(): Promise<PlaceOrderResult> {
|
|
|
441
1246
|
// The active cart is only cleared when it is the committed cart; a new cart
|
|
442
1247
|
// started after an earlier order is preserved by the session core.
|
|
443
1248
|
if (session.cartId) {
|
|
444
|
-
const result = await reconcileOrder(session.cartId, context)
|
|
1249
|
+
const result = await reconcileOrder(session.cartId, context, customerToken)
|
|
445
1250
|
if (result.status === 'order') {
|
|
446
1251
|
await clearConfirmedSession(context, session.cartId)
|
|
447
1252
|
return result
|
|
@@ -456,7 +1261,7 @@ export async function reconcileReceiptAction(): Promise<PlaceOrderResult> {
|
|
|
456
1261
|
if (!candidate) {
|
|
457
1262
|
return { status: 'unresolved', message: 'No hay un comprobante autorizado para esta sesión.' }
|
|
458
1263
|
}
|
|
459
|
-
const result = await reconcileOrder(candidate, context)
|
|
1264
|
+
const result = await reconcileOrder(candidate, context, customerToken)
|
|
460
1265
|
if (result.status === 'order') {
|
|
461
1266
|
await clearConfirmedSession(context, candidate)
|
|
462
1267
|
return result
|
|
@@ -659,3 +1464,357 @@ export async function loadOrdersPageAction(input?: {
|
|
|
659
1464
|
return { ok: false, error: toError(error, 'No se pudieron cargar tus pedidos.') }
|
|
660
1465
|
}
|
|
661
1466
|
}
|
|
1467
|
+
|
|
1468
|
+
/**
|
|
1469
|
+
* One query window for the advanced order-history port. The block owns its
|
|
1470
|
+
* filtering, sorting and pagination UI; this action is the request-scoped read
|
|
1471
|
+
* behind `OrdersPort.list`, the same token-scoped history the canonical surface
|
|
1472
|
+
* reads. It touches ONLY the auth cookie — never the guest session cookie or the
|
|
1473
|
+
* cart — and no token is logged or returned. A missing token resolves to the
|
|
1474
|
+
* empty page without contacting the backend.
|
|
1475
|
+
*/
|
|
1476
|
+
export async function listOrdersQueryPageAction(
|
|
1477
|
+
query: OrdersQuery,
|
|
1478
|
+
): Promise<OrdersQueryPageActionResult> {
|
|
1479
|
+
const context = getStoreContext()
|
|
1480
|
+
const token = await readAuthToken(context)
|
|
1481
|
+
try {
|
|
1482
|
+
const page = await loadOrderHistoryPage(token, query, context)
|
|
1483
|
+
return { ok: true, page }
|
|
1484
|
+
} catch (error) {
|
|
1485
|
+
logServerError('listOrdersQueryPageAction', error)
|
|
1486
|
+
return { ok: false, error: toError(error, 'No se pudieron cargar tus pedidos.') }
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
// ---------------------------------------------------------------------------
|
|
1491
|
+
// Account modules (change: storefront-customer-view, task 4.4)
|
|
1492
|
+
// ---------------------------------------------------------------------------
|
|
1493
|
+
//
|
|
1494
|
+
// Profile and address-book mutations are account-scoped: they use ONLY the auth
|
|
1495
|
+
// cookie, never the guest cart, and never require a checkout region. Every action
|
|
1496
|
+
// returns an allowlisted, serializable result and never a token.
|
|
1497
|
+
|
|
1498
|
+
type AccountProfileResult =
|
|
1499
|
+
| { ok: true; customer: Pick<Customer, 'id' | 'email' | 'firstName' | 'lastName'> }
|
|
1500
|
+
| { ok: false; error: string; fieldErrors?: Record<string, string> }
|
|
1501
|
+
|
|
1502
|
+
type AccountAddressesResult =
|
|
1503
|
+
| { ok: true; addresses: AccountAddressView[] }
|
|
1504
|
+
| { ok: false; error: string }
|
|
1505
|
+
|
|
1506
|
+
type AccountAddressMutationResult =
|
|
1507
|
+
| { ok: true; addresses: AccountAddressView[] }
|
|
1508
|
+
| { ok: false; error: string; fieldErrors?: Record<string, string> }
|
|
1509
|
+
|
|
1510
|
+
interface AccountAddressInput {
|
|
1511
|
+
firstName: string
|
|
1512
|
+
lastName: string
|
|
1513
|
+
address1: string
|
|
1514
|
+
address2?: string
|
|
1515
|
+
city: string
|
|
1516
|
+
province?: string
|
|
1517
|
+
postalCode?: string
|
|
1518
|
+
countryCode: string
|
|
1519
|
+
phone?: string
|
|
1520
|
+
label?: string
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
function optionalText(value: string | undefined): string | undefined {
|
|
1524
|
+
const trimmed = value?.trim()
|
|
1525
|
+
return trimmed ? value : undefined
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
function toAccountAddress(address: Address, index: number): AccountAddressView {
|
|
1529
|
+
return {
|
|
1530
|
+
id: address.id ?? `account-address-${index}`,
|
|
1531
|
+
firstName: address.firstName,
|
|
1532
|
+
lastName: address.lastName,
|
|
1533
|
+
...(optionalText(address.address1) ? { address1: address.address1 } : {}),
|
|
1534
|
+
...(optionalText(address.address2) ? { address2: address.address2 } : {}),
|
|
1535
|
+
city: address.city,
|
|
1536
|
+
...(optionalText(address.province) ? { province: address.province } : {}),
|
|
1537
|
+
...(optionalText(address.postalCode) ? { postalCode: address.postalCode } : {}),
|
|
1538
|
+
countryCode: address.countryCode,
|
|
1539
|
+
...(optionalText(address.phone) ? { phone: address.phone } : {}),
|
|
1540
|
+
...(optionalText(address.label) ? { label: address.label } : {}),
|
|
1541
|
+
...(address.isDefaultShipping ? { isDefaultShipping: true } : {}),
|
|
1542
|
+
...(address.isDefaultBilling ? { isDefaultBilling: true } : {}),
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
async function readAccountToken(): Promise<string | null> {
|
|
1547
|
+
return readAuthToken(getStoreContext())
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
/**
|
|
1551
|
+
* Update the authenticated customer's profile. Only the fields the caller
|
|
1552
|
+
* supplies are sent; the returned identity is allowlisted to the same keys the
|
|
1553
|
+
* session projection exposes.
|
|
1554
|
+
*/
|
|
1555
|
+
export async function updateAccountProfileAction(input: {
|
|
1556
|
+
firstName?: string
|
|
1557
|
+
lastName?: string
|
|
1558
|
+
phone?: string
|
|
1559
|
+
email?: string
|
|
1560
|
+
/** Namespaced profile metadata to merge; never replaces unrelated metadata. */
|
|
1561
|
+
profile?: AccountProfileMetadataPatch
|
|
1562
|
+
}): Promise<AccountProfileResult> {
|
|
1563
|
+
const token = await readAccountToken()
|
|
1564
|
+
if (!token) return { ok: false, error: 'Inicia sesión para actualizar tu perfil.' }
|
|
1565
|
+
|
|
1566
|
+
const fieldErrors: Record<string, string> = {}
|
|
1567
|
+
const firstName = input.firstName?.trim()
|
|
1568
|
+
const lastName = input.lastName?.trim()
|
|
1569
|
+
const email = input.email?.trim()
|
|
1570
|
+
if (!firstName) fieldErrors.firstName = 'El nombre es obligatorio.'
|
|
1571
|
+
if (!lastName) fieldErrors.lastName = 'Los apellidos son obligatorios.'
|
|
1572
|
+
if (email !== undefined && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
|
1573
|
+
fieldErrors.email = 'El correo no es válido.'
|
|
1574
|
+
}
|
|
1575
|
+
if (Object.keys(fieldErrors).length > 0) {
|
|
1576
|
+
return { ok: false, error: 'Revisa los datos antes de guardar.', fieldErrors }
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
try {
|
|
1580
|
+
let metadata: Record<string, unknown> | undefined
|
|
1581
|
+
if (input.profile) {
|
|
1582
|
+
const current = await loadCustomer(token)
|
|
1583
|
+
const base = current && isRecord(current.metadata) ? current.metadata : {}
|
|
1584
|
+
const profile = isRecord(base.profile) ? base.profile : {}
|
|
1585
|
+
metadata = { ...base, profile: mergeProfileMetadata(profile, input.profile) }
|
|
1586
|
+
}
|
|
1587
|
+
|
|
1588
|
+
const customer = await updateCustomerProfile(token, {
|
|
1589
|
+
...(firstName ? { firstName } : {}),
|
|
1590
|
+
...(lastName ? { lastName } : {}),
|
|
1591
|
+
...(input.phone !== undefined ? { phone: optionalText(input.phone) ?? '' } : {}),
|
|
1592
|
+
...(email !== undefined ? { email } : {}),
|
|
1593
|
+
...(metadata ? { metadata } : {}),
|
|
1594
|
+
})
|
|
1595
|
+
return {
|
|
1596
|
+
ok: true,
|
|
1597
|
+
customer: {
|
|
1598
|
+
id: customer.id,
|
|
1599
|
+
email: customer.email,
|
|
1600
|
+
firstName: customer.firstName,
|
|
1601
|
+
lastName: customer.lastName,
|
|
1602
|
+
},
|
|
1603
|
+
}
|
|
1604
|
+
} catch (error) {
|
|
1605
|
+
logServerError('updateAccountProfileAction', error)
|
|
1606
|
+
return { ok: false, error: toError(error, 'No se pudo guardar tu perfil.') }
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
1611
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
/** Merge the profile namespace without dropping unrelated metadata keys. */
|
|
1615
|
+
function mergeProfileMetadata(
|
|
1616
|
+
current: Record<string, unknown>,
|
|
1617
|
+
patch: AccountProfileMetadataPatch,
|
|
1618
|
+
): Record<string, unknown> {
|
|
1619
|
+
return {
|
|
1620
|
+
...current,
|
|
1621
|
+
...patch,
|
|
1622
|
+
...(patch.person
|
|
1623
|
+
? { person: { ...(isRecord(current.person) ? current.person : {}), ...patch.person } }
|
|
1624
|
+
: {}),
|
|
1625
|
+
...(patch.preferences
|
|
1626
|
+
? {
|
|
1627
|
+
preferences: {
|
|
1628
|
+
...(isRecord(current.preferences) ? current.preferences : {}),
|
|
1629
|
+
...patch.preferences,
|
|
1630
|
+
},
|
|
1631
|
+
}
|
|
1632
|
+
: {}),
|
|
1633
|
+
...(patch.professional
|
|
1634
|
+
? {
|
|
1635
|
+
professional: {
|
|
1636
|
+
...(isRecord(current.professional) ? current.professional : {}),
|
|
1637
|
+
...patch.professional,
|
|
1638
|
+
},
|
|
1639
|
+
}
|
|
1640
|
+
: {}),
|
|
1641
|
+
...(patch.customFields ? { customFields: patch.customFields } : {}),
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
type AccountProfileLoadResult =
|
|
1646
|
+
| { ok: true; profile: AccountProfilePayload }
|
|
1647
|
+
| { ok: false; error: string }
|
|
1648
|
+
|
|
1649
|
+
/**
|
|
1650
|
+
* Load the authenticated customer's full profile. Only the profile namespace
|
|
1651
|
+
* of `metadata` is returned; unrelated backend metadata never reaches the
|
|
1652
|
+
* client.
|
|
1653
|
+
*/
|
|
1654
|
+
export async function loadAccountProfileAction(): Promise<AccountProfileLoadResult> {
|
|
1655
|
+
const token = await readAccountToken()
|
|
1656
|
+
if (!token) return { ok: false, error: 'Inicia sesión para ver tu perfil.' }
|
|
1657
|
+
|
|
1658
|
+
try {
|
|
1659
|
+
const customer = await loadCustomer(token)
|
|
1660
|
+
if (!customer) return { ok: false, error: 'Inicia sesión para ver tu perfil.' }
|
|
1661
|
+
const metadata = isRecord(customer.metadata) ? customer.metadata : {}
|
|
1662
|
+
const profile = isRecord(metadata.profile)
|
|
1663
|
+
? (metadata.profile as AccountProfilePayload['metadata'])
|
|
1664
|
+
: undefined
|
|
1665
|
+
return {
|
|
1666
|
+
ok: true,
|
|
1667
|
+
profile: {
|
|
1668
|
+
id: customer.id,
|
|
1669
|
+
email: customer.email,
|
|
1670
|
+
firstName: customer.firstName,
|
|
1671
|
+
lastName: customer.lastName,
|
|
1672
|
+
...(customer.phone ? { phone: customer.phone } : {}),
|
|
1673
|
+
...(profile ? { metadata: profile } : {}),
|
|
1674
|
+
},
|
|
1675
|
+
}
|
|
1676
|
+
} catch (error) {
|
|
1677
|
+
logServerError('loadAccountProfileAction', error)
|
|
1678
|
+
return { ok: false, error: toError(error, 'No se pudo cargar tu perfil.') }
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
/** Persist the profile-only metadata namespace without touching identity fields. */
|
|
1683
|
+
export async function updateAccountProfileMetadataAction(
|
|
1684
|
+
patch: AccountProfileMetadataPatch,
|
|
1685
|
+
): Promise<{ ok: true } | { ok: false; error: string }> {
|
|
1686
|
+
const token = await readAccountToken()
|
|
1687
|
+
if (!token) return { ok: false, error: 'Inicia sesión para actualizar tu perfil.' }
|
|
1688
|
+
|
|
1689
|
+
try {
|
|
1690
|
+
const customer = await loadCustomer(token)
|
|
1691
|
+
if (!customer) return { ok: false, error: 'Inicia sesión para actualizar tu perfil.' }
|
|
1692
|
+
const metadata = isRecord(customer.metadata) ? customer.metadata : {}
|
|
1693
|
+
const current = isRecord(metadata.profile) ? metadata.profile : {}
|
|
1694
|
+
await updateCustomerProfile(token, {
|
|
1695
|
+
metadata: { ...metadata, profile: mergeProfileMetadata(current, patch) },
|
|
1696
|
+
})
|
|
1697
|
+
return { ok: true }
|
|
1698
|
+
} catch (error) {
|
|
1699
|
+
logServerError('updateAccountProfileMetadataAction', error)
|
|
1700
|
+
return { ok: false, error: toError(error, 'No se pudo guardar tu perfil.') }
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
/** Load the authenticated customer's address book. */
|
|
1705
|
+
export async function loadAccountAddressesAction(): Promise<AccountAddressesResult> {
|
|
1706
|
+
const token = await readAccountToken()
|
|
1707
|
+
if (!token) return { ok: true, addresses: [] }
|
|
1708
|
+
try {
|
|
1709
|
+
const addresses = await loadCustomerAddresses(token)
|
|
1710
|
+
return { ok: true, addresses: addresses.map(toAccountAddress) }
|
|
1711
|
+
} catch (error) {
|
|
1712
|
+
logServerError('loadAccountAddressesAction', error)
|
|
1713
|
+
return { ok: false, error: toError(error, 'No se pudieron cargar tus direcciones.') }
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
|
|
1717
|
+
function validateAccountAddress(input: AccountAddressInput): Record<string, string> {
|
|
1718
|
+
const errors: Record<string, string> = {}
|
|
1719
|
+
if (!input.firstName?.trim()) errors.firstName = 'El nombre es obligatorio.'
|
|
1720
|
+
if (!input.lastName?.trim()) errors.lastName = 'Los apellidos son obligatorios.'
|
|
1721
|
+
if (!input.address1?.trim()) errors.address1 = 'La dirección es obligatoria.'
|
|
1722
|
+
if (!input.city?.trim()) errors.city = 'La ciudad es obligatoria.'
|
|
1723
|
+
if (!/^[A-Za-z]{2}$/.test(input.countryCode?.trim() ?? '')) {
|
|
1724
|
+
errors.countryCode = 'Usa un código de país ISO de dos letras.'
|
|
1725
|
+
}
|
|
1726
|
+
return errors
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
function toAddressData(input: AccountAddressInput): CreateAddressData {
|
|
1730
|
+
return {
|
|
1731
|
+
firstName: input.firstName,
|
|
1732
|
+
lastName: input.lastName,
|
|
1733
|
+
address1: input.address1,
|
|
1734
|
+
address2: optionalText(input.address2),
|
|
1735
|
+
city: input.city,
|
|
1736
|
+
province: optionalText(input.province),
|
|
1737
|
+
postalCode: optionalText(input.postalCode),
|
|
1738
|
+
countryCode: input.countryCode.toUpperCase(),
|
|
1739
|
+
phone: optionalText(input.phone),
|
|
1740
|
+
label: optionalText(input.label),
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
async function refreshAccountAddresses(token: string): Promise<AccountAddressView[]> {
|
|
1745
|
+
const addresses = await loadCustomerAddresses(token)
|
|
1746
|
+
return addresses.map(toAccountAddress)
|
|
1747
|
+
}
|
|
1748
|
+
|
|
1749
|
+
/** Create an address in the authenticated customer's address book. */
|
|
1750
|
+
export async function createAccountAddressAction(
|
|
1751
|
+
input: AccountAddressInput,
|
|
1752
|
+
): Promise<AccountAddressMutationResult> {
|
|
1753
|
+
const token = await readAccountToken()
|
|
1754
|
+
if (!token) return { ok: false, error: 'Inicia sesión para guardar direcciones.' }
|
|
1755
|
+
const fieldErrors = validateAccountAddress(input)
|
|
1756
|
+
if (Object.keys(fieldErrors).length > 0) {
|
|
1757
|
+
return { ok: false, error: 'Revisa la dirección antes de guardarla.', fieldErrors }
|
|
1758
|
+
}
|
|
1759
|
+
try {
|
|
1760
|
+
await createCustomerAddress(token, toAddressData(input))
|
|
1761
|
+
return { ok: true, addresses: await refreshAccountAddresses(token) }
|
|
1762
|
+
} catch (error) {
|
|
1763
|
+
logServerError('createAccountAddressAction', error)
|
|
1764
|
+
return { ok: false, error: toError(error, 'No se pudo guardar la dirección.') }
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1768
|
+
/** Update a saved address; omitted optional values are preserved by the adapter. */
|
|
1769
|
+
export async function updateAccountAddressAction(
|
|
1770
|
+
input: AccountAddressInput & { id: string },
|
|
1771
|
+
): Promise<AccountAddressMutationResult> {
|
|
1772
|
+
const token = await readAccountToken()
|
|
1773
|
+
if (!token) return { ok: false, error: 'Inicia sesión para guardar direcciones.' }
|
|
1774
|
+
const fieldErrors = validateAccountAddress(input)
|
|
1775
|
+
if (Object.keys(fieldErrors).length > 0) {
|
|
1776
|
+
return { ok: false, error: 'Revisa la dirección antes de guardarla.', fieldErrors }
|
|
1777
|
+
}
|
|
1778
|
+
try {
|
|
1779
|
+
await updateCustomerAddress(token, input.id, toAddressData(input))
|
|
1780
|
+
return { ok: true, addresses: await refreshAccountAddresses(token) }
|
|
1781
|
+
} catch (error) {
|
|
1782
|
+
logServerError('updateAccountAddressAction', error)
|
|
1783
|
+
return { ok: false, error: toError(error, 'No se pudo guardar la dirección.') }
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
|
|
1787
|
+
/** Delete a saved address; the backend enforces ownership. */
|
|
1788
|
+
export async function deleteAccountAddressAction(input: {
|
|
1789
|
+
id: string
|
|
1790
|
+
}): Promise<AccountAddressMutationResult> {
|
|
1791
|
+
const token = await readAccountToken()
|
|
1792
|
+
if (!token) return { ok: false, error: 'Inicia sesión para eliminar direcciones.' }
|
|
1793
|
+
try {
|
|
1794
|
+
await deleteCustomerAddress(token, input.id)
|
|
1795
|
+
return { ok: true, addresses: await refreshAccountAddresses(token) }
|
|
1796
|
+
} catch (error) {
|
|
1797
|
+
logServerError('deleteAccountAddressAction', error)
|
|
1798
|
+
return { ok: false, error: toError(error, 'No se pudo eliminar la dirección.') }
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
/** Mark an address as the default shipping or billing address. */
|
|
1803
|
+
export async function setDefaultAccountAddressAction(input: {
|
|
1804
|
+
id: string
|
|
1805
|
+
kind: 'shipping' | 'billing'
|
|
1806
|
+
}): Promise<AccountAddressMutationResult> {
|
|
1807
|
+
const token = await readAccountToken()
|
|
1808
|
+
if (!token) return { ok: false, error: 'Inicia sesión para actualizar direcciones.' }
|
|
1809
|
+
try {
|
|
1810
|
+
await updateCustomerAddress(
|
|
1811
|
+
token,
|
|
1812
|
+
input.id,
|
|
1813
|
+
input.kind === 'shipping' ? { isDefaultShipping: true } : { isDefaultBilling: true },
|
|
1814
|
+
)
|
|
1815
|
+
return { ok: true, addresses: await refreshAccountAddresses(token) }
|
|
1816
|
+
} catch (error) {
|
|
1817
|
+
logServerError('setDefaultAccountAddressAction', error)
|
|
1818
|
+
return { ok: false, error: toError(error, 'No se pudo actualizar la dirección.') }
|
|
1819
|
+
}
|
|
1820
|
+
}
|