Merge branch 'dev' of github.com:Tria-plc/edr-platform into contrat-backup2

This commit is contained in:
Marshal
2026-07-02 13:29:10 +00:00
71 changed files with 5165 additions and 672 deletions

View File

@@ -4,6 +4,7 @@ import {
ChevronRight,
Eye,
MoreHorizontal,
PackageCheck,
Printer,
RefreshCw,
Ruler,
@@ -35,6 +36,7 @@ import {
import { ruleEngineTable } from "@/components/ruleEngine/ruleEngineStyles";
import { FirstMileContainerAllocationTable } from "@/components/FirstMileContainerAllocationTable";
import { ReceiveInventoryModal } from "@/components/warehouses/ReceiveInventoryModal";
import { QUERY_KEYS } from "@/constants/QUERY_KEYS";
import { useToast } from "@/hooks/use-toast";
import {
@@ -338,6 +340,8 @@ const FirstMilePage = () => {
const [distanceValue, setDistanceValue] = useState("");
const [invoiceOpen, setInvoiceOpen] = useState(false);
const [invoiceRecord, setInvoiceRecord] = useState<FirstMileRecord | null>(null);
const [warehouseReceiveOpen, setWarehouseReceiveOpen] = useState(false);
const [warehouseReceiveRecord, setWarehouseReceiveRecord] = useState<FirstMileRecord | null>(null);
const [containerAllocationOpen, setContainerAllocationOpen] = useState(false);
const [containerAllocationFirstMileId, setContainerAllocationFirstMileId] = useState<string | null>(null);
@@ -527,6 +531,16 @@ const FirstMilePage = () => {
setInvoiceRecord(null);
};
const openWarehouseReceive = (record: FirstMileRecord) => {
setWarehouseReceiveRecord(record);
setWarehouseReceiveOpen(true);
};
const closeWarehouseReceive = () => {
setWarehouseReceiveOpen(false);
setWarehouseReceiveRecord(null);
};
const openContainerAllocation = (firstMileId: string) => {
setContainerAllocationFirstMileId(firstMileId);
setContainerAllocationOpen(true);
@@ -829,6 +843,7 @@ const FirstMilePage = () => {
const assigned = isAssigned(row.original);
const nextStatus = NEXT_STATUS[row.original.status];
const canPrint = row.original.status !== "PAYMENT_PENDING";
const canReceiveToWarehouse = row.original.status === "RECEIVED_TO_PORT";
return (
<Group gap={4} justify="flex-end" wrap="nowrap">
<Menu position="bottom-end" width={200} withinPortal>
@@ -867,6 +882,13 @@ const FirstMilePage = () => {
>
View detail
</Menu.Item>
<Menu.Item
leftSection={<PackageCheck size={15} />}
disabled={!canReceiveToWarehouse}
onClick={() => openWarehouseReceive(row.original)}
>
Receive to warehouse
</Menu.Item>
<Menu.Item
leftSection={<Ruler size={15} />}
onClick={() => openDistance(row.original.id)}
@@ -1055,6 +1077,19 @@ const FirstMilePage = () => {
</Stack>
</Modal>
<ReceiveInventoryModal
opened={warehouseReceiveOpen}
onClose={closeWarehouseReceive}
mode="bulk"
direction="EXPORT"
bookingId={warehouseReceiveRecord?.bookingId}
bookingLabel={warehouseReceiveRecord ? bookingRef(warehouseReceiveRecord) : undefined}
onReceived={() => {
void qc.invalidateQueries({ queryKey: QUERY_KEYS.FIRST_MILE.list() });
closeWarehouseReceive();
}}
/>
{/* Accept Booking modal — step 1: booking list, step 2: details + vehicle */}
<Modal
opened={acceptOpen}

View File

@@ -31,7 +31,7 @@ import {
TextInput,
UnstyledButton,
} from "@mantine/core";
import type { ArrivalQueueItem } from "@/types/warehouse";
import type { ArrivalQueueItem, ImportUnloadedItem, WarehouseInventoryItem } from "@/types/warehouse";
import { warehouseService } from "@/services/warehouse.service";
import { ruleEngineTable } from "@/components/ruleEngine/ruleEngineStyles";
@@ -44,8 +44,10 @@ import {
lastMileService,
} from "@/services/last-mile.service";
import { vehiclesService } from "@/services/vehicles.service";
import { driversService, type Driver } from "@/services/drivers.service";
import { ratesService } from "@/services/rates.service";
import { LastMileContainerAllocationTable, type LastMileContainerRow } from "@/components/LastMileContainerAllocationTable";
import { ReleaseOrderModal, type ReleaseOrderTruckPrefill } from "@/components/warehouses/ReleaseOrderModal";
import { api } from "@/auth/http";
const formatPrice = (amount: number) =>
@@ -110,6 +112,59 @@ const requestedDate = (r: LastMileRecord) => {
const serviceTypeName = (r: LastMileRecord) =>
r.booking?.serviceType?.label ?? r.booking?.serviceType?.name ?? "—";
const toReleaseInventoryItem = (row: ImportUnloadedItem): WarehouseInventoryItem =>
({
id: row.id,
bookingId: row.bookingId,
quantity: 1,
weight: Number(row.weight) || 0,
grnNumber: row.grnNumber,
status: row.currentStatus,
arrivedAt: row.arrivalTime,
unloadedAt: row.arrivalTime,
inspectionStatus: row.inspectionStatus,
releaseDate: row.releaseDate,
releaseOrderReference: row.releaseOrderReference,
handoverDocumentReference: row.handoverDocumentReference,
handoverDocumentDate: row.handoverDocumentDate,
deliveredAt: row.deliveredAt,
booking: row.bookingId
? {
id: row.bookingId,
reference: row.bookingReference ?? row.bookingId,
tradeDirection: "IMPORT",
lastMileDeliveryAddress: row.lastMileRequested ? row.pickupOption : null,
customerTruckPlateNumber: row.customerTruckPlateNumber,
customerTruckDriverName: row.customerTruckDriverName,
customerTruckType: row.customerTruckType,
customerTruckContainerNumber: row.customerTruckContainerNumber,
customerTruckAssignedAt: row.customerTruckAssignedAt,
}
: null,
}) as unknown as WarehouseInventoryItem;
const releasePrefillFromLastMile = (
record: LastMileRecord,
row?: ImportUnloadedItem | null,
driversById?: Map<string, Driver>,
): ReleaseOrderTruckPrefill => {
const vehicle = record.vehicle;
const truckType = [vehicle?.manufacturer, vehicle?.model].filter(Boolean).join(" ").trim();
const assignedDriver = vehicle?.assignedDriverId ? driversById?.get(vehicle.assignedDriverId) : undefined;
const assignedDriverName = assignedDriver
? `${assignedDriver.firstName ?? ""} ${assignedDriver.lastName ?? ""}`.trim()
: "";
return {
truckPlateNumber: vehicle?.powerPlateNo || vehicle?.plateNumber || null,
trailerPlateNumber: vehicle?.trailerPlateNo || null,
driverName: vehicle?.assignedDriverName || assignedDriverName || null,
driverLicense: assignedDriver?.licenseNumber || null,
driverPhone: assignedDriver?.phoneNumber || null,
truckType: vehicle?.vehicleType || truckType || null,
containerNumber: row?.containerNumber ?? null,
};
};
const InfoRow = ({ label, value }: { label: string; value: string }) => (
<Stack gap={2}>
<Text size="xs" c="dimmed" tt="uppercase" fw={600}>{label}</Text>
@@ -325,6 +380,8 @@ const LastMilePage = () => {
const [allocationOpen, setAllocationOpen] = useState(false);
const [allocationContainers, setAllocationContainers] = useState<LastMileContainerRow[]>([]);
const [releaseItem, setReleaseItem] = useState<WarehouseInventoryItem | null>(null);
const [releaseTruckPrefill, setReleaseTruckPrefill] = useState<ReleaseOrderTruckPrefill | null>(null);
const { data: listData, isLoading } = useQuery({
queryKey: QUERY_KEYS.LAST_MILE.list(),
@@ -352,6 +409,27 @@ const LastMilePage = () => {
const records = listData?.data ?? [];
const needsDriverLookup = records.some((record) => record.vehicle?.assignedDriverId);
const { data: driversData } = useQuery({
queryKey: ["drivers", "list", "ACTIVE"],
queryFn: async () => {
const res = await driversService.getAll({ status: "ACTIVE" });
return res.data;
},
enabled: needsDriverLookup,
});
const driversById = useMemo(
() => new Map((driversData ?? []).map((driver) => [driver.id, driver])),
[driversData],
);
const { data: pickupReadyRows = [] } = useQuery({
queryKey: ["warehouse-inventory", "import-pickup-ready-queue"],
queryFn: () => warehouseService.importPickupReadyQueue().then((r) => r.data),
});
const vehicleOptions = useMemo(
() =>
(Array.isArray(vehiclesData) ? vehiclesData : []).map((v) => {
@@ -533,6 +611,15 @@ const LastMilePage = () => {
[records, activeId],
);
const pickupReadyByBooking = useMemo(() => {
const map = new Map<string, ImportUnloadedItem>();
for (const row of pickupReadyRows) {
if (row.bookingId) map.set(row.bookingId, row);
if (row.bookingReference) map.set(row.bookingReference, row);
}
return map;
}, [pickupReadyRows]);
const selectedIds = useMemo(
() => Object.keys(rowSelection).filter((id) => rowSelection[id]),
[rowSelection],
@@ -569,6 +656,7 @@ const LastMilePage = () => {
const term = search.trim().toLowerCase();
return records.filter((r) => {
if (!matchesFilter(r)) return false;
if (filterPostPaymentPending && !(r.remainingPayment > 0)) return false;
if (!term) return true;
return [bookingRef(r), customerName(r), deliveryLocation(r), cargoDesc(r)]
.join(" ")
@@ -649,6 +737,37 @@ const LastMilePage = () => {
setTripSlipOpen(true);
};
const openTruckArrival = (record: LastMileRecord) => {
if (!isAssigned(record)) {
toast({
title: "Assign a truck first",
description: "Truck arrival opens after a last-mile vehicle is assigned.",
variant: "destructive",
});
return;
}
const row = pickupReadyByBooking.get(record.bookingId) ?? pickupReadyByBooking.get(bookingRef(record));
if (!row) {
toast({
title: "Import inventory is not pickup-ready",
description: `${bookingRef(record)} must be unloaded and pass inspection before truck arrival.`,
variant: "destructive",
});
return;
}
setReleaseTruckPrefill(releasePrefillFromLastMile(record, row, driversById));
setReleaseItem(toReleaseInventoryItem(row));
};
const closeTruckArrival = () => {
setReleaseItem(null);
setReleaseTruckPrefill(null);
void qc.invalidateQueries({ queryKey: ["warehouse-inventory"] });
void qc.invalidateQueries({ queryKey: QUERY_KEYS.LAST_MILE.ROOT });
};
const printTripSlip = () => {
if (!tripSlipRecord) return;
const win = window.open("", "_blank", "width=820,height=920");
@@ -809,6 +928,9 @@ const LastMilePage = () => {
const assigned = isAssigned(row.original);
const nextStatus = NEXT_STATUS[row.original.status];
const canPrint = row.original.status !== "PAYMENT_PENDING";
const releaseRow =
pickupReadyByBooking.get(row.original.bookingId) ?? pickupReadyByBooking.get(bookingRef(row.original));
const truckArrivalLabel = releaseRow?.releaseOrderReference ? "Truck Leaving" : "Truck Arrival";
return (
<Group gap={4} justify="flex-end" wrap="nowrap">
<Menu position="bottom-end" width={200} withinPortal>
@@ -840,6 +962,13 @@ const LastMilePage = () => {
>
Reassign
</Menu.Item>
<Menu.Item
leftSection={<Truck size={15} />}
disabled={!assigned}
onClick={() => openTruckArrival(row.original)}
>
{truckArrivalLabel}
</Menu.Item>
<Menu.Divider />
<Menu.Item
leftSection={<Eye size={15} />}
@@ -869,7 +998,7 @@ const LastMilePage = () => {
},
];
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [vehicleOptions]);
}, [vehicleOptions, pickupReadyByBooking]);
return (
<Stack gap="md">
@@ -1358,6 +1487,13 @@ const LastMilePage = () => {
</Group>
</Stack>
</Modal>
<ReleaseOrderModal
opened={Boolean(releaseItem)}
onClose={closeTruckArrival}
item={releaseItem}
truckPrefill={releaseTruckPrefill}
/>
</Stack>
);
};

View File

@@ -9,6 +9,8 @@ import {
RingProgress,
Stack,
Text,
Textarea,
TextInput,
ThemeIcon,
Title,
} from "@mantine/core";
@@ -88,6 +90,10 @@ export default function TrainScheduleV2DetailPage() {
const [previewResult, setPreviewResult] = useState<TrainSchedulePreviewResponse | null>(null);
const [containerPlacements, setContainerPlacements] = useState<ContainerPlacement[]>([]);
const [maintenanceOpen, setMaintenanceOpen] = useState(false);
const [gatepassSecuredAt, setGatepassSecuredAt] = useState("");
const [gatepassReference, setGatepassReference] = useState("");
const [gatepassFileUrl, setGatepassFileUrl] = useState("");
const [gatepassNotes, setGatepassNotes] = useState("");
const autoPreviewedRef = useRef(false);
const detailQuery = useQuery(
@@ -98,6 +104,42 @@ export default function TrainScheduleV2DetailPage() {
);
const schedule = detailQuery.data;
const freightType: FreightType | undefined = schedule?.freightType as FreightType | undefined;
const isDjiboutiPort = (value?: string | null) =>
["DJIBOUTI", "DORALEH", "DMP", "DCT", "NAGAD"].some((token) =>
(value ?? "").toUpperCase().includes(token),
);
const gatepassApplies = Boolean(
schedule &&
((schedule.direction === "IMPORT" &&
isDjiboutiPort(`${schedule.originStation?.code ?? ""} ${schedule.originStation?.label ?? ""}`)) ||
(schedule.direction === "EXPORT" &&
isDjiboutiPort(`${schedule.destinationStation?.code ?? ""} ${schedule.destinationStation?.label ?? ""}`))),
);
const gatepassQuery = useQuery({
queryKey: ["train-scheduling", "gatepass", scheduleId],
queryFn: () => trainSchedulingService.getImportDjiboutiOperation(scheduleId as string),
enabled: Boolean(scheduleId && gatepassApplies),
});
const secureGatepass = useMutation({
mutationFn: () =>
trainSchedulingService.grantImportDjiboutiGatepass(scheduleId as string, {
securedAt: gatepassSecuredAt ? new Date(gatepassSecuredAt).toISOString() : undefined,
reference: gatepassReference.trim() || undefined,
fileUrl: gatepassFileUrl.trim() || undefined,
notes: gatepassNotes.trim() || undefined,
}),
onSuccess: () => {
toast({ title: "Gate pass secured" });
void gatepassQuery.refetch();
},
onError: (error) => {
toast({
title: "Gate pass failed",
description: parseError(error, "Could not secure gate pass"),
variant: "destructive",
});
},
});
const eligibleFilters = useMemo(
() =>
@@ -133,6 +175,16 @@ export default function TrainScheduleV2DetailPage() {
: trainSchedulingService.downloadImportDjiboutiLoadListDocument(id),
});
useEffect(() => {
const operation = gatepassQuery.data;
if (!operation) return;
const secured = operation.gatepassSecuredAt ?? operation.gatepassGrantedAt;
setGatepassSecuredAt(secured ? new Date(secured).toISOString().slice(0, 16) : "");
setGatepassReference(operation.documents?.GATE_PASS?.reference ?? "");
setGatepassFileUrl(operation.documents?.GATE_PASS?.fileUrl ?? "");
setGatepassNotes(operation.documents?.GATE_PASS?.notes ?? operation.notes ?? "");
}, [gatepassQuery.data]);
const assignedIds = useMemo(
() => (schedule?.bookings ?? []).map((b) => b.id),
[schedule?.bookings],
@@ -899,6 +951,83 @@ export default function TrainScheduleV2DetailPage() {
]}
/>
{gatepassApplies ? (
<Paper radius="xl" p="lg" withBorder>
<Stack gap="md">
<Group justify="space-between" align="flex-start" wrap="wrap">
<Group gap="md" align="flex-start" wrap="nowrap">
<ThemeIcon
size={44}
radius="md"
variant="light"
color={gatepassQuery.data?.gatepassStatus === "SECURED" ? "edr-green" : "orange"}
>
<FileText size={22} />
</ThemeIcon>
<Stack gap={4}>
<Group gap="sm">
<Title order={4} fw={700}>
Djibouti Port gate pass
</Title>
<Badge
color={gatepassQuery.data?.gatepassStatus === "SECURED" ? "green" : "orange"}
variant="light"
>
{gatepassQuery.data?.gatepassStatus ?? "NOT_SECURED"}
</Badge>
</Group>
<Text size="sm" c="dimmed">
{schedule.direction === "IMPORT"
? "Secure before dispatch from Djibouti."
: "Secure after dispatch before Djibouti Port entry / unloading."}
</Text>
</Stack>
</Group>
{gatepassQuery.isLoading ? <Loader size="sm" /> : null}
</Group>
<Group align="flex-end" grow>
<TextInput
label="Secured date"
type="datetime-local"
value={gatepassSecuredAt}
onChange={(event) => setGatepassSecuredAt(event.currentTarget.value)}
/>
<TextInput
label="Document reference"
placeholder="Optional"
value={gatepassReference}
onChange={(event) => setGatepassReference(event.currentTarget.value)}
/>
<TextInput
label="Document URL"
placeholder="Optional upload/link"
value={gatepassFileUrl}
onChange={(event) => setGatepassFileUrl(event.currentTarget.value)}
/>
</Group>
<Textarea
label="Notes"
placeholder="Optional"
autosize
minRows={2}
value={gatepassNotes}
onChange={(event) => setGatepassNotes(event.currentTarget.value)}
/>
<Group justify="flex-end">
<Button
color="edr-green"
leftSection={<CheckCircle2 size={16} />}
loading={secureGatepass.isPending}
onClick={() => secureGatepass.mutate()}
>
Save as Secured
</Button>
</Group>
</Stack>
</Paper>
) : null}
<Paper radius="xl" p="lg">
<Stack gap="lg">
{/* Workflow header with ring progress */}

View File

@@ -1,4 +1,4 @@
import { Fragment, useState } from 'react';
import { Fragment, useEffect, useMemo, useState } from 'react';
import {
Badge,
Button,
@@ -6,6 +6,7 @@ import {
Container,
Group,
Loader,
Select,
Stack,
Table,
Text,
@@ -21,11 +22,17 @@ import {
} from '@/components/warehouses';
import {
useAutoUnloadArrivedBookings,
useAllWarehouseYards,
useAllWarehouseZones,
useImportArriveQueue,
useImportTrainItems,
useWarehouses,
} from '@/hooks/useWarehouses';
import { useToast } from '@/hooks/use-toast';
import type { AutoUnloadArrivedResult, ImportTrain, ImportTrainItem } from '@/types/warehouse';
import type { AutoUnloadArrivedResult, ImportTrain, ImportTrainItem, Warehouse, WarehouseYard, WarehouseZone } from '@/types/warehouse';
type UnloadAssignment = { bookingId: string; warehouseId: string; yardId: string; zoneId: string };
type AssignmentDraft = Partial<Omit<UnloadAssignment, 'bookingId'>>;
const getErrorMessage = (error: unknown) => {
if (error && typeof error === 'object' && 'response' in error) {
@@ -43,8 +50,54 @@ const getPendingUnloadBookings = (train: ImportTrain) =>
const isFullyUnloaded = (train: ImportTrain) =>
Boolean(train.fullyUnloaded) || (train.totalBookings > 0 && getPendingUnloadBookings(train) === 0);
function ImportTrainDetailRows({ scheduleId }: { scheduleId: string }) {
const locationTypesForFreight = (freightType: string | null | undefined) => {
const normalized = (freightType ?? '').toUpperCase();
if (normalized === 'CONTAINER') {
return { yardTypes: ['CONTAINER_YARD', 'GENERAL_CARGO_YARD'], zoneTypes: ['CONTAINER_ZONE', 'GENERAL_CARGO_ZONE'] };
}
return { yardTypes: ['BULK_YARD', 'GENERAL_CARGO_YARD'], zoneTypes: ['BULK_ZONE', 'GENERAL_CARGO_ZONE'] };
};
const isContainerFreight = (freightType: string | null | undefined) =>
(freightType ?? '').toUpperCase() === 'CONTAINER';
function isUnloadPending(item: ImportTrainItem) {
return !item.currentStatus || item.currentStatus === 'RECEIVED';
}
function ImportTrainDetailRows({
scheduleId,
warehouses,
yards,
zones,
assignments,
onAssignmentChange,
onReadyChange,
}: {
scheduleId: string;
warehouses: Warehouse[];
yards: WarehouseYard[];
zones: WarehouseZone[];
assignments: Record<string, AssignmentDraft>;
onAssignmentChange: (bookingId: string, draft: AssignmentDraft) => void;
onReadyChange: (ready: boolean) => void;
}) {
const { data: items = [], isLoading } = useImportTrainItems(scheduleId);
const warehouseOptions = useMemo(
() => warehouses.map((warehouse) => ({ value: warehouse.id, label: `${warehouse.name} (${warehouse.code})` })),
[warehouses],
);
useEffect(() => {
const pending = items.filter(isUnloadPending);
onReadyChange(
pending.length > 0 &&
pending.every((item) => {
const draft = assignments[item.bookingId];
return Boolean(draft?.warehouseId && draft.yardId && draft.zoneId);
}),
);
}, [assignments, items]);
if (isLoading) {
return (
@@ -73,12 +126,26 @@ function ImportTrainDetailRows({ scheduleId }: { scheduleId: string }) {
<Table.Th>Weight</Table.Th>
<Table.Th>Arrival</Table.Th>
<Table.Th>Status</Table.Th>
<Table.Th>Warehouse</Table.Th>
<Table.Th>Yard</Table.Th>
<Table.Th>Zone</Table.Th>
<Table.Th>Inspection</Table.Th>
<Table.Th>Pickup</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{items.map((item: ImportTrainItem) => (
{items.map((item: ImportTrainItem) => {
const draft = assignments[item.bookingId] ?? {};
const { yardTypes, zoneTypes } = locationTypesForFreight(item.freightType);
const yardOptions = yards
.filter((yard) => yard.warehouseId === draft.warehouseId && yardTypes.includes(yard.type))
.map((yard) => ({ value: yard.id, label: `${yard.name} (${yard.code})` }));
const zoneOptions = zones
.filter((zone) => zone.yardId === draft.yardId && zoneTypes.includes(zone.type))
.map((zone) => ({ value: zone.id, label: `${zone.name} (${zone.code})` }));
const pending = isUnloadPending(item);
return (
<Table.Tr key={item.bookingId}>
<Table.Td>
<Text size="sm" fw={600}>
@@ -95,6 +162,41 @@ function ImportTrainDetailRows({ scheduleId }: { scheduleId: string }) {
{item.currentStatus ?? 'PENDING'}
</Badge>
</Table.Td>
<Table.Td>
<Select
placeholder="Warehouse"
data={warehouseOptions}
value={draft.warehouseId ?? null}
onChange={(value) => onAssignmentChange(item.bookingId, { warehouseId: value ?? undefined })}
searchable
disabled={!pending}
w={210}
/>
</Table.Td>
<Table.Td>
<Select
placeholder={isContainerFreight(item.freightType) ? 'Container yard' : 'Bulk yard'}
data={yardOptions}
value={draft.yardId ?? null}
onChange={(value) =>
onAssignmentChange(item.bookingId, { ...draft, yardId: value ?? undefined, zoneId: undefined })
}
searchable
disabled={!pending || !draft.warehouseId}
w={190}
/>
</Table.Td>
<Table.Td>
<Select
placeholder={isContainerFreight(item.freightType) ? 'Container zone' : 'Bulk zone'}
data={zoneOptions}
value={draft.zoneId ?? null}
onChange={(value) => onAssignmentChange(item.bookingId, { ...draft, zoneId: value ?? undefined })}
searchable
disabled={!pending || !draft.yardId}
w={190}
/>
</Table.Td>
<Table.Td>
<Badge variant="light" color={item.inspectionStatus === 'PASSED' ? 'green' : 'gray'} size="sm">
{item.inspectionStatus ?? 'Not inspected'}
@@ -102,7 +204,8 @@ function ImportTrainDetailRows({ scheduleId }: { scheduleId: string }) {
</Table.Td>
<Table.Td>{item.pickupOption.replace(/_/g, ' ')}</Table.Td>
</Table.Tr>
))}
);
})}
</Table.Tbody>
</Table>
);
@@ -112,11 +215,36 @@ function ImportTrainDetailRows({ scheduleId }: { scheduleId: string }) {
export default function ArrivalQueuePage() {
const { toast } = useToast();
const { data: trains = [], isLoading } = useImportArriveQueue();
const { data: warehouses = [], isLoading: warehousesLoading } = useWarehouses({ status: 'ACTIVE' });
const { data: yards = [] } = useAllWarehouseYards();
const { data: zones = [] } = useAllWarehouseZones();
const autoUnload = useAutoUnloadArrivedBookings();
const [openScheduleId, setOpenScheduleId] = useState<string | null>(null);
const [busyScheduleId, setBusyScheduleId] = useState<string | null>(null);
const [assignmentsBySchedule, setAssignmentsBySchedule] = useState<Record<string, Record<string, AssignmentDraft>>>({});
const [readyBySchedule, setReadyBySchedule] = useState<Record<string, boolean>>({});
const unloadTrain = async (train: ImportTrain) => {
const assignments = Object.entries(assignmentsBySchedule[train.scheduleId] ?? {})
.filter((entry): entry is [string, Required<AssignmentDraft>] =>
Boolean(entry[1].warehouseId && entry[1].yardId && entry[1].zoneId),
)
.map(([bookingId, draft]) => ({
bookingId,
warehouseId: draft.warehouseId,
yardId: draft.yardId,
zoneId: draft.zoneId,
}));
if (!readyBySchedule[train.scheduleId] || assignments.length === 0) {
toast({
variant: 'destructive',
title: 'Assign locations',
description: 'Select warehouse, yard and zone for each pending booking before unloading.',
});
return;
}
if (isFullyUnloaded(train)) {
toast({
title: 'Already unloaded',
@@ -127,7 +255,9 @@ export default function ArrivalQueuePage() {
setBusyScheduleId(train.scheduleId);
try {
const res = (await autoUnload.mutateAsync(train.scheduleId)) as { data: AutoUnloadArrivedResult };
const res = (await autoUnload.mutateAsync({ scheduleId: train.scheduleId, assignments })) as {
data: AutoUnloadArrivedResult;
};
const result = res.data;
const alreadyUnloaded = result.unloadedCount === 0 && result.skippedCount > 0 && result.failedCount === 0;
const firstReason = result.results.find((item) => item.reason)?.reason;
@@ -169,10 +299,12 @@ export default function ArrivalQueuePage() {
<Card withBorder radius="md" padding="lg">
<Group justify="space-between" mb="md">
<Text fw={600}>{trains.length} arrived import train(s)</Text>
<Text size="sm" c="dimmed">
Open a train to review assigned bookings, then auto unload it.
</Text>
<Stack gap={2}>
<Text fw={600}>{trains.length} arrived import train(s)</Text>
<Text size="sm" c="dimmed">
Open a train, assign each booking to a warehouse yard and zone, then unload it.
</Text>
</Stack>
</Group>
{isLoading ? (
@@ -254,7 +386,7 @@ export default function ArrivalQueuePage() {
color={fullyUnloaded ? 'gray' : 'orange'}
leftSection={busyScheduleId === train.scheduleId ? <PackageOpen size={14} /> : <Truck size={14} />}
loading={busyScheduleId === train.scheduleId}
disabled={fullyUnloaded || train.totalBookings === 0}
disabled={fullyUnloaded || train.totalBookings === 0 || !readyBySchedule[train.scheduleId] || warehousesLoading}
onClick={() => unloadTrain(train)}
>
{fullyUnloaded ? 'Already Unloaded' : 'Auto Unload'}
@@ -265,7 +397,27 @@ export default function ArrivalQueuePage() {
{isOpen && (
<Table.Tr>
<Table.Td colSpan={10} bg="var(--mantine-color-gray-0)">
<ImportTrainDetailRows scheduleId={train.scheduleId} />
<ImportTrainDetailRows
scheduleId={train.scheduleId}
warehouses={warehouses}
yards={yards}
zones={zones}
assignments={assignmentsBySchedule[train.scheduleId] ?? {}}
onAssignmentChange={(bookingId, draft) =>
setAssignmentsBySchedule((current) => ({
...current,
[train.scheduleId]: {
...(current[train.scheduleId] ?? {}),
[bookingId]: draft.warehouseId
? draft
: {},
},
}))
}
onReadyChange={(ready) =>
setReadyBySchedule((current) => ({ ...current, [train.scheduleId]: ready }))
}
/>
</Table.Td>
</Table.Tr>
)}

View File

@@ -1,4 +1,4 @@
import { useMemo, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import {
ActionIcon,
Badge,
@@ -29,6 +29,7 @@ import { useToast } from '@/hooks/use-toast';
import {
WAREHOUSE_INVOICE_STATUSES,
type WarehouseFeeInvoice,
type WarehouseGatewayPaymentMethod,
type WarehouseInvoiceStatus,
} from '@/types/warehouse';
import { openPdfBlob } from '@/components/warehouses/pdf';
@@ -164,15 +165,23 @@ function InvoiceDetailModal({ id, onClose }: { id: string | null; onClose: () =>
}),
);
const pay = useMutation(api.warehouses.payInvoice.mutationOptions());
const payOnline = useMutation(api.warehouses.payInvoiceOnline.mutationOptions());
const cancel = useMutation(api.warehouses.cancelInvoice.mutationOptions());
const gateClear = useMutation(api.warehouses.gateClearance.mutationOptions());
const [payAmount, setPayAmount] = useState<number | ''>('');
const [driverName, setDriverName] = useState('');
const [driverPhone, setDriverPhone] = useState('');
const [gatewayMethod, setGatewayMethod] = useState<WarehouseGatewayPaymentMethod>('TELEBIRR');
const [payerAccount, setPayerAccount] = useState('');
const canPay = inv && (inv.status === 'ISSUED' || inv.status === 'PARTIALLY_PAID');
const canGateClear = inv?.status === 'PAID' && Boolean(inv.inventoryId);
useEffect(() => {
setGatewayMethod(inv?.currency === 'USD' ? 'WAAFI' : 'TELEBIRR');
setPayerAccount('');
}, [inv?.id, inv?.currency]);
const downloadInvoicePdf = async (invoice: WarehouseFeeInvoice) => {
const pdfWindow = window.open('', '_blank');
try {
@@ -302,6 +311,34 @@ function InvoiceDetailModal({ id, onClose }: { id: string | null; onClose: () =>
}
};
const handleOnlinePay = async () => {
if (!inv) return;
try {
const currentUrl = window.location.href;
const result = await payOnline.mutateAsync({
id: inv.id,
payload: {
method: gatewayMethod,
platform: 'web',
payerAccount: payerAccount.trim() || undefined,
returnUrl: currentUrl,
failureUrl: currentUrl,
},
});
const url = result.clientAction?.url;
if (url) {
window.location.href = url;
return;
}
toast({
title: 'Payment initiated',
description: 'No redirect URL was returned by the payment provider.',
});
} catch (e) {
toast({ variant: 'destructive', title: 'Payment failed', description: extractErrorMessage(e) });
}
};
const handleCancel = async () => {
if (!inv) return;
try {
@@ -359,7 +396,31 @@ function InvoiceDetailModal({ id, onClose }: { id: string | null; onClose: () =>
{canPay && (
<>
<Divider label="Record payment" labelPosition="left" />
<Divider label="Online payment" labelPosition="left" />
<Group align="flex-end">
<Select
label="Provider"
value={gatewayMethod}
onChange={(v) => setGatewayMethod((v as WarehouseGatewayPaymentMethod) ?? 'TELEBIRR')}
data={[
{ value: 'TELEBIRR', label: 'Telebirr' },
{ value: 'WAAFI', label: 'Waafi' },
]}
style={{ flex: 1 }}
/>
<TextInput
label="Wallet phone / account"
value={payerAccount}
onChange={(e) => setPayerAccount(e.currentTarget.value)}
placeholder="Optional"
style={{ flex: 1 }}
/>
<Button leftSection={<CreditCard size={16} />} loading={payOnline.isPending} onClick={handleOnlinePay}>
Pay with {gatewayMethod === 'WAAFI' ? 'Waafi' : 'Telebirr'}
</Button>
</Group>
<Divider label="Record manual payment" labelPosition="left" />
<Group align="flex-end">
<NumberInput
label="Amount"

View File

@@ -18,6 +18,8 @@ import {
} from '@mantine/core';
import { Info, Plus, Trash2 } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import { PageContainer, PageHeader } from '@/components/page';
import { useToast } from '@/hooks/use-toast';
import {
@@ -29,7 +31,9 @@ import {
useDeleteFeeRule,
useFeeRules,
} from '@/hooks/useWarehouses';
import { api } from '@/services/api';
import { FEE_RULE_TYPES, type FeeRuleType } from '@/types/warehouse';
import { extractErrorMessage } from '@/components/warehouses/options';
const FREIGHT = [
{ value: 'CONTAINER', label: 'Container' },
@@ -38,6 +42,7 @@ const FREIGHT = [
const TRADE = [
{ value: 'IMPORT', label: 'Import' },
{ value: 'EXPORT', label: 'Export' },
{ value: 'BOTH', label: 'Import & Export' },
{ value: 'DOMESTIC', label: 'Domestic' },
];
const CURRENCIES = [
@@ -53,6 +58,23 @@ const numberValue = (value: string | number, fallback = 0) => {
};
const anyLabel = (value: string, label: string) => value.trim() || `Any ${label}`;
const dash = '-';
type CodeOptionSource = {
id?: string;
code?: string;
cargoTypeName?: string;
label?: string;
name?: string;
};
const codeOptions = (rows: unknown[]) =>
(rows as CodeOptionSource[])
.filter((row) => row.code)
.map((row) => ({
value: row.code as string,
label: `${row.cargoTypeName ?? row.label ?? row.name ?? row.code} (${row.code})`,
}));
const isUnknownTiersError = (error: unknown) => extractErrorMessage(error).includes('property tiers should not exist');
export default function WarehouseRulesPage() {
return (
@@ -319,6 +341,12 @@ function AllocationRules() {
function FeeRules() {
const { toast } = useToast();
const { data, isLoading } = useFeeRules();
const { data: cargoTypes = [], isLoading: cargoTypesLoading } = useQuery(
api.cargoTypes.list.queryOptions({ staleTime: Infinity }),
);
const { data: containerTypes = [], isLoading: containerTypesLoading } = useQuery(
api.containerTypes.list.queryOptions({ staleTime: Infinity }),
);
const create = useCreateFeeRule();
const remove = useDeleteFeeRule();
const [open, setOpen] = useState(false);
@@ -328,11 +356,56 @@ function FeeRules() {
freightType: '',
tradeDirection: '',
cargoTypeCode: '',
containerType: '',
freeDays: 3,
ratePerDay: 0,
tiers: [] as Array<{ fromDay: number; toDay: number | null; ratePerDay: number }>,
currency: 'USD',
});
const rules = data ?? [];
const cargoTypeOptions = codeOptions(cargoTypes);
const containerTypeOptions = codeOptions(containerTypes);
const isBulkRule = form.freightType === 'BULK';
const isContainerRule = form.freightType === 'CONTAINER';
const resetForm = () =>
setForm({
name: '',
ruleType: 'DEMURRAGE_FEE',
freightType: '',
tradeDirection: '',
cargoTypeCode: '',
containerType: '',
freeDays: 3,
ratePerDay: 0,
tiers: [],
currency: 'USD',
});
const addTier = () =>
setForm((f) => {
const last = f.tiers[f.tiers.length - 1];
const fromDay = last?.toDay ? last.toDay + 1 : f.tiers.length ? last.fromDay + 1 : f.freeDays + 1;
return {
...f,
tiers: [...f.tiers, { fromDay, toDay: fromDay, ratePerDay: f.ratePerDay || 0 }],
};
});
const updateTier = (
index: number,
patch: Partial<{ fromDay: number; toDay: number | null; ratePerDay: number }>,
) =>
setForm((f) => ({
...f,
tiers: f.tiers.map((tier, i) => (i === index ? { ...tier, ...patch } : tier)),
}));
const removeTier = (index: number) =>
setForm((f) => ({
...f,
tiers: f.tiers.filter((_, i) => i !== index),
}));
const submit = async () => {
if (!form.name.trim()) {
@@ -340,18 +413,68 @@ function FeeRules() {
return;
}
await create.mutateAsync({
const tiers = form.tiers.map((tier) => ({
fromDay: tier.fromDay,
toDay: tier.toDay || null,
ratePerDay: tier.ratePerDay,
}));
for (const [index, tier] of tiers.entries()) {
if (!Number.isInteger(tier.fromDay) || tier.fromDay < 1) {
toast({ variant: 'destructive', title: `Tier ${index + 1}: from day must be at least 1` });
return;
}
if (tier.toDay != null && tier.toDay < tier.fromDay) {
toast({ variant: 'destructive', title: `Tier ${index + 1}: to day must be after from day` });
return;
}
if (tier.ratePerDay < 0) {
toast({ variant: 'destructive', title: `Tier ${index + 1}: amount must be zero or greater` });
return;
}
}
const payload = {
name: form.name.trim(),
ruleType: form.ruleType,
freightType: clean(form.freightType) ?? null,
tradeDirection: clean(form.tradeDirection) ?? null,
cargoTypeCode: clean(form.cargoTypeCode) ?? null,
cargoTypeCode: isBulkRule ? (clean(form.cargoTypeCode) ?? null) : null,
containerType: isContainerRule ? (clean(form.containerType) ?? null) : null,
freeDays: form.freeDays,
ratePerDay: form.ratePerDay,
currency: form.currency || 'USD',
} as never);
toast({ title: 'Fee rule created' });
setOpen(false);
...(tiers.length ? { tiers } : {}),
};
try {
await create.mutateAsync(payload as never);
toast({ title: 'Fee rule created' });
setOpen(false);
resetForm();
} catch (error) {
if (tiers.length && isUnknownTiersError(error)) {
const legacyPayload: Omit<typeof payload, 'tiers'> = {
name: payload.name,
ruleType: payload.ruleType,
freightType: payload.freightType,
tradeDirection: payload.tradeDirection,
cargoTypeCode: payload.cargoTypeCode,
containerType: payload.containerType,
freeDays: payload.freeDays,
ratePerDay: payload.ratePerDay,
currency: payload.currency,
};
await create.mutateAsync(legacyPayload as never);
toast({
title: 'Fee rule created without tiers',
description: 'The connected API does not support progressive tiers yet. Deploy the warehouse fee tier migration/API to save tier rows.',
});
setOpen(false);
resetForm();
return;
}
toast({ variant: 'destructive', title: 'Create failed', description: extractErrorMessage(error) });
}
};
return (
@@ -370,7 +493,7 @@ function FeeRules() {
<Loader />
</Group>
) : (
<Table.ScrollContainer minWidth={900}>
<Table.ScrollContainer minWidth={1100}>
<Table striped highlightOnHover verticalSpacing="sm">
<Table.Thead>
<Table.Tr>
@@ -378,6 +501,9 @@ function FeeRules() {
<Table.Th>Name</Table.Th>
<Table.Th>Freight</Table.Th>
<Table.Th>Trade</Table.Th>
<Table.Th>Cargo</Table.Th>
<Table.Th>Container</Table.Th>
<Table.Th>Location scope</Table.Th>
<Table.Th>Free days</Table.Th>
<Table.Th>Rate / day</Table.Th>
<Table.Th>Active</Table.Th>
@@ -395,6 +521,20 @@ function FeeRules() {
<Table.Td>{rule.name}</Table.Td>
<Table.Td>{rule.freightType ?? dash}</Table.Td>
<Table.Td>{rule.tradeDirection ?? dash}</Table.Td>
<Table.Td>{rule.cargoTypeCode ?? dash}</Table.Td>
<Table.Td>{rule.containerType ?? dash}</Table.Td>
<Table.Td>
{[rule.facilityId, rule.warehouseId, rule.yardId, rule.zoneId].some(Boolean) ? (
<Stack gap={2}>
{rule.facilityId && <Text size="xs">Facility: {rule.facilityId}</Text>}
{rule.warehouseId && <Text size="xs">Warehouse: {rule.warehouseId}</Text>}
{rule.yardId && <Text size="xs">Yard: {rule.yardId}</Text>}
{rule.zoneId && <Text size="xs">Zone: {rule.zoneId}</Text>}
</Stack>
) : (
dash
)}
</Table.Td>
<Table.Td>{rule.freeDays}</Table.Td>
<Table.Td>
{Number(rule.ratePerDay).toLocaleString()} {rule.currency}
@@ -454,7 +594,14 @@ function FeeRules() {
label="Freight type"
data={FREIGHT}
value={form.freightType || null}
onChange={(value) => setForm((f) => ({ ...f, freightType: selectValue(value) }))}
onChange={(value) =>
setForm((f) => ({
...f,
freightType: selectValue(value),
cargoTypeCode: value === 'BULK' ? f.cargoTypeCode : '',
containerType: value === 'CONTAINER' ? f.containerType : '',
}))
}
clearable
/>
<Select
@@ -464,15 +611,31 @@ function FeeRules() {
onChange={(value) => setForm((f) => ({ ...f, tradeDirection: selectValue(value) }))}
clearable
/>
<TextInput
label="Cargo type code"
value={form.cargoTypeCode}
onChange={(e) => {
const value = e.currentTarget.value;
setForm((f) => ({ ...f, cargoTypeCode: value }));
}}
/>
{isBulkRule && (
<Select
label="Cargo type"
placeholder={cargoTypesLoading ? 'Loading cargo types...' : 'Any cargo'}
data={cargoTypeOptions}
value={form.cargoTypeCode || null}
onChange={(value) => setForm((f) => ({ ...f, cargoTypeCode: selectValue(value) }))}
searchable
clearable
disabled={cargoTypesLoading}
/>
)}
</Group>
{isContainerRule && (
<Select
label="Container type"
placeholder={containerTypesLoading ? 'Loading container types...' : 'Any container'}
data={containerTypeOptions}
value={form.containerType || null}
onChange={(value) => setForm((f) => ({ ...f, containerType: selectValue(value) }))}
searchable
clearable
disabled={containerTypesLoading}
/>
)}
<Group grow>
<NumberInput
label="Free days"
@@ -494,6 +657,51 @@ function FeeRules() {
allowDeselect={false}
/>
</Group>
<Stack gap="xs">
<Group justify="space-between">
<Text size="sm" fw={600}>
Progressive tariff tiers
</Text>
<Button variant="light" size="xs" leftSection={<Plus size={14} />} onClick={addTier}>
Add tier
</Button>
</Group>
{form.tiers.map((tier, index) => (
<Group key={index} grow align="end">
<NumberInput
label="From day"
min={1}
value={tier.fromDay}
onChange={(value) => updateTier(index, { fromDay: numberValue(value, 1) || 1 })}
/>
<NumberInput
label="To day"
min={tier.fromDay}
value={tier.toDay ?? ''}
placeholder="Open"
onChange={(value) =>
updateTier(index, {
toDay: value === '' ? null : numberValue(value, tier.fromDay),
})
}
/>
<NumberInput
label="Amount / day"
min={0}
value={tier.ratePerDay}
onChange={(value) => updateTier(index, { ratePerDay: numberValue(value) })}
/>
<ActionIcon variant="subtle" color="red" onClick={() => removeTier(index)} title="Remove tier">
<Trash2 size={16} />
</ActionIcon>
</Group>
))}
{form.tiers.length === 0 && (
<Text size="xs" c="dimmed">
No stepped tiers. The flat rate per day is used after the free days.
</Text>
)}
</Stack>
<Group justify="flex-end" mt="sm">
<Button variant="default" onClick={() => setOpen(false)}>
Cancel