/** * Tracking row and pop-up for a shipment: parcel numbers, proof images and courier events. */ import { __ } from '@wordpress/i18n'; import { useState, useCallback, useEffect, useRef } from '@wordpress/element'; import apiFetch from '@wordpress/api-fetch'; import { Flex, FlexItem, Icon, Modal, Notice, Spinner, Tooltip } from '@wordpress/components'; import { chevronRight, shipping } from '@wordpress/icons'; import type { ShipmentTracking as Tracking, TrackingParcel } from '../../types'; import { getApiErrorMessage } from '../../shared/utils'; import { captureException } from '../../shared/sentry'; const STAGE_LABELS: Record = { DroppedOff: __('Dropped off', 'parcel2go-shipping'), Collected: __('Collected', 'parcel2go-shipping'), InTransit: __('In transit', 'parcel2go-shipping'), AtDepot: __('At depot', 'parcel2go-shipping'), DeliveryScheduled: __('Delivery scheduled', 'parcel2go-shipping'), Delivered: __('Delivered', 'parcel2go-shipping'), }; /** "InTransit" -> "In transit"; unknown stages are split on capitals. */ export function formatStage(stage: string): string { if (!stage) return ''; if (STAGE_LABELS[stage]) return STAGE_LABELS[stage]; const words = stage.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase(); return words.charAt(0).toUpperCase() + words.slice(1); } export function formatTimestamp(timestamp: string): string { const date = new Date(timestamp); if (!timestamp || isNaN(date.getTime())) return timestamp; return date.toLocaleString(undefined, { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit', }); } function ParcelTracking({ parcel }: { parcel: TrackingParcel }) { return (

{parcel.number}

{parcel.images.map((image) => ( {image.key ))} {parcel.events.length === 0 ? (

{__('Awaiting tracking data from courier', 'parcel2go-shipping')}

) : ( )}
); } /** Tracking older than this is loaded again when the pop-up opens (the server caches it for 5 minutes too). */ export const TRACKING_STALE_MS = 5 * 60 * 1000; /** No events or photos for any parcel yet. */ export function isAwaitingCourier(tracking: Tracking | null): boolean { return (tracking?.parcels ?? []).every((parcel) => parcel.events.length === 0 && parcel.images.length === 0); } /** Body of the tracking pop-up, for each state of the request. */ export function TrackingDetails({ loading, error, tracking, }: { loading: boolean; error: string | null; tracking: Tracking | null; }) { if (loading) { return (
); } if (error) { return ( {error} ); } const parcels = tracking?.parcels ?? []; if (isAwaitingCourier(tracking)) { return (

{__('Awaiting tracking data from courier', 'parcel2go-shipping')}

); } return ( <> {parcels.map((parcel, index) => ( ))} ); } /** Loads a shipment's tracking as soon as the card shows; the server caches it for a few minutes. */ export function useShipmentTracking(orderId: number) { const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [tracking, setTracking] = useState(null); const mounted = useRef(true); const loadedAt = useRef(0); const load = useCallback( async (report: boolean) => { setLoading(true); setError(null); try { const data = (await apiFetch({ path: `/parcel2go-shipping/v1/shipments/${orderId}/tracking`, })) as Tracking; if (mounted.current) { setTracking(data); loadedAt.current = Date.now(); } } catch (err) { // Report only when the merchant asked; only the error, no order or address details. if (report) captureException(err instanceof Error ? err : new Error('Shipment tracking failed')); if (mounted.current) setError(getApiErrorMessage(err, __('Could not load tracking. Please try again.', 'parcel2go-shipping'))); } finally { if (mounted.current) setLoading(false); } }, [orderId] ); useEffect(() => { mounted.current = true; load(false); return () => { mounted.current = false; }; }, [load]); return { loading, error, tracking, load, loadedAt }; } /** Text for the tracking row before the pop-up opens. */ export function trackingRowLabel(loading: boolean, error: string | null, tracking: Tracking | null): string { if (loading) return __('Checking…', 'parcel2go-shipping'); if (error || !tracking) return __('View tracking', 'parcel2go-shipping'); return formatStage(tracking.currentStage) || __('Awaiting courier', 'parcel2go-shipping'); } /** The card's text size, in the admin theme colour the plugin's buttons use. */ const TRACKING_LINK_STYLE: React.CSSProperties = { display: 'inline-flex', alignItems: 'center', gap: 4, padding: 0, border: 0, background: 'none', cursor: 'pointer', font: 'inherit', fontWeight: 500, color: 'var(--wp-admin-theme-color, #3858e9)', textDecoration: 'none', }; /** "Tracking" detail row: the current stage as a link that opens the pop-up. */ export default function ShipmentTracking({ orderId }: { orderId: number }) { const [open, setOpen] = useState(false); const { loading, error, tracking, load, loadedAt } = useShipmentTracking(orderId); const openTracking = useCallback(() => { setOpen(true); if (loading) return; // Retry a failed preload, and report it this time. if (error) { load(true); return; } // Ask again when the page has been open a while, or the courier had nothing yet. if (Date.now() - loadedAt.current > TRACKING_STALE_MS || isAwaitingCourier(tracking)) load(false); }, [loading, error, tracking, load, loadedAt]); return ( {__('Tracking', 'parcel2go-shipping')} {/* Plain button so it keeps the card's text size; WordPress's link button sets its own. */} {open && ( setOpen(false)} > )} ); }