@thorprovider/storefront 0.10.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 (32) 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 +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__/order-detail-aftersales.ts +55 -0
  9. package/assets/templates/app/lib/__STOREFRONT__/order-detail-capabilities.ts +79 -0
  10. package/assets/templates/app/lib/__STOREFRONT__/order-detail-mapper.ts +13 -2
  11. package/assets/templates/app/lib/__STOREFRONT__/order-detail-money.ts +39 -0
  12. package/assets/templates/app/lib/__STOREFRONT__/order-detail-reorder.ts +62 -0
  13. package/assets/templates/views/account/assembly/index.skeleton.tsx +3 -0
  14. package/assets/templates/views/account/assembly/registry.skeleton.tsx +115 -4
  15. package/assets/templates/views/account/content.ts +6 -0
  16. package/assets/templates/views/account/index.tsx +3 -0
  17. package/assets/templates/views/account/order-detail-flows.defaults.ts +106 -0
  18. package/assets/templates/views/account/order-detail-invoice.ts +136 -0
  19. package/assets/templates/views/account/order-detail-sheet.tsx +100 -0
  20. package/assets/templates/views/account/order-detail-sheets.tsx +122 -0
  21. package/assets/templates/views/account/order-detail.client.tsx +401 -1
  22. package/assets/templates/views/account/registry.tsx +115 -4
  23. package/assets/templates/views/account/schema.ts +2 -0
  24. package/assets/templates/views/home/content.ts +3 -1
  25. package/assets/templates/views/product/data.ts +13 -6
  26. package/assets/templates/views/product/index.tsx +3 -3
  27. package/bin/storefront.js +5 -4
  28. package/package.json +1 -1
  29. package/scripts/candidate.mjs +8 -4
  30. package/scripts/mock-capabilities.mjs +22 -0
  31. package/scripts/reconcile.mjs +5 -2
  32. package/scripts/render-templates.mjs +126 -43
@@ -118,6 +118,15 @@ const SHELL_DEFAULTS = {
118
118
  },
119
119
  overview: {
120
120
  sections: 'Secciones de tu cuenta',
121
+ // The card summaries are preformatted text, exactly what the host passes. A
122
+ // module with nothing inside keeps its card summary-less: the overview never
123
+ // prints a zero to fill space.
124
+ summaries: {
125
+ orders: '{count} pedidos',
126
+ ordersOne: '1 pedido',
127
+ addresses: '{count} guardadas',
128
+ addressesOne: '1 guardada',
129
+ },
121
130
  },
122
131
  placeholder: {
123
132
  badge: 'Próximamente',
@@ -182,6 +191,10 @@ const shellContent = {
182
191
  overview: {
183
192
  ...SHELL_DEFAULTS.overview,
184
193
  ...(accountContentCompat.overview ?? {}),
194
+ summaries: {
195
+ ...SHELL_DEFAULTS.overview.summaries,
196
+ ...(accountContentCompat.overview?.summaries ?? {}),
197
+ },
185
198
  },
186
199
  placeholder: {
187
200
  ...SHELL_DEFAULTS.placeholder,
@@ -360,14 +373,29 @@ function shellCustomer(customer: Customer): CustomerAccountV1Props['context']['c
360
373
  .map((part) => part[0])
361
374
  .join('')
362
375
  .toUpperCase() || customer.email.slice(0, 2).toUpperCase()
376
+ const memberSince = memberSinceLabel(customer.createdAt)
363
377
  return {
364
378
  name,
365
379
  email: customer.email,
366
380
  initials,
367
381
  ...(customer.phone ? { phone: customer.phone } : {}),
382
+ ...(memberSince ? { memberSince } : {}),
368
383
  }
369
384
  }
370
385
 
386
+ /**
387
+ * The join date the header prints as "Cliente desde {date}". Only the month and
388
+ * year leave the store ("marzo de 2023"), the same granularity the account
389
+ * surface needs; an absent or unparseable date simply hides the line instead of
390
+ * inventing one.
391
+ */
392
+ function memberSinceLabel(createdAt: string | null | undefined): string | undefined {
393
+ if (!createdAt) return undefined
394
+ const date = new Date(createdAt)
395
+ if (Number.isNaN(date.getTime())) return undefined
396
+ return new Intl.DateTimeFormat('es-ES', { month: 'long', year: 'numeric' }).format(date)
397
+ }
398
+
371
399
  function shellState(state: AccountState): CustomerAccountV1Props['state'] {
372
400
  if (state.accountReconciling === true) return { status: 'loading' }
373
401
  if (state.accountResolution === 'unavailable') {
@@ -432,10 +460,93 @@ function AccountShellPanel({ children }: ShellPanelProps) {
432
460
  )
433
461
  }
434
462
 
463
+ /** One order row is enough to read the authoritative page count. */
464
+ const OVERVIEW_ORDERS_PAGE_SIZE = 1
465
+
466
+ function summaryText(template: string, single: string, count: number): string {
467
+ return count === 1 ? single : template.replaceAll('{count}', String(count))
468
+ }
469
+
470
+ /**
471
+ * Preformatted card summaries. The overview names how much is waiting inside the
472
+ * modules, so it reads the two counters the modules load anyway: the order page
473
+ * count and the saved-address list. Nothing is invented — a module the store
474
+ * does not offer is never counted, a failed read leaves the card summary-less,
475
+ * and an empty module prints no zero.
476
+ */
477
+ function overviewSummaries(
478
+ state: AccountState,
479
+ capabilities: CustomerAccountOverviewProps['capabilities'],
480
+ ): Record<string, string> {
481
+ const summaries: Record<string, string> = {}
482
+ const orderCount =
483
+ typeof state.accountOrdersCount === 'number' ? state.accountOrdersCount : 0
484
+ const addressCount = Array.isArray(state.accountAddresses)
485
+ ? state.accountAddresses.length
486
+ : 0
487
+ if (capabilities.orderHistory === true && orderCount > 0) {
488
+ summaries.orders = summaryText(
489
+ shellContent.overview.summaries.orders,
490
+ shellContent.overview.summaries.ordersOne,
491
+ orderCount,
492
+ )
493
+ }
494
+ if (capabilities.addressBook === true && addressCount > 0) {
495
+ summaries.addresses = summaryText(
496
+ shellContent.overview.summaries.addresses,
497
+ shellContent.overview.summaries.addressesOne,
498
+ addressCount,
499
+ )
500
+ }
501
+ return summaries
502
+ }
503
+
435
504
  function AccountOverviewPanel() {
436
- const { state } = useStateStore()
505
+ const { state, set } = useStateStore()
437
506
  const pathname = usePathname()
438
507
  const router = useRouter()
508
+ const { identityKey, reconciling } = useAccountLifecycle()
509
+ const loadedKeyRef = useRef<string | null>(null)
510
+ const capabilities = shellCapabilities(state)
511
+ const authenticated = state.accountAuthenticated === true
512
+ const wantsOrders = capabilities.orderHistory === true
513
+ const wantsAddresses = capabilities.addressBook === true
514
+
515
+ // The overview is the only surface that needs a count without rendering the
516
+ // module, so it performs the same reads the module would and stores their
517
+ // result in the shared account state. Keyed by identity: a new shopper never
518
+ // inherits the previous one's counters, and a read that lands after an
519
+ // identity change is dropped instead of overwriting the new state.
520
+ useEffect(() => {
521
+ if (!authenticated || reconciling) return
522
+ if (pathname !== '/account') return
523
+ if (identityKey === 'anonymous') return
524
+ if (loadedKeyRef.current === identityKey) return
525
+ loadedKeyRef.current = identityKey
526
+ if (wantsOrders) {
527
+ void loadOrdersPageAction({ page: 1, pageSize: OVERVIEW_ORDERS_PAGE_SIZE })
528
+ .then((result) => {
529
+ if (result.ok && loadedKeyRef.current === identityKey) {
530
+ set('/accountOrdersCount', result.count)
531
+ }
532
+ })
533
+ .catch(() => {
534
+ // A failed count read is not an account error: the card keeps its
535
+ // description and simply shows no summary.
536
+ })
537
+ }
538
+ if (wantsAddresses) {
539
+ void loadAccountAddressesAction()
540
+ .then((result) => {
541
+ if (result.ok && loadedKeyRef.current === identityKey) {
542
+ set('/accountAddresses', result.addresses)
543
+ }
544
+ })
545
+ .catch(() => {
546
+ // Same rule as the order count: no summary beats a made-up number.
547
+ })
548
+ }
549
+ }, [authenticated, reconciling, pathname, identityKey, wantsOrders, wantsAddresses, set])
439
550
 
440
551
  useEffect(() => {
441
552
  if (pathname !== '/account') return
@@ -448,12 +559,12 @@ function AccountOverviewPanel() {
448
559
  return () => cancelAnimationFrame(frame)
449
560
  }, [pathname])
450
561
 
451
- if (!state.accountAuthenticated) return null
562
+ if (!authenticated) return null
452
563
  return (
453
564
  <AccountOverviewBlock
454
565
  title={shellContent.shellModules.overview.label}
455
- model={{ cards: shellCards(), summaries: {}, notice: null }}
456
- capabilities={shellCapabilities(state)}
566
+ model={{ cards: shellCards(), summaries: overviewSummaries(state, capabilities), notice: null }}
567
+ capabilities={capabilities}
457
568
  labels={{ sections: shellContent.overview.sections }}
458
569
  onOpenCard={(cardId) => {
459
570
  sessionStorage.setItem('account:origin-card', cardId)
@@ -29,6 +29,12 @@ export const accountContent = {
29
29
  },
30
30
  overview: {
31
31
  sections: 'Secciones de tu cuenta',
32
+ summaries: {
33
+ orders: '{count} pedidos',
34
+ ordersOne: '1 pedido',
35
+ addresses: '{count} guardadas',
36
+ addressesOne: '1 guardada',
37
+ },
32
38
  },
33
39
  placeholder: {
34
40
  badge: 'Próximamente',
@@ -24,6 +24,7 @@ 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'
27
28
  import { fulfillmentEvidenceDefaults } from './fulfillment-evidence.defaults'
28
29
  import { accountOrdersAdvancedDefaults } from './orders-advanced.defaults'
29
30
  import {
@@ -59,6 +60,8 @@ const elements: Record<string, StorefrontElement> = {
59
60
  props: {
60
61
  orderId: { $state: '/orderDetailId' },
61
62
  ...orderDetailDefaults,
63
+ supportHref: orderDetailSupport.href,
64
+ flows: orderDetailFlowLabels,
62
65
  },
63
66
  },
64
67
  // Headless account boundary. It is fixed infrastructure, not a selectable
@@ -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
+ }
@@ -0,0 +1,122 @@
1
+ 'use client'
2
+
3
+ import type { OrderDetailMoney, OrderDetailOrder, TrackingEvent } from '@thorprovider/blocks/ports'
4
+
5
+ import { formatMinor } from '../../order-detail-money'
6
+ import type { OrderDetailFlowLabels } from './order-detail-flows.defaults'
7
+
8
+ const formatMoney = (money: OrderDetailMoney, locale = 'es-MX'): string =>
9
+ formatMinor(money.amount, money.currency, locale)
10
+
11
+ /** Carrier, number and events the backend reported. Nothing is synthesized. */
12
+ export function trackingFacts(order: OrderDetailOrder): {
13
+ carrier?: string
14
+ number?: string
15
+ events: TrackingEvent[]
16
+ } {
17
+ const carrier = order.fulfillments.find((fulfillment) => fulfillment.carrier)?.carrier
18
+ const number = order.fulfillments.find(
19
+ (fulfillment) => fulfillment.trackingNumber,
20
+ )?.trackingNumber
21
+ const events = order.fulfillments.flatMap((fulfillment) => fulfillment.events ?? [])
22
+ return {
23
+ ...(carrier ? { carrier } : {}),
24
+ ...(number ? { number } : {}),
25
+ events,
26
+ }
27
+ }
28
+
29
+ /** Outstanding balance: total minus captured payments plus refunds. */
30
+ export function dueAmount(order: OrderDetailOrder): OrderDetailMoney {
31
+ const paid = order.transactions
32
+ .filter((transaction) => transaction.status === 'captured')
33
+ .reduce((sum, transaction) => sum + transaction.amount.amount, 0)
34
+ const refunded = order.transactions
35
+ .filter((transaction) => transaction.kind === 'refund' && transaction.status === 'refunded')
36
+ .reduce((sum, transaction) => sum + transaction.amount.amount, 0)
37
+ return {
38
+ amount: Math.max(0, order.totals.total.amount - paid + refunded),
39
+ currency: order.totals.total.currency,
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Tracking sheet. The demo data has no carrier URL, so the sheet reports the
45
+ * identifiers and the events it has instead of linking somewhere invented.
46
+ */
47
+ export function TrackSheet({
48
+ order,
49
+ labels,
50
+ locale,
51
+ }: {
52
+ order: OrderDetailOrder
53
+ labels: OrderDetailFlowLabels
54
+ locale?: string
55
+ }) {
56
+ const facts = trackingFacts(order)
57
+ const copy = labels.track
58
+
59
+ return (
60
+ <div className="space-y-4 text-sm">
61
+ <dl className="grid grid-cols-1 gap-2 sm:grid-cols-2">
62
+ {facts.carrier ? (
63
+ <div>
64
+ <dt className="text-xs text-muted-foreground">{copy.carrier}</dt>
65
+ <dd className="font-medium">{facts.carrier}</dd>
66
+ </div>
67
+ ) : null}
68
+ {facts.number ? (
69
+ <div>
70
+ <dt className="text-xs text-muted-foreground">{copy.number}</dt>
71
+ <dd className="font-medium break-all">{facts.number}</dd>
72
+ </div>
73
+ ) : null}
74
+ </dl>
75
+
76
+ <div className="space-y-2">
77
+ <p className="text-xs font-medium text-muted-foreground">{copy.events}</p>
78
+ {facts.events.length === 0 ? (
79
+ <p className="text-muted-foreground">{copy.noEvents}</p>
80
+ ) : (
81
+ <ol className="space-y-2">
82
+ {facts.events.map((event) => (
83
+ <li key={event.id} className="rounded-md border p-2">
84
+ <p className="font-medium">{event.label}</p>
85
+ <p className="text-xs text-muted-foreground">
86
+ {new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(
87
+ new Date(event.at),
88
+ )}
89
+ {event.place ? ` · ${event.place}` : ''}
90
+ </p>
91
+ </li>
92
+ ))}
93
+ </ol>
94
+ )}
95
+ </div>
96
+ </div>
97
+ )
98
+ }
99
+
100
+ /** Outstanding-balance sheet. A form that cannot charge would be a lie. */
101
+ export function PayBalanceSheet({
102
+ order,
103
+ labels,
104
+ }: {
105
+ order: OrderDetailOrder
106
+ labels: OrderDetailFlowLabels
107
+ locale?: string
108
+ }) {
109
+ const copy = labels.payBalance
110
+
111
+ return (
112
+ <div className="space-y-4 text-sm">
113
+ <div className="flex items-baseline justify-between gap-3 rounded-lg border p-3">
114
+ <span className="text-muted-foreground">{copy.amount}</span>
115
+ <span className="text-lg font-semibold tabular-nums">
116
+ {formatMoney(dueAmount(order))}
117
+ </span>
118
+ </div>
119
+ <p className="rounded-lg border border-dashed p-3 text-muted-foreground">{copy.demoNotice}</p>
120
+ </div>
121
+ )
122
+ }