@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,642 @@
1
+ // Generated by Thor Commerce storefront (template: assets/templates/app/lib/__STOREFRONT__/order-detail-mapper.ts)
2
+ //
3
+ // The host-side projection from the universal `Order` the provider reports to
4
+ // the order-detail surface's snapshot contract. It is pure and server-safe:
5
+ // no React, no Next.js, no transport. Every displayed amount comes from the
6
+ // order the provider returned; the mapper only converts the decimal money
7
+ // envelope to integer minor units and groups the existing fields.
8
+ //
9
+ // Honest limits: the universal order envelope does not carry per-shipment
10
+ // allocations, transactions or after-sales cases. A provider that has a richer
11
+ // detail contract replaces this factory later; until then the mapper derives
12
+ // only what the envelope states (aggregate fulfilment, the single payment
13
+ // status, the order's own lines/addresses/totals) and never invents a line, a
14
+ // charge or a section.
15
+
16
+ import type {
17
+ Address as CommerceAddress,
18
+ Money as CommerceMoney,
19
+ Order,
20
+ } from '@thorprovider/types'
21
+ import type {
22
+ Adjustment,
23
+ AfterSalesCase,
24
+ Fulfillment,
25
+ OrderDetailFulfillmentStatus,
26
+ LogisticsGroup,
27
+ OrderDetailMoney,
28
+ OrderDetailActionId,
29
+ OrderDetailOrder,
30
+ OrderDetailSnapshot,
31
+ OrderLine,
32
+ TaxLine,
33
+ Transaction,
34
+ } from '@thorprovider/blocks/ports'
35
+
36
+ type Money = OrderDetailMoney
37
+ type FulfillmentStatus = OrderDetailFulfillmentStatus
38
+ type OrderActionId = OrderDetailActionId
39
+
40
+ const MOCK_TRACKING_CARRIER = 'Thor Express'
41
+ const MOCK_PICKUP = {
42
+ locationName: 'Thor Store · Centro',
43
+ address: 'Av. Reforma 100, Ciudad de México',
44
+ schedule: 'Lun–Sáb · 10:00–19:00',
45
+ } as const
46
+
47
+ type LifecycleHint = {
48
+ fulfilment?: 'shipped' | 'delayed' | 'ready_for_pickup' | 'partially_delivered'
49
+ returns?: 'none' | 'requested' | 'in_progress' | 'completed'
50
+ payment?: 'partially_paid'
51
+ /** Mock fixture: captured amount for a partially paid order (major units). */
52
+ paidAmount?: number
53
+ /** Mock fixture: refunded amount for a partially refunded order (major units). */
54
+ refundAmount?: number
55
+ creditTerms?: boolean
56
+ partiallyCancelled?: boolean
57
+ }
58
+
59
+ function readLifecycleHint(order: Order): LifecycleHint {
60
+ const raw = order.metadata?.orderHistory
61
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}
62
+ return raw as LifecycleHint
63
+ }
64
+
65
+ function currencyDigits(currency: string): number {
66
+ try {
67
+ return (
68
+ new Intl.NumberFormat('en', { style: 'currency', currency }).resolvedOptions()
69
+ .maximumFractionDigits ?? 2
70
+ )
71
+ } catch {
72
+ return 2
73
+ }
74
+ }
75
+
76
+ /** The backend decimal string as integer minor units, the block's money shape. */
77
+ export function toDetailMoney(
78
+ value: CommerceMoney | undefined,
79
+ currency: string,
80
+ ): Money {
81
+ const code = value?.currencyCode ?? currency
82
+ const amount = Number(value?.amount ?? 0)
83
+ return {
84
+ amount: Number.isFinite(amount) ? Math.round(amount * 10 ** currencyDigits(code)) : 0,
85
+ currency: code,
86
+ }
87
+ }
88
+
89
+ function zero(currency: string): Money {
90
+ return { amount: 0, currency }
91
+ }
92
+
93
+ function toDetailAddress(address: CommerceAddress | undefined): OrderDetailOrder['shippingAddress'] {
94
+ if (!address) return undefined
95
+ const name = [address.firstName, address.lastName].filter(Boolean).join(' ').trim()
96
+ if (!name || !address.address1 || !address.city || !address.countryCode) return undefined
97
+ return {
98
+ name,
99
+ line1: address.address1,
100
+ ...(address.address2 ? { line2: address.address2 } : {}),
101
+ city: address.city,
102
+ ...(address.province ? { region: address.province } : {}),
103
+ postalCode: address.postalCode ?? '',
104
+ country: address.countryCode,
105
+ ...(address.phone ? { phone: address.phone } : {}),
106
+ }
107
+ }
108
+
109
+ function toCommercial(order: Order): OrderDetailOrder['commercial'] {
110
+ switch (order.status) {
111
+ case 'pending':
112
+ case 'processing':
113
+ case 'completed':
114
+ case 'cancelled':
115
+ return order.status
116
+ // A refunded order is finished; the refund is carried by its transactions.
117
+ case 'refunded':
118
+ return 'completed'
119
+ }
120
+ }
121
+
122
+ function toFulfillmentStatus(order: Order, hint: LifecycleHint): FulfillmentStatus {
123
+ if (order.status === 'cancelled') return 'cancelled'
124
+ switch (order.fulfillmentStatus) {
125
+ case 'unfulfilled':
126
+ if (hint.fulfilment === 'ready_for_pickup') return 'ready_for_pickup'
127
+ return order.status === 'processing' ? 'preparing' : 'pending'
128
+ case 'partially_fulfilled':
129
+ return 'partially_delivered'
130
+ case 'fulfilled':
131
+ return order.completedAt ? 'delivered' : 'shipped'
132
+ case 'returned':
133
+ return 'delivered'
134
+ }
135
+ }
136
+
137
+ type GroupSource = {
138
+ id: string
139
+ mode: 'shipping' | 'pickup'
140
+ methodName: string
141
+ fee: CommerceMoney | undefined
142
+ lineIds: string[]
143
+ }
144
+
145
+ function resolveGroupSources(order: Order): GroupSource[] {
146
+ const allLineIds = order.items.map((item) => item.id)
147
+ if (Array.isArray(order.deliveryGroups) && order.deliveryGroups.length > 0) {
148
+ return order.deliveryGroups.map((group, index) => ({
149
+ id: group.id,
150
+ mode: group.mode === 'pickup' ? 'pickup' : 'shipping',
151
+ methodName:
152
+ group.methodLabel ?? (group.mode === 'pickup' ? 'Recogida en tienda' : 'Envío estándar'),
153
+ fee: group.fee ?? (index === 0 ? order.shipping : undefined),
154
+ lineIds:
155
+ Array.isArray(group.lineIds) && group.lineIds.length > 0 ? group.lineIds : allLineIds,
156
+ }))
157
+ }
158
+ return [
159
+ {
160
+ id: `${order.id}-group-default`,
161
+ mode: order.shippingMethod?.mode === 'pickup' ? 'pickup' : 'shipping',
162
+ methodName: order.shippingMethod?.label ?? 'Envío estándar',
163
+ fee: order.shipping,
164
+ lineIds: allLineIds,
165
+ },
166
+ ]
167
+ }
168
+
169
+ function toOrderLine(
170
+ item: Order['items'][number],
171
+ currency: string,
172
+ cancelledQuantity: number,
173
+ ): OrderLine {
174
+ const chargeable = Math.max(0, item.quantity - cancelledQuantity)
175
+ const unit = toDetailMoney(item.price, currency)
176
+ const lineTotal: Money = { amount: unit.amount * chargeable, currency }
177
+ return {
178
+ id: item.id,
179
+ ...(item.productId ? { productId: item.productId } : {}),
180
+ name: item.title,
181
+ sku: item.sku ?? item.variantId ?? item.id,
182
+ ...(item.image?.url ? { image: item.image.url } : {}),
183
+ ...(item.variantTitle ? { variant: item.variantTitle } : {}),
184
+ quantity: item.quantity,
185
+ cancelledQuantity,
186
+ unitPrice: { original: unit, applied: unit, kind: 'list' },
187
+ subtotal: lineTotal,
188
+ discounts: [],
189
+ taxes: [] as TaxLine[],
190
+ total: lineTotal,
191
+ attributes: [],
192
+ kind: 'physical',
193
+ }
194
+ }
195
+
196
+ function calculateTax(order: Order, currency: string, orderDiscount: number): number {
197
+ if (order.tax) return toDetailMoney(order.tax, currency).amount
198
+ const subtotal = toDetailMoney(order.subtotal, currency).amount
199
+ const shipping = toDetailMoney(order.shipping, currency).amount
200
+ const total = toDetailMoney(order.total, currency).amount
201
+ return Math.max(0, total - subtotal - shipping + orderDiscount)
202
+ }
203
+
204
+ function allocateLines(
205
+ lines: OrderLine[],
206
+ group: GroupSource,
207
+ status: FulfillmentStatus,
208
+ ): { lineId: string; quantity: number }[] {
209
+ const groupLines = lines.filter((line) => group.lineIds.includes(line.id))
210
+ const chargeable = (line: OrderLine) => Math.max(0, line.quantity - line.cancelledQuantity)
211
+ if (status === 'pending' || status === 'preparing' || status === 'ready_for_pickup' || status === 'cancelled') {
212
+ return []
213
+ }
214
+ if (status === 'partially_delivered') {
215
+ const first = groupLines.find((line) => chargeable(line) > 0)
216
+ return first ? [{ lineId: first.id, quantity: chargeable(first) }] : []
217
+ }
218
+ return groupLines
219
+ .filter((line) => chargeable(line) > 0)
220
+ .map((line) => ({ lineId: line.id, quantity: chargeable(line) }))
221
+ }
222
+
223
+ function toFulfillment(
224
+ order: Order,
225
+ group: GroupSource,
226
+ status: FulfillmentStatus,
227
+ lines: OrderLine[],
228
+ isMock: boolean,
229
+ ): Fulfillment {
230
+ const allocations = allocateLines(lines, group, status)
231
+ const sent = status !== 'pending' && status !== 'preparing' && status !== 'ready_for_pickup' && status !== 'cancelled'
232
+ const shippedAt = sent ? order.updatedAt : undefined
233
+ const deliveredAt = status === 'delivered' || status === 'picked_up' ? order.completedAt : undefined
234
+ const trackingNumber = isMock && (status === 'shipped' || status === 'delivered')
235
+ ? `THOR-${order.orderNumber}-${group.mode === 'pickup' ? 'P' : 'S'}`
236
+ : undefined
237
+ return {
238
+ id: `${group.id}-fulfillment`,
239
+ groupId: group.id,
240
+ status,
241
+ ...(isMock && status !== 'cancelled' && group.mode === 'shipping'
242
+ ? { carrier: MOCK_TRACKING_CARRIER }
243
+ : {}),
244
+ ...(trackingNumber ? { trackingNumber } : {}),
245
+ ...(shippedAt ? { shippedAt } : {}),
246
+ ...(deliveredAt ? { deliveredAt } : {}),
247
+ packages:
248
+ isMock && sent && group.mode === 'shipping'
249
+ ? [{ id: `${group.id}-package`, label: 'Paquete 1' }]
250
+ : [],
251
+ events:
252
+ isMock && sent
253
+ ? [
254
+ {
255
+ id: `${group.id}-event-confirmed`,
256
+ at: order.createdAt,
257
+ label: 'Pedido confirmado',
258
+ },
259
+ ...(shippedAt
260
+ ? [
261
+ {
262
+ id: `${group.id}-event-shipped`,
263
+ at: shippedAt,
264
+ label: group.mode === 'pickup' ? 'Listo para recoger' : 'En camino',
265
+ },
266
+ ]
267
+ : []),
268
+ ...(deliveredAt
269
+ ? [
270
+ {
271
+ id: `${group.id}-event-delivered`,
272
+ at: deliveredAt,
273
+ label: group.mode === 'pickup' ? 'Recogido' : 'Entregado',
274
+ },
275
+ ]
276
+ : []),
277
+ ]
278
+ : [],
279
+ allocations,
280
+ ...(isMock && group.mode === 'pickup'
281
+ ? {
282
+ pickup: {
283
+ ...MOCK_PICKUP,
284
+ status:
285
+ status === 'picked_up' || status === 'delivered'
286
+ ? ('picked_up' as const)
287
+ : status === 'ready_for_pickup'
288
+ ? ('ready' as const)
289
+ : ('scheduled' as const),
290
+ code: order.orderNumber,
291
+ },
292
+ }
293
+ : {}),
294
+ }
295
+ }
296
+
297
+ function resolveTransactions(
298
+ order: Order,
299
+ total: Money,
300
+ refund: Money,
301
+ isMock: boolean,
302
+ hintPaidAmount = 0,
303
+ ): Transaction[] {
304
+ if (!isMock) {
305
+ // A live provider that reaches this mapper without a transaction contract
306
+ // reports only the aggregate status; no movement is invented.
307
+ return []
308
+ }
309
+ const method = 'card' as const
310
+ const at = order.completedAt ?? order.updatedAt ?? order.createdAt
311
+ const entries: Transaction[] = []
312
+ switch (order.paymentStatus) {
313
+ case 'paid':
314
+ entries.push({
315
+ id: `${order.id}-payment`,
316
+ kind: 'payment',
317
+ status: 'captured',
318
+ amount: total,
319
+ at,
320
+ method,
321
+ })
322
+ break
323
+ case 'partially_refunded':
324
+ entries.push({
325
+ id: `${order.id}-payment`,
326
+ kind: 'payment',
327
+ status: 'captured',
328
+ amount: total,
329
+ at,
330
+ method,
331
+ })
332
+ if (refund.amount > 0) {
333
+ entries.push({
334
+ id: `${order.id}-refund`,
335
+ kind: 'refund',
336
+ status: 'refunded',
337
+ amount: refund,
338
+ at: order.updatedAt,
339
+ method,
340
+ })
341
+ }
342
+ break
343
+ case 'refunded':
344
+ entries.push({
345
+ id: `${order.id}-payment`,
346
+ kind: 'payment',
347
+ status: 'captured',
348
+ amount: total,
349
+ at,
350
+ method,
351
+ })
352
+ entries.push({
353
+ id: `${order.id}-refund`,
354
+ kind: 'refund',
355
+ status: 'refunded',
356
+ amount: total,
357
+ at: order.updatedAt ?? at,
358
+ method,
359
+ })
360
+ break
361
+ case 'authorized':
362
+ entries.push({
363
+ id: `${order.id}-authorization`,
364
+ kind: 'authorization',
365
+ status: 'authorized',
366
+ amount: total,
367
+ at,
368
+ method,
369
+ })
370
+ break
371
+ case 'pending': {
372
+ const paid = isMock && hintPaidAmount > 0
373
+ ? { amount: Math.min(hintPaidAmount, total.amount), currency: total.currency }
374
+ : undefined
375
+ if (paid) {
376
+ entries.push({
377
+ id: `${order.id}-payment`,
378
+ kind: 'payment',
379
+ status: 'captured',
380
+ amount: paid,
381
+ at,
382
+ method,
383
+ })
384
+ entries.push({
385
+ id: `${order.id}-balance`,
386
+ kind: 'payment',
387
+ status: 'pending',
388
+ amount: { amount: total.amount - paid.amount, currency: total.currency },
389
+ at,
390
+ method,
391
+ })
392
+ } else {
393
+ entries.push({
394
+ id: `${order.id}-payment`,
395
+ kind: 'payment',
396
+ status: 'pending',
397
+ amount: total,
398
+ at,
399
+ method,
400
+ })
401
+ }
402
+ break
403
+ }
404
+ }
405
+ return entries
406
+ }
407
+
408
+ type DetailPaymentStatus = 'unpaid' | 'authorized' | 'partially_paid' | 'paid'
409
+ type DetailReturnStatus = 'none' | 'requested' | 'in_progress' | 'completed'
410
+
411
+ function toActionSet(input: {
412
+ commercial: OrderDetailOrder['commercial']
413
+ paymentStatus: DetailPaymentStatus
414
+ logistics: FulfillmentStatus
415
+ returns: DetailReturnStatus
416
+ }): OrderActionId[] {
417
+ const actions: OrderActionId[] = []
418
+ switch (input.commercial) {
419
+ case 'completed':
420
+ actions.push('reorder', 'invoice')
421
+ break
422
+ case 'cancelled':
423
+ actions.push('invoice')
424
+ break
425
+ case 'processing':
426
+ if (input.paymentStatus === 'paid') actions.push('invoice')
427
+ break
428
+ case 'pending':
429
+ actions.push('cancel')
430
+ break
431
+ }
432
+ if (input.paymentStatus === 'unpaid' || input.paymentStatus === 'partially_paid') {
433
+ actions.push('pay-balance')
434
+ }
435
+ if (
436
+ input.logistics === 'shipped' ||
437
+ input.logistics === 'partially_delivered' ||
438
+ input.logistics === 'ready_for_pickup'
439
+ ) {
440
+ actions.push('track')
441
+ }
442
+ if (input.logistics === 'delivered' && input.returns === 'none') {
443
+ actions.push('return', 'exchange')
444
+ }
445
+ if (input.returns === 'requested' || input.returns === 'in_progress') actions.push('problem')
446
+ if (
447
+ input.commercial !== 'completed' &&
448
+ input.commercial !== 'cancelled' &&
449
+ (input.logistics === 'pending' || input.logistics === 'preparing')
450
+ ) {
451
+ actions.push('cancel')
452
+ }
453
+ actions.push('support')
454
+ return [...new Set(actions)]
455
+ }
456
+
457
+ /**
458
+ * Project one universal order into the order-detail snapshot.
459
+ *
460
+ * `orderId` is the requested id; the provider has already enforced ownership.
461
+ * The mapper never changes the order identity or the authoritative total.
462
+ */
463
+ export function toOrderDetailSnapshot(order: Order): OrderDetailSnapshot {
464
+ const currency = order.total.currencyCode
465
+ const hint = readLifecycleHint(order)
466
+ const isMock = order.metadata?.provider === 'mock'
467
+ const orderDiscount = toDetailMoney(order.discount, currency).amount
468
+ const taxAmount = calculateTax(order, currency, orderDiscount)
469
+ const lines = order.items.map((item, index) =>
470
+ toOrderLine(
471
+ item,
472
+ currency,
473
+ hint.partiallyCancelled && index === order.items.length - 1 ? 1 : 0,
474
+ ),
475
+ )
476
+ if (taxAmount > 0 && lines[0]) {
477
+ lines[0].taxes = [
478
+ {
479
+ id: `${order.id}-tax`,
480
+ label: 'Impuestos',
481
+ amount: { amount: taxAmount, currency },
482
+ },
483
+ ]
484
+ // The line total is the authoritative charged amount (taxes included), so
485
+ // the order total reconciles without re-applying tax in the view.
486
+ lines[0].total = {
487
+ amount: lines[0].total.amount + taxAmount,
488
+ currency,
489
+ }
490
+ }
491
+
492
+ const groupSources = resolveGroupSources(order)
493
+ const groups: LogisticsGroup[] = groupSources.map((group) => {
494
+ const fee = toDetailMoney(group.fee, currency)
495
+ return {
496
+ id: group.id,
497
+ mode: group.mode,
498
+ method: { id: `${group.id}-method`, name: group.methodName },
499
+ shippingSubtotal: fee,
500
+ discounts: [],
501
+ taxes: [],
502
+ total: fee,
503
+ ...(group.mode === 'pickup' && isMock
504
+ ? {
505
+ pickup: {
506
+ ...MOCK_PICKUP,
507
+ status: hint.fulfilment === 'ready_for_pickup' ? 'ready' : 'scheduled',
508
+ code: order.orderNumber,
509
+ },
510
+ }
511
+ : {}),
512
+ }
513
+ })
514
+
515
+ const logistics = toFulfillmentStatus(order, hint)
516
+ const fulfillments = groupSources.map((group) => {
517
+ const status =
518
+ groupSources.length > 1 && group.mode === 'pickup' && logistics === 'partially_delivered'
519
+ ? 'preparing'
520
+ : logistics
521
+ return toFulfillment(order, group, status, lines, isMock)
522
+ })
523
+
524
+ const refund =
525
+ hint.refundAmount !== undefined
526
+ ? toDetailMoney({ amount: String(hint.refundAmount), currencyCode: currency }, currency)
527
+ : toDetailMoney(order.discount, currency)
528
+ const hintPaid = hint.paidAmount !== undefined
529
+ ? Math.round(hint.paidAmount * 10 ** currencyDigits(currency))
530
+ : 0
531
+ const transactions = resolveTransactions(
532
+ order,
533
+ toDetailMoney(order.total, currency),
534
+ refund,
535
+ isMock,
536
+ hintPaid,
537
+ )
538
+
539
+ const cases: AfterSalesCase[] =
540
+ hint.returns && hint.returns !== 'none'
541
+ ? [
542
+ {
543
+ id: `${order.id}-return`,
544
+ type: 'return',
545
+ status:
546
+ hint.returns === 'requested'
547
+ ? 'requested'
548
+ : hint.returns === 'in_progress'
549
+ ? 'in_transit'
550
+ : 'completed',
551
+ createdAt: order.updatedAt,
552
+ reason: 'Solicitud de devolución del cliente',
553
+ lines: lines.map((line) => ({
554
+ lineId: line.id,
555
+ quantity: Math.max(0, line.quantity - line.cancelledQuantity),
556
+ })),
557
+ ...(hint.returns === 'completed' ? { refund } : {}),
558
+ availableActions: [],
559
+ },
560
+ ]
561
+ : order.fulfillmentStatus === 'returned'
562
+ ? [
563
+ {
564
+ id: `${order.id}-return`,
565
+ type: 'return',
566
+ status: 'completed',
567
+ createdAt: order.updatedAt,
568
+ reason: 'Devolución completada',
569
+ lines: lines.map((line) => ({
570
+ lineId: line.id,
571
+ quantity: Math.max(0, line.quantity - line.cancelledQuantity),
572
+ })),
573
+ refund: toDetailMoney(order.total, currency),
574
+ availableActions: [],
575
+ },
576
+ ]
577
+ : []
578
+
579
+ const paymentStatus: DetailPaymentStatus =
580
+ hint.payment ??
581
+ (order.paymentStatus === 'pending'
582
+ ? 'unpaid'
583
+ : order.paymentStatus === 'authorized'
584
+ ? 'authorized'
585
+ : 'paid')
586
+ const returns: DetailReturnStatus =
587
+ hint.returns ?? (order.fulfillmentStatus === 'returned' ? 'completed' : 'none')
588
+ const commercial = toCommercial(order)
589
+ const adjustments: Adjustment[] =
590
+ orderDiscount > 0
591
+ ? [
592
+ {
593
+ id: `${order.id}-discount`,
594
+ label: 'Descuento',
595
+ scope: 'order',
596
+ direction: 'discount',
597
+ amount: { amount: orderDiscount, currency },
598
+ source: 'manual',
599
+ },
600
+ ]
601
+ : []
602
+
603
+ const subtotal = toDetailMoney(order.subtotal, currency)
604
+ const shipping = toDetailMoney(order.shipping, currency)
605
+ const total = toDetailMoney(order.total, currency)
606
+
607
+ const shippingAddress = toDetailAddress(order.shippingAddress)
608
+ const billingAddress = toDetailAddress(order.billingAddress)
609
+ const detail: OrderDetailOrder = {
610
+ id: order.id,
611
+ number: order.orderNumber,
612
+ createdAt: order.createdAt,
613
+ updatedAt: order.updatedAt,
614
+ currency,
615
+ commercial,
616
+ logistics: { status: logistics, ...(hint.fulfilment === 'delayed' ? { delayed: true } : {}) },
617
+ ...(shippingAddress ? { shippingAddress } : {}),
618
+ ...(billingAddress ? { billingAddress } : {}),
619
+ lines,
620
+ groups,
621
+ fulfillments,
622
+ promotions: [],
623
+ adjustments,
624
+ transactions,
625
+ cases,
626
+ documents: [],
627
+ revisions: [],
628
+ totals: {
629
+ itemsSubtotal: subtotal,
630
+ itemDiscounts: zero(currency),
631
+ orderDiscounts: { amount: orderDiscount, currency },
632
+ shippingSubtotal: shipping,
633
+ shippingDiscounts: zero(currency),
634
+ tax: { amount: taxAmount, currency },
635
+ adjustments: zero(currency),
636
+ total,
637
+ },
638
+ availableActions: toActionSet({ commercial, paymentStatus, logistics, returns }),
639
+ }
640
+
641
+ return { order: detail }
642
+ }
@@ -0,0 +1,25 @@
1
+ import { PortError } from '@thorprovider/blocks/ports'
2
+ import type { OrderDetailPort } from '@thorprovider/blocks/ports'
3
+
4
+ export type OrderDetailRunner = OrderDetailPort['get']
5
+
6
+ /**
7
+ * Host seam for the order-detail route. The backend contract lives in
8
+ * `STOREFRONT_BACKEND_WIRING/components/order-detail.md`. The generated host
9
+ * injects its ownership-scoped runner (`loadOrderDetailAction`): mock mode
10
+ * serves the same customer-owned order store as the history, while a live
11
+ * provider without a detail endpoint fails closed through that runner. With no
12
+ * runner at all the port throws the same typed `unavailable` error, so the
13
+ * surface renders its own error state and never synthesizes an order.
14
+ */
15
+ export function createOrderDetailPort(run?: OrderDetailRunner): OrderDetailPort {
16
+ return {
17
+ async get(orderId, options) {
18
+ if (run) return run(orderId, options)
19
+ throw new PortError(
20
+ 'unavailable',
21
+ `Order detail is not connected to the backend yet (requested ${orderId}).`,
22
+ )
23
+ },
24
+ }
25
+ }
@@ -0,0 +1,30 @@
1
+ import { PortError } from '@thorprovider/blocks/ports'
2
+ import type { OrdersPort } from '@thorprovider/blocks/ports'
3
+
4
+ import { listOrdersQueryPageAction } from './actions'
5
+
6
+ export type OrdersQueryRunner = OrdersPort['list']
7
+
8
+ /**
9
+ * Host seam for the advanced order-history query, which is the default
10
+ * `account.orders` surface.
11
+ *
12
+ * The default runner is the `listOrdersQueryPageAction` Server Action: the
13
+ * customer token never reaches the client, and the request-scoped runtime read
14
+ * serves both mock mode (`THOR_DATA_SOURCE=mock`, the seeded demo account) and a
15
+ * Medusa backend. The block owns the query UI; the action owns the data read.
16
+ *
17
+ * A Server Action cannot be cancelled, so `options.signal` only tells the block
18
+ * to discard a superseded result; the read itself completes. The `run` override
19
+ * stays for a host that wants to inject its own runner through the same factory.
20
+ */
21
+ export function createOrdersPort(run?: OrdersQueryRunner): OrdersPort {
22
+ return {
23
+ async list(query, options) {
24
+ if (run) return run(query, options)
25
+ const result = await listOrdersQueryPageAction(query)
26
+ if (!result.ok) throw new PortError('unavailable', result.error)
27
+ return result.page
28
+ },
29
+ }
30
+ }