Merge pull request #167 from Tria-plc/freight_feature/payments

Freight feature/payments
This commit is contained in:
yaschalew10
2026-06-16 11:13:03 +03:00
committed by GitHub
40 changed files with 1809 additions and 1345 deletions

View File

@@ -38,7 +38,6 @@ import DropdownSettingsPage from "./pages/dropdown_settings/DropdownSettingsPage
import FileUploadSettingsPage from "./pages/documents/FileUploadSettingsPage";
import RuleEngineLegacyRedirect from "./pages/ruleEngine/RuleEngineLegacyRedirect";
import RuleEngineResourcePage from "./pages/ruleEngine/RuleEngineResourcePage";
import TrainsPage from "./pages/trains/TrainsPage";
import TrainScheduleV2ListPage from "./pages/trainScheduling/TrainScheduleV2ListPage";
import BatchBoardPage from "./pages/trainScheduling/BatchBoardPage";
import BatchScheduleDetailPage from "./pages/trainScheduling/BatchScheduleDetailPage";
@@ -78,11 +77,6 @@ const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [
items: [
{
label: "Train Schedules",
href: "/dashboard/operations/train-scheduling",
icon: <Train />,
},
{
label: "Train Schedules v2",
href: "/dashboard/operations/train-scheduling-v2",
icon: <Train />,
},
@@ -106,31 +100,31 @@ const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [
href: "/dashboard/locomotives",
icon: <Train />,
},
{
label: "Trains",
href: "/dashboard/trains",
icon: <Train />,
},
{
label: "Wagon types",
href: "/dashboard/wagon-types",
icon: <Boxes />,
},
// {
// label: "Trains",
// href: "/dashboard/trains",
// icon: <Train />,
// },
// {
// label: "Wagon types",
// href: "/dashboard/wagon-types",
// icon: <Boxes />,
// },
{
label: "Wagons",
href: "/dashboard/wagons",
icon: <Truck />,
},
{
label: "Containers",
href: "/dashboard/containers",
icon: <Container />,
},
{
label: "Cargoes",
href: "/dashboard/cargoes",
icon: <Package />,
},
// {
// label: "Containers",
// href: "/dashboard/containers",
// icon: <Container />,
// },
// {
// label: "Cargoes",
// href: "/dashboard/cargoes",
// icon: <Package />,
// },
],
},
{
@@ -271,7 +265,10 @@ const App = () => {
path="booking-requests/:id/contract"
element={<BookingContractPage />}
/>
<Route path="operations/train-scheduling" element={<TrainsPage />} />
<Route
path="operations/train-scheduling"
element={<Navigate to="/dashboard/operations/train-scheduling-v2" replace />}
/>
<Route path="operations/batch-board" element={<BatchBoardPage />} />
<Route
path="operations/batch-board/:scheduleId"

View File

@@ -150,7 +150,10 @@ const FleetFormDialog = ({
label={field.label}
value={String(value ?? "")}
onChange={(e) =>
setValues((current) => ({ ...current, [field.name]: e.currentTarget.value }))
setValues((current) => ({
...current,
[field.name]: e.target?.value ?? "",
}))
}
error={error}
minRows={3}
@@ -164,7 +167,10 @@ const FleetFormDialog = ({
label={field.label}
value={String(value ?? "")}
onChange={(e) =>
setValues((current) => ({ ...current, [field.name]: e.currentTarget.value }))
setValues((current) => ({
...current,
[field.name]: e.target?.value ?? "",
}))
}
error={error}
/>

View File

@@ -181,6 +181,22 @@
transition: transform 220ms ease;
}
.fsb-chevron-btn {
display: flex;
align-items: center;
justify-content: center;
padding: 0;
margin: 0;
border: none;
background: transparent;
cursor: pointer;
flex-shrink: 0;
}
.fsb-chevron-btn:hover .fsb-chevron {
color: #64748b;
}
/* ---- Nested branch ---- */
.fsb-branch {
margin: 2px 0 2px 22px;

View File

@@ -180,23 +180,37 @@ const FreightSidebar = ({
href={item.href}
className="fsb-item"
data-active={isActive}
onClick={(e) => navigateTo(e, item.href!)}
onClick={(e) => {
if (hasChildren) {
setExpanded((current) => ({
...current,
[item.href!]: true,
}));
}
navigateTo(e, item.href!);
}}
>
{item.icon && <span className="fsb-icon">{item.icon}</span>}
<span className="fsb-item-label">{item.label}</span>
{hasChildren && (
<ChevronDown
size={16}
className="fsb-chevron"
style={{
transform: isOpen ? "rotate(0deg)" : "rotate(-90deg)",
}}
<button
type="button"
className="fsb-chevron-btn"
aria-label={isOpen ? "Collapse section" : "Expand section"}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
toggleExpanded(item.href!);
}}
/>
>
<ChevronDown
size={16}
className="fsb-chevron"
style={{
transform: isOpen ? "rotate(0deg)" : "rotate(-90deg)",
}}
/>
</button>
)}
</a>

View File

@@ -45,16 +45,9 @@ const ROUTE_META: Array<{ prefix: string; meta: PageMeta }> = [
},
{
prefix: "/dashboard/operations/train-scheduling-v2",
meta: {
title: "Train Schedules v2",
subtitle: "Operational train scheduling with full allocation workflow",
},
},
{
prefix: "/dashboard/operations/train-scheduling",
meta: {
title: "Train Schedules",
subtitle: "Create and manage container train schedules",
subtitle: "Operational train scheduling with full allocation workflow",
},
},
{

View File

@@ -16,7 +16,7 @@ import {
Group,
Loader,
Paper,
SimpleGrid,
Progress,
Stack,
Text,
ThemeIcon,
@@ -25,12 +25,8 @@ import {
} from "@mantine/core";
import { RouteCorridorTrack } from "@/components/trainScheduling/RouteCorridorTrack";
import {
RouteCorridor,
StatTile,
StatusPill,
scheduleBrand,
} from "@/components/trainScheduling/scheduleVisuals";
import { RouteCorridor, StatusPill } from "@/components/trainScheduling/scheduleVisuals";
import { freightBrand } from "@/theme/freight-brand";
import { useTrainTrack, useScheduleMutations } from "@/hooks/trainScheduling/useTrainScheduling";
import { useToast } from "@/hooks/use-toast";
@@ -54,6 +50,33 @@ function formatDateTime(iso?: string | null) {
});
}
/** Compact icon + label + value cell used in the header meta strip. */
function MetaStat({
icon,
label,
value,
}: {
icon: React.ReactNode;
label: string;
value: string;
}) {
return (
<Group gap={8} wrap="nowrap" style={{ minWidth: 0 }}>
<ThemeIcon size={32} radius="md" variant="light" color="green">
{icon}
</ThemeIcon>
<Stack gap={0} style={{ minWidth: 0 }}>
<Text size="10px" fw={700} tt="uppercase" c="dimmed" style={{ letterSpacing: 0.5 }}>
{label}
</Text>
<Text size="sm" fw={700} c="dark.5" truncate>
{value}
</Text>
</Stack>
</Group>
);
}
export default function TrainScheduleTrackPage() {
const { scheduleId } = useParams<{ scheduleId: string }>();
const { toast } = useToast();
@@ -63,7 +86,7 @@ export default function TrainScheduleTrackPage() {
if (trackQuery.isLoading) {
return (
<Group justify="center" py="xl">
<Loader size="sm" />
<Loader size="sm" color="green" />
</Group>
);
}
@@ -80,7 +103,9 @@ export default function TrainScheduleTrackPage() {
const canLog = track.status === "DISPATCHED";
const totalStations = track.stations.length;
const reached = Math.min(track.currentSequenceNo + 1, totalStations);
const progressLabel = `${reached} / ${totalStations}`;
const progressPct = totalStations > 1 ? (track.currentSequenceNo / (totalStations - 1)) * 100 : 0;
const clampedPct = Math.min(100, Math.max(0, progressPct));
const currentStation = track.stations[Math.max(0, track.currentSequenceNo)]?.label ?? "—";
const handleLog = (sequenceNo: number) => {
const isFinal = sequenceNo === track.stations[totalStations - 1]?.sequenceNo;
@@ -105,7 +130,7 @@ export default function TrainScheduleTrackPage() {
};
return (
<Stack gap="lg">
<Stack gap="md" px={{ base: "xs", sm: 0 }} py="md" maw={1080} mx="auto" w="100%">
<Button
component={Link}
to={`/dashboard/operations/train-scheduling-v2/${scheduleId}`}
@@ -118,89 +143,111 @@ export default function TrainScheduleTrackPage() {
Back to schedule
</Button>
{/* Hero */}
<Paper
radius="xl"
p="xl"
style={{
position: "relative",
overflow: "hidden",
background: scheduleBrand.heroGradient,
boxShadow: scheduleBrand.shadow,
}}
>
<Box
style={{
position: "absolute",
top: -90,
right: -50,
width: 280,
height: 280,
borderRadius: "50%",
background: "rgba(255,255,255,0.10)",
pointerEvents: "none",
}}
/>
<Stack gap="lg" style={{ position: "relative" }}>
<Group justify="space-between" align="flex-start" wrap="wrap">
<Group gap="md" align="flex-start" wrap="nowrap">
<ThemeIcon size={56} radius="lg" variant="white" style={{ color: "var(--mantine-color-green-7)" }}>
<Navigation size={28} />
</ThemeIcon>
<Stack gap={6}>
{/* Header */}
<Paper radius="lg" withBorder p="lg" style={{ borderColor: "var(--mantine-color-gray-2)" }}>
<Stack gap="lg">
<Group justify="space-between" align="flex-start" wrap="wrap" gap="md">
<Group gap="md" align="flex-start" wrap="nowrap" style={{ minWidth: 0 }}>
<Box
style={{
width: 48,
height: 48,
borderRadius: 12,
display: "flex",
alignItems: "center",
justifyContent: "center",
background: freightBrand.gradient,
color: "white",
flexShrink: 0,
}}
>
<Navigation size={24} />
</Box>
<Stack gap={6} style={{ minWidth: 0 }}>
<Group gap="sm" align="center" wrap="wrap">
<Title order={2} c="white" fw={700}>
Track train
<Title order={3} fw={800}>
Train tracking
</Title>
{track.trainNumber ? (
<Badge variant="white" c="green.8" radius="sm" style={{ fontWeight: 600 }}>
<Badge variant="light" color="green" radius="sm">
{track.trainNumber}
</Badge>
) : null}
{track.direction ? (
<Badge variant="white" c="green.8" radius="sm">
<Badge variant="light" color="gray" radius="sm">
{track.direction}
</Badge>
) : null}
</Group>
<Box maw={340}>
<RouteCorridor onDark origin={track.origin} destination={track.destination} />
<Box maw={360}>
<RouteCorridor origin={track.origin} destination={track.destination} variant="compact" />
</Box>
<StatusPill status={track.status} />
</Stack>
</Group>
<StatusPill status={track.status} />
</Group>
<SimpleGrid cols={{ base: 2, sm: 4 }} spacing="md">
<StatTile onDark icon={Train} label="Progress" value={progressLabel} hint="stations reached" />
<StatTile onDark icon={MapPin} label="Current" value={track.stations[Math.max(0, track.currentSequenceNo)]?.label ?? "—"} />
<StatTile onDark icon={CalendarClock} label="Departed" value={formatDateTime(track.actualDepartureAt)} />
<StatTile onDark icon={Flag} label="Arrived" value={formatDateTime(track.actualArrivalAt)} />
</SimpleGrid>
{/* Journey progress */}
<Box>
<Group justify="space-between" mb={6}>
<Text size="xs" fw={700} c="gray.7" tt="uppercase" style={{ letterSpacing: 0.4 }}>
Journey progress
</Text>
<Text size="xs" fw={700} c="green.8">
{reached} / {totalStations} stations · {Math.round(clampedPct)}%
</Text>
</Group>
<Progress
value={clampedPct}
size="lg"
radius="xl"
color="green"
striped={track.status === "DISPATCHED"}
animated={track.status === "DISPATCHED"}
/>
</Box>
{/* Meta strip */}
<Group justify="space-between" wrap="wrap" gap="lg">
<MetaStat icon={<MapPin size={16} />} label="Current" value={currentStation} />
<MetaStat
icon={<CalendarClock size={16} />}
label="Departed"
value={formatDateTime(track.actualDepartureAt)}
/>
<MetaStat
icon={<Flag size={16} />}
label="Arrived"
value={formatDateTime(track.actualArrivalAt)}
/>
<MetaStat
icon={<Train size={16} />}
label="Stations"
value={`${reached} of ${totalStations}`}
/>
</Group>
</Stack>
</Paper>
{/* Corridor */}
<Paper radius="xl" p="lg" withBorder style={{ borderColor: "var(--mantine-color-gray-2)" }}>
<Stack gap="lg">
<Group justify="space-between" align="center" wrap="nowrap">
<Group gap="md" align="center" wrap="nowrap">
<ThemeIcon size={44} radius="md" variant="gradient" gradient={{ from: "green", to: "teal", deg: 135 }}>
<Navigation size={22} />
</ThemeIcon>
<Stack gap={2}>
<Title order={4} fw={700}>
Route corridor
</Title>
<Text size="sm" c="dimmed">
{canLog
? "Log the train passing each station; the final station marks arrival."
: track.status === "ARRIVED"
? "This train has arrived at its destination."
: "Tracking becomes available once the train is dispatched."}
</Text>
</Stack>
</Group>
<Paper radius="lg" p="lg" withBorder style={{ borderColor: "var(--mantine-color-gray-2)" }}>
<Stack gap="md">
<Group gap="sm" align="center" wrap="nowrap">
<ThemeIcon size={34} radius="md" variant="light" color="green">
<Navigation size={17} />
</ThemeIcon>
<Stack gap={0}>
<Text fw={800} size="sm">
Route corridor
</Text>
<Text size="xs" c="dimmed">
{canLog
? "Log the train passing each station; the final station marks arrival."
: track.status === "ARRIVED"
? "This train has arrived at its destination."
: "Tracking becomes available once the train is dispatched."}
</Text>
</Stack>
</Group>
<RouteCorridorTrack
@@ -216,47 +263,68 @@ export default function TrainScheduleTrackPage() {
</Stack>
</Paper>
{/* Timeline */}
<Paper radius="xl" p="lg" withBorder style={{ borderColor: "var(--mantine-color-gray-2)" }}>
<Stack gap="md">
<Title order={5} fw={700}>
Checkpoint log
</Title>
{track.checkpoints.length === 0 ? (
<Text size="sm" c="dimmed">
No checkpoints logged yet.
{/* Checkpoint log */}
<Paper radius="lg" p="lg" withBorder style={{ borderColor: "var(--mantine-color-gray-2)" }}>
<Group gap="sm" align="center" wrap="nowrap" mb="md">
<ThemeIcon size={34} radius="md" variant="light" color="green">
<CheckCircle2 size={17} />
</ThemeIcon>
<Stack gap={0}>
<Text fw={800} size="sm">
Checkpoint log
</Text>
) : (
<Timeline active={track.checkpoints.length} bulletSize={22} lineWidth={2} color="green">
{track.checkpoints.map((cp) => (
<Timeline.Item
key={cp.id}
bullet={cp.kind === "ARRIVED" ? <CheckCircle2 size={13} /> : <MapPin size={12} />}
title={
<Group gap="sm">
<Text fw={600} size="sm">
{cp.label ?? `Station ${cp.sequenceNo}`}
</Text>
<Badge
size="xs"
radius="sm"
variant="light"
color={cp.kind === "ARRIVED" ? "teal" : cp.kind === "DEPARTED" ? "blue" : "green"}
>
{cp.kind}
</Badge>
</Group>
}
>
<Text size="xs" c="dimmed">
{formatDateTime(cp.occurredAt)}
<Text size="xs" c="dimmed">
{track.checkpoints.length} event{track.checkpoints.length === 1 ? "" : "s"} recorded
</Text>
</Stack>
</Group>
{track.checkpoints.length === 0 ? (
<Stack align="center" gap="xs" py="xl">
<ThemeIcon size={44} radius="xl" variant="light" color="gray">
<MapPin size={20} />
</ThemeIcon>
<Text size="sm" fw={600} c="gray.7">
No checkpoints yet
</Text>
<Text size="xs" c="dimmed" ta="center" maw={300}>
Each station the train passes will be logged here with its timestamp.
</Text>
</Stack>
) : (
<Timeline active={track.checkpoints.length} bulletSize={22} lineWidth={2} color="green">
{track.checkpoints.map((cp) => (
<Timeline.Item
key={cp.id}
bullet={cp.kind === "ARRIVED" ? <CheckCircle2 size={13} /> : <MapPin size={12} />}
title={
<Group gap="sm">
<Text fw={700} size="sm">
{cp.label ?? `Station ${cp.sequenceNo}`}
</Text>
<Badge
size="xs"
radius="sm"
variant="light"
color={cp.kind === "ARRIVED" ? "teal" : cp.kind === "DEPARTED" ? "blue" : "green"}
>
{cp.kind}
</Badge>
</Group>
}
>
<Text size="xs" c="dimmed">
{formatDateTime(cp.occurredAt)}
</Text>
{cp.note ? (
<Text size="xs" mt={2}>
{cp.note}
</Text>
{cp.note ? <Text size="xs">{cp.note}</Text> : null}
</Timeline.Item>
))}
</Timeline>
)}
</Stack>
) : null}
</Timeline.Item>
))}
</Timeline>
)}
</Paper>
</Stack>
);

View File

@@ -1,482 +0,0 @@
import { useMemo, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { isAxiosError } from 'axios';
import toast from 'react-hot-toast';
import { Calendar, RefreshCw, TrainTrack } from 'lucide-react';
import {
Button,
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@edr/ui-common';
import Breadcrumbs from '@/components/ui/Breadcrumbs';
import { QUERY_KEYS } from '@/constants/QUERY_KEYS';
import { useRoutes } from '@/hooks/useRoutes';
import { trainSchedulingService } from '@/services/trainScheduling.service';
const inputClassName =
'w-full rounded-xl border border-border bg-background px-3 py-2.5 text-sm text-foreground outline-none transition focus:border-emerald-500 focus:ring-2 focus:ring-emerald-100 dark:focus:ring-emerald-950';
const formatDate = (value?: string | null) => {
if (!value) return '-';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return '-';
return new Intl.DateTimeFormat('en', {
year: 'numeric',
month: 'short',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
}).format(date);
};
const parseError = (error: unknown, fallback: string) => {
if (isAxiosError(error)) {
const message = error.response?.data?.message;
if (Array.isArray(message)) return message.join(', ');
if (typeof message === 'string') return message;
const violations = error.response?.data?.violations;
if (Array.isArray(violations)) return violations.join(', ');
}
return fallback;
};
const TrainsPage = () => {
const qc = useQueryClient();
const [routeId, setRouteId] = useState('');
const [scheduleDate, setScheduleDate] = useState('');
const [selectedLocomotiveId, setSelectedLocomotiveId] = useState('');
const [detailId, setDetailId] = useState<string | null>(null);
const [scheduleSearch, setScheduleSearch] = useState('');
const [scheduleStatusFilter, setScheduleStatusFilter] = useState('ALL');
const routesQuery = useRoutes();
const locomotivesQuery = useQuery({
queryKey: QUERY_KEYS.TRAIN_SCHEDULING.locomotives(),
queryFn: () => trainSchedulingService.getAvailableLocomotives(),
});
const schedulesQuery = useQuery({
queryKey: QUERY_KEYS.TRAIN_SCHEDULING.schedules(),
queryFn: () => trainSchedulingService.listSchedules(),
});
const detailQuery = useQuery({
queryKey: QUERY_KEYS.TRAIN_SCHEDULING.scheduleById(detailId ?? ''),
queryFn: () => trainSchedulingService.getScheduleById(detailId!),
enabled: Boolean(detailId),
});
const activeRoutes = useMemo(
() => (routesQuery.data ?? []).filter((route) => route.isActive),
[routesQuery.data],
);
const selectedRoute = activeRoutes.find((route) => route.id === routeId) ?? null;
const selectedLocomotive = (locomotivesQuery.data ?? []).find(
(locomotive) => locomotive.id === selectedLocomotiveId,
);
const filteredSchedules = useMemo(() => {
const query = scheduleSearch.trim().toLowerCase();
return (schedulesQuery.data ?? []).filter((schedule) => {
const matchesStatus =
scheduleStatusFilter === 'ALL' || schedule.status === scheduleStatusFilter;
if (!matchesStatus) {
return false;
}
if (!query) {
return true;
}
const haystack = [
schedule.id,
schedule.routeName ?? '',
schedule.origin ?? '',
schedule.destination ?? '',
schedule.locomotive?.code ?? '',
schedule.status,
]
.join(' ')
.toLowerCase();
return haystack.includes(query);
});
}, [scheduleSearch, scheduleStatusFilter, schedulesQuery.data]);
const createMutation = useMutation({
mutationFn: () => {
if (!routeId || !scheduleDate || !selectedLocomotiveId) {
throw new Error('Please select route, departure date, and locomotive');
}
return trainSchedulingService.createSchedule({
routeId,
scheduleDate: new Date(`${scheduleDate}T08:00:00.000Z`).toISOString(),
locomotiveId: selectedLocomotiveId,
});
},
onSuccess: (data) => {
toast.success('Train schedule created');
setRouteId('');
setScheduleDate('');
setSelectedLocomotiveId('');
void qc.invalidateQueries({ queryKey: QUERY_KEYS.TRAIN_SCHEDULING.ROOT });
void qc.invalidateQueries({ queryKey: QUERY_KEYS.TRAIN_SCHEDULING.schedules() });
void qc.invalidateQueries({ queryKey: QUERY_KEYS.TRAIN_SCHEDULING.locomotives() });
setDetailId(data.id);
},
onError: (error) => {
toast.error(parseError(error, 'Failed to create train schedule'));
},
});
const cancelMutation = useMutation({
mutationFn: (id: string) => trainSchedulingService.cancelSchedule(id),
onSuccess: (data) => {
toast.success('Train schedule cancelled');
void qc.invalidateQueries({ queryKey: QUERY_KEYS.TRAIN_SCHEDULING.schedules() });
void qc.invalidateQueries({ queryKey: QUERY_KEYS.TRAIN_SCHEDULING.locomotives() });
void qc.invalidateQueries({ queryKey: QUERY_KEYS.TRAIN_SCHEDULING.ROOT });
void qc.invalidateQueries({ queryKey: QUERY_KEYS.TRAIN_SCHEDULING.scheduleById(data.id) });
setDetailId(data.id);
},
onError: (error) => {
toast.error(parseError(error, 'Failed to cancel train schedule'));
},
});
const detail = detailQuery.data;
const isBusy = createMutation.isPending;
return (
<div className="space-y-6 p-6">
<Breadcrumbs items={[{ label: 'Operations' }, { label: 'Train schedules' }]} />
<section className="overflow-hidden rounded-3xl border border-border bg-card shadow-sm">
<div className="flex flex-col gap-5 border-b border-border px-6 py-6 lg:flex-row lg:items-center lg:justify-between">
<div className="flex items-start gap-4">
<div className="flex size-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
<TrainTrack className="size-7" />
</div>
<div>
<h1 className="text-2xl font-bold tracking-tight">Train Schedules</h1>
<p className="mt-1 text-sm text-muted-foreground">
Create the train schedule first, reserve the locomotive, and assign bookings and wagons later.
</p>
</div>
</div>
<Button
variant="outline"
className="gap-2"
onClick={() => {
void routesQuery.refetch();
void schedulesQuery.refetch();
void locomotivesQuery.refetch();
}}
>
<RefreshCw className="size-4" />
Refresh
</Button>
</div>
<div className="grid gap-6 p-6 xl:grid-cols-[1.1fr,1.4fr]">
<section className="rounded-2xl border border-border bg-background/60 p-5">
<div className="mb-4 flex items-center gap-2">
<Calendar className="size-4 text-muted-foreground" />
<h2 className="text-lg font-semibold">Schedule builder</h2>
</div>
<div className="grid gap-4">
<div className="space-y-2">
<label className="text-sm font-medium">Route</label>
<Select value={routeId} onValueChange={setRouteId}>
<SelectTrigger>
<SelectValue placeholder="Select active route" />
</SelectTrigger>
<SelectContent>
{activeRoutes.map((route) => (
<SelectItem key={route.id} value={route.id}>
{route.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Departure date</label>
<input
className={inputClassName}
type="date"
value={scheduleDate}
onChange={(event) => setScheduleDate(event.target.value)}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Locomotive</label>
<Select value={selectedLocomotiveId} onValueChange={setSelectedLocomotiveId}>
<SelectTrigger>
<SelectValue placeholder="Select available locomotive" />
</SelectTrigger>
<SelectContent>
{(locomotivesQuery.data ?? []).map((locomotive) => (
<SelectItem key={locomotive.id} value={locomotive.id}>
{locomotive.code} - {locomotive.maxPullWeightTons}T / {locomotive.maxTrainLengthMeters}m
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="mt-5 grid gap-3 sm:grid-cols-2">
<div className="rounded-xl border border-border bg-card p-4">
<p className="text-xs uppercase tracking-wide text-muted-foreground">Origin</p>
<p className="mt-2 text-sm font-medium">
{selectedRoute?.originYard?.label ?? selectedRoute?.originYard?.code ?? '-'}
</p>
</div>
<div className="rounded-xl border border-border bg-card p-4">
<p className="text-xs uppercase tracking-wide text-muted-foreground">Destination</p>
<p className="mt-2 text-sm font-medium">
{selectedRoute?.destinationYard?.label ?? selectedRoute?.destinationYard?.code ?? '-'}
</p>
</div>
<div className="rounded-xl border border-border bg-card p-4">
<p className="text-xs uppercase tracking-wide text-muted-foreground">Locomotive capacity</p>
<p className="mt-2 text-sm font-medium">
{selectedLocomotive
? `${selectedLocomotive.maxPullWeightTons}T / ${selectedLocomotive.maxTrainLengthMeters}m`
: '-'}
</p>
</div>
<div className="rounded-xl border border-border bg-card p-4">
<p className="text-xs uppercase tracking-wide text-muted-foreground">Next step</p>
<p className="mt-2 text-sm font-medium">Assign bookings, then allocate wagons</p>
</div>
</div>
<div className="mt-5">
<Button className="w-full" disabled={isBusy} onClick={() => createMutation.mutate()}>
Create schedule
</Button>
</div>
</section>
<section className="rounded-2xl border border-border bg-background/60 p-5">
<div className="mb-4 flex items-center justify-between">
<div>
<h2 className="text-lg font-semibold">Created schedules</h2>
<p className="text-sm text-muted-foreground">
Open a schedule to inspect the reserved locomotive and prepare for later booking and wagon work.
</p>
</div>
<span className="rounded-full bg-muted px-3 py-1 text-xs font-medium text-muted-foreground">
{filteredSchedules.length} schedules
</span>
</div>
<div className="mb-4 grid gap-3 md:grid-cols-[1fr,220px]">
<input
className={inputClassName}
placeholder="Search by schedule, route, locomotive, or status"
value={scheduleSearch}
onChange={(event) => setScheduleSearch(event.target.value)}
/>
<Select value={scheduleStatusFilter} onValueChange={setScheduleStatusFilter}>
<SelectTrigger>
<SelectValue placeholder="All statuses" />
</SelectTrigger>
<SelectContent>
<SelectItem value="ALL">All statuses</SelectItem>
<SelectItem value="DRAFT">DRAFT</SelectItem>
<SelectItem value="SCHEDULED">SCHEDULED</SelectItem>
<SelectItem value="DISPATCHED">DISPATCHED</SelectItem>
<SelectItem value="ARRIVED">ARRIVED</SelectItem>
<SelectItem value="CANCELLED">CANCELLED</SelectItem>
</SelectContent>
</Select>
</div>
<div className="overflow-x-auto rounded-2xl border border-border">
<table className="min-w-full divide-y divide-border text-sm">
<thead className="bg-muted/40 text-left text-xs uppercase tracking-wide text-muted-foreground">
<tr>
<th className="px-3 py-3">Schedule</th>
<th className="px-3 py-3">Departure</th>
<th className="px-3 py-3">Route</th>
<th className="px-3 py-3">Locomotive</th>
<th className="px-3 py-3">Bookings</th>
<th className="px-3 py-3">Wagons</th>
<th className="px-3 py-3">Weight</th>
<th className="px-3 py-3">Length</th>
<th className="px-3 py-3">Status</th>
<th className="px-3 py-3">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-border bg-card">
{filteredSchedules.map((schedule) => (
<tr key={schedule.id} className="hover:bg-muted/20">
<td className="px-3 py-3 font-mono text-xs">{schedule.id}</td>
<td className="px-3 py-3">{formatDate(schedule.scheduleDate)}</td>
<td className="px-3 py-3">
{schedule.routeName ?? `${schedule.origin ?? '-'} to ${schedule.destination ?? '-'}`}
</td>
<td className="px-3 py-3">{schedule.locomotive?.code ?? '-'}</td>
<td className="px-3 py-3">{schedule.bookingsCount}</td>
<td className="px-3 py-3">{schedule.wagonCount}</td>
<td className="px-3 py-3">{schedule.totalWeightTons} T</td>
<td className="px-3 py-3">{schedule.totalLengthMeters} m</td>
<td className="px-3 py-3">{schedule.status}</td>
<td className="px-3 py-3">
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => setDetailId(schedule.id)}>
View
</Button>
{schedule.status !== 'CANCELLED' ? (
<Button
variant="outline"
size="sm"
onClick={() => cancelMutation.mutate(schedule.id)}
>
Cancel
</Button>
) : null}
</div>
</td>
</tr>
))}
{!schedulesQuery.isLoading && filteredSchedules.length === 0 ? (
<tr>
<td className="px-3 py-8 text-center text-sm text-muted-foreground" colSpan={10}>
No train schedules matched the current filters.
</td>
</tr>
) : null}
</tbody>
</table>
</div>
</section>
</div>
</section>
<Dialog open={Boolean(detailId)} onOpenChange={(open) => (!open ? setDetailId(null) : null)}>
<DialogContent className="max-h-[90vh] max-w-5xl overflow-y-auto">
<DialogHeader>
<DialogTitle>Train schedule detail</DialogTitle>
<DialogDescription>
Inspect the selected schedule. Booking assignment and wagon allocation happen after schedule creation.
</DialogDescription>
</DialogHeader>
{detail ? (
<div className="space-y-6">
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-5">
<div className="rounded-xl border border-border p-4">
<p className="text-xs uppercase tracking-wide text-muted-foreground">Schedule</p>
<p className="mt-2 break-all font-mono text-xs">{detail.id}</p>
</div>
<div className="rounded-xl border border-border p-4">
<p className="text-xs uppercase tracking-wide text-muted-foreground">Departure</p>
<p className="mt-2 text-sm font-medium">{formatDate(detail.scheduledDepartureDate)}</p>
</div>
<div className="rounded-xl border border-border p-4">
<p className="text-xs uppercase tracking-wide text-muted-foreground">Route</p>
<p className="mt-2 text-sm font-medium">{detail.route?.name ?? '-'}</p>
</div>
<div className="rounded-xl border border-border p-4">
<p className="text-xs uppercase tracking-wide text-muted-foreground">Origin / destination</p>
<p className="mt-2 text-sm font-medium">
{detail.originStation?.label ?? detail.originStation?.code ?? '-'} to{' '}
{detail.destinationStation?.label ?? detail.destinationStation?.code ?? '-'}
</p>
</div>
<div className="rounded-xl border border-border p-4">
<p className="text-xs uppercase tracking-wide text-muted-foreground">Status</p>
<p className="mt-2 text-sm font-medium">{detail.status}</p>
</div>
</div>
<div className="rounded-2xl border border-border p-4">
<h3 className="text-lg font-semibold">Locomotive</h3>
<p className="mt-2 text-sm text-muted-foreground">
{detail.trainSet?.locomotive
? `${detail.trainSet.locomotive.code} (${detail.trainSet.locomotive.maxPullWeightTons}T pull capacity / ${detail.trainSet.locomotive.maxTrainLengthMeters ?? 0}m)`
: 'No locomotive attached'}
</p>
</div>
<div className="rounded-2xl border border-border p-4">
<h3 className="text-lg font-semibold">Wagons and allocations</h3>
{(detail.trainSet?.wagons?.length ?? 0) === 0 ? (
<p className="mt-3 text-sm text-muted-foreground">No wagons allocated yet.</p>
) : (
<div className="mt-4 space-y-4">
{(detail.trainSet?.wagons ?? []).map((wagon) => (
<div key={wagon.id} className="rounded-xl border border-border p-4">
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div>
<p className="font-semibold">
Wagon {wagon.sequenceNo} - {wagon.wagonType?.code ?? 'NW5'}
</p>
<p className="text-sm text-muted-foreground">
{wagon.assignedWeightTons}T assigned / {wagon.capacityTons}T capacity / {wagon.lengthMeters}m
</p>
</div>
</div>
</div>
))}
</div>
)}
</div>
<div className="rounded-2xl border border-border p-4">
<h3 className="text-lg font-semibold">Bookings in schedule</h3>
{detail.bookings.length === 0 ? (
<p className="mt-3 text-sm text-muted-foreground">No bookings assigned yet.</p>
) : (
<div className="mt-4 overflow-x-auto rounded-xl border border-border">
<table className="min-w-full divide-y divide-border text-sm">
<thead className="bg-muted/40 text-left text-xs uppercase tracking-wide text-muted-foreground">
<tr>
<th className="px-3 py-2">Reference</th>
<th className="px-3 py-2">Customer</th>
<th className="px-3 py-2">Weight</th>
<th className="px-3 py-2">Status</th>
</tr>
</thead>
<tbody className="divide-y divide-border bg-card">
{detail.bookings.map((booking) => (
<tr key={booking.id}>
<td className="px-3 py-2">{booking.reference ?? booking.id}</td>
<td className="px-3 py-2">{booking.customer ?? '-'}</td>
<td className="px-3 py-2">{booking.weightTons} T</td>
<td className="px-3 py-2">{booking.status ?? '-'}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
) : (
<p className="text-sm text-muted-foreground">Loading schedule detail...</p>
)}
</DialogContent>
</Dialog>
</div>
);
};
export default TrainsPage;