automate the schedule

This commit is contained in:
Marshal
2026-06-11 19:42:23 +00:00
parent f85c13ce8c
commit cde3e462ba
28 changed files with 1197 additions and 12 deletions

View File

@@ -0,0 +1,252 @@
import { useMemo, useState } from "react";
import {
Badge,
Button,
Group,
Modal,
Paper,
Select,
Stack,
Table,
Text,
ThemeIcon,
} from "@mantine/core";
import { CheckCircle2, Layers, Lock, LockOpen, PlayCircle, Repeat, XCircle } from "lucide-react";
import { BookingStatusBadge } from "@/components/bookings/BookingStatusBadge";
import {
useBatchActions,
useBookableSchedules,
} from "@/hooks/trainScheduling/useTrainScheduling";
import { useToast } from "@/hooks/use-toast";
import type { TrainScheduleDetail } from "@/types/trainScheduling";
interface ScheduleBatchPanelProps {
schedule: TrainScheduleDetail;
}
const windowColor: Record<string, string> = {
OPEN: "green",
FULL: "orange",
CLOSED: "gray",
};
export function ScheduleBatchPanel({ schedule }: ScheduleBatchPanelProps) {
const { toast } = useToast();
const actions = useBatchActions(schedule.id);
const windowStatus = (schedule as { bookingWindowStatus?: string }).bookingWindowStatus ?? "OPEN";
const locked = schedule.status === "DISPATCHED" || schedule.status === "ARRIVED";
const [moveBookingId, setMoveBookingId] = useState<string | null>(null);
const [moveTarget, setMoveTarget] = useState<string | null>(null);
const { data: targets } = useBookableSchedules(
schedule.originStation?.id,
schedule.destinationStation?.id,
);
const moveOptions = useMemo(
() =>
(targets ?? [])
.filter((s) => s.id !== schedule.id)
.map((s) => ({
value: s.id,
label: `${s.routeName ?? `${s.origin}${s.destination}`} · ${new Date(
s.scheduleDate,
).toLocaleString()} · ${s.remainingWagons}/${s.maxWagons} free`,
})),
[targets, schedule.id],
);
const bookings = schedule.bookings ?? [];
const run = (fn: Promise<unknown>, ok: string) =>
fn
.then(() => toast({ title: ok }))
.catch(() => toast({ title: "Action failed", variant: "destructive" }));
return (
<Paper radius="lg" withBorder p="lg" style={{ borderColor: "var(--mantine-color-gray-2)" }}>
<Group justify="space-between" align="center" mb="md" wrap="wrap">
<Group gap="sm">
<ThemeIcon size={36} radius="md" variant="light" color="green">
<Layers size={18} />
</ThemeIcon>
<div>
<Text fw={700}>Batch allocation</Text>
<Text size="xs" c="dimmed">
{bookings.length} allocated · {schedule.trainSet?.wagonCount ?? 0} wagons used
</Text>
</div>
</Group>
<Group gap="sm">
<Badge color={windowColor[windowStatus] ?? "gray"} variant="light" radius="sm" size="lg">
Window: {windowStatus}
</Badge>
</Group>
</Group>
{!locked && (
<Group gap="sm" mb="md">
<Button
size="compact-sm"
variant="light"
color="green"
leftSection={<PlayCircle size={15} />}
loading={actions.runBatch.isPending}
onClick={() => run(actions.runBatch.mutateAsync(schedule.id), "Batch fill run")}
>
Run batch fill
</Button>
{windowStatus === "CLOSED" ? (
<Button
size="compact-sm"
variant="default"
leftSection={<LockOpen size={15} />}
loading={actions.setWindow.isPending}
onClick={() =>
run(
actions.setWindow.mutateAsync({ id: schedule.id, status: "OPEN" }),
"Window opened",
)
}
>
Open window
</Button>
) : (
<Button
size="compact-sm"
variant="default"
leftSection={<Lock size={15} />}
loading={actions.setWindow.isPending}
onClick={() =>
run(
actions.setWindow.mutateAsync({ id: schedule.id, status: "CLOSED" }),
"Window closed",
)
}
>
Close window
</Button>
)}
</Group>
)}
{bookings.length === 0 ? (
<Text size="sm" c="dimmed">
No bookings allocated yet. The batch cron fills this schedule by priority; paid bookings are
assigned automatically.
</Text>
) : (
<Table verticalSpacing="xs" highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th>Booking</Table.Th>
<Table.Th>Customer</Table.Th>
<Table.Th>Status</Table.Th>
<Table.Th ta="right">Actions</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{bookings.map((b) => (
<Table.Tr key={b.id}>
<Table.Td>
<Text size="sm" fw={600}>
{b.reference ?? b.id.slice(0, 8)}
</Text>
</Table.Td>
<Table.Td>
<Text size="sm" c="dimmed">
{b.customer ?? "—"}
</Text>
</Table.Td>
<Table.Td>
<BookingStatusBadge status={b.status ?? ""} />
</Table.Td>
<Table.Td>
{!locked && (
<Group gap={6} justify="flex-end" wrap="nowrap">
{b.status !== "PAID" && (
<Button
size="compact-xs"
variant="light"
color="green"
leftSection={<CheckCircle2 size={13} />}
onClick={() => run(actions.markPaid.mutateAsync(b.id), "Marked paid")}
>
Mark paid
</Button>
)}
<Button
size="compact-xs"
variant="subtle"
color="orange"
leftSection={<Repeat size={13} />}
onClick={() => {
setMoveBookingId(b.id);
setMoveTarget(null);
}}
>
Move
</Button>
<Button
size="compact-xs"
variant="subtle"
color="red"
leftSection={<XCircle size={13} />}
onClick={() => run(actions.expire.mutateAsync(b.id), "Reservation expired")}
>
Expire
</Button>
</Group>
)}
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
)}
<Modal
opened={Boolean(moveBookingId)}
onClose={() => setMoveBookingId(null)}
title="Move booking to another schedule"
centered
radius="lg"
>
<Stack gap="md">
<Select
label="Target schedule (same route)"
placeholder="Select an OPEN schedule"
data={moveOptions}
value={moveTarget}
onChange={setMoveTarget}
searchable
nothingFoundMessage="No other open schedules on this route"
/>
<Group justify="flex-end">
<Button variant="default" onClick={() => setMoveBookingId(null)}>
Cancel
</Button>
<Button
color="green"
disabled={!moveTarget}
loading={actions.moveSchedule.isPending}
onClick={() => {
if (!moveBookingId || !moveTarget) return;
run(
actions.moveSchedule.mutateAsync({
bookingId: moveBookingId,
trainScheduleId: moveTarget,
}),
"Booking moved",
).then(() => setMoveBookingId(null));
}}
>
Move booking
</Button>
</Group>
</Stack>
</Modal>
</Paper>
);
}

View File

@@ -132,6 +132,15 @@ export const URL_CONSTANTS = {
TRAIN_SCHEDULING: {
ELIGIBLE_BOOKINGS: "/train-scheduling/eligible-bookings",
BOOKABLE_SCHEDULES: "/train-scheduling/bookable-schedules",
RUN_BATCH: (id: string) => `/train-scheduling/schedules/${id}/run-batch`,
BOOKING_WINDOW: (id: string) => `/train-scheduling/schedules/${id}/booking-window`,
MARK_BOOKING_PAID: (bookingId: string) =>
`/train-scheduling/bookings/${bookingId}/mark-paid`,
EXPIRE_BOOKING: (bookingId: string) =>
`/train-scheduling/bookings/${bookingId}/expire`,
MOVE_BOOKING_SCHEDULE: (bookingId: string) =>
`/train-scheduling/bookings/${bookingId}/move-schedule`,
GLOBAL_RULES: "/train-scheduling/global-rules",
PREVIEW: "/train-scheduling/preview",
ASSIGN_BOOKINGS: (id: string) => `/train-scheduling/schedules/${id}/assign-bookings`,

View File

@@ -154,6 +154,18 @@ export const BOOKING_STATUS_META: Record<string, StatusMeta> = {
color: "text-amber-700",
stage: 3,
},
AWAITING_PAYMENT: {
title: "Awaiting Payment",
description: "Selected in a batch — pay within 1 hour to secure the slot.",
color: "text-amber-600",
stage: 3,
},
EXPIRED: {
title: "Expired",
description: "Pay window missed — move to another schedule or cancel.",
color: "text-red-600",
stage: 3,
},
PAID: {
title: "Paid",
description: "Payment confirmed; ready for operations.",

View File

@@ -42,6 +42,63 @@ export const useAvailableLocomotives = () =>
queryFn: () => trainSchedulingService.getAvailableLocomotives(),
});
export const useBatchActions = (scheduleId?: string) => {
const qc = useQueryClient();
const invalidate = () => {
void qc.invalidateQueries({ queryKey: QUERY_KEYS.TRAIN_SCHEDULING.ROOT });
void qc.invalidateQueries({ queryKey: QUERY_KEYS.BOOKINGS.ROOT });
if (scheduleId) {
void qc.invalidateQueries({
queryKey: QUERY_KEYS.TRAIN_SCHEDULING.scheduleById(scheduleId),
});
}
};
const runBatch = useMutation({
mutationFn: (id: string) => trainSchedulingService.runBatch(id),
onSuccess: invalidate,
});
const setWindow = useMutation({
mutationFn: ({ id, status }: { id: string; status: "OPEN" | "CLOSED" }) =>
trainSchedulingService.setBookingWindow(id, status),
onSuccess: invalidate,
});
const markPaid = useMutation({
mutationFn: (bookingId: string) => trainSchedulingService.markBookingPaid(bookingId),
onSuccess: invalidate,
});
const expire = useMutation({
mutationFn: (bookingId: string) => trainSchedulingService.expireBooking(bookingId),
onSuccess: invalidate,
});
const moveSchedule = useMutation({
mutationFn: ({ bookingId, trainScheduleId }: { bookingId: string; trainScheduleId: string }) =>
trainSchedulingService.moveBookingSchedule(bookingId, trainScheduleId),
onSuccess: invalidate,
});
return { runBatch, setWindow, markPaid, expire, moveSchedule, invalidate };
};
export const useBookableSchedules = (
originYardId?: string | null,
destinationYardId?: string | null,
) =>
useQuery({
queryKey: [
...QUERY_KEYS.TRAIN_SCHEDULING.ROOT,
"bookable",
originYardId ?? "",
destinationYardId ?? "",
],
queryFn: () =>
trainSchedulingService.getBookableSchedules(
originYardId ?? undefined,
destinationYardId ?? undefined,
),
enabled: Boolean(originYardId && destinationYardId),
});
export const useTrainTrack = (id: string | undefined) =>
useQuery({
queryKey: QUERY_KEYS.TRAIN_SCHEDULING.track(id ?? ""),

View File

@@ -44,6 +44,7 @@ import toast from "react-hot-toast";
import Breadcrumbs from "@/components/ui/Breadcrumbs";
import { bookingsService } from "@/services/bookings.service";
import { useBookableSchedules } from "@/hooks/trainScheduling/useTrainScheduling";
import { api } from "@/auth/http";
import { unwrap } from "@/utils/endpoint";
import { URL_CONSTANTS } from "@/constants/URLS";
@@ -165,6 +166,7 @@ export default function NewBookingPage() {
const [freightType, setFreightType] = useState<FreightType>("CONTAINER");
const [originYardId, setOriginYardId] = useState<string | null>(null);
const [destinationYardId, setDestinationYardId] = useState<string | null>(null);
const [trainScheduleId, setTrainScheduleId] = useState<string | null>(null);
const [serviceTypeId, setServiceTypeId] = useState<string | null>(null);
const [scheduledDate, setScheduledDate] = useState("");
const [tradeDirection, setTradeDirection] = useState("IMPORT");
@@ -207,6 +209,17 @@ export default function NewBookingPage() {
c.id,
}));
const { data: bookableSchedules, isLoading: schedulesLoading } = useBookableSchedules(
originYardId,
destinationYardId,
);
const scheduleOptions = (bookableSchedules ?? []).map((s) => ({
value: s.id,
label: `${s.routeName ?? `${s.origin}${s.destination}`} · ${new Date(
s.scheduleDate,
).toLocaleString()} · ${s.remainingWagons}/${s.maxWagons} wagons free`,
}));
const yards = (refData?.yard ?? []).map((y) => ({ value: y.id, label: y.name ?? y.code }));
const services = (refData?.service ?? []).map((s) => ({ value: s.id, label: s.name ?? s.code }));
const shippingLines = (refData?.shipping_line ?? []).map((s) => ({ value: s.id, label: s.name ?? s.code }));
@@ -253,6 +266,7 @@ export default function NewBookingPage() {
Boolean(originYardId) &&
Boolean(destinationYardId) &&
!sameYard &&
Boolean(trainScheduleId) &&
Boolean(serviceTypeId) &&
Boolean(scheduledDate) &&
(isGovernment ? governmentInstitution.trim().length >= 2 : Boolean(companyId)) &&
@@ -280,6 +294,7 @@ export default function NewBookingPage() {
scheduledDate: scheduledDate ? new Date(scheduledDate).toISOString() : new Date().toISOString(),
originYardId,
destinationYardId,
trainScheduleId: trainScheduleId || undefined,
serviceTypeId,
shippingLineId: shippingLineId || undefined,
firstMilePickupAddress: firstMilePickupAddress.trim() || undefined,
@@ -420,7 +435,10 @@ export default function NewBookingPage() {
placeholder="Select origin"
data={yards}
value={originYardId}
onChange={setOriginYardId}
onChange={(v) => {
setOriginYardId(v);
setTrainScheduleId(null);
}}
searchable
disabled={isLoading}
error={sameYard ? "Same as destination" : undefined}
@@ -430,12 +448,31 @@ export default function NewBookingPage() {
placeholder="Select destination"
data={yards}
value={destinationYardId}
onChange={setDestinationYardId}
onChange={(v) => {
setDestinationYardId(v);
setTrainScheduleId(null);
}}
searchable
disabled={isLoading}
error={sameYard ? "Same as origin" : undefined}
/>
</Group>
<Select
label="Train schedule"
placeholder={
originYardId && destinationYardId
? "Select an open schedule on this route"
: "Pick origin & destination first"
}
data={scheduleOptions}
value={trainScheduleId}
onChange={setTrainScheduleId}
searchable
required
disabled={!originYardId || !destinationYardId || schedulesLoading}
nothingFoundMessage="No open schedules on this route"
description="The booking will be batched against this schedule once its contract is signed."
/>
<Group grow>
<Select
label="Service type"

View File

@@ -52,6 +52,7 @@ import {
scheduleBrand,
} from "@/components/trainScheduling/scheduleVisuals";
import { RescheduleTrainDialog } from "@/components/trainScheduling/RescheduleTrainDialog";
import { ScheduleBatchPanel } from "@/components/trainScheduling/ScheduleBatchPanel";
import { WorkflowRail, WorkflowStep } from "@/components/trainScheduling/WorkflowStep";
import { shouldShowContainerPlacementStep } from "@/components/trainScheduling/schedulingContainerStep.util";
import { WagonPlanGrid } from "@/components/trainScheduling/WagonPlanGrid";
@@ -902,6 +903,8 @@ export default function TrainScheduleV2DetailPage() {
</Stack>
</Paper>
<ScheduleBatchPanel schedule={schedule} />
{scheduleId ? (
<RescheduleTrainDialog
scheduleId={scheduleId}

View File

@@ -2,6 +2,7 @@ import { api as client } from '../auth/http';
import { unwrap } from '@/utils/endpoint';
import { URL_CONSTANTS } from '@/constants/URLS';
import type {
BookableSchedule,
AssignBookingsPayload,
CreateTrainSchedulePayload,
EligibleContainerBookingsResponse,
@@ -77,6 +78,53 @@ export const trainSchedulingService = {
return unwrap(response.data);
},
getBookableSchedules: async (
originYardId?: string,
destinationYardId?: string,
): Promise<BookableSchedule[]> => {
const response = await client.get<BookableSchedule[]>(
URL_CONSTANTS.TRAIN_SCHEDULING.BOOKABLE_SCHEDULES,
{ params: { originYardId, destinationYardId } },
);
return unwrap(response.data);
},
runBatch: async (scheduleId: string): Promise<TrainScheduleDetail> => {
const response = await client.post<TrainScheduleDetail>(
URL_CONSTANTS.TRAIN_SCHEDULING.RUN_BATCH(scheduleId),
{},
);
return unwrap(response.data);
},
setBookingWindow: async (
scheduleId: string,
status: "OPEN" | "CLOSED",
): Promise<TrainScheduleDetail> => {
const response = await client.patch<TrainScheduleDetail>(
URL_CONSTANTS.TRAIN_SCHEDULING.BOOKING_WINDOW(scheduleId),
{ status },
);
return unwrap(response.data);
},
markBookingPaid: async (bookingId: string): Promise<void> => {
await client.post(URL_CONSTANTS.TRAIN_SCHEDULING.MARK_BOOKING_PAID(bookingId), {});
},
expireBooking: async (bookingId: string): Promise<void> => {
await client.post(URL_CONSTANTS.TRAIN_SCHEDULING.EXPIRE_BOOKING(bookingId), {});
},
moveBookingSchedule: async (
bookingId: string,
trainScheduleId: string,
): Promise<void> => {
await client.post(URL_CONSTANTS.TRAIN_SCHEDULING.MOVE_BOOKING_SCHEDULE(bookingId), {
trainScheduleId,
});
},
getScheduleById: async (
id: string,
freightType?: FreightType,

View File

@@ -163,6 +163,21 @@ export interface TrainScheduleListItem {
status: TrainScheduleStatus | string;
}
export interface BookableSchedule {
id: string;
scheduleDate: string;
trainNumber?: string | null;
routeName?: string | null;
origin: string | null;
destination: string | null;
freightType?: FreightType | null;
status: TrainScheduleStatus | string;
bookingWindowStatus: "OPEN" | "FULL" | "CLOSED" | string;
maxWagons: number;
remainingWagons: number;
locomotive: { id: string; code: string; name?: string | null } | null;
}
export interface TrainScheduleWagonAllocation {
id: string;
bookingId: string;