mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-26 18:42:49 +00:00
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:
@@ -0,0 +1,32 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { ArrayNotEmpty, IsArray, IsIn, IsOptional, IsString, IsUUID } from 'class-validator';
|
||||
|
||||
/** Bulk-receive eligible PAID bookings into a warehouse location, by trade direction. */
|
||||
export class BulkReceiveDto {
|
||||
@ApiProperty({ enum: ['IMPORT', 'EXPORT'] })
|
||||
@IsIn(['IMPORT', 'EXPORT'])
|
||||
direction!: 'IMPORT' | 'EXPORT';
|
||||
|
||||
@ApiProperty({ format: 'uuid' })
|
||||
@IsUUID()
|
||||
warehouseId!: string;
|
||||
|
||||
@ApiProperty({ format: 'uuid' })
|
||||
@IsUUID()
|
||||
yardId!: string;
|
||||
|
||||
@ApiProperty({ format: 'uuid' })
|
||||
@IsUUID()
|
||||
zoneId!: string;
|
||||
|
||||
@ApiProperty({ type: [String], format: 'uuid' })
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@IsUUID('all', { each: true })
|
||||
bookingIds!: string[];
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
performedBy?: string;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Body, Controller, Get, Param, ParseUUIDPipe, Patch, Post, Query } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
|
||||
import { BulkReceiveDto } from './dto/bulk-receive.dto';
|
||||
import { DeliverInventoryDto } from './dto/deliver-inventory.dto';
|
||||
import { FilterWarehouseInventoryDto } from './dto/filter-inventory.dto';
|
||||
import { InquiryWarehouseInventoryDto } from './dto/inquiry-inventory.dto';
|
||||
@@ -58,6 +59,24 @@ export class WarehouseInventoryController {
|
||||
return this.inventoryService.autoLoadReady();
|
||||
}
|
||||
|
||||
@Get('eligible-bookings')
|
||||
@ApiOperation({ summary: 'Eligible PAID bookings for a direction (IMPORT/EXPORT) not yet received' })
|
||||
eligibleBookings(@Query('direction') direction: 'IMPORT' | 'EXPORT') {
|
||||
return this.inventoryService.eligibleBookings(direction === 'EXPORT' ? 'EXPORT' : 'IMPORT');
|
||||
}
|
||||
|
||||
@Post('receive-bulk')
|
||||
@ApiOperation({ summary: 'Bulk-receive selected eligible PAID bookings into a location' })
|
||||
receiveBulk(@Body() dto: BulkReceiveDto) {
|
||||
return this.inventoryService.bulkReceive(dto);
|
||||
}
|
||||
|
||||
@Post('load-passed-export')
|
||||
@ApiOperation({ summary: 'Bulk-load all EXPORT inventory that passed inspection (READY_FOR_LOADING)' })
|
||||
loadPassedExport(@Body('performedBy') performedBy?: string) {
|
||||
return this.inventoryService.loadPassedExport(performedBy);
|
||||
}
|
||||
|
||||
@Post('bookings/:bookingId/unload')
|
||||
@ApiOperation({ summary: 'Unload a single arrived booking into a location' })
|
||||
unloadBooking(
|
||||
|
||||
@@ -2,6 +2,7 @@ import { BadRequestException, Injectable, NotFoundException } from '@nestjs/comm
|
||||
import { DataSource, EntityManager, FindManyOptions, ILike } from 'typeorm';
|
||||
|
||||
import { Cargo } from '../cargoes/entities/cargoes.entity';
|
||||
import { BulkReceiveDto } from './dto/bulk-receive.dto';
|
||||
import { DeliverInventoryDto } from './dto/deliver-inventory.dto';
|
||||
import { FilterWarehouseInventoryDto } from './dto/filter-inventory.dto';
|
||||
import { InquiryWarehouseInventoryDto } from './dto/inquiry-inventory.dto';
|
||||
@@ -116,6 +117,33 @@ export interface AutoLoadResult {
|
||||
results: { inventoryId: string; status: string; reason?: string }[];
|
||||
}
|
||||
|
||||
// ── Receive (Import/Export bulk) shapes ──────────────────────────────────────
|
||||
export interface EligibleBookingRow {
|
||||
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 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 }[];
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class WarehouseInventoryService {
|
||||
constructor(
|
||||
@@ -406,6 +434,144 @@ export class WarehouseInventoryService {
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── Receive (Import/Export bulk) ───────────────────────────────────────────
|
||||
|
||||
/** Eligible PAID bookings for a direction that have NOT been received yet. */
|
||||
eligibleBookings(direction: 'IMPORT' | 'EXPORT'): Promise<EligibleBookingRow[]> {
|
||||
return this.dataSource.query(
|
||||
`SELECT b.id,
|
||||
b.reference AS "reference",
|
||||
company.name AS "customer",
|
||||
b.trade_direction AS "direction",
|
||||
oy.code AS "origin",
|
||||
dy.code AS "destination",
|
||||
b.freight_type AS "freightType",
|
||||
COALESCE(ct.cargo_type_name, b.cargo_free_text) AS "cargo",
|
||||
b.cargo_total_weight_vgm AS "weight",
|
||||
b.payment_status AS "paymentStatus",
|
||||
b.status AS "status"
|
||||
FROM freight.bookings b
|
||||
LEFT JOIN freight.companies company ON company.id = b.company_id
|
||||
LEFT JOIN freight.yards oy ON oy.id = b.origin_yard_id
|
||||
LEFT JOIN freight.yards dy ON dy.id = b.destination_yard_id
|
||||
LEFT JOIN freight.cargo_types ct ON ct.id = b.cargo_type_id
|
||||
LEFT JOIN freight.warehouse_inventory inv ON inv.booking_id = b.id AND inv.deleted_at IS NULL
|
||||
WHERE b.deleted_at IS NULL
|
||||
AND b.payment_status = 'PAID'
|
||||
AND b.trade_direction = $1
|
||||
AND inv.id IS NULL
|
||||
ORDER BY b.scheduled_date DESC NULLS LAST`,
|
||||
[direction],
|
||||
);
|
||||
}
|
||||
|
||||
/** Bulk-receive eligible PAID bookings into a location. Skips duplicates / wrong direction. */
|
||||
async bulkReceive(dto: BulkReceiveDto): Promise<BulkReceiveResult> {
|
||||
const result: BulkReceiveResult = { receivedCount: 0, skippedCount: 0, results: [] };
|
||||
|
||||
await this.dataSource.transaction(async (manager) => {
|
||||
await this.validateLocation(manager, {
|
||||
warehouseId: dto.warehouseId,
|
||||
yardId: dto.yardId,
|
||||
zoneId: dto.zoneId,
|
||||
});
|
||||
|
||||
for (const bookingId of dto.bookingIds) {
|
||||
const skip = (reason: string) => {
|
||||
result.skippedCount += 1;
|
||||
result.results.push({ bookingId, status: 'SKIPPED', reason });
|
||||
};
|
||||
|
||||
const [booking] = await manager.query(
|
||||
`SELECT payment_status AS "paymentStatus", trade_direction AS "tradeDirection",
|
||||
cargo_total_weight_vgm AS "weight"
|
||||
FROM freight.bookings WHERE id = $1 AND deleted_at IS NULL LIMIT 1`,
|
||||
[bookingId],
|
||||
);
|
||||
if (!booking) { skip('Booking not found'); continue; }
|
||||
if (booking.paymentStatus !== 'PAID') { skip('Booking not PAID'); continue; }
|
||||
if (booking.tradeDirection !== dto.direction) {
|
||||
skip(`Booking is ${booking.tradeDirection}, not ${dto.direction}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const existing = await manager.getRepository(WarehouseInventory).findOne({ where: { bookingId } });
|
||||
if (existing) { skip('Already received'); continue; }
|
||||
|
||||
const saved = await manager.getRepository(WarehouseInventory).save(
|
||||
manager.getRepository(WarehouseInventory).create({
|
||||
warehouseId: dto.warehouseId,
|
||||
yardId: dto.yardId,
|
||||
zoneId: dto.zoneId,
|
||||
bookingId,
|
||||
quantity: 1,
|
||||
weight: Number(booking.weight) || 0,
|
||||
status: 'RECEIVED',
|
||||
arrivedAt: new Date(),
|
||||
notes: `Bulk received (${dto.direction})`,
|
||||
}),
|
||||
);
|
||||
|
||||
await this.activityLog.record(
|
||||
{
|
||||
activityType: 'INVENTORY_RECEIVED',
|
||||
inventoryId: saved.id,
|
||||
warehouseId: dto.warehouseId,
|
||||
description: `Bulk received ${dto.direction} booking`,
|
||||
performedBy: dto.performedBy,
|
||||
},
|
||||
manager,
|
||||
);
|
||||
|
||||
result.receivedCount += 1;
|
||||
result.results.push({ bookingId, status: 'RECEIVED', inventoryId: saved.id });
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Bulk-load all EXPORT inventory that passed inspection and is READY_FOR_LOADING. */
|
||||
async loadPassedExport(performedBy?: string): Promise<LoadPassedExportResult> {
|
||||
const ready = await this.inventoryRepository.findAll({ where: { status: 'READY_FOR_LOADING' } });
|
||||
const result: LoadPassedExportResult = { loadedCount: 0, skippedCount: 0, results: [] };
|
||||
|
||||
for (const item of ready) {
|
||||
const skip = (reason: string) => {
|
||||
result.skippedCount += 1;
|
||||
result.results.push({ inventoryId: item.id, status: 'SKIPPED', reason });
|
||||
};
|
||||
|
||||
if (item.inspectionStatus !== 'PASSED') { skip('Inspection not PASSED'); continue; }
|
||||
const direction = item.bookingId ? await this.getBookingDirection(item.bookingId) : null;
|
||||
if (direction !== 'EXPORT') { skip('Not an EXPORT item'); continue; }
|
||||
const bookingStatus = item.bookingId ? await this.getBookingStatus(item.bookingId) : null;
|
||||
if (bookingStatus !== 'PAID') { skip('Booking not PAID'); continue; }
|
||||
|
||||
await this.dataSource.transaction(async (manager) => {
|
||||
await manager.getRepository(WarehouseInventory).update(item.id, {
|
||||
status: 'LOADED',
|
||||
loadedAt: new Date(),
|
||||
});
|
||||
await this.activityLog.record(
|
||||
{
|
||||
activityType: 'INVENTORY_LOADED',
|
||||
inventoryId: item.id,
|
||||
warehouseId: item.warehouseId,
|
||||
description: 'Bulk loaded (passed export)',
|
||||
performedBy,
|
||||
},
|
||||
manager,
|
||||
);
|
||||
});
|
||||
|
||||
result.loadedCount += 1;
|
||||
result.results.push({ inventoryId: item.id, status: 'LOADED' });
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── Receive ──────────────────────────────────────────────────────────────
|
||||
|
||||
async receive(dto: ReceiveWarehouseInventoryDto): Promise<WarehouseInventory> {
|
||||
|
||||
@@ -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} />;
|
||||
}
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user