@thorprovider/storefront 0.7.0 → 0.10.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.
Files changed (164) hide show
  1. package/README.md +22 -2
  2. package/assets/templates/AGENTS.md +14 -2
  3. package/assets/templates/app/app/[[...slug]]/page.tsx +9 -2
  4. package/assets/templates/app/lib/__STOREFRONT__/account-address.ts +129 -0
  5. package/assets/templates/app/lib/__STOREFRONT__/account-lifecycle.client.tsx +2 -2
  6. package/assets/templates/app/lib/__STOREFRONT__/account-private.core.ts +143 -0
  7. package/assets/templates/app/lib/__STOREFRONT__/account-profile.ts +220 -0
  8. package/assets/templates/app/lib/__STOREFRONT__/actions.ts +677 -80
  9. package/assets/templates/app/lib/__STOREFRONT__/addresses-port.ts +107 -0
  10. package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +477 -38
  11. package/assets/templates/app/lib/__STOREFRONT__/confirmation.core.ts +240 -0
  12. package/assets/templates/app/lib/__STOREFRONT__/customer-profile-port.ts +103 -0
  13. package/assets/templates/app/lib/__STOREFRONT__/fulfillment-evidence-port.ts +31 -0
  14. package/assets/templates/app/lib/__STOREFRONT__/handlers.core.ts +21 -4
  15. package/assets/templates/app/lib/__STOREFRONT__/mappers.ts +6 -2
  16. package/assets/templates/app/lib/__STOREFRONT__/order-detail-mapper.ts +642 -0
  17. package/assets/templates/app/lib/__STOREFRONT__/order-detail-port.ts +25 -0
  18. package/assets/templates/app/lib/__STOREFRONT__/orders-port.ts +30 -0
  19. package/assets/templates/app/lib/__STOREFRONT__/ports.ts +28 -0
  20. package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.client.tsx +4 -4
  21. package/assets/templates/app/lib/__STOREFRONT__/session.ts +24 -6
  22. package/assets/templates/app/lib/__STOREFRONT__/state.core.ts +21 -0
  23. package/assets/templates/app/lib/__STOREFRONT__/views/sections/address-book-advanced.client.tsx +29 -0
  24. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.client.tsx +19 -0
  25. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.tsx +16 -0
  26. package/assets/templates/app/lib/__STOREFRONT__/views/sections/customer-profile.client.tsx +27 -0
  27. package/assets/templates/app/lib/__STOREFRONT__/views/sections/index.ts +4 -1
  28. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.client.tsx +19 -0
  29. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.tsx +16 -0
  30. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.address-book-advanced.ts +437 -0
  31. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.checkout-commerce-v1.ts +398 -0
  32. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.customer-profile.ts +138 -0
  33. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.mega-menu-universal.ts +76 -0
  34. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.universal-banner.ts +217 -0
  35. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.client.tsx +24 -0
  36. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.tsx +16 -0
  37. package/assets/templates/features/checkout/handlers.ts +24 -4
  38. package/assets/templates/features/customer-addresses/handlers.ts +11 -0
  39. package/assets/templates/features/customer-addresses/state.ts +33 -0
  40. package/assets/templates/features/customer-auth/state.ts +10 -0
  41. package/assets/templates/features/customer-profile/handlers.ts +11 -0
  42. package/assets/templates/features/customer-profile/state.ts +18 -0
  43. package/assets/templates/views/account/address-book-advanced.defaults.ts +534 -0
  44. package/assets/templates/views/account/assembly/assembly.json +36 -0
  45. package/assets/templates/views/account/assembly/index.skeleton.tsx +277 -0
  46. package/assets/templates/views/account/assembly/registry.skeleton.tsx +1057 -0
  47. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/binding.json +5 -0
  48. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/catalog.part +4 -0
  49. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/element.part +5 -0
  50. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/registry.part +1 -0
  51. package/assets/templates/views/account/assembly/slots/addresses/cards/catalog.part +5 -0
  52. package/assets/templates/views/account/assembly/slots/addresses/cards/element.part +10 -0
  53. package/assets/templates/views/account/assembly/slots/addresses/cards/registry.part +1 -0
  54. package/assets/templates/views/account/assembly/slots/login/card/catalog.part +4 -0
  55. package/assets/templates/views/account/assembly/slots/login/card/element.part +13 -0
  56. package/assets/templates/views/account/assembly/slots/login/card/registry.part +1 -0
  57. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/catalog.part +5 -0
  58. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/element.part +5 -0
  59. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/registry.part +2 -0
  60. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/binding.json +5 -0
  61. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/catalog.part +5 -0
  62. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/element.part +5 -0
  63. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/registry.part +1 -0
  64. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/binding.json +5 -0
  65. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/catalog.part +4 -0
  66. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/element.part +5 -0
  67. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/registry.part +1 -0
  68. package/assets/templates/views/account/assembly/slots/profile/form/catalog.part +5 -0
  69. package/assets/templates/views/account/assembly/slots/profile/form/element.part +10 -0
  70. package/assets/templates/views/account/assembly/slots/profile/form/registry.part +1 -0
  71. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/catalog.part +4 -0
  72. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/element.part +13 -0
  73. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/registry.part +1 -0
  74. package/assets/templates/views/account/assembly/slots/summary/stack/catalog.part +5 -0
  75. package/assets/templates/views/account/assembly/slots/summary/stack/element.part +5 -0
  76. package/assets/templates/views/account/assembly/slots/summary/stack/registry.part +1 -0
  77. package/assets/templates/views/account/assembly/slots/summary/tabs/catalog.part +5 -0
  78. package/assets/templates/views/account/assembly/slots/summary/tabs/element.part +5 -0
  79. package/assets/templates/views/account/assembly/slots/summary/tabs/registry.part +1 -0
  80. package/assets/templates/views/account/content.ts +326 -0
  81. package/assets/templates/views/account/customer-profile.defaults.ts +136 -0
  82. package/assets/templates/views/account/fulfillment-evidence.client.tsx +34 -0
  83. package/assets/templates/views/account/fulfillment-evidence.defaults.ts +145 -0
  84. package/assets/templates/views/account/fulfillment-evidence.schema.ts +15 -0
  85. package/assets/templates/views/account/index.tsx +259 -38
  86. package/assets/templates/views/account/order-detail.client.tsx +35 -0
  87. package/assets/templates/views/account/order-detail.defaults.ts +457 -0
  88. package/assets/templates/views/account/orders-advanced.client.tsx +77 -0
  89. package/assets/templates/views/account/orders-advanced.defaults.ts +230 -0
  90. package/assets/templates/views/account/registry.tsx +935 -420
  91. package/assets/templates/views/account/schema.ts +50 -0
  92. package/assets/templates/views/account/sections-data.ts +2 -0
  93. package/assets/templates/views/cart/content.ts +1 -0
  94. package/assets/templates/views/category/assembly/index.skeleton.tsx +1 -0
  95. package/assets/templates/views/category/assembly/slots/filter/CategoryListing/element.part +1 -0
  96. package/assets/templates/views/category/content.ts +2 -0
  97. package/assets/templates/views/category/index.tsx +2 -0
  98. package/assets/templates/views/category/sections-data.ts +2 -0
  99. package/assets/templates/views/checkout/checkout-commerce-hosted.tsx +1089 -0
  100. package/assets/templates/views/checkout/content.ts +51 -0
  101. package/assets/templates/views/checkout/index.tsx +1 -1
  102. package/assets/templates/views/checkout/props.ts +10 -2
  103. package/assets/templates/views/checkout/registry.tsx +104 -42
  104. package/assets/templates/views/checkout/schema.ts +76 -1
  105. package/assets/templates/views/home/assembly/assembly.json +23 -2
  106. package/assets/templates/views/home/assembly/index.skeleton.tsx +4 -1
  107. package/assets/templates/views/home/assembly/registry.skeleton.tsx +1 -0
  108. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/binding.json +5 -0
  109. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/catalog.part +4 -0
  110. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/element.part +4 -0
  111. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/registry.part +10 -0
  112. package/assets/templates/views/home/content.ts +247 -1
  113. package/assets/templates/views/home/data.ts +10 -1
  114. package/assets/templates/views/home/index.tsx +8 -6
  115. package/assets/templates/views/home/props.ts +7 -1
  116. package/assets/templates/views/home/registry.tsx +11 -28
  117. package/assets/templates/views/home/schema.ts +163 -0
  118. package/assets/templates/views/home/sections-data.ts +2 -0
  119. package/assets/templates/views/product/content.ts +1 -0
  120. package/assets/templates/views/static/content.ts +1 -0
  121. package/bin/storefront.js +356 -27
  122. package/package.json +2 -1
  123. package/recipes/adapter-surface.json +159 -0
  124. package/recipes/archetypes.json +43 -4
  125. package/recipes/catalog.json +147 -2
  126. package/recipes/feature.schema.json +9 -0
  127. package/recipes/features.json +72 -1
  128. package/recipes/manifest.schema.json +5 -0
  129. package/recipes/recipe.schema.json +13 -1
  130. package/recipes/recipes.json +37 -7
  131. package/recipes/section.schema.json +112 -0
  132. package/recipes/sections.json +281 -4
  133. package/recipes/validate.mjs +83 -1
  134. package/scripts/adapter-surface.mjs +41 -0
  135. package/scripts/agent-blocks.mjs +700 -0
  136. package/scripts/block-validator.mjs +45 -0
  137. package/scripts/candidate.mjs +56 -14
  138. package/scripts/composers.mjs +7 -2
  139. package/scripts/default-sections.mjs +78 -0
  140. package/scripts/file-classes.mjs +18 -0
  141. package/scripts/generate-adapter-surface.mjs +148 -0
  142. package/scripts/operations.mjs +100 -0
  143. package/scripts/reconcile.mjs +67 -39
  144. package/scripts/section-configure.mjs +316 -0
  145. package/scripts/sync-assets.mjs +1 -0
  146. package/scripts/view-assembly.mjs +101 -14
  147. package/skills/sf-feature/SKILL.md +19 -0
  148. package/skills/sf-view-gen/SKILL.md +73 -7
  149. package/skills/sf-view-gen/assets/recipes/archetypes.json +43 -4
  150. package/skills/sf-view-gen/assets/recipes/catalog.json +147 -2
  151. package/skills/sf-view-gen/assets/recipes/features.json +72 -1
  152. package/skills/sf-view-gen/assets/recipes/recipes.json +37 -7
  153. package/skills/sf-view-gen/assets/recipes/section.schema.json +112 -0
  154. package/skills/sf-view-gen/assets/recipes/sections.json +281 -4
  155. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.client.tsx +19 -0
  156. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.tsx +16 -0
  157. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.client.tsx +19 -0
  158. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.tsx +16 -0
  159. package/skills/sf-view-gen/assets/templates/views/sections/schema.checkout-commerce-v1.ts +398 -0
  160. package/skills/sf-view-gen/assets/templates/views/sections/schema.mega-menu-universal.ts +76 -0
  161. package/skills/sf-view-gen/assets/templates/views/sections/schema.universal-banner.ts +217 -0
  162. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.client.tsx +24 -0
  163. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.tsx +16 -0
  164. package/skills/sf-view-gen/scripts/validate.mjs +83 -1
@@ -15,7 +15,7 @@
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, CartLineState } from './state.core'
18
+ import type { AccountAddressView, AccountOrderView, CartLineState } from './state.core'
19
19
  import type {
20
20
  Address,
21
21
  CheckoutAddressOption,
@@ -32,12 +32,14 @@ import type {
32
32
  CheckoutSavedAddress,
33
33
  CheckoutShippingGroup,
34
34
  } from '@thorprovider/blocks'
35
+ import type { OrderDetailSnapshot, OrdersPage, OrdersQuery } from '@thorprovider/blocks/ports'
35
36
  import {
36
37
  EMPTY_CART_STATE,
37
38
  addVariant,
38
39
  applyCheckoutShippingGroups,
39
40
  applyLineDelta,
40
41
  applyPayment,
42
+ assignCartToCustomer,
41
43
  authenticate,
42
44
  completeOrder,
43
45
  createGuestCart,
@@ -45,11 +47,14 @@ import {
45
47
  deleteCustomerAddress,
46
48
  endSession,
47
49
  loadCheckoutCountries,
50
+ loadCartCustomerId,
48
51
  loadCheckoutShippingGroups,
49
52
  loadCustomer,
50
53
  loadCustomerAddresses,
54
+ loadCustomerOrderDetail,
51
55
  loadGeoCities,
52
56
  loadGeoProvinces,
57
+ loadOrderHistoryPage,
53
58
  loadOrders,
54
59
  loadOrdersPage,
55
60
  loadPaymentMethods,
@@ -67,15 +72,18 @@ import {
67
72
  toCheckoutFieldErrors,
68
73
  toCheckoutShippingGroups,
69
74
  updateCustomerAddress,
75
+ updateCustomerProfile,
76
+ getHostCommerceProvider,
70
77
  validateAddress,
71
78
  validateCustomerAddress,
72
79
  type AddressInput,
73
80
  type CartStatePatch,
81
+ type HostCommerceProvider,
74
82
  type PlaceOrderResult,
75
83
  } from './commerce'
76
84
  import { readAccountSession } from './account-session'
77
85
  import { accountIdentitySchema, type AccountIdentity } from './account-session.core'
78
- import { getStoreContext } from './store-context'
86
+ import { getDataSource, getStoreContext } from './store-context'
79
87
  import {
80
88
  bindHostSessionCart,
81
89
  clearAuthToken,
@@ -84,6 +92,8 @@ import {
84
92
  readHostSession,
85
93
  writeAuthToken,
86
94
  } from './session'
95
+ import type { AccountProfileMetadataPatch, AccountProfilePayload } from './account-profile'
96
+ import { toOrderDetailSnapshot } from './order-detail-mapper'
87
97
 
88
98
  // A `'use server'` module may export ONLY async functions. Next/Turbopack's
89
99
  // server-actions transform registers every export as a runtime server
@@ -127,10 +137,22 @@ type CheckoutActionResult =
127
137
  ok: false
128
138
  error: string
129
139
  fieldErrors?: Record<string, unknown>
140
+ /** Stable machine code for a failure the UI must treat specially. */
141
+ code?: string
130
142
  /** Set by a failed grouped apply so the UI can distinguish unsupported. */
131
143
  shippingState?: CheckoutShippingState
132
144
  }
133
145
 
146
+ /** Raised when a checkout action requires an authenticated customer. */
147
+ class CheckoutAuthError extends Error {
148
+ readonly code = 'AUTH_REQUIRED'
149
+
150
+ constructor() {
151
+ super('Inicia sesión para continuar con el checkout.')
152
+ this.name = 'CheckoutAuthError'
153
+ }
154
+ }
155
+
134
156
  /**
135
157
  * Structured result for a login/register auth action. It carries ONLY the
136
158
  * allowlisted display identity (id/email/names) — never a token or customer
@@ -166,6 +188,21 @@ type OrdersPageActionResult =
166
188
  | { ok: true; orders: AccountOrderView[]; count: number; limit: number; offset: number }
167
189
  | { ok: false; error: string }
168
190
 
191
+ /** Structured result for one advanced order-history port query. */
192
+ type OrdersQueryPageActionResult =
193
+ | { ok: true; page: OrdersPage }
194
+ | { ok: false; error: string }
195
+
196
+ /**
197
+ * Structured result for the order-detail route. The code is the contract the
198
+ * host port maps to a `PortError`: `forbidden` (no session), `not_found`
199
+ * (unknown or foreign order) and `unavailable` (no detail read configured or a
200
+ * provider failure). It never carries a fabricated order.
201
+ */
202
+ type OrderDetailActionResult =
203
+ | { ok: true; snapshot: OrderDetailSnapshot }
204
+ | { ok: false; code: 'forbidden' | 'not_found' | 'unavailable'; error: string }
205
+
169
206
  /** Basic email shape check; a boundary guard, not a full RFC validation. */
170
207
  const EMAIL_PATTERN = /\S+@\S+\.\S+/
171
208
 
@@ -203,6 +240,17 @@ function toError(error: unknown, fallback: string): string {
203
240
  return error instanceof Error && error.message.trim() !== '' ? error.message : fallback
204
241
  }
205
242
 
243
+ /** Preserve the auth code so the checkout boot can send the shopper to login. */
244
+ function toCheckoutActionError(
245
+ error: unknown,
246
+ fallback: string,
247
+ ): { ok: false; error: string; code?: string } {
248
+ if (error instanceof CheckoutAuthError) {
249
+ return { ok: false, error: error.message, code: error.code }
250
+ }
251
+ return { ok: false, error: toError(error, fallback) }
252
+ }
253
+
206
254
  /**
207
255
  * Allowlist a backend customer to the serializable display identity before it
208
256
  * crosses the Server Action boundary. Returns `null` for a confirmed anonymous
@@ -217,30 +265,122 @@ function toDisplayIdentity(customer: Customer | null): AccountIdentity | null |
217
265
  return parsed.success ? parsed.data : undefined
218
266
  }
219
267
 
268
+ type ActiveCartContext = {
269
+ cartId: string
270
+ context: ReturnType<typeof getStoreContext>
271
+ token: string | null
272
+ provider: HostCommerceProvider
273
+ customerId: string | null
274
+ }
275
+
276
+ /** Read the authenticated customer without letting an expired token break a cart. */
277
+ async function resolveHostCustomer(token: string | null) {
278
+ if (!token) return null
279
+ try {
280
+ return await loadCustomer(token)
281
+ } catch (error) {
282
+ logServerError('resolveHostCustomer', error)
283
+ return null
284
+ }
285
+ }
286
+
220
287
  /**
221
- * Resolve the active cart id, creating and binding a new backend cart when the
222
- * session has none or its cart was completed. A new cart after a completed one
223
- * keeps the SAME shopper and preserves the prior receipt cart id, so the
224
- * receipt proof cookie is never lost.
288
+ * Resolve the active cart for the current session.
289
+ *
290
+ * When a customer token is present the provider carries it, so a newly created
291
+ * cart belongs to the customer. If the session holds a guest cart, the cart is
292
+ * transferred to the authenticated customer before reuse; a cart that already
293
+ * belongs to a different customer is never reassigned — a new cart is created
294
+ * instead. `requireAuth` is used by checkout actions and fails closed.
225
295
  */
226
- async function ensureActiveCartId(): Promise<{ cartId: string; context: ReturnType<typeof getStoreContext> }> {
296
+ async function ensureActiveCartId(
297
+ options: { requireAuth?: boolean } = {},
298
+ ): Promise<ActiveCartContext> {
227
299
  const context = getStoreContext()
300
+ const token = await readAuthToken(context)
301
+ const customer = await resolveHostCustomer(token)
302
+
303
+ // Real mode requires an authenticated customer. Mock mode is an explicit,
304
+ // labelled fixture with no auth surface, so it keeps the demo checkout usable.
305
+ const authRequired = options.requireAuth === true && getDataSource() === 'medusa'
306
+ if (authRequired && !customer) throw new CheckoutAuthError()
307
+
308
+ const provider = getHostCommerceProvider(customer ? token : null)
228
309
  const session = await readHostSession(context)
310
+
229
311
  if (session?.cartId) {
230
- const existing = await readCart(session.cartId, context)
231
- if (existing && !existing.cartCompleted) return { cartId: session.cartId, context }
312
+ try {
313
+ const existing = await readCart(session.cartId, context, provider)
314
+ if (existing && !existing.cartCompleted) {
315
+ if (!customer) {
316
+ return {
317
+ cartId: session.cartId,
318
+ context,
319
+ token,
320
+ provider,
321
+ customerId: null,
322
+ }
323
+ }
324
+
325
+ const owner = await loadCartCustomerId(session.cartId, context, provider)
326
+ if (owner === customer.id) {
327
+ return {
328
+ cartId: session.cartId,
329
+ context,
330
+ token,
331
+ provider,
332
+ customerId: customer.id,
333
+ }
334
+ }
335
+
336
+ if (owner === null) {
337
+ const linked = await assignCartToCustomer(session.cartId, context, provider)
338
+ if (linked.cartId) {
339
+ await bindHostSessionCart(context, linked.cartId)
340
+ return {
341
+ cartId: linked.cartId,
342
+ context,
343
+ token,
344
+ provider,
345
+ customerId: customer.id,
346
+ }
347
+ }
348
+ }
349
+ }
350
+ } catch (error) {
351
+ // A stale, foreign-channel or otherwise unreadable cart is replaced.
352
+ logServerError('ensureActiveCartId', error)
353
+ }
232
354
  }
233
- const created = await createGuestCart(context)
355
+
356
+ const created = await createGuestCart(context, provider)
234
357
  if (!created.cartId) throw new Error('Cart creation returned no id')
358
+
359
+ if (customer) {
360
+ try {
361
+ await assignCartToCustomer(created.cartId, context, provider)
362
+ } catch (error) {
363
+ // The authenticated create normally links the customer; a transfer failure
364
+ // is logged and the backend ownership check remains authoritative.
365
+ logServerError('assignCartToCustomer', error)
366
+ }
367
+ }
368
+
235
369
  await bindHostSessionCart(context, created.cartId)
236
- return { cartId: created.cartId, context }
370
+ return {
371
+ cartId: created.cartId,
372
+ context,
373
+ token,
374
+ provider,
375
+ customerId: customer?.id ?? null,
376
+ }
237
377
  }
238
378
 
239
379
  /** Ensure a guest cart exists and return its authoritative snapshot. */
240
380
  export async function ensureCartAction(): Promise<CartActionResult> {
241
381
  try {
242
- const { cartId, context } = await ensureActiveCartId()
243
- return { ok: true, cart: (await readCart(cartId, context)) ?? EMPTY_CART_STATE }
382
+ const { cartId, context, provider } = await ensureActiveCartId()
383
+ return { ok: true, cart: (await readCart(cartId, context, provider)) ?? EMPTY_CART_STATE }
244
384
  } catch (error) {
245
385
  return { ok: false, error: toError(error, 'No se pudo iniciar el carrito.') }
246
386
  }
@@ -254,8 +394,11 @@ export async function addToCartAction(input: {
254
394
  try {
255
395
  if (!input?.variantId) return { ok: false, error: 'Selecciona una variante antes de agregar.' }
256
396
  const quantity = Number.isFinite(input.quantity) && input.quantity > 0 ? Math.floor(input.quantity) : 1
257
- const { cartId, context } = await ensureActiveCartId()
258
- return { ok: true, cart: await addVariant(cartId, input.variantId, quantity, context) }
397
+ const { cartId, context, provider } = await ensureActiveCartId()
398
+ return {
399
+ ok: true,
400
+ cart: await addVariant(cartId, input.variantId, quantity, context, provider),
401
+ }
259
402
  } catch (error) {
260
403
  return { ok: false, error: toError(error, 'No se pudo agregar el producto.') }
261
404
  }
@@ -284,8 +427,11 @@ export async function addToCartByHandleAction(input: {
284
427
  const { detail } = await loadProductDetail(productHandle)
285
428
  const target = resolveProductCartTarget(detail)
286
429
  if (!target.ok) return { ok: false, error: target.error }
287
- const { cartId, context } = await ensureActiveCartId()
288
- return { ok: true, cart: await addVariant(cartId, target.variantId, quantity, context) }
430
+ const { cartId, context, provider } = await ensureActiveCartId()
431
+ return {
432
+ ok: true,
433
+ cart: await addVariant(cartId, target.variantId, quantity, context, provider),
434
+ }
289
435
  } catch (error) {
290
436
  return { ok: false, error: toError(error, 'No se pudo agregar el producto.') }
291
437
  }
@@ -299,10 +445,17 @@ export async function setLineQuantityAction(input: {
299
445
  }): Promise<CartActionResult> {
300
446
  try {
301
447
  const quantity = Math.max(1, Math.floor(input.quantity))
302
- const { cartId, context } = await ensureActiveCartId()
448
+ const { cartId, context, provider } = await ensureActiveCartId()
303
449
  return {
304
450
  ok: true,
305
- cart: await setLineQuantity(cartId, input.lineId, input.merchandiseId, quantity, context),
451
+ cart: await setLineQuantity(
452
+ cartId,
453
+ input.lineId,
454
+ input.merchandiseId,
455
+ quantity,
456
+ context,
457
+ provider,
458
+ ),
306
459
  }
307
460
  } catch (error) {
308
461
  return { ok: false, error: toError(error, 'No se pudo actualizar la cantidad.') }
@@ -319,8 +472,11 @@ export async function applyQuantityDeltaAction(input: {
319
472
  delta: number
320
473
  }): Promise<CartActionResult> {
321
474
  try {
322
- const { cartId, context } = await ensureActiveCartId()
323
- return { ok: true, cart: await applyLineDelta(cartId, input.lineId, input.delta, context) }
475
+ const { cartId, context, provider } = await ensureActiveCartId()
476
+ return {
477
+ ok: true,
478
+ cart: await applyLineDelta(cartId, input.lineId, input.delta, context, provider),
479
+ }
324
480
  } catch (error) {
325
481
  return { ok: false, error: toError(error, 'No se pudo actualizar la cantidad.') }
326
482
  }
@@ -329,8 +485,8 @@ export async function applyQuantityDeltaAction(input: {
329
485
  /** Remove a backend cart line by its line-item id. */
330
486
  export async function removeLineAction(input: { lineId: string }): Promise<CartActionResult> {
331
487
  try {
332
- const { cartId, context } = await ensureActiveCartId()
333
- return { ok: true, cart: await removeLine(cartId, input.lineId, context) }
488
+ const { cartId, context, provider } = await ensureActiveCartId()
489
+ return { ok: true, cart: await removeLine(cartId, input.lineId, context, provider) }
334
490
  } catch (error) {
335
491
  return { ok: false, error: toError(error, 'No se pudo quitar el producto.') }
336
492
  }
@@ -415,9 +571,10 @@ async function loadMappedShippingGroups(
415
571
  cartLines: CartLineState[],
416
572
  previous: CheckoutShippingGroup[] | undefined,
417
573
  context: ReturnType<typeof getStoreContext>,
574
+ provider?: HostCommerceProvider,
418
575
  ): Promise<CheckoutShippingGroupsLoad> {
419
576
  try {
420
- const quote = await loadCheckoutShippingGroups(cartId, context)
577
+ const quote = await loadCheckoutShippingGroups(cartId, context, provider)
421
578
  const mapped = toCheckoutShippingGroups(quote, cartLines, previous)
422
579
  return { groups: mapped.groups, productsByGroup: mapped.productsByGroup }
423
580
  } catch (error) {
@@ -449,8 +606,8 @@ export async function syncCheckoutAddressAction(
449
606
  values: Record<string, unknown>,
450
607
  ): Promise<CheckoutActionResult> {
451
608
  try {
452
- const { cartId, context } = await ensureActiveCartId()
453
- const countries = await loadCheckoutCountries(cartId, context)
609
+ const { cartId, context, provider } = await ensureActiveCartId({ requireAuth: true })
610
+ const countries = await loadCheckoutCountries(cartId, context, provider)
454
611
  const validation = validateAddress(toAddressInput(values), countries)
455
612
  if (!validation.success) {
456
613
  return {
@@ -459,8 +616,14 @@ export async function syncCheckoutAddressAction(
459
616
  fieldErrors: toCheckoutFieldErrors(validation.errors),
460
617
  }
461
618
  }
462
- const cart = await saveShippingAddress(cartId, validation.address, context)
463
- const shipping = await loadMappedShippingGroups(cartId, cart.cart, undefined, context)
619
+ const cart = await saveShippingAddress(cartId, validation.address, context, provider)
620
+ const shipping = await loadMappedShippingGroups(
621
+ cartId,
622
+ cart.cart,
623
+ undefined,
624
+ context,
625
+ provider,
626
+ )
464
627
  return {
465
628
  ok: true,
466
629
  cart,
@@ -471,7 +634,7 @@ export async function syncCheckoutAddressAction(
471
634
  : {}),
472
635
  }
473
636
  } catch (error) {
474
- return { ok: false, error: toError(error, 'No se pudo validar la dirección.') }
637
+ return toCheckoutActionError(error, 'No se pudo validar la dirección.')
475
638
  }
476
639
  }
477
640
 
@@ -484,11 +647,11 @@ export async function selectShippingMethodAction(input: {
484
647
  methodId: string
485
648
  }): Promise<CheckoutActionResult> {
486
649
  try {
487
- const { cartId, context } = await ensureActiveCartId()
488
- const cart = await selectShipping(cartId, input.methodId, context)
650
+ const { cartId, context, provider } = await ensureActiveCartId({ requireAuth: true })
651
+ const cart = await selectShipping(cartId, input.methodId, context, provider)
489
652
  return { ok: true, cart }
490
653
  } catch (error) {
491
- return { ok: false, error: toError(error, 'No se pudo seleccionar el envío.') }
654
+ return toCheckoutActionError(error, 'No se pudo seleccionar el envío.')
492
655
  }
493
656
  }
494
657
 
@@ -506,10 +669,18 @@ export async function applyCheckoutShippingGroupsAction(input: {
506
669
  if (!Array.isArray(input?.shippingGroups)) {
507
670
  return { ok: false, error: 'No se recibieron opciones de envío.' }
508
671
  }
509
- const { cartId, context } = await ensureActiveCartId()
510
- const cart = await applyCheckoutShippingGroups(cartId, input.shippingGroups, context)
672
+ const { cartId, context, provider } = await ensureActiveCartId({ requireAuth: true })
673
+ const cart = await applyCheckoutShippingGroups(
674
+ cartId,
675
+ input.shippingGroups,
676
+ context,
677
+ provider,
678
+ )
511
679
  return { ok: true, cart }
512
680
  } catch (error) {
681
+ if (error instanceof CheckoutAuthError) {
682
+ return { ok: false, error: error.message, code: error.code }
683
+ }
513
684
  // Same boundary policy as the quote path: the provider/backend detail is
514
685
  // logged server-side and the shopper gets one fixed, user-safe message. An
515
686
  // unsupported provider is `unavailable` (retrying cannot help).
@@ -536,11 +707,11 @@ export async function loadCheckoutAction(
536
707
  input: { previousShippingGroups?: CheckoutShippingGroup[] } = {},
537
708
  ): Promise<CheckoutActionResult> {
538
709
  try {
539
- const { cartId, context } = await ensureActiveCartId()
710
+ const { cartId, context, provider } = await ensureActiveCartId({ requireAuth: true })
540
711
  const [regionCountries, paymentMethods, cart] = await Promise.all([
541
- loadCheckoutCountries(cartId, context),
542
- loadPaymentMethods(context),
543
- readCart(cartId, context),
712
+ loadCheckoutCountries(cartId, context, provider),
713
+ loadPaymentMethods(context, provider),
714
+ readCart(cartId, context, provider),
544
715
  ])
545
716
  const patch = cart ?? EMPTY_CART_STATE
546
717
  const shipping = await loadMappedShippingGroups(
@@ -548,6 +719,7 @@ export async function loadCheckoutAction(
548
719
  patch.cart,
549
720
  input?.previousShippingGroups,
550
721
  context,
722
+ provider,
551
723
  )
552
724
  return {
553
725
  ok: true,
@@ -561,7 +733,7 @@ export async function loadCheckoutAction(
561
733
  : {}),
562
734
  }
563
735
  } catch (error) {
564
- return { ok: false, error: toError(error, 'No se pudo cargar el checkout.') }
736
+ return toCheckoutActionError(error, 'No se pudo cargar el checkout.')
565
737
  }
566
738
  }
567
739
 
@@ -572,7 +744,7 @@ type CheckoutPrefillPayload = ReturnType<typeof prefillCheckoutFromCustomer> & {
572
744
 
573
745
  type CheckoutPrefillActionResult =
574
746
  | ({ ok: true } & CheckoutPrefillPayload)
575
- | { ok: false; error: string }
747
+ | { ok: false; error: string; code?: string }
576
748
 
577
749
  type CheckoutLocationsActionResult =
578
750
  | { ok: true; options: CheckoutAddressOption[] }
@@ -584,7 +756,7 @@ type CheckoutSavedAddressActionResult =
584
756
  savedAddresses: CheckoutSavedAddress[]
585
757
  savedAddressId?: string
586
758
  }
587
- | { ok: false; error: string; fieldErrors?: Record<string, unknown> }
759
+ | { ok: false; error: string; code?: string; fieldErrors?: Record<string, unknown> }
588
760
 
589
761
  function toSavedAddress(address: Address, index: number): CheckoutSavedAddress {
590
762
  const optional = (value: string | undefined): string | undefined => {
@@ -642,8 +814,8 @@ export async function createCheckoutAddressAction(
642
814
  return { ok: false, error: 'Inicia sesión para guardar direcciones.' }
643
815
  }
644
816
 
645
- const { cartId } = await ensureActiveCartId()
646
- const countries = await loadCheckoutCountries(cartId, context)
817
+ const { cartId, provider } = await ensureActiveCartId({ requireAuth: true })
818
+ const countries = await loadCheckoutCountries(cartId, context, provider)
647
819
  const validation = validateCustomerAddress(address, countries)
648
820
  if (!validation.success) {
649
821
  return {
@@ -667,10 +839,7 @@ export async function createCheckoutAddressAction(
667
839
  }
668
840
  } catch (error) {
669
841
  logServerError('createCheckoutAddressAction', error)
670
- return {
671
- ok: false,
672
- error: toError(error, 'No se pudo guardar la dirección.'),
673
- }
842
+ return toCheckoutActionError(error, 'No se pudo guardar la dirección.')
674
843
  }
675
844
  }
676
845
 
@@ -686,8 +855,8 @@ export async function updateCheckoutAddressAction(input: {
686
855
  return { ok: false, error: 'Inicia sesión para actualizar direcciones.' }
687
856
  }
688
857
 
689
- const { cartId } = await ensureActiveCartId()
690
- const countries = await loadCheckoutCountries(cartId, context)
858
+ const { cartId, provider } = await ensureActiveCartId({ requireAuth: true })
859
+ const countries = await loadCheckoutCountries(cartId, context, provider)
691
860
  const validation = validateCustomerAddress(input.address, countries)
692
861
  if (!validation.success) {
693
862
  return {
@@ -703,10 +872,7 @@ export async function updateCheckoutAddressAction(input: {
703
872
  return { ok: true, savedAddresses, savedAddressId: input.id }
704
873
  } catch (error) {
705
874
  logServerError('updateCheckoutAddressAction', error)
706
- return {
707
- ok: false,
708
- error: toError(error, 'No se pudo actualizar la dirección.'),
709
- }
875
+ return toCheckoutActionError(error, 'No se pudo actualizar la dirección.')
710
876
  }
711
877
  }
712
878
 
@@ -727,10 +893,7 @@ export async function deleteCheckoutAddressAction(input: {
727
893
  return { ok: true, savedAddresses, savedAddressId: input.id }
728
894
  } catch (error) {
729
895
  logServerError('deleteCheckoutAddressAction', error)
730
- return {
731
- ok: false,
732
- error: toError(error, 'No se pudo eliminar la dirección.'),
733
- }
896
+ return toCheckoutActionError(error, 'No se pudo eliminar la dirección.')
734
897
  }
735
898
  }
736
899
 
@@ -749,8 +912,8 @@ export async function loadCheckoutPrefillAction(
749
912
  } = {},
750
913
  ): Promise<CheckoutPrefillActionResult> {
751
914
  try {
752
- const { cartId, context } = await ensureActiveCartId()
753
- const regionCountries = await loadCheckoutCountries(cartId, context)
915
+ const { cartId, context, provider, token } = await ensureActiveCartId({ requireAuth: true })
916
+ const regionCountries = await loadCheckoutCountries(cartId, context, provider)
754
917
  const countries = regionCountries.map((country) => ({
755
918
  value: country.code,
756
919
  label: country.name,
@@ -772,7 +935,6 @@ export async function loadCheckoutPrefillAction(
772
935
  sameAsShipping: input.sameAsShipping,
773
936
  }
774
937
 
775
- const token = await readAuthToken(context)
776
938
  if (!token) {
777
939
  const result = prefillCheckoutFromCustomer({
778
940
  cart: cartInput,
@@ -819,10 +981,7 @@ export async function loadCheckoutPrefillAction(
819
981
  return { ok: true, ...result, shippingLocations, billingLocations }
820
982
  }
821
983
  } catch (error) {
822
- return {
823
- ok: false,
824
- error: toError(error, 'No se pudo cargar la información del cliente.'),
825
- }
984
+ return toCheckoutActionError(error, 'No se pudo cargar la información del cliente.')
826
985
  }
827
986
  }
828
987
 
@@ -876,8 +1035,8 @@ export async function syncCheckoutAddressStructuredAction(input: {
876
1035
  previousShippingGroups?: CheckoutShippingGroup[]
877
1036
  }): Promise<CheckoutActionResult> {
878
1037
  try {
879
- const { cartId, context } = await ensureActiveCartId()
880
- const countries = await loadCheckoutCountries(cartId, context)
1038
+ const { cartId, context, provider } = await ensureActiveCartId({ requireAuth: true })
1039
+ const countries = await loadCheckoutCountries(cartId, context, provider)
881
1040
  const validation = validateAddress(
882
1041
  {
883
1042
  email: input.contact.email,
@@ -902,7 +1061,7 @@ export async function syncCheckoutAddressStructuredAction(input: {
902
1061
  }
903
1062
  }
904
1063
 
905
- const cart = await saveShippingAddress(cartId, validation.address, context)
1064
+ const cart = await saveShippingAddress(cartId, validation.address, context, provider)
906
1065
  if (!input.sameAsShipping && input.billingAddress) {
907
1066
  await saveBillingAddress(
908
1067
  cartId,
@@ -919,6 +1078,7 @@ export async function syncCheckoutAddressStructuredAction(input: {
919
1078
  phone: input.billingAddress.phone ?? '',
920
1079
  },
921
1080
  context,
1081
+ provider,
922
1082
  )
923
1083
  }
924
1084
 
@@ -927,6 +1087,7 @@ export async function syncCheckoutAddressStructuredAction(input: {
927
1087
  cart.cart,
928
1088
  input.previousShippingGroups,
929
1089
  context,
1090
+ provider,
930
1091
  )
931
1092
  return {
932
1093
  ok: true,
@@ -938,7 +1099,7 @@ export async function syncCheckoutAddressStructuredAction(input: {
938
1099
  : {}),
939
1100
  }
940
1101
  } catch (error) {
941
- return { ok: false, error: toError(error, 'No se pudo validar la dirección.') }
1102
+ return toCheckoutActionError(error, 'No se pudo validar la dirección.')
942
1103
  }
943
1104
  }
944
1105
 
@@ -976,15 +1137,30 @@ async function clearConfirmedSession(
976
1137
  * a committed order as a retryable failure.
977
1138
  */
978
1139
  export async function placeOrderAction(
979
- input: { shippingGroups?: ShippingGroupSelection[] } = {},
1140
+ input: { shippingGroups?: ShippingGroupSelection[]; paymentMethodId?: string } = {},
980
1141
  ): Promise<PlaceOrderResult> {
981
1142
  try {
982
- const context = getStoreContext()
983
- const session = await readHostSession(context)
984
- if (!session?.cartId) {
985
- return { status: 'error', message: 'No hay un carrito activo.' }
1143
+ const { cartId, context, provider, customerId } = await ensureActiveCartId({
1144
+ requireAuth: true,
1145
+ })
1146
+ if (!customerId && getDataSource() === 'medusa') {
1147
+ return {
1148
+ status: 'error',
1149
+ message: 'Inicia sesión para completar el pedido.',
1150
+ code: 'AUTH_REQUIRED',
1151
+ }
986
1152
  }
987
- const cartId = session.cartId
1153
+
1154
+ const paymentMethodId =
1155
+ typeof input.paymentMethodId === 'string' ? input.paymentMethodId.trim() : ''
1156
+ if (!paymentMethodId) {
1157
+ return {
1158
+ status: 'error',
1159
+ message: 'Selecciona un método de pago antes de confirmar.',
1160
+ code: 'PAYMENT_METHOD_REQUIRED',
1161
+ }
1162
+ }
1163
+
988
1164
  const shippingGroups = input?.shippingGroups
989
1165
  if (shippingGroups) {
990
1166
  // An explicitly empty selection set means the delivery step was not
@@ -999,7 +1175,7 @@ export async function placeOrderAction(
999
1175
  }
1000
1176
  }
1001
1177
  try {
1002
- await applyCheckoutShippingGroups(cartId, shippingGroups, context)
1178
+ await applyCheckoutShippingGroups(cartId, shippingGroups, context, provider)
1003
1179
  } catch (error) {
1004
1180
  // Logged server-side only; the shopper gets a fixed recoverable message.
1005
1181
  logServerError('applyCheckoutShippingGroups', error)
@@ -1011,12 +1187,20 @@ export async function placeOrderAction(
1011
1187
  }
1012
1188
  }
1013
1189
  try {
1014
- await applyPayment(cartId, context)
1190
+ await applyPayment(cartId, paymentMethodId, context, provider)
1015
1191
  } catch (error) {
1016
1192
  logServerError('applyPayment', error)
1017
- return { status: 'error', message: toError(error, 'No se pudo iniciar el pago.') }
1193
+ return {
1194
+ status: 'error',
1195
+ message: toError(error, 'No se pudo iniciar el pago.'),
1196
+ code: 'PAYMENT_METHOD_REJECTED',
1197
+ }
1018
1198
  }
1019
- const result = await completeOrder(cartId, context)
1199
+ // Thread the request's customer token (design D11) so an authenticated
1200
+ // checkout is attributed to the session customer; guests complete the same
1201
+ // tokenless provider as before.
1202
+ const customerToken = await readAuthToken(context)
1203
+ const result = await completeOrder(cartId, context, customerToken)
1020
1204
  if (result.status !== 'order') return result
1021
1205
  if (!(await clearConfirmedSession(context, cartId))) {
1022
1206
  return {
@@ -1027,6 +1211,9 @@ export async function placeOrderAction(
1027
1211
  }
1028
1212
  return result
1029
1213
  } catch (error) {
1214
+ if (error instanceof CheckoutAuthError) {
1215
+ return { status: 'error', message: error.message, code: error.code }
1216
+ }
1030
1217
  // An unexpected failure during completion is ambiguous: never a blind retry.
1031
1218
  logServerError('placeOrderAction', error)
1032
1219
  return {
@@ -1047,10 +1234,22 @@ export async function placeOrderAction(
1047
1234
  export async function reconcileReceiptAction(): Promise<PlaceOrderResult> {
1048
1235
  try {
1049
1236
  const context = getStoreContext()
1237
+ const token = await readAuthToken(context)
1238
+ if (!token && getDataSource() === 'medusa') {
1239
+ return {
1240
+ status: 'error',
1241
+ message: 'Inicia sesión para recuperar el comprobante.',
1242
+ code: 'AUTH_REQUIRED',
1243
+ }
1244
+ }
1245
+ const provider = getHostCommerceProvider(token)
1050
1246
  const session = await readHostSession(context)
1051
1247
  if (!session) {
1052
1248
  return { status: 'unresolved', message: 'No hay un comprobante autorizado para esta sesión.' }
1053
1249
  }
1250
+ // Same threading as the completion (design D11): the reconcile completes
1251
+ // under the session customer when one is signed in.
1252
+ const customerToken = await readAuthToken(context)
1054
1253
 
1055
1254
  // An active cart is reconciled first: the runtime does a single GET and
1056
1255
  // only POSTs complete when the backend committed. A cart the backend did
@@ -1059,7 +1258,7 @@ export async function reconcileReceiptAction(): Promise<PlaceOrderResult> {
1059
1258
  // The active cart is only cleared when it is the committed cart; a new cart
1060
1259
  // started after an earlier order is preserved by the session core.
1061
1260
  if (session.cartId) {
1062
- const result = await reconcileOrder(session.cartId, context)
1261
+ const result = await reconcileOrder(session.cartId, context, customerToken)
1063
1262
  if (result.status === 'order') {
1064
1263
  await clearConfirmedSession(context, session.cartId)
1065
1264
  return result
@@ -1074,7 +1273,7 @@ export async function reconcileReceiptAction(): Promise<PlaceOrderResult> {
1074
1273
  if (!candidate) {
1075
1274
  return { status: 'unresolved', message: 'No hay un comprobante autorizado para esta sesión.' }
1076
1275
  }
1077
- const result = await reconcileOrder(candidate, context)
1276
+ const result = await reconcileOrder(candidate, context, customerToken)
1078
1277
  if (result.status === 'order') {
1079
1278
  await clearConfirmedSession(context, candidate)
1080
1279
  return result
@@ -1277,3 +1476,401 @@ export async function loadOrdersPageAction(input?: {
1277
1476
  return { ok: false, error: toError(error, 'No se pudieron cargar tus pedidos.') }
1278
1477
  }
1279
1478
  }
1479
+
1480
+ /**
1481
+ * One query window for the advanced order-history port. The block owns its
1482
+ * filtering, sorting and pagination UI; this action is the request-scoped read
1483
+ * behind `OrdersPort.list`, the same token-scoped history the canonical surface
1484
+ * reads. It touches ONLY the auth cookie — never the guest session cookie or the
1485
+ * cart — and no token is logged or returned. A missing token resolves to the
1486
+ * empty page without contacting the backend.
1487
+ */
1488
+ export async function listOrdersQueryPageAction(
1489
+ query: OrdersQuery,
1490
+ ): Promise<OrdersQueryPageActionResult> {
1491
+ const context = getStoreContext()
1492
+ const token = await readAuthToken(context)
1493
+ try {
1494
+ const page = await loadOrderHistoryPage(token, query, context)
1495
+ return { ok: true, page }
1496
+ } catch (error) {
1497
+ logServerError('listOrdersQueryPageAction', error)
1498
+ return { ok: false, error: toError(error, 'No se pudieron cargar tus pedidos.') }
1499
+ }
1500
+ }
1501
+
1502
+ /**
1503
+ * Load ONE order for the authenticated customer and project it into the
1504
+ * order-detail snapshot. It touches ONLY the auth cookie — never the guest cart
1505
+ * — and no token is logged or returned. No token yields `forbidden` without a
1506
+ * backend call; an unknown or foreign order yields `not_found` without
1507
+ * revealing whether it exists. A provider without a customer detail read fails
1508
+ * closed as `unavailable`; the detail is never assembled from the list.
1509
+ */
1510
+ export async function loadOrderDetailAction(input: {
1511
+ id: string
1512
+ }): Promise<OrderDetailActionResult> {
1513
+ const id = typeof input?.id === 'string' ? input.id.trim() : ''
1514
+ if (!id) {
1515
+ return { ok: false, code: 'not_found', error: 'Pedido no encontrado.' }
1516
+ }
1517
+ const context = getStoreContext()
1518
+ const token = await readAuthToken(context)
1519
+ if (!token) {
1520
+ return {
1521
+ ok: false,
1522
+ code: 'forbidden',
1523
+ error: 'Inicia sesión con una cuenta autorizada para consultar el pedido.',
1524
+ }
1525
+ }
1526
+ try {
1527
+ const order = await loadCustomerOrderDetail(token, id, context)
1528
+ return { ok: true, snapshot: toOrderDetailSnapshot(order) }
1529
+ } catch (error) {
1530
+ const code = errorCode(error)
1531
+ if (code === 'ORDER_DETAIL_NOT_FOUND' || code === 'RESOURCE_NOT_FOUND') {
1532
+ return { ok: false, code: 'not_found', error: 'Pedido no encontrado.' }
1533
+ }
1534
+ if (code === 'ORDER_DETAIL_FORBIDDEN' || code === 'AUTH_UNAUTHENTICATED') {
1535
+ return {
1536
+ ok: false,
1537
+ code: 'forbidden',
1538
+ error: 'Inicia sesión con una cuenta autorizada para consultar el pedido.',
1539
+ }
1540
+ }
1541
+ logServerError('loadOrderDetailAction', error)
1542
+ return { ok: false, code: 'unavailable', error: 'No se pudo cargar el pedido.' }
1543
+ }
1544
+ }
1545
+
1546
+ // ---------------------------------------------------------------------------
1547
+ // Account modules (change: storefront-customer-view, task 4.4)
1548
+ // ---------------------------------------------------------------------------
1549
+ //
1550
+ // Profile and address-book mutations are account-scoped: they use ONLY the auth
1551
+ // cookie, never the guest cart, and never require a checkout region. Every action
1552
+ // returns an allowlisted, serializable result and never a token.
1553
+
1554
+ type AccountProfileResult =
1555
+ | { ok: true; customer: Pick<Customer, 'id' | 'email' | 'firstName' | 'lastName'> }
1556
+ | { ok: false; error: string; fieldErrors?: Record<string, string> }
1557
+
1558
+ type AccountAddressesResult =
1559
+ | { ok: true; addresses: AccountAddressView[] }
1560
+ | { ok: false; error: string }
1561
+
1562
+ type AccountAddressMutationResult =
1563
+ | { ok: true; addresses: AccountAddressView[] }
1564
+ | { ok: false; error: string; fieldErrors?: Record<string, string> }
1565
+
1566
+ interface AccountAddressInput {
1567
+ firstName: string
1568
+ lastName: string
1569
+ address1: string
1570
+ address2?: string
1571
+ city: string
1572
+ province?: string
1573
+ postalCode?: string
1574
+ countryCode: string
1575
+ phone?: string
1576
+ label?: string
1577
+ }
1578
+
1579
+ function optionalText(value: string | undefined): string | undefined {
1580
+ const trimmed = value?.trim()
1581
+ return trimmed ? value : undefined
1582
+ }
1583
+
1584
+ function toAccountAddress(address: Address, index: number): AccountAddressView {
1585
+ return {
1586
+ id: address.id ?? `account-address-${index}`,
1587
+ firstName: address.firstName,
1588
+ lastName: address.lastName,
1589
+ ...(optionalText(address.address1) ? { address1: address.address1 } : {}),
1590
+ ...(optionalText(address.address2) ? { address2: address.address2 } : {}),
1591
+ city: address.city,
1592
+ ...(optionalText(address.province) ? { province: address.province } : {}),
1593
+ ...(optionalText(address.postalCode) ? { postalCode: address.postalCode } : {}),
1594
+ countryCode: address.countryCode,
1595
+ ...(optionalText(address.phone) ? { phone: address.phone } : {}),
1596
+ ...(optionalText(address.label) ? { label: address.label } : {}),
1597
+ ...(address.isDefaultShipping ? { isDefaultShipping: true } : {}),
1598
+ ...(address.isDefaultBilling ? { isDefaultBilling: true } : {}),
1599
+ }
1600
+ }
1601
+
1602
+ async function readAccountToken(): Promise<string | null> {
1603
+ return readAuthToken(getStoreContext())
1604
+ }
1605
+
1606
+ /**
1607
+ * Update the authenticated customer's profile. Only the fields the caller
1608
+ * supplies are sent; the returned identity is allowlisted to the same keys the
1609
+ * session projection exposes.
1610
+ */
1611
+ export async function updateAccountProfileAction(input: {
1612
+ firstName?: string
1613
+ lastName?: string
1614
+ phone?: string
1615
+ email?: string
1616
+ /** Namespaced profile metadata to merge; never replaces unrelated metadata. */
1617
+ profile?: AccountProfileMetadataPatch
1618
+ }): Promise<AccountProfileResult> {
1619
+ const token = await readAccountToken()
1620
+ if (!token) return { ok: false, error: 'Inicia sesión para actualizar tu perfil.' }
1621
+
1622
+ const fieldErrors: Record<string, string> = {}
1623
+ const firstName = input.firstName?.trim()
1624
+ const lastName = input.lastName?.trim()
1625
+ const email = input.email?.trim()
1626
+ if (!firstName) fieldErrors.firstName = 'El nombre es obligatorio.'
1627
+ if (!lastName) fieldErrors.lastName = 'Los apellidos son obligatorios.'
1628
+ if (email !== undefined && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
1629
+ fieldErrors.email = 'El correo no es válido.'
1630
+ }
1631
+ if (Object.keys(fieldErrors).length > 0) {
1632
+ return { ok: false, error: 'Revisa los datos antes de guardar.', fieldErrors }
1633
+ }
1634
+
1635
+ try {
1636
+ let metadata: Record<string, unknown> | undefined
1637
+ if (input.profile) {
1638
+ const current = await loadCustomer(token)
1639
+ const base = current && isRecord(current.metadata) ? current.metadata : {}
1640
+ const profile = isRecord(base.profile) ? base.profile : {}
1641
+ metadata = { ...base, profile: mergeProfileMetadata(profile, input.profile) }
1642
+ }
1643
+
1644
+ const customer = await updateCustomerProfile(token, {
1645
+ ...(firstName ? { firstName } : {}),
1646
+ ...(lastName ? { lastName } : {}),
1647
+ ...(input.phone !== undefined ? { phone: optionalText(input.phone) ?? '' } : {}),
1648
+ ...(email !== undefined ? { email } : {}),
1649
+ ...(metadata ? { metadata } : {}),
1650
+ })
1651
+ return {
1652
+ ok: true,
1653
+ customer: {
1654
+ id: customer.id,
1655
+ email: customer.email,
1656
+ firstName: customer.firstName,
1657
+ lastName: customer.lastName,
1658
+ },
1659
+ }
1660
+ } catch (error) {
1661
+ logServerError('updateAccountProfileAction', error)
1662
+ return { ok: false, error: toError(error, 'No se pudo guardar tu perfil.') }
1663
+ }
1664
+ }
1665
+
1666
+ function isRecord(value: unknown): value is Record<string, unknown> {
1667
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
1668
+ }
1669
+
1670
+ /** Merge the profile namespace without dropping unrelated metadata keys. */
1671
+ function mergeProfileMetadata(
1672
+ current: Record<string, unknown>,
1673
+ patch: AccountProfileMetadataPatch,
1674
+ ): Record<string, unknown> {
1675
+ return {
1676
+ ...current,
1677
+ ...patch,
1678
+ ...(patch.person
1679
+ ? { person: { ...(isRecord(current.person) ? current.person : {}), ...patch.person } }
1680
+ : {}),
1681
+ ...(patch.preferences
1682
+ ? {
1683
+ preferences: {
1684
+ ...(isRecord(current.preferences) ? current.preferences : {}),
1685
+ ...patch.preferences,
1686
+ },
1687
+ }
1688
+ : {}),
1689
+ ...(patch.professional
1690
+ ? {
1691
+ professional: {
1692
+ ...(isRecord(current.professional) ? current.professional : {}),
1693
+ ...patch.professional,
1694
+ },
1695
+ }
1696
+ : {}),
1697
+ ...(patch.customFields ? { customFields: patch.customFields } : {}),
1698
+ }
1699
+ }
1700
+
1701
+ type AccountProfileLoadResult =
1702
+ | { ok: true; profile: AccountProfilePayload }
1703
+ | { ok: false; error: string }
1704
+
1705
+ /**
1706
+ * Load the authenticated customer's full profile. Only the profile namespace
1707
+ * of `metadata` is returned; unrelated backend metadata never reaches the
1708
+ * client.
1709
+ */
1710
+ export async function loadAccountProfileAction(): Promise<AccountProfileLoadResult> {
1711
+ const token = await readAccountToken()
1712
+ if (!token) return { ok: false, error: 'Inicia sesión para ver tu perfil.' }
1713
+
1714
+ try {
1715
+ const customer = await loadCustomer(token)
1716
+ if (!customer) return { ok: false, error: 'Inicia sesión para ver tu perfil.' }
1717
+ const metadata = isRecord(customer.metadata) ? customer.metadata : {}
1718
+ const profile = isRecord(metadata.profile)
1719
+ ? (metadata.profile as AccountProfilePayload['metadata'])
1720
+ : undefined
1721
+ return {
1722
+ ok: true,
1723
+ profile: {
1724
+ id: customer.id,
1725
+ email: customer.email,
1726
+ firstName: customer.firstName,
1727
+ lastName: customer.lastName,
1728
+ ...(customer.phone ? { phone: customer.phone } : {}),
1729
+ ...(profile ? { metadata: profile } : {}),
1730
+ },
1731
+ }
1732
+ } catch (error) {
1733
+ logServerError('loadAccountProfileAction', error)
1734
+ return { ok: false, error: toError(error, 'No se pudo cargar tu perfil.') }
1735
+ }
1736
+ }
1737
+
1738
+ /** Persist the profile-only metadata namespace without touching identity fields. */
1739
+ export async function updateAccountProfileMetadataAction(
1740
+ patch: AccountProfileMetadataPatch,
1741
+ ): Promise<{ ok: true } | { ok: false; error: string }> {
1742
+ const token = await readAccountToken()
1743
+ if (!token) return { ok: false, error: 'Inicia sesión para actualizar tu perfil.' }
1744
+
1745
+ try {
1746
+ const customer = await loadCustomer(token)
1747
+ if (!customer) return { ok: false, error: 'Inicia sesión para actualizar tu perfil.' }
1748
+ const metadata = isRecord(customer.metadata) ? customer.metadata : {}
1749
+ const current = isRecord(metadata.profile) ? metadata.profile : {}
1750
+ await updateCustomerProfile(token, {
1751
+ metadata: { ...metadata, profile: mergeProfileMetadata(current, patch) },
1752
+ })
1753
+ return { ok: true }
1754
+ } catch (error) {
1755
+ logServerError('updateAccountProfileMetadataAction', error)
1756
+ return { ok: false, error: toError(error, 'No se pudo guardar tu perfil.') }
1757
+ }
1758
+ }
1759
+
1760
+ /** Load the authenticated customer's address book. */
1761
+ export async function loadAccountAddressesAction(): Promise<AccountAddressesResult> {
1762
+ const token = await readAccountToken()
1763
+ if (!token) return { ok: true, addresses: [] }
1764
+ try {
1765
+ const addresses = await loadCustomerAddresses(token)
1766
+ return { ok: true, addresses: addresses.map(toAccountAddress) }
1767
+ } catch (error) {
1768
+ logServerError('loadAccountAddressesAction', error)
1769
+ return { ok: false, error: toError(error, 'No se pudieron cargar tus direcciones.') }
1770
+ }
1771
+ }
1772
+
1773
+ function validateAccountAddress(input: AccountAddressInput): Record<string, string> {
1774
+ const errors: Record<string, string> = {}
1775
+ if (!input.firstName?.trim()) errors.firstName = 'El nombre es obligatorio.'
1776
+ if (!input.lastName?.trim()) errors.lastName = 'Los apellidos son obligatorios.'
1777
+ if (!input.address1?.trim()) errors.address1 = 'La dirección es obligatoria.'
1778
+ if (!input.city?.trim()) errors.city = 'La ciudad es obligatoria.'
1779
+ if (!/^[A-Za-z]{2}$/.test(input.countryCode?.trim() ?? '')) {
1780
+ errors.countryCode = 'Usa un código de país ISO de dos letras.'
1781
+ }
1782
+ return errors
1783
+ }
1784
+
1785
+ function toAddressData(input: AccountAddressInput): CreateAddressData {
1786
+ return {
1787
+ firstName: input.firstName,
1788
+ lastName: input.lastName,
1789
+ address1: input.address1,
1790
+ address2: optionalText(input.address2),
1791
+ city: input.city,
1792
+ province: optionalText(input.province),
1793
+ postalCode: optionalText(input.postalCode),
1794
+ countryCode: input.countryCode.toUpperCase(),
1795
+ phone: optionalText(input.phone),
1796
+ label: optionalText(input.label),
1797
+ }
1798
+ }
1799
+
1800
+ async function refreshAccountAddresses(token: string): Promise<AccountAddressView[]> {
1801
+ const addresses = await loadCustomerAddresses(token)
1802
+ return addresses.map(toAccountAddress)
1803
+ }
1804
+
1805
+ /** Create an address in the authenticated customer's address book. */
1806
+ export async function createAccountAddressAction(
1807
+ input: AccountAddressInput,
1808
+ ): Promise<AccountAddressMutationResult> {
1809
+ const token = await readAccountToken()
1810
+ if (!token) return { ok: false, error: 'Inicia sesión para guardar direcciones.' }
1811
+ const fieldErrors = validateAccountAddress(input)
1812
+ if (Object.keys(fieldErrors).length > 0) {
1813
+ return { ok: false, error: 'Revisa la dirección antes de guardarla.', fieldErrors }
1814
+ }
1815
+ try {
1816
+ await createCustomerAddress(token, toAddressData(input))
1817
+ return { ok: true, addresses: await refreshAccountAddresses(token) }
1818
+ } catch (error) {
1819
+ logServerError('createAccountAddressAction', error)
1820
+ return { ok: false, error: toError(error, 'No se pudo guardar la dirección.') }
1821
+ }
1822
+ }
1823
+
1824
+ /** Update a saved address; omitted optional values are preserved by the adapter. */
1825
+ export async function updateAccountAddressAction(
1826
+ input: AccountAddressInput & { id: string },
1827
+ ): Promise<AccountAddressMutationResult> {
1828
+ const token = await readAccountToken()
1829
+ if (!token) return { ok: false, error: 'Inicia sesión para guardar direcciones.' }
1830
+ const fieldErrors = validateAccountAddress(input)
1831
+ if (Object.keys(fieldErrors).length > 0) {
1832
+ return { ok: false, error: 'Revisa la dirección antes de guardarla.', fieldErrors }
1833
+ }
1834
+ try {
1835
+ await updateCustomerAddress(token, input.id, toAddressData(input))
1836
+ return { ok: true, addresses: await refreshAccountAddresses(token) }
1837
+ } catch (error) {
1838
+ logServerError('updateAccountAddressAction', error)
1839
+ return { ok: false, error: toError(error, 'No se pudo guardar la dirección.') }
1840
+ }
1841
+ }
1842
+
1843
+ /** Delete a saved address; the backend enforces ownership. */
1844
+ export async function deleteAccountAddressAction(input: {
1845
+ id: string
1846
+ }): Promise<AccountAddressMutationResult> {
1847
+ const token = await readAccountToken()
1848
+ if (!token) return { ok: false, error: 'Inicia sesión para eliminar direcciones.' }
1849
+ try {
1850
+ await deleteCustomerAddress(token, input.id)
1851
+ return { ok: true, addresses: await refreshAccountAddresses(token) }
1852
+ } catch (error) {
1853
+ logServerError('deleteAccountAddressAction', error)
1854
+ return { ok: false, error: toError(error, 'No se pudo eliminar la dirección.') }
1855
+ }
1856
+ }
1857
+
1858
+ /** Mark an address as the default shipping or billing address. */
1859
+ export async function setDefaultAccountAddressAction(input: {
1860
+ id: string
1861
+ kind: 'shipping' | 'billing'
1862
+ }): Promise<AccountAddressMutationResult> {
1863
+ const token = await readAccountToken()
1864
+ if (!token) return { ok: false, error: 'Inicia sesión para actualizar direcciones.' }
1865
+ try {
1866
+ await updateCustomerAddress(
1867
+ token,
1868
+ input.id,
1869
+ input.kind === 'shipping' ? { isDefaultShipping: true } : { isDefaultBilling: true },
1870
+ )
1871
+ return { ok: true, addresses: await refreshAccountAddresses(token) }
1872
+ } catch (error) {
1873
+ logServerError('setDefaultAccountAddressAction', error)
1874
+ return { ok: false, error: toError(error, 'No se pudo actualizar la dirección.') }
1875
+ }
1876
+ }