@thorprovider/storefront 0.9.0 → 0.11.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 (66) hide show
  1. package/README.md +8 -5
  2. package/assets/templates/app/app/globals.css +0 -1
  3. package/assets/templates/app/lib/__STOREFRONT__/account-session.core.ts +4 -2
  4. package/assets/templates/app/lib/__STOREFRONT__/account-user.core.ts +2 -1
  5. package/assets/templates/app/lib/__STOREFRONT__/actions.ts +130 -12
  6. package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +156 -9
  7. package/assets/templates/app/lib/__STOREFRONT__/confirmation.core.ts +38 -3
  8. package/assets/templates/app/lib/__STOREFRONT__/fulfillment-evidence-port.ts +31 -0
  9. package/assets/templates/app/lib/__STOREFRONT__/handlers.core.ts +21 -4
  10. package/assets/templates/app/lib/__STOREFRONT__/mappers.ts +6 -2
  11. package/assets/templates/app/lib/__STOREFRONT__/order-detail-aftersales.ts +55 -0
  12. package/assets/templates/app/lib/__STOREFRONT__/order-detail-capabilities.ts +79 -0
  13. package/assets/templates/app/lib/__STOREFRONT__/order-detail-mapper.ts +653 -0
  14. package/assets/templates/app/lib/__STOREFRONT__/order-detail-money.ts +39 -0
  15. package/assets/templates/app/lib/__STOREFRONT__/order-detail-port.ts +6 -7
  16. package/assets/templates/app/lib/__STOREFRONT__/order-detail-reorder.ts +62 -0
  17. package/assets/templates/app/lib/__STOREFRONT__/ports.ts +13 -3
  18. package/assets/templates/views/account/assembly/assembly.json +0 -5
  19. package/assets/templates/views/account/assembly/index.skeleton.tsx +51 -0
  20. package/assets/templates/views/account/assembly/registry.skeleton.tsx +120 -68
  21. package/assets/templates/views/account/content.ts +13 -7
  22. package/assets/templates/views/account/fulfillment-evidence.client.tsx +34 -0
  23. package/assets/templates/views/account/fulfillment-evidence.defaults.ts +145 -0
  24. package/assets/templates/views/account/fulfillment-evidence.schema.ts +15 -0
  25. package/assets/templates/views/account/index.tsx +44 -3
  26. package/assets/templates/views/account/order-detail-flows.defaults.ts +106 -0
  27. package/assets/templates/views/account/order-detail-invoice.ts +136 -0
  28. package/assets/templates/views/account/order-detail-sheet.tsx +100 -0
  29. package/assets/templates/views/account/order-detail-sheets.tsx +122 -0
  30. package/assets/templates/views/account/order-detail.client.tsx +401 -1
  31. package/assets/templates/views/account/orders-advanced.client.tsx +10 -99
  32. package/assets/templates/views/account/orders-advanced.defaults.ts +7 -7
  33. package/assets/templates/views/account/registry.tsx +120 -69
  34. package/assets/templates/views/account/schema.ts +2 -0
  35. package/assets/templates/views/home/assembly/assembly.json +1 -1
  36. package/assets/templates/views/home/assembly/index.skeleton.tsx +3 -1
  37. package/assets/templates/views/home/assembly/registry.skeleton.tsx +1 -0
  38. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/binding.json +5 -0
  39. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/catalog.part +4 -0
  40. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/element.part +4 -0
  41. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/registry.part +10 -0
  42. package/assets/templates/views/home/content.ts +248 -2
  43. package/assets/templates/views/home/data.ts +10 -1
  44. package/assets/templates/views/home/index.tsx +7 -6
  45. package/assets/templates/views/home/props.ts +7 -1
  46. package/assets/templates/views/home/registry.tsx +11 -28
  47. package/assets/templates/views/home/schema.ts +163 -0
  48. package/assets/templates/views/product/data.ts +13 -6
  49. package/assets/templates/views/product/index.tsx +3 -3
  50. package/bin/storefront.js +18 -18
  51. package/package.json +1 -1
  52. package/recipes/adapter-surface.json +1 -0
  53. package/recipes/archetypes.json +5 -1
  54. package/recipes/catalog.json +9 -1
  55. package/recipes/recipes.json +5 -4
  56. package/scripts/candidate.mjs +59 -14
  57. package/scripts/file-classes.mjs +4 -0
  58. package/scripts/mock-capabilities.mjs +22 -0
  59. package/scripts/reconcile.mjs +5 -2
  60. package/scripts/render-templates.mjs +126 -43
  61. package/skills/sf-view-gen/assets/recipes/archetypes.json +5 -1
  62. package/skills/sf-view-gen/assets/recipes/catalog.json +9 -1
  63. package/skills/sf-view-gen/assets/recipes/recipes.json +5 -4
  64. package/assets/templates/views/account/assembly/slots/boot/AccountBoot/catalog.part +0 -5
  65. package/assets/templates/views/account/assembly/slots/boot/AccountBoot/element.part +0 -5
  66. package/assets/templates/views/account/assembly/slots/boot/AccountBoot/registry.part +0 -1
package/README.md CHANGED
@@ -205,11 +205,14 @@ storefront feature add customer-addresses # refused when the backend lacks man
205
205
  ```
206
206
 
207
207
  A failed probe records no list (unknown), so capability-gated features stay
208
- uninstallable until `storefront setup` succeeds again. `storefront doctor` re-probes and
209
- reports an installed feature whose capability the backend no longer advertises. Features
210
- also declare `requires` (a module needs its host feature) and `adapter.needs` (callables
211
- checked against the adapter/commerce surface), and a held feature is inspectable with
212
- `storefront features --json` but never installable.
208
+ uninstallable until `storefront setup` succeeds again. In **mock mode** there is no
209
+ endpoint to probe, so `setup` records the mock provider's own flags: the modules the
210
+ mock genuinely supports (profile updates, address book, order history) install, and the
211
+ ones it refuses truthfully (email change, password change, saved payment methods) stay
212
+ out. `storefront doctor` re-probes and reports an installed feature whose capability the
213
+ backend no longer advertises. Features also declare `requires` (a module needs its host
214
+ feature) and `adapter.needs` (callables checked against the adapter/commerce surface),
215
+ and a held feature is inspectable with `storefront features --json` but never installable.
213
216
 
214
217
  The guest flow is backend-authoritative end to end: the signed host cookie binds a
215
218
  persistent backend cart; the PDP adds the explicitly selected variant; the cart and
@@ -1,5 +1,4 @@
1
1
  @import "tailwindcss";
2
- @import "tw-animate-css";
3
2
  @import "@thorprovider/blocks/styles.css";
4
3
 
5
4
  @custom-variant dark (&:is(.dark *));
@@ -20,15 +20,17 @@ import type { Customer } from '@thorprovider/types'
20
20
 
21
21
  /**
22
22
  * The display allowlist. Zod strips unknown keys on parse, so a backend
23
- * customer projects to exactly these four fields. An absent optional name is
23
+ * customer projects to exactly these fields. An absent optional name is
24
24
  * normalized to null (never undefined) so the projection is stable to
25
- * serialize.
25
+ * serialize. `createdAt` is the display-only join date the account header
26
+ * renders ("Cliente desde …"); it is a public account fact, never a credential.
26
27
  */
27
28
  export const accountIdentitySchema = z.object({
28
29
  id: z.string().min(1),
29
30
  email: z.string().min(1),
30
31
  firstName: z.string().nullish().transform((value) => value ?? null),
31
32
  lastName: z.string().nullish().transform((value) => value ?? null),
33
+ createdAt: z.string().nullish().transform((value) => value ?? null),
32
34
  })
33
35
 
34
36
  /** The only customer fields permitted in projected/serialized account state. */
@@ -5,7 +5,8 @@
5
5
  //
6
6
  // The navbar account menu renders `@thorprovider/blocks`' `StoreUser`
7
7
  // (`{ name, email, avatar?, initials }`), which differs from the allowlisted
8
- // identity (`{ id, email, firstName|null, lastName|null }`). The mapping lives
8
+ // identity (`{ id, email, firstName|null, lastName|null, createdAt|null }`).
9
+ // The mapping lives
9
10
  // in this DERIVED module — regenerated by the CLI — rather than in the
10
11
  // user-owned `mappers.ts` (seeded once, never rewritten by `reconcile`, so a new
11
12
  // required export there would break older storefronts on upgrade).
@@ -19,6 +19,7 @@ import type { AccountAddressView, AccountOrderView, CartLineState } from './stat
19
19
  import type {
20
20
  Address,
21
21
  CheckoutAddressOption,
22
+ CheckoutPaymentPlanItem,
22
23
  CreateAddressData,
23
24
  Customer,
24
25
  PaymentMethod,
@@ -32,7 +33,7 @@ import type {
32
33
  CheckoutSavedAddress,
33
34
  CheckoutShippingGroup,
34
35
  } from '@thorprovider/blocks'
35
- import type { OrdersPage, OrdersQuery } from '@thorprovider/blocks/ports'
36
+ import type { OrderDetailSnapshot, OrdersPage, OrdersQuery } from '@thorprovider/blocks/ports'
36
37
  import {
37
38
  EMPTY_CART_STATE,
38
39
  addVariant,
@@ -51,6 +52,7 @@ import {
51
52
  loadCheckoutShippingGroups,
52
53
  loadCustomer,
53
54
  loadCustomerAddresses,
55
+ loadCustomerOrderDetail,
54
56
  loadGeoCities,
55
57
  loadGeoProvinces,
56
58
  loadOrderHistoryPage,
@@ -92,6 +94,8 @@ import {
92
94
  writeAuthToken,
93
95
  } from './session'
94
96
  import type { AccountProfileMetadataPatch, AccountProfilePayload } from './account-profile'
97
+ import { toOrderDetailSnapshot } from './order-detail-mapper'
98
+ import { toReorderLines, type ReorderOrderResult } from './order-detail-reorder'
95
99
 
96
100
  // A `'use server'` module may export ONLY async functions. Next/Turbopack's
97
101
  // server-actions transform registers every export as a runtime server
@@ -191,6 +195,16 @@ type OrdersQueryPageActionResult =
191
195
  | { ok: true; page: OrdersPage }
192
196
  | { ok: false; error: string }
193
197
 
198
+ /**
199
+ * Structured result for the order-detail route. The code is the contract the
200
+ * host port maps to a `PortError`: `forbidden` (no session), `not_found`
201
+ * (unknown or foreign order) and `unavailable` (no detail read configured or a
202
+ * provider failure). It never carries a fabricated order.
203
+ */
204
+ type OrderDetailActionResult =
205
+ | { ok: true; snapshot: OrderDetailSnapshot }
206
+ | { ok: false; code: 'forbidden' | 'not_found' | 'unavailable'; error: string }
207
+
194
208
  /** Basic email shape check; a boundary guard, not a full RFC validation. */
195
209
  const EMAIL_PATTERN = /\S+@\S+\.\S+/
196
210
 
@@ -425,6 +439,53 @@ export async function addToCartByHandleAction(input: {
425
439
  }
426
440
  }
427
441
 
442
+ /**
443
+ * Re-add a stored order to the cart, addressed by its backend id.
444
+ *
445
+ * The ownership-scoped read is the only source of variants and quantities; the
446
+ * client never sends either. Adds are sequential because each one rewrites the
447
+ * cart, and a rejected variant is reported as a skipped line instead of being
448
+ * dropped or retried blindly.
449
+ */
450
+ export async function reorderOrderAction(input: {
451
+ orderId: string
452
+ }): Promise<ReorderOrderResult> {
453
+ const orderId = typeof input?.orderId === 'string' ? input.orderId.trim() : ''
454
+ if (!orderId) return { ok: false, error: 'Pedido no encontrado.' }
455
+
456
+ const context = getStoreContext()
457
+ const token = await readAuthToken(context)
458
+ if (!token) return { ok: false, error: 'Inicia sesión para repetir esta compra.' }
459
+
460
+ try {
461
+ const order = await loadCustomerOrderDetail(token, orderId, context)
462
+ const { lines, skipped } = toReorderLines(order)
463
+ if (lines.length === 0) return { ok: true, added: 0, skipped }
464
+
465
+ const { cartId, context: cartContext, provider } = await ensureActiveCartId()
466
+ let added = 0
467
+ for (const line of lines) {
468
+ try {
469
+ await addVariant(cartId, line.variantId, line.quantity, cartContext, provider)
470
+ added += line.quantity
471
+ } catch (error) {
472
+ skipped.push({ title: line.title, reason: toError(error, 'No se pudo agregar') })
473
+ }
474
+ }
475
+ return { ok: true, added, skipped }
476
+ } catch (error) {
477
+ logServerError('reorderOrderAction', error)
478
+ const code = errorCode(error)
479
+ if (code === 'ORDER_DETAIL_NOT_FOUND' || code === 'RESOURCE_NOT_FOUND') {
480
+ return { ok: false, error: 'Pedido no encontrado.' }
481
+ }
482
+ if (code === 'ORDER_DETAIL_FORBIDDEN' || code === 'AUTH_UNAUTHENTICATED') {
483
+ return { ok: false, error: 'Inicia sesión para repetir esta compra.' }
484
+ }
485
+ return { ok: false, error: toError(error, 'No se pudo repetir la compra.') }
486
+ }
487
+ }
488
+
428
489
  /** Set a backend cart line to an ABSOLUTE quantity by its line-item id. */
429
490
  export async function setLineQuantityAction(input: {
430
491
  lineId: string
@@ -1125,7 +1186,11 @@ async function clearConfirmedSession(
1125
1186
  * a committed order as a retryable failure.
1126
1187
  */
1127
1188
  export async function placeOrderAction(
1128
- input: { shippingGroups?: ShippingGroupSelection[]; paymentMethodId?: string } = {},
1189
+ input: {
1190
+ shippingGroups?: ShippingGroupSelection[]
1191
+ paymentMethodId?: string
1192
+ payments?: CheckoutPaymentPlanItem[]
1193
+ } = {},
1129
1194
  ): Promise<PlaceOrderResult> {
1130
1195
  try {
1131
1196
  const { cartId, context, provider, customerId } = await ensureActiveCartId({
@@ -1139,9 +1204,13 @@ export async function placeOrderAction(
1139
1204
  }
1140
1205
  }
1141
1206
 
1207
+ const paymentPlan =
1208
+ Array.isArray(input.payments) && input.payments.length > 0
1209
+ ? input.payments
1210
+ : undefined
1142
1211
  const paymentMethodId =
1143
1212
  typeof input.paymentMethodId === 'string' ? input.paymentMethodId.trim() : ''
1144
- if (!paymentMethodId) {
1213
+ if (!paymentPlan && !paymentMethodId) {
1145
1214
  return {
1146
1215
  status: 'error',
1147
1216
  message: 'Selecciona un método de pago antes de confirmar.',
@@ -1174,21 +1243,26 @@ export async function placeOrderAction(
1174
1243
  }
1175
1244
  }
1176
1245
  }
1177
- try {
1178
- await applyPayment(cartId, paymentMethodId, context, provider)
1179
- } catch (error) {
1180
- logServerError('applyPayment', error)
1181
- return {
1182
- status: 'error',
1183
- message: toError(error, 'No se pudo iniciar el pago.'),
1184
- code: 'PAYMENT_METHOD_REJECTED',
1246
+ // A payment plan defines every instrument with an exact amount; the
1247
+ // backend creates and authorizes the sessions. The legacy single-method
1248
+ // path keeps working when no plan is supplied.
1249
+ if (!paymentPlan) {
1250
+ try {
1251
+ await applyPayment(cartId, paymentMethodId, context, provider)
1252
+ } catch (error) {
1253
+ logServerError('applyPayment', error)
1254
+ return {
1255
+ status: 'error',
1256
+ message: toError(error, 'No se pudo iniciar el pago.'),
1257
+ code: 'PAYMENT_METHOD_REJECTED',
1258
+ }
1185
1259
  }
1186
1260
  }
1187
1261
  // Thread the request's customer token (design D11) so an authenticated
1188
1262
  // checkout is attributed to the session customer; guests complete the same
1189
1263
  // tokenless provider as before.
1190
1264
  const customerToken = await readAuthToken(context)
1191
- const result = await completeOrder(cartId, context, customerToken)
1265
+ const result = await completeOrder(cartId, context, customerToken, paymentPlan)
1192
1266
  if (result.status !== 'order') return result
1193
1267
  if (!(await clearConfirmedSession(context, cartId))) {
1194
1268
  return {
@@ -1487,6 +1561,50 @@ export async function listOrdersQueryPageAction(
1487
1561
  }
1488
1562
  }
1489
1563
 
1564
+ /**
1565
+ * Load ONE order for the authenticated customer and project it into the
1566
+ * order-detail snapshot. It touches ONLY the auth cookie — never the guest cart
1567
+ * — and no token is logged or returned. No token yields `forbidden` without a
1568
+ * backend call; an unknown or foreign order yields `not_found` without
1569
+ * revealing whether it exists. A provider without a customer detail read fails
1570
+ * closed as `unavailable`; the detail is never assembled from the list.
1571
+ */
1572
+ export async function loadOrderDetailAction(input: {
1573
+ id: string
1574
+ }): Promise<OrderDetailActionResult> {
1575
+ const id = typeof input?.id === 'string' ? input.id.trim() : ''
1576
+ if (!id) {
1577
+ return { ok: false, code: 'not_found', error: 'Pedido no encontrado.' }
1578
+ }
1579
+ const context = getStoreContext()
1580
+ const token = await readAuthToken(context)
1581
+ if (!token) {
1582
+ return {
1583
+ ok: false,
1584
+ code: 'forbidden',
1585
+ error: 'Inicia sesión con una cuenta autorizada para consultar el pedido.',
1586
+ }
1587
+ }
1588
+ try {
1589
+ const order = await loadCustomerOrderDetail(token, id, context)
1590
+ return { ok: true, snapshot: toOrderDetailSnapshot(order) }
1591
+ } catch (error) {
1592
+ const code = errorCode(error)
1593
+ if (code === 'ORDER_DETAIL_NOT_FOUND' || code === 'RESOURCE_NOT_FOUND') {
1594
+ return { ok: false, code: 'not_found', error: 'Pedido no encontrado.' }
1595
+ }
1596
+ if (code === 'ORDER_DETAIL_FORBIDDEN' || code === 'AUTH_UNAUTHENTICATED') {
1597
+ return {
1598
+ ok: false,
1599
+ code: 'forbidden',
1600
+ error: 'Inicia sesión con una cuenta autorizada para consultar el pedido.',
1601
+ }
1602
+ }
1603
+ logServerError('loadOrderDetailAction', error)
1604
+ return { ok: false, code: 'unavailable', error: 'No se pudo cargar el pedido.' }
1605
+ }
1606
+ }
1607
+
1490
1608
  // ---------------------------------------------------------------------------
1491
1609
  // Account modules (change: storefront-customer-view, task 4.4)
1492
1610
  // ---------------------------------------------------------------------------
@@ -22,6 +22,8 @@ import type {
22
22
  Address,
23
23
  Cart,
24
24
  CheckoutAddressOption,
25
+ CheckoutPaymentPlanItem,
26
+ CheckoutPaymentSummary,
25
27
  CreateAddressData,
26
28
  Customer,
27
29
  LoginCredentials,
@@ -59,6 +61,7 @@ import {
59
61
  getGeoCities,
60
62
  getGeoProvinces,
61
63
  getCustomerOrdersPage,
64
+ getCustomerOrderDetail,
62
65
  getEligibleShippingMethods,
63
66
  getPaymentMethodsByRegion,
64
67
  getProductDetailByHandle,
@@ -97,7 +100,10 @@ import type {
97
100
  StorefrontOrderLineView,
98
101
  } from './state.core'
99
102
  import { assertBackendConfigured, getDataSource, getStoreContext, type StoreDataSource } from './store-context'
100
- import { queryOrderHistoryPage } from '@thorprovider/blocks'
103
+ // The query engine is imported through its server-safe subpath: the package
104
+ // root is a client entry (`'use client'`), so a Server Action cannot call a
105
+ // function exported from it (React refuses a client function on the server).
106
+ import { queryOrderHistoryPage } from '@thorprovider/blocks/order-history-engine'
101
107
  import type { OrderHistoryAdvancedRecord } from '@thorprovider/blocks'
102
108
  import type { OrdersPage, OrdersQuery } from '@thorprovider/blocks/ports'
103
109
 
@@ -144,6 +150,7 @@ export type PlaceOrderResult =
144
150
  order: StorefrontOrder
145
151
  lines: StorefrontOrderLineView[]
146
152
  confirmation: StorefrontConfirmation
153
+ paymentSummary?: CheckoutPaymentSummary
147
154
  }
148
155
  | { status: 'error'; message: string; code?: string }
149
156
  | { status: 'cart-error'; message: string; code?: string }
@@ -295,6 +302,7 @@ export function toPlaceOrderResult(result: CartCompletionResult): PlaceOrderResu
295
302
  order: toStorefrontOrder(result.order),
296
303
  lines: toOrderLines(result.order),
297
304
  confirmation: toStorefrontConfirmation(result.order),
305
+ ...(result.paymentSummary ? { paymentSummary: result.paymentSummary } : {}),
298
306
  }
299
307
  }
300
308
  if (result.type === 'cart') {
@@ -639,6 +647,7 @@ export async function completeOrder(
639
647
  cartId: string,
640
648
  context: StoreContext = getStoreContext(),
641
649
  customerToken?: string | null,
650
+ payments?: CheckoutPaymentPlanItem[],
642
651
  ): Promise<PlaceOrderResult> {
643
652
  assertBackendConfigured()
644
653
  // The host owns the auth cookie and threads the request's customer token
@@ -646,7 +655,12 @@ export async function completeOrder(
646
655
  // customer (mock) or links it server-side (Medusa). A tokenless completion
647
656
  // builds exactly the provider the previous token-blind default built.
648
657
  return toPlaceOrderResult(
649
- await completeCart(cartId, context, getCommerceClientWithToken(customerToken ?? null)),
658
+ await completeCart(
659
+ cartId,
660
+ context,
661
+ getCommerceClientWithToken(customerToken ?? null),
662
+ payments,
663
+ ),
650
664
  )
651
665
  }
652
666
 
@@ -660,10 +674,16 @@ export async function reconcileOrder(
660
674
  cartId: string,
661
675
  context: StoreContext = getStoreContext(),
662
676
  customerToken?: string | null,
677
+ payments?: CheckoutPaymentPlanItem[],
663
678
  ): Promise<PlaceOrderResult> {
664
679
  assertBackendConfigured()
665
680
  return toPlaceOrderResult(
666
- await reconcileCart(cartId, context, getCommerceClientWithToken(customerToken ?? null)),
681
+ await reconcileCart(
682
+ cartId,
683
+ context,
684
+ getCommerceClientWithToken(customerToken ?? null),
685
+ payments,
686
+ ),
667
687
  )
668
688
  }
669
689
 
@@ -970,6 +990,100 @@ function toOrderHistoryFulfilmentStatus(
970
990
  }
971
991
  }
972
992
 
993
+ type OrderHistoryFulfilmentStage =
994
+ | 'shipped'
995
+ | 'delayed'
996
+ | 'ready_for_pickup'
997
+ | 'partially_delivered'
998
+
999
+ type OrderHistoryLifecycleHint = {
1000
+ fulfilment?: OrderHistoryFulfilmentStage
1001
+ returns?: OrderHistoryAdvancedRecord['returns']
1002
+ payment?: 'partially_paid'
1003
+ creditTerms?: boolean
1004
+ partiallyCancelled?: boolean
1005
+ }
1006
+
1007
+ const FULFILMENT_STAGES: readonly string[] = [
1008
+ 'shipped',
1009
+ 'delayed',
1010
+ 'ready_for_pickup',
1011
+ 'partially_delivered',
1012
+ ]
1013
+ const RETURN_STAGES: readonly string[] = ['none', 'requested', 'in_progress', 'completed']
1014
+
1015
+ /**
1016
+ * Optional lifecycle detail the universal order envelope cannot express yet
1017
+ * (a delayed shipment, an open return, a partial payment). A backend or a demo
1018
+ * fixture may publish it under `metadata.orderHistory`; the mapper validates
1019
+ * every value and falls back to the truthful aggregate status otherwise.
1020
+ */
1021
+ function readOrderHistoryHint(order: Order): OrderHistoryLifecycleHint {
1022
+ const raw = order.metadata?.orderHistory
1023
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}
1024
+ const candidate = raw as Record<string, unknown>
1025
+ const hint: OrderHistoryLifecycleHint = {}
1026
+ if (typeof candidate.fulfilment === 'string' && FULFILMENT_STAGES.includes(candidate.fulfilment)) {
1027
+ hint.fulfilment = candidate.fulfilment as OrderHistoryFulfilmentStage
1028
+ }
1029
+ if (typeof candidate.returns === 'string' && RETURN_STAGES.includes(candidate.returns)) {
1030
+ hint.returns = candidate.returns as OrderHistoryAdvancedRecord['returns']
1031
+ }
1032
+ if (candidate.payment === 'partially_paid') hint.payment = 'partially_paid'
1033
+ if (typeof candidate.creditTerms === 'boolean') hint.creditTerms = candidate.creditTerms
1034
+ if (typeof candidate.partiallyCancelled === 'boolean') {
1035
+ hint.partiallyCancelled = candidate.partiallyCancelled
1036
+ }
1037
+ return hint
1038
+ }
1039
+
1040
+ /**
1041
+ * The action menu is a function of the order's truthful state: a delivered
1042
+ * order can be repeated, returned or invoiced; an open one can be cancelled or
1043
+ * paid. Capabilities still gate what the store offers, and the block intersects
1044
+ * both lists before rendering an action.
1045
+ */
1046
+ function deriveOrderHistoryActions(input: {
1047
+ commercial: OrderHistoryAdvancedRecord['commercial']
1048
+ paymentStatus: OrderHistoryAdvancedRecord['payment']['status']
1049
+ fulfilmentStatus: OrderHistoryAdvancedRecord['fulfilment']['status']
1050
+ returns: OrderHistoryAdvancedRecord['returns']
1051
+ }): OrderHistoryAdvancedRecord['availableActions'] {
1052
+ const actions: OrderHistoryAdvancedRecord['availableActions'] = ['view']
1053
+ switch (input.commercial) {
1054
+ case 'completed':
1055
+ actions.push('reorder', 'invoice')
1056
+ break
1057
+ case 'cancelled':
1058
+ actions.push('invoice')
1059
+ break
1060
+ case 'processing':
1061
+ if (input.paymentStatus === 'paid') actions.push('invoice')
1062
+ if (input.fulfilmentStatus === 'unfulfilled') actions.push('cancel')
1063
+ break
1064
+ case 'pending':
1065
+ actions.push('cancel')
1066
+ break
1067
+ }
1068
+ if (input.paymentStatus === 'unpaid' || input.paymentStatus === 'partially_paid') {
1069
+ actions.push('pay-balance')
1070
+ }
1071
+ if (
1072
+ input.fulfilmentStatus === 'shipped' ||
1073
+ input.fulfilmentStatus === 'partially_delivered' ||
1074
+ input.fulfilmentStatus === 'ready_for_pickup' ||
1075
+ input.fulfilmentStatus === 'delayed'
1076
+ ) {
1077
+ actions.push('track')
1078
+ }
1079
+ if (input.fulfilmentStatus === 'delivered' && input.returns === 'none') {
1080
+ actions.push('return', 'exchange')
1081
+ }
1082
+ if (input.returns === 'requested' || input.returns === 'in_progress') actions.push('problem')
1083
+ actions.push('support')
1084
+ return actions
1085
+ }
1086
+
973
1087
  function toOrderHistoryDeliveryMode(
974
1088
  order: Order,
975
1089
  ): OrderHistoryAdvancedRecord['deliveryMode'] {
@@ -1005,8 +1119,15 @@ export function toOrderHistoryItem(
1005
1119
 
1006
1120
  /** Map one backend order to the advanced block's normalised record. */
1007
1121
  export function toOrderHistoryRecord(order: Order): OrderHistoryAdvancedRecord {
1122
+ const hint = readOrderHistoryHint(order)
1008
1123
  const items = order.items.map(toOrderHistoryItem)
1009
- return {
1124
+ const commercial = toOrderHistoryCommercial(order.status)
1125
+ const paymentStatus = hint.payment ?? toOrderHistoryPaymentStatus(order.paymentStatus)
1126
+ const fulfilmentStatus =
1127
+ hint.fulfilment ?? toOrderHistoryFulfilmentStatus(order.fulfillmentStatus)
1128
+ const returns =
1129
+ hint.returns ?? (order.fulfillmentStatus === 'returned' ? 'completed' : 'none')
1130
+ const record: OrderHistoryAdvancedRecord = {
1010
1131
  id: order.id,
1011
1132
  number: order.orderNumber,
1012
1133
  placedAt: toOrderHistoryDate(order.createdAt),
@@ -1014,19 +1135,26 @@ export function toOrderHistoryRecord(order: Order): OrderHistoryAdvancedRecord {
1014
1135
  total: toOrderHistoryMoney(order.total),
1015
1136
  items,
1016
1137
  itemCount: items.reduce((sum, item) => sum + item.quantity, 0),
1017
- commercial: toOrderHistoryCommercial(order.status),
1018
- payment: { status: toOrderHistoryPaymentStatus(order.paymentStatus), creditTerms: false },
1138
+ commercial,
1139
+ payment: { status: paymentStatus, creditTerms: hint.creditTerms ?? false },
1019
1140
  refund: toOrderHistoryRefund(order.paymentStatus),
1020
1141
  // The order envelope carries no per-shipment records, so the host reports
1021
1142
  // the aggregate fulfilment status and no fabricated shipment list.
1022
1143
  fulfilment: {
1023
- status: toOrderHistoryFulfilmentStatus(order.fulfillmentStatus),
1144
+ status: fulfilmentStatus,
1024
1145
  shipments: [],
1025
1146
  },
1026
1147
  deliveryMode: toOrderHistoryDeliveryMode(order),
1027
- returns: order.fulfillmentStatus === 'returned' ? 'completed' : 'none',
1028
- availableActions: ['view'],
1148
+ returns,
1149
+ availableActions: deriveOrderHistoryActions({
1150
+ commercial,
1151
+ paymentStatus,
1152
+ fulfilmentStatus,
1153
+ returns,
1154
+ }),
1029
1155
  }
1156
+ if (hint.partiallyCancelled) record.partiallyCancelled = true
1157
+ return record
1030
1158
  }
1031
1159
 
1032
1160
  // The query ids the block renders. Validated here because a Server Action is a
@@ -1081,4 +1209,23 @@ export async function loadOrderHistoryPage(
1081
1209
  return queryOrderHistoryPage(orders.map(toOrderHistoryRecord), normalized)
1082
1210
  }
1083
1211
 
1212
+ /**
1213
+ * Resolve ONE order for the authenticated customer. It is a separate,
1214
+ * ownership-scoped read: the provider resolves the token to a customer and the
1215
+ * order must belong to that customer and the store's channel. In mock mode the
1216
+ * bundled provider serves the same seeded order store as the history; a live
1217
+ * provider that has not shipped the detail endpoint fails closed, and the
1218
+ * detail is never assembled from the list payload.
1219
+ */
1220
+ export async function loadCustomerOrderDetail(
1221
+ token: string | null,
1222
+ id: string,
1223
+ context: StoreContext = getStoreContext(),
1224
+ ): Promise<Order> {
1225
+ return getCustomerOrderDetail(
1226
+ { token, id, salesChannelId: context.salesChannelId },
1227
+ getCommerceClientWithToken,
1228
+ )
1229
+ }
1230
+
1084
1231
  export type { Money }
@@ -41,6 +41,15 @@ export interface StorefrontConfirmationGroup {
41
41
  lines: StorefrontConfirmationLine[]
42
42
  }
43
43
 
44
+ export interface StorefrontConfirmationPayment {
45
+ id: string
46
+ providerId: string
47
+ label: string
48
+ amountCents?: number
49
+ status: 'authorized' | 'captured' | 'canceled' | 'pending'
50
+ capturedAt?: string
51
+ }
52
+
44
53
  export interface StorefrontConfirmationPromotion {
45
54
  id: string
46
55
  label: string
@@ -65,6 +74,8 @@ export interface StorefrontConfirmation {
65
74
  address: StorefrontConfirmationAddress | null
66
75
  paymentLabel: string
67
76
  paymentDetail: string
77
+ /** Per-instrument breakdown when the order reports multiple payments. */
78
+ payments?: StorefrontConfirmationPayment[]
68
79
  billingLabel: string
69
80
  billingDetail: string
70
81
  customerName: string
@@ -149,10 +160,33 @@ export function toStorefrontConfirmation(order: Order): StorefrontConfirmation {
149
160
  order.deliveryGroups?.length
150
161
  ? order.deliveryGroups.every((group) => group.mode === 'pickup')
151
162
  : order.shippingMethod?.mode === 'pickup'
152
- const paymentLabel =
153
- order.payment?.providerId === APPROVED_MANUAL_TEST_PROVIDER_ID
163
+ const labelForPayment = (payment: {
164
+ providerId?: string
165
+ label?: string
166
+ }): string =>
167
+ payment.providerId === APPROVED_MANUAL_TEST_PROVIDER_ID
154
168
  ? 'Pago manual TEST'
155
- : order.payment?.label ?? ''
169
+ : payment.label ?? ''
170
+ const payments: StorefrontConfirmationPayment[] = (order.payments ?? []).map(
171
+ (payment) => {
172
+ const amountCents = moneyToCents(payment.amount)
173
+ return {
174
+ id: payment.id,
175
+ providerId: payment.providerId,
176
+ label: labelForPayment(payment),
177
+ ...(amountCents !== undefined ? { amountCents } : {}),
178
+ status: payment.status,
179
+ ...(payment.capturedAt ? { capturedAt: payment.capturedAt } : {}),
180
+ }
181
+ },
182
+ )
183
+ const paymentLabel =
184
+ payments.length > 0
185
+ ? payments
186
+ .map((payment) => payment.label)
187
+ .filter((label) => label.trim() !== '')
188
+ .join(' + ')
189
+ : labelForPayment(order.payment ?? {})
156
190
 
157
191
  // One confirmation entry per confirmed backend group, preserving each
158
192
  // group's mode, method, detail, fee and line membership. Line membership is
@@ -228,6 +262,7 @@ export function toStorefrontConfirmation(order: Order): StorefrontConfirmation {
228
262
  : null,
229
263
  paymentLabel,
230
264
  paymentDetail: order.payment?.detail ?? '',
265
+ ...(payments.length > 0 ? { payments } : {}),
231
266
  billingLabel: billing ? billing.label || 'Dirección de facturación' : '',
232
267
  billingDetail: billing ? addressDetail(billing) : '',
233
268
  customerName,
@@ -0,0 +1,31 @@
1
+ import { PortError } from '@thorprovider/blocks/ports'
2
+ import type { FulfillmentEvidencePort } from '@thorprovider/blocks/ports'
3
+
4
+ export type FulfillmentEvidenceRunner = FulfillmentEvidencePort
5
+
6
+ /**
7
+ * Host seam for the fulfillment-evidence route. Until the evidence backend and
8
+ * signed asset resolution exist, both reads fail closed with a typed
9
+ * `unavailable` error; the landed gallery renders its own error state and never
10
+ * falls back to demo data. The backend owner supplies the runner and the route
11
+ * binding does not change.
12
+ */
13
+ export function createFulfillmentEvidencePort(
14
+ runner?: FulfillmentEvidenceRunner,
15
+ ): FulfillmentEvidencePort {
16
+ if (runner) return runner
17
+ return {
18
+ async getEvidence(fulfillmentId) {
19
+ throw new PortError(
20
+ 'unavailable',
21
+ `Fulfillment evidence is not connected to the backend yet (requested ${fulfillmentId}).`,
22
+ )
23
+ },
24
+ async resolveAssetUrl(assetId) {
25
+ throw new PortError(
26
+ 'unavailable',
27
+ `Evidence asset resolution is not connected to the backend yet (requested ${assetId}).`,
28
+ )
29
+ },
30
+ }
31
+ }
@@ -87,9 +87,18 @@ export function useCoreHandlers() {
87
87
  // A confirmed cart transition — observed only after the mutation
88
88
  // succeeded, and only when a section origin exists (default: off).
89
89
  recordConfirmedTransition('cart_add_confirmed')
90
- } else fail(result.error)
90
+ } else {
91
+ // A refused add (out of stock, no purchasable variant) must be
92
+ // visible: open the sheet so its error label renders instead of
93
+ // failing silently — which read as "the previous item replaced".
94
+ set('/cartOpen', true)
95
+ fail(result.error)
96
+ }
97
+ })
98
+ .catch((error) => {
99
+ set('/cartOpen', true)
100
+ onError('addToCart')(error)
91
101
  })
92
- .catch(onError('addToCart'))
93
102
  },
94
103
  addClickedToCart: () => {
95
104
  // Product-card shortcut: add the clicked product's first purchasable
@@ -104,9 +113,17 @@ export function useCoreHandlers() {
104
113
  applyCart(result.cart)
105
114
  set('/cartOpen', true)
106
115
  recordConfirmedTransition('cart_add_confirmed')
107
- } else fail(result.error)
116
+ } else {
117
+ // Same visibility contract as the explicit add: a refused add
118
+ // opens the sheet so the error is seen, never silent.
119
+ set('/cartOpen', true)
120
+ fail(result.error)
121
+ }
122
+ })
123
+ .catch((error) => {
124
+ set('/cartOpen', true)
125
+ onError('addClickedToCart')(error)
108
126
  })
109
- .catch(onError('addClickedToCart'))
110
127
  },
111
128
  ensureCart: () => {
112
129
  begin()