Merge pull request #430 from Tria-plc/freight/feature/first_mile_invoice

mile
This commit is contained in:
yaschalew10
2026-07-03 22:22:42 +03:00
committed by GitHub
9 changed files with 289 additions and 131 deletions

View File

@@ -755,30 +755,6 @@ const FirstMilePage = () => {
meta: { headerClassName, cellClassName },
cell: ({ row }) => customerName(row.original),
},
{
id: "pickup",
header: "Pickup",
meta: { headerClassName, cellClassName },
cell: ({ row }) => pickupLocation(row.original),
},
{
id: "destination",
header: "Destination",
meta: { headerClassName, cellClassName },
cell: ({ row }) => destinationYardName(row.original),
},
{
id: "cargo",
header: "Cargo",
meta: { headerClassName, cellClassName },
cell: ({ row }) => cargoDesc(row.original),
},
{
id: "advancedPayment",
header: "Advanced Payment",
meta: { headerClassName, cellClassName },
cell: ({ row }) => formatPrice(row.original.advancedPayment),
},
{
id: "postPayment",
header: "Post Payment",
@@ -789,13 +765,8 @@ const FirstMilePage = () => {
id: "vehicle",
header: "Vehicle",
meta: { headerClassName, cellClassName },
cell: ({ row }) => vehicleLabel(row.original) ?? <Text c="dimmed"></Text>,
},
{
id: "estimatedKm",
header: "Est. Distance (KM)",
meta: { headerClassName, cellClassName },
cell: ({ row }) => row.original.estimatedKm != null ? row.original.estimatedKm : <Text c="dimmed"></Text>,
cell: ({ row }) =>
vehicleLabel(row.original) ?? <Text c="dimmed">Unassigned</Text>,
},
{
id: "exactKm",
@@ -849,16 +820,6 @@ const FirstMilePage = () => {
return <Badge color={meta.color} variant="light" size="sm">{meta.label}</Badge>;
},
},
{
id: "assignment",
header: "Assignment",
meta: { headerClassName, cellClassName },
cell: ({ row }) => (
<Badge color={isAssigned(row.original) ? "green" : "orange"} variant="light" size="sm">
{isAssigned(row.original) ? "Assigned" : "Unassigned"}
</Badge>
),
},
{
id: "actions",
header: "Actions",

View File

@@ -3,18 +3,21 @@ import {
ArrowRight,
Eye,
MoreHorizontal,
Plus,
Printer,
Receipt,
RefreshCw,
Ruler,
Trash,
Truck,
X,
} from "lucide-react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { ColumnDef } from "@edr/ui-common";
import { DataTable, DataTableFooter, usePagination } from "@edr/ui-common";
import {
ActionIcon,
Alert,
Badge,
Box,
Button,
@@ -24,6 +27,7 @@ import {
Group,
Menu,
Modal,
MultiSelect,
NumberInput,
ScrollArea,
Select,
@@ -92,6 +96,32 @@ const vehicleLabel = (record: LastMileRecord) => {
return parts.join(" · ");
};
/** One vehicle (with trailer) carries two containers. */
const CONTAINERS_PER_VEHICLE = 2;
const containerCount = (record: LastMileRecord) =>
(record.booking?.bookingContainers ?? []).reduce(
(sum, c) => sum + (Number(c.quantity) || 0),
0,
);
/** Trucks needed for a booking = ceil(containers / 2). 0 when no container data. */
const requiredVehicles = (record: LastMileRecord) => {
const n = containerCount(record);
return n > 0 ? Math.ceil(n / CONTAINERS_PER_VEHICLE) : 0;
};
/** Column summary: the primary vehicle, plus a "+N more" when multi-truck. */
const vehiclesSummary = (record: LastMileRecord) => {
const assigns = record.vehicleAssignments ?? [];
if (assigns.length > 1) {
const first = assigns[0]?.vehicle;
const firstLabel = first
? [first.code, first.plateNumber].filter(Boolean).join(" · ")
: "Vehicle";
return `${firstLabel} +${assigns.length - 1} more`;
}
return vehicleLabel(record);
};
const isAssigned = (record: LastMileRecord) => Boolean(record.vehicleId);
const fmtStamp = (iso?: string | null) => {
@@ -422,13 +452,14 @@ const LastMilePage = () => {
const [tripSlipOpen, setTripSlipOpen] = useState(false);
const [tripSlipRecord, setTripSlipRecord] = useState<LastMileRecord | null>(null);
const [activeId, setActiveId] = useState<string | null>(null);
const [vehicleValue, setVehicleValue] = useState<string | null>(null);
// Multi-vehicle assign: one entry per selected vehicle (null = empty picker).
const [vehicleValues, setVehicleValues] = useState<(string | null)[]>([null]);
// 2-step "Assign Mile" accept modal (arrival queue → vehicle)
const [acceptOpen, setAcceptOpen] = useState(false);
const [acceptStep, setAcceptStep] = useState<1 | 2>(1);
const [selectedArrivalItems, setSelectedArrivalItems] = useState<ArrivalQueueItem[]>([]);
const [acceptVehicleValue, setAcceptVehicleValue] = useState<string | null>(null);
const [acceptVehicleValues, setAcceptVehicleValues] = useState<string[]>([]);
const [arrivalSearch, setArrivalSearch] = useState("");
const [distanceOpen, setDistanceOpen] = useState(false);
@@ -516,6 +547,18 @@ const LastMilePage = () => {
},
});
const setVehiclesMutation = useMutation({
mutationFn: ({ id, vehicleIds }: { id: string; vehicleIds: string[] }) =>
lastMileService.setVehicles(id, vehicleIds),
onSuccess: () => {
void qc.invalidateQueries({ queryKey: QUERY_KEYS.LAST_MILE.ROOT });
void qc.invalidateQueries({ queryKey: ["vehicles"] });
},
onError: () => {
toast({ title: "Assign failed", variant: "destructive" });
},
});
const updateDistanceMutation = useMutation({
mutationFn: ({ id, exactKm, remainingPayment }: { id: string; exactKm: number; remainingPayment?: number }) =>
lastMileService.update(id, { exactKm, ...(remainingPayment != null && { remainingPayment }) }),
@@ -576,12 +619,12 @@ const LastMilePage = () => {
}, [arrivalQueue, arrivalSearch, existingLastMileBookingIds]);
const acceptMutation = useMutation({
mutationFn: async ({ items, vehicleId }: { items: ArrivalQueueItem[]; vehicleId: string | null }) => {
mutationFn: async ({ items, vehicleIds }: { items: ArrivalQueueItem[]; vehicleIds: string[] }) => {
const created = await Promise.all(
items.map((item) => lastMileService.accept(item.bookingReference).then((r) => r.data)),
);
if (vehicleId) {
await Promise.all(created.map((record) => lastMileService.update(record.id, { vehicleId })));
if (vehicleIds.length) {
await Promise.all(created.map((record) => lastMileService.setVehicles(record.id, vehicleIds)));
}
return created;
},
@@ -603,7 +646,7 @@ const LastMilePage = () => {
setAcceptOpen(true);
setAcceptStep(1);
setSelectedArrivalItems([]);
setAcceptVehicleValue(null);
setAcceptVehicleValues([]);
setArrivalSearch("");
};
@@ -611,7 +654,7 @@ const LastMilePage = () => {
setAcceptOpen(false);
setAcceptStep(1);
setSelectedArrivalItems([]);
setAcceptVehicleValue(null);
setAcceptVehicleValues([]);
setArrivalSearch("");
};
@@ -625,7 +668,7 @@ const LastMilePage = () => {
const handleAcceptConfirm = () => {
if (!selectedArrivalItems.length) return;
acceptMutation.mutate({ items: selectedArrivalItems, vehicleId: acceptVehicleValue });
acceptMutation.mutate({ items: selectedArrivalItems, vehicleIds: acceptVehicleValues });
};
const openDistance = (id: string) => {
@@ -688,6 +731,27 @@ const LastMilePage = () => {
[records, activeId],
);
// Vehicle picker options for the assign modal = free vehicles PLUS the ones
// already on this record (which are BUSY, so absent from the free list) so a
// reassign shows its current trucks selected instead of blank.
const assignVehicleOptions = useMemo(() => {
const opts = [...vehicleOptions];
const seen = new Set(opts.map((o) => o.value));
const current = [
...(activeRecord?.vehicleAssignments?.map((a) => a.vehicle) ?? []),
activeRecord?.vehicle,
];
for (const v of current) {
if (v && !seen.has(v.id)) {
seen.add(v.id);
const parts = [`${v.manufacturer} ${v.model}`, v.plateNumber];
if (v.code) parts.unshift(v.code);
opts.push({ value: v.id, label: parts.join(" · ") });
}
}
return opts;
}, [vehicleOptions, activeRecord]);
const pickupReadyByBooking = useMemo(() => {
const map = new Map<string, ImportUnloadedItem>();
for (const row of pickupReadyRows) {
@@ -751,16 +815,22 @@ const LastMilePage = () => {
const openAssign = (id: string | null) => {
const resolved = id ?? filteredRecords.find((r) => !isAssigned(r))?.id ?? null;
const rec = records.find((r) => r.id === resolved);
const existing = rec?.vehicleAssignments?.length
? rec.vehicleAssignments.map((a) => a.vehicleId)
: rec?.vehicleId
? [rec.vehicleId]
: [];
setBulkMode(false);
setActiveId(resolved);
setVehicleValue(null);
setVehicleValues(existing.length ? existing : [null]);
setAssignOpen(true);
};
const openBulkAssign = () => {
setBulkMode(true);
setActiveId(null);
setVehicleValue(null);
setVehicleValues([null]);
setAssignOpen(true);
};
@@ -768,28 +838,26 @@ const LastMilePage = () => {
setAssignOpen(false);
setBulkMode(false);
setActiveId(null);
setVehicleValue(null);
setVehicleValues([null]);
};
const handleAssign = () => {
if (!vehicleValue) {
toast({ title: "Select a vehicle", description: "Choose a vehicle to assign.", variant: "destructive" });
return;
}
const ids = [...new Set(vehicleValues.filter((v): v is string => Boolean(v)))];
const targetIds = bulkMode
? selectedIds
: [activeId ?? filteredRecords.find((r) => !isAssigned(r))?.id].filter((id): id is string => Boolean(id));
if (!targetIds.length) return;
if (!ids.length) {
toast({ title: "Select a vehicle", description: "Choose at least one vehicle to assign.", variant: "destructive" });
return;
}
const selectedLabel = vehicleOptions.find((o) => o.value === vehicleValue)?.label ?? vehicleValue;
Promise.all(targetIds.map((id) => updateMutation.mutateAsync({ id, data: { vehicleId: vehicleValue } })))
Promise.all(targetIds.map((id) => setVehiclesMutation.mutateAsync({ id, vehicleIds: ids })))
.then(() => {
toast({
title: "Vehicle assigned",
description: bulkMode ? `${targetIds.length} deliveries ${selectedLabel}` : selectedLabel,
title: ids.length > 1 ? "Vehicles assigned" : "Vehicle assigned",
description: `${bulkMode ? `${targetIds.length} deliveries · ` : ""}${ids.length} vehicle${ids.length > 1 ? "s" : ""}`,
});
if (bulkMode) setRowSelection({});
closeAssign();
@@ -893,30 +961,6 @@ const LastMilePage = () => {
meta: { headerClassName, cellClassName },
cell: ({ row }) => customerName(row.original),
},
{
id: "pickup",
header: "Pickup",
meta: { headerClassName, cellClassName },
cell: ({ row }) => originYardName(row.original),
},
{
id: "destination",
header: "Destination",
meta: { headerClassName, cellClassName },
cell: ({ row }) => deliveryLocation(row.original),
},
{
id: "cargo",
header: "Cargo",
meta: { headerClassName, cellClassName },
cell: ({ row }) => cargoDesc(row.original),
},
{
id: "advancedPayment",
header: "Advanced Payment",
meta: { headerClassName, cellClassName },
cell: ({ row }) => formatPrice(row.original.advancedPayment),
},
{
id: "postPayment",
header: "Post Payment",
@@ -927,13 +971,8 @@ const LastMilePage = () => {
id: "vehicle",
header: "Vehicle",
meta: { headerClassName, cellClassName },
cell: ({ row }) => vehicleLabel(row.original) ?? <Text c="dimmed"></Text>,
},
{
id: "estimatedKm",
header: "Est. Distance (KM)",
meta: { headerClassName, cellClassName },
cell: ({ row }) => row.original.estimatedKm != null ? row.original.estimatedKm : <Text c="dimmed"></Text>,
cell: ({ row }) =>
vehiclesSummary(row.original) ?? <Text c="dimmed">Unassigned</Text>,
},
{
id: "exactKm",
@@ -987,16 +1026,6 @@ const LastMilePage = () => {
return <Badge color={meta.color} variant="light" size="sm">{meta.label}</Badge>;
},
},
{
id: "assignment",
header: "Assignment",
meta: { headerClassName, cellClassName },
cell: ({ row }) => (
<Badge color={isAssigned(row.original) ? "green" : "orange"} variant="light" size="sm">
{isAssigned(row.original) ? "Assigned" : "Unassigned"}
</Badge>
),
},
{
id: "actions",
header: "Actions",
@@ -1315,19 +1344,26 @@ const LastMilePage = () => {
</Stack>
</Card>
<Divider />
<Select
label="Assign Vehicle (optional)"
placeholder={vehicleOptions.length === 0 ? "No free vehicles" : "Select a vehicle"}
<MultiSelect
label="Assign Vehicles (optional)"
placeholder={
vehicleOptions.length === 0
? "No free vehicles"
: acceptVehicleValues.length === 0
? "Add vehicles"
: undefined
}
description={
vehicleOptions.length === 0
? "No free vehicles available — you can still accept and assign a vehicle later."
: undefined
? "No free vehicles available — you can still accept and assign vehicles later."
: "Pick one or more trucks for this delivery."
}
data={vehicleOptions}
value={acceptVehicleValue}
onChange={setAcceptVehicleValue}
value={acceptVehicleValues}
onChange={setAcceptVehicleValues}
searchable
clearable
hidePickedOptions
disabled={vehicleOptions.length === 0}
/>
<Group justify="space-between" gap="sm">
@@ -1368,29 +1404,82 @@ const LastMilePage = () => {
) : (
<Text size="sm" c="dimmed">No unassigned deliveries available.</Text>
)}
{!bulkMode && activeRecord && requiredVehicles(activeRecord) > 0 && (() => {
const containers = containerCount(activeRecord);
const needed = requiredVehicles(activeRecord);
const picked = vehicleValues.filter(Boolean).length;
const ok = picked === needed;
return (
<Alert
variant="light"
color={ok ? "green" : "yellow"}
title={`${containers} container${containers === 1 ? "" : "s"} · needs ${needed} vehicle${needed === 1 ? "" : "s"}`}
>
One truck (with trailer) carries {CONTAINERS_PER_VEHICLE} containers.
{picked > 0 && !ok &&
` You've selected ${picked}${picked < needed ? "add more" : "that's more than needed"}.`}
</Alert>
);
})()}
<Divider />
<Select
label="Vehicle"
placeholder={vehicleOptions.length === 0 ? "No free vehicles" : "Select a vehicle"}
description={
vehicleOptions.length === 0
? "No free vehicles available — all vehicles are busy, in maintenance, or retired. Free up a vehicle in Fleet Vehicles first."
: undefined
}
data={vehicleOptions}
value={vehicleValue}
onChange={setVehicleValue}
searchable
disabled={vehicleOptions.length === 0}
/>
<Stack gap="xs">
{vehicleValues.map((val, i) => (
<Group key={i} gap="xs" wrap="nowrap" align="flex-end">
<Select
style={{ flex: 1 }}
label={i === 0 ? "Vehicles" : undefined}
placeholder={assignVehicleOptions.length === 0 ? "No free vehicles" : "Select a vehicle"}
description={
i === 0 && assignVehicleOptions.length === 0
? "No free vehicles available — free up a vehicle in Fleet Vehicles first."
: undefined
}
data={assignVehicleOptions.filter(
(o) => o.value === val || !vehicleValues.includes(o.value),
)}
value={val}
onChange={(v) =>
setVehicleValues((prev) => prev.map((x, idx) => (idx === i ? v : x)))
}
searchable
clearable
disabled={assignVehicleOptions.length === 0}
/>
{vehicleValues.length > 1 && (
<ActionIcon
variant="subtle"
color="red"
aria-label="Remove vehicle"
onClick={() => setVehicleValues((prev) => prev.filter((_, idx) => idx !== i))}
>
<X size={16} />
</ActionIcon>
)}
</Group>
))}
<Button
variant="light"
size="xs"
leftSection={<Plus size={14} />}
onClick={() => setVehicleValues((prev) => [...prev, null])}
disabled={
assignVehicleOptions.length === 0 ||
vehicleValues.some((v) => !v) ||
vehicleValues.filter(Boolean).length >= assignVehicleOptions.length
}
style={{ alignSelf: "flex-start" }}
>
Add vehicle
</Button>
</Stack>
<Group justify="flex-end" gap="sm">
<Button variant="default" onClick={closeAssign}>Cancel</Button>
<Button
onClick={handleAssign}
loading={updateMutation.isPending}
loading={setVehiclesMutation.isPending}
disabled={bulkMode ? selectedIds.length === 0 : !activeRecord}
>
{!bulkMode && activeRecord && isAssigned(activeRecord) ? "Reassign" : "Assign"}
{!bulkMode && activeRecord && isAssigned(activeRecord) ? "Update vehicles" : "Assign"}
</Button>
</Group>
</Stack>

View File

@@ -22,6 +22,8 @@ export interface LastMileBooking {
originYard?: { id: string; name?: string; label?: string } | null;
destinationYard?: { id: string; name?: string; label?: string } | null;
cargoType?: { id: string; name?: string; label?: string; cargoTypeName?: string } | null;
/** Container lines — total container count drives how many trucks are needed. */
bookingContainers?: Array<{ id: string; quantity: number }>;
}
export interface LastMileVehicle {
@@ -48,6 +50,8 @@ export interface LastMileRecord {
vehicleId?: string | null;
booking?: LastMileBooking | null;
vehicle?: LastMileVehicle | null;
/** Full set of vehicles serving this delivery (multi-truck). */
vehicleAssignments?: Array<{ id: string; vehicleId: string; vehicle?: LastMileVehicle | null }>;
createdAt: string;
updatedAt: string;
}
@@ -69,4 +73,6 @@ export const lastMileService = {
api.post<LastMileRecord>(LM.ACCEPT(encodeURIComponent(bookingReference))),
remove: (id: string) =>
api.delete<void>(LM.BY_ID(id)),
setVehicles: (id: string, vehicleIds: string[]) =>
api.post<LastMileRecord>(`${LM.BASE}/${id}/vehicles`, { vehicleIds }),
};