@thorprovider/storefront 0.10.0 → 0.12.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 (39) hide show
  1. package/README.md +22 -11
  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 +73 -11
  6. package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +18 -2
  7. package/assets/templates/app/lib/__STOREFRONT__/confirmation.core.ts +38 -3
  8. package/assets/templates/app/lib/__STOREFRONT__/footer-content.ts +203 -0
  9. package/assets/templates/app/lib/__STOREFRONT__/order-detail-aftersales.ts +55 -0
  10. package/assets/templates/app/lib/__STOREFRONT__/order-detail-capabilities.ts +79 -0
  11. package/assets/templates/app/lib/__STOREFRONT__/order-detail-mapper.ts +13 -2
  12. package/assets/templates/app/lib/__STOREFRONT__/order-detail-money.ts +39 -0
  13. package/assets/templates/app/lib/__STOREFRONT__/order-detail-reorder.ts +62 -0
  14. package/assets/templates/app/lib/__STOREFRONT__/registry.tsx +8 -24
  15. package/assets/templates/app/lib/__STOREFRONT__/schema.ts +5 -3
  16. package/assets/templates/app/lib/__STOREFRONT__/shell/content.ts +14 -13
  17. package/assets/templates/app/lib/__STOREFRONT__/shell/props.ts +7 -2
  18. package/assets/templates/views/account/assembly/index.skeleton.tsx +3 -0
  19. package/assets/templates/views/account/assembly/registry.skeleton.tsx +115 -4
  20. package/assets/templates/views/account/content.ts +6 -0
  21. package/assets/templates/views/account/index.tsx +3 -0
  22. package/assets/templates/views/account/order-detail-flows.defaults.ts +106 -0
  23. package/assets/templates/views/account/order-detail-invoice.ts +136 -0
  24. package/assets/templates/views/account/order-detail-sheet.tsx +100 -0
  25. package/assets/templates/views/account/order-detail-sheets.tsx +122 -0
  26. package/assets/templates/views/account/order-detail.client.tsx +401 -1
  27. package/assets/templates/views/account/registry.tsx +115 -4
  28. package/assets/templates/views/account/schema.ts +2 -0
  29. package/assets/templates/views/home/content.ts +3 -1
  30. package/assets/templates/views/product/data.ts +13 -6
  31. package/assets/templates/views/product/index.tsx +3 -3
  32. package/bin/storefront.js +59 -23
  33. package/package.json +1 -1
  34. package/scripts/candidate.mjs +8 -4
  35. package/scripts/file-classes.mjs +3 -0
  36. package/scripts/mock-capabilities.mjs +22 -0
  37. package/scripts/reconcile.mjs +5 -2
  38. package/scripts/render-templates.mjs +126 -43
  39. package/scripts/scaffold-env.mjs +48 -0
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
@@ -469,12 +472,20 @@ The shell's derived `spec/index.ts` imports the user-owned `shell/props.ts`
469
472
  surface and footer copy are configured without touching derived files. Configure
470
473
  `shell/content.ts` (`logoAccent`/`brandAccent`, `navbarClassName`/`footerClassName`,
471
474
  `brandDescription`, `linkColumns`); defaults are neutral and link only to served routes
472
- (`/`, `/categories`, `/checkout`), never dead `#` links. `newsletter` defaults to `false`
473
- and the scaffold ships no submit callback, so a content-only newsletter renders no form
474
- — never a fake form. `shippingNote` defaults to `''`: while it is empty (and there are
475
- no utility links) the navbar renders no utility strip, so no placeholder note is shown.
476
- The generated footer uses canonical `FooterSection` with `brand-columns` and
477
- native link behavior; numbered footer adapters are no longer part of the Blocks API.
475
+ (`/`, `/categories`, `/checkout`), never dead `#` links. `shippingNote` defaults to `''`:
476
+ while it is empty (and there are no utility links) the navbar renders no utility strip,
477
+ so no placeholder note is shown.
478
+
479
+ The generated footer **is** the `UniversalFooter` design block, rendered in its `commerce`
480
+ preset. Its own copy — newsletter, contact, payments, legal, region — comes from
481
+ `lib/<name>/footer-content.ts`, whose Zod schema is also the response contract of
482
+ `GET /store/footer`: a backend that owns the footer serves that shape and the shell drops
483
+ its defaults. Until then, override individual keys with `footerContent` in
484
+ `shell/content.ts`; the full contract and its wiring live in
485
+ `docs/footer-content-endpoint.md`. The scaffold ships no subscribe callback, so the newsletter form renders
486
+ disabled rather than faking a subscription, and no app-store listing or QR image is
487
+ invented (the app band hides itself while `apps.links` is empty). Navigation stays
488
+ derived from `linkColumns`, so the footer cannot drift from the rest of the chrome.
478
489
 
479
490
  A view's derived `index.tsx` imports the user-owned `content.ts`/`props.ts`/
480
491
  `data.ts`, so a customization changes real spec/loader output and survives `sync`.
@@ -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,
@@ -94,6 +95,7 @@ import {
94
95
  } from './session'
95
96
  import type { AccountProfileMetadataPatch, AccountProfilePayload } from './account-profile'
96
97
  import { toOrderDetailSnapshot } from './order-detail-mapper'
98
+ import { toReorderLines, type ReorderOrderResult } from './order-detail-reorder'
97
99
 
98
100
  // A `'use server'` module may export ONLY async functions. Next/Turbopack's
99
101
  // server-actions transform registers every export as a runtime server
@@ -437,6 +439,53 @@ export async function addToCartByHandleAction(input: {
437
439
  }
438
440
  }
439
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
+
440
489
  /** Set a backend cart line to an ABSOLUTE quantity by its line-item id. */
441
490
  export async function setLineQuantityAction(input: {
442
491
  lineId: string
@@ -1137,7 +1186,11 @@ async function clearConfirmedSession(
1137
1186
  * a committed order as a retryable failure.
1138
1187
  */
1139
1188
  export async function placeOrderAction(
1140
- input: { shippingGroups?: ShippingGroupSelection[]; paymentMethodId?: string } = {},
1189
+ input: {
1190
+ shippingGroups?: ShippingGroupSelection[]
1191
+ paymentMethodId?: string
1192
+ payments?: CheckoutPaymentPlanItem[]
1193
+ } = {},
1141
1194
  ): Promise<PlaceOrderResult> {
1142
1195
  try {
1143
1196
  const { cartId, context, provider, customerId } = await ensureActiveCartId({
@@ -1151,9 +1204,13 @@ export async function placeOrderAction(
1151
1204
  }
1152
1205
  }
1153
1206
 
1207
+ const paymentPlan =
1208
+ Array.isArray(input.payments) && input.payments.length > 0
1209
+ ? input.payments
1210
+ : undefined
1154
1211
  const paymentMethodId =
1155
1212
  typeof input.paymentMethodId === 'string' ? input.paymentMethodId.trim() : ''
1156
- if (!paymentMethodId) {
1213
+ if (!paymentPlan && !paymentMethodId) {
1157
1214
  return {
1158
1215
  status: 'error',
1159
1216
  message: 'Selecciona un método de pago antes de confirmar.',
@@ -1186,21 +1243,26 @@ export async function placeOrderAction(
1186
1243
  }
1187
1244
  }
1188
1245
  }
1189
- try {
1190
- await applyPayment(cartId, paymentMethodId, context, provider)
1191
- } catch (error) {
1192
- logServerError('applyPayment', error)
1193
- return {
1194
- status: 'error',
1195
- message: toError(error, 'No se pudo iniciar el pago.'),
1196
- 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
+ }
1197
1259
  }
1198
1260
  }
1199
1261
  // Thread the request's customer token (design D11) so an authenticated
1200
1262
  // checkout is attributed to the session customer; guests complete the same
1201
1263
  // tokenless provider as before.
1202
1264
  const customerToken = await readAuthToken(context)
1203
- const result = await completeOrder(cartId, context, customerToken)
1265
+ const result = await completeOrder(cartId, context, customerToken, paymentPlan)
1204
1266
  if (result.status !== 'order') return result
1205
1267
  if (!(await clearConfirmedSession(context, cartId))) {
1206
1268
  return {
@@ -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,
@@ -148,6 +150,7 @@ export type PlaceOrderResult =
148
150
  order: StorefrontOrder
149
151
  lines: StorefrontOrderLineView[]
150
152
  confirmation: StorefrontConfirmation
153
+ paymentSummary?: CheckoutPaymentSummary
151
154
  }
152
155
  | { status: 'error'; message: string; code?: string }
153
156
  | { status: 'cart-error'; message: string; code?: string }
@@ -299,6 +302,7 @@ export function toPlaceOrderResult(result: CartCompletionResult): PlaceOrderResu
299
302
  order: toStorefrontOrder(result.order),
300
303
  lines: toOrderLines(result.order),
301
304
  confirmation: toStorefrontConfirmation(result.order),
305
+ ...(result.paymentSummary ? { paymentSummary: result.paymentSummary } : {}),
302
306
  }
303
307
  }
304
308
  if (result.type === 'cart') {
@@ -643,6 +647,7 @@ export async function completeOrder(
643
647
  cartId: string,
644
648
  context: StoreContext = getStoreContext(),
645
649
  customerToken?: string | null,
650
+ payments?: CheckoutPaymentPlanItem[],
646
651
  ): Promise<PlaceOrderResult> {
647
652
  assertBackendConfigured()
648
653
  // The host owns the auth cookie and threads the request's customer token
@@ -650,7 +655,12 @@ export async function completeOrder(
650
655
  // customer (mock) or links it server-side (Medusa). A tokenless completion
651
656
  // builds exactly the provider the previous token-blind default built.
652
657
  return toPlaceOrderResult(
653
- await completeCart(cartId, context, getCommerceClientWithToken(customerToken ?? null)),
658
+ await completeCart(
659
+ cartId,
660
+ context,
661
+ getCommerceClientWithToken(customerToken ?? null),
662
+ payments,
663
+ ),
654
664
  )
655
665
  }
656
666
 
@@ -664,10 +674,16 @@ export async function reconcileOrder(
664
674
  cartId: string,
665
675
  context: StoreContext = getStoreContext(),
666
676
  customerToken?: string | null,
677
+ payments?: CheckoutPaymentPlanItem[],
667
678
  ): Promise<PlaceOrderResult> {
668
679
  assertBackendConfigured()
669
680
  return toPlaceOrderResult(
670
- await reconcileCart(cartId, context, getCommerceClientWithToken(customerToken ?? null)),
681
+ await reconcileCart(
682
+ cartId,
683
+ context,
684
+ getCommerceClientWithToken(customerToken ?? null),
685
+ payments,
686
+ ),
671
687
  )
672
688
  }
673
689
 
@@ -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,203 @@
1
+ // Footer content: the data contract behind the site footer, plus the neutral
2
+ // defaults a fresh storefront ships with.
3
+ //
4
+ // `UniversalFooter` (the footer block) renders `data`, and the shell supplies it.
5
+ // The shape below is the whole contract, so a backend can serve it as-is:
6
+ //
7
+ // GET /store/footer
8
+ // 200 application/json → { ...footerContentSchema }
9
+ //
10
+ // Nothing here performs a request. The generated storefront reads the defaults
11
+ // in this file at build time; replacing them with a `GET /store/footer` read is
12
+ // a one-file change in `shell/props.ts` (see `footerContentEndpoint`), and does
13
+ // not touch the block, the registry, or the shell schema.
14
+ //
15
+ // Defaults are neutral on purpose: no delivery, shipping, or promo promise, no
16
+ // invented social account, no fake app store listing. Phone, address, payment
17
+ // methods and app links are placeholders a merchant must replace.
18
+
19
+ import { z } from 'zod'
20
+ import type { UniversalFooterProps } from '@thorprovider/blocks'
21
+
22
+ export const footerContentSchema = z.object({
23
+ /** Footer navigation, grouped. Derived from `shell/content.ts` link columns by default. */
24
+ nav: z.array(
25
+ z.object({
26
+ title: z.string(),
27
+ links: z.array(z.object({ label: z.string(), href: z.string() })),
28
+ }),
29
+ ),
30
+ /** Accessible label for the navigation region. */
31
+ navLabel: z.string(),
32
+ newsletter: z.object({
33
+ title: z.string(),
34
+ description: z.string(),
35
+ fieldLabel: z.string(),
36
+ placeholder: z.string(),
37
+ buttonLabel: z.string(),
38
+ /** Feedback copy for a successful subscription. */
39
+ success: z.string(),
40
+ /** Feedback copy for a failed subscription. */
41
+ error: z.string(),
42
+ }),
43
+ contact: z.object({
44
+ title: z.string(),
45
+ email: z.string(),
46
+ phone: z.string(),
47
+ address: z.string(),
48
+ hours: z.string(),
49
+ }),
50
+ apps: z.object({
51
+ available: z.boolean(),
52
+ title: z.string(),
53
+ description: z.string(),
54
+ eyebrow: z.string(),
55
+ /** Short glyph shown beside the app invitation. */
56
+ mark: z.string(),
57
+ qr: z.object({ src: z.string(), alt: z.string(), fallback: z.string() }),
58
+ links: z.array(z.object({ label: z.string(), href: z.string(), caption: z.string() })),
59
+ }),
60
+ payments: z.object({ title: z.string(), methods: z.array(z.string()) }),
61
+ legal: z.object({
62
+ company: z.string(),
63
+ title: z.string(),
64
+ copyright: z.string(),
65
+ links: z.array(z.object({ label: z.string(), href: z.string() })),
66
+ }),
67
+ region: z.object({
68
+ label: z.string(),
69
+ languageLabel: z.string(),
70
+ countryLabel: z.string(),
71
+ currencyLabel: z.string(),
72
+ /** Human-readable summary of the active selection (e.g. `Español · Uruguay · UYU`). */
73
+ active: z.string(),
74
+ languages: z.array(z.object({ value: z.string(), label: z.string() })),
75
+ countries: z.array(z.object({ value: z.string(), label: z.string() })),
76
+ currencies: z.array(z.object({ value: z.string(), label: z.string() })),
77
+ }),
78
+ })
79
+
80
+ export type FooterContent = z.infer<typeof footerContentSchema>
81
+
82
+ /** The endpoint a backend implements to own the footer; the shape is the schema above. */
83
+ export const footerContentEndpoint = {
84
+ method: 'GET',
85
+ path: '/store/footer',
86
+ /** Every field is required; partial responses are rejected by the shell schema. */
87
+ response: 'FooterContent',
88
+ } as const
89
+
90
+ /**
91
+ * Default footer content: complete enough to render the commerce footer in a
92
+ * fresh storefront (apps band, newsletter, contact, payments, legal, region).
93
+ * Placeholder values are marked; a merchant replaces them.
94
+ */
95
+ export const footerContentDefaults: FooterContent = {
96
+ // Navigation comes from the shell's link columns; a backend response carries its own.
97
+ nav: [],
98
+ navLabel: 'Navegación del sitio',
99
+ newsletter: {
100
+ title: 'Novedades del catálogo',
101
+ description: 'Productos nuevos y reposiciones, una vez al mes.',
102
+ fieldLabel: 'Correo electrónico',
103
+ placeholder: 'tu@email.com',
104
+ buttonLabel: 'Suscribirme',
105
+ success: 'Listo. Te escribimos cuando haya novedades.',
106
+ error: 'No pudimos suscribirte. Probá de nuevo.',
107
+ },
108
+ contact: {
109
+ title: 'Contacto',
110
+ email: 'hola@example.com',
111
+ phone: '+00 0000 0000',
112
+ address: 'Dirección a definir',
113
+ hours: 'Lunes a viernes, 10:00 a 18:00',
114
+ },
115
+ apps: {
116
+ available: true,
117
+ title: 'Tu catálogo, siempre a mano.',
118
+ description: 'Seguí tus pedidos y mirá las novedades desde el teléfono.',
119
+ eyebrow: 'EN TU TELÉFONO',
120
+ mark: 'S',
121
+ // No QR and no store listing is shipped: a QR image would be a binary asset
122
+ // the scaffold does not own, and invented store URLs would dead-end.
123
+ qr: { src: '', alt: 'Código QR de la aplicación', fallback: '' },
124
+ links: [],
125
+ },
126
+ payments: {
127
+ title: 'Medios de pago',
128
+ methods: ['Tarjeta de crédito', 'Tarjeta de débito', 'Transferencia'],
129
+ },
130
+ legal: {
131
+ company: 'Nombre de la empresa',
132
+ title: 'Legal',
133
+ copyright: 'Todos los derechos reservados.',
134
+ links: [
135
+ { label: 'Términos', href: '/terms' },
136
+ { label: 'Privacidad', href: '/privacy' },
137
+ ],
138
+ },
139
+ region: {
140
+ label: 'Idioma y región',
141
+ languageLabel: 'Idioma',
142
+ countryLabel: 'País',
143
+ currencyLabel: 'Moneda',
144
+ active: 'Español',
145
+ languages: [{ value: 'es', label: 'Español' }],
146
+ countries: [{ value: 'uy', label: 'Uruguay' }],
147
+ currencies: [{ value: 'uyu', label: 'UYU' }],
148
+ },
149
+ }
150
+
151
+ /**
152
+ * Footer navigation from the user-owned shell link columns, so the footer and the
153
+ * rest of the shell never carry two competing link lists. Entries without an
154
+ * `href` are labels, not links, and are dropped.
155
+ */
156
+ export function navFromLinkColumns(
157
+ columns: { title: string; links: { label: string; href?: string }[] }[],
158
+ ): FooterContent['nav'] {
159
+ return columns
160
+ .map((column) => ({
161
+ title: column.title,
162
+ links: column.links
163
+ .filter((link): link is { label: string; href: string } => typeof link.href === 'string')
164
+ .map(({ label, href }) => ({ label, href })),
165
+ }))
166
+ .filter((column) => column.links.length > 0)
167
+ }
168
+
169
+ /** The shell props `UniversalFooter` needs, mirroring `footerPropsSchema`. */
170
+ export interface FooterShellProps {
171
+ brandName: string
172
+ brandAccent?: { text: string; className?: string }
173
+ brandDescription?: string
174
+ linkColumns: { title: string; links: { label: string; href?: string }[] }[]
175
+ className?: string
176
+ footerContent?: FooterContent
177
+ }
178
+
179
+ /**
180
+ * Map the shell seam onto the footer block. The commerce preset is fixed: this
181
+ * is the storefront shell footer, not a chooser. Link columns stay authoritative
182
+ * for navigation so the footer and the rest of the chrome cannot drift apart;
183
+ * `footerContent.nav` is the backend-owned fallback for a shell that ships none.
184
+ */
185
+ export function toUniversalFooterProps(shell: FooterShellProps): UniversalFooterProps {
186
+ const content = shell.footerContent ?? footerContentDefaults
187
+ return {
188
+ data: {
189
+ niche: 'commerce',
190
+ navLabel: content.navLabel,
191
+ brand: { name: shell.brandName, description: shell.brandDescription ?? '' },
192
+ nav: shell.linkColumns.length ? navFromLinkColumns(shell.linkColumns) : content.nav,
193
+ newsletter: content.newsletter,
194
+ contact: content.contact,
195
+ apps: content.apps,
196
+ payments: content.payments,
197
+ legal: content.legal,
198
+ region: content.region,
199
+ },
200
+ brandAccent: shell.brandAccent,
201
+ className: shell.className,
202
+ }
203
+ }
@@ -0,0 +1,55 @@
1
+ import type { AfterSalesLine } from '@thorprovider/blocks'
2
+
3
+ import { fromMinor } from './order-detail-money'
4
+ import type { OrderDetailOrder } from '@thorprovider/blocks/ports'
5
+
6
+ const DELIVERED_STATUSES = new Set(['delivered', 'partially_delivered'])
7
+ const RETURNED_STATUSES = new Set(['requested', 'approved', 'in_transit', 'received', 'completed'])
8
+
9
+ /**
10
+ * Project the order snapshot into the lines the after-sales flow may offer.
11
+ *
12
+ * `delivered` comes from the fulfilment allocations the backend reported;
13
+ * `returnable` subtracts units already in a live return case, so the flow can
14
+ * never ask for more than the shopper still holds. Rejected cases release their
15
+ * units again. Both numbers are computed here, never in the block.
16
+ */
17
+ export function toAfterSalesLines(order: OrderDetailOrder): AfterSalesLine[] {
18
+ const returned = new Map<string, number>()
19
+ for (const entry of order.cases ?? []) {
20
+ if (entry.type !== 'return' || !RETURNED_STATUSES.has(entry.status)) continue
21
+ for (const line of entry.lines) {
22
+ returned.set(line.lineId, (returned.get(line.lineId) ?? 0) + line.quantity)
23
+ }
24
+ }
25
+
26
+ const delivered = new Map<string, number>()
27
+ for (const fulfillment of order.fulfillments ?? []) {
28
+ if (!DELIVERED_STATUSES.has(fulfillment.status)) continue
29
+ for (const allocation of fulfillment.allocations) {
30
+ delivered.set(
31
+ allocation.lineId,
32
+ (delivered.get(allocation.lineId) ?? 0) + allocation.quantity,
33
+ )
34
+ }
35
+ }
36
+
37
+ return (order.lines ?? []).map((line) => {
38
+ const deliveredQuantity = delivered.get(line.id) ?? 0
39
+ const returnable = Math.max(0, deliveredQuantity - (returned.get(line.id) ?? 0))
40
+ return {
41
+ id: line.id,
42
+ name: line.name,
43
+ ...(line.sku ? { sku: line.sku } : {}),
44
+ ...(line.image ? { image: line.image } : {}),
45
+ // The block speaks the canonical decimal `Money`; the snapshot speaks
46
+ // integer minor units.
47
+ unitPrice: {
48
+ amount: fromMinor(line.unitPrice.applied.amount, line.unitPrice.applied.currency),
49
+ currencyCode: line.unitPrice.applied.currency,
50
+ },
51
+ delivered: deliveredQuantity,
52
+ returnable,
53
+ }
54
+ })
55
+ }