import { Badge } from '@components/common/ui/Badge.js'; import { Button } from '@components/common/ui/Button.js'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@components/common/ui/Dialog.js'; import { Label } from '@components/common/ui/Label.js'; import { toast } from '@components/common/ui/Sonner.js'; import { Switch } from '@components/common/ui/Switch.js'; import { _ } from '@evershop/evershop/lib/locale/translate/_'; import axios from 'axios'; import { Check, Minus, Plus, Truck } from 'lucide-react'; import React from 'react'; import { hasTrackingCapability } from './carrierCaps.js'; export interface UnshippedItem { uuid: string; orderItemId: number; productSku: string; productName: string; qtyOrdered: number; qtyUnshipped: number; } interface Carrier { code: string; name: string; capabilities?: { createLabel?: boolean; generateTrackingUrl?: boolean; voidLabel?: boolean; fetchStatus?: boolean; }; } interface DraftLine { order_item_id: number; qty: number; checked: boolean; } function QtyStepper({ value, min, max, onChange }: { value: number; min: number; max: number; onChange: (n: number) => void; }) { const clamp = (n: number) => Math.max(min, Math.min(max, n)); return (
{ const n = parseInt(e.target.value.replace(/\D/g, ''), 10); onChange(clamp(Number.isNaN(n) ? min : n)); }} inputMode="numeric" />
); } /** * Create Shipment modal. Triggered by the "Create shipment" button in the * Items card header. Shape per the multi-shipment UI design pass * (wiki/log.md → "Multi-shipment admin UI refactor"): * * - Item picker rows — checkbox + thumbnail + name + "N of M available to * ship" or "Fully shipped" + qty stepper visible when checked. * - Carrier select + Tracking number input (2-col). * - Notify customer Switch row with subtitle "Email a shipment * confirmation with tracking details", default ON. Drives the * `notifyCustomer` flag on the createShipment payload — the * `shipment_created` event subscriber respects it. * - Footer: "N units across M items" summary + Cancel + Create shipment. * * No "Generate label" radio (the earlier review decided drop — no built-in * carrier implements createLabel today; extensions own that flow). * No "Tracking URL" or "ETA" inputs (the schema has no columns for those). */ export function NewShipmentDialog({ unshippedItems, carriers, defaultCarrierCode, createShipmentApi, onCreated }: { unshippedItems: UnshippedItem[]; carriers: Carrier[]; defaultCarrierCode: string | null; createShipmentApi: string; onCreated: () => void; }) { const isRegisteredHint = !!defaultCarrierCode && carriers.some((c) => c.code === defaultCarrierCode); const initialCarrier = isRegisteredHint ? (defaultCarrierCode as string) : carriers[0]?.code ?? ''; const [open, setOpen] = React.useState(false); const [carrier, setCarrier] = React.useState(initialCarrier); const [trackingNumber, setTrackingNumber] = React.useState(''); const [notifyCustomer, setNotifyCustomer] = React.useState(true); const [submitting, setSubmitting] = React.useState(false); const [draft, setDraft] = React.useState>(() => seedDraft(unshippedItems) ); // Re-seed the form ONLY when the dialog (re)opens — deliberately not on // unshippedItems/initialCarrier changes, which must not reset in-progress // edits while the dialog is open. (No eslint-disable: the react-hooks // plugin isn't registered in this repo's ESLint config, and a disable // comment for an unknown rule is itself a lint error.) React.useEffect(() => { if (!open) return; setDraft(seedDraft(unshippedItems)); setTrackingNumber(''); setNotifyCustomer(true); setCarrier(initialCarrier); }, [open]); const toggleLine = (orderItemId: number, checked: boolean) => setDraft((d) => ({ ...d, [orderItemId]: { ...d[orderItemId], checked } })); const setLineQty = (orderItemId: number, qty: number) => setDraft((d) => ({ ...d, [orderItemId]: { ...d[orderItemId], qty } })); const chosen = Object.values(draft).filter((d) => d.checked && d.qty > 0); const unitCount = chosen.reduce((n, d) => n + d.qty, 0); const itemCount = chosen.length; const canSubmit = chosen.length > 0; const selectedCarrier = carriers.find((c) => c.code === carrier); const showTrackingInput = hasTrackingCapability(selectedCarrier); const handleSubmit = async () => { if (!canSubmit) { toast.error(_('Select at least one item to ship')); return; } if (!carrier) { toast.error(_('Select a carrier')); return; } setSubmitting(true); try { await axios.post(createShipmentApi, { items: chosen.map((d) => ({ order_item_id: d.order_item_id, qty: d.qty })), carrier, ...(showTrackingInput && trackingNumber.trim() ? { tracking_number: trackingNumber.trim() } : {}), notifyCustomer }); toast.success(_('Shipment created')); setOpen(false); onCreated(); } catch (e) { const err = e as { response?: { data?: { error?: { message?: string } } }; }; toast.error( err.response?.data?.error?.message ?? _('Failed to create shipment') ); } finally { setSubmitting(false); } }; if (unshippedItems.length === 0) return null; // Row data — combine unshipped (selectable) with the rest of order_items? // For now the picker only shows unshippedItems since they're the only // valid options. Digital items don't appear in unshippedItems (the // resolver filters them), so we don't render the "Digital · no shipping" // tag here either — the design's locked-digital-row is informational // and isn't required for the create flow to be correct. Keep the visual // hook open via the `selectable` flag for when a future extension wants // to surface them. return ( {_('Create shipment')} } /> {_('Create shipment')} {_( 'Select the items going in this shipment, then add the carrier & tracking.' )}
{unshippedItems.map((item) => { const line = draft[item.orderItemId]; if (!line) return null; const selectable = item.qtyUnshipped > 0; return (
toggleLine(item.orderItemId, v)} />
{item.productName}
{selectable ? ( <> {item.qtyUnshipped} {_('of')} {item.qtyOrdered}{' '} {_('available to ship')} ) : ( {_('Fully shipped')} )}
{selectable && line.checked && ( setLineQty(item.orderItemId, q)} /> )}
); })}
{showTrackingInput && (
setTrackingNumber(e.target.value)} />
)}
{/* The text is a real
); } function seedDraft(items: UnshippedItem[]): Record { const out: Record = {}; for (const item of items) { out[item.orderItemId] = { order_item_id: item.orderItemId, qty: item.qtyUnshipped, checked: item.qtyUnshipped > 0 }; } return out; } function CheckboxBox({ checked, disabled, onChange }: { checked: boolean; disabled?: boolean; onChange: (v: boolean) => void; }) { return ( ); }