mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-29 18:48:11 +00:00
Merge branch 'dev' of github.com:Tria-plc/edr-platform into freight_feature/usermanagement
This commit is contained in:
@@ -249,6 +249,16 @@ const FleetFormDialog = ({
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Format check (e.g. plate numbers). Skipped for an empty optional field —
|
||||
// "required" above already owns the empty case. Upper-cased to match the
|
||||
// server, which stores plates upper-case.
|
||||
if (field.pattern && stringValue && stringValue !== FLEET_SELECT_NONE) {
|
||||
const candidate = field.pattern.uppercase === false ? stringValue : stringValue.toUpperCase();
|
||||
if (!field.pattern.regex.test(candidate)) {
|
||||
next[field.name] = field.pattern.message;
|
||||
}
|
||||
}
|
||||
});
|
||||
setErrors(next);
|
||||
return Object.keys(next).length === 0;
|
||||
|
||||
@@ -2647,7 +2647,9 @@ function ImportUnloadedQueueTab({ enabled }: { enabled: boolean }) {
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
{/* Primary stage action stays visible; the rest live under the kebab. */}
|
||||
{r.currentStatus === 'READY_FOR_PICKUP' && !r.releaseDate && r.hasAssignedTruck && (
|
||||
{/* Stays visible after the first exit — multi-truck bookings
|
||||
weigh each truck in and out until all have left. */}
|
||||
{r.currentStatus === 'READY_FOR_PICKUP' && r.hasAssignedTruck && (
|
||||
<Button
|
||||
size="compact-xs"
|
||||
variant="light"
|
||||
@@ -2655,7 +2657,7 @@ function ImportUnloadedQueueTab({ enabled }: { enabled: boolean }) {
|
||||
leftSection={<Truck size={14} />}
|
||||
onClick={() => setReleaseItem(toInventoryItem(r))}
|
||||
>
|
||||
{r.releaseOrderReference ? 'Truck Leaving' : 'Truck Arrival'}
|
||||
{r.releaseOrderReference ? 'Truck Arrival / Leaving' : 'Truck Arrival'}
|
||||
</Button>
|
||||
)}
|
||||
{r.currentStatus === 'READY_FOR_PICKUP' && r.releaseDate && (
|
||||
@@ -2692,7 +2694,7 @@ function ImportUnloadedQueueTab({ enabled }: { enabled: boolean }) {
|
||||
Ready for pickup
|
||||
</Menu.Item>
|
||||
)}
|
||||
{r.currentStatus === 'READY_FOR_PICKUP' && !r.releaseDate && (
|
||||
{r.currentStatus === 'READY_FOR_PICKUP' && (
|
||||
<Menu.Item
|
||||
leftSection={<Truck size={14} />}
|
||||
disabled={!r.hasAssignedTruck}
|
||||
@@ -2700,7 +2702,7 @@ function ImportUnloadedQueueTab({ enabled }: { enabled: boolean }) {
|
||||
>
|
||||
{r.hasAssignedTruck
|
||||
? r.releaseOrderReference
|
||||
? 'Truck leaving'
|
||||
? 'Truck arrival / leaving'
|
||||
: 'Truck arrival'
|
||||
: 'Truck arrival — assign a truck first'}
|
||||
</Menu.Item>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Alert, Button, Group, Modal, MultiSelect, NumberInput, SegmentedControl, Select, SimpleGrid, Stack, Text, TextInput } from '@mantine/core';
|
||||
import { Info, Scale } from 'lucide-react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, Badge, Button, Group, Modal, MultiSelect, NumberInput, SegmentedControl, Select, SimpleGrid, Stack, Text, TextInput } from '@mantine/core';
|
||||
import { Info, Scale, Truck } from 'lucide-react';
|
||||
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
import { api } from '@/services/api';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
@@ -28,6 +28,8 @@ export interface ReleaseOrderTruckPrefill {
|
||||
containerNumber?: string | null;
|
||||
}
|
||||
|
||||
const EXIT_INSPECTION_MARKER = '[Exit Inspection]';
|
||||
|
||||
const toIsoDateTime = (value: string) => {
|
||||
if (!value) return undefined;
|
||||
const date = new Date(value);
|
||||
@@ -70,9 +72,6 @@ const splitContainerNumbers = (value: string | null | undefined) =>
|
||||
const getItemContainerNumber = (item: WarehouseInventoryItem | null) =>
|
||||
(item as (WarehouseInventoryItem & { containerNumber?: string | null }) | null)?.containerNumber ?? '';
|
||||
|
||||
const assignedTruckValue = (item: WarehouseInventoryItem | null, key: keyof NonNullable<WarehouseInventoryItem['booking']>) =>
|
||||
item?.booking?.[key] == null ? '' : String(item.booking[key]);
|
||||
|
||||
const isContainerInventory = (item: WarehouseInventoryItem | null, containerCount: number) => {
|
||||
const freightType = (item as (WarehouseInventoryItem & { booking?: { freightType?: string | null } | null }) | null)
|
||||
?.booking?.freightType;
|
||||
@@ -88,29 +87,66 @@ const initialContainerNumbers = (item: WarehouseInventoryItem | null, savedConta
|
||||
return Array.from({ length: expectedCount }, (_, index) => sourceNumbers[index] ?? '');
|
||||
};
|
||||
|
||||
const parseInspectionNote = (notes: string | null | undefined) => {
|
||||
const marker = '[Exit Inspection]';
|
||||
const index = notes?.lastIndexOf(marker) ?? -1;
|
||||
const note = index >= 0 ? notes?.slice(index + marker.length) : notes;
|
||||
return {
|
||||
truckPlateNumber: lineValue(note, 'Truck Plate'),
|
||||
trailerPlateNumber: lineValue(note, 'Trailer Plate'),
|
||||
driverName: lineValue(note, 'Driver'),
|
||||
driverLicense: lineValue(note, 'Driver License'),
|
||||
driverPhone: lineValue(note, 'Driver Phone'),
|
||||
truckType: lineValue(note, 'Truck Type'),
|
||||
containerNumber: lineValue(note, 'Container Number'),
|
||||
gateInTime: toLocalDateTimeInput(lineValue(note, 'Gate In Time')),
|
||||
tareWeight: lineNumber(note, 'Tare Weight'),
|
||||
grossWeight: lineNumber(note, 'Gross Weight'),
|
||||
netWeight: lineNumber(note, 'Net Weight'),
|
||||
gateOutTime: toLocalDateTimeInput(lineValue(note, 'Gate Out Time')),
|
||||
weighingSkipped: /^Weighing:\s*SKIPPED/im.test(note ?? ''),
|
||||
};
|
||||
/** One truck's saved arrival/exit weighing, parsed from its inspection block. */
|
||||
interface InspectionBlock {
|
||||
truckPlateNumber: string;
|
||||
trailerPlateNumber: string;
|
||||
driverName: string;
|
||||
driverLicense: string;
|
||||
driverPhone: string;
|
||||
truckType: string;
|
||||
containerNumber: string;
|
||||
gateInTime: string;
|
||||
tareWeight: number | '';
|
||||
grossWeight: number | '';
|
||||
netWeight: number | '';
|
||||
gateOutTime: string;
|
||||
weighingSkipped: boolean;
|
||||
}
|
||||
|
||||
const parseInspectionSection = (note: string): InspectionBlock => ({
|
||||
truckPlateNumber: lineValue(note, 'Truck Plate'),
|
||||
trailerPlateNumber: lineValue(note, 'Trailer Plate'),
|
||||
driverName: lineValue(note, 'Driver'),
|
||||
driverLicense: lineValue(note, 'Driver License'),
|
||||
driverPhone: lineValue(note, 'Driver Phone'),
|
||||
truckType: lineValue(note, 'Truck Type'),
|
||||
containerNumber: lineValue(note, 'Container Number'),
|
||||
gateInTime: toLocalDateTimeInput(lineValue(note, 'Gate In Time')),
|
||||
tareWeight: lineNumber(note, 'Tare Weight'),
|
||||
grossWeight: lineNumber(note, 'Gross Weight'),
|
||||
netWeight: lineNumber(note, 'Net Weight'),
|
||||
gateOutTime: toLocalDateTimeInput(lineValue(note, 'Gate Out Time')),
|
||||
weighingSkipped: /^Weighing:\s*SKIPPED/im.test(note),
|
||||
});
|
||||
|
||||
/** Every truck's saved block — multi-truck bookings weigh each truck separately. */
|
||||
const parseInspectionBlocks = (notes: string | null | undefined): InspectionBlock[] =>
|
||||
(notes ?? '')
|
||||
.split(EXIT_INSPECTION_MARKER)
|
||||
.slice(1)
|
||||
.map(parseInspectionSection)
|
||||
.filter((block) => block.truckPlateNumber);
|
||||
|
||||
/** Match by plate; a legacy block may hold a comma-joined plate list. */
|
||||
const blockForPlate = (blocks: InspectionBlock[], plate: string): InspectionBlock | undefined => {
|
||||
const key = plate.trim().toUpperCase();
|
||||
if (!key) return undefined;
|
||||
return blocks.find((block) => {
|
||||
const stored = block.truckPlateNumber.toUpperCase();
|
||||
return stored === key || stored.split(/[,;]+/).map((p) => p.trim()).includes(key);
|
||||
});
|
||||
};
|
||||
|
||||
const blockArrived = (block: InspectionBlock | undefined) =>
|
||||
Boolean(block && (block.tareWeight !== '' || block.weighingSkipped));
|
||||
|
||||
const blockLeft = (block: InspectionBlock | undefined) =>
|
||||
Boolean(block?.gateOutTime && (block.grossWeight !== '' || block.weighingSkipped));
|
||||
|
||||
export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: ReleaseOrderModalProps) {
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
const releaseMutation = useMutation(api.warehouses.release.mutationOptions());
|
||||
// Some openers (inventory workbench) supply bookingId without the booking
|
||||
// relation — fall back to it, or the truck/container-weight queries never run.
|
||||
@@ -152,78 +188,16 @@ export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: Relea
|
||||
const [netWeight, setNetWeight] = useState<number | ''>('');
|
||||
const [gateOutTime, setGateOutTime] = useState('');
|
||||
const [downloading, setDownloading] = useState(false);
|
||||
// Plate whose saved block was last loaded into the form — stops the
|
||||
// per-plate loader effect from clobbering operator edits in a loop.
|
||||
const loadedPlateRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (opened) {
|
||||
const inspection = parseInspectionNote(item?.notes);
|
||||
const assignedTruckPlate = assignedTruckValue(item, 'customerTruckPlateNumber');
|
||||
const assignedDriverName = assignedTruckValue(item, 'customerTruckDriverName');
|
||||
const assignedTruckType = assignedTruckValue(item, 'customerTruckType');
|
||||
const assignedContainerNumber = assignedTruckValue(item, 'customerTruckContainerNumber');
|
||||
const prefillContainerNumber = truckPrefill?.containerNumber ?? '';
|
||||
setReference(item?.releaseOrderReference ?? generateReleaseReference(item));
|
||||
setTruckPlateNumber(inspection.truckPlateNumber || truckPrefill?.truckPlateNumber || assignedTruckPlate || '');
|
||||
setTrailerPlateNumber(inspection.trailerPlateNumber || truckPrefill?.trailerPlateNumber || '');
|
||||
setDriverName(inspection.driverName || truckPrefill?.driverName || assignedDriverName || '');
|
||||
setDriverLicense(inspection.driverLicense || truckPrefill?.driverLicense || '');
|
||||
setDriverPhone(inspection.driverPhone || truckPrefill?.driverPhone || '');
|
||||
setTruckType(inspection.truckType || truckPrefill?.truckType || assignedTruckType || '');
|
||||
setContainerNumbers(initialContainerNumbers(item, inspection.containerNumber || prefillContainerNumber || assignedContainerNumber));
|
||||
setGateInTime(inspection.gateInTime);
|
||||
setTareWeight(inspection.tareWeight);
|
||||
setWeighTruck(inspection.weighingSkipped ? 'no' : 'yes');
|
||||
setGrossWeight(inspection.grossWeight);
|
||||
setNetWeight(item?.weight == null ? inspection.netWeight : Number(item.weight));
|
||||
setGateOutTime(inspection.gateOutTime);
|
||||
}
|
||||
}, [opened, item, truckPrefill]);
|
||||
|
||||
const savedInspection = parseInspectionNote(item?.notes);
|
||||
const isExitStep = savedInspection.tareWeight !== '' || savedInspection.weighingSkipped;
|
||||
const isEntranceLocked = isExitStep;
|
||||
const isCustomerAssignedTruck = Boolean(item?.booking?.customerTruckAssignedAt);
|
||||
const hasLastMileTruckPrefill = Boolean(truckPrefill?.truckPlateNumber || truckPrefill?.trailerPlateNumber);
|
||||
|
||||
// Opened from the warehouse flow (no truckPrefill prop): once the last-mile
|
||||
// truck query resolves, auto-fill the first assigned EDR truck — without
|
||||
// overwriting anything the operator typed or the locked exit-step values.
|
||||
useEffect(() => {
|
||||
if (!opened || truckPrefill || isExitStep) return;
|
||||
const first = lastMileTrucks[0];
|
||||
if (!first) return;
|
||||
setTruckPlateNumber((p) => p || first.truckPlateNumber || '');
|
||||
setTrailerPlateNumber((p) => p || first.trailerPlateNumber || '');
|
||||
setDriverName((p) => p || first.driverName || '');
|
||||
setDriverLicense((p) => p || first.driverLicense || '');
|
||||
setDriverPhone((p) => p || first.driverPhone || '');
|
||||
setTruckType((p) => p || first.truckType || '');
|
||||
setContainerNumbers((prev) =>
|
||||
prev.length === 1 && !prev[0] && first.containerNumber ? [first.containerNumber] : prev,
|
||||
);
|
||||
}, [opened, truckPrefill, isExitStep, lastMileTrucks]);
|
||||
|
||||
// The same for a customer self-haul truck. The prefill above reads the
|
||||
// booking.customer_truck_* columns, but multi-truck self-haul writes the plate
|
||||
// and driver to customer_truck_assignments and leaves those columns null — so
|
||||
// a booking with a truck on file still opened this form blank. Only auto-fills
|
||||
// a single truck: with several, the operator picks which one is at the gate.
|
||||
useEffect(() => {
|
||||
if (!opened || truckPrefill || isExitStep) return;
|
||||
if (customerTrucks.length !== 1) return;
|
||||
const [truck] = customerTrucks;
|
||||
setTruckPlateNumber((p) => p || truck.plateNumber || '');
|
||||
setDriverName((p) => p || truck.driverName || '');
|
||||
setTruckType((p) => p || truck.truckType || '');
|
||||
setContainerNumbers((prev) => {
|
||||
const loaded = (truck.containers ?? []).map((c) => c.containerNumber).filter(Boolean);
|
||||
return prev.every((n) => !n) && loaded.length ? loaded : prev;
|
||||
});
|
||||
}, [opened, truckPrefill, isExitStep, customerTrucks]);
|
||||
const savedBlocks = parseInspectionBlocks(item?.notes);
|
||||
|
||||
// Registered trucks for THIS booking, from both sources: EDR last-mile
|
||||
// (truckPrefill) and the customer portal (customer_truck_assignments).
|
||||
const assignedTruckOptions = [
|
||||
...(truckPrefill?.truckPlateNumber
|
||||
...(truckPrefill?.truckPlateNumber && !truckPrefill.truckPlateNumber.includes(',')
|
||||
? [
|
||||
{
|
||||
value: truckPrefill.truckPlateNumber,
|
||||
@@ -232,6 +206,9 @@ export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: Relea
|
||||
driverName: truckPrefill.driverName ?? '',
|
||||
driverPhone: truckPrefill.driverPhone ?? '',
|
||||
truckType: truckPrefill.truckType ?? '',
|
||||
containerNumbers: splitContainerNumbers(truckPrefill.containerNumber),
|
||||
arrived: false,
|
||||
left: false,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
@@ -242,6 +219,9 @@ export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: Relea
|
||||
driverName: t.driverName,
|
||||
driverPhone: '',
|
||||
truckType: t.truckType,
|
||||
containerNumbers: (t.containers ?? []).map((c) => c.containerNumber).filter(Boolean),
|
||||
arrived: Boolean(t.arrivedAt),
|
||||
left: Boolean(t.departedAt),
|
||||
})),
|
||||
...lastMileTrucks
|
||||
.filter((t) => t.truckPlateNumber || t.vehicleId)
|
||||
@@ -252,6 +232,9 @@ export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: Relea
|
||||
driverName: t.driverName ?? '',
|
||||
driverPhone: t.driverPhone ?? '',
|
||||
truckType: t.truckType ?? '',
|
||||
containerNumbers: splitContainerNumbers(t.containerNumber),
|
||||
arrived: Boolean(t.arrivedAt),
|
||||
left: Boolean(t.departedAt),
|
||||
})),
|
||||
];
|
||||
// Only trucks actually assigned to THIS booking (last-mile prefill or customer
|
||||
@@ -261,10 +244,132 @@ export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: Relea
|
||||
const truckSelectOptions = [
|
||||
...new Map(assignedTruckOptions.map((t) => [t.value, t])).values(),
|
||||
];
|
||||
const isCustomerAssignedTruck = Boolean(item?.booking?.customerTruckAssignedAt);
|
||||
// Neither a last-mile truck nor a customer truck has been assigned yet.
|
||||
const noTruckAssigned = assignedTruckOptions.length === 0 && !isCustomerAssignedTruck;
|
||||
const isTruckIdentityLocked = isEntranceLocked || isCustomerAssignedTruck || hasLastMileTruckPrefill;
|
||||
const isDriverNameLocked = isEntranceLocked || isCustomerAssignedTruck || Boolean(truckPrefill?.driverName);
|
||||
|
||||
// Per-truck progress: every truck is weighed in and out on its own; the saved
|
||||
// blocks also cover walk-in trucks that were never formally assigned.
|
||||
const truckProgress = new Map<string, { arrived: boolean; left: boolean }>();
|
||||
for (const option of truckSelectOptions) {
|
||||
truckProgress.set(option.value.trim().toUpperCase(), { arrived: option.arrived, left: option.left });
|
||||
}
|
||||
for (const block of savedBlocks) {
|
||||
const key = block.truckPlateNumber.trim().toUpperCase();
|
||||
const prior = truckProgress.get(key);
|
||||
truckProgress.set(key, {
|
||||
arrived: Boolean(prior?.arrived) || blockArrived(block),
|
||||
left: Boolean(prior?.left) || blockLeft(block),
|
||||
});
|
||||
}
|
||||
const totalTrucks = truckProgress.size;
|
||||
const arrivedTrucks = [...truckProgress.values()].filter((t) => t.arrived).length;
|
||||
const leftTrucks = [...truckProgress.values()].filter((t) => t.left).length;
|
||||
|
||||
// The step is decided PER TRUCK: the selected plate's saved block. A new plate
|
||||
// (or a truck without a saved arrival) starts at the arrival step even when
|
||||
// other trucks of the booking are already mid-flow or gone.
|
||||
const selectedBlock = blockForPlate(savedBlocks, truckPlateNumber);
|
||||
const isExitStep = blockArrived(selectedBlock);
|
||||
const hasTruckLeft = blockLeft(selectedBlock);
|
||||
const isEntranceLocked = isExitStep;
|
||||
const selectedOption = truckSelectOptions.find(
|
||||
(option) => option.value.trim().toUpperCase() === truckPlateNumber.trim().toUpperCase(),
|
||||
);
|
||||
// Identity comes from the arrival record or the assignment — locked either
|
||||
// way. A walk-in truck (typed plate, no assignment) stays editable at arrival.
|
||||
const isTruckIdentityLocked = isEntranceLocked || Boolean(selectedOption);
|
||||
const isDriverNameLocked = isEntranceLocked || Boolean(selectedOption?.driverName);
|
||||
const referenceLocked = Boolean(item?.releaseOrderReference) || savedBlocks.length > 0;
|
||||
|
||||
/** Load a truck into the form: its saved block if any, else its assignment. */
|
||||
const applyTruckSelection = (plate: string) => {
|
||||
const block = blockForPlate(savedBlocks, plate);
|
||||
const option = truckSelectOptions.find(
|
||||
(o) => o.value.trim().toUpperCase() === plate.trim().toUpperCase(),
|
||||
);
|
||||
loadedPlateRef.current = plate.trim().toUpperCase();
|
||||
setTruckPlateNumber(plate);
|
||||
setTrailerPlateNumber(block?.trailerPlateNumber || option?.trailerPlate || '');
|
||||
setDriverName(block?.driverName || option?.driverName || '');
|
||||
setDriverLicense(block?.driverLicense || '');
|
||||
setDriverPhone(block?.driverPhone || option?.driverPhone || '');
|
||||
setTruckType(block?.truckType || option?.truckType || '');
|
||||
const loaded = block
|
||||
? splitContainerNumbers(block.containerNumber)
|
||||
: (option?.containerNumbers ?? []);
|
||||
setContainerNumbers(loaded.length ? loaded : initialContainerNumbers(item, ''));
|
||||
setGateInTime(block?.gateInTime ?? '');
|
||||
setTareWeight(block?.tareWeight ?? '');
|
||||
setWeighTruck(block?.weighingSkipped ? 'no' : 'yes');
|
||||
setGrossWeight(block?.grossWeight ?? '');
|
||||
setNetWeight(block?.netWeight ?? (item?.weight == null ? '' : Number(item.weight)));
|
||||
setGateOutTime(block?.gateOutTime ?? '');
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (opened) {
|
||||
loadedPlateRef.current = null;
|
||||
setReference(item?.releaseOrderReference ?? generateReleaseReference(item));
|
||||
// Initial truck: the caller's prefill, else the first truck still mid-flow
|
||||
// (arrived but not left) — the operator can switch trucks in the select.
|
||||
const prefillPlate =
|
||||
truckPrefill?.truckPlateNumber && !truckPrefill.truckPlateNumber.includes(',')
|
||||
? truckPrefill.truckPlateNumber
|
||||
: '';
|
||||
const blocks = parseInspectionBlocks(item?.notes);
|
||||
const inProgress = blocks.find((block) => blockArrived(block) && !blockLeft(block));
|
||||
// Legacy single-truck bookings stored the truck on the booking columns; a
|
||||
// comma-joined value means several trucks, so the operator picks instead.
|
||||
const bookingPlate = item?.booking?.customerTruckPlateNumber ?? '';
|
||||
const legacyPlate = bookingPlate && !bookingPlate.includes(',') ? bookingPlate : '';
|
||||
const initialPlate = prefillPlate || inProgress?.truckPlateNumber || legacyPlate || '';
|
||||
const block = blockForPlate(blocks, initialPlate);
|
||||
loadedPlateRef.current = initialPlate ? initialPlate.trim().toUpperCase() : null;
|
||||
setTruckPlateNumber(initialPlate);
|
||||
setTrailerPlateNumber(block?.trailerPlateNumber || truckPrefill?.trailerPlateNumber || '');
|
||||
setDriverName(
|
||||
block?.driverName ||
|
||||
truckPrefill?.driverName ||
|
||||
(legacyPlate && initialPlate === legacyPlate ? (item?.booking?.customerTruckDriverName ?? '') : ''),
|
||||
);
|
||||
setDriverLicense(block?.driverLicense || truckPrefill?.driverLicense || '');
|
||||
setDriverPhone(block?.driverPhone || truckPrefill?.driverPhone || '');
|
||||
setTruckType(
|
||||
block?.truckType ||
|
||||
truckPrefill?.truckType ||
|
||||
(legacyPlate && initialPlate === legacyPlate ? (item?.booking?.customerTruckType ?? '') : ''),
|
||||
);
|
||||
setContainerNumbers(
|
||||
initialContainerNumbers(item, block?.containerNumber || truckPrefill?.containerNumber || ''),
|
||||
);
|
||||
setGateInTime(block?.gateInTime ?? '');
|
||||
setTareWeight(block?.tareWeight ?? '');
|
||||
setWeighTruck(block?.weighingSkipped ? 'no' : 'yes');
|
||||
setGrossWeight(block?.grossWeight ?? '');
|
||||
setNetWeight(block?.netWeight ?? (item?.weight == null ? '' : Number(item.weight)));
|
||||
setGateOutTime(block?.gateOutTime ?? '');
|
||||
}
|
||||
}, [opened, item, truckPrefill]);
|
||||
|
||||
// No truck chosen yet and exactly one is assigned — load it. With several
|
||||
// trucks the operator picks which one is at the gate.
|
||||
useEffect(() => {
|
||||
if (!opened || truckPlateNumber || loadedPlateRef.current) return;
|
||||
if (truckSelectOptions.length !== 1) return;
|
||||
applyTruckSelection(truckSelectOptions[0].value);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [opened, truckPlateNumber, customerTrucks, lastMileTrucks]);
|
||||
|
||||
// A typed plate that matches a saved arrival reloads that truck's record, so
|
||||
// the exit step opens with the weigh-in data instead of blank fields.
|
||||
useEffect(() => {
|
||||
if (!opened) return;
|
||||
const key = truckPlateNumber.trim().toUpperCase();
|
||||
if (!key || loadedPlateRef.current === key) return;
|
||||
if (blockForPlate(savedBlocks, truckPlateNumber)) applyTruckSelection(truckPlateNumber);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [opened, truckPlateNumber]);
|
||||
|
||||
// Which containers ride this truck, and their combined cargo weight. When the
|
||||
// booking has container weights, that sum is the authoritative net; the
|
||||
@@ -294,7 +399,9 @@ export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: Relea
|
||||
);
|
||||
// Skip is only offered for container bookings; bulk always weighs.
|
||||
const skipWeighing = hasContainerWeights && weighTruck === 'no';
|
||||
const useContainerNet = hasContainerWeights && selectedContainerNumbers.length > 0 && !skipWeighing;
|
||||
// Even an unweighed truck records the cargo weight it is holding — the
|
||||
// selected containers' sum is the net that goes on the exit record.
|
||||
const useContainerNet = hasContainerWeights && selectedContainerNumbers.length > 0;
|
||||
|
||||
const systemNetWeight = useContainerNet
|
||||
? selectedCargoWeight
|
||||
@@ -314,6 +421,10 @@ export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: Relea
|
||||
toast({ variant: 'destructive', title: 'Truck plate and driver name are required' });
|
||||
return;
|
||||
}
|
||||
if (hasTruckLeft) {
|
||||
toast({ variant: 'destructive', title: `Truck ${truckPlateNumber} has already left — its exit record is locked` });
|
||||
return;
|
||||
}
|
||||
if (!gateInTime || (!skipWeighing && tareWeight === '')) {
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
@@ -363,13 +474,17 @@ export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: Relea
|
||||
weighingSkipped: skipWeighing || undefined,
|
||||
tareWeight: skipWeighing ? undefined : Number(tareWeight),
|
||||
grossWeight: skipWeighing || grossWeight === '' ? undefined : Number(grossWeight),
|
||||
netWeight: !skipWeighing && isExitStep && systemNetWeight !== '' ? Number(systemNetWeight) : undefined,
|
||||
// Skipped weighing still records the net from what the truck holds.
|
||||
netWeight: isExitStep && systemNetWeight !== '' ? Number(systemNetWeight) : undefined,
|
||||
gateOutTime: isExitStep ? toIsoDateTime(gateOutTime) : undefined,
|
||||
},
|
||||
});
|
||||
await queryClient.invalidateQueries({ queryKey: ['release-customer-trucks', bookingId] });
|
||||
await queryClient.invalidateQueries({ queryKey: ['release-last-mile-trucks', bookingId] });
|
||||
if (!isExitStep) {
|
||||
const remaining = totalTrucks > 1 ? ` (${Math.min(arrivedTrucks + 1, totalTrucks)} of ${totalTrucks} trucks arrived)` : '';
|
||||
toast({
|
||||
title: 'Truck arrival saved',
|
||||
title: `Truck ${truckPlateNumber.trim()} arrival saved${remaining}`,
|
||||
description: `${released.releaseOrderReference ?? reference} is ready for exit weighing.`,
|
||||
});
|
||||
onClose();
|
||||
@@ -380,11 +495,12 @@ export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: Relea
|
||||
const blob = response.data;
|
||||
const filename = `release-${released.booking?.reference ?? released.bookingId ?? item.id}.pdf`;
|
||||
const opened = openPdfBlob(blob, filename, pdfWindow);
|
||||
const remainingExit = totalTrucks > 1 ? ` ${Math.min(leftTrucks + 1, totalTrucks)} of ${totalTrucks} trucks have left.` : '';
|
||||
toast({
|
||||
title: 'Release exit paper issued',
|
||||
description: opened
|
||||
description: (opened
|
||||
? 'The PDF opened in a browser tab for printing or saving.'
|
||||
: 'The browser blocked the preview tab, so the PDF was downloaded.',
|
||||
: 'The browser blocked the preview tab, so the PDF was downloaded.') + remainingExit,
|
||||
});
|
||||
onClose();
|
||||
} catch (error) {
|
||||
@@ -411,12 +527,35 @@ export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: Relea
|
||||
</Text>
|
||||
)}
|
||||
</Alert>
|
||||
{totalTrucks > 1 && (
|
||||
<Alert icon={<Truck size={16} />} color="blue" variant="light">
|
||||
<Group gap="xs">
|
||||
<Text size="sm">
|
||||
{totalTrucks} trucks on this booking — each is weighed in and out separately.
|
||||
</Text>
|
||||
<Badge size="sm" variant="light" color={arrivedTrucks === totalTrucks ? 'green' : 'blue'}>
|
||||
{arrivedTrucks}/{totalTrucks} arrived
|
||||
</Badge>
|
||||
<Badge size="sm" variant="light" color={leftTrucks === totalTrucks ? 'green' : 'gray'}>
|
||||
{leftTrucks}/{totalTrucks} left
|
||||
</Badge>
|
||||
</Group>
|
||||
</Alert>
|
||||
)}
|
||||
{hasTruckLeft && (
|
||||
<Alert icon={<Info size={16} />} color="green" variant="light">
|
||||
<Text size="sm">
|
||||
Truck {truckPlateNumber} has already left — its exit record is locked. Pick another
|
||||
truck to continue the remaining arrivals and exits.
|
||||
</Text>
|
||||
</Alert>
|
||||
)}
|
||||
<TextInput
|
||||
label="Release document reference"
|
||||
placeholder="e.g. REL-2026-001"
|
||||
value={reference}
|
||||
onChange={(e) => setReference(e.currentTarget.value)}
|
||||
readOnly={isEntranceLocked}
|
||||
readOnly={referenceLocked}
|
||||
/>
|
||||
{noTruckAssigned && (
|
||||
<Alert color="orange" variant="light" icon={<Info size={16} />}>
|
||||
@@ -425,22 +564,19 @@ export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: Relea
|
||||
)}
|
||||
{truckSelectOptions.length > 0 && (
|
||||
<Select
|
||||
label="Assigned first / last-mile truck"
|
||||
label="Truck at the gate"
|
||||
description="Pick which assigned truck is being processed — switching trucks loads that truck's own arrival/exit record."
|
||||
placeholder="Select the assigned truck"
|
||||
searchable
|
||||
clearable
|
||||
// Enabled at arrival so the operator picks which assigned truck came;
|
||||
// only locked on the exit (leaving) step once identity is captured.
|
||||
disabled={isEntranceLocked}
|
||||
data={truckSelectOptions}
|
||||
disabled={releaseMutation.isPending || downloading}
|
||||
data={truckSelectOptions.map(({ value, label, arrived, left }) => ({
|
||||
value,
|
||||
label: `${label}${left ? ' · LEFT' : arrived ? ' · ON SITE' : ''}`,
|
||||
}))}
|
||||
value={truckSelectOptions.some((truck) => truck.value === truckPlateNumber) ? truckPlateNumber : null}
|
||||
onChange={(value) => {
|
||||
const truck = truckSelectOptions.find((row) => row.value === value);
|
||||
setTruckPlateNumber(truck?.value ?? '');
|
||||
setTrailerPlateNumber(truck?.trailerPlate ?? '');
|
||||
if (truck?.driverName) setDriverName(truck.driverName);
|
||||
if (truck?.driverPhone) setDriverPhone(truck.driverPhone);
|
||||
if (truck?.truckType) setTruckType(truck.truckType);
|
||||
if (value) applyTruckSelection(value);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
@@ -481,6 +617,7 @@ export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: Relea
|
||||
data={containerSelectData}
|
||||
value={selectedContainerNumbers}
|
||||
onChange={(values) => setContainerNumbers(values.length ? values : [''])}
|
||||
disabled={hasTruckLeft}
|
||||
/>
|
||||
) : (
|
||||
<Stack gap={6}>
|
||||
@@ -514,13 +651,15 @@ export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: Relea
|
||||
disabled={isEntranceLocked}
|
||||
/>
|
||||
{skipWeighing && (
|
||||
<Text size="xs" c="dimmed">Weighbridge skipped — container passes without tare/gross.</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
Weighbridge skipped — the selected containers' cargo weight is recorded as the net.
|
||||
</Text>
|
||||
)}
|
||||
</Group>
|
||||
)}
|
||||
<Group grow>
|
||||
<NumberInput label="Tare weight (t)" required={!skipWeighing} min={0} value={tareWeight} onChange={(v) => setTareWeight(v === '' ? '' : Number(v))} readOnly={isEntranceLocked} disabled={skipWeighing} />
|
||||
<NumberInput label="Gross weight (t)" required={isExitStep && !skipWeighing} min={0} value={grossWeight} onChange={(v) => setGrossWeight(v === '' ? '' : Number(v))} disabled={!isExitStep || skipWeighing} />
|
||||
<NumberInput label="Gross weight (t)" required={isExitStep && !skipWeighing} min={0} value={grossWeight} onChange={(v) => setGrossWeight(v === '' ? '' : Number(v))} disabled={!isExitStep || skipWeighing || hasTruckLeft} />
|
||||
<NumberInput
|
||||
label={useContainerNet ? 'Selected cargo net (t)' : 'Recorded net weight (system t)'}
|
||||
min={0}
|
||||
@@ -532,7 +671,7 @@ export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: Relea
|
||||
<Text size="sm" c={weightMismatch ? 'red' : 'dimmed'}>
|
||||
Computed net: <b>{computedNetWeight == null ? '-' : `${computedNetWeight.toLocaleString()} t`}</b>
|
||||
</Text>
|
||||
<TextInput label="Gate out time" type="datetime-local" value={gateOutTime} onChange={(e) => setGateOutTime(e.currentTarget.value)} disabled={!isExitStep} />
|
||||
<TextInput label="Gate out time" type="datetime-local" value={gateOutTime} onChange={(e) => setGateOutTime(e.currentTarget.value)} disabled={!isExitStep || hasTruckLeft} />
|
||||
</Group>
|
||||
{weightMismatch && (
|
||||
<Alert icon={<Scale size={16} />} color="red" variant="light">
|
||||
@@ -546,7 +685,7 @@ export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: Relea
|
||||
<Button variant="default" onClick={onClose} disabled={releaseMutation.isPending || downloading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button color="orange" onClick={handleSubmit} loading={releaseMutation.isPending || downloading}>
|
||||
<Button color="orange" onClick={handleSubmit} loading={releaseMutation.isPending || downloading} disabled={hasTruckLeft}>
|
||||
{isExitStep ? 'Save Truck Leaving & View Exit Paper' : 'Save Truck Arrival'}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
@@ -51,8 +51,10 @@ const actionColor: Record<InventoryAction, string> = {
|
||||
deliver: 'green',
|
||||
};
|
||||
|
||||
// After the first truck registers, the modal decides per truck whether it is
|
||||
// arriving or leaving — the item-level label covers both for multi-truck.
|
||||
const releaseActionLabel = (item: WarehouseInventoryItem) =>
|
||||
item.releaseOrderReference ? 'Truck Leaving' : 'Truck Arrival';
|
||||
item.releaseOrderReference ? 'Truck Arrival / Leaving' : 'Truck Arrival';
|
||||
|
||||
const noteLineValue = (notes: string | null | undefined, label: string) => {
|
||||
const match = notes?.match(new RegExp(`^${label}:\\s*(.+)$`, 'im'));
|
||||
@@ -276,6 +278,19 @@ export function WarehouseInventoryTable({
|
||||
{nextAction === 'release' ? releaseActionLabel(item) : humanizeEnum(nextAction.replace(/-/g, '_'))}
|
||||
</Button>
|
||||
)}
|
||||
{/* After the first exit the primary action flips to Deliver, but a
|
||||
multi-truck booking still weighs its remaining trucks in and out. */}
|
||||
{item.status === 'READY_FOR_PICKUP' && item.releaseDate && nextAction !== 'release' && (
|
||||
<Button
|
||||
size="compact-xs"
|
||||
variant="light"
|
||||
color="yellow"
|
||||
loading={busy}
|
||||
onClick={() => onAdvance(item, 'release')}
|
||||
>
|
||||
Truck Arrival / Leaving
|
||||
</Button>
|
||||
)}
|
||||
{item.status === 'READY_FOR_PICKUP' && (
|
||||
<Button
|
||||
size="compact-xs"
|
||||
|
||||
@@ -23,23 +23,24 @@ export function WarehouseOpsKpiStrip() {
|
||||
delta:
|
||||
data != null ? data.receivedToday - data.receivedYesterday : undefined,
|
||||
hint: "vs yesterday",
|
||||
// The received cargo itself, on the inventory board.
|
||||
href: "/dashboard/warehouse-inventory?status=RECEIVED",
|
||||
// Exactly the items behind the counter: received today.
|
||||
href: "/dashboard/warehouse-inventory?receivedToday=1",
|
||||
},
|
||||
{
|
||||
label: "Pending inspection",
|
||||
value: data?.pendingInspection ?? 0,
|
||||
icon: ClipboardCheck,
|
||||
color: "yellow",
|
||||
// Received cargo still awaiting inspection lives in the RECEIVED bucket.
|
||||
href: "/dashboard/warehouse-inventory?status=RECEIVED",
|
||||
// RECEIVED items with no inspection recorded yet.
|
||||
href: "/dashboard/warehouse-inventory?pendingInspection=1",
|
||||
},
|
||||
{
|
||||
label: "Trucks on-site",
|
||||
value: data?.trucksOnSite ?? 0,
|
||||
icon: Truck,
|
||||
color: "blue",
|
||||
href: "/dashboard/trucks-on-site",
|
||||
// Land on the On-site tab — the counter excludes inbound trucks.
|
||||
href: "/dashboard/trucks-on-site?scope=ON_SITE",
|
||||
},
|
||||
{
|
||||
label: "Items aging (>7d)",
|
||||
@@ -47,8 +48,7 @@ export function WarehouseOpsKpiStrip() {
|
||||
icon: AlertTriangle,
|
||||
color: (data?.itemsAging ?? 0) > 0 ? "red" : "edr-green",
|
||||
hint: "In warehouse over 7 days",
|
||||
// No aging filter on the board; the inventory list is the landing.
|
||||
href: "/dashboard/warehouse-inventory",
|
||||
href: "/dashboard/warehouse-inventory?agingOverDays=7",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -69,6 +69,11 @@ export interface FleetFormFieldDef extends FormFieldDef {
|
||||
* (e.g. a license expiry); "past" (default) = cannot be in the future.
|
||||
*/
|
||||
dateBound?: "past" | "future";
|
||||
/**
|
||||
* Format the value must match, checked on submit. The value is upper-cased and
|
||||
* trimmed before the test, matching the server. Empty optional fields skip it.
|
||||
*/
|
||||
pattern?: { regex: RegExp; message: string; uppercase?: boolean };
|
||||
}
|
||||
|
||||
export interface FleetListFilterDef {
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
import type { FleetResourceConfig } from "./resources";
|
||||
|
||||
/**
|
||||
* A plate is two or three letters, a hyphen, then two to six digits — ET-9875,
|
||||
* AA-8642. Mirrors VEHICLE_PLATE_REGEX on the API so the form and the server
|
||||
* agree on what a plate looks like.
|
||||
*/
|
||||
const PLATE_PATTERN = {
|
||||
regex: /^[A-Z]{2,3}-\d{2,6}$/,
|
||||
message: "Use letters and numbers like ET-9875 or AA-8642",
|
||||
};
|
||||
|
||||
const VEHICLE_TYPE_OPTIONS = [
|
||||
{ label: "Truck", value: "TRUCK" },
|
||||
{ label: "Van", value: "VAN" },
|
||||
@@ -77,9 +87,9 @@ export const vehiclesConfig: FleetResourceConfig = {
|
||||
],
|
||||
formFields: [
|
||||
{ name: "code", label: "Code", type: "text" },
|
||||
{ name: "plateNumber", label: "Power Plate No", type: "text", required: true },
|
||||
{ name: "plateNumber", label: "Power Plate No", type: "text", required: true, pattern: PLATE_PATTERN },
|
||||
// { name: "powerPlateNo", label: "Power Plate No", type: "text" },
|
||||
{ name: "trailerPlateNo", label: "Trailer Plate No", type: "text" },
|
||||
{ name: "trailerPlateNo", label: "Trailer Plate No", type: "text", pattern: PLATE_PATTERN },
|
||||
{ name: "vehicleType", label: "Vehicle Type", type: "select", required: true, options: VEHICLE_TYPE_OPTIONS },
|
||||
{ name: "manufacturer", label: "Manufacturer", type: "text", required: true },
|
||||
{ name: "model", label: "Model", type: "text", required: true },
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import {
|
||||
Alert,
|
||||
Badge,
|
||||
@@ -139,7 +140,13 @@ function Rows({ rows }: { rows: TruckOnSite[] }) {
|
||||
|
||||
export default function TrucksOnSitePage() {
|
||||
const { data: trucks = [], isLoading } = useTrucksOnSite();
|
||||
const [scope, setScope] = useState<"ALL" | "ON_SITE" | "INBOUND">("ALL");
|
||||
// The dashboard's "Trucks on-site" card counts only arrived trucks, so it
|
||||
// deep-links here with ?scope=ON_SITE to land on the matching tab.
|
||||
const [searchParams] = useSearchParams();
|
||||
const scopeParam = searchParams.get("scope");
|
||||
const [scope, setScope] = useState<"ALL" | "ON_SITE" | "INBOUND">(
|
||||
scopeParam === "ON_SITE" || scopeParam === "INBOUND" ? scopeParam : "ALL",
|
||||
);
|
||||
const [source, setSource] = useState<"ALL" | "CUSTOMER" | "EDR">("ALL");
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useMemo, useState } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { Button, Card, Group, Select, Stack, TextInput } from '@mantine/core';
|
||||
import { useDebouncedValue } from '@mantine/hooks';
|
||||
import { PackageOpen, Search, Truck } from 'lucide-react';
|
||||
import { PackageOpen, Search, Truck, X } from 'lucide-react';
|
||||
|
||||
import { PageContainer, PageHeader } from '@/components/page';
|
||||
import {
|
||||
@@ -25,14 +25,36 @@ export default function WarehouseInventoryPage() {
|
||||
const [filter, setFilter] = useState<InventoryFilter>(
|
||||
initialStatus ? { status: initialStatus } : {},
|
||||
);
|
||||
// KPI drill-downs arriving from the ops dashboard cards; each shows as a
|
||||
// dismissible chip so the list can be widened back out in place.
|
||||
const [quick, setQuick] = useState<
|
||||
Pick<InventoryFilter, 'receivedToday' | 'pendingInspection' | 'agingOverDays'>
|
||||
>(() => {
|
||||
const aging = Number(searchParams.get('agingOverDays'));
|
||||
return {
|
||||
receivedToday: searchParams.get('receivedToday') ? true : undefined,
|
||||
pendingInspection: searchParams.get('pendingInspection') ? true : undefined,
|
||||
agingOverDays: Number.isFinite(aging) && aging > 0 ? aging : undefined,
|
||||
};
|
||||
});
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
const [debouncedSearch] = useDebouncedValue(search, 300);
|
||||
const queryFilter = useMemo<InventoryFilter>(
|
||||
() => ({ ...filter, direction, search: debouncedSearch || undefined }),
|
||||
[filter, direction, debouncedSearch],
|
||||
() => ({ ...filter, ...quick, direction, search: debouncedSearch || undefined }),
|
||||
[filter, quick, direction, debouncedSearch],
|
||||
);
|
||||
|
||||
const quickChips: Array<{ key: keyof typeof quick; label: string }> = [
|
||||
...(quick.receivedToday ? [{ key: 'receivedToday' as const, label: 'Received today' }] : []),
|
||||
...(quick.pendingInspection
|
||||
? [{ key: 'pendingInspection' as const, label: 'Pending inspection' }]
|
||||
: []),
|
||||
...(quick.agingOverDays
|
||||
? [{ key: 'agingOverDays' as const, label: `In warehouse >${quick.agingOverDays}d` }]
|
||||
: []),
|
||||
];
|
||||
|
||||
const warehousesQuery = useWarehouses();
|
||||
const yardsQuery = useWarehouseYards(filter.warehouseId);
|
||||
const zonesQuery = useWarehouseZones(filter.yardId);
|
||||
@@ -136,6 +158,17 @@ export default function WarehouseInventoryPage() {
|
||||
}
|
||||
w={200}
|
||||
/>
|
||||
{quickChips.map((chip) => (
|
||||
<Button
|
||||
key={chip.key}
|
||||
size="compact-xs"
|
||||
variant="light"
|
||||
rightSection={<X size={12} />}
|
||||
onClick={() => setQuick((q) => ({ ...q, [chip.key]: undefined }))}
|
||||
>
|
||||
{chip.label}
|
||||
</Button>
|
||||
))}
|
||||
</Group>
|
||||
|
||||
<InventoryWorkbench items={inventoryQuery.data ?? []} isLoading={inventoryQuery.isLoading} />
|
||||
|
||||
@@ -144,6 +144,8 @@ export interface LastMileArrivalTruck {
|
||||
driverPhone: string | null;
|
||||
truckType: string | null;
|
||||
containerNumber: string | null;
|
||||
arrivedAt: string | null;
|
||||
departedAt: string | null;
|
||||
}
|
||||
|
||||
export const warehouseService = {
|
||||
|
||||
@@ -1083,6 +1083,10 @@ export interface InventoryFilter {
|
||||
search?: string;
|
||||
dateFrom?: string;
|
||||
dateTo?: string;
|
||||
/** KPI drill-downs — mirror the ops-stats counters exactly. */
|
||||
receivedToday?: boolean;
|
||||
pendingInspection?: boolean;
|
||||
agingOverDays?: number;
|
||||
}
|
||||
|
||||
export interface InventoryInquiryFilter {
|
||||
|
||||
@@ -34,6 +34,7 @@ import { HeaderButton, PageHeader } from "./components/PageHeader";
|
||||
import { PaymentMethodModal } from "./components/PaymentMethodModal";
|
||||
import { ScheduleCard } from "./components/ScheduleCard";
|
||||
import { WarehousePaymentsSection } from "./components/WarehousePaymentsSection";
|
||||
import { WarehouseLocationCard } from "./components/WarehouseLocationCard";
|
||||
import { ShipmentDetailsCard } from "./components/ShipmentDetailsCard";
|
||||
import { ShipmentTrackingCard } from "./components/ShipmentTrackingCard";
|
||||
import { StatusHero } from "./components/StatusHero";
|
||||
@@ -273,6 +274,8 @@ export function ReadonlyBookingView({
|
||||
|
||||
<ContainersCard booking={booking} />
|
||||
|
||||
<WarehouseLocationCard bookingId={booking.id} />
|
||||
|
||||
<ContractInfoCard booking={booking} />
|
||||
|
||||
<ShipmentTrackingCard bookingId={booking.id} />
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Group, Paper, Stack, Text, Divider } from "@mantine/core";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Warehouse as WarehouseIcon } from "lucide-react";
|
||||
|
||||
import { warehouseService } from "@/services/warehouse.service";
|
||||
|
||||
interface WarehouseLocationCardProps {
|
||||
bookingId: string;
|
||||
}
|
||||
|
||||
function Row({ label, value }: { label: string; value: React.ReactNode }) {
|
||||
return (
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Text size="sm" c="dimmed">
|
||||
{label}
|
||||
</Text>
|
||||
<Text size="sm" fw={500} ta="right">
|
||||
{value}
|
||||
</Text>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
|
||||
export function WarehouseLocationCard({ bookingId }: WarehouseLocationCardProps) {
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["warehouse-inventory", bookingId],
|
||||
queryFn: () => warehouseService.listInventory({ bookingId }),
|
||||
});
|
||||
|
||||
const items = data ?? [];
|
||||
const latest = items[0];
|
||||
|
||||
return (
|
||||
<Paper withBorder radius="md" padding="lg">
|
||||
<Stack gap="md">
|
||||
<Group gap="xs">
|
||||
<WarehouseIcon size={18} />
|
||||
<Text fw={700}>Warehouse Location</Text>
|
||||
</Group>
|
||||
|
||||
<Divider />
|
||||
|
||||
{isLoading ? (
|
||||
<Text size="sm" c="dimmed">
|
||||
Loading…
|
||||
</Text>
|
||||
) : !latest ? (
|
||||
<Text size="sm" c="dimmed">
|
||||
Your cargo will appear here once it arrives at the warehouse.
|
||||
</Text>
|
||||
) : (
|
||||
<Stack gap="xs">
|
||||
<Row
|
||||
label="Warehouse"
|
||||
value={latest.warehouse ? `${latest.warehouse.name} (${latest.warehouse.code})` : "—"}
|
||||
/>
|
||||
<Row
|
||||
label="Yard"
|
||||
value={latest.yard ? `${latest.yard.name} (${latest.yard.code})` : "—"}
|
||||
/>
|
||||
<Row
|
||||
label="Zone"
|
||||
value={latest.zone ? `${latest.zone.name} (${latest.zone.code})` : "—"}
|
||||
/>
|
||||
<Row label="Arrived At" value={latest.arrivedAt ? new Date(latest.arrivedAt).toLocaleString() : "—"} />
|
||||
</Stack>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,15 @@
|
||||
import { Alert, Button, Group, Loader, Modal, Stack, Text, TextInput } from "@mantine/core";
|
||||
import {
|
||||
Alert,
|
||||
Badge,
|
||||
Button,
|
||||
Group,
|
||||
Loader,
|
||||
Modal,
|
||||
Stack,
|
||||
Text,
|
||||
TextInput,
|
||||
UnstyledButton,
|
||||
} from "@mantine/core";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { CheckCircle2, Info } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
@@ -36,7 +47,10 @@ const downloadBlob = (blob: Blob, filename: string) => {
|
||||
|
||||
/**
|
||||
* Approve-delivery flow: open the handover document for the customer to review,
|
||||
* then apply their saved signature (approve) and hand back the signed PDF.
|
||||
* then sign it with their typed full name (saved signature applied when present).
|
||||
* Self-haul: one booking-level handover, signed once. EDR last-mile: one
|
||||
* handover per delivering truck — the customer signs each; when the last one is
|
||||
* signed the delivery completes automatically.
|
||||
*/
|
||||
export function ApproveDeliveryModal({
|
||||
bookingId,
|
||||
@@ -48,15 +62,33 @@ export function ApproveDeliveryModal({
|
||||
const queryClient = useQueryClient();
|
||||
const [pdfUrl, setPdfUrl] = useState<string | null>(null);
|
||||
const [signerName, setSignerName] = useState("");
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
|
||||
const { data: handovers } = useQuery({
|
||||
queryKey: ["booking-handovers", bookingId],
|
||||
queryFn: () => bookingsService.listBookingHandovers(bookingId),
|
||||
enabled: opened && Boolean(bookingId),
|
||||
staleTime: 0,
|
||||
});
|
||||
|
||||
// Per-truck mode: any EDR last-mile handover means one signature per truck.
|
||||
const edrMode = (handovers ?? []).some((h) => h.mileType === "EDR_LAST_MILE");
|
||||
const unsigned = (handovers ?? []).filter((h) => !h.signedAt);
|
||||
const selected =
|
||||
(handovers ?? []).find((h) => h.id === selectedId && !h.signedAt) ?? unsigned[0] ?? null;
|
||||
|
||||
const {
|
||||
data: docBlob,
|
||||
isLoading,
|
||||
isError,
|
||||
} = useQuery({
|
||||
queryKey: ["booking-handover-doc", bookingId],
|
||||
queryFn: () => bookingsService.downloadBookingHandoverDocument(bookingId),
|
||||
enabled: opened && Boolean(bookingId),
|
||||
queryKey: ["booking-handover-doc", bookingId, edrMode ? selected?.id : "booking"],
|
||||
queryFn: () =>
|
||||
bookingsService.downloadBookingHandoverDocument(
|
||||
bookingId,
|
||||
edrMode ? selected?.id : undefined,
|
||||
),
|
||||
enabled: opened && Boolean(bookingId) && (!edrMode || Boolean(selected)),
|
||||
staleTime: 0,
|
||||
});
|
||||
|
||||
@@ -70,10 +102,32 @@ export function ApproveDeliveryModal({
|
||||
return () => URL.revokeObjectURL(url);
|
||||
}, [docBlob]);
|
||||
|
||||
const invalidateBooking = () =>
|
||||
Promise.all([
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: api.bookings.get.queryKey({ id: bookingId }),
|
||||
}),
|
||||
queryClient.invalidateQueries({ queryKey: api.bookings.list.queryKey() }),
|
||||
queryClient.invalidateQueries({ queryKey: ["companies", "getDashboard"] }),
|
||||
]);
|
||||
|
||||
const onSignError = (error: unknown) => {
|
||||
const message = errorMessage(error);
|
||||
toast.error(message);
|
||||
if (message.toLowerCase().includes("save your signature")) {
|
||||
onClose();
|
||||
navigate("/signature");
|
||||
} else if (/demurrage|storage|warehouse invoice|fully paid/i.test(message)) {
|
||||
onClose();
|
||||
navigate("/billing");
|
||||
}
|
||||
};
|
||||
|
||||
const handoverMutation = useMutation(
|
||||
api.bookings.downloadHandoverDocument.mutationOptions(),
|
||||
);
|
||||
|
||||
// Booking-level (self-haul) approval — signs every handover at once.
|
||||
const approve = useMutation({
|
||||
...api.bookings.approveDelivery.mutationOptions(),
|
||||
onSuccess: async (result) => {
|
||||
@@ -87,30 +141,35 @@ export function ApproveDeliveryModal({
|
||||
toast.success("Delivery approved and handover signed");
|
||||
toast.error("Signed handover document could not be downloaded");
|
||||
}
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: api.bookings.get.queryKey({ id: bookingId }),
|
||||
}),
|
||||
queryClient.invalidateQueries({ queryKey: api.bookings.list.queryKey() }),
|
||||
queryClient.invalidateQueries({ queryKey: ["companies", "getDashboard"] }),
|
||||
]);
|
||||
await invalidateBooking();
|
||||
onApproved?.();
|
||||
onClose();
|
||||
},
|
||||
onError: (error) => {
|
||||
const message = errorMessage(error);
|
||||
toast.error(message);
|
||||
if (message.toLowerCase().includes("save your signature")) {
|
||||
onClose();
|
||||
navigate("/signature");
|
||||
} else if (/demurrage|storage|warehouse invoice|fully paid/i.test(message)) {
|
||||
onClose();
|
||||
navigate("/billing");
|
||||
}
|
||||
},
|
||||
onError: onSignError,
|
||||
});
|
||||
|
||||
const busy = approve.isPending || handoverMutation.isPending;
|
||||
// Per-truck (EDR last-mile) signature — one handover at a time.
|
||||
const signOne = useMutation({
|
||||
mutationFn: ({ handoverId, name }: { handoverId: string; name: string }) =>
|
||||
bookingsService.signHandover(handoverId, name),
|
||||
onSuccess: async (result) => {
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: ["booking-handovers", bookingId],
|
||||
});
|
||||
setSelectedId(null);
|
||||
if (result.allSigned) {
|
||||
toast.success("All handovers signed — delivery confirmed");
|
||||
await invalidateBooking();
|
||||
onApproved?.();
|
||||
onClose();
|
||||
} else {
|
||||
toast.success("Handover signed — please sign the remaining truck(s)");
|
||||
}
|
||||
},
|
||||
onError: onSignError,
|
||||
});
|
||||
|
||||
const busy = approve.isPending || handoverMutation.isPending || signOne.isPending;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
@@ -123,12 +182,42 @@ export function ApproveDeliveryModal({
|
||||
<Stack gap="md">
|
||||
<Alert color="blue" variant="light" icon={<Info size={16} />}>
|
||||
<Text size="sm">
|
||||
Review the handover document below, then type your full name to sign and
|
||||
confirm you received the goods. Your saved signature is applied automatically
|
||||
if you have one.
|
||||
{edrMode
|
||||
? "Your goods were delivered by EDR truck(s). Review and sign the handover for each truck to confirm you received the goods — delivery completes once every truck is signed."
|
||||
: "Review the handover document below, then type your full name to sign and confirm you received the goods. Your saved signature is applied automatically if you have one."}
|
||||
</Text>
|
||||
</Alert>
|
||||
|
||||
{edrMode && (handovers?.length ?? 0) > 0 && (
|
||||
<Stack gap={4}>
|
||||
{handovers!.map((h) => (
|
||||
<UnstyledButton
|
||||
key={h.id}
|
||||
onClick={() => !h.signedAt && setSelectedId(h.id)}
|
||||
style={{
|
||||
padding: "8px 12px",
|
||||
borderRadius: 8,
|
||||
border:
|
||||
selected?.id === h.id
|
||||
? "1px solid var(--mantine-color-edr-green-6)"
|
||||
: "1px solid var(--mantine-color-gray-3)",
|
||||
cursor: h.signedAt ? "default" : "pointer",
|
||||
}}
|
||||
>
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Text size="sm" fw={600}>
|
||||
{h.truckPlate ? `Truck ${h.truckPlate}` : "Booking handover"} —{" "}
|
||||
{h.reference}
|
||||
</Text>
|
||||
<Badge color={h.signedAt ? "green" : "yellow"} variant="light">
|
||||
{h.signedAt ? `Signed${h.signerName ? ` — ${h.signerName}` : ""}` : "Awaiting signature"}
|
||||
</Badge>
|
||||
</Group>
|
||||
</UnstyledButton>
|
||||
))}
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
{isLoading ? (
|
||||
<Group justify="center" py="xl">
|
||||
<Loader size="sm" />
|
||||
@@ -170,10 +259,21 @@ export function ApproveDeliveryModal({
|
||||
color="edr-green"
|
||||
leftSection={<CheckCircle2 size={16} />}
|
||||
loading={busy}
|
||||
disabled={isLoading || isError || !signerName.trim()}
|
||||
onClick={() => approve.mutate({ id: bookingId, signerName: signerName.trim() })}
|
||||
disabled={
|
||||
isLoading ||
|
||||
isError ||
|
||||
!signerName.trim() ||
|
||||
(edrMode && !selected)
|
||||
}
|
||||
onClick={() =>
|
||||
edrMode && selected
|
||||
? signOne.mutate({ handoverId: selected.id, name: signerName.trim() })
|
||||
: approve.mutate({ id: bookingId, signerName: signerName.trim() })
|
||||
}
|
||||
>
|
||||
Approve & sign delivery
|
||||
{edrMode && selected?.truckPlate
|
||||
? `Sign for truck ${selected.truckPlate}`
|
||||
: "Approve & sign delivery"}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
|
||||
@@ -137,6 +137,26 @@ export interface ApproveDeliveryResponse {
|
||||
signerDisplayName: string;
|
||||
}
|
||||
|
||||
/** One import handover record — booking-level or per truck (EDR last-mile). */
|
||||
export interface BookingHandoverRecord {
|
||||
id: string;
|
||||
reference: string;
|
||||
truckPlate: string | null;
|
||||
mileType: "SELF_HAUL" | "EDR_LAST_MILE";
|
||||
generatedAt: string;
|
||||
signedAt: string | null;
|
||||
signerName: string | null;
|
||||
deliveredAt: string | null;
|
||||
}
|
||||
|
||||
export interface SignHandoverResponse {
|
||||
handoverId: string;
|
||||
bookingId: string;
|
||||
signedAt: string | null;
|
||||
signerDisplayName: string;
|
||||
allSigned: boolean;
|
||||
}
|
||||
|
||||
export interface CustomerTruckAssignmentPayload {
|
||||
truckPlateNumber: string;
|
||||
driverName: string;
|
||||
@@ -206,13 +226,36 @@ export const bookingsService = {
|
||||
);
|
||||
return data;
|
||||
},
|
||||
downloadBookingHandoverDocument: async (bookingId: string): Promise<Blob> => {
|
||||
downloadBookingHandoverDocument: async (
|
||||
bookingId: string,
|
||||
handoverId?: string,
|
||||
): Promise<Blob> => {
|
||||
const { data } = await client.get(
|
||||
`/api/warehouse-inventory/bookings/${bookingId}/handover-document`,
|
||||
{ responseType: "blob" },
|
||||
{ responseType: "blob", params: handoverId ? { handoverId } : undefined },
|
||||
);
|
||||
return data;
|
||||
},
|
||||
|
||||
listBookingHandovers: async (
|
||||
bookingId: string,
|
||||
): Promise<BookingHandoverRecord[]> => {
|
||||
const { data } = await client.get(
|
||||
`/api/warehouse-inventory/bookings/${bookingId}/handovers`,
|
||||
);
|
||||
return data.data ?? data;
|
||||
},
|
||||
|
||||
signHandover: async (
|
||||
handoverId: string,
|
||||
signerName: string,
|
||||
): Promise<SignHandoverResponse> => {
|
||||
const { data } = await client.post(
|
||||
`/api/warehouse-inventory/handovers/${handoverId}/sign`,
|
||||
{ signerName },
|
||||
);
|
||||
return data.data ?? data;
|
||||
},
|
||||
downloadBookingGrnDocument: async (bookingId: string): Promise<Blob> => {
|
||||
const { data } = await client.get(
|
||||
`/api/warehouse-inventory/bookings/${bookingId}/grn-document`,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { client } from "@/utils/api";
|
||||
|
||||
export interface InventoryFilter {
|
||||
bookingId?: string;
|
||||
}
|
||||
|
||||
export interface WarehouseInventoryItem {
|
||||
id: string;
|
||||
bookingId: string | null;
|
||||
warehouseId: string;
|
||||
yardId: string;
|
||||
zoneId: string;
|
||||
status: string;
|
||||
arrivedAt: string | null;
|
||||
warehouse?: {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
} | null;
|
||||
yard?: {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
} | null;
|
||||
zone?: {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface BookingScheduleView {
|
||||
schedule: {
|
||||
status: string;
|
||||
scheduledDepartureDate: string | null;
|
||||
scheduledArrivalDate: string | null;
|
||||
} | null;
|
||||
wagon?: {
|
||||
wagonNumber: string | null;
|
||||
sequenceNo: number | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export const warehouseService = {
|
||||
listInventory: async (filter?: InventoryFilter): Promise<WarehouseInventoryItem[]> => {
|
||||
const { data } = await client.get("/warehouse-inventory", {
|
||||
params: filter,
|
||||
});
|
||||
return data?.data ?? data ?? [];
|
||||
},
|
||||
|
||||
bookingSchedule: async (bookingId: string): Promise<BookingScheduleView> => {
|
||||
const { data } = await client.get(`/warehouse-inventory/booking-schedule/${bookingId}`);
|
||||
return data?.data ?? data ?? { schedule: null, wagon: null };
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user