feat(warehouse): Receive Import/Export tabs with bulk receive + load-passed-export

- Backend: GET eligible-bookings?direction, POST receive-bulk, POST load-passed-export
  (reuse autoUnload/autoLoad patterns; no train-schedule/wagon logic changed)
- Frontend: ReceiveInventoryModal split into Import/Export tabs with eligible PAID
  bookings table, select-all/bulk receive, and Load Passed Export Items button
- Single-booking receive and all existing inventory row actions preserved

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Hagernesh
2026-06-20 08:29:59 +00:00
parent d7352ba4e8
commit 0005b2edb3
8 changed files with 632 additions and 88 deletions

View File

@@ -1,71 +1,66 @@
import { useEffect, useMemo, useState } from 'react';
import { Button, Group, Modal, NumberInput, Select, Stack, Textarea, TextInput } from '@mantine/core';
import {
Alert,
Badge,
Button,
Checkbox,
Group,
Loader,
Modal,
NumberInput,
Select,
Stack,
Table,
Tabs,
Text,
Textarea,
TextInput,
} from '@mantine/core';
import { Info, PackageSearch, Truck } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import {
useBulkReceive,
useEligibleBookings,
useLoadPassedExport,
useReceiveInventory,
useWarehouseYards,
useWarehouseZones,
useWarehouses,
} from '@/hooks/useWarehouses';
import type { ReceiveInventoryPayload } from '@/types/warehouse';
import type { BulkReceiveResult, LoadPassedExportResult, ReceiveInventoryPayload } from '@/types/warehouse';
import { BookingSelect } from './BookingSelect';
import { extractErrorMessage } from './options';
import { extractErrorMessage, formatNumber } from './options';
interface ReceiveInventoryModalProps {
opened: boolean;
onClose: () => void;
/** When supplied the booking field is locked to this booking. */
/** When supplied the modal locks to a single booking (legacy single-receive). */
bookingId?: string;
bookingLabel?: string;
onReceived?: () => void;
}
interface FormState {
bookingId: string;
interface Location {
warehouseId: string;
yardId: string;
zoneId: string;
quantity: number | '';
weight: number | '';
volume: number | '';
notes: string;
}
const emptyForm = (bookingId?: string): FormState => ({
bookingId: bookingId ?? '',
warehouseId: '',
yardId: '',
zoneId: '',
quantity: '',
weight: '',
volume: '',
notes: '',
});
export function ReceiveInventoryModal({
opened,
onClose,
bookingId,
bookingLabel,
onReceived,
}: ReceiveInventoryModalProps) {
const { toast } = useToast();
const receiveMutation = useReceiveInventory();
const [form, setForm] = useState<FormState>(emptyForm(bookingId));
useEffect(() => {
if (opened) setForm(emptyForm(bookingId));
}, [opened, bookingId]);
// Cascading data — only ACTIVE warehouses are selectable for receiving.
/** 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(form.warehouseId || undefined);
const zonesQuery = useWarehouseZones(form.yardId || undefined);
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 ?? []).map((w) => ({ value: w.id, label: `${w.name} (${w.code})` })),
[warehousesQuery.data],
);
const yardOptions = useMemo(
@@ -83,10 +78,307 @@ export function ReceiveInventoryModal({
[zonesQuery.data],
);
const submitting = receiveMutation.isPending;
return (
<Group grow align="flex-end">
<Select
label="Warehouse"
placeholder={warehousesQuery.isLoading ? 'Loading…' : 'Select warehouse'}
required
searchable
data={warehouseOptions}
value={value.warehouseId || null}
onChange={(v) => onChange({ warehouseId: v ?? '', yardId: '', zoneId: '' })}
/>
<Select
label="Yard"
placeholder={!value.warehouseId ? 'Select warehouse first' : 'Select yard'}
required
searchable
disabled={!value.warehouseId}
data={yardOptions}
value={value.yardId || null}
onChange={(v) => onChange({ ...value, yardId: v ?? '', zoneId: '' })}
/>
<Select
label="Zone"
placeholder={!value.yardId ? 'Select yard first' : 'Select zone'}
required
searchable
disabled={!value.yardId}
data={zoneOptions}
value={value.zoneId || null}
onChange={(v) => onChange({ ...value, zoneId: v ?? '' })}
/>
</Group>
);
}
/** 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: rows = [], isLoading } = useEligibleBookings(direction, enabled);
const bulkReceive = useBulkReceive();
const loadPassed = useLoadPassedExport();
const [selected, setSelected] = useState<Set<string>>(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`,
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 (
<Stack gap="sm" mt="sm">
<Group justify="space-between">
<Text size="sm" c="dimmed">
Selected: <b>{selected.size}</b> / {rows.length} eligible
</Text>
<Group gap="xs">
{direction === 'EXPORT' && (
<Button
size="compact-sm"
variant="light"
color="teal"
leftSection={<Truck size={14} />}
loading={loadPassed.isPending}
onClick={loadPassedExport}
>
Load Passed Export Items
</Button>
)}
<Button
size="compact-sm"
variant="default"
disabled={!locationReady || rows.length === 0}
loading={bulkReceive.isPending}
onClick={() => receive(rows.map((r) => r.id))}
>
Receive All Eligible
</Button>
<Button
size="compact-sm"
disabled={!locationReady || selected.size === 0}
loading={bulkReceive.isPending}
onClick={() => receive([...selected])}
>
Receive Selected
</Button>
</Group>
</Group>
{!locationReady && (
<Alert icon={<Info size={16} />} color="orange" variant="light">
<Text size="sm">Select a warehouse, yard and zone above before receiving.</Text>
</Alert>
)}
{isLoading ? (
<Group justify="center" py="lg">
<Loader size="sm" />
</Group>
) : rows.length === 0 ? (
<Text c="dimmed" ta="center" py="lg" size="sm">
No eligible PAID {direction.toLowerCase()} bookings to receive.
</Text>
) : (
<Table.ScrollContainer minWidth={900}>
<Table highlightOnHover verticalSpacing="xs" striped>
<Table.Thead>
<Table.Tr>
<Table.Th w={40}>
<Checkbox
aria-label="Select all"
checked={allSelected}
indeterminate={someSelected}
onChange={toggleAll}
/>
</Table.Th>
<Table.Th>Booking</Table.Th>
<Table.Th>Customer</Table.Th>
<Table.Th>Origin</Table.Th>
<Table.Th>Destination</Table.Th>
<Table.Th>Freight</Table.Th>
<Table.Th>Cargo</Table.Th>
<Table.Th>Weight</Table.Th>
<Table.Th>Payment</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{rows.map((r) => (
<Table.Tr key={r.id}>
<Table.Td>
<Checkbox
aria-label={`Select ${r.reference}`}
checked={selected.has(r.id)}
onChange={() => toggleOne(r.id)}
/>
</Table.Td>
<Table.Td>
<Text size="sm" fw={600}>
{r.reference}
</Text>
</Table.Td>
<Table.Td>{r.customer ?? '—'}</Table.Td>
<Table.Td>{r.origin ?? '—'}</Table.Td>
<Table.Td>{r.destination ?? '—'}</Table.Td>
<Table.Td>{r.freightType ?? '—'}</Table.Td>
<Table.Td>{r.cargo ?? '—'}</Table.Td>
<Table.Td>{formatNumber(Number(r.weight))}</Table.Td>
<Table.Td>
<Badge color="green" variant="light" size="sm">
{r.paymentStatus}
</Badge>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
</Table.ScrollContainer>
)}
</Stack>
);
}
/** New bulk Receive: Import / Export tabs with eligible PAID bookings. */
function BulkReceiveModal({ opened, onClose, onReceived }: ReceiveInventoryModalProps) {
const [location, setLocation] = useState<Location>({ warehouseId: '', yardId: '', zoneId: '' });
const [tab, setTab] = useState<'IMPORT' | 'EXPORT'>('IMPORT');
useEffect(() => {
if (opened) setLocation({ warehouseId: '', yardId: '', zoneId: '' });
}, [opened]);
return (
<Modal opened={opened} onClose={onClose} title="Receive at warehouse" centered size="80rem">
<Stack gap="md">
<LocationSelects value={location} onChange={setLocation} />
<Tabs value={tab} onChange={(v) => setTab((v as 'IMPORT' | 'EXPORT') ?? 'IMPORT')}>
<Tabs.List>
<Tabs.Tab value="IMPORT" leftSection={<PackageSearch size={16} />}>
Import
</Tabs.Tab>
<Tabs.Tab value="EXPORT" leftSection={<Truck size={16} />}>
Export
</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value="IMPORT">
<EligibleTab direction="IMPORT" location={location} enabled={opened} onChanged={onReceived} />
</Tabs.Panel>
<Tabs.Panel value="EXPORT">
<EligibleTab direction="EXPORT" location={location} enabled={opened} onChanged={onReceived} />
</Tabs.Panel>
</Tabs>
<Group justify="flex-end" mt="sm">
<Button variant="default" onClick={onClose}>
Close
</Button>
</Group>
</Stack>
</Modal>
);
}
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<SingleFormState>({
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 (!form.bookingId.trim()) {
if (!selectedBooking.trim()) {
toast({ variant: 'destructive', title: 'Booking is required' });
return;
}
@@ -98,9 +390,8 @@ export function ReceiveInventoryModal({
toast({ variant: 'destructive', title: 'Quantity and weight are required' });
return;
}
const payload: ReceiveInventoryPayload = {
bookingId: form.bookingId.trim(),
bookingId: selectedBooking.trim(),
warehouseId: form.warehouseId,
yardId: form.yardId,
zoneId: form.zoneId,
@@ -109,10 +400,9 @@ export function ReceiveInventoryModal({
volume: form.volume === '' ? undefined : Number(form.volume),
notes: form.notes.trim() || undefined,
};
try {
await receiveMutation.mutateAsync(payload);
toast({ title: 'Inventory received', description: 'Status set to ARRIVED_AT_WAREHOUSE' });
toast({ title: 'Inventory received' });
onReceived?.();
onClose();
} catch (error) {
@@ -126,46 +416,10 @@ export function ReceiveInventoryModal({
{bookingId ? (
<TextInput label="Booking" value={bookingLabel ?? bookingId} readOnly />
) : (
<BookingSelect
label="Booking"
value={form.bookingId}
onChange={(v) => setForm((f) => ({ ...f, bookingId: v }))}
/>
<BookingSelect label="Booking" value={selectedBooking} onChange={setSelectedBooking} />
)}
<Select
label="Warehouse"
placeholder={warehousesQuery.isLoading ? 'Loading…' : 'Select warehouse'}
required
searchable
data={warehouseOptions}
value={form.warehouseId || null}
onChange={(value) =>
setForm((f) => ({ ...f, warehouseId: value ?? '', yardId: '', zoneId: '' }))
}
/>
<Select
label="Yard"
placeholder={!form.warehouseId ? 'Select a warehouse first' : 'Select yard'}
required
searchable
disabled={!form.warehouseId}
data={yardOptions}
value={form.yardId || null}
onChange={(value) => setForm((f) => ({ ...f, yardId: value ?? '', zoneId: '' }))}
/>
<Select
label="Zone"
placeholder={!form.yardId ? 'Select a yard first' : 'Select zone'}
required
searchable
disabled={!form.yardId}
data={zoneOptions}
value={form.zoneId || null}
onChange={(value) => setForm((f) => ({ ...f, zoneId: value ?? '' }))}
/>
<LocationSelects value={location} onChange={(next) => setForm((f) => ({ ...f, ...next }))} />
<Group grow>
<NumberInput
@@ -197,14 +451,17 @@ export function ReceiveInventoryModal({
autosize
minRows={2}
value={form.notes}
onChange={(e) => { const v = e.currentTarget.value; setForm((f) => ({ ...f, notes: v })); }}
onChange={(e) => {
const v = e.currentTarget.value;
setForm((f) => ({ ...f, notes: v }));
}}
/>
<Group justify="flex-end" mt="sm">
<Button variant="default" onClick={onClose} disabled={submitting}>
<Button variant="default" onClick={onClose} disabled={receiveMutation.isPending}>
Cancel
</Button>
<Button onClick={handleSubmit} loading={submitting}>
<Button onClick={handleSubmit} loading={receiveMutation.isPending}>
Receive inventory
</Button>
</Group>
@@ -212,3 +469,8 @@ export function ReceiveInventoryModal({
</Modal>
);
}
export function ReceiveInventoryModal(props: ReceiveInventoryModalProps) {
// Locked to a booking → legacy single receive; otherwise the Import/Export bulk flow.
return props.bookingId ? <SingleBookingReceiveModal {...props} /> : <BulkReceiveModal {...props} />;
}

View File

@@ -306,6 +306,10 @@ export const URL_CONSTANTS = {
MARK_READY_PICKUP: (id: string) => `/warehouse-inventory/${id}/ready-for-pickup`,
RELEASE: (id: string) => `/warehouse-inventory/${id}/release`,
DELIVER: (id: string) => `/warehouse-inventory/${id}/deliver`,
// Receive (Import/Export bulk)
ELIGIBLE_BOOKINGS: (direction: string) => `/warehouse-inventory/eligible-bookings?direction=${direction}`,
RECEIVE_BULK: '/warehouse-inventory/receive-bulk',
LOAD_PASSED_EXPORT: '/warehouse-inventory/load-passed-export',
},
WAREHOUSE_LOADINGS: {

View File

@@ -14,6 +14,7 @@ import type {
ReceiveInventoryPayload,
ReleaseOrderPayload,
DeliverInventoryPayload,
BulkReceivePayload,
ReserveInventoryPayload,
SaveWarehousePayload,
SaveYardPayload,
@@ -186,6 +187,19 @@ export const useDeliverInventory = () =>
warehouseService.deliver(args.id, args.payload),
);
// ── Receive (Import/Export bulk) ───────────────────────────────────────────
export function useEligibleBookings(direction: 'IMPORT' | 'EXPORT', enabled = true) {
return useQuery({
queryKey: ['warehouse-inventory', 'eligible-bookings', direction],
queryFn: () => warehouseService.eligibleBookings(direction).then((r) => r.data),
enabled,
});
}
export const useBulkReceive = () =>
useInventoryMutation((payload: BulkReceivePayload) => warehouseService.receiveBulk(payload));
export const useLoadPassedExport = () =>
useInventoryMutation(() => warehouseService.loadPassedExport());
// ── Loading (Batch 3) ────────────────────────────────────────────────────────
export function useLoadableWagons(enabled = true) {

View File

@@ -29,6 +29,10 @@ import type {
ReceiveInventoryPayload,
ReleaseOrderPayload,
DeliverInventoryPayload,
EligibleBooking,
BulkReceivePayload,
BulkReceiveResult,
LoadPassedExportResult,
ReserveInventoryPayload,
SaveWarehousePayload,
SaveYardPayload,
@@ -114,6 +118,14 @@ export const warehouseService = {
apiClient.post<WarehouseInventoryItem>(URL_CONSTANTS.WAREHOUSE_INVENTORY.RELEASE(id), payload),
deliver: (id: string, payload: DeliverInventoryPayload) =>
apiClient.post<WarehouseInventoryItem>(URL_CONSTANTS.WAREHOUSE_INVENTORY.DELIVER(id), payload),
// ── Receive (Import/Export bulk) ─────────────────────────────────────────
eligibleBookings: (direction: 'IMPORT' | 'EXPORT') =>
apiClient.get<EligibleBooking[]>(URL_CONSTANTS.WAREHOUSE_INVENTORY.ELIGIBLE_BOOKINGS(direction)),
receiveBulk: (payload: BulkReceivePayload) =>
apiClient.post<BulkReceiveResult>(URL_CONSTANTS.WAREHOUSE_INVENTORY.RECEIVE_BULK, payload),
loadPassedExport: () =>
apiClient.post<LoadPassedExportResult>(URL_CONSTANTS.WAREHOUSE_INVENTORY.LOAD_PASSED_EXPORT, {}),
move: (id: string, payload: MoveInventoryPayload) =>
apiClient.post<WarehouseInventoryItem>(URL_CONSTANTS.WAREHOUSE_INVENTORY.MOVE(id), payload),
movements: (id: string) =>

View File

@@ -332,6 +332,41 @@ export interface DeliverInventoryPayload {
remarks?: string;
}
/** Receive (Import/Export) bulk flow. */
export interface EligibleBooking {
id: string;
reference: string;
customer: string | null;
direction: string;
origin: string | null;
destination: string | null;
freightType: string | null;
cargo: string | null;
weight: string | null;
paymentStatus: string;
status: string;
}
export interface BulkReceivePayload {
direction: 'IMPORT' | 'EXPORT';
warehouseId: string;
yardId: string;
zoneId: string;
bookingIds: string[];
}
export interface BulkReceiveResult {
receivedCount: number;
skippedCount: number;
results: { bookingId: string; status: string; inventoryId?: string; reason?: string }[];
}
export interface LoadPassedExportResult {
loadedCount: number;
skippedCount: number;
results: { inventoryId: string; status: string; reason?: string }[];
}
export interface InventoryInquiryResult {
id: string;
bookingId: string;