'use client'; import { useState } from 'react'; import { useTranslations } from '@/core/lib/translations'; import { cn } from '@/core/lib/utils'; /** * Where each parcel of an order is: a progress bar, the estimated delivery when the carrier gives one, * and the latest tracking updates. Reads `order.shipments`, which the backend builds from an allow-list * (no label, no cost, no address, none of the carrier's free text), so everything shown here is already * safe for a shopper. * * The shape is declared here instead of imported so this component compiles against any SDK version: an * older backend or SDK simply has no `shipments`, and the page falls back to the single tracking line. * Once the SDK pin carries `PublicShipment`, the type can come from `brainerce`. */ export type ShipmentStatus = | 'label_created' | 'in_transit' | 'out_for_delivery' | 'delivered' | 'returned'; export type ShipmentEventStatus = | 'label_created' | 'in_transit' | 'out_for_delivery' | 'delivered' | 'returned' | 'attempt_failed' | 'update'; export interface ShipmentEventView { status: ShipmentEventStatus; occurredAt: string; city: string | null; country: string | null; } export interface ShipmentView { carrier: string; service: string | null; status: ShipmentStatus; trackingNumber: string | null; trackingUrl: string | null; estimatedDeliveryDate: string | null; actualDeliveryDate: string | null; /** What this parcel carries when the order was split: line position in `order.items` and units. Empty = the whole order. */ items?: Array<{ lineIndex: number; quantity: number }>; events: ShipmentEventView[]; /** * Set when the store own courier delivers this parcel: there is no carrier, no tracking number and no link, so the card shows * the courier name and the day and window instead. Never a phone number. Absent on an older backend or SDK. */ ownCourier?: { courierName: string; deliveryWindow: { date: string | null; from: string | null; to: string | null }; } | null; } /** The names of an order's lines, by position; only the name is read. */ export type OrderLineNames = Array<{ name?: string | null } | null | undefined>; /** * What is in one parcel, as "2 × Mug, Plate". Empty when the parcel names no items (it carries the whole order) or * none of its lines can be named, so a parcel never claims a line it cannot show. */ export function parcelItemsText( items: ShipmentView['items'], lines: OrderLineNames | undefined ): string { if (!items || items.length === 0 || !lines) return ''; return items .map((i) => { const name = (lines[i.lineIndex]?.name ?? '').toString().trim(); if (!name) return ''; return i.quantity > 1 ? `${i.quantity} × ${name}` : name; }) .filter(Boolean) .join(', '); } /** "18.11.2026, 14:00 to 16:00" for an own-courier parcel (day and window as the merchant gave them); empty when it gave none. */ export function ownCourierWhen( window: { date: string | null; from: string | null; to: string | null }, words: { between: (from: string, to: string) => string; from: (from: string) => string } ): string { const parts: string[] = []; if (window.date && /^\d{4}-\d{2}-\d{2}$/.test(window.date)) { // Noon UTC, shown as the same UTC day: no time zone can move the calendar day the merchant chose. parts.push( new Date(`${window.date}T12:00:00Z`).toLocaleDateString(undefined, { timeZone: 'UTC' }) ); } if (window.from && window.to) parts.push(words.between(window.from, window.to)); else if (window.from) parts.push(words.from(window.from)); return parts.join(', '); } /** The parcels of an order, or none when the backend or SDK does not send them. */ export function shipmentsOf(order: unknown): ShipmentView[] { const list = (order as { shipments?: unknown } | null)?.shipments; return Array.isArray(list) ? (list as ShipmentView[]) : []; } const STEPS: ShipmentStatus[] = ['label_created', 'in_transit', 'out_for_delivery', 'delivered']; const STEP_LABEL_KEYS: Record = { label_created: 'shipmentStatusLabelCreated', in_transit: 'shipmentStatusInTransit', out_for_delivery: 'shipmentStatusOutForDelivery', delivered: 'shipmentStatusDelivered', returned: 'shipmentStatusReturned', }; const EVENT_LABEL_KEYS: Record = { label_created: 'shipmentEventLabelCreated', in_transit: 'shipmentEventInTransit', out_for_delivery: 'shipmentEventOutForDelivery', delivered: 'shipmentEventDelivered', returned: 'shipmentEventReturned', attempt_failed: 'shipmentEventAttemptFailed', update: 'shipmentEventUpdate', }; /** Updates shown before "show all". */ const EVENTS_COLLAPSED = 3; function formatDate(iso: string): string { const d = new Date(iso); return isNaN(d.getTime()) ? '' : d.toLocaleDateString(); } function formatDateTime(iso: string): string { const d = new Date(iso); return isNaN(d.getTime()) ? '' : d.toLocaleString(); } function ShipmentCard({ shipment, position, lines, }: { shipment: ShipmentView; /** Which box of how many, only for an order in several boxes. */ position?: { index: number; total: number }; lines?: OrderLineNames; }) { const t = useTranslations('account'); const contents = position ? parcelItemsText(shipment.items, lines) : ''; const [showAll, setShowAll] = useState(false); const returned = shipment.status === 'returned'; const stepIndex = STEPS.indexOf(shipment.status); const events = shipment.events ?? []; const visibleEvents = showAll ? events : events.slice(0, EVENTS_COLLAPSED); const delivered = shipment.status === 'delivered'; const ownCourier = shipment.ownCourier ?? null; const ownCourierText = ownCourier ? ownCourierWhen(ownCourier.deliveryWindow, { between: (from, to) => t('shipmentOwnCourierBetween', { from, to }), from: (from) => t('shipmentOwnCourierFrom', { from }), }) : ''; // A courier parcel states its own day and window; a generic estimate would repeat or contradict it. const showEstimate = !ownCourier && !!shipment.estimatedDeliveryDate && !delivered && !returned; const deliveredOn = delivered ? shipment.actualDeliveryDate || events[0]?.occurredAt : null; return (
{position && (

{t('shipmentParcelOf', { index: String(position.index), total: String(position.total), })}

{contents &&

{contents}

}
)} {ownCourier ? (

{ownCourier.courierName ? t('shipmentOwnCourierName', { name: ownCourier.courierName }) : t('shipmentOwnCourier')}

{ownCourierText && !delivered && (

{t('shipmentOwnCourierExpected', { when: ownCourierText })}

)} {!delivered && (

{t('shipmentOwnCourierNoTracking')}

)}
) : (

{[shipment.carrier, shipment.trackingNumber].filter(Boolean).join(' · ')}

{shipment.service &&

{shipment.service}

}
)} {returned ? (

{t(STEP_LABEL_KEYS.returned)}

) : (
    {STEPS.map((step, i) => { const done = i <= stepIndex; return (
  1. ); })}
)}
{showEstimate && (

{t('shipmentEstimated', { date: formatDate(shipment.estimatedDeliveryDate!) })}

)} {deliveredOn &&

{t('deliveredOn', { date: formatDate(deliveredOn) })}

} {events.length === 0 && shipment.status === 'label_created' && (

{t('shipmentWaiting')}

)}
{events.length > 0 && (

{t('shipmentUpdates')}

    {visibleEvents.map((event, idx) => { const place = [event.city, event.country].filter(Boolean).join(', '); return (
  1. {t(EVENT_LABEL_KEYS[event.status] ?? 'shipmentEventUpdate')} {place && · {place}} {formatDateTime(event.occurredAt)}
  2. ); })}
{events.length > EVENTS_COLLAPSED && ( )}
)} {shipment.trackingUrl && ( {t('trackOrder')} )}
); } interface OrderShipmentTrackingProps { shipments: ShipmentView[]; /** `order.items`, to name what is in each box when the order went out in several. */ orderItems?: OrderLineNames; className?: string; } export function OrderShipmentTracking({ shipments, orderItems, className, }: OrderShipmentTrackingProps) { const t = useTranslations('account'); if (shipments.length === 0) return null; return (

{t('tracking')}

{shipments.map((shipment, idx) => ( 1 ? { index: idx + 1, total: shipments.length } : undefined} lines={orderItems} /> ))}
); }