mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-09-07 15:25:45 +00:00
Merge pull request #1472 from Tria-plc/freight_feature/usermanagement
feat: Implement handling for partially loaded bookings in train sched…
This commit is contained in:
@@ -641,6 +641,7 @@ export default function TrainScheduleTrackPage() {
|
||||
onClose={() => setYardModal(null)}
|
||||
scheduleId={scheduleId}
|
||||
station={yardModal?.station ?? null}
|
||||
stations={track.stations}
|
||||
isFinal={yardModal?.isFinal ?? false}
|
||||
alreadyLogged={yardModal?.alreadyLogged ?? false}
|
||||
/>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
ActionIcon,
|
||||
Alert,
|
||||
Anchor,
|
||||
Badge,
|
||||
Box,
|
||||
Button,
|
||||
@@ -64,6 +65,11 @@ import { LegCapacityPanel } from "@/components/trainScheduling/LegCapacityPanel"
|
||||
import { ScheduleWagonYardPanel } from "@/components/trainScheduling/ScheduleWagonYardPanel";
|
||||
import { LegLoadBoardPanel } from "@/components/trainScheduling/LegLoadBoardPanel";
|
||||
import { LoadEmptyContainersModal } from "@/components/trainScheduling/LoadEmptyContainersModal";
|
||||
import {
|
||||
PartiallyLoadedDecisionModal,
|
||||
parsePartiallyLoaded,
|
||||
type PartiallyLoadedPayload,
|
||||
} from "@/components/trainScheduling/PartiallyLoadedDecisionModal";
|
||||
import MergeScheduleTrainModal from "@/components/trainScheduling/MergeScheduleTrainModal";
|
||||
import ScheduleHistoryPanel from "@/components/trainScheduling/ScheduleHistoryPanel";
|
||||
import { StationWorkControls } from "@/components/trainScheduling/StationWorkControls";
|
||||
@@ -135,10 +141,12 @@ export default function TrainScheduleV2DetailPage() {
|
||||
// Actual departure — staff often dispatch on paper first and record it later,
|
||||
// so the time is picked (defaults to now when the dialog opens).
|
||||
const [dispatchAt, setDispatchAt] = useState<Date | null>(null);
|
||||
const openDispatchConfirm = () => {
|
||||
setDispatchAt(new Date());
|
||||
setDispatchConfirmOpen(true);
|
||||
};
|
||||
// Set when dispatch is rejected because a booking is part-loaded; drives the
|
||||
// EDR-fault / customer-fault decision modal.
|
||||
const [partialGate, setPartialGate] = useState<PartiallyLoadedPayload | null>(null);
|
||||
// Log-pass / arrive confirmation for the dispatched leg of the workflow.
|
||||
const [passConfirmOpen, setPassConfirmOpen] = useState(false);
|
||||
const [passAt, setPassAt] = useState<Date | null>(null);
|
||||
const [switchTarget, setSwitchTarget] = useState<EligibleContainerBooking | null>(null);
|
||||
const [visualization3DOpen, setVisualization3DOpen] = useState(false);
|
||||
const [loadEmptiesOpen, setLoadEmptiesOpen] = useState(false);
|
||||
@@ -155,6 +163,23 @@ export default function TrainScheduleV2DetailPage() {
|
||||
refetchInterval: 300_000,
|
||||
}),
|
||||
);
|
||||
// Journey state for the dispatched leg of the workflow: the corridor stops,
|
||||
// which one the train has reached, and each yard's loading/unloading windows.
|
||||
// Only a rolling train has a journey, so it stays idle until then.
|
||||
const trackQuery = useQuery(
|
||||
api.trainScheduling.trainTrack.queryOptions({
|
||||
input: { id: scheduleId ?? "" },
|
||||
enabled: Boolean(scheduleId),
|
||||
}),
|
||||
);
|
||||
// Which bookings board/alight at each yard — drives the loading gate on the
|
||||
// log-pass button (a yard with cargo to load must finish its window first).
|
||||
const yardWorkQuery = useQuery(
|
||||
api.trainScheduling.yardWork.queryOptions({
|
||||
input: { scheduleId: scheduleId ?? "" },
|
||||
enabled: Boolean(scheduleId),
|
||||
}),
|
||||
);
|
||||
// One-row 60s heartbeat: refetch the (expensive) full detail only when the
|
||||
// schedule row actually changed — same freshness as polling the detail
|
||||
// itself, at a fraction of the server cost.
|
||||
@@ -256,6 +281,9 @@ export default function TrainScheduleV2DetailPage() {
|
||||
const unassign = useMutation(api.trainScheduling.unassignBooking.mutationOptions());
|
||||
const switchGov = useMutation(api.trainScheduling.switchGovernmentBooking.mutationOptions());
|
||||
const dispatch = useMutation(api.trainScheduling.dispatchSchedule.mutationOptions());
|
||||
const recordCheckpoint = useMutation(
|
||||
api.trainScheduling.recordCheckpoint.mutationOptions(),
|
||||
);
|
||||
const downloadMarshalling = useMutation({
|
||||
mutationFn: ({
|
||||
id,
|
||||
@@ -503,6 +531,28 @@ export default function TrainScheduleV2DetailPage() {
|
||||
// Shipping-line bookings ride from accept on the credit ledger.
|
||||
(Boolean(b.shippingLineCompanyId) && b.status === "FULLY_EXECUTED")),
|
||||
);
|
||||
// A slot can carry several loads of the same booking, so count DISTINCT
|
||||
// slots per booking — the operator is being told how much steel is freed.
|
||||
const slotIdsByBookingId = new Map<string, Set<string>>();
|
||||
for (const slot of schedule.trainSet?.wagons ?? []) {
|
||||
for (const alloc of slot.allocations ?? []) {
|
||||
if (!alloc.bookingId) continue;
|
||||
const slots = slotIdsByBookingId.get(alloc.bookingId) ?? new Set<string>();
|
||||
slots.add(slot.id);
|
||||
slotIdsByBookingId.set(alloc.bookingId, slots);
|
||||
}
|
||||
}
|
||||
const wagonsOf = (bookingId: string) => slotIdsByBookingId.get(bookingId)?.size ?? 0;
|
||||
|
||||
const openDispatchConfirm = () => {
|
||||
setDispatchAt(new Date());
|
||||
setDispatchConfirmOpen(true);
|
||||
};
|
||||
// Everything unloaded at the origin comes off the train on dispatch.
|
||||
// Government bookings can never be shed: the server refuses to unassign them.
|
||||
const leftBehind = pendingOriginBoarders.filter((b) => !b.isGovernment);
|
||||
const leftBehindWagons = leftBehind.reduce((n, b) => n + wagonsOf(b.id), 0);
|
||||
|
||||
// Origin loading time window: dispatch (which marks the boarders loaded)
|
||||
// is server-rejected until "Start loading" was clicked for the origin
|
||||
// yard, so the button mirrors that gate.
|
||||
@@ -516,6 +566,89 @@ export default function TrainScheduleV2DetailPage() {
|
||||
// Same gate the server enforces.
|
||||
const dispatchBlockedByLoading = !originLoadingEnded;
|
||||
|
||||
// ── Journey leg: log pass / mark arrived ────────────────────────────────
|
||||
// Once the train is rolling, the workflow's last step drives the corridor
|
||||
// instead of dispatch. The stop being logged is the one AFTER the train's
|
||||
// current position; the last stop on the route is the arrival.
|
||||
const track = trackQuery.data;
|
||||
const trackStations = track?.stations ?? [];
|
||||
const isRolling = schedule.status === "DISPATCHED";
|
||||
const nextStation = isRolling
|
||||
? trackStations.find((st) => st.sequenceNo === (track?.currentSequenceNo ?? 0) + 1)
|
||||
: undefined;
|
||||
const nextIsFinal =
|
||||
Boolean(nextStation) &&
|
||||
nextStation?.sequenceNo === trackStations[trackStations.length - 1]?.sequenceNo;
|
||||
// Same permission the track page gates its checkpoint actions on.
|
||||
const canLogPass =
|
||||
isRolling && hasPermission(authUser, FREIGHT_PERMS.trainScheduling.update);
|
||||
// Loading gate. Logging a pass means the train LEAVES the yard it is standing
|
||||
// at, so cargo boarding there must have finished loading first — an open (or
|
||||
// never-opened) loading window at a yard with boarders blocks the button.
|
||||
// Unloading never blocks: cargo alighting here can be taken off after the
|
||||
// pass is recorded, and the final arrival is what opens that window at all.
|
||||
const currentStation = isRolling
|
||||
? trackStations.find((st) => st.sequenceNo === (track?.currentSequenceNo ?? 0))
|
||||
: undefined;
|
||||
const currentYardWork = currentStation
|
||||
? yardWorkQuery.data?.yards.find((y) => y.yardId === currentStation.yardId)
|
||||
: undefined;
|
||||
const boardersHere = (currentYardWork?.toLoad ?? []).filter((r) => !r.loadedAt);
|
||||
const currentLoadingLog = currentStation
|
||||
? track?.stationWorkLogs?.[currentStation.yardId]?.loading
|
||||
: undefined;
|
||||
// Only a yard that actually has cargo to load can be blocked by its window.
|
||||
const passBlockedByLoading =
|
||||
boardersHere.length > 0 && !currentLoadingLog?.endedAt;
|
||||
const passBlockReason = !passBlockedByLoading
|
||||
? null
|
||||
: currentLoadingLog?.startedAt
|
||||
? `End the loading window at ${currentStation?.label ?? "this yard"} — the train cannot leave mid-loading.`
|
||||
: `Start and end the loading window at ${currentStation?.label ?? "this yard"} — ${boardersHere.length} booking(s) board here.`;
|
||||
|
||||
const openPassConfirm = () => {
|
||||
setPassAt(new Date());
|
||||
setPassConfirmOpen(true);
|
||||
};
|
||||
|
||||
const runLogPass = async () => {
|
||||
if (!nextStation) return;
|
||||
setPassConfirmOpen(false);
|
||||
try {
|
||||
await recordCheckpoint.mutateAsync({
|
||||
id: scheduleId,
|
||||
payload: {
|
||||
sequenceNo: nextStation.sequenceNo,
|
||||
...(passAt ? { occurredAt: passAt.toISOString() } : {}),
|
||||
},
|
||||
});
|
||||
toast({
|
||||
title: nextIsFinal
|
||||
? `Train arrived at ${nextStation.label}`
|
||||
: `Pass logged at ${nextStation.label}`,
|
||||
description: nextIsFinal
|
||||
? "Remaining bookings are marked arrived and the assets are freed."
|
||||
: "The train's position has moved to this yard.",
|
||||
});
|
||||
void trackQuery.refetch();
|
||||
void yardWorkQuery.refetch();
|
||||
void detailQuery.refetch();
|
||||
} catch (err) {
|
||||
// A part-loaded booking blocks the pass until its never-loaded wagons are
|
||||
// cut — hand over the fault decision rather than a dead-end error.
|
||||
const gate = parsePartiallyLoaded(err);
|
||||
if (gate) {
|
||||
setPartialGate(gate);
|
||||
return;
|
||||
}
|
||||
toast({
|
||||
title: nextIsFinal ? "Could not mark arrived" : "Could not log pass",
|
||||
description: parseError(err, "Please try again"),
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const finalizeStep = hasContainerStep ? 3 : 2;
|
||||
const canModifyBookings = canEditBookings && !["DISPATCHED", "ARRIVED"].includes(schedule.status);
|
||||
const canPrintMarshalling =
|
||||
@@ -572,17 +705,34 @@ export default function TrainScheduleV2DetailPage() {
|
||||
id: scheduleId,
|
||||
payload: {
|
||||
...(dispatchAt ? { actualDepartureAt: dispatchAt.toISOString() } : {}),
|
||||
// No per-booking ticking in the dispatch dialog: every pending origin
|
||||
// boarder rides — none are left behind at dispatch time.
|
||||
loadedBookingIds: pendingOriginBoarders.map((b) => b.id),
|
||||
// Dispatch never loads cargo — loading is recorded in the yard, per
|
||||
// booking. Anything still unloaded when the train leaves did not make
|
||||
// it aboard: the server unassigns it (wagons freed, booking back in
|
||||
// the pool). Government bookings are exempt and ride regardless.
|
||||
loadedBookingIds: pendingOriginBoarders
|
||||
.filter((b) => b.isGovernment)
|
||||
.map((b) => b.id),
|
||||
},
|
||||
});
|
||||
if (leftBehind.length) {
|
||||
toast({
|
||||
title: `${leftBehind.length} booking${leftBehind.length === 1 ? "" : "s"} removed from the train`,
|
||||
description: `Never loaded at the origin — ${leftBehindWagons} wagon${leftBehindWagons === 1 ? "" : "s"} freed. The bookings are back in the pool and can be allocated to another train or cancelled.`,
|
||||
});
|
||||
}
|
||||
await openMarshallingDocument({
|
||||
title: "Train dispatched",
|
||||
successDescription: "Marshalling document generated for the dispatched train.",
|
||||
errorTitle: "Train dispatched, but document could not open",
|
||||
});
|
||||
} catch (err) {
|
||||
// A part-loaded booking blocks dispatch until its never-loaded wagons are
|
||||
// cut — hand the operator the fault decision instead of a dead error.
|
||||
const gate = parsePartiallyLoaded(err);
|
||||
if (gate) {
|
||||
setPartialGate(gate);
|
||||
return;
|
||||
}
|
||||
toast({
|
||||
title: "Dispatch failed",
|
||||
description: parseError(err, "Could not dispatch"),
|
||||
@@ -705,8 +855,10 @@ export default function TrainScheduleV2DetailPage() {
|
||||
{
|
||||
key: "finalize",
|
||||
icon: CheckCircle2,
|
||||
title: "Dispatch",
|
||||
subtitle: "Review the consist & dispatch",
|
||||
title: isRolling ? "Journey" : "Dispatch",
|
||||
subtitle: isRolling
|
||||
? "Log each pass, then mark arrived"
|
||||
: "Review the consist & dispatch",
|
||||
complete: finalizeComplete,
|
||||
},
|
||||
];
|
||||
@@ -958,14 +1110,51 @@ export default function TrainScheduleV2DetailPage() {
|
||||
<CheckCircle2 size={22} />
|
||||
</ThemeIcon>
|
||||
<Stack gap={2}>
|
||||
<Text fw={600}>Ready to depart</Text>
|
||||
<Text fw={600}>
|
||||
{isRolling
|
||||
? nextIsFinal
|
||||
? "Final leg"
|
||||
: `In transit — at ${currentStation?.label ?? "the corridor"}`
|
||||
: "Ready to depart"}
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
Dispatch begins rail movement and notifies the yard.
|
||||
{isRolling
|
||||
? nextIsFinal
|
||||
? "Marking arrived ends the journey and frees the locomotive and wagons."
|
||||
: "Logging the pass moves the train to the next yard and settles its cargo there."
|
||||
: "Dispatch begins rail movement and notifies the yard."}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
</Paper>
|
||||
{originYardId ? (
|
||||
{/* Mid-route loading/unloading is recorded on the TRACKING page, per
|
||||
yard — only the origin's window lives here (below), because dispatch
|
||||
is the action this page owns. What stays is the read-only reason the
|
||||
pass button is held, so the blocker is explainable without
|
||||
duplicating the controls. */}
|
||||
{isRolling && currentStation && passBlockedByLoading ? (
|
||||
<Alert
|
||||
color="orange"
|
||||
variant="light"
|
||||
radius="md"
|
||||
icon={<AlertTriangle size={18} />}
|
||||
title={`Loading is not finished at ${currentStation.label}`}
|
||||
>
|
||||
<Text size="xs">
|
||||
{boardersHere.length} booking(s) board here, so the train cannot leave until
|
||||
the loading window is closed. Start and end it on the{" "}
|
||||
<Anchor
|
||||
component={Link}
|
||||
to={`/dashboard/operations/train-scheduling-v2/${scheduleId}/track`}
|
||||
fw={600}
|
||||
>
|
||||
tracking page
|
||||
</Anchor>
|
||||
.
|
||||
</Text>
|
||||
</Alert>
|
||||
) : null}
|
||||
{!isRolling && originYardId ? (
|
||||
<Paper p="md" radius="lg" withBorder>
|
||||
<Stack gap={6}>
|
||||
<Text fw={600} size="sm">
|
||||
@@ -1000,7 +1189,35 @@ export default function TrainScheduleV2DetailPage() {
|
||||
Dispatch train
|
||||
</Button>
|
||||
) : null}
|
||||
{!canDispatch ? (
|
||||
{/* The train is rolling: the same slot now drives the corridor. */}
|
||||
{canLogPass && nextStation ? (
|
||||
<Tooltip
|
||||
label={passBlockReason ?? ""}
|
||||
disabled={!passBlockedByLoading}
|
||||
withArrow
|
||||
multiline
|
||||
w={280}
|
||||
>
|
||||
<div>
|
||||
<Button
|
||||
color="edr-green"
|
||||
size="md"
|
||||
radius="md"
|
||||
leftSection={
|
||||
nextIsFinal ? <CheckCircle2 size={18} /> : <Navigation size={18} />
|
||||
}
|
||||
loading={recordCheckpoint.isPending}
|
||||
disabled={passBlockedByLoading}
|
||||
onClick={openPassConfirm}
|
||||
>
|
||||
{nextIsFinal
|
||||
? `Mark arrived at ${nextStation.label}`
|
||||
: `Log pass at ${nextStation.label}`}
|
||||
</Button>
|
||||
</div>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{!canDispatch && !(canLogPass && nextStation) ? (
|
||||
<Text size="sm" c="dimmed">
|
||||
No actions available for this schedule status.
|
||||
</Text>
|
||||
@@ -1636,6 +1853,25 @@ export default function TrainScheduleV2DetailPage() {
|
||||
radius="md"
|
||||
/>
|
||||
|
||||
{leftBehind.length > 0 ? (
|
||||
<Alert
|
||||
color="orange"
|
||||
variant="light"
|
||||
radius="md"
|
||||
icon={<AlertTriangle size={18} />}
|
||||
title={`${leftBehind.length} booking${leftBehind.length === 1 ? "" : "s"} will be removed from this train`}
|
||||
>
|
||||
<Text size="xs">
|
||||
Never loaded at the origin, so {leftBehind.length === 1 ? "it is" : "they are"}{" "}
|
||||
not aboard. Dispatch frees {leftBehindWagons} wagon
|
||||
{leftBehindWagons === 1 ? "" : "s"} and returns{" "}
|
||||
{leftBehind.length === 1 ? "the booking" : "them"} to the pool, ready to be
|
||||
allocated to another train or cancelled. Load cargo from the yard workspace
|
||||
before dispatching if it should ride.
|
||||
</Text>
|
||||
</Alert>
|
||||
) : null}
|
||||
|
||||
{hasDispatchWarnings ? (
|
||||
<Alert
|
||||
color="orange"
|
||||
@@ -1717,6 +1953,62 @@ export default function TrainScheduleV2DetailPage() {
|
||||
</Group>
|
||||
</Stack>
|
||||
</Modal>
|
||||
{/* Log pass / arrival — confirmation only, with the recorded time. */}
|
||||
<Modal
|
||||
opened={passConfirmOpen}
|
||||
onClose={() => setPassConfirmOpen(false)}
|
||||
centered
|
||||
radius="lg"
|
||||
title={
|
||||
<Group gap={8}>
|
||||
{nextIsFinal ? <CheckCircle2 size={18} /> : <Navigation size={18} />}
|
||||
<Text fw={700}>
|
||||
{nextIsFinal ? "Mark the train arrived?" : "Log the pass?"}
|
||||
</Text>
|
||||
</Group>
|
||||
}
|
||||
>
|
||||
<Stack gap="md">
|
||||
<Text size="sm" c="dimmed">
|
||||
{nextIsFinal
|
||||
? `Recording arrival at ${nextStation?.label ?? "the destination"} ends the journey: remaining bookings are marked arrived and the locomotive and wagons are freed.`
|
||||
: `Recording the pass at ${nextStation?.label ?? "the next yard"} moves the train there. Cargo destined for that yard alights, and cargo boarding there becomes loadable.`}
|
||||
</Text>
|
||||
|
||||
<DateTimePicker
|
||||
label={nextIsFinal ? "Arrival time" : "Time at station"}
|
||||
description="Defaults to now — pick an earlier time if you are recording after the fact."
|
||||
value={passAt}
|
||||
onChange={(v) => setPassAt(v ? new Date(v) : null)}
|
||||
maxDate={new Date()}
|
||||
valueFormat="DD MMM YYYY HH:mm"
|
||||
clearable={false}
|
||||
radius="md"
|
||||
/>
|
||||
|
||||
<Group justify="flex-end" gap="sm">
|
||||
<Button variant="default" radius="md" onClick={() => setPassConfirmOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
color="edr-green"
|
||||
radius="md"
|
||||
loading={recordCheckpoint.isPending}
|
||||
onClick={() => void runLogPass()}
|
||||
>
|
||||
{nextIsFinal ? "Mark arrived" : "Log pass"}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Modal>
|
||||
|
||||
{/* Part-loaded gate. Cutting the wagons does NOT dispatch — the operator
|
||||
confirms dispatch again once the consist is clean. */}
|
||||
<PartiallyLoadedDecisionModal
|
||||
payload={partialGate}
|
||||
onClose={() => setPartialGate(null)}
|
||||
onResolved={() => void detailQuery.refetch()}
|
||||
/>
|
||||
{visualization3DOpen ? (
|
||||
<Train3DVisualization schedule={schedule} onClose={() => setVisualization3DOpen(false)} />
|
||||
) : null}
|
||||
|
||||
Reference in New Issue
Block a user