feat(warehouse): Batch 6 — Export Loaded queue + Dispatch Queue with bulk dispatch

- GET /warehouse-inventory/loaded-export: EXPORT+LOADED items (route-derived direction)
- POST /warehouse-inventory/bulk-dispatch-export: reuses existing dispatch() transition
  (LOADED → DISPATCHED, capacity freed, movement/activity logged); skips non-LOADED/non-EXPORT
- Extracted shared exportInventoryByStatus() helper (readyToLoadExport now delegates to it)
- Frontend LoadedExportTab serves both Loaded (read-only) and Dispatch Queue (dispatchable)
  sub-tabs with Dispatch / Dispatch Selected / Dispatch All + per-row Dispatch
- Replaces "Loaded" and "Dispatch Queue — coming in the next batch" placeholders
- Train/schedule flow (DISPATCHED → IN_TRANSIT) unchanged

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Hagernesh
2026-06-20 20:04:18 +00:00
parent 43ba3c790b
commit 0ab508e377
7 changed files with 282 additions and 11 deletions

View File

@@ -84,6 +84,18 @@ export class WarehouseInventoryController {
return this.inventoryService.readyToLoadExport();
}
@Get('loaded-export')
@ApiOperation({ summary: 'EXPORT inventory that is LOADED and queued for dispatch' })
loadedExport() {
return this.inventoryService.loadedExport();
}
@Post('bulk-dispatch-export')
@ApiOperation({ summary: 'Bulk-dispatch loaded EXPORT inventory (LOADED → DISPATCHED)' })
bulkDispatchExport(@Body() dto: { inventoryIds: string[]; performedBy?: string }) {
return this.inventoryService.bulkDispatchExport(dto.inventoryIds ?? [], dto.performedBy);
}
@Post('bulk-mark-inspected')
@ApiOperation({ summary: 'Bulk mark received inventory inspection PASSED (EXPORT → READY_FOR_LOADING)' })
bulkMarkInspected(@Body() dto: BulkInspectDto) {

View File

@@ -169,6 +169,12 @@ export interface ReadyToLoadRow {
status: string;
}
export interface BulkDispatchResult {
dispatchedCount: number;
skippedCount: number;
results: { inventoryId: string; status: string; reason?: string }[];
}
@Injectable()
export class WarehouseInventoryService {
constructor(
@@ -616,8 +622,11 @@ export class WarehouseInventoryService {
return result;
}
/** EXPORT inventory that passed inspection and is waiting to be loaded (READY_FOR_LOADING). */
async readyToLoadExport(): Promise<ReadyToLoadRow[]> {
/** EXPORT inventory rows at a given status (route-derived direction), with booking detail. */
private async exportInventoryByStatus(
status: WarehouseInventoryStatus,
requireInspectionPassed = false,
): Promise<ReadyToLoadRow[]> {
const rows: Array<
ReadyToLoadRow & { originCountry: string | null; destinationCountry: string | null }
> = await this.dataSource.query(
@@ -643,9 +652,10 @@ export class WarehouseInventoryService {
LEFT JOIN freight.cargo_types cgt ON cgt.id = b.cargo_type_id
LEFT JOIN freight.containers ct ON ct.id = inv.container_id
WHERE inv.deleted_at IS NULL
AND inv.status = 'READY_FOR_LOADING'
AND inv.inspection_status = 'PASSED'
AND inv.status = $1
${requireInspectionPassed ? `AND inv.inspection_status = 'PASSED'` : ''}
ORDER BY inv.created_at DESC`,
[status],
);
return rows
@@ -656,6 +666,48 @@ export class WarehouseInventoryService {
.map(({ originCountry: _oc, destinationCountry: _dc, ...rest }) => rest);
}
/** EXPORT inventory that passed inspection and is waiting to be loaded (READY_FOR_LOADING). */
async readyToLoadExport(): Promise<ReadyToLoadRow[]> {
return this.exportInventoryByStatus('READY_FOR_LOADING', true);
}
/** EXPORT inventory that has been loaded onto a wagon and is queued for dispatch (LOADED). */
async loadedExport(): Promise<ReadyToLoadRow[]> {
return this.exportInventoryByStatus('LOADED');
}
/**
* Bulk-dispatch loaded EXPORT inventory. Reuses the single-item dispatch transition
* (status LOADED → DISPATCHED, capacity freed, movement/activity logged). Items not
* LOADED or not EXPORT are skipped. The train/schedule flow later moves DISPATCHED → IN_TRANSIT.
*/
async bulkDispatchExport(inventoryIds: string[], performedBy?: string): Promise<BulkDispatchResult> {
const result: BulkDispatchResult = { dispatchedCount: 0, skippedCount: 0, results: [] };
for (const inventoryId of inventoryIds) {
const skip = (reason: string) => {
result.skippedCount += 1;
result.results.push({ inventoryId, status: 'SKIPPED', reason });
};
const item = await this.inventoryRepository.findById(inventoryId);
if (!item) { skip('Inventory not found'); continue; }
if (item.status !== 'LOADED') { skip(`Status is ${item.status}, not LOADED`); continue; }
const direction = item.bookingId ? await this.getBookingDirection(item.bookingId) : null;
if (direction !== 'EXPORT') { skip('Not an EXPORT item'); continue; }
try {
await this.dispatch(inventoryId, performedBy);
result.dispatchedCount += 1;
result.results.push({ inventoryId, status: 'DISPATCHED' });
} catch (error) {
skip(error instanceof Error ? error.message : String(error));
}
}
return result;
}
/**
* Bulk-mark received items inspection PASSED (reusing the inspection service to create a minimal
* report + sync inspectionStatus/inspectedAt). EXPORT items advance straight to READY_FOR_LOADING.

View File

@@ -20,16 +20,24 @@ import { Info, PackageSearch, Truck } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import {
useBulkDispatchExport,
useBulkReceive,
useEligibleBookings,
useLoadPassedExport,
useLoadedExport,
useReadyToLoadExport,
useReceiveInventory,
useWarehouseYards,
useWarehouseZones,
useWarehouses,
} from '@/hooks/useWarehouses';
import type { BulkReceiveResult, LoadPassedExportResult, ReadyToLoadRow, ReceiveInventoryPayload } from '@/types/warehouse';
import type {
BulkDispatchResult,
BulkReceiveResult,
LoadPassedExportResult,
ReadyToLoadRow,
ReceiveInventoryPayload,
} from '@/types/warehouse';
import { BookingSelect } from './BookingSelect';
import { extractErrorMessage, formatNumber } from './options';
@@ -458,6 +466,183 @@ function ReadyToLoadTab({ enabled, onChanged }: { enabled: boolean; onChanged?:
);
}
/**
* 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<Set<string>>(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 (
<Stack gap="sm" mt="sm">
<Group justify="space-between">
<Text size="sm" c="dimmed">
{dispatchable ? (
<>
Selected: <b>{selected.size}</b> / {rows.length} loaded
</>
) : (
<>
<b>{rows.length}</b> item{rows.length !== 1 ? 's' : ''} loaded
</>
)}
</Text>
{dispatchable && (
<Group gap="xs">
<Button
size="compact-sm"
variant="default"
disabled={rows.length === 0}
loading={bulkDispatch.isPending}
onClick={() => dispatch(rows.map((r) => r.id))}
>
Dispatch All
</Button>
<Button
size="compact-sm"
color="green"
leftSection={<Truck size={14} />}
disabled={selected.size === 0}
loading={bulkDispatch.isPending}
onClick={() => dispatch([...selected])}
>
Dispatch Selected
</Button>
</Group>
)}
</Group>
{isLoading ? (
<Group justify="center" py="lg">
<Loader size="sm" />
</Group>
) : rows.length === 0 ? (
<Text c="dimmed" ta="center" py="lg" size="sm">
No LOADED export items {dispatchable ? 'waiting to dispatch' : 'yet'}.
</Text>
) : (
<Table.ScrollContainer minWidth={1600}>
<Table highlightOnHover verticalSpacing="xs" striped>
<Table.Thead>
<Table.Tr>
{dispatchable && (
<Table.Th w={40}>
<Checkbox
aria-label="Select all"
checked={allSelected}
indeterminate={someSelected}
onChange={toggleAll}
/>
</Table.Th>
)}
<Table.Th>Booking Ref</Table.Th>
<Table.Th>Booking ID</Table.Th>
<Table.Th>Customer ID</Table.Th>
<Table.Th>Customer Name</Table.Th>
<Table.Th>Container #</Table.Th>
<Table.Th>Cargo Type</Table.Th>
<Table.Th>Weight</Table.Th>
<Table.Th>Route</Table.Th>
<Table.Th>Status</Table.Th>
{dispatchable && <Table.Th ta="right">Actions</Table.Th>}
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{rows.map((r: ReadyToLoadRow) => (
<Table.Tr key={r.id}>
{dispatchable && (
<Table.Td>
<Checkbox
aria-label={`Select ${r.bookingReference ?? r.id}`}
checked={selected.has(r.id)}
onChange={() => toggleOne(r.id)}
/>
</Table.Td>
)}
<Table.Td>
<Text size="sm" fw={600}>{r.bookingReference ?? '—'}</Text>
</Table.Td>
<Table.Td>
<Text size="xs" c="dimmed">{r.bookingId ? `${r.bookingId.slice(0, 8)}` : '—'}</Text>
</Table.Td>
<Table.Td>
<Text size="xs" c="dimmed">{r.customerId ? `${r.customerId.slice(0, 8)}` : '—'}</Text>
</Table.Td>
<Table.Td>{r.customerName ?? '—'}</Table.Td>
<Table.Td>{r.containerNumber ?? '—'}</Table.Td>
<Table.Td>{r.cargoType ?? '—'}</Table.Td>
<Table.Td>{formatNumber(Number(r.weight))}</Table.Td>
<Table.Td>
{r.origin || r.destination ? `${r.origin ?? '?'}${r.destination ?? '?'}` : '—'}
</Table.Td>
<Table.Td>
<Badge color="blue" variant="light" size="sm">
{r.status}
</Badge>
</Table.Td>
{dispatchable && (
<Table.Td ta="right">
<Button
size="compact-xs"
variant="light"
color="green"
loading={bulkDispatch.isPending}
onClick={() => dispatch([r.id])}
>
Dispatch
</Button>
</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: '' });
@@ -501,14 +686,10 @@ function BulkReceiveModal({ opened, onClose, onReceived }: ReceiveInventoryModal
<ReadyToLoadTab enabled={opened} onChanged={onReceived} />
</Tabs.Panel>
<Tabs.Panel value="loaded">
<Text c="dimmed" ta="center" py="lg" size="sm">
Loaded coming in the next batch.
</Text>
<LoadedExportTab enabled={opened} dispatchable={false} onChanged={onReceived} />
</Tabs.Panel>
<Tabs.Panel value="dispatch-queue">
<Text c="dimmed" ta="center" py="lg" size="sm">
Dispatch Queue coming in the next batch.
</Text>
<LoadedExportTab enabled={opened} dispatchable onChanged={onReceived} />
</Tabs.Panel>
</Tabs>
</Tabs.Panel>

View File

@@ -312,6 +312,8 @@ export const URL_CONSTANTS = {
LOAD_PASSED_EXPORT: '/warehouse-inventory/load-passed-export',
BULK_MARK_INSPECTED: '/warehouse-inventory/bulk-mark-inspected',
READY_TO_LOAD_EXPORT: '/warehouse-inventory/ready-to-load-export',
LOADED_EXPORT: '/warehouse-inventory/loaded-export',
BULK_DISPATCH_EXPORT: '/warehouse-inventory/bulk-dispatch-export',
},
WAREHOUSE_LOADINGS: {

View File

@@ -211,6 +211,17 @@ export function useReadyToLoadExport(enabled = true) {
});
}
export function useLoadedExport(enabled = true) {
return useQuery({
queryKey: ['warehouse-inventory', 'loaded-export'],
queryFn: () => warehouseService.loadedExport().then((r) => r.data),
enabled,
});
}
export const useBulkDispatchExport = () =>
useInventoryMutation((inventoryIds: string[]) => warehouseService.bulkDispatchExport(inventoryIds));
// ── Loading (Batch 3) ────────────────────────────────────────────────────────
export function useLoadableWagons(enabled = true) {

View File

@@ -36,6 +36,7 @@ import type {
BulkInspectPayload,
BulkInspectResult,
ReadyToLoadRow,
BulkDispatchResult,
ReserveInventoryPayload,
SaveWarehousePayload,
SaveYardPayload,
@@ -133,6 +134,12 @@ export const warehouseService = {
apiClient.post<BulkInspectResult>(URL_CONSTANTS.WAREHOUSE_INVENTORY.BULK_MARK_INSPECTED, payload),
readyToLoadExport: () =>
apiClient.get<ReadyToLoadRow[]>(URL_CONSTANTS.WAREHOUSE_INVENTORY.READY_TO_LOAD_EXPORT),
loadedExport: () =>
apiClient.get<ReadyToLoadRow[]>(URL_CONSTANTS.WAREHOUSE_INVENTORY.LOADED_EXPORT),
bulkDispatchExport: (inventoryIds: string[]) =>
apiClient.post<BulkDispatchResult>(URL_CONSTANTS.WAREHOUSE_INVENTORY.BULK_DISPATCH_EXPORT, {
inventoryIds,
}),
move: (id: string, payload: MoveInventoryPayload) =>
apiClient.post<WarehouseInventoryItem>(URL_CONSTANTS.WAREHOUSE_INVENTORY.MOVE(id), payload),
movements: (id: string) =>

View File

@@ -395,6 +395,12 @@ export interface ReadyToLoadRow {
status: string;
}
export interface BulkDispatchResult {
dispatchedCount: number;
skippedCount: number;
results: { inventoryId: string; status: string; reason?: string }[];
}
export interface InventoryInquiryResult {
id: string;
bookingId: string;