@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
@@ -0,0 +1,145 @@
1
+ // Generated from the fulfillment-evidence-gallery delivery copy
2
+ // (designs/fulfillment-evidence-gallery/data.ts). The route is host-owned; the
3
+ // block never reads the delivery data module. Serial numbers, downloads and zoom
4
+ // stay opt-in, matching the storefront-safe defaults.
5
+ import type { FulfillmentEvidenceGalleryProps } from '@thorprovider/blocks'
6
+
7
+ export const fulfillmentEvidenceLabels = {
8
+ "titles": {
9
+ "shipping": "Evidencias de tu entrega",
10
+ "pickup": "Evidencias de tu recogida",
11
+ "generic": "Evidencias del pedido"
12
+ },
13
+ "summary": {
14
+ "files": "{count} archivos disponibles",
15
+ "fileOne": "1 archivo disponible",
16
+ "view": "Ver evidencias",
17
+ "viewAll": "Ver todas",
18
+ "empty": "Todavía no hay evidencias"
19
+ },
20
+ "categories": {
21
+ "product_preparation": "Productos preparados",
22
+ "package_preparation": "Paquete preparado",
23
+ "delivery": "Entrega realizada",
24
+ "pickup": "Recogida realizada",
25
+ "shipment": "Envío",
26
+ "other": "Otras evidencias"
27
+ },
28
+ "categoryHints": {
29
+ "product_preparation": "Qué se preparó para tu pedido, unidad por unidad.",
30
+ "package_preparation": "Cómo se embaló cada paquete antes de salir del almacén.",
31
+ "delivery": "Prueba de entrega registrada por la operación logística.",
32
+ "pickup": "Evidencias de la entrega en el punto de recogida.",
33
+ "shipment": "Evidencias del paso por el almacén y la salida del envío.",
34
+ "other": "Otras evidencias autorizadas para tu pedido."
35
+ },
36
+ "mediaTypes": {
37
+ "image": "Fotografía",
38
+ "pdf": "Documento",
39
+ "video": "Vídeo"
40
+ },
41
+ "product": {
42
+ "prepared": "Producto",
43
+ "quantity": "{count} uds. preparadas",
44
+ "variant": "Variante",
45
+ "sku": "SKU",
46
+ "serial": "Número de serie",
47
+ "units": "Unidades preparadas",
48
+ "allUnits": "Todas",
49
+ "unit": "Unidad {index}",
50
+ "noEvidence": "No hay fotografías de esta unidad."
51
+ },
52
+ "package": {
53
+ "title": "Paquete",
54
+ "reference": "Referencia",
55
+ "preparedAt": "Preparado el",
56
+ "files": "{count} archivos"
57
+ },
58
+ "delivery": {
59
+ "confirmed": "Entrega confirmada",
60
+ "notConfirmed": "Entrega sin confirmar",
61
+ "deliveredAt": "Entregada el",
62
+ "reference": "Envío"
63
+ },
64
+ "pickup": {
65
+ "confirmed": "Recogida confirmada",
66
+ "notConfirmed": "Recogida sin confirmar",
67
+ "pickedUpAt": "Recogida el",
68
+ "reference": "Recogida"
69
+ },
70
+ "fulfillment": {
71
+ "method": {
72
+ "shipping": "Envío",
73
+ "pickup": "Recogida"
74
+ },
75
+ "status": {
76
+ "pending": "Pendiente",
77
+ "preparing": "En preparación",
78
+ "ready": "Listo",
79
+ "shipped": "Enviado",
80
+ "delivered": "Entregado",
81
+ "picked_up": "Recogido",
82
+ "cancelled": "Cancelado"
83
+ }
84
+ },
85
+ "viewer": {
86
+ "title": "Evidencias",
87
+ "close": "Cerrar",
88
+ "previous": "Anterior",
89
+ "next": "Siguiente",
90
+ "zoomIn": "Ampliar",
91
+ "zoomOut": "Ajustar",
92
+ "download": "Descargar",
93
+ "counter": "{index} de {total}",
94
+ "loading": "Cargando archivo…",
95
+ "unavailable": "Este archivo no está disponible en este momento.",
96
+ "forbidden": "No tienes acceso a este archivo.",
97
+ "revoked": "Esta evidencia se ha retirado.",
98
+ "retry": "Reintentar",
99
+ "openDocument": "Abrir documento",
100
+ "thumbnails": "Evidencias disponibles",
101
+ "goTo": "Ver evidencia {index}",
102
+ "open": "Abrir evidencia",
103
+ "type": "Tipo",
104
+ "product": "Producto",
105
+ "package": "Paquete",
106
+ "fulfillment": "Operación"
107
+ },
108
+ "states": {
109
+ "loading": "Cargando evidencias",
110
+ "emptyTitle": "Todavía no hay evidencias",
111
+ "emptyBody": "Cuando el pedido tenga fotografías de preparación, embalaje, entrega o recogida, aparecerán aquí.",
112
+ "errorTitle": "No pudimos cargar las evidencias",
113
+ "errorBody": "El servicio de evidencias no respondió. Puedes intentarlo de nuevo.",
114
+ "retry": "Reintentar",
115
+ "forbiddenTitle": "Evidencias no disponibles",
116
+ "forbiddenBody": "Tu cuenta no tiene acceso a las evidencias de esta entrega.",
117
+ "notFoundTitle": "Entrega no encontrada",
118
+ "notFoundBody": "Esta entrega no existe o ya no está disponible para tu cuenta.",
119
+ "partialTitle": "Algunas evidencias no se cargaron",
120
+ "restrictedTitle": "Algunas evidencias no están publicadas para tu cuenta",
121
+ "assetError": "Vista previa no disponible",
122
+ "retryAsset": "Reintentar",
123
+ "noEvidence": "Sin fotografías"
124
+ },
125
+ "dates": {
126
+ "captured": "Registrada",
127
+ "prepared": "Preparado"
128
+ }
129
+ } as const satisfies FulfillmentEvidenceGalleryProps['labels']
130
+
131
+ export const fulfillmentEvidenceCapabilities = {
132
+ showSerialNumbers: false,
133
+ allowDownloads: false,
134
+ allowZoom: false,
135
+ } as const satisfies NonNullable<FulfillmentEvidenceGalleryProps['capabilities']>
136
+
137
+ export const fulfillmentEvidencePresentation = {
138
+ mode: 'expanded',
139
+ } as const satisfies NonNullable<FulfillmentEvidenceGalleryProps['presentation']>
140
+
141
+ export const fulfillmentEvidenceDefaults = {
142
+ labels: fulfillmentEvidenceLabels,
143
+ capabilities: fulfillmentEvidenceCapabilities,
144
+ presentation: fulfillmentEvidencePresentation,
145
+ }
@@ -0,0 +1,15 @@
1
+ // Derived schema for the route-only fulfillment-evidence element. Kept in its
2
+ // own file so an existing store receives it through `storefront sync`; the
3
+ // account `schema.ts` stays user-owned and is never rewritten.
4
+ import { z } from 'zod'
5
+
6
+ export const accountFulfillmentEvidencePropsSchema = z.object({
7
+ fulfillmentId: z.string().min(1),
8
+ labels: z.record(z.string(), z.unknown()),
9
+ capabilities: z.record(z.string(), z.boolean()).optional(),
10
+ presentation: z.record(z.string(), z.unknown()).optional(),
11
+ })
12
+
13
+ export type AccountFulfillmentEvidenceProps = z.infer<
14
+ typeof accountFulfillmentEvidencePropsSchema
15
+ >
@@ -24,6 +24,8 @@ import { registry } from './registry'
24
24
  import { sectionData } from './sections-data'
25
25
  import { accountContent } from './content'
26
26
  import { orderDetailDefaults } from './order-detail.defaults'
27
+ import { orderDetailFlowLabels, orderDetailSupport } from './order-detail-flows.defaults'
28
+ import { fulfillmentEvidenceDefaults } from './fulfillment-evidence.defaults'
27
29
  import { accountOrdersAdvancedDefaults } from './orders-advanced.defaults'
28
30
  import {
29
31
  accountAddressPropsSchema,
@@ -36,6 +38,7 @@ import {
36
38
  accountProfilePropsSchema,
37
39
  accountRegisterPropsSchema,
38
40
  } from './schema'
41
+ import { accountFulfillmentEvidencePropsSchema } from './fulfillment-evidence.schema'
39
42
  import { customerProfileDefaults } from './customer-profile.defaults'
40
43
  import { customerProfilePropsSchema } from '../sections/schema.customer-profile'
41
44
  import { addressBookAdvancedDefaults } from './address-book-advanced.defaults'
@@ -57,13 +60,27 @@ const elements: Record<string, StorefrontElement> = {
57
60
  props: {
58
61
  orderId: { $state: '/orderDetailId' },
59
62
  ...orderDetailDefaults,
63
+ supportHref: orderDetailSupport.href,
64
+ flows: orderDetailFlowLabels,
60
65
  },
61
66
  },
67
+ // Headless account boundary. It is fixed infrastructure, not a selectable
68
+ // slot, so a generated store's normalized composition cannot drop it and
69
+ // leave every account route referencing a missing element.
62
70
  'account.boot': {
63
71
  type: 'AccountBoot',
64
72
  props: {},
65
73
  on: { retry: { action: 'retryAccountSession' } },
66
74
  },
75
+ // Route-only evidence element: it belongs to the nested fulfillment route,
76
+ // never to the account page root or the order-detail page root.
77
+ 'account.fulfillmentEvidence': {
78
+ type: 'AccountFulfillmentEvidence',
79
+ props: {
80
+ fulfillmentId: { $state: '/fulfillmentEvidenceId' },
81
+ ...fulfillmentEvidenceDefaults,
82
+ },
83
+ },
67
84
  'account.login': {
68
85
  type: 'AccountLogin',
69
86
  visible: {
@@ -161,10 +178,10 @@ const catalog = {
161
178
  description:
162
179
  'Route-only order detail surface for one authenticated customer order; the host port supplies the data and the block owns its states.',
163
180
  },
164
- AccountBoot: {
165
- props: accountEmptyPropsSchema,
181
+ AccountFulfillmentEvidence: {
182
+ props: accountFulfillmentEvidencePropsSchema,
166
183
  description:
167
- 'Passive account boundary: shows a retryable unavailable status when the session cannot be resolved, otherwise nothing. Never fetches identity.',
184
+ 'Route-only fulfillment evidence gallery for one order fulfillment; the host port supplies the snapshot and signed asset URLs, and the block owns its states.',
168
185
  },
169
186
  AccountLogin: {
170
187
  props: accountLoginPropsSchema,
@@ -297,6 +314,22 @@ export const account: ViewModule = {
297
314
  'account.orderDetail': elements['account.orderDetail'],
298
315
  }),
299
316
  },
317
+ {
318
+ // The evidence route is nested under the order detail and binds both
319
+ // dynamic segments. The gallery only needs the fulfillment id; the order
320
+ // id keeps the URL scoped to the purchase. The evidence port owns the read
321
+ // and fails closed until the backend exists.
322
+ path: '/account/orders/[id]/fulfillments/[fulfillmentId]',
323
+ loaderName: 'fulfillmentEvidence',
324
+ layout: 'default',
325
+ metadata: {
326
+ title: 'Evidencias de entrega',
327
+ description: 'Consulta las evidencias de una entrega o recogida.',
328
+ },
329
+ entry: pageRoot('accountFulfillmentEvidence', ['account.fulfillmentEvidence'], {
330
+ 'account.fulfillmentEvidence': elements['account.fulfillmentEvidence'],
331
+ }),
332
+ },
300
333
  ],
301
334
  loader: {
302
335
  account: async () => ({ dataSource: getDataSource(), dataError: null }),
@@ -305,5 +338,13 @@ export const account: ViewModule = {
305
338
  if (!orderId) notFound()
306
339
  return { orderDetailId: orderId }
307
340
  },
341
+ fulfillmentEvidence: async (params) => {
342
+ const orderId = Array.isArray(params.id) ? params.id[0] : params.id
343
+ const fulfillmentId = Array.isArray(params.fulfillmentId)
344
+ ? params.fulfillmentId[0]
345
+ : params.fulfillmentId
346
+ if (!orderId || !fulfillmentId) notFound()
347
+ return { orderDetailId: orderId, fulfillmentEvidenceId: fulfillmentId }
348
+ },
308
349
  },
309
350
  }
@@ -0,0 +1,106 @@
1
+ // Host-owned copy and destinations for the order-detail route's sheets.
2
+ //
3
+ // These surfaces exist because the delivered block reports actions and documents
4
+ // through callbacks. The copy lives here so a store can translate or reword it
5
+ // without touching the block, and every mocked surface states that it is a
6
+ // demonstration: the demo database has no invoice issuer and no payment capture.
7
+ import { ORDER_DETAIL_SUPPORT_HREF } from '../../order-detail-capabilities'
8
+
9
+ export type OrderDetailFlowLabels = {
10
+ dialog: { close: string; sectionError: string }
11
+ reorder: {
12
+ pending: string
13
+ title: string
14
+ added: string
15
+ failedTitle: string
16
+ skippedTitle: string
17
+ goToCart: string
18
+ close: string
19
+ }
20
+ invoice: {
21
+ title: string
22
+ demoBanner: string
23
+ buyer: string
24
+ lines: string
25
+ totals: string
26
+ print: string
27
+ blocked: string
28
+ loading: string
29
+ error: string
30
+ }
31
+ track: {
32
+ title: string
33
+ carrier: string
34
+ number: string
35
+ events: string
36
+ noEvents: string
37
+ close: string
38
+ }
39
+ payBalance: {
40
+ title: string
41
+ amount: string
42
+ demoNotice: string
43
+ close: string
44
+ }
45
+ afterSales: {
46
+ loading: string
47
+ title: string
48
+ resultTitle: string
49
+ resultBody: string
50
+ units: string
51
+ close: string
52
+ }
53
+ }
54
+
55
+ export const orderDetailFlowLabels: OrderDetailFlowLabels = {
56
+ dialog: {
57
+ close: 'Cerrar',
58
+ sectionError: 'No pudimos cargar esta parte del pedido. Cierra e inténtalo de nuevo.',
59
+ },
60
+ reorder: {
61
+ pending: 'Agregando los productos al carrito…',
62
+ title: 'Repetir compra',
63
+ added: '{count} artículos agregados al carrito',
64
+ failedTitle: 'No se pudo repetir la compra',
65
+ skippedTitle: 'No se pudieron agregar',
66
+ goToCart: 'Ir al carrito',
67
+ close: 'Seguir en esta página',
68
+ },
69
+ invoice: {
70
+ title: 'Documento del pedido',
71
+ demoBanner: 'Documento de demostración — sin validez fiscal',
72
+ buyer: 'Comprador',
73
+ lines: 'Productos',
74
+ totals: 'Totales',
75
+ print: 'Imprimir o guardar',
76
+ blocked: 'El navegador bloqueó la ventana. Usa el documento que se muestra aquí.',
77
+ loading: 'Preparando el documento…',
78
+ error: 'No pudimos preparar el documento del pedido.',
79
+ },
80
+ track: {
81
+ title: 'Seguimiento del envío',
82
+ carrier: 'Transportista',
83
+ number: 'Número de seguimiento',
84
+ events: 'Eventos',
85
+ noEvents: 'La transportista todavía no reporta eventos.',
86
+ close: 'Cerrar',
87
+ },
88
+ payBalance: {
89
+ title: 'Saldo pendiente',
90
+ amount: 'Importe pendiente',
91
+ demoNotice: 'Pago de demostración — no se cobrará nada',
92
+ close: 'Cerrar',
93
+ },
94
+ afterSales: {
95
+ loading: 'Preparando la solicitud…',
96
+ title: 'Solicitud de posventa',
97
+ resultTitle: 'Solicitud de demostración preparada',
98
+ resultBody:
99
+ 'La solicitud quedó lista y no se envió: el pedido no se modificó y no se abrió ningún caso real.',
100
+ units: '{count} unidades en la solicitud',
101
+ close: 'Entendido',
102
+ },
103
+ }
104
+
105
+ /** Support destination for the "Contactar soporte" action. */
106
+ export const orderDetailSupport = { href: ORDER_DETAIL_SUPPORT_HREF }
@@ -0,0 +1,136 @@
1
+ import type { OrderDetailOrder, OrderDocument } from '@thorprovider/blocks/ports'
2
+
3
+ import { formatMinor } from '../../order-detail-money'
4
+ import type { OrderDetailFlowLabels } from './order-detail-flows.defaults'
5
+
6
+ type InvoiceInput = {
7
+ order: OrderDetailOrder
8
+ document: OrderDocument
9
+ /** Store display name. The sheet falls back to the document label. */
10
+ storeName?: string
11
+ labels: OrderDetailFlowLabels
12
+ locale: string
13
+ }
14
+
15
+ const ESCAPES: Record<string, string> = {
16
+ '&': '&amp;',
17
+ '<': '&lt;',
18
+ '>': '&gt;',
19
+ '"': '&quot;',
20
+ "'": '&#39;',
21
+ }
22
+
23
+ const escapeHtml = (value: string): string =>
24
+ value.replace(/[&<>"']/g, (character) => ESCAPES[character] ?? character)
25
+
26
+ const formatMoney = (money: { amount: number; currency: string }, locale: string): string =>
27
+ formatMinor(money.amount, money.currency, locale)
28
+
29
+ const formatDate = (iso: string, locale: string): string => {
30
+ const date = new Date(iso)
31
+ if (Number.isNaN(date.getTime())) return ''
32
+ try {
33
+ return new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(date)
34
+ } catch {
35
+ return date.toISOString().slice(0, 10)
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Build the printable invoice sheet from the loaded snapshot.
41
+ *
42
+ * The demo storefront can open a document the backend never issued, so the
43
+ * demonstration banner is part of the artifact itself: what leaves the browser
44
+ * (print, save, share) must never look like a fiscal document. Every dynamic
45
+ * value is escaped; nothing is fetched.
46
+ */
47
+ export function buildInvoiceHtml({
48
+ order,
49
+ document,
50
+ storeName,
51
+ labels,
52
+ locale,
53
+ }: InvoiceInput): string {
54
+ const copy = labels.invoice
55
+ const lines = order.lines
56
+ .map(
57
+ (line) => `<tr>
58
+ <td>${escapeHtml(line.name)}</td>
59
+ <td>${escapeHtml(line.sku)}</td>
60
+ <td class="num">${line.quantity - line.cancelledQuantity}</td>
61
+ <td class="num">${escapeHtml(formatMoney(line.unitPrice.applied, locale))}</td>
62
+ <td class="num">${escapeHtml(formatMoney(line.total, locale))}</td>
63
+ </tr>`,
64
+ )
65
+ .join('')
66
+
67
+ const buyer = order.billingAddress
68
+ ? `<p><strong>${escapeHtml(copy.buyer)}</strong><br>${escapeHtml(order.billingAddress.name)}<br>${escapeHtml(
69
+ [order.billingAddress.line1, order.billingAddress.line2].filter(Boolean).join(' '),
70
+ )}<br>${escapeHtml(
71
+ [order.billingAddress.city, order.billingAddress.region, order.billingAddress.postalCode]
72
+ .filter(Boolean)
73
+ .join(', '),
74
+ )}<br>${escapeHtml(order.billingAddress.country)}</p>`
75
+ : ''
76
+
77
+ return `<!doctype html>
78
+ <html lang="${escapeHtml(locale)}">
79
+ <head>
80
+ <meta charset="utf-8">
81
+ <title>${escapeHtml(document.label)}</title>
82
+ <style>
83
+ body { font-family: ui-sans-serif, system-ui, sans-serif; margin: 0; padding: 32px; color: #111; }
84
+ .demo { border: 2px dashed #b45309; color: #7c2d12; padding: 12px 16px; border-radius: 8px; font-weight: 600; }
85
+ h1 { font-size: 20px; margin: 24px 0 4px; }
86
+ .meta { color: #555; font-size: 13px; margin: 0 0 24px; }
87
+ table { width: 100%; border-collapse: collapse; font-size: 13px; margin-top: 16px; }
88
+ th, td { text-align: left; padding: 8px 6px; border-bottom: 1px solid #ddd; }
89
+ .num { text-align: right; white-space: nowrap; }
90
+ .totals { margin-top: 24px; margin-left: auto; width: 280px; font-size: 13px; }
91
+ .totals div { display: flex; justify-content: space-between; padding: 4px 0; }
92
+ .totals .grand { border-top: 1px solid #999; font-weight: 700; }
93
+ footer { margin-top: 32px; font-size: 11px; color: #666; }
94
+ @media print { body { padding: 0; } }
95
+ </style>
96
+ </head>
97
+ <body class="order-print">
98
+ <p class="demo">${escapeHtml(copy.demoBanner)}</p>
99
+ <h1>${escapeHtml(storeName ?? document.label)}</h1>
100
+ <p class="meta">${escapeHtml(document.label)} · Pedido ${escapeHtml(order.number)} · ${escapeHtml(
101
+ formatDate(order.createdAt, locale),
102
+ )}</p>
103
+ ${buyer}
104
+ <h2>${escapeHtml(copy.lines)}</h2>
105
+ <table>
106
+ <thead>
107
+ <tr>
108
+ <th>Producto</th><th>SKU</th><th class="num">Cant.</th><th class="num">Precio</th><th class="num">Importe</th>
109
+ </tr>
110
+ </thead>
111
+ <tbody>${lines}</tbody>
112
+ </table>
113
+ <div class="totals">
114
+ <div><span>Subtotal</span><span>${escapeHtml(formatMoney(order.totals.itemsSubtotal, locale))}</span></div>
115
+ <div><span>Envío</span><span>${escapeHtml(formatMoney(order.totals.shippingSubtotal, locale))}</span></div>
116
+ <div><span>Impuestos</span><span>${escapeHtml(formatMoney(order.totals.tax, locale))}</span></div>
117
+ <div class="grand"><span>${escapeHtml(copy.totals)}</span><span>${escapeHtml(
118
+ formatMoney(order.totals.total, locale),
119
+ )}</span></div>
120
+ </div>
121
+ <footer>${escapeHtml(copy.demoBanner)}</footer>
122
+ </body>
123
+ </html>`
124
+ }
125
+
126
+ /** Open the printable sheet in a new tab; returns false when it was blocked. */
127
+ export function openPrintable(html: string): boolean {
128
+ const url = URL.createObjectURL(new Blob([html], { type: 'text/html' }))
129
+ const opened = window.open(url, '_blank', 'noopener,noreferrer')
130
+ if (!opened) {
131
+ URL.revokeObjectURL(url)
132
+ return false
133
+ }
134
+ window.setTimeout(() => URL.revokeObjectURL(url), 60_000)
135
+ return true
136
+ }
@@ -0,0 +1,100 @@
1
+ 'use client'
2
+
3
+ import { useEffect, useId, useRef, type ReactNode } from 'react'
4
+
5
+ type SheetProps = {
6
+ title: string
7
+ closeLabel: string
8
+ onClose: () => void
9
+ children: ReactNode
10
+ }
11
+
12
+ const FOCUSABLE =
13
+ 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
14
+
15
+ /**
16
+ * Accessible modal sheet for the order-detail callbacks.
17
+ *
18
+ * The surface reports documents and actions through callbacks; the host answers
19
+ * with a sheet instead of a new route, so the order stays behind it. The sheet
20
+ * traps focus, closes on Escape and restores focus to whatever opened it.
21
+ */
22
+ export function OrderDetailSheet({ title, closeLabel, onClose, children }: SheetProps) {
23
+ const titleId = useId()
24
+ const bodyRef = useRef<HTMLDivElement>(null)
25
+
26
+ useEffect(() => {
27
+ const trigger = document.activeElement as HTMLElement | null
28
+ const node = bodyRef.current
29
+ const focusables = () =>
30
+ Array.from(node?.querySelectorAll<HTMLElement>(FOCUSABLE) ?? []).filter(
31
+ (element) => element.offsetParent !== null,
32
+ )
33
+
34
+ const first = focusables()[0]
35
+ if (first) first.focus()
36
+ else node?.focus()
37
+
38
+ const onKeyDown = (event: KeyboardEvent) => {
39
+ if (event.key === 'Escape') {
40
+ event.preventDefault()
41
+ onClose()
42
+ return
43
+ }
44
+ if (event.key !== 'Tab') return
45
+ const items = focusables()
46
+ if (items.length === 0) return
47
+ const firstItem = items[0]
48
+ const lastItem = items[items.length - 1]
49
+ if (event.shiftKey && document.activeElement === firstItem) {
50
+ event.preventDefault()
51
+ lastItem.focus()
52
+ } else if (!event.shiftKey && document.activeElement === lastItem) {
53
+ event.preventDefault()
54
+ firstItem.focus()
55
+ }
56
+ }
57
+
58
+ const previousOverflow = document.body.style.overflow
59
+ document.body.style.overflow = 'hidden'
60
+ document.addEventListener('keydown', onKeyDown)
61
+
62
+ return () => {
63
+ document.removeEventListener('keydown', onKeyDown)
64
+ document.body.style.overflow = previousOverflow
65
+ trigger?.focus?.()
66
+ }
67
+ }, [onClose])
68
+
69
+ return (
70
+ <div
71
+ className="fixed inset-0 z-50 flex items-end justify-center bg-foreground/40 p-0 sm:items-center sm:p-6"
72
+ onMouseDown={(event) => {
73
+ if (event.target === event.currentTarget) onClose()
74
+ }}
75
+ >
76
+ <div
77
+ ref={bodyRef}
78
+ role="dialog"
79
+ aria-modal="true"
80
+ aria-labelledby={titleId}
81
+ tabIndex={-1}
82
+ className="flex max-h-[92vh] w-full max-w-lg flex-col overflow-hidden rounded-t-2xl border bg-background shadow-xl sm:rounded-2xl"
83
+ >
84
+ <div className="flex items-start justify-between gap-3 border-b px-4 py-3">
85
+ <h2 id={titleId} className="text-base font-semibold">
86
+ {title}
87
+ </h2>
88
+ <button
89
+ type="button"
90
+ onClick={onClose}
91
+ className="inline-flex h-11 items-center rounded-md px-3 text-sm font-medium text-muted-foreground hover:bg-muted focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
92
+ >
93
+ {closeLabel}
94
+ </button>
95
+ </div>
96
+ <div className="overflow-y-auto px-4 py-4">{children}</div>
97
+ </div>
98
+ </div>
99
+ )
100
+ }