import { Fragment, useEffect, useMemo, useState } from 'react';
import {
Alert,
Badge,
Button,
Checkbox,
Group,
Loader,
Modal,
NumberInput,
Select,
Stack,
Table,
Tabs,
Text,
Textarea,
TextInput,
} from '@mantine/core';
import { ChevronDown, ChevronRight, ClipboardCheck, Info, PackageSearch, Train, Truck } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import {
useAutoUnloadArrivedBookings,
useBulkDispatchExport,
useBulkMarkInspected,
useBulkReceive,
useEligibleBookings,
useImportArriveQueue,
useImportTrainItems,
useImportUnloadedQueue,
useLoadPassedExport,
useLoadedExport,
useReadyToLoadExport,
useReceiveInventory,
useWarehouseInventory,
useWarehouseYards,
useWarehouseZones,
useWarehouses,
} from '@/hooks/useWarehouses';
import type {
AutoUnloadArrivedResult,
BulkDispatchResult,
BulkInspectResult,
BulkReceiveResult,
ImportTrain,
ImportTrainItem,
ImportUnloadedItem,
LoadPassedExportResult,
ReadyToLoadRow,
ReceiveInventoryPayload,
} from '@/types/warehouse';
import { BookingSelect } from './BookingSelect';
import { InspectionReportModal } from './InspectionReportModal';
import { InventoryWorkbench } from './InventoryWorkbench';
import { extractErrorMessage, formatDate, formatNumber } from './options';
interface ReceiveInventoryModalProps {
opened: boolean;
onClose: () => void;
/** When supplied the modal locks to a single booking (legacy single-receive). */
bookingId?: string;
bookingLabel?: string;
onReceived?: () => void;
}
interface Location {
warehouseId: string;
yardId: string;
zoneId: string;
}
/** Cascading Warehouse → Yard → Zone selectors (ACTIVE only). */
function LocationSelects({
value,
onChange,
}: {
value: Location;
onChange: (next: Location) => void;
}) {
const warehousesQuery = useWarehouses({ status: 'ACTIVE' });
const yardsQuery = useWarehouseYards(value.warehouseId || undefined);
const zonesQuery = useWarehouseZones(value.yardId || undefined);
const warehouseOptions = useMemo(
() => (warehousesQuery.data ?? []).map((w) => ({ value: w.id, label: `${w.name} (${w.code})` })),
[warehousesQuery.data],
);
const yardOptions = useMemo(
() =>
(yardsQuery.data ?? [])
.filter((y) => y.status === 'ACTIVE')
.map((y) => ({ value: y.id, label: `${y.name} (${y.code})` })),
[yardsQuery.data],
);
const zoneOptions = useMemo(
() =>
(zonesQuery.data ?? [])
.filter((z) => z.status === 'ACTIVE')
.map((z) => ({ value: z.id, label: `${z.name} (${z.code})` })),
[zonesQuery.data],
);
return (
);
}
/** One tab: eligible PAID bookings for a direction, with bulk receive (+ export load). */
function EligibleTab({
direction,
location,
enabled,
onChanged,
}: {
direction: 'IMPORT' | 'EXPORT';
location: Location;
enabled: boolean;
onChanged?: () => void;
}) {
const { toast } = useToast();
const { data: allRows = [], isLoading } = useEligibleBookings(enabled);
const rows = useMemo(() => allRows.filter((r) => r.direction === direction), [allRows, direction]);
const bulkReceive = useBulkReceive();
const loadPassed = useLoadPassedExport();
const [selected, setSelected] = useState>(new Set());
const locationReady = Boolean(location.warehouseId && location.yardId && location.zoneId);
const allSelected = rows.length > 0 && selected.size === rows.length;
const someSelected = selected.size > 0 && !allSelected;
const toggleAll = () =>
setSelected(allSelected ? new Set() : new Set(rows.map((r) => r.id)));
const toggleOne = (id: string) =>
setSelected((prev) => {
const next = new Set(prev);
next.has(id) ? next.delete(id) : next.add(id);
return next;
});
const receive = async (bookingIds: string[]) => {
if (!locationReady) {
toast({ variant: 'destructive', title: 'Select warehouse, yard and zone first' });
return;
}
if (bookingIds.length === 0) {
toast({ variant: 'destructive', title: 'Select at least one booking' });
return;
}
try {
const res = (await bulkReceive.mutateAsync({ direction, ...location, bookingIds })) as {
data: BulkReceiveResult;
};
const r = res.data;
toast({
title: `${r.receivedCount} received at ${direction === 'EXPORT' ? 'facility' : 'warehouse'}`,
description: r.skippedCount ? `${r.skippedCount} skipped` : undefined,
});
setSelected(new Set());
onChanged?.();
} catch (error) {
toast({ variant: 'destructive', title: 'Receive failed', description: extractErrorMessage(error) });
}
};
const loadPassedExport = async () => {
try {
const res = (await loadPassed.mutateAsync(undefined)) as { data: LoadPassedExportResult };
const r = res.data;
toast({
title: `${r.loadedCount} loaded`,
description: r.skippedCount ? `${r.skippedCount} skipped — inspection not passed` : undefined,
});
onChanged?.();
} catch (error) {
toast({ variant: 'destructive', title: 'Load failed', description: extractErrorMessage(error) });
}
};
return (
Selected: {selected.size} / {rows.length} eligible
{direction === 'EXPORT' && (
}
loading={loadPassed.isPending}
onClick={loadPassedExport}
>
Load Passed Export Items
)}
{!locationReady && (
} color="orange" variant="light">
Select a warehouse, yard and zone above before receiving.
)}
{isLoading ? (
) : rows.length === 0 ? (
No eligible PAID {direction.toLowerCase()} bookings to receive.
) : (
Booking Ref
Booking ID
Customer ID
Customer Name
Origin
Destination
Route
Container #
Cargo Type
Weight
Payment
Current Status
Inspection
Actions
{rows.map((r) => (
toggleOne(r.id)}
/>
{r.reference}
{r.id.slice(0, 8)}…
{r.customerId ? `${r.customerId.slice(0, 8)}…` : '—'}
{r.customer ?? '—'}
{r.origin ?? '—'}
{r.destination ?? '—'}
{r.origin || r.destination ? `${r.origin ?? '?'} → ${r.destination ?? '?'}` : '—'}
—
{r.cargo ?? '—'}
{formatNumber(Number(r.weight))}
{r.paymentStatus}
{r.status ?? '—'}
—
))}
)}
);
}
/** Export items that passed inspection and are queued to be loaded onto a train. */
function ReadyToLoadTab({ enabled, onChanged }: { enabled: boolean; onChanged?: () => void }) {
const { toast } = useToast();
const { data: rows = [], isLoading } = useReadyToLoadExport(enabled);
const loadPassed = useLoadPassedExport();
const [selected, setSelected] = useState>(new Set());
const allSelected = rows.length > 0 && selected.size === rows.length;
const someSelected = selected.size > 0 && !allSelected;
const toggleAll = () => setSelected(allSelected ? new Set() : new Set(rows.map((r) => r.id)));
const toggleOne = (id: string) =>
setSelected((prev) => {
const next = new Set(prev);
next.has(id) ? next.delete(id) : next.add(id);
return next;
});
const autoLoad = async () => {
try {
const res = (await loadPassed.mutateAsync(undefined)) as { data: LoadPassedExportResult };
const r = res.data;
toast({
title: `${r.loadedCount} items loaded`,
description: r.skippedCount ? `${r.skippedCount} skipped` : undefined,
});
setSelected(new Set());
onChanged?.();
} catch (error) {
toast({ variant: 'destructive', title: 'Load failed', description: extractErrorMessage(error) });
}
};
return (
{rows.length} item{rows.length !== 1 ? 's' : ''} ready to load
}
loading={loadPassed.isPending}
disabled={rows.length === 0}
onClick={autoLoad}
>
Auto Load Ready Items
{isLoading ? (
) : rows.length === 0 ? (
No EXPORT items with inspection PASSED waiting to be loaded.
) : (
Booking Ref
Booking ID
Customer ID
Customer Name
Container #
Cargo Type
Weight
Route
Inspection
Status
{rows.map((r: ReadyToLoadRow) => (
toggleOne(r.id)}
/>
{r.bookingReference ?? '—'}
{r.bookingId ? `${r.bookingId.slice(0, 8)}…` : '—'}
{r.customerId ? `${r.customerId.slice(0, 8)}…` : '—'}
{r.customerName ?? '—'}
{r.containerNumber ?? '—'}
{r.cargoType ?? '—'}
{formatNumber(Number(r.weight))}
{r.origin || r.destination ? `${r.origin ?? '?'} → ${r.destination ?? '?'}` : '—'}
{r.inspectionStatus ?? '—'}
{r.status}
))}
)}
);
}
/**
* Export items that are LOADED onto a wagon. Serves both the "Loaded" tab (read-only)
* and the "Dispatch Queue" tab (dispatchable=true → selection + Dispatch actions).
*/
function LoadedExportTab({
enabled,
dispatchable,
onChanged,
}: {
enabled: boolean;
dispatchable: boolean;
onChanged?: () => void;
}) {
const { toast } = useToast();
const { data: rows = [], isLoading } = useLoadedExport(enabled);
const bulkDispatch = useBulkDispatchExport();
const [selected, setSelected] = useState>(new Set());
const allSelected = rows.length > 0 && selected.size === rows.length;
const someSelected = selected.size > 0 && !allSelected;
const toggleAll = () => setSelected(allSelected ? new Set() : new Set(rows.map((r) => r.id)));
const toggleOne = (id: string) =>
setSelected((prev) => {
const next = new Set(prev);
next.has(id) ? next.delete(id) : next.add(id);
return next;
});
const dispatch = async (inventoryIds: string[]) => {
if (inventoryIds.length === 0) {
toast({ variant: 'destructive', title: 'Select at least one item' });
return;
}
try {
const res = (await bulkDispatch.mutateAsync(inventoryIds)) as { data: BulkDispatchResult };
const r = res.data;
toast({
title: `${r.dispatchedCount} dispatched`,
description: r.skippedCount ? `${r.skippedCount} skipped` : undefined,
});
setSelected(new Set());
onChanged?.();
} catch (error) {
toast({ variant: 'destructive', title: 'Dispatch failed', description: extractErrorMessage(error) });
}
};
return (
{dispatchable ? (
<>
Selected: {selected.size} / {rows.length} loaded
>
) : (
<>
{rows.length} item{rows.length !== 1 ? 's' : ''} loaded
>
)}
{dispatchable && (
}
disabled={selected.size === 0}
loading={bulkDispatch.isPending}
onClick={() => dispatch([...selected])}
>
Dispatch Selected
)}
{isLoading ? (
) : rows.length === 0 ? (
No LOADED export items {dispatchable ? 'waiting to dispatch' : 'yet'}.
) : (
{dispatchable && (
)}
Booking Ref
Booking ID
Customer ID
Customer Name
Container #
Cargo Type
Weight
Route
Status
{dispatchable && Actions}
{rows.map((r: ReadyToLoadRow) => (
{dispatchable && (
toggleOne(r.id)}
/>
)}
{r.bookingReference ?? '—'}
{r.bookingId ? `${r.bookingId.slice(0, 8)}…` : '—'}
{r.customerId ? `${r.customerId.slice(0, 8)}…` : '—'}
{r.customerName ?? '—'}
{r.containerNumber ?? '—'}
{r.cargoType ?? '—'}
{formatNumber(Number(r.weight))}
{r.origin || r.destination ? `${r.origin ?? '?'} → ${r.destination ?? '?'}` : '—'}
{r.status}
{dispatchable && (
)}
))}
)}
);
}
/** Assigned bookings/items for an arrived import train (read-only detail view). */
function ImportTrainDetailTable({ scheduleId }: { scheduleId: string }) {
const { data: items = [], isLoading } = useImportTrainItems(scheduleId);
if (isLoading) {
return (
);
}
if (items.length === 0) {
return (
No assigned bookings on this train.
);
}
return (
Booking ID
Booking Ref
Customer ID
Customer Name
Container #
Cargo Type
Weight
Arrival
Current Status
Last Mile
Pickup Option
{items.map((it: ImportTrainItem) => (
{it.bookingId.slice(0, 8)}…
{it.bookingReference ?? '—'}
{it.customerId ? `${it.customerId.slice(0, 8)}…` : '—'}
{it.customerName ?? '—'}
{it.containerNumber ?? '—'}
{it.cargoType ?? '—'}
{formatNumber(Number(it.weight))}
{formatDate(it.arrivalTime)}
{it.currentStatus ?? '—'}
{it.lastMileRequested ? 'Yes' : 'No'}
{it.pickupOption}
))}
);
}
/** Import Arrive Queue: arrived IMPORT trains, with Open (detail) + Auto Unload per train. */
function ImportArriveQueueTab({
enabled,
onChanged,
}: {
enabled: boolean;
onChanged?: () => void;
}) {
const { toast } = useToast();
const { data: trains = [], isLoading } = useImportArriveQueue(enabled);
const autoUnloadMutation = useAutoUnloadArrivedBookings();
const [openId, setOpenId] = useState(null);
const [busyId, setBusyId] = useState(null);
const autoUnload = async (train: ImportTrain) => {
setBusyId(train.scheduleId);
try {
const res = (await autoUnloadMutation.mutateAsync(train.scheduleId)) as {
data: AutoUnloadArrivedResult;
};
const r = res.data;
const extra = [
r.skippedCount ? `${r.skippedCount} skipped` : '',
r.failedCount ? `${r.failedCount} failed` : '',
]
.filter(Boolean)
.join(', ');
toast({
title: `${r.unloadedCount} unloaded`,
description: extra || undefined,
});
onChanged?.();
} catch (error) {
toast({ variant: 'destructive', title: 'Auto unload failed', description: extractErrorMessage(error) });
} finally {
setBusyId(null);
}
};
return (
{trains.length} arrived import train{trains.length !== 1 ? 's' : ''}
{isLoading ? (
) : trains.length === 0 ? (
No arrived import trains. Trains appear here once their schedule status is ARRIVED.
) : (
Schedule ID
Train #
Route
Origin
Destination
Arrival Time
Bookings
Containers
Cargoes
Status
Actions
{trains.map((t: ImportTrain) => {
const isOpen = openId === t.scheduleId;
return (
{t.scheduleId.slice(0, 8)}…
{t.trainNumber ?? '—'}
{t.route ?? '—'}
{t.origin ?? '—'}
{t.destination ?? '—'}
{formatDate(t.arrivalTime)}
{t.totalBookings}
{t.totalContainers}
{t.totalCargoes}
{t.status}
: }
onClick={() => setOpenId(isOpen ? null : t.scheduleId)}
>
Open
}
loading={busyId === t.scheduleId}
onClick={() => autoUnload(t)}
>
Auto Unload Arrived Bookings
{isOpen && (
)}
);
})}
)}
);
}
/**
* Import Unloaded Queue (Batch 9): all unloaded import items with the destination-inspection columns.
* Multi-select + Mark Selected as Inspected (import passed → READY_FOR_PICKUP), and the per-item
* Inspect / Report action stays for damage / images / weight-loss detail.
*/
function ImportUnloadedQueueTab({ enabled }: { enabled: boolean }) {
const { toast } = useToast();
const { data: rows = [], isLoading } = useImportUnloadedQueue(enabled);
const inspectMutation = useBulkMarkInspected();
const [selected, setSelected] = useState>(new Set());
const [inspectId, setInspectId] = useState(null);
const allSelected = rows.length > 0 && selected.size === rows.length;
const someSelected = selected.size > 0 && !allSelected;
const selectAll = () => setSelected(new Set(rows.map((r) => r.id)));
const unselectAll = () => setSelected(new Set());
const toggleOne = (id: string) =>
setSelected((prev) => {
const next = new Set(prev);
next.has(id) ? next.delete(id) : next.add(id);
return next;
});
const markInspected = async () => {
if (selected.size === 0) {
toast({ variant: 'destructive', title: 'Select at least one item' });
return;
}
try {
const res = (await inspectMutation.mutateAsync({ inventoryIds: [...selected] })) as {
data: BulkInspectResult;
};
const r = res.data;
toast({
title: `${r.inspectedCount} marked inspected`,
description: r.skippedCount ? `${r.skippedCount} skipped` : undefined,
});
setSelected(new Set());
} catch (error) {
toast({ variant: 'destructive', title: 'Mark inspected failed', description: extractErrorMessage(error) });
}
};
return (
Selected: {selected.size} / {rows.length} unloaded
}
disabled={selected.size === 0}
loading={inspectMutation.isPending}
onClick={markInspected}
>
Mark Selected as Inspected
{isLoading ? (
) : rows.length === 0 ? (
No unloaded import items. Items appear here after Auto Unload on an arrived train.
) : (
(allSelected ? unselectAll() : selectAll())}
/>
Booking ID
Booking Ref
Customer ID
Customer Name
Arrival Time
Container #
Cargo Type
Weight
Train Schedule
Inspection
Pickup Option
Last Mile
Current Status
Actions
{rows.map((r: ImportUnloadedItem) => (
toggleOne(r.id)}
/>
{r.bookingId ? `${r.bookingId.slice(0, 8)}…` : '—'}
{r.bookingReference ?? '—'}
{r.customerId ? `${r.customerId.slice(0, 8)}…` : '—'}
{r.customerName ?? '—'}
{formatDate(r.arrivalTime)}
{r.containerNumber ?? '—'}
{r.cargoType ?? '—'}
{formatNumber(Number(r.weight))}
{r.trainSchedule ?? '—'}
{r.inspectionStatus ?? 'Not inspected'}
{r.pickupOption}
{r.lastMileRequested ? 'Yes' : 'No'}
{r.currentStatus}
))}
)}
setInspectId(null)}
inventoryId={inspectId}
/>
);
}
/**
* Import Dispatch Queue (Batch 10): inspected import items that are PICKUP_READY (READY_FOR_PICKUP),
* awaiting Customer Pickup (release → deliver), Store, or Dispatch. Reuses InventoryWorkbench so all
* existing actions + modals stay intact; Last Mile shows only when the booking requested door delivery.
* Nothing is stored automatically — Store is an explicit operator action.
*/
function ImportDispatchQueueTab({ enabled }: { enabled: boolean }) {
const { toast } = useToast();
const { data: items = [], isLoading } = useWarehouseInventory(
enabled ? { status: 'READY_FOR_PICKUP' } : undefined,
);
return (
{items.length} pickup-ready item{items.length !== 1 ? 's' : ''}
toast({
title: 'Last mile delivery',
description: `Door delivery for ${it.booking?.reference ?? it.id} — handled in the next batch.`,
})
}
/>
);
}
/** New bulk Receive: Import / Export tabs with eligible PAID bookings. */
function BulkReceiveModal({ opened, onClose, onReceived }: ReceiveInventoryModalProps) {
const [location, setLocation] = useState({ warehouseId: '', yardId: '', zoneId: '' });
const [tab, setTab] = useState<'IMPORT' | 'EXPORT'>('IMPORT');
useEffect(() => {
if (opened) setLocation({ warehouseId: '', yardId: '', zoneId: '' });
}, [opened]);
return (
setTab((v as 'IMPORT' | 'EXPORT') ?? 'IMPORT')}>
}>
Import
}>
Export
}>
Arrive Queue
Unloaded Queue
Dispatch Queue
Receive Queue
Ready To Load
Loaded
Dispatch Queue
);
}
interface SingleFormState {
warehouseId: string;
yardId: string;
zoneId: string;
quantity: number | '';
weight: number | '';
volume: number | '';
notes: string;
}
/** Legacy single-booking receive — used when a specific bookingId is supplied. */
function SingleBookingReceiveModal({
opened,
onClose,
bookingId,
bookingLabel,
onReceived,
}: ReceiveInventoryModalProps) {
const { toast } = useToast();
const receiveMutation = useReceiveInventory();
const [selectedBooking, setSelectedBooking] = useState(bookingId ?? '');
const [form, setForm] = useState({
warehouseId: '',
yardId: '',
zoneId: '',
quantity: '',
weight: '',
volume: '',
notes: '',
});
useEffect(() => {
if (opened) {
setSelectedBooking(bookingId ?? '');
setForm({ warehouseId: '', yardId: '', zoneId: '', quantity: '', weight: '', volume: '', notes: '' });
}
}, [opened, bookingId]);
const location: Location = { warehouseId: form.warehouseId, yardId: form.yardId, zoneId: form.zoneId };
const handleSubmit = async () => {
if (!selectedBooking.trim()) {
toast({ variant: 'destructive', title: 'Booking is required' });
return;
}
if (!form.warehouseId || !form.yardId || !form.zoneId) {
toast({ variant: 'destructive', title: 'Select warehouse, yard and zone' });
return;
}
if (form.quantity === '' || form.weight === '') {
toast({ variant: 'destructive', title: 'Quantity and weight are required' });
return;
}
const payload: ReceiveInventoryPayload = {
bookingId: selectedBooking.trim(),
warehouseId: form.warehouseId,
yardId: form.yardId,
zoneId: form.zoneId,
quantity: Number(form.quantity),
weight: Number(form.weight),
volume: form.volume === '' ? undefined : Number(form.volume),
notes: form.notes.trim() || undefined,
};
try {
await receiveMutation.mutateAsync(payload);
toast({ title: 'Inventory received' });
onReceived?.();
onClose();
} catch (error) {
toast({ variant: 'destructive', title: 'Receive failed', description: extractErrorMessage(error) });
}
};
return (
{bookingId ? (
) : (
)}
setForm((f) => ({ ...f, ...next }))} />
setForm((f) => ({ ...f, quantity: value === '' ? '' : Number(value) }))}
/>
setForm((f) => ({ ...f, weight: value === '' ? '' : Number(value) }))}
/>
setForm((f) => ({ ...f, volume: value === '' ? '' : Number(value) }))}
/>
);
}
export function ReceiveInventoryModal(props: ReceiveInventoryModalProps) {
// Locked to a booking → legacy single receive; otherwise the Import/Export bulk flow.
return props.bookingId ? : ;
}