@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
@@ -0,0 +1,1057 @@
1
+ 'use client'
2
+
3
+ // Thor Commerce view registry fragment: account
4
+ // Client boundary for the account view. Imports value bindings from
5
+ // @json-render/react and components from @thorprovider/blocks — both must stay
6
+ // on the client side of the RSC graph. Kept separate from index.tsx so the view
7
+ // spec (elements/catalog/route/loader) stays a pure Server Component module.
8
+ //
9
+ // Security invariant: the block-owned credential payload (email/password) is
10
+ // passed straight from the block callback to the Server Action and is NEVER
11
+ // written to the json-render state store, so no password reaches client state,
12
+ // HTML, or logs. Only the non-secret result (customer/error) is stored.
13
+ //
14
+ // The account modules (profile, addresses) are installed as separate features.
15
+ // Their presence flag lives in the feature's state slice, so an uninstalled
16
+ // module has no flag, no navigation entry, and performs no backend read. The
17
+ // frame owns the shape (stack/tabs) and the module navigation; tab visibility is
18
+ // runtime state so the element tree stays static and assemblable.
19
+
20
+ import { useCallback, useEffect, useRef } from 'react'
21
+ import type { ReactNode } from 'react'
22
+ import { usePathname, useRouter } from 'next/navigation'
23
+ import { Button } from '@thorprovider/blocks/ui/button'
24
+ import {
25
+ AccountFrame as AccountFrameBlock,
26
+ AddressBook as AddressBookBlock,
27
+ AddressForm as AddressFormBlock,
28
+ CustomerAccountOverview as AccountOverviewBlock,
29
+ CustomerAccountPlaceholder as ModulePlaceholderBlock,
30
+ CustomerAccountV1 as AccountShellBlock,
31
+ LoginPage as LoginPageBlock,
32
+ OrderHistory as OrderHistoryBlock,
33
+ ProfileForm as ProfileFormBlock,
34
+ SignUpPage1 as SignUpBlock,
35
+ } from '@thorprovider/blocks'
36
+ import type {
37
+ AddressBookLabels,
38
+ CustomerAccountOverviewProps,
39
+ CustomerAccountPlaceholderProps,
40
+ CustomerAccountV1Props,
41
+ OrderHistoryLabels,
42
+ OrderHistoryOrder,
43
+ OrderHistoryStatusTone,
44
+ } from '@thorprovider/blocks'
45
+ @@BLOCK_IMPORTS@@
46
+ import { useStateStore } from '@json-render/react'
47
+ import type { Customer } from '@thorprovider/types'
48
+ import {
49
+ createAccountAddressAction,
50
+ deleteAccountAddressAction,
51
+ loadAccountAddressesAction,
52
+ loadOrdersPageAction,
53
+ setDefaultAccountAddressAction,
54
+ updateAccountAddressAction,
55
+ updateAccountProfileAction,
56
+ } from '../../actions'
57
+ import { ACCOUNT_ORDERS_DEFAULT_PAGE_SIZE, accountIdentityKey, buildAccountProfileFields, isAccountModuleVisible } from '../../account-private.core'
58
+ import { AccountBoundary } from '../../account-boundary.client'
59
+ import { useAccountLifecycle } from '../../account-lifecycle.client'
60
+ import type { AccountAddressView, AccountOrderView } from '../../state.core'
61
+ import type { ViewRegistry } from '../types'
62
+ import { accountContent } from './content'
63
+ import { AccountOrderDetailPanel } from './order-detail.client'
64
+ import { AccountFulfillmentEvidencePanel } from './fulfillment-evidence.client'
65
+ import {
66
+ accountAddressPropsSchema,
67
+ accountFramePropsSchema,
68
+ accountLoginPropsSchema,
69
+ accountOrdersPropsSchema,
70
+ accountProfilePropsSchema,
71
+ accountRegisterPropsSchema,
72
+ } from './schema'
73
+
74
+ /** Bounded page size for the account order-history window. */
75
+ const ORDERS_PAGE_SIZE = ACCOUNT_ORDERS_DEFAULT_PAGE_SIZE
76
+
77
+ type PanelProps = {
78
+ props: Record<string, unknown>
79
+ emit: (event: string) => void
80
+ }
81
+
82
+ type AccountState = Record<string, unknown>
83
+
84
+ // The installed account modules, in render order. `orders` is part of the auth
85
+ // host; `profile` and `addresses` exist only when their feature is installed
86
+ // (the presence flag comes from the feature state slice).
87
+ function installedModules(state: AccountState): { id: string; label: string }[] {
88
+ const modules = [{ id: 'orders', label: accountContent.modules.orders }]
89
+ if (state.accountProfileAvailable === true) {
90
+ modules.push({ id: 'profile', label: accountContent.modules.profile })
91
+ }
92
+ if (state.accountAddressesAvailable === true) {
93
+ modules.push({ id: 'addresses', label: accountContent.modules.addresses })
94
+ }
95
+ return modules
96
+ }
97
+
98
+ const SHELL_OVERVIEW_ID = 'overview'
99
+ const SHELL_FAVORITES_ID = 'lists'
100
+
101
+ // `views/account/content.ts` is user-owned and is never rewritten by sync. An
102
+ // existing store therefore has no shell keys when this registry lands; the
103
+ // defaults keep the cutover from crashing and can be overridden per store.
104
+ const SHELL_DEFAULTS = {
105
+ shell: {
106
+ loading: 'Cargando tu cuenta…',
107
+ retry: 'Reintentar',
108
+ reference: 'Referencia: {reference}',
109
+ backToAccount: 'Mi cuenta',
110
+ errorTitle: 'No pudimos cargar tu cuenta',
111
+ errorBody: 'Vuelve a intentarlo en unos segundos.',
112
+ header: {
113
+ greeting: 'Hola, {name}',
114
+ signOut: 'Cerrar sesión',
115
+ verified: 'Correo verificado',
116
+ memberSince: 'Cliente desde {date}',
117
+ },
118
+ },
119
+ overview: {
120
+ sections: 'Secciones de tu cuenta',
121
+ },
122
+ placeholder: {
123
+ badge: 'Próximamente',
124
+ upcoming: 'Qué encontrarás aquí',
125
+ },
126
+ shellModules: {
127
+ overview: {
128
+ label: 'Mi cuenta',
129
+ description: 'Todas las secciones de tu cuenta en un solo lugar.',
130
+ },
131
+ orders: {
132
+ label: 'Mis pedidos',
133
+ description: 'Consulta tus compras, entregas y devoluciones.',
134
+ },
135
+ profile: {
136
+ label: 'Mi perfil',
137
+ description: 'Administra tus datos personales y de contacto.',
138
+ },
139
+ addresses: {
140
+ label: 'Direcciones',
141
+ description: 'Administra tus direcciones de envío y facturación.',
142
+ },
143
+ favorites: {
144
+ label: 'Listas de compras',
145
+ description: 'Guarda productos para comprarlos después.',
146
+ planned: [
147
+ 'Listas con nombre y productos guardados',
148
+ 'Mover productos a la cesta',
149
+ 'Listas compartidas cuando la tienda lo permita',
150
+ ],
151
+ note: 'Se activa cuando las listas de compras están habilitadas.',
152
+ },
153
+ },
154
+ shellCards: {
155
+ orders: {
156
+ description: 'Consulta tus compras, entregas y devoluciones.',
157
+ },
158
+ profile: {
159
+ description: 'Administra tus datos personales y de contacto.',
160
+ },
161
+ addresses: {
162
+ description: 'Administra tus direcciones de envío y facturación.',
163
+ },
164
+ favorites: {
165
+ description: 'Guarda productos para comprarlos después.',
166
+ },
167
+ },
168
+ }
169
+
170
+ type ShellContent = typeof SHELL_DEFAULTS
171
+
172
+ const accountContentCompat = accountContent as typeof accountContent & Partial<ShellContent>
173
+ const shellContent = {
174
+ shell: {
175
+ ...SHELL_DEFAULTS.shell,
176
+ ...(accountContentCompat.shell ?? {}),
177
+ header: {
178
+ ...SHELL_DEFAULTS.shell.header,
179
+ ...(accountContentCompat.shell?.header ?? {}),
180
+ },
181
+ },
182
+ overview: {
183
+ ...SHELL_DEFAULTS.overview,
184
+ ...(accountContentCompat.overview ?? {}),
185
+ },
186
+ placeholder: {
187
+ ...SHELL_DEFAULTS.placeholder,
188
+ ...(accountContentCompat.placeholder ?? {}),
189
+ },
190
+ shellModules: {
191
+ overview: {
192
+ ...SHELL_DEFAULTS.shellModules.overview,
193
+ ...(accountContentCompat.shellModules?.overview ?? {}),
194
+ },
195
+ orders: {
196
+ ...SHELL_DEFAULTS.shellModules.orders,
197
+ ...(accountContentCompat.shellModules?.orders ?? {}),
198
+ },
199
+ profile: {
200
+ ...SHELL_DEFAULTS.shellModules.profile,
201
+ ...(accountContentCompat.shellModules?.profile ?? {}),
202
+ },
203
+ addresses: {
204
+ ...SHELL_DEFAULTS.shellModules.addresses,
205
+ ...(accountContentCompat.shellModules?.addresses ?? {}),
206
+ },
207
+ favorites: {
208
+ ...SHELL_DEFAULTS.shellModules.favorites,
209
+ ...(accountContentCompat.shellModules?.favorites ?? {}),
210
+ },
211
+ },
212
+ shellCards: {
213
+ orders: {
214
+ ...SHELL_DEFAULTS.shellCards.orders,
215
+ ...(accountContentCompat.shellCards?.orders ?? {}),
216
+ },
217
+ profile: {
218
+ ...SHELL_DEFAULTS.shellCards.profile,
219
+ ...(accountContentCompat.shellCards?.profile ?? {}),
220
+ },
221
+ addresses: {
222
+ ...SHELL_DEFAULTS.shellCards.addresses,
223
+ ...(accountContentCompat.shellCards?.addresses ?? {}),
224
+ },
225
+ favorites: {
226
+ ...SHELL_DEFAULTS.shellCards.favorites,
227
+ ...(accountContentCompat.shellCards?.favorites ?? {}),
228
+ },
229
+ },
230
+ }
231
+
232
+ function shellCapabilities(state: AccountState): CustomerAccountV1Props['context']['capabilities'] {
233
+ return {
234
+ orderHistory: state.accountAuthenticated === true,
235
+ profile: state.accountProfileAvailable === true,
236
+ addressBook: state.accountAddressesAvailable === true,
237
+ // The planner entry is explicit: the card opens a documented placeholder,
238
+ // never a fake favorites list.
239
+ shoppingLists: true,
240
+ }
241
+ }
242
+
243
+ function shellModules(): CustomerAccountV1Props['context']['modules'] {
244
+ return [
245
+ {
246
+ id: SHELL_OVERVIEW_ID,
247
+ label: shellContent.shellModules.overview.label,
248
+ status: 'ready',
249
+ description: shellContent.shellModules.overview.description,
250
+ planned: [],
251
+ },
252
+ {
253
+ id: 'orders',
254
+ label: shellContent.shellModules.orders.label,
255
+ status: 'ready',
256
+ capability: 'orderHistory',
257
+ description: shellContent.shellModules.orders.description,
258
+ planned: [],
259
+ },
260
+ {
261
+ id: 'profile',
262
+ label: shellContent.shellModules.profile.label,
263
+ status: 'ready',
264
+ capability: 'profile',
265
+ description: shellContent.shellModules.profile.description,
266
+ planned: [],
267
+ },
268
+ {
269
+ id: 'addresses',
270
+ label: shellContent.shellModules.addresses.label,
271
+ status: 'ready',
272
+ capability: 'addressBook',
273
+ description: shellContent.shellModules.addresses.description,
274
+ planned: [],
275
+ },
276
+ {
277
+ id: SHELL_FAVORITES_ID,
278
+ label: shellContent.shellModules.favorites.label,
279
+ status: 'planned',
280
+ capability: 'shoppingLists',
281
+ description: shellContent.shellModules.favorites.description,
282
+ planned: shellContent.shellModules.favorites.planned,
283
+ ...(shellContent.shellModules.favorites.note === undefined
284
+ ? {}
285
+ : { note: shellContent.shellModules.favorites.note }),
286
+ },
287
+ ]
288
+ }
289
+
290
+ function shellCards(): CustomerAccountOverviewProps['model']['cards'] {
291
+ return [
292
+ {
293
+ id: 'orders',
294
+ title: shellContent.shellModules.orders.label,
295
+ description: shellContent.shellCards.orders.description,
296
+ icon: 'orders',
297
+ capability: 'orderHistory',
298
+ order: 1,
299
+ },
300
+ {
301
+ id: 'profile',
302
+ title: shellContent.shellModules.profile.label,
303
+ description: shellContent.shellCards.profile.description,
304
+ icon: 'profile',
305
+ capability: 'profile',
306
+ order: 2,
307
+ },
308
+ {
309
+ id: 'addresses',
310
+ title: shellContent.shellModules.addresses.label,
311
+ description: shellContent.shellCards.addresses.description,
312
+ icon: 'addresses',
313
+ capability: 'addressBook',
314
+ order: 3,
315
+ },
316
+ {
317
+ id: SHELL_FAVORITES_ID,
318
+ title: shellContent.shellModules.favorites.label,
319
+ description: shellContent.shellCards.favorites.description,
320
+ icon: 'lists',
321
+ capability: 'shoppingLists',
322
+ order: 4,
323
+ },
324
+ ]
325
+ }
326
+
327
+ function shellModuleRoute(moduleId: string): string {
328
+ switch (moduleId) {
329
+ case 'orders':
330
+ return '/account/orders'
331
+ case 'profile':
332
+ return '/account/profile'
333
+ case 'addresses':
334
+ return '/account/addresses'
335
+ case SHELL_FAVORITES_ID:
336
+ return '/account/favorites'
337
+ default:
338
+ return '/account'
339
+ }
340
+ }
341
+
342
+ function shellActiveModule(pathname: string): string {
343
+ if (pathname === '/account/orders' || pathname.startsWith('/account/orders/')) {
344
+ return 'orders'
345
+ }
346
+ if (pathname === '/account/profile') return 'profile'
347
+ if (pathname === '/account/addresses') return 'addresses'
348
+ if (pathname === '/account/favorites') return SHELL_FAVORITES_ID
349
+ return SHELL_OVERVIEW_ID
350
+ }
351
+
352
+ function shellCustomer(customer: Customer): CustomerAccountV1Props['context']['customer'] {
353
+ const name =
354
+ [customer.firstName, customer.lastName].filter(Boolean).join(' ') || customer.email
355
+ const initials =
356
+ name
357
+ .split(/\s+/)
358
+ .filter(Boolean)
359
+ .slice(0, 2)
360
+ .map((part) => part[0])
361
+ .join('')
362
+ .toUpperCase() || customer.email.slice(0, 2).toUpperCase()
363
+ return {
364
+ name,
365
+ email: customer.email,
366
+ initials,
367
+ ...(customer.phone ? { phone: customer.phone } : {}),
368
+ }
369
+ }
370
+
371
+ function shellState(state: AccountState): CustomerAccountV1Props['state'] {
372
+ if (state.accountReconciling === true) return { status: 'loading' }
373
+ if (state.accountResolution === 'unavailable') {
374
+ return {
375
+ status: 'error',
376
+ title: shellContent.shell.errorTitle,
377
+ message: shellContent.shell.errorBody,
378
+ }
379
+ }
380
+ return { status: 'ready' }
381
+ }
382
+
383
+ type ShellPanelProps = PanelProps & { children?: ReactNode }
384
+
385
+ function AccountShellPanel({ children }: ShellPanelProps) {
386
+ const { state } = useStateStore()
387
+ const pathname = usePathname()
388
+ const router = useRouter()
389
+ const lifecycle = useAccountLifecycle()
390
+ const customer = (state.accountCustomer ?? null) as Customer | null
391
+ const wrapperRef = useRef<HTMLDivElement | null>(null)
392
+
393
+ // A route change remounts the shell, so its own module-change focus effect
394
+ // cannot run. Focus the shell content region after a module route renders;
395
+ // the overview route restores focus to its originating card instead.
396
+ useEffect(() => {
397
+ if (pathname === '/account') return
398
+ const frame = requestAnimationFrame(() => {
399
+ wrapperRef.current
400
+ ?.querySelector<HTMLElement>('[role="region"][tabindex="-1"]')
401
+ ?.focus()
402
+ })
403
+ return () => cancelAnimationFrame(frame)
404
+ }, [pathname])
405
+
406
+ if (!state.accountAuthenticated || !customer) return null
407
+
408
+ return (
409
+ <div
410
+ ref={wrapperRef}
411
+ className="mx-auto w-full max-w-7xl px-4 py-8 sm:px-6 lg:px-8"
412
+ >
413
+ <AccountShellBlock
414
+ context={{
415
+ customer: shellCustomer(customer),
416
+ capabilities: shellCapabilities(state),
417
+ modules: shellModules(),
418
+ activeModuleId: shellActiveModule(pathname),
419
+ locale: 'es-ES',
420
+ currency: 'EUR',
421
+ }}
422
+ labels={shellContent.shell}
423
+ state={shellState(state)}
424
+ lang="es"
425
+ onModuleSelect={(moduleId) => router.push(shellModuleRoute(moduleId))}
426
+ onSignOut={() => void lifecycle.logout()}
427
+ onRetry={() => void lifecycle.retryResolution()}
428
+ >
429
+ {children}
430
+ </AccountShellBlock>
431
+ </div>
432
+ )
433
+ }
434
+
435
+ function AccountOverviewPanel() {
436
+ const { state } = useStateStore()
437
+ const pathname = usePathname()
438
+ const router = useRouter()
439
+
440
+ useEffect(() => {
441
+ if (pathname !== '/account') return
442
+ const originCard = sessionStorage.getItem('account:origin-card')
443
+ if (!originCard) return
444
+ const frame = requestAnimationFrame(() => {
445
+ document.querySelector<HTMLElement>(`[data-module-id="${originCard}"]`)?.focus()
446
+ sessionStorage.removeItem('account:origin-card')
447
+ })
448
+ return () => cancelAnimationFrame(frame)
449
+ }, [pathname])
450
+
451
+ if (!state.accountAuthenticated) return null
452
+ return (
453
+ <AccountOverviewBlock
454
+ title={shellContent.shellModules.overview.label}
455
+ model={{ cards: shellCards(), summaries: {}, notice: null }}
456
+ capabilities={shellCapabilities(state)}
457
+ labels={{ sections: shellContent.overview.sections }}
458
+ onOpenCard={(cardId) => {
459
+ sessionStorage.setItem('account:origin-card', cardId)
460
+ router.push(shellModuleRoute(cardId))
461
+ }}
462
+ />
463
+ )
464
+ }
465
+
466
+ function AccountModulePlaceholderPanel() {
467
+ const { state } = useStateStore()
468
+ if (!state.accountAuthenticated) return null
469
+ const module = shellModules().find((entry) => entry.id === SHELL_FAVORITES_ID)
470
+ if (!module) return null
471
+ const labels: CustomerAccountPlaceholderProps['labels'] = shellContent.placeholder
472
+ return <ModulePlaceholderBlock module={module} labels={labels} />
473
+ }
474
+
475
+ // Tab visibility is runtime state: the element tree stays static, and only the
476
+ // frame decides which module is current. In the stacked shape every installed
477
+ // module renders in order.
478
+ function useModuleVisible(id: string): boolean {
479
+ const { state } = useStateStore()
480
+ return isAccountModuleVisible(
481
+ typeof state.accountShape === 'string' ? state.accountShape : null,
482
+ typeof state.accountTab === 'string' ? state.accountTab : null,
483
+ id,
484
+ )
485
+ }
486
+
487
+ // Non-secret status surface for the block pages, which expose no error/pending
488
+ // prop of their own. Renders nothing when there is no pending work or error.
489
+ function AuthNotice({ pending, error }: { pending: boolean; error: string | null }) {
490
+ if (!pending && !error) return null
491
+ return (
492
+ <div
493
+ role="alert"
494
+ aria-live="polite"
495
+ className="bg-background text-foreground fixed inset-x-0 top-4 z-50 mx-auto w-fit max-w-md rounded-md border px-4 py-2 text-center text-sm shadow-lg"
496
+ >
497
+ {pending ? 'Procesando…' : error}
498
+ </div>
499
+ )
500
+ }
501
+
502
+ // The page side of the auth contract. The blocks render only the form: the page
503
+ // — not the block — owns the viewport. This wrapper keeps the shopper-visible
504
+ // result of every auth surface unchanged and stays theme-driven.
505
+ function AuthCanvas({ stack = false, children }: { stack?: boolean; children: ReactNode }) {
506
+ return (
507
+ <section
508
+ className={`from-background to-muted/50 relative isolate flex min-h-dvh w-full items-center justify-center overflow-hidden bg-linear-to-br ${stack ? 'flex-col' : ''}`}
509
+ >
510
+ <div
511
+ className={`relative z-10 container mx-auto flex min-h-dvh items-center justify-center px-4 py-12 ${stack ? 'flex-col' : ''}`}
512
+ >
513
+ {children}
514
+ </div>
515
+ </section>
516
+ )
517
+ }
518
+
519
+ // Neutral pending surface shown while a cross-tab/foreground reconciliation is in
520
+ // flight. It replaces the previously held identity/orders so no stale private
521
+ // data is presented as current during the server round-trip.
522
+ function ReconcilingStatus() {
523
+ return (
524
+ <p
525
+ role="status"
526
+ aria-live="polite"
527
+ data-account-reconciling="1"
528
+ className="text-muted-foreground mx-auto max-w-7xl px-4 py-8 text-sm"
529
+ >
530
+ Actualizando tu cuenta…
531
+ </p>
532
+ )
533
+ }
534
+
535
+ // Backend order status → badge tone. The status model belongs to the host (the
536
+ // block never compares a status string), so this map is the storefront's own
537
+ // vocabulary; an unknown status keeps the neutral tone and its own label.
538
+ const ORDER_STATUS_TONES: Record<string, OrderHistoryStatusTone> = {
539
+ pending: 'outline',
540
+ processing: 'secondary',
541
+ completed: 'default',
542
+ cancelled: 'destructive',
543
+ refunded: 'outline',
544
+ }
545
+
546
+ function toOrderHistoryOrder(order: AccountOrderView): OrderHistoryOrder {
547
+ return {
548
+ id: order.id,
549
+ number: order.number,
550
+ date: order.date,
551
+ status: {
552
+ label: order.status,
553
+ tone: ORDER_STATUS_TONES[order.status] ?? 'secondary',
554
+ },
555
+ total: order.total,
556
+ items: order.items.map((item) => ({
557
+ id: item.id,
558
+ name: item.name,
559
+ ...(item.image === undefined ? {} : { image: item.image }),
560
+ ...(item.variant === undefined ? {} : { details: item.variant }),
561
+ quantity: item.quantity,
562
+ lineTotal: item.lineTotal,
563
+ })),
564
+ }
565
+ }
566
+
567
+ function AccountLoginPanel({ props, emit }: PanelProps) {
568
+ const { state } = useStateStore()
569
+ const lifecycle = useAccountLifecycle()
570
+ const parsed = accountLoginPropsSchema.parse(props)
571
+ const error = typeof state.accountError === 'string' ? state.accountError : null
572
+ const pending = Boolean(state.accountPending)
573
+ return (
574
+ <>
575
+ <AuthNotice pending={pending} error={error} />
576
+ <AuthCanvas>
577
+ <fieldset disabled={pending} aria-busy={pending} className="contents">
578
+ <LoginPageBlock
579
+ presentation="card"
580
+ logoText={parsed.logoText}
581
+ welcomeTitleLabel={parsed.welcomeTitleLabel}
582
+ welcomeDescriptionLabel={parsed.welcomeDescriptionLabel}
583
+ emailLabel={parsed.emailLabel}
584
+ passwordLabel={parsed.passwordLabel}
585
+ signInLabel={parsed.signInLabel}
586
+ createAccountLabel={parsed.createAccountLabel}
587
+ rememberMeLabel="Recuérdame"
588
+ onSubmit={(data) => {
589
+ void lifecycle.login({ email: data.email, password: data.password })
590
+ }}
591
+ onCreateAccount={() => emit('showRegister')}
592
+ />
593
+ </fieldset>
594
+ </AuthCanvas>
595
+ </>
596
+ )
597
+ }
598
+
599
+ function AccountRegisterPanel({ props, emit }: PanelProps) {
600
+ const { state } = useStateStore()
601
+ const lifecycle = useAccountLifecycle()
602
+ const parsed = accountRegisterPropsSchema.parse(props)
603
+ const error = typeof state.accountError === 'string' ? state.accountError : null
604
+ const pending = Boolean(state.accountPending)
605
+ return (
606
+ <>
607
+ <AuthNotice pending={pending} error={error} />
608
+ <AuthCanvas stack>
609
+ <fieldset disabled={pending} aria-busy={pending} className="contents">
610
+ <SignUpBlock
611
+ logoText={parsed.logoText}
612
+ createAccountTitleLabel={parsed.createAccountTitleLabel}
613
+ createAccountDescriptionLabel={parsed.createAccountDescriptionLabel}
614
+ fullNameLabel={parsed.fullNameLabel}
615
+ emailLabel={parsed.emailLabel}
616
+ passwordLabel={parsed.passwordLabel}
617
+ createAccountLabel={parsed.createAccountLabel}
618
+ signInLabel={parsed.signInLabel}
619
+ onSubmit={(data) => {
620
+ const parts = data.fullName.trim().split(/\s+/).filter(Boolean)
621
+ void lifecycle.register({
622
+ email: data.email,
623
+ password: data.password,
624
+ firstName: parts[0] ?? '',
625
+ lastName: parts.slice(1).join(' '),
626
+ })
627
+ }}
628
+ onSignIn={() => emit('showLogin')}
629
+ />
630
+ </fieldset>
631
+ </AuthCanvas>
632
+ </>
633
+ )
634
+ }
635
+
636
+ /**
637
+ * The account frame: the signed-in identity and the module navigation. It is
638
+ * rendered only for an authenticated shopper (the element visibility gate) and
639
+ * it seeds the shape/tab state the module panels read.
640
+ */
641
+ function AccountFramePanel({ props }: PanelProps) {
642
+ const { state, set } = useStateStore()
643
+ const parsed = accountFramePropsSchema.parse(props)
644
+ const presentation = parsed.presentation ?? 'stack'
645
+ const customer = (state.accountCustomer ?? null) as Customer | null
646
+ const modules = installedModules(state)
647
+ const activeModule = typeof state.accountTab === 'string' ? state.accountTab : undefined
648
+
649
+ useEffect(() => {
650
+ if (presentation === 'tabs') {
651
+ set('/accountShape', 'tabs')
652
+ if (!modules.some((module) => module.id === activeModule)) {
653
+ set('/accountTab', modules[0]?.id ?? 'orders')
654
+ }
655
+ } else {
656
+ set('/accountShape', 'stack')
657
+ set('/accountTab', null)
658
+ }
659
+ }, [presentation, modules.length, activeModule, set])
660
+
661
+ if (!state.accountAuthenticated || !customer) return null
662
+ const displayName =
663
+ [customer.firstName, customer.lastName].filter(Boolean).join(' ') || customer.email
664
+ const labels = parsed.labels ?? {}
665
+ return (
666
+ <div className="mx-auto w-full max-w-7xl px-4 pt-10 sm:px-6 lg:px-8">
667
+ <AccountFrameBlock
668
+ displayName={displayName}
669
+ {...(customer.email ? { email: customer.email } : {})}
670
+ modules={modules}
671
+ {...(activeModule ? { activeModule } : {})}
672
+ presentation={presentation}
673
+ labels={labels}
674
+ onSelectModule={(id) => set('/accountTab', id)}
675
+ />
676
+ </div>
677
+ )
678
+ }
679
+
680
+ function AccountProfilePanel({ props }: PanelProps) {
681
+ const { state, set } = useStateStore()
682
+ const parsed = accountProfilePropsSchema.parse(props)
683
+ const customer = (state.accountCustomer ?? null) as Customer | null
684
+ const visible = useModuleVisible('profile')
685
+ if (state.accountProfileAvailable !== true || !visible || !customer) return null
686
+
687
+ const pending = Boolean(state.accountProfilePending)
688
+ const error = typeof state.accountProfileError === 'string' ? state.accountProfileError : null
689
+ const emailEditable = state.accountEmailEditable === true
690
+
691
+ return (
692
+ <div className="mx-auto w-full max-w-7xl px-4 py-8 sm:px-6 lg:px-8" id="account-profile">
693
+ <ProfileFormBlock
694
+ fields={buildAccountProfileFields(customer, emailEditable)}
695
+ labels={parsed.labels}
696
+ pending={pending}
697
+ error={error}
698
+ onSubmit={(values) => {
699
+ set('/accountProfilePending', true)
700
+ set('/accountProfileError', null)
701
+ void updateAccountProfileAction({
702
+ firstName: values.firstName,
703
+ lastName: values.lastName,
704
+ phone: values.phone,
705
+ ...(emailEditable && values.email !== undefined ? { email: values.email } : {}),
706
+ }).then((result) => {
707
+ set('/accountProfilePending', false)
708
+ if (result.ok) {
709
+ set('/accountCustomer', { ...customer, ...result.customer })
710
+ return
711
+ }
712
+ set('/accountProfileError', result.error)
713
+ })
714
+ }}
715
+ />
716
+ </div>
717
+ )
718
+ }
719
+
720
+ function toAddressEntry(address: AccountAddressView): {
721
+ id: string
722
+ recipientName: string
723
+ lines: string[]
724
+ isDefaultShipping?: boolean
725
+ isDefaultBilling?: boolean
726
+ } {
727
+ const lines = [
728
+ address.address1,
729
+ address.address2,
730
+ [address.city, address.province, address.postalCode].filter(Boolean).join(', '),
731
+ address.countryCode,
732
+ ].filter((line): line is string => typeof line === 'string' && line.length > 0)
733
+ return {
734
+ id: address.id,
735
+ recipientName: [address.firstName, address.lastName].filter(Boolean).join(' '),
736
+ lines,
737
+ ...(address.isDefaultShipping ? { isDefaultShipping: true } : {}),
738
+ ...(address.isDefaultBilling ? { isDefaultBilling: true } : {}),
739
+ }
740
+ }
741
+
742
+ function AccountAddressesPanel({ props }: PanelProps) {
743
+ const { state, set } = useStateStore()
744
+ const parsed = accountAddressPropsSchema.parse(props)
745
+ const { identityKey } = useAccountLifecycle()
746
+ const visible = useModuleVisible('addresses')
747
+ const available = state.accountAddressesAvailable === true
748
+ const loadedKeyRef = useRef<string | null>(null)
749
+
750
+ const addresses = Array.isArray(state.accountAddresses)
751
+ ? (state.accountAddresses as AccountAddressView[])
752
+ : []
753
+ const pending = Boolean(state.accountAddressesPending)
754
+ const error = typeof state.accountAddressesError === 'string' ? state.accountAddressesError : null
755
+ const formOpen = Boolean(state.accountAddressFormOpen)
756
+ const editingId = typeof state.accountAddressEditingId === 'string' ? state.accountAddressEditingId : null
757
+ const mutationPending = Boolean(state.accountAddressMutationPending)
758
+ const mutationError =
759
+ typeof state.accountAddressMutationError === 'string' ? state.accountAddressMutationError : null
760
+ const fieldErrors =
761
+ state.accountAddressFieldErrors && typeof state.accountAddressFieldErrors === 'object'
762
+ ? (state.accountAddressFieldErrors as Record<string, string>)
763
+ : {}
764
+
765
+ const load = useCallback(() => {
766
+ set('/accountAddressesPending', true)
767
+ set('/accountAddressesError', null)
768
+ void loadAccountAddressesAction().then((result) => {
769
+ set('/accountAddressesPending', false)
770
+ if (result.ok) {
771
+ set('/accountAddresses', result.addresses)
772
+ return
773
+ }
774
+ set('/accountAddressesError', result.error)
775
+ })
776
+ }, [set])
777
+
778
+ useEffect(() => {
779
+ if (!available || !visible) return
780
+ if (loadedKeyRef.current === identityKey) return
781
+ // A new identity reloads its own address book; the previous identity's rows
782
+ // were already cleared by the account claim write path.
783
+ loadedKeyRef.current = identityKey
784
+ load()
785
+ }, [available, visible, identityKey, load])
786
+
787
+ if (!available || !visible) return null
788
+
789
+ const editing = editingId ? addresses.find((address) => address.id === editingId) ?? null : null
790
+ const labels = (parsed.labels ?? {}) as Partial<AddressBookLabels>
791
+ const closeForm = () => {
792
+ set('/accountAddressFormOpen', false)
793
+ set('/accountAddressEditingId', null)
794
+ set('/accountAddressMutationError', null)
795
+ set('/accountAddressFieldErrors', {})
796
+ }
797
+ const applyResult = (result: { ok: true; addresses: AccountAddressView[] } | { ok: false; error: string; fieldErrors?: Record<string, string> }) => {
798
+ set('/accountAddressMutationPending', false)
799
+ if (result.ok) {
800
+ set('/accountAddresses', result.addresses)
801
+ closeForm()
802
+ return
803
+ }
804
+ set('/accountAddressMutationError', result.error)
805
+ set('/accountAddressFieldErrors', result.fieldErrors ?? {})
806
+ }
807
+ const submitForm = (values: Record<string, string>) => {
808
+ set('/accountAddressMutationPending', true)
809
+ set('/accountAddressMutationError', null)
810
+ set('/accountAddressFieldErrors', {})
811
+ const input = {
812
+ firstName: values.firstName ?? '',
813
+ lastName: values.lastName ?? '',
814
+ address1: values.address1 ?? '',
815
+ address2: values.address2,
816
+ city: values.city ?? '',
817
+ province: values.province,
818
+ postalCode: values.postalCode,
819
+ countryCode: values.countryCode ?? '',
820
+ phone: values.phone,
821
+ label: values.label,
822
+ }
823
+ const request = editingId
824
+ ? updateAccountAddressAction({ ...input, id: editingId })
825
+ : createAccountAddressAction(input)
826
+ void request.then(applyResult)
827
+ }
828
+
829
+ return (
830
+ <div className="mx-auto w-full max-w-7xl px-4 pb-12 sm:px-6 lg:px-8" id="account-addresses">
831
+ {pending ? (
832
+ <p role="status" aria-live="polite" className="text-muted-foreground py-8 text-sm">
833
+ {accountContent.addresses.loadingLabel}
834
+ </p>
835
+ ) : error ? (
836
+ <div className="flex flex-col items-start gap-3 py-8">
837
+ <p role="alert" className="text-destructive text-sm">
838
+ {error}
839
+ </p>
840
+ <Button type="button" variant="outline" size="sm" onClick={load}>
841
+ {accountContent.addresses.retryLabel}
842
+ </Button>
843
+ </div>
844
+ ) : formOpen ? (
845
+ <AddressFormBlock
846
+ fields={accountContent.addressFields.map((field) => ({
847
+ ...field,
848
+ value: editing ? (editing as unknown as Record<string, string>)[field.name] ?? '' : '',
849
+ }))}
850
+ labels={labels}
851
+ pending={mutationPending}
852
+ error={mutationError}
853
+ fieldErrors={fieldErrors}
854
+ onSubmit={submitForm}
855
+ onCancel={closeForm}
856
+ />
857
+ ) : (
858
+ <AddressBookBlock
859
+ addresses={addresses.map(toAddressEntry)}
860
+ labels={labels}
861
+ onCreate={() => {
862
+ set('/accountAddressEditingId', null)
863
+ set('/accountAddressFormOpen', true)
864
+ }}
865
+ onEdit={(id) => {
866
+ set('/accountAddressEditingId', id)
867
+ set('/accountAddressFormOpen', true)
868
+ }}
869
+ onDelete={(id) => {
870
+ set('/accountAddressMutationPending', true)
871
+ void deleteAccountAddressAction({ id }).then(applyResult)
872
+ }}
873
+ onSetDefaultShipping={(id) => {
874
+ set('/accountAddressMutationPending', true)
875
+ void setDefaultAccountAddressAction({ id, kind: 'shipping' }).then(applyResult)
876
+ }}
877
+ onSetDefaultBilling={(id) => {
878
+ set('/accountAddressMutationPending', true)
879
+ void setDefaultAccountAddressAction({ id, kind: 'billing' }).then(applyResult)
880
+ }}
881
+ />
882
+ )}
883
+ </div>
884
+ )
885
+ }
886
+
887
+ function AccountOrdersPanel({ props }: PanelProps) {
888
+ const router = useRouter()
889
+ const { state, set, getSnapshot } = useStateStore()
890
+ const parsed = accountOrdersPropsSchema.parse(props)
891
+ const { identityKey, reconciling } = useAccountLifecycle()
892
+ const visible = useModuleVisible('orders')
893
+
894
+ const generationRef = useRef(0)
895
+ const loadedKeyRef = useRef<string | null>(null)
896
+ const requestedPageRef = useRef(1)
897
+
898
+ const currentIdentityKey = useCallback(
899
+ () =>
900
+ accountIdentityKey(
901
+ (getSnapshot().accountCustomer ?? null) as { id?: string | null } | null,
902
+ ),
903
+ [getSnapshot],
904
+ )
905
+
906
+ const loadPage = (page: number) => {
907
+ const capturedKey = currentIdentityKey()
908
+ const capturedGeneration = generationRef.current
909
+ requestedPageRef.current = page
910
+ set('/accountOrdersPending', true)
911
+ set('/accountOrdersError', null)
912
+ void loadOrdersPageAction({ page, pageSize: ORDERS_PAGE_SIZE })
913
+ .then((result) => {
914
+ if (
915
+ currentIdentityKey() !== capturedKey ||
916
+ generationRef.current !== capturedGeneration
917
+ ) {
918
+ return
919
+ }
920
+ set('/accountOrdersPending', false)
921
+ if (result.ok) {
922
+ set('/accountOrders', result.orders)
923
+ set('/accountOrdersCount', result.count)
924
+ set('/accountOrdersPage', page)
925
+ set('/accountOrdersPageSize', result.limit)
926
+ set('/accountOrdersError', null)
927
+ loadedKeyRef.current = capturedKey
928
+ return
929
+ }
930
+ set('/accountOrdersError', result.error)
931
+ })
932
+ .catch((error) => {
933
+ if (
934
+ currentIdentityKey() !== capturedKey ||
935
+ generationRef.current !== capturedGeneration
936
+ ) {
937
+ return
938
+ }
939
+ console.error(
940
+ '[storefront/account] loadOrders failed',
941
+ error instanceof Error ? error.message : error,
942
+ )
943
+ set('/accountOrdersPending', false)
944
+ set('/accountOrdersError', parsed.errorLabel ?? 'No se pudieron cargar tus pedidos.')
945
+ })
946
+ }
947
+
948
+ useEffect(() => {
949
+ if (loadedKeyRef.current !== identityKey) {
950
+ generationRef.current += 1
951
+ loadedKeyRef.current = null
952
+ }
953
+ if (identityKey === 'anonymous') return
954
+ if (loadedKeyRef.current === identityKey) return
955
+ loadPage(1)
956
+ // eslint-disable-next-line react-hooks/exhaustive-deps
957
+ }, [identityKey])
958
+
959
+ if (!visible) return null
960
+
961
+ const pending = Boolean(state.accountOrdersPending)
962
+ const error = typeof state.accountOrdersError === 'string' ? state.accountOrdersError : null
963
+ const allOrders = Array.isArray(state.accountOrders)
964
+ ? (state.accountOrders as AccountOrderView[])
965
+ : []
966
+ const orders = loadedKeyRef.current === identityKey ? allOrders : []
967
+ const count = typeof state.accountOrdersCount === 'number' ? state.accountOrdersCount : orders.length
968
+ const page = typeof state.accountOrdersPage === 'number' ? state.accountOrdersPage : 1
969
+ const pageSize =
970
+ typeof state.accountOrdersPageSize === 'number' && state.accountOrdersPageSize > 0
971
+ ? state.accountOrdersPageSize
972
+ : ORDERS_PAGE_SIZE
973
+ const labels: Partial<OrderHistoryLabels> = {
974
+ ...(parsed.labels ?? {}),
975
+ ...(parsed.titleLabel === undefined ? {} : { title: parsed.titleLabel }),
976
+ ...(parsed.descriptionLabel === undefined ? {} : { description: parsed.descriptionLabel }),
977
+ ...(parsed.emptyLabel === undefined ? {} : { emptyLabel: parsed.emptyLabel }),
978
+ }
979
+
980
+ if (reconciling) return <ReconcilingStatus />
981
+ if (pending) {
982
+ return (
983
+ <p
984
+ role="status"
985
+ aria-live="polite"
986
+ className="text-muted-foreground mx-auto max-w-7xl px-4 py-8 text-sm"
987
+ >
988
+ {parsed.loadingLabel ?? 'Cargando pedidos…'}
989
+ </p>
990
+ )
991
+ }
992
+ if (error) {
993
+ return (
994
+ <div className="mx-auto flex w-full max-w-7xl flex-col items-start gap-3 px-4 py-8 sm:px-6 lg:px-8">
995
+ <p role="alert" className="text-destructive text-sm">
996
+ {error}
997
+ </p>
998
+ <Button
999
+ type="button"
1000
+ variant="outline"
1001
+ size="sm"
1002
+ disabled={pending}
1003
+ onClick={() => loadPage(requestedPageRef.current)}
1004
+ >
1005
+ Reintentar
1006
+ </Button>
1007
+ </div>
1008
+ )
1009
+ }
1010
+ const totalPages = Math.max(1, Math.ceil(count / pageSize))
1011
+ return (
1012
+ <div id="account-orders">
1013
+ <OrderHistoryBlock
1014
+ orders={orders.map(toOrderHistoryOrder)}
1015
+ presentation="cards"
1016
+ labels={labels}
1017
+ onViewOrder={(id) => router.push(`/account/orders/${encodeURIComponent(id)}`)}
1018
+ />
1019
+ {count > pageSize ? (
1020
+ <div className="mx-auto flex w-full max-w-7xl items-center justify-between gap-4 px-4 pb-6 sm:px-6 lg:px-8">
1021
+ <p className="text-muted-foreground text-sm" role="status" aria-live="polite">
1022
+ {`${count} pedidos · página ${page} de ${totalPages}`}
1023
+ </p>
1024
+ <div className="flex gap-2">
1025
+ <Button
1026
+ variant="outline"
1027
+ size="sm"
1028
+ disabled={pending || page <= 1}
1029
+ onClick={() => loadPage(page - 1)}
1030
+ >
1031
+ Anterior
1032
+ </Button>
1033
+ <Button
1034
+ variant="outline"
1035
+ size="sm"
1036
+ disabled={pending || page >= totalPages}
1037
+ onClick={() => loadPage(page + 1)}
1038
+ >
1039
+ Siguiente
1040
+ </Button>
1041
+ </div>
1042
+ </div>
1043
+ ) : null}
1044
+ </div>
1045
+ )
1046
+ }
1047
+
1048
+ export const registry: ViewRegistry = {
1049
+ AccountBoot: ({ emit }) => <AccountBoundary emit={emit} />,
1050
+ AccountOrderDetail: (ctx) => <AccountOrderDetailPanel {...ctx} />,
1051
+ AccountFulfillmentEvidence: (ctx) => <AccountFulfillmentEvidencePanel {...ctx} />,
1052
+ AccountShell: (ctx) => <AccountShellPanel {...ctx} />,
1053
+ AccountOverview: () => <AccountOverviewPanel />,
1054
+ AccountModulePlaceholder: () => <AccountModulePlaceholderPanel />,
1055
+ AccountOrders: (ctx) => <AccountOrdersPanel {...ctx} />,
1056
+ @@REGISTRY@@
1057
+ }