Merge freight/develop into Warehouses

This commit is contained in:
Hagernesh
2026-06-11 19:26:21 +00:00
709 changed files with 68627 additions and 9486 deletions

View File

@@ -7,6 +7,7 @@ import { useBookingActionDialog } from "./useBookingActionDialog";
import { useAuth } from "@/auth/useAuth";
import {
getNextPendingApprovalStep,
isAllocateAction,
isContractNavAction,
listRowHasActions,
type BookingActionContext,
@@ -20,12 +21,14 @@ interface BookingActionsMenuProps {
className?: string;
/** Suppresses table row navigation after menu/dialog close (click-through). */
onSuppressRowClick?: () => void;
onAllocateBooking?: () => void;
}
export function BookingActionsMenu({
row,
variant = "table",
onSuppressRowClick,
onAllocateBooking,
}: BookingActionsMenuProps) {
const navigate = useNavigate();
const { user } = useAuth();
@@ -34,6 +37,7 @@ export function BookingActionsMenu({
paymentCurrency: row.paymentCurrency,
reference: row.reference,
approvalSteps: row.approvalSteps,
schedulingStatus: row.schedulingStatus,
};
const flow = useBookingActionDialog(row.id, context);
@@ -46,6 +50,8 @@ export function BookingActionsMenu({
onSuppressRowClick?.();
if (isContractNavAction(action.id)) {
goToContract();
} else if (isAllocateAction(action.id)) {
onAllocateBooking?.();
} else {
flow.openAction(action);
}

View File

@@ -1,10 +1,13 @@
import { useState } from "react";
import { Download, Zap, FileText, Clock } from "lucide-react";
import { Stack, Text, Button } from "@mantine/core";
import { AllocateBookingWizard } from "@/components/trainScheduling/AllocateBookingWizard";
import type { BookingDetail } from "@/types/booking";
import { BookingActionsMenu } from "./BookingActionsMenu";
import { SectionCard } from "./detail/SectionCard";
import { toBookingListRow } from "@/features/bookings/mapBookingListRow";
import { canAllocateBooking } from "@/features/bookings/booking-actions.config";
import type { useBookingMutations } from "@/hooks/bookings/useBookings";
type Mutations = ReturnType<typeof useBookingMutations>;
@@ -18,6 +21,7 @@ interface BookingActionsToolbarProps {
export function BookingActionsToolbar({ booking, mutations }: BookingActionsToolbarProps) {
const row = toBookingListRow(booking);
const { status } = booking;
const [allocateOpen, setAllocateOpen] = useState(false);
const downloadBlob = async (fn: () => Promise<Blob>, filename: string) => {
const blob = await fn();
@@ -98,7 +102,11 @@ export function BookingActionsToolbar({ booking, mutations }: BookingActionsTool
<Text size="xs" c="dimmed">
Confirm each step before it is applied.
</Text>
<BookingActionsMenu row={row} variant="toolbar" />
<BookingActionsMenu
row={row}
variant="toolbar"
onAllocateBooking={() => setAllocateOpen(true)}
/>
</Stack>
</SectionCard>
@@ -118,6 +126,14 @@ export function BookingActionsToolbar({ booking, mutations }: BookingActionsTool
</Button>
</SectionCard>
)}
{canAllocateBooking(booking) ? (
<AllocateBookingWizard
booking={booking}
opened={allocateOpen}
onClose={() => setAllocateOpen(false)}
/>
) : null}
</Stack>
);
}

View File

@@ -0,0 +1,353 @@
import type { ReactNode } from "react";
import { Box, Button, Group, Paper, Stack, Text, ThemeIcon, Title } from "@mantine/core";
import type { LucideIcon } from "lucide-react";
import {
AlertTriangle,
CheckCircle2,
Clock,
Inbox,
LayoutList,
Plus,
RefreshCw,
} from "lucide-react";
import { freightBrand } from "@/theme/freight-brand";
import type {
BookingListSummaryMetrics,
BookingListSummaryTabs,
} from "@/services/bookings.service";
const HERO_GRADIENT = `linear-gradient(135deg, ${freightBrand.primaryDark} 0%, ${freightBrand.primary} 48%, ${freightBrand.primaryLight} 120%)`;
/** Lifecycle stages for the pipeline distribution bar (in flow order). */
const PIPELINE_STAGES: Array<{
key: keyof BookingListSummaryTabs;
label: string;
color: string;
}> = [
{ key: "intake", label: "Intake", color: "#38bdf8" },
{ key: "in_approval", label: "Approval", color: "#fbbf24" },
{ key: "approved_contract", label: "Contract", color: "#a78bfa" },
{ key: "payment", label: "Payment", color: "#fb923c" },
{ key: "operations", label: "Operations", color: "#2dd4bf" },
{ key: "completed", label: "Completed", color: "#86efac" },
];
export interface BookingRequestsHeaderProps {
metrics?: BookingListSummaryMetrics;
tabs?: BookingListSummaryTabs;
loading?: boolean;
isFetching?: boolean;
onCreate: () => void;
onRefresh: () => void;
}
export function BookingRequestsHeader({
metrics,
tabs,
loading,
isFetching,
onCreate,
onRefresh,
}: BookingRequestsHeaderProps) {
const val = (n?: number) => (loading ? "—" : (n ?? 0));
return (
<Paper
radius="xl"
p="xl"
style={{
position: "relative",
overflow: "hidden",
background: HERO_GRADIENT,
boxShadow: freightBrand.shadow,
}}
>
{/* decorative glows */}
<Box
style={{
position: "absolute",
top: -100,
right: -60,
width: 300,
height: 300,
borderRadius: "50%",
background: "rgba(255,255,255,0.12)",
pointerEvents: "none",
}}
/>
<Box
style={{
position: "absolute",
bottom: -130,
right: 160,
width: 240,
height: 240,
borderRadius: "50%",
background: "rgba(255,255,255,0.06)",
pointerEvents: "none",
}}
/>
<Stack gap="lg" style={{ position: "relative" }}>
<Group justify="space-between" align="flex-start" wrap="wrap" gap="md">
<Group gap="md" align="center" wrap="nowrap">
<ThemeIcon size={56} radius="lg" variant="white" style={{ color: freightBrand.primary }}>
<Inbox size={28} />
</ThemeIcon>
<Stack gap={4}>
<Text size="xs" fw={700} c="rgba(255,255,255,0.8)" tt="uppercase" style={{ letterSpacing: 1 }}>
Operations
</Text>
<Title order={2} c="white" fw={700}>
Booking Requests
</Title>
<Text size="sm" c="rgba(255,255,255,0.85)" maw={520}>
Track every booking from submission through approval, payment, and
dispatch prioritize what needs action.
</Text>
</Stack>
</Group>
<Group gap="sm">
<Button
variant="white"
c="green.8"
radius="lg"
leftSection={<Plus size={18} />}
onClick={onCreate}
>
Create booking
</Button>
<Button
variant="light"
color="white"
radius="lg"
c="white"
leftSection={<RefreshCw size={16} />}
loading={isFetching}
onClick={onRefresh}
style={{ background: "rgba(255,255,255,0.15)" }}
>
Refresh
</Button>
</Group>
</Group>
<Group grow gap="md" align="stretch" wrap="wrap">
<HeroStat
icon={LayoutList}
label="In queue"
value={val(metrics?.inQueue)}
hint="Matching current filter"
/>
<HeroStat
icon={Clock}
label="Needs action"
value={val(metrics?.needsAction)}
hint="Submitted or pending"
ratio={metrics?.inQueue ? (metrics.needsAction ?? 0) / metrics.inQueue : 0}
ratioColor="#fbbf24"
/>
<HeroStat
icon={AlertTriangle}
label="Urgent"
value={val(metrics?.urgent)}
hint="High priority score"
ratio={metrics?.inQueue ? (metrics.urgent ?? 0) / metrics.inQueue : 0}
ratioColor="#fca5a5"
/>
<HeroStat
icon={CheckCircle2}
label="Completed"
value={val(tabs?.completed)}
hint="Fully executed"
/>
</Group>
{tabs ? <PipelineBar tabs={tabs} /> : null}
</Stack>
</Paper>
);
}
/** Compact ring gauge with the stat icon at its center. */
function MiniDonut({
pct,
color = "white",
children,
size = 52,
stroke = 5,
}: {
pct?: number | null;
color?: string;
children: ReactNode;
size?: number;
stroke?: number;
}) {
const radius = (size - stroke) / 2;
const circumference = 2 * Math.PI * radius;
const clamped =
pct != null ? Math.min(100, Math.max(0, Math.round(pct))) : null;
const dash = clamped != null ? (clamped / 100) * circumference : 0;
return (
<Box style={{ position: "relative", width: size, height: size, flexShrink: 0 }}>
<svg
width={size}
height={size}
style={{ transform: "rotate(-90deg)", display: "block" }}
>
<circle
cx={size / 2}
cy={size / 2}
r={radius}
fill="none"
stroke="rgba(255,255,255,0.18)"
strokeWidth={stroke}
/>
{clamped != null ? (
<circle
cx={size / 2}
cy={size / 2}
r={radius}
fill="none"
stroke={color}
strokeWidth={stroke}
strokeLinecap="round"
strokeDasharray={`${dash} ${circumference}`}
style={{ transition: "stroke-dasharray 400ms ease" }}
/>
) : null}
</svg>
<Box
style={{
position: "absolute",
inset: 0,
display: "flex",
alignItems: "center",
justifyContent: "center",
color: "white",
}}
>
{children}
</Box>
</Box>
);
}
function HeroStat({
icon: Icon,
label,
value,
hint,
ratio,
ratioColor = "white",
}: {
icon: LucideIcon;
label: string;
value: ReactNode;
hint?: string;
ratio?: number;
ratioColor?: string;
}) {
const pct = ratio != null ? Math.round(Math.min(1, Math.max(0, ratio)) * 100) : null;
return (
<Paper
p="md"
radius="lg"
style={{
flex: "1 1 180px",
minWidth: 160,
background: "rgba(255,255,255,0.12)",
border: "1px solid rgba(255,255,255,0.18)",
backdropFilter: "blur(6px)",
}}
>
<Group gap="md" wrap="nowrap" align="center">
<MiniDonut pct={pct} color={ratioColor}>
<Icon size={19} />
</MiniDonut>
<Stack gap={2} style={{ flex: 1, minWidth: 0 }}>
<Text size="xs" fw={600} tt="uppercase" c="rgba(255,255,255,0.78)" style={{ letterSpacing: 0.4 }}>
{label}
</Text>
<Text fw={700} size="28px" c="white" lh={1}>
{value}
</Text>
<Text size="xs" c="rgba(255,255,255,0.72)" truncate>
{pct != null ? `${pct}% of queue` : hint}
</Text>
</Stack>
</Group>
</Paper>
);
}
function PipelineBar({ tabs }: { tabs: BookingListSummaryTabs }) {
const segments = PIPELINE_STAGES.map((s) => ({ ...s, count: tabs[s.key] ?? 0 }));
const total = segments.reduce((sum, s) => sum + s.count, 0);
return (
<Paper
p="md"
radius="lg"
style={{
background: "rgba(255,255,255,0.12)",
border: "1px solid rgba(255,255,255,0.18)",
backdropFilter: "blur(6px)",
}}
>
<Group justify="space-between" mb={10}>
<Text size="sm" fw={700} c="white">
Booking pipeline
</Text>
<Text size="xs" c="rgba(255,255,255,0.75)">
{total} active
</Text>
</Group>
<Box
style={{
display: "flex",
height: 14,
borderRadius: 999,
overflow: "hidden",
background: "rgba(255,255,255,0.18)",
gap: 2,
}}
>
{total > 0 ? (
segments.map((s) =>
s.count > 0 ? (
<Box
key={s.key}
title={`${s.label}: ${s.count}`}
style={{
width: `${(s.count / total) * 100}%`,
background: s.color,
transition: "width 200ms ease",
}}
/>
) : null,
)
) : (
<Box style={{ width: "100%" }} />
)}
</Box>
<Group gap="md" mt={10} wrap="wrap">
{segments.map((s) => (
<Group key={s.key} gap={6} wrap="nowrap">
<Box style={{ width: 9, height: 9, borderRadius: 3, background: s.color }} />
<Text size="xs" c="rgba(255,255,255,0.85)">
{s.label}
</Text>
<Text size="xs" fw={700} c="white">
{s.count}
</Text>
</Group>
))}
</Group>
</Paper>
);
}

View File

@@ -8,22 +8,23 @@ import {
Wallet,
XCircle,
} from "lucide-react";
import { Group, Badge, UnstyledButton, Text } from "@mantine/core";
import { Badge, Tabs } from "@mantine/core";
import {
BOOKING_LIST_TABS,
type BookingStatusTabKey,
} from "@/features/bookings/booking-status.config";
import "@/components/overview/overview.css";
const TAB_ICONS: Record<BookingStatusTabKey, React.ReactNode> = {
all: <LayoutGrid size={18} strokeWidth={1.75} />,
intake: <Inbox size={18} strokeWidth={1.75} />,
in_approval: <ClipboardCheck size={18} strokeWidth={1.75} />,
approved_contract: <FileSignature size={18} strokeWidth={1.75} />,
payment: <Wallet size={18} strokeWidth={1.75} />,
operations: <Train size={18} strokeWidth={1.75} />,
completed: <CheckCircle size={18} strokeWidth={1.75} />,
closed: <XCircle size={18} strokeWidth={1.75} />,
all: <LayoutGrid size={17} strokeWidth={1.85} />,
intake: <Inbox size={17} strokeWidth={1.85} />,
in_approval: <ClipboardCheck size={17} strokeWidth={1.85} />,
approved_contract: <FileSignature size={17} strokeWidth={1.85} />,
payment: <Wallet size={17} strokeWidth={1.85} />,
operations: <Train size={17} strokeWidth={1.85} />,
completed: <CheckCircle size={17} strokeWidth={1.85} />,
closed: <XCircle size={17} strokeWidth={1.85} />,
};
interface BookingStatusTabsProps {
@@ -38,74 +39,47 @@ export function BookingStatusTabs({
counts,
}: BookingStatusTabsProps) {
return (
<Group
gap="sm"
wrap="nowrap"
p="md"
style={{
background: "var(--mantine-color-gray-0)",
borderRadius: "12px",
border: "1px solid var(--mantine-color-gray-2)",
overflowX: "auto",
overflowY: "hidden",
WebkitOverflowScrolling: "touch",
scrollBehavior: "smooth",
scrollbarWidth: "thin",
}}
<Tabs
value={active}
onChange={(value) => onChange((value as BookingStatusTabKey) ?? "all")}
variant="pills"
color="green"
keepMounted={false}
classNames={{ list: "ov-tablist", tab: "ov-tab" }}
>
{BOOKING_LIST_TABS.map((tab) => {
const isActive = active === tab.key;
const count = counts?.[tab.key];
return (
<UnstyledButton
key={tab.key}
onClick={() => onChange(tab.key)}
style={{
flexShrink: 0,
background: isActive ? "white" : "transparent",
border: isActive ? "1px solid var(--freight-brand-border)" : "1px solid var(--mantine-color-gray-2)",
borderRadius: "10px",
padding: "10px 16px",
transition: "all 0.2s ease",
cursor: "pointer",
boxShadow: isActive ? "0 2px 8px rgb(21 128 61 / 0.12)" : "none",
}}
>
<Group gap="sm" justify="space-between" wrap="nowrap">
<Group gap={8}>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: "32px",
height: "32px",
borderRadius: "8px",
background: isActive ? "var(--freight-brand-muted)" : "var(--mantine-color-gray-1)",
color: isActive ? "var(--freight-brand-dark)" : "var(--mantine-color-gray-6)",
}}
>
{TAB_ICONS[tab.key]}
</div>
<Text size="sm" fw={600}>
{tab.label}
</Text>
</Group>
{count !== undefined && count > 0 && (
<Badge
size="sm"
variant={isActive ? "filled" : "light"}
color={isActive ? "green" : "gray"}
radius="lg"
>
{count}
</Badge>
)}
</Group>
</UnstyledButton>
);
})}
</Group>
<Tabs.List>
{BOOKING_LIST_TABS.map((tab) => {
const isActive = active === tab.key;
const count = counts?.[tab.key];
return (
<Tabs.Tab
key={tab.key}
value={tab.key}
leftSection={TAB_ICONS[tab.key]}
rightSection={
count !== undefined ? (
<Badge
size="sm"
radius="sm"
variant={isActive ? "white" : "light"}
color={isActive ? "green" : "gray"}
styles={
isActive
? { root: { background: "rgba(255,255,255,0.9)", color: "#15805f" } }
: undefined
}
>
{count}
</Badge>
) : undefined
}
>
{tab.label}
</Tabs.Tab>
);
})}
</Tabs.List>
</Tabs>
);
}

View File

@@ -0,0 +1,225 @@
import { useMemo, useState } from "react";
import { ArrowRight, Building2, Package } from "lucide-react";
import {
Accordion,
Badge,
Button,
Checkbox,
Group,
Paper,
Stack,
Text,
Title,
} from "@mantine/core";
import { BookingPriorityBadge } from "@/components/bookings/BookingPriorityBadge";
import { canAllocateBooking } from "@/features/bookings/booking-actions.config";
import type { BookingListRow } from "@/types/booking";
import { groupBookingsForOperationsQueue } from "@/utils/groupBookingsForOperationsQueue";
function BookingQueueRow({
booking,
selected,
disabled,
onToggle,
}: {
booking: BookingListRow;
selected: boolean;
disabled: boolean;
onToggle: () => void;
}) {
return (
<Group
align="flex-start"
wrap="nowrap"
p="sm"
style={{
border: "1px solid var(--mantine-color-gray-3)",
borderRadius: 8,
}}
>
<Checkbox checked={selected} disabled={disabled} onChange={onToggle} mt={4} />
<Stack gap={4} style={{ flex: 1 }}>
<Group gap="xs">
<Package size={14} />
<Text fw={600} size="sm">{booking.reference}</Text>
{booking.isGovernment ? (
<Badge color="violet" size="xs" leftSection={<Building2 size={10} />}>
Government
</Badge>
) : null}
<Badge variant="outline" size="xs">{booking.freightType}</Badge>
{booking.schedulingStatus ? (
<Badge variant="light" size="xs">{booking.schedulingStatus}</Badge>
) : null}
</Group>
<Text size="xs" c="dimmed">{booking.customerLabel}</Text>
<Group gap={6}>
<Text size="xs">{booking.originLabel}</Text>
<ArrowRight size={12} />
<Text size="xs">{booking.destinationLabel}</Text>
</Group>
<Group gap="sm">
<BookingPriorityBadge score={booking.priorityScore} />
{booking.serviceTypeLabel ? (
<Text size="xs" c="dimmed">
{booking.serviceTypeLabel}
{booking.serviceTypeBonus ? ` (+${booking.serviceTypeBonus} bonus)` : ""}
</Text>
) : null}
</Group>
</Stack>
</Group>
);
}
export function OperationsBookingQueue({
bookings,
isLoading,
onAllocate,
}: {
bookings: BookingListRow[];
isLoading?: boolean;
onAllocate: (bookingIds: string[]) => void;
}) {
const { government, commercial } = useMemo(
() => groupBookingsForOperationsQueue(bookings),
[bookings],
);
const [govSelected, setGovSelected] = useState<string[]>([]);
const [selectedByBucket, setSelectedByBucket] = useState<Record<string, string[]>>({});
const allocatable = (row: BookingListRow) =>
row.status === "PAID" &&
canAllocateBooking({ status: row.status, schedulingStatus: row.schedulingStatus });
const govSelection = govSelected.length
? govSelected
: government.filter(allocatable).map((b) => b.id);
const bucketSelection = (bucketKey: string, bucketBookings: BookingListRow[]) => {
const existing = selectedByBucket[bucketKey];
if (existing) return existing;
return bucketBookings.filter(allocatable).map((b) => b.id);
};
const toggleGov = (bookingId: string) => {
setGovSelected((prev) => {
const base = prev.length ? prev : government.filter(allocatable).map((b) => b.id);
return base.includes(bookingId)
? base.filter((id) => id !== bookingId)
: [...base, bookingId];
});
};
const toggleBucket = (bucketKey: string, bookingId: string) => {
setSelectedByBucket((prev) => {
const current = prev[bucketKey] ?? [];
const next = current.includes(bookingId)
? current.filter((id) => id !== bookingId)
: [...current, bookingId];
return { ...prev, [bucketKey]: next };
});
};
if (isLoading) {
return <Text size="sm" c="dimmed">Loading operations queue</Text>;
}
if (!government.length && !commercial.length) {
return (
<Text size="sm" c="dimmed">
No PAID bookings ready to allocate.
</Text>
);
}
return (
<Stack gap="lg">
{government.length > 0 ? (
<Paper withBorder p="md" radius="md">
<Group justify="space-between" mb="md">
<Stack gap={2}>
<Title order={5}>Government priority</Title>
<Text size="xs" c="dimmed">
Served first not grouped by 3-hour window
</Text>
</Stack>
<Group gap="xs">
<Badge variant="light">{govSelection.length} selected</Badge>
<Button
size="compact-sm"
color="violet"
disabled={!govSelection.length}
onClick={() => onAllocate(govSelection)}
>
Allocate
</Button>
</Group>
</Group>
<Stack gap="sm">
{government.map((booking) => (
<BookingQueueRow
key={booking.id}
booking={booking}
selected={govSelection.includes(booking.id)}
disabled={!allocatable(booking)}
onToggle={() => toggleGov(booking.id)}
/>
))}
</Stack>
</Paper>
) : null}
{commercial.length > 0 ? (
<Accordion defaultValue={commercial[0]?.key} variant="separated" radius="md">
{commercial.map((bucket) => {
const selected = bucketSelection(bucket.key, bucket.bookings);
return (
<Accordion.Item key={bucket.key} value={bucket.key}>
<Accordion.Control>
<Group justify="space-between" wrap="nowrap" pr="md">
<Stack gap={2}>
<Text fw={600} size="sm">{bucket.label}</Text>
<Text size="xs" c="dimmed">
{bucket.bookings.length} commercial booking
{bucket.bookings.length === 1 ? "" : "s"}
</Text>
</Stack>
<Group gap="xs">
<Badge variant="light">{selected.length} selected</Badge>
<Button
size="compact-sm"
color="green"
disabled={!selected.length}
onClick={(e) => {
e.stopPropagation();
onAllocate(selected);
}}
>
Allocate
</Button>
</Group>
</Group>
</Accordion.Control>
<Accordion.Panel>
<Stack gap="sm">
{bucket.bookings.map((booking) => (
<BookingQueueRow
key={booking.id}
booking={booking}
selected={selected.includes(booking.id)}
disabled={!allocatable(booking)}
onToggle={() => toggleBucket(bucket.key, booking.id)}
/>
))}
</Stack>
</Accordion.Panel>
</Accordion.Item>
);
})}
</Accordion>
) : null}
</Stack>
);
}

View File

@@ -0,0 +1,97 @@
import { Link } from "react-router-dom";
import { ArrowRight, ExternalLink } from "lucide-react";
import { Badge, Button, Group, Stack, Text } from "@mantine/core";
import { SchedulingStatusBadge } from "@/components/trainScheduling/ScheduleStatusBadge";
import type { BookingListRow } from "@/types/booking";
import { DataTable, type ColumnDef } from "@edr/ui-common";
export function OperationsScheduledBookings({
bookings,
isLoading,
}: {
bookings: BookingListRow[];
isLoading?: boolean;
}) {
const columns: ColumnDef<BookingListRow>[] = [
{
id: "reference",
header: "Booking",
cell: ({ row }) => (
<Stack gap={2}>
<Group gap={6}>
<Text fw={600} size="sm">{row.original.reference}</Text>
{row.original.isGovernment ? (
<Badge color="violet" size="xs">Government</Badge>
) : null}
</Group>
<Text size="xs" c="dimmed">{row.original.customerLabel}</Text>
</Stack>
),
},
{
id: "route",
header: "Route",
cell: ({ row }) => (
<Group gap={6}>
<Text size="sm">{row.original.originLabel}</Text>
<ArrowRight size={12} />
<Text size="sm">{row.original.destinationLabel}</Text>
</Group>
),
},
{
id: "scheduled",
header: "Scheduled",
cell: ({ row }) => (
<Text size="sm">{String(row.original.scheduledDate).slice(0, 16)}</Text>
),
},
{
id: "status",
header: "Scheduling",
cell: ({ row }) =>
row.original.schedulingStatus ? (
<SchedulingStatusBadge status={row.original.schedulingStatus} />
) : (
<Badge variant="light"></Badge>
),
},
{
id: "actions",
header: "",
cell: ({ row }) => (
<Group gap="xs">
<Button
component={Link}
to={`/dashboard/booking-requests/${row.original.id}`}
variant="light"
size="compact-sm"
>
View booking
</Button>
{row.original.trainScheduleId ? (
<Button
component={Link}
to={`/dashboard/operations/train-scheduling-v2/${row.original.trainScheduleId}`}
variant="subtle"
size="compact-sm"
leftSection={<ExternalLink size={14} />}
>
Train schedule
</Button>
) : null}
</Group>
),
},
];
return (
<DataTable
columns={columns}
data={bookings}
status={isLoading ? "loading" : "success"}
emptyMessage="No bookings currently assigned to a train schedule"
/>
);
}

View File

@@ -19,6 +19,7 @@ export function BookingApprovalCard({ steps, approvedCount }: BookingApprovalCar
<SectionCard
icon={CheckCircle}
title="Approval Workflow"
accent="green"
extra={
<Badge color="green" variant="light" radius="sm">
{approvedCount} / {steps.length} approved

View File

@@ -15,7 +15,7 @@ export function BookingCargoCard({ booking }: BookingCargoCardProps) {
const containers = booking.bookingContainers ?? [];
return (
<SectionCard icon={Package} title="Cargo specifications">
<SectionCard icon={Package} title="Cargo specifications" accent="orange">
<SimpleGrid cols={{ base: 1, sm: 3 }} spacing="sm">
<MetricTile
label="Cargo type"

View File

@@ -13,6 +13,7 @@ export function BookingContainersCard({ containers }: BookingContainersCardProps
<SectionCard
icon={Boxes}
title="Containers & Cargo"
accent="teal"
extra={
<Badge color="gray" variant="light" radius="sm">
{containers.length} line{containers.length === 1 ? "" : "s"}

View File

@@ -10,7 +10,7 @@ export interface BookingContractSummaryCardProps {
/** Generated contract terms, shown verbatim. */
export function BookingContractSummaryCard({ summary }: BookingContractSummaryCardProps) {
return (
<SectionCard icon={Anchor} title="Contract summary">
<SectionCard icon={Anchor} title="Contract summary" accent="teal">
<Code
block
style={{

View File

@@ -15,6 +15,7 @@ export function BookingDocumentsCard({ files, onDownload }: BookingDocumentsCard
<SectionCard
icon={FileText}
title="Documents"
accent="indigo"
extra={
<Badge color="gray" variant="light" radius="sm">
{files.length}

View File

@@ -43,7 +43,7 @@ export function BookingFactsCard({ booking }: BookingFactsCardProps) {
];
return (
<SectionCard icon={Hash} title="Booking Details">
<SectionCard icon={Hash} title="Booking Details" accent="cyan">
<Stack gap={0}>
{facts.map((fact, index) => (
<div key={fact.label}>

View File

@@ -17,7 +17,7 @@ export function BookingMileServicesCard({ booking }: BookingMileServicesCardProp
}
return (
<SectionCard icon={Truck} title="Mile services">
<SectionCard icon={Truck} title="Mile services" accent="grape">
<SimpleGrid cols={{ base: 1, md: 2 }} spacing="sm">
{booking.firstMilePickupAddress && (
<MetricTile label="First mile pickup" value={booking.firstMilePickupAddress} />

View File

@@ -1,12 +1,28 @@
import { Building2, Calendar, Clock, RefreshCw, ArrowLeft } from "lucide-react";
import { Paper, Group, Stack, Title, Text, Button, Box } from "@mantine/core";
import type { ReactNode } from "react";
import {
ArrowLeft,
Building2,
Calendar,
Clock,
Container as ContainerIcon,
Flame,
RefreshCw,
Wallet,
Weight,
} from "lucide-react";
import { Box, Button, Group, Paper, Stack, Text, Title } from "@mantine/core";
import type { LucideIcon } from "lucide-react";
import type { BookingDetail } from "@/types/booking";
import { BookingStatusBadge } from "@/components/bookings/BookingStatusBadge";
import { BookingPriorityBadge } from "@/components/bookings/BookingPriorityBadge";
import { SchedulingStatusBadge } from "@/components/trainScheduling/ScheduleStatusBadge";
import { NextStepBanner } from "@/components/bookings/NextStepBanner";
import { freightBrand } from "@/theme/freight-brand";
import { detailStyles, formatDate } from "./booking-detail.styles";
import { formatDate } from "./booking-detail.styles";
const HERO_GRADIENT = `linear-gradient(135deg, ${freightBrand.primaryDark} 0%, ${freightBrand.primary} 48%, ${freightBrand.primaryLight} 120%)`;
export interface BookingRequestHeroProps {
booking: BookingDetail;
@@ -16,7 +32,7 @@ export interface BookingRequestHeroProps {
isFetching?: boolean;
}
/** Top hero for the request detail page: identity, status, next step, total value. */
/** Top hero for the request detail page: identity, status, next step, key figures. */
export function BookingRequestHero({
booking,
customerLabel,
@@ -25,85 +41,198 @@ export function BookingRequestHero({
isFetching,
}: BookingRequestHeroProps) {
const amount = Number(booking.totalAmount);
const containers = booking.bookingContainers ?? [];
const containerCount = containers.reduce(
(sum, c) => sum + Number(c.quantity ?? 0),
0,
);
const weight = Number(booking.cargoTotalWeightVgm ?? 0);
return (
<Paper radius="md" withBorder p="xl" style={detailStyles.card}>
<Button
variant="subtle"
color="gray"
size="compact-sm"
leftSection={<ArrowLeft size={16} />}
onClick={onBack}
mb="md"
ml={-8}
fw={600}
>
Back to list
</Button>
<Paper
radius="xl"
p="xl"
style={{
position: "relative",
overflow: "hidden",
background: HERO_GRADIENT,
boxShadow: freightBrand.shadow,
}}
>
<Box
style={{
position: "absolute",
top: -110,
right: -50,
width: 300,
height: 300,
borderRadius: "50%",
background: "rgba(255,255,255,0.10)",
pointerEvents: "none",
}}
/>
<Group justify="space-between" align="flex-start" wrap="wrap" gap="lg">
<Stack gap="sm" style={{ flex: 1, minWidth: 0 }}>
<Text size="xs" c="dimmed" fw={600} tt="uppercase" lts="0.06em">
Booking reference
</Text>
<Group gap="sm" align="center" wrap="wrap">
<Title order={2} fw={700} style={{ letterSpacing: "-0.4px" }}>
{booking.reference}
</Title>
<BookingStatusBadge status={booking.status} />
<BookingPriorityBadge score={booking.priorityScore} />
</Group>
{booking.nextStep && (
<Box maw={520}>
<NextStepBanner nextStep={booking.nextStep} />
</Box>
)}
<Group gap="lg" mt={4}>
<Group gap={6} wrap="nowrap">
<Building2 size={14} color="var(--mantine-color-gray-5)" />
<Text size="sm" fw={500}>
{customerLabel}
</Text>
</Group>
<Group gap={6} wrap="nowrap">
<Calendar size={14} color="var(--mantine-color-gray-5)" />
<Text size="sm" c="dimmed">
Scheduled {booking.scheduledDate}
</Text>
</Group>
<Group gap={6} wrap="nowrap">
<Clock size={14} color="var(--mantine-color-gray-5)" />
<Text size="sm" c="dimmed">
Created {formatDate(booking.createdAt)}
</Text>
</Group>
</Group>
</Stack>
<Stack gap="sm" align="flex-end">
<Paper radius="md" withBorder p="md" miw={200} style={detailStyles.highlightCard}>
<Text size="xs" c="dimmed" fw={500} tt="uppercase" lts="0.04em" ta="right">
Total value
</Text>
<Text size="xl" fw={700} c="green.9" ta="right" mt={4} style={{ fontVariantNumeric: "tabular-nums" }}>
{booking.paymentCurrency}{" "}
{amount.toLocaleString(undefined, { minimumFractionDigits: 2 })}
</Text>
<Text size="xs" c="dimmed" ta="right" mt={2}>
{booking.paymentStatus}
</Text>
</Paper>
<Stack gap="lg" style={{ position: "relative" }}>
<Group justify="space-between" align="flex-start" wrap="wrap">
<Button
variant="default"
size="sm"
variant="white"
color="white"
c="white"
size="compact-sm"
radius="lg"
leftSection={<ArrowLeft size={16} />}
onClick={onBack}
style={{ background: "rgba(255,255,255,0.15)", border: "1px solid rgba(255,255,255,0.25)" }}
>
Back to list
</Button>
<Button
variant="white"
c="green.8"
size="compact-sm"
radius="lg"
leftSection={<RefreshCw size={15} />}
loading={isFetching}
onClick={onRefresh}
>
Refresh
</Button>
</Group>
<Group justify="space-between" align="flex-start" wrap="wrap" gap="lg">
<Stack gap="sm" style={{ flex: 1, minWidth: 0 }}>
<Text size="xs" c="rgba(255,255,255,0.78)" fw={700} tt="uppercase" style={{ letterSpacing: 1 }}>
Booking reference
</Text>
<Group gap="sm" align="center" wrap="wrap">
<Title order={2} c="white" fw={700} style={{ letterSpacing: "-0.4px" }}>
{booking.reference}
</Title>
<BookingStatusBadge status={booking.status} />
<BookingPriorityBadge score={booking.priorityScore} />
{booking.schedulingStatus ? (
<SchedulingStatusBadge status={booking.schedulingStatus} />
) : null}
</Group>
{booking.holdExpiresAt && booking.schedulingStatus === "HOLDING" ? (
<Text size="xs" c="rgba(255,255,255,0.85)">
Hold expires {new Date(booking.holdExpiresAt).toLocaleString()}
</Text>
) : null}
<Group gap="lg" mt={4}>
<MetaItem icon={Building2} text={customerLabel} strong />
<MetaItem icon={Calendar} text={`Scheduled ${booking.scheduledDate}`} />
<MetaItem icon={Clock} text={`Created ${formatDate(booking.createdAt)}`} />
</Group>
</Stack>
</Group>
{booking.nextStep ? (
<Paper radius="lg" p={4} style={{ background: "rgba(255,255,255,0.92)" }} maw={640}>
<NextStepBanner nextStep={booking.nextStep} />
</Paper>
) : null}
<Group grow gap="md" align="stretch" wrap="wrap">
<HeroTile
icon={Wallet}
label="Total value"
value={`${booking.paymentCurrency} ${amount.toLocaleString(undefined, {
minimumFractionDigits: 2,
})}`}
hint={booking.paymentStatus}
/>
<HeroTile icon={Weight} label="Cargo weight" value={`${weight} T`} hint="VGM total" />
<HeroTile
icon={ContainerIcon}
label="Containers"
value={containerCount || "—"}
hint={`${containers.length} line${containers.length === 1 ? "" : "s"}`}
/>
<HeroTile
icon={Flame}
label="Priority score"
value={booking.priorityScore ?? 0}
hint={booking.tradeDirection}
/>
</Group>
</Stack>
</Paper>
);
}
function MetaItem({
icon: Icon,
text,
strong,
}: {
icon: LucideIcon;
text: ReactNode;
strong?: boolean;
}) {
return (
<Group gap={6} wrap="nowrap">
<Icon size={14} color="rgba(255,255,255,0.8)" />
<Text size="sm" fw={strong ? 600 : 400} c={strong ? "white" : "rgba(255,255,255,0.85)"}>
{text}
</Text>
</Group>
);
}
function HeroTile({
icon: Icon,
label,
value,
hint,
}: {
icon: LucideIcon;
label: string;
value: ReactNode;
hint?: ReactNode;
}) {
return (
<Paper
p="md"
radius="lg"
style={{
flex: "1 1 160px",
minWidth: 150,
background: "rgba(255,255,255,0.12)",
border: "1px solid rgba(255,255,255,0.18)",
backdropFilter: "blur(6px)",
}}
>
<Group gap="sm" wrap="nowrap" align="flex-start">
<Box
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: 36,
height: 36,
borderRadius: 10,
background: "rgba(255,255,255,0.18)",
color: "white",
flexShrink: 0,
}}
>
<Icon size={18} />
</Box>
<Stack gap={2} style={{ minWidth: 0 }}>
<Text size="xs" fw={600} tt="uppercase" c="rgba(255,255,255,0.78)" style={{ letterSpacing: 0.4 }}>
{label}
</Text>
<Text fw={700} size="lg" c="white" lh={1.1} style={{ whiteSpace: "nowrap" }}>
{value}
</Text>
{hint ? (
<Text size="xs" c="rgba(255,255,255,0.7)" truncate>
{hint}
</Text>
) : null}
</Stack>
</Group>
</Paper>

View File

@@ -12,7 +12,7 @@ export interface BookingReviewNotesCardProps {
export function BookingReviewNotesCard({ notes }: BookingReviewNotesCardProps) {
if (notes.length === 0) {
return (
<SectionCard icon={MessageSquare} title="Review Notes">
<SectionCard icon={MessageSquare} title="Review Notes" accent="grape">
<Text size="sm" c="dimmed">
No review notes have been added yet.
</Text>

View File

@@ -10,7 +10,7 @@ export interface BookingRouteCardProps {
export function BookingRouteCard({ booking }: BookingRouteCardProps) {
return (
<SectionCard icon={MapPin} title="Shipment Route">
<SectionCard icon={MapPin} title="Shipment Route" accent="blue">
<Group justify="space-between" align="center" wrap="nowrap" gap="xl">
{/* Origin */}
<Stack gap={2} style={{ flex: 1 }}>

View File

@@ -63,7 +63,7 @@ export function BookingRouteServiceCard({
];
return (
<SectionCard icon={Train} title="Route & service">
<SectionCard icon={Train} title="Route & service" accent="blue">
<Group justify="space-between" align="center" wrap="nowrap" gap="md">
<Endpoint label="Origin" station={originLabel} />
<Stack gap={6} align="center" style={{ flexShrink: 0 }}>

View File

@@ -7,20 +7,68 @@ import { detailStyles } from "./booking-detail.styles";
export interface SectionCardProps {
icon: LucideIcon;
title: string;
/** Optional one-line context shown under the title. */
subtitle?: string;
/** Mantine palette key used to tint the icon chip + top accent (default green). */
accent?: string;
extra?: ReactNode;
children: ReactNode;
}
/** Consistent flat card with a minimal icon + title header used by every detail section. */
export function SectionCard({ icon: Icon, title, extra, children }: SectionCardProps) {
/** Consistent card with a colored icon chip + accent stripe header used by every detail section. */
export function SectionCard({
icon: Icon,
title,
subtitle,
accent = "green",
extra,
children,
}: SectionCardProps) {
return (
<Paper radius="md" withBorder style={detailStyles.card}>
<Group justify="space-between" px="xl" py="md" style={detailStyles.cardHeader}>
<Group gap="sm">
<Icon size={16} color="var(--mantine-color-gray-6)" />
<Text fw={600} size="sm" c="dark">
{title}
</Text>
<Paper radius="md" withBorder style={{ ...detailStyles.card, overflow: "hidden" }}>
<Box
style={{
height: 3,
background: `linear-gradient(90deg, var(--mantine-color-${accent}-5) 0%, var(--mantine-color-${accent}-7) 100%)`,
}}
/>
<Group
justify="space-between"
px="xl"
py="md"
wrap="nowrap"
style={{
...detailStyles.cardHeader,
background: `linear-gradient(180deg, var(--mantine-color-${accent}-0) 0%, white 100%)`,
}}
>
<Group gap="sm" wrap="nowrap" style={{ minWidth: 0 }}>
<Box
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: 34,
height: 34,
borderRadius: 10,
flexShrink: 0,
background: `var(--mantine-color-${accent}-1)`,
color: `var(--mantine-color-${accent}-7)`,
border: `1px solid var(--mantine-color-${accent}-2)`,
}}
>
<Icon size={17} strokeWidth={2} />
</Box>
<Box style={{ minWidth: 0 }}>
<Text fw={600} size="sm" c="dark" truncate>
{title}
</Text>
{subtitle ? (
<Text size="xs" c="dimmed" truncate>
{subtitle}
</Text>
) : null}
</Box>
</Group>
{extra}
</Group>

View File

@@ -1,47 +0,0 @@
import { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@edr/ui-common';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useContainers, useAssignContainerToWagon } from './use-containers';
import { useToast } from '@/hooks/use-toast';
import { Plus } from 'lucide-react';
export function AssignContainerDialog({ wagonId }: { wagonId: string }) {
const [open, setOpen] = useState(false);
const [containerId, setContainerId] = useState('');
const [position, setPosition] = useState<number>();
const { data: containers } = useContainers();
const assign = useAssignContainerToWagon();
const { toast } = useToast();
const available = containers?.filter(c => c.status === 'AVAILABLE' && !c.wagonId);
const handleAssign = async () => {
if (!containerId) return;
await assign.mutateAsync({ containerId, wagonId, position });
toast({ title: 'Assigned', description: 'Container placed on wagon.' });
setOpen(false);
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild><Button size="sm"><Plus className="mr-2 h-4 w-4" />Assign Container</Button></DialogTrigger>
<DialogContent>
<DialogHeader><DialogTitle>Assign Container to Wagon</DialogTitle></DialogHeader>
<div className="space-y-4">
<div><Label>Container</Label><Select value={containerId} onValueChange={setContainerId}><SelectTrigger><SelectValue placeholder="Select container" /></SelectTrigger><SelectContent>{available?.map(c => <SelectItem key={c.id} value={c.id}>{c.containerNumber}</SelectItem>)}</SelectContent></Select></div>
<div><Label>Position (optional)</Label><Input type="number" value={position ?? ''} onChange={e => setPosition(parseInt(e.target.value) || undefined)} /></div>
<Button onClick={handleAssign} disabled={assign.isPending}>Assign</Button>
</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,125 +0,0 @@
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@edr/ui-common';
import { Textarea } from '@/components/ui/textarea';
import { useCargoTypes } from './use-cargo-types';
import { useCargoMutations } from './use-cargoes';
import { Loader2 } from 'lucide-react';
interface Cargo {
id: string;
cargoNumber: string;
cargoTypeId: string;
weight: number;
remarks?: string;
}
interface CargoFormDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
cargo?: Cargo | null;
onSuccess?: () => void;
}
export default function CargoFormDialog({
open,
onOpenChange,
cargo,
onSuccess,
}: CargoFormDialogProps) {
const { data: cargoTypes } = useCargoTypes();
const { createCargo, updateCargo } = useCargoMutations();
const [formData, setFormData] = useState<Partial<Cargo>>({
cargoNumber: '',
cargoTypeId: '',
weight: 0,
remarks: '',
});
useEffect(() => {
if (cargo) {
setFormData(cargo);
} else {
setFormData({
cargoNumber: '',
cargoTypeId: '',
weight: 0,
remarks: '',
});
}
}, [cargo, open]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (cargo?.id) {
updateCargo.mutate(
{ id: cargo.id, data: formData },
{ onSuccess: () => { onOpenChange(false); onSuccess?.(); } }
);
} else {
createCargo.mutate(formData, {
onSuccess: () => { onOpenChange(false); onSuccess?.(); }
});
}
};
const isLoading = createCargo.isPending || updateCargo.isPending;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader><DialogTitle>{cargo ? 'Edit Cargo' : 'Create New Cargo'}</DialogTitle></DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<Label>Cargo Number *</Label>
<Input value={formData.cargoNumber} onChange={e => setFormData({...formData, cargoNumber: e.target.value})} required />
</div>
<div>
<Label>Cargo Type *</Label>
<Select
value={formData.cargoTypeId || ''}
onValueChange={(val) => setFormData({ ...formData, cargoTypeId: val })}
>
<SelectTrigger>
<SelectValue placeholder="Select cargo type..." />
</SelectTrigger>
<SelectContent>
{cargoTypes?.map((type: any) => (
<SelectItem key={type.id} value={type.id}>{type.cargo_type_name || type.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div>
<Label>Weight (kg) *</Label>
<Input type="number" value={formData.weight} onChange={e => setFormData({...formData, weight: parseFloat(e.target.value)})} required />
</div>
<div>
<Label>Remarks</Label>
<Textarea value={formData.remarks} onChange={e => setFormData({...formData, remarks: e.target.value})} rows={3} />
</div>
<DialogFooter>
<Button type="submit" disabled={isLoading}>{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}{cargo ? 'Update' : 'Create'}</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,246 +0,0 @@
import { useState, useEffect } from 'react';
import { toast } from 'sonner';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@edr/ui-common';
import { Textarea } from '@/components/ui/textarea';
import { useContainerTypes } from './use-container-types';
import { useContainerMutations } from './use-containers';
import { Loader2 } from 'lucide-react';
interface Container {
id: string;
containerNumber: string;
containerTypeId: string;
wagonId?: string;
status: 'AVAILABLE' | 'IN_USE' | 'MAINTENANCE' | 'RETIRED';
capacity: number;
weight: number;
remarks?: string;
}
interface Wagon {
id: string;
wagonNumber: string;
}
interface ContainerFormDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
container?: Container | null;
wagons: Wagon[];
onSuccess?: () => void;
}
export default function ContainerFormDialog({
open,
onOpenChange,
container,
wagons = [],
onSuccess,
}: ContainerFormDialogProps) {
const { data: containerTypes } = useContainerTypes();
const { createContainer, updateContainer } = useContainerMutations();
const [formData, setFormData] = useState<Partial<Container>>({
containerNumber: '',
containerTypeId: '',
status: 'AVAILABLE',
capacity: 0,
weight: 0,
remarks: '',
});
useEffect(() => {
if (container) {
setFormData(container);
} else {
setFormData({
containerNumber: '',
containerTypeId: '',
status: 'AVAILABLE',
capacity: 0,
weight: 0,
remarks: '',
});
}
}, [container, open]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!formData.containerNumber || !formData.containerTypeId) {
toast.error('Please fill in all required fields');
return;
}
if (container?.id) {
updateContainer.mutate(
{ id: container.id, data: formData },
{ onSuccess: () => { onOpenChange(false); onSuccess?.(); } }
);
} else {
createContainer.mutate(formData, {
onSuccess: () => { onOpenChange(false); onSuccess?.(); }
});
}
};
const isLoading = createContainer.isPending || updateContainer.isPending;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>
{container ? 'Edit Container' : 'Create New Container'}
</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-6">
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="containerNumber">Container Number *</Label>
<Input
id="containerNumber"
value={formData.containerNumber || ''}
onChange={(e) =>
setFormData({ ...formData, containerNumber: e.target.value })
}
placeholder="e.g., CNT001"
required
/>
</div>
<div>
<Label htmlFor="containerTypeId">Container Type *</Label>
<Select
value={formData.containerTypeId || ''}
onValueChange={(val:any) => setFormData({ ...formData, containerTypeId: val })}
>
<SelectTrigger id="containerTypeId">
<SelectValue placeholder="Select container type..." />
</SelectTrigger>
<SelectContent>
{containerTypes?.map((type: any) => (
<SelectItem key={type.id} value={type.id}>{type.name || type.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="wagonId">Wagon (Optional)</Label>
<Select
value={formData.wagonId || 'none'}
onValueChange={(val:any) => setFormData({ ...formData, wagonId: val === 'none' ? undefined : val })}
>
<SelectTrigger id="wagonId">
<SelectValue placeholder="Select a wagon..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">None</SelectItem>
{wagons.map((wagon) => (
<SelectItem key={wagon.id} value={wagon.id}>
{wagon.wagonNumber}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="status">Status</Label>
<Select
value={formData.status || 'AVAILABLE'}
onValueChange={(val:any) => setFormData({ ...formData, status: val })}
>
<SelectTrigger id="status">
<SelectValue placeholder="Select status" />
</SelectTrigger>
<SelectContent>
<SelectItem value="AVAILABLE">Available</SelectItem>
<SelectItem value="IN_USE">In Use</SelectItem>
<SelectItem value="MAINTENANCE">Maintenance</SelectItem>
<SelectItem value="RETIRED">Retired</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="capacity">Capacity *</Label>
<Input
id="capacity"
type="number"
value={formData.capacity || ''}
onChange={(e) =>
setFormData({
...formData,
capacity: parseFloat(e.target.value) || 0,
})
}
placeholder="0"
required
/>
</div>
<div>
<Label htmlFor="weight">Weight (kg)</Label>
<Input
id="weight"
type="number"
value={formData.weight || ''}
onChange={(e) =>
setFormData({
...formData,
weight: parseFloat(e.target.value) || 0,
})
}
placeholder="0"
/>
</div>
</div>
<div>
<Label htmlFor="remarks">Remarks</Label>
<Textarea
id="remarks"
value={formData.remarks || ''}
onChange={(e) =>
setFormData({ ...formData, remarks: e.target.value })
}
placeholder="Add any additional notes..."
rows={3}
/>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isLoading}
>
Cancel
</Button>
<Button type="submit" disabled={isLoading}>
{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{container ? 'Update' : 'Create'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,44 +0,0 @@
import { useContainersByWagon, useUnassignContainer } from './use-containers';
import { Button } from '@/components/ui/button';
import { Trash2 } from 'lucide-react';
import type { Container } from './container.service';
export function ContainersTable({ wagonId }: { wagonId: string }) {
const { data: containers, refetch } = useContainersByWagon(wagonId);
const unassign = useUnassignContainer();
if (!containers?.length) return <div className="text-muted-foreground">No containers assigned.</div>;
return (
<table className="w-full table-fixed">
<thead>
<tr>
<th className="text-left">Number</th>
<th className="text-left">Type</th>
<th className="text-left">Position</th>
<th className="text-left">Status</th>
<th className="text-left">Actions</th>
</tr>
</thead>
<tbody>
{containers.map((container: Container) => (
<tr key={container.id}>
<td className="py-2">{container.containerNumber}</td>
<td className="py-2">{container.containerTypeId}</td>
<td className="py-2">{container.position}</td>
<td className="py-2">{container.status}</td>
<td className="py-2">
<Button
variant="ghost"
size="icon"
onClick={() => unassign.mutateAsync(container.id).then(() => refetch())}
>
<Trash2 className="h-4 w-4" />
</Button>
</td>
</tr>
))}
</tbody>
</table>
);
}

View File

@@ -1,15 +0,0 @@
import { api } from '../../auth/http';
type ListResponse<T> = T[] | { data: T[] };
const asList = <T>(payload: ListResponse<T>): T[] =>
Array.isArray(payload) ? payload : payload.data;
export const cargoTypesService = {
async getCargoTypes() {
const response = await api.get<ListResponse<unknown>>('/cargo-types', {
params: { isActive: true, pageSize: 500 },
});
return asList(response.data);
},
};

View File

@@ -1,19 +0,0 @@
import { api } from "../../auth/http";
export const cargoService = {
async getCargoes() {
const response = await api.get('/cargoes');
return response.data;
},
async createCargo(data: any) {
const response = await api.post('/cargoes', data);
return response.data;
},
async updateCargo(id: string, data: any) {
const response = await api.patch(`/cargoes/${id}`, data);
return response.data;
},
async deleteCargo(id: string) {
await api.delete(`/cargoes/${id}`);
},
};

View File

@@ -1,15 +0,0 @@
import { api } from '../../auth/http';
type ListResponse<T> = T[] | { data: T[] };
const asList = <T>(payload: ListResponse<T>): T[] =>
Array.isArray(payload) ? payload : payload.data;
export const containerTypesService = {
async getContainerTypes() {
const response = await api.get<ListResponse<unknown>>('/container-types', {
params: { isActive: true, pageSize: 500 },
});
return asList(response.data);
},
};

View File

@@ -1,31 +0,0 @@
import { api } from "../../auth/http";
export const containerService = {
async getContainers() {
const response = await api.get('/containers');
return response.data;
},
async getContainersByWagon(wagonId: string) {
const response = await api.get('/containers', { params: { wagonId } });
return response.data;
},
async createContainer(data: any) {
const response = await api.post('/containers', data);
return response.data;
},
async updateContainer(id: string, data: any) {
const response = await api.patch(`/containers/${id}`, data);
return response.data;
},
async deleteContainer(id: string) {
await api.delete(`/containers/${id}`);
},
async assignToWagon(containerId: string, wagonId: string, position?: number) {
const response = await api.post(`/containers/${containerId}/assign-wagon`, { wagonId, position });
return response.data;
},
async unassignFromWagon(containerId: string) {
const response = await api.post(`/containers/${containerId}/unassign-wagon`);
return response.data;
},
};

View File

@@ -1,12 +0,0 @@
import { useQuery } from '@tanstack/react-query';
import { cargoTypesService } from './cargo-types.service';
export const CARGO_TYPES_QUERY_KEY = ['cargo-types'];
export function useCargoTypes() {
return useQuery({
queryKey: CARGO_TYPES_QUERY_KEY,
queryFn: () => cargoTypesService.getCargoTypes(),
staleTime: Infinity,
});
}

View File

@@ -1,42 +0,0 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { cargoService } from './cargo.service';
import { toast } from 'sonner';
export const CARGOES_QUERY_KEY = ['cargoes'];
export function useCargoes() {
return useQuery({
queryKey: CARGOES_QUERY_KEY,
queryFn: () => cargoService.getCargoes(),
});
}
export function useCargoMutations() {
const queryClient = useQueryClient();
const createCargo = useMutation({
mutationFn: (data: any) => cargoService.createCargo(data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: CARGOES_QUERY_KEY });
toast.success('Cargo created successfully');
},
});
const updateCargo = useMutation({
mutationFn: ({ id, data }: { id: string; data: any }) => cargoService.updateCargo(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: CARGOES_QUERY_KEY });
toast.success('Cargo updated successfully');
},
});
const deleteCargo = useMutation({
mutationFn: (id: string) => cargoService.deleteCargo(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: CARGOES_QUERY_KEY });
toast.success('Cargo deleted successfully');
},
});
return { createCargo, updateCargo, deleteCargo };
}

View File

@@ -1,12 +0,0 @@
import { useQuery } from '@tanstack/react-query';
import { containerTypesService } from './container-types.service';
export const CONTAINER_TYPES_QUERY_KEY = ['container-types'];
export function useContainerTypes() {
return useQuery({
queryKey: CONTAINER_TYPES_QUERY_KEY,
queryFn: () => containerTypesService.getContainerTypes(),
staleTime: Infinity,
});
}

View File

@@ -1,73 +0,0 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { containerService } from './container.service';
import { toast } from 'sonner';
export const CONTAINERS_QUERY_KEY = ['containers'];
export function useContainers() {
return useQuery({
queryKey: CONTAINERS_QUERY_KEY,
queryFn: () => containerService.getContainers(),
});
}
export function useContainersByWagon(wagonId: string) {
return useQuery({
queryKey: [...CONTAINERS_QUERY_KEY, 'wagon', wagonId],
queryFn: () => containerService.getContainersByWagon(wagonId),
enabled: !!wagonId,
});
}
export function useContainerMutations() {
const queryClient = useQueryClient();
const createContainer = useMutation({
mutationFn: (data: any) => containerService.createContainer(data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: CONTAINERS_QUERY_KEY });
toast.success('Container created successfully');
},
});
const updateContainer = useMutation({
mutationFn: ({ id, data }: { id: string; data: any }) => containerService.updateContainer(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: CONTAINERS_QUERY_KEY });
toast.success('Container updated successfully');
},
});
const deleteContainer = useMutation({
mutationFn: (id: string) => containerService.deleteContainer(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: CONTAINERS_QUERY_KEY });
toast.success('Container deleted successfully');
},
});
return { createContainer, updateContainer, deleteContainer };
}
export function useUnassignContainer() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: string) => containerService.unassignFromWagon(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: CONTAINERS_QUERY_KEY });
toast.success('Container unassigned from wagon');
},
});
}
export function useAssignContainerToWagon() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ containerId, wagonId, position }: { containerId: string; wagonId: string; position?: number }) =>
containerService.assignToWagon(containerId, wagonId, position),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: CONTAINERS_QUERY_KEY });
toast.success('Container assigned to wagon');
},
});
}

View File

@@ -1,12 +0,0 @@
import { useQuery } from '@tanstack/react-query';
import { wagonTypesService } from './wagon-types.service';
export const WAGON_TYPES_QUERY_KEY = ['wagon-types'];
export function useWagonTypes() {
return useQuery({
queryKey: WAGON_TYPES_QUERY_KEY,
queryFn: () => wagonTypesService.getWagonTypes(),
staleTime: Infinity,
});
}

View File

@@ -1,48 +0,0 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { wagonService } from './wagon.service';
import { toast } from 'sonner';
export const WAGONS_QUERY_KEY = ['wagons'];
export function useWagons() {
return useQuery({
queryKey: WAGONS_QUERY_KEY,
queryFn: () => wagonService.getWagons(),
});
}
export function useWagonMutations() {
const queryClient = useQueryClient();
const createWagon = useMutation({
mutationFn: (data: any) => wagonService.createWagon(data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: WAGONS_QUERY_KEY });
toast.success('Wagon created successfully');
},
onError: (error: any) => {
toast.error(error.response?.data?.message || 'Failed to create wagon');
},
});
const updateWagon = useMutation({
mutationFn: ({ id, data }: { id: string; data: any }) => wagonService.updateWagon(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: WAGONS_QUERY_KEY });
toast.success('Wagon updated successfully');
},
onError: (error: any) => {
toast.error(error.response?.data?.message || 'Failed to update wagon');
},
});
const deleteWagon = useMutation({
mutationFn: (id: string) => wagonService.delete(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: WAGONS_QUERY_KEY });
toast.success('Wagon deleted successfully');
},
});
return { createWagon, updateWagon, deleteWagon };
}

View File

@@ -1,13 +0,0 @@
import { api } from '../../auth/http';
type ListResponse<T> = T[] | { data: T[] };
const asList = <T>(payload: ListResponse<T>): T[] =>
Array.isArray(payload) ? payload : payload.data;
export const wagonTypesService = {
async getWagonTypes() {
const response = await api.get<ListResponse<unknown>>('/wagon-types');
return asList(response.data);
},
};

View File

@@ -1,23 +0,0 @@
import { api } from "../../auth/http";
export const wagonService = {
async getWagons() {
const response = await api.get('/wagons');
return response.data;
},
async getWagonById(id: string) {
const response = await api.get(`/wagons/${id}`);
return response.data;
},
async createWagon(data: any) {
const response = await api.post('/wagons', data);
return response.data;
},
async updateWagon(id: string, data: any) {
const response = await api.patch(`/wagons/${id}`, data);
return response.data;
},
async deleteWagon(id: string) {
await api.delete(`/wagons/${id}`);
},
};

View File

@@ -0,0 +1,182 @@
import type { OnChangeFn, PaginationState } from "@edr/ui-common";
import { Card, Group, SimpleGrid, Stack, Text } from "@mantine/core";
import { Badge } from "@mantine/core";
import type { FleetResourceConfig } from "@/pages/fleet/config/resources";
import type { FleetRecord } from "@/services/fleet/fleet.service";
import FleetRecordActions from "./FleetRecordActions";
import { cardInitials, resolveFleetCardPresentation } from "./fleetCardMeta";
import { formatFleetCell } from "./fleetFormat";
import RuleEngineListFooter from "../ruleEngine/RuleEngineListFooter";
export interface FleetCardGridProps {
config: FleetResourceConfig;
rows: FleetRecord[];
status: "loading" | "error" | "success";
emptyMessage: string;
pagination: PaginationState;
pageCount: number;
totalCount: number;
onPaginationChange: OnChangeFn<PaginationState>;
onEdit: (record: FleetRecord) => void;
onRemove: (record: FleetRecord) => void;
}
const FleetCardGrid = ({
config,
rows,
status,
emptyMessage,
pagination,
pageCount,
totalCount,
onPaginationChange,
onEdit,
onRemove,
}: FleetCardGridProps) => {
const presentation = resolveFleetCardPresentation(config);
if (status === "loading") {
return (
<Text size="sm" c="dimmed" py="xl" ta="center">
Loading
</Text>
);
}
if (status === "error") {
return (
<Text size="sm" c="red" py="xl" ta="center">
Failed to load data
</Text>
);
}
if (!rows.length) {
return (
<Text size="sm" c="dimmed" py="xl" ta="center">
{emptyMessage}
</Text>
);
}
return (
<Stack gap={0}>
<SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="md" p="md">
{rows.map((record) => {
const title = String(
(record as unknown as Record<string, unknown>)[presentation.titleKey] ?? config.entityLabel,
);
const code = presentation.codeKey
? (record as unknown as Record<string, unknown>)[presentation.codeKey]
: null;
const subtitle = presentation.subtitleKey
? (record as unknown as Record<string, unknown>)[presentation.subtitleKey]
: null;
const statusValue = presentation.statusKey
? (record as unknown as Record<string, unknown>)[presentation.statusKey]
: null;
return (
<Card
key={String((record as { id: string }).id)}
radius="lg"
padding="lg"
withBorder
style={{ borderColor: "var(--mantine-color-gray-2)" }}
>
<Stack gap="md">
<Group justify="space-between" align="flex-start" wrap="nowrap">
<Group gap="sm" wrap="nowrap">
<div
style={{
width: 40,
height: 40,
borderRadius: 10,
background: "var(--mantine-color-green-0)",
color: "var(--mantine-color-green-7)",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontWeight: 700,
fontSize: 14,
}}
>
{cardInitials(title)}
</div>
<Stack gap={2}>
<Text fw={600} size="sm" lineClamp={1}>
{title || "—"}
</Text>
{subtitle != null && subtitle !== "" ? (
<Text size="xs" c="dimmed" lineClamp={1}>
{String(subtitle)}
</Text>
) : null}
</Stack>
</Group>
{code != null && code !== "" ? (
<Badge variant="light" color="blue" size="sm" radius="md">
{String(code)}
</Badge>
) : null}
</Group>
<Stack gap={6}>
{config.columns
.filter(
(col) =>
col.accessorKey !== presentation.titleKey &&
col.accessorKey !== presentation.codeKey &&
col.accessorKey !== presentation.statusKey,
)
.slice(0, 4)
.map((col) => (
<Group key={col.id} justify="space-between" gap="xs">
<Text size="xs" c="dimmed">
{col.header}
</Text>
<Text size="xs" fw={500}>
{formatFleetCell(
(record as unknown as Record<string, unknown>)[col.accessorKey],
col.format,
col.accessorKey,
)}
</Text>
</Group>
))}
{statusValue != null ? (
<Group justify="space-between" gap="xs">
<Text size="xs" c="dimmed">
Status
</Text>
{formatFleetCell(statusValue, "statusBadge")}
</Group>
) : null}
</Stack>
<FleetRecordActions
record={record}
config={config}
layout="compact"
onEdit={onEdit}
onRemove={onRemove}
/>
</Stack>
</Card>
);
})}
</SimpleGrid>
<RuleEngineListFooter
pagination={pagination}
pageCount={pageCount}
totalCount={totalCount}
itemLabel={config.entityLabel.toLowerCase() + "s"}
onPaginationChange={onPaginationChange}
/>
</Stack>
);
};
export default FleetCardGrid;

View File

@@ -0,0 +1,201 @@
import { useEffect, useMemo, useState } from "react";
import { Loader2 } from "lucide-react";
import {
Button,
Group,
Modal,
NumberInput,
Select,
SimpleGrid,
Stack,
Text,
Textarea,
TextInput,
} from "@mantine/core";
import { FLEET_SELECT_NONE, type FleetFormFieldDef } from "@/pages/fleet/config/resources";
import type { FleetRecord } from "@/services/fleet/fleet.service";
export interface FleetFormDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
fields: FleetFormFieldDef[];
initialRecord?: FleetRecord | null;
emptyValues: Record<string, unknown>;
isSubmitting: boolean;
selectOptionsLoading?: boolean;
onSubmit: (values: Record<string, unknown>) => void;
}
const buildInitialValues = (
fields: FleetFormFieldDef[],
emptyValues: Record<string, unknown>,
record?: FleetRecord | null,
): Record<string, unknown> => {
const values: Record<string, unknown> = { ...emptyValues };
if (!record) return values;
fields.forEach((field) => {
const raw = (record as unknown as Record<string, unknown>)[field.name];
if (raw === null || raw === undefined) {
values[field.name] = field.noneOption ? FLEET_SELECT_NONE : "";
return;
}
values[field.name] = raw;
});
return values;
};
const FleetFormDialog = ({
open,
onOpenChange,
title,
fields,
initialRecord,
emptyValues,
isSubmitting,
selectOptionsLoading,
onSubmit,
}: FleetFormDialogProps) => {
const [values, setValues] = useState<Record<string, unknown>>({});
const [errors, setErrors] = useState<Record<string, string>>({});
useEffect(() => {
if (open) {
setValues(buildInitialValues(fields, emptyValues, initialRecord));
setErrors({});
}
}, [open, fields, emptyValues, initialRecord]);
const shortFields = useMemo(
() => fields.filter((f) => f.type !== "textarea"),
[fields],
);
const longFields = useMemo(
() => fields.filter((f) => f.type === "textarea"),
[fields],
);
const validate = () => {
const next: Record<string, string> = {};
fields.forEach((field) => {
const value = values[field.name];
const stringValue =
typeof value === "string" ? value.trim() : String(value ?? "");
if (field.required && (stringValue === "" || stringValue === FLEET_SELECT_NONE)) {
next[field.name] = `${field.label} is required`;
}
});
setErrors(next);
return Object.keys(next).length === 0;
};
const handleSubmit = () => {
if (!validate()) return;
const payload = Object.fromEntries(
Object.entries(values)
.map(([key, value]) => {
if (value === FLEET_SELECT_NONE || value === "") return [key, undefined];
return [key, value];
})
.filter(([, value]) => value !== undefined),
);
onSubmit(payload);
};
const renderField = (field: FleetFormFieldDef) => {
const value = values[field.name];
const error = errors[field.name];
if (field.type === "select") {
return (
<Select
key={field.name}
label={field.label}
data={field.options ?? []}
value={value == null || value === "" ? (field.noneOption ? FLEET_SELECT_NONE : null) : String(value)}
onChange={(next) =>
setValues((current) => ({ ...current, [field.name]: next ?? "" }))
}
error={error}
searchable
disabled={selectOptionsLoading}
rightSection={selectOptionsLoading ? <Loader2 size={14} className="animate-spin" /> : undefined}
/>
);
}
if (field.type === "number") {
return (
<NumberInput
key={field.name}
label={field.label}
value={value === "" || value == null ? "" : Number(value)}
onChange={(next) =>
setValues((current) => ({
...current,
[field.name]: next === "" ? "" : next,
}))
}
error={error}
/>
);
}
if (field.type === "textarea") {
return (
<Textarea
key={field.name}
label={field.label}
value={String(value ?? "")}
onChange={(e) =>
setValues((current) => ({ ...current, [field.name]: e.currentTarget.value }))
}
error={error}
minRows={3}
/>
);
}
return (
<TextInput
key={field.name}
label={field.label}
value={String(value ?? "")}
onChange={(e) =>
setValues((current) => ({ ...current, [field.name]: e.currentTarget.value }))
}
error={error}
/>
);
};
return (
<Modal
opened={open}
onClose={() => onOpenChange(false)}
title={<Text fw={600}>{title}</Text>}
size="lg"
radius="lg"
centered
>
<Stack gap="md">
<SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
{shortFields.map(renderField)}
</SimpleGrid>
{longFields.map(renderField)}
<Group justify="flex-end" gap="sm" mt="sm">
<Button variant="default" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button color="green" loading={isSubmitting} onClick={handleSubmit}>
Save
</Button>
</Group>
</Stack>
</Modal>
);
};
export default FleetFormDialog;

View File

@@ -0,0 +1,101 @@
import { MoreHorizontal, Pencil, Trash2, Truck } from "lucide-react";
import { ActionIcon, Button, Group, Menu, Tooltip } from "@mantine/core";
import { useNavigate } from "react-router-dom";
import type { FleetResourceConfig } from "@/pages/fleet/config/resources";
import type { FleetRecord } from "@/services/fleet/fleet.service";
export interface FleetRecordActionsProps {
record: FleetRecord;
config: FleetResourceConfig;
onEdit: (record: FleetRecord) => void;
onRemove: (record: FleetRecord) => void;
layout?: "row" | "compact";
}
const FleetRecordActions = ({
record,
config,
onEdit,
onRemove,
layout = "row",
}: FleetRecordActionsProps) => {
const navigate = useNavigate();
const removeLabel = config.removeActionLabel ?? "Delete";
const showDetail = Boolean(config.detailPath && "id" in record);
const handleDetail = () => {
if (!config.detailPath || !("id" in record)) return;
navigate(config.detailPath.replace(":id", String(record.id)));
};
if (layout === "compact") {
return (
<Group gap={6} wrap="nowrap" justify="flex-end">
{showDetail ? (
<Button
variant="light"
color="green"
size="compact-sm"
radius="md"
onClick={handleDetail}
leftSection={<Truck size={14} />}
>
Manage wagons
</Button>
) : null}
<Button
variant="light"
color="gray"
size="compact-sm"
radius="md"
onClick={() => onEdit(record)}
leftSection={<Pencil size={14} />}
>
Edit
</Button>
<Button
variant="light"
color="red"
size="compact-sm"
radius="md"
onClick={() => onRemove(record)}
leftSection={<Trash2 size={14} />}
>
{removeLabel}
</Button>
</Group>
);
}
return (
<Group gap={4} wrap="nowrap" justify="flex-end">
{showDetail ? (
<Tooltip label="Manage wagons">
<ActionIcon variant="subtle" color="green" size="md" radius="md" onClick={handleDetail}>
<Truck size={16} />
</ActionIcon>
</Tooltip>
) : null}
<Tooltip label="Edit">
<ActionIcon variant="subtle" color="gray" size="md" radius="md" onClick={() => onEdit(record)}>
<Pencil size={16} />
</ActionIcon>
</Tooltip>
<Menu position="bottom-end" withinPortal>
<Menu.Target>
<ActionIcon variant="subtle" color="gray" size="md" radius="md">
<MoreHorizontal size={16} />
</ActionIcon>
</Menu.Target>
<Menu.Dropdown>
<Menu.Item color="red" leftSection={<Trash2 size={14} />} onClick={() => onRemove(record)}>
{removeLabel}
</Menu.Item>
</Menu.Dropdown>
</Menu>
</Group>
);
};
export default FleetRecordActions;

View File

@@ -0,0 +1,113 @@
import type { ReactNode } from "react";
import { LayoutGrid, Plus, Search, Table2 } from "lucide-react";
import { Box, Button, Group, SegmentedControl, TextInput } from "@mantine/core";
import type { FleetViewMode } from "./useFleetViewMode";
export interface FleetToolbarProps {
search?: string;
onSearchChange?: (value: string) => void;
searchPlaceholder?: string;
showSearch?: boolean;
onAdd?: () => void;
addLabel?: string;
viewMode: FleetViewMode;
onViewModeChange: (mode: FleetViewMode) => void;
/** Optional filters rendered beside search (status, freight type, etc.) */
filters?: ReactNode;
}
const FleetToolbar = ({
search = "",
onSearchChange,
searchPlaceholder = "Search…",
showSearch = true,
onAdd,
addLabel = "Add",
viewMode,
onViewModeChange,
filters,
}: FleetToolbarProps) => (
<Box w="100%">
<Group
gap="md"
justify="space-between"
align="center"
wrap="wrap"
style={{ width: "100%" }}
>
<Group
gap="sm"
align="center"
wrap="wrap"
style={{ flex: "1 1 280px", minWidth: 0 }}
>
{showSearch && onSearchChange ? (
<TextInput
placeholder={searchPlaceholder}
value={search}
onChange={(e) => onSearchChange(e.currentTarget.value)}
leftSection={<Search size={16} />}
size="sm"
radius="lg"
style={{ flex: "1 1 200px", minWidth: 180, maxWidth: 360 }}
styles={{ input: { borderColor: "var(--mantine-color-gray-3)" } }}
/>
) : null}
{filters ? (
<Group gap="sm" align="center" wrap="nowrap" style={{ flexShrink: 0 }}>
{filters}
</Group>
) : null}
</Group>
<Group gap="sm" align="center" wrap="nowrap" style={{ flexShrink: 0 }}>
<SegmentedControl
value={viewMode}
onChange={(value) => onViewModeChange(value as FleetViewMode)}
size="sm"
radius="lg"
color="green"
data={[
{
value: "table",
label: (
<Group gap={6} justify="center" wrap="nowrap">
<Table2 size={14} />
<span>Table</span>
</Group>
),
},
{
value: "cards",
label: (
<Group gap={6} justify="center" wrap="nowrap">
<LayoutGrid size={14} />
<span>Cards</span>
</Group>
),
},
]}
styles={{
root: { background: "var(--mantine-color-gray-1)" },
}}
/>
{onAdd ? (
<Button
color="green"
radius="lg"
size="sm"
fw={600}
leftSection={<Plus size={16} />}
onClick={onAdd}
style={{ whiteSpace: "nowrap" }}
>
{addLabel}
</Button>
) : null}
</Group>
</Group>
</Box>
);
export default FleetToolbar;

View File

@@ -0,0 +1,39 @@
import type { FleetResourceConfig } from "@/pages/fleet/config/resources";
export interface FleetCardPresentation {
titleKey: string;
subtitleKey?: string;
codeKey?: string;
statusKey?: string;
}
export const resolveFleetCardPresentation = (config: FleetResourceConfig): FleetCardPresentation => {
const titleKey =
config.cardTitleKey ??
config.columns.find((col) => col.format !== "code" && col.accessorKey !== "status")
?.accessorKey ??
"id";
const codeKey =
config.cardCodeKey ?? config.columns.find((col) => col.format === "code")?.accessorKey;
const statusKey = config.columns.find((col) => col.format === "statusBadge")?.accessorKey;
const subtitleKey =
config.cardSubtitleKey ??
config.columns.find(
(col) =>
col.accessorKey !== titleKey &&
col.accessorKey !== codeKey &&
col.accessorKey !== statusKey,
)?.accessorKey;
return { titleKey, subtitleKey, codeKey, statusKey };
};
export const cardInitials = (title: string) => {
const parts = title.trim().split(/\s+/).filter(Boolean);
if (!parts.length) return "?";
if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
return `${parts[0][0] ?? ""}${parts[1][0] ?? ""}`.toUpperCase();
};

View File

@@ -0,0 +1,40 @@
import type { ReactNode } from "react";
import { Badge, Text } from "@mantine/core";
import type { ColumnFormat } from "@/pages/ruleEngine/config/resources";
import { formatCell as formatRuleEngineCell } from "@/components/ruleEngine/ruleEngineFormat";
export type FleetColumnFormat = ColumnFormat | "statusBadge";
const optionLabelMap = new Map<string, Map<string, string>>();
export const registerFleetOptionLabels = (
fieldKey: string,
options: { value: string; label: string }[],
) => {
optionLabelMap.set(fieldKey, new Map(options.map((o) => [o.value, o.label])));
};
export const formatFleetCell = (
value: unknown,
format?: FleetColumnFormat,
accessorKey?: string,
): ReactNode => {
if (format === "statusBadge") {
const status = value == null || value === "" ? "—" : String(value);
return (
<Badge variant="light" color="gray" size="sm" radius="md">
{status}
</Badge>
);
}
if (accessorKey && optionLabelMap.has(accessorKey)) {
const label = optionLabelMap.get(accessorKey)?.get(String(value ?? ""));
if (label) {
return <Text size="sm">{label}</Text>;
}
}
return formatRuleEngineCell(value, format as ColumnFormat | undefined);
};

View File

@@ -0,0 +1,40 @@
import { useCallback, useEffect, useState } from "react";
import type { FleetResourceSlug } from "@/pages/fleet/config/resources";
export type FleetViewMode = "table" | "cards";
const STORAGE_PREFIX = "edr-freight-fleet-view:";
type ViewModeSlug = FleetResourceSlug | "routes" | "train-scheduling-v2";
const readStored = (slug: ViewModeSlug): FleetViewMode => {
try {
const raw = localStorage.getItem(`${STORAGE_PREFIX}${slug}`);
return raw === "cards" ? "cards" : "table";
} catch {
return "table";
}
};
export const useFleetViewMode = (slug: ViewModeSlug) => {
const [viewMode, setViewModeState] = useState<FleetViewMode>(() => readStored(slug));
useEffect(() => {
setViewModeState(readStored(slug));
}, [slug]);
const setViewMode = useCallback(
(mode: FleetViewMode) => {
setViewModeState(mode);
try {
localStorage.setItem(`${STORAGE_PREFIX}${slug}`, mode);
} catch {
/* ignore */
}
},
[slug],
);
return { viewMode, setViewMode };
};

View File

@@ -0,0 +1,126 @@
/* ============================================================
EDR Freight — Header styles
============================================================ */
.fdh-root {
display: flex;
height: 80px;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 0 22px;
}
/* eyebrow above the page title */
.fdh-eyebrow {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.6px;
text-transform: uppercase;
color: #1B9E7A;
margin-bottom: 3px;
}
.fdh-eyebrow-dot {
width: 5px;
height: 5px;
border-radius: 50%;
background: #2DBF95;
box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.16);
}
/* action icon buttons */
.fdh-icon-btn {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
border-radius: 12px;
background: #f7f9fb;
border: 1px solid #eef1f4;
color: #475569;
cursor: pointer;
transition: all 160ms ease;
}
.fdh-icon-btn:hover {
background: #ffffff;
border-color: rgba(27, 158, 122, 0.28);
color: #1B9E7A;
box-shadow: 0 4px 12px -4px rgba(27, 158, 122, 0.28);
transform: translateY(-1px);
}
.fdh-icon-btn:active {
transform: translateY(0);
}
/* notification badge */
.fdh-badge {
position: absolute;
top: -5px;
right: -5px;
min-width: 17px;
height: 17px;
padding: 0 4px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 9px;
background: linear-gradient(135deg, #f87171 0%, #ef4444 100%);
color: #ffffff;
font-size: 10px;
font-weight: 700;
line-height: 1;
border: 2px solid #ffffff;
box-shadow: 0 2px 6px -1px rgba(239, 68, 68, 0.45);
}
.fdh-divider {
width: 1px;
height: 30px;
background: #e9eef3;
margin: 0 2px;
}
/* user button */
.fdh-user {
display: flex;
align-items: center;
gap: 10px;
padding: 5px 12px 5px 5px;
border-radius: 13px;
cursor: pointer;
border: 1px solid transparent;
transition: all 160ms ease;
}
.fdh-user:hover {
background: #f7f9fb;
border-color: #eef1f4;
}
.fdh-avatar-ring {
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
padding: 2px;
background: linear-gradient(135deg, #2DBF95 0%, #1B9E7A 100%);
box-shadow: 0 4px 10px -3px rgba(27, 158, 122, 0.4);
}
.fdh-avatar {
display: flex;
align-items: center;
justify-content: center;
width: 34px;
height: 34px;
border-radius: 50%;
background: linear-gradient(135deg, #1B9E7A 0%, #15805F 100%);
color: #ffffff;
font-size: 13px;
font-weight: 700;
letter-spacing: 0.3px;
border: 2px solid #ffffff;
}

View File

@@ -9,10 +9,10 @@ import {
Sun,
User,
} from "lucide-react";
import { Group, Stack, Text, Avatar, Menu, ActionIcon, Badge, Box } from "@mantine/core";
import { Group, Stack, Text, Menu, Tooltip, Box } from "@mantine/core";
import type { PageMeta } from "./types";
import { freightBrand } from "@/theme/freight-brand";
import "./FreightDashboardHeader.css";
export interface FreightDashboardHeaderProps {
pageMeta: PageMeta;
@@ -39,12 +39,13 @@ const FreightDashboardHeader = ({
}: FreightDashboardHeaderProps) => {
const initials =
userInitials ??
userName
(userName
.split(" ")
.filter(Boolean)
.slice(0, 2)
.map((n) => n[0].toUpperCase())
.join("");
.join("") ||
"U");
const [isUserMenuOpen, setIsUserMenuOpen] = useState(false);
const userMenuRef = useRef<HTMLDivElement | null>(null);
@@ -74,133 +75,137 @@ const FreightDashboardHeader = ({
}, [isUserMenuOpen]);
return (
<header
style={{
display: "flex",
height: "80px",
alignItems: "center",
justifyContent: "space-between",
gap: "16px",
padding: "0 24px",
// borderBottom: `3px solid ${freightBrand.primary}`,
}}
>
<Stack gap={2} style={{ flex: 1, minWidth: 0 }}>
<Text size="lg" fw={700} truncate style={{ color: freightBrand.primaryDark }}>
<header className="fdh-root">
<Stack gap={0} style={{ flex: 1, minWidth: 0 }}>
<span className="fdh-eyebrow">
<span className="fdh-eyebrow-dot" />
Freight Backoffice
</span>
<Text
fw={700}
truncate
style={{ fontSize: "20px", lineHeight: 1.2, color: "#0f172a", letterSpacing: "-0.4px" }}
>
{pageMeta.title}
</Text>
<Text size="sm" c="dimmed" truncate>
<Text size="sm" truncate style={{ color: "#94a3b8", lineHeight: 1.35 }}>
{pageMeta.subtitle}
</Text>
</Stack>
<Group gap="sm" wrap="nowrap">
<Group gap={10} wrap="nowrap">
{enableThemeToggle && (
<ActionIcon
variant="default"
size={40}
radius="lg"
onClick={onToggleTheme}
style={{
background: "var(--mantine-color-gray-1)",
border: "1px solid var(--mantine-color-gray-2)",
color: "var(--mantine-color-gray-7)",
}}
<Tooltip
label={theme === "dark" ? "Light mode" : "Dark mode"}
withArrow
openDelay={300}
>
{theme === "dark" ? <Sun size={18} /> : <Moon size={18} />}
</ActionIcon>
<button
type="button"
className="fdh-icon-btn"
onClick={onToggleTheme}
aria-label="Toggle theme"
>
{theme === "dark" ? <Sun size={18} /> : <Moon size={18} />}
</button>
</Tooltip>
)}
<ActionIcon
variant="default"
size={40}
radius="lg"
style={{
background: "var(--mantine-color-gray-1)",
border: "1px solid var(--mantine-color-gray-2)",
color: "var(--mantine-color-gray-7)",
}}
>
<Languages size={18} />
</ActionIcon>
<Tooltip label="Language" withArrow openDelay={300}>
<button type="button" className="fdh-icon-btn" aria-label="Language">
<Languages size={18} />
</button>
</Tooltip>
<ActionIcon
variant="default"
size={40}
radius="lg"
style={{
background: "var(--mantine-color-gray-1)",
border: "1px solid var(--mantine-color-gray-2)",
color: "var(--mantine-color-gray-7)",
position: "relative",
}}
>
<MessageSquare size={18} />
<Badge
size="xs"
color="red"
circle
style={{
position: "absolute",
top: "-3px",
right: "-3px",
}}
/>
</ActionIcon>
<Tooltip label="Messages" withArrow openDelay={300}>
<button type="button" className="fdh-icon-btn" aria-label="Messages">
<MessageSquare size={18} />
<span className="fdh-badge">3</span>
</button>
</Tooltip>
<ActionIcon
variant="default"
size={40}
radius="lg"
style={{
background: "var(--mantine-color-gray-1)",
border: "1px solid var(--mantine-color-gray-2)",
color: "var(--mantine-color-gray-7)",
position: "relative",
}}
>
<Bell size={18} />
<Badge
size="xs"
color="red"
circle
style={{
position: "absolute",
top: "-3px",
right: "-3px",
}}
/>
</ActionIcon>
<Tooltip label="Notifications" withArrow openDelay={300}>
<button
type="button"
className="fdh-icon-btn"
aria-label="Notifications"
>
<Bell size={18} />
<span className="fdh-badge">5</span>
</button>
</Tooltip>
<Menu position="bottom-end" shadow="md" opened={isUserMenuOpen} onOpen={() => setIsUserMenuOpen(true)} onClose={() => setIsUserMenuOpen(false)}>
<div className="fdh-divider" />
<Menu
position="bottom-end"
shadow="lg"
radius="md"
width={240}
opened={isUserMenuOpen}
onOpen={() => setIsUserMenuOpen(true)}
onClose={() => setIsUserMenuOpen(false)}
>
<Menu.Target>
<Group gap="sm" p="xs" style={{ cursor: "pointer", borderRadius: "12px" }}>
<Avatar name={initials} color="green" size="md" styles={{ root: { background: freightBrand.primary } }} />
<ChevronDown size={16} style={{ transition: "transform 0.2s", transform: isUserMenuOpen ? "rotate(180deg)" : "rotate(0deg)" }} />
</Group>
</Menu.Target>
<Menu.Dropdown>
<Menu.Item disabled>
<Stack gap={0}>
<Text size="sm" fw={600}>
<div className="fdh-user">
<div className="fdh-avatar-ring">
<div className="fdh-avatar">{initials}</div>
</div>
<Stack gap={0} style={{ minWidth: 0 }} visibleFrom="sm">
<Text
size="sm"
fw={600}
truncate
style={{ color: "#0f172a", lineHeight: 1.25, maxWidth: 140 }}
>
{userName}
</Text>
{userEmail && (
<Text size="xs" c="dimmed">
{userEmail}
</Text>
)}
<Text
size="xs"
truncate
style={{ color: "#94a3b8", lineHeight: 1.25, maxWidth: 140 }}
>
{userEmail ?? "Administrator"}
</Text>
</Stack>
</Menu.Item>
<ChevronDown
size={16}
style={{
color: "#94a3b8",
flexShrink: 0,
transition: "transform 0.2s",
transform: isUserMenuOpen ? "rotate(180deg)" : "rotate(0deg)",
}}
/>
</div>
</Menu.Target>
<Menu.Dropdown>
<Box px="sm" py="xs">
<Group gap={10} wrap="nowrap">
<div className="fdh-avatar-ring">
<div className="fdh-avatar">{initials}</div>
</div>
<Stack gap={0} style={{ minWidth: 0 }}>
<Text size="sm" fw={600} truncate style={{ color: "#0f172a" }}>
{userName}
</Text>
{userEmail && (
<Text size="xs" truncate style={{ color: "#94a3b8" }}>
{userEmail}
</Text>
)}
</Stack>
</Group>
</Box>
<Menu.Divider />
<Menu.Item
leftSection={<User size={14} />}
leftSection={<User size={15} />}
onClick={() => setIsUserMenuOpen(false)}
>
Profile
</Menu.Item>
<Menu.Item
leftSection={<LogOut size={14} />}
leftSection={<LogOut size={15} />}
color="red"
onClick={() => {
setIsUserMenuOpen(false);

View File

@@ -0,0 +1,304 @@
/* ============================================================
EDR Freight — Sidebar styles
Polished, professional navigation surface.
============================================================ */
.fsb-aside {
height: 100%;
max-height: 100%;
width: 280px;
flex-shrink: 0;
border-radius: 16px;
border: 1px solid #eef1f4;
background: #ffffff;
box-shadow:
0 1px 2px rgba(15, 23, 42, 0.04),
0 8px 24px -16px rgba(15, 23, 42, 0.12);
display: flex;
flex-direction: column;
overflow: hidden;
}
/* ---- Brand header ---- */
.fsb-brand {
position: relative;
display: flex;
align-items: center;
gap: 12px;
height: 80px;
padding: 0 20px;
flex-shrink: 0;
border-bottom: 1px solid #f1f5f9;
overflow: hidden;
}
.fsb-brand::after {
content: "";
position: absolute;
inset: 0;
background:
radial-gradient(120px 80px at 24px 18px, rgba(34, 197, 94, 0.08), transparent 70%);
pointer-events: none;
}
.fsb-logo {
position: relative;
z-index: 1;
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
border-radius: 13px;
background: linear-gradient(135deg, #2DBF95 0%, #1B9E7A 60%, #15805F 100%);
box-shadow:
0 6px 16px -4px rgba(27, 158, 122, 0.45),
inset 0 1px 0 rgba(255, 255, 255, 0.25);
flex-shrink: 0;
}
/* ---- Nav scroll region ---- */
.fsb-nav {
flex: 1;
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
padding: 14px 12px 12px;
display: flex;
flex-direction: column;
gap: 20px;
}
.fsb-nav::-webkit-scrollbar {
width: 6px;
}
.fsb-nav::-webkit-scrollbar-thumb {
background: #e2e8f0;
border-radius: 3px;
}
.fsb-nav::-webkit-scrollbar-thumb:hover {
background: #cbd5e1;
}
.fsb-nav::-webkit-scrollbar-track {
background: transparent;
}
.fsb-section-label {
font-size: 11px;
font-weight: 700;
letter-spacing: 0.7px;
text-transform: uppercase;
color: #94a3b8;
padding: 0 12px;
margin-bottom: 6px;
}
/* ---- Top-level item ---- */
.fsb-item {
position: relative;
display: flex;
align-items: center;
gap: 11px;
width: 100%;
padding: 9px 12px;
border-radius: 11px;
cursor: pointer;
color: #475569;
font-size: 14px;
font-weight: 500;
line-height: 1.2;
text-align: left;
text-decoration: none;
transition:
background-color 160ms ease,
color 160ms ease,
box-shadow 160ms ease;
}
.fsb-item:hover {
background-color: #f5f7fa;
color: #0f172a;
}
.fsb-item[data-active="true"] {
background: linear-gradient(
135deg,
rgba(34, 197, 94, 0.12) 0%,
rgba(27, 158, 122, 0.06) 100%
);
color: #1B9E7A;
font-weight: 600;
}
.fsb-item[data-active="true"]::before {
content: "";
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
width: 3px;
height: 22px;
border-radius: 0 4px 4px 0;
background: linear-gradient(180deg, #2DBF95 0%, #1B9E7A 100%);
}
.fsb-item-label {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* ---- Icon well ---- */
.fsb-icon {
display: flex;
align-items: center;
justify-content: center;
width: 31px;
height: 31px;
border-radius: 9px;
flex-shrink: 0;
background: #f1f5f9;
color: #64748b;
transition: all 160ms ease;
}
.fsb-item:hover .fsb-icon {
background: #e6ebf1;
color: #334155;
}
.fsb-item[data-active="true"] .fsb-icon {
background: linear-gradient(135deg, #2DBF95 0%, #1B9E7A 100%);
color: #ffffff;
box-shadow: 0 5px 12px -2px rgba(27, 158, 122, 0.45);
}
.fsb-chevron {
flex-shrink: 0;
color: #94a3b8;
transition: transform 220ms ease;
}
/* ---- Nested branch ---- */
.fsb-branch {
margin: 2px 0 2px 22px;
padding-left: 12px;
border-left: 1.5px solid #eef2f6;
display: flex;
flex-direction: column;
gap: 2px;
}
/* group header (non-navigable) */
.fsb-group {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
padding: 7px 10px;
border-radius: 8px;
cursor: pointer;
background: transparent;
transition: background-color 150ms ease;
}
.fsb-group:hover {
background-color: #f5f7fa;
}
.fsb-group-label {
font-size: 11px;
font-weight: 700;
letter-spacing: 0.4px;
text-transform: uppercase;
color: #94a3b8;
}
.fsb-group[data-active="true"] .fsb-group-label {
color: #1B9E7A;
}
/* child leaf */
.fsb-child {
position: relative;
display: flex;
align-items: center;
gap: 9px;
width: 100%;
padding: 7px 10px;
border-radius: 8px;
cursor: pointer;
color: #64748b;
font-size: 13px;
font-weight: 500;
text-decoration: none;
transition:
background-color 150ms ease,
color 150ms ease;
}
.fsb-child:hover {
background-color: #f5f7fa;
color: #0f172a;
}
.fsb-child[data-active="true"] {
color: #1B9E7A;
font-weight: 600;
background-color: rgba(27, 158, 122, 0.08);
}
.fsb-dot {
width: 6px;
height: 6px;
border-radius: 50%;
flex-shrink: 0;
background: #cbd5e1;
transition: all 150ms ease;
}
.fsb-child:hover .fsb-dot {
background: #94a3b8;
}
.fsb-child[data-active="true"] .fsb-dot {
background: #1B9E7A;
box-shadow: 0 0 0 3px rgba(27, 158, 122, 0.16);
}
/* ---- Footer status card ---- */
.fsb-footer {
flex-shrink: 0;
padding: 12px;
border-top: 1px solid #f1f5f9;
}
.fsb-status {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 12px;
border-radius: 11px;
background: linear-gradient(135deg, #E7F8F2 0%, #f8fafc 100%);
border: 1px solid #e7f3ec;
}
.fsb-pulse {
position: relative;
width: 9px;
height: 9px;
border-radius: 50%;
background: #2DBF95;
flex-shrink: 0;
}
.fsb-pulse::after {
content: "";
position: absolute;
inset: 0;
border-radius: 50%;
background: #2DBF95;
animation: fsb-pulse 2s ease-out infinite;
}
@keyframes fsb-pulse {
0% {
transform: scale(1);
opacity: 0.6;
}
100% {
transform: scale(2.6);
opacity: 0;
}
}

View File

@@ -1,15 +1,16 @@
import {
type MouseEvent,
type ReactNode,
useCallback,
useEffect,
useMemo,
useState,
} from "react";
import { ChevronDown, ChevronRight, Train } from "lucide-react";
import { Stack, Group, Text, Box, UnstyledButton, NavLink } from "@mantine/core";
import { ChevronDown, Train } from "lucide-react";
import { Box, Stack, Text } from "@mantine/core";
import type { SidebarItem, SidebarSection } from "./types";
import { freightBrand } from "@/theme/freight-brand";
import "./FreightSidebar.css";
export interface FreightSidebarProps {
sections: SidebarSection[];
@@ -105,7 +106,7 @@ const FreightSidebar = ({
children: SidebarItem[],
depth: number,
parentKey: string,
) =>
): ReactNode =>
children.map((child) => {
const key = sidebarItemKey(child, parentKey);
const isGroup = Boolean(child.children?.length) && !child.href;
@@ -115,87 +116,50 @@ const FreightSidebar = ({
const groupActive = branchContainsActive(child.children!);
return (
<Stack key={key} gap={4}>
<UnstyledButton
<div key={key}>
<button
type="button"
className="fsb-group"
data-active={groupActive}
onClick={() => toggleExpanded(key)}
style={{
background: groupActive ? freightBrand.mutedBg : "transparent",
padding: "8px 12px",
borderRadius: "8px",
width: "100%",
cursor: "pointer",
}}
>
<Group justify="space-between">
<Text size="xs" fw={600} style={{ color: groupActive ? freightBrand.primary : undefined }} c={groupActive ? undefined : "dimmed"} tt="uppercase">
{child.label}
</Text>
<ChevronDown
size={14}
style={{
transform: isOpen ? "rotate(0deg)" : "rotate(-90deg)",
transition: "transform 0.2s",
color: groupActive ? freightBrand.primary : "var(--mantine-color-gray-5)",
}}
/>
</Group>
</UnstyledButton>
<span className="fsb-group-label">{child.label}</span>
<ChevronDown
size={13}
className="fsb-chevron"
style={{
transform: isOpen ? "rotate(0deg)" : "rotate(-90deg)",
color: groupActive ? "#1B9E7A" : undefined,
}}
/>
</button>
{isOpen && (
<Stack gap={2} style={{ paddingLeft: "12px", borderLeft: `2px solid ${freightBrand.mutedBorder}` }}>
<div className="fsb-branch">
{renderNavBranch(child.children!, depth + 1, key)}
</Stack>
</div>
)}
</Stack>
</div>
);
}
if (!child.href) return null;
const childHref = child.href.toLowerCase();
const childActiveHref = isHrefActive(childHref);
const childActive = isHrefActive(child.href);
return (
<NavLink
<a
key={key}
component="a"
href={child.href}
onClick={(e) => navigateTo(e as any, child.href!)}
label={child.label}
active={childActiveHref}
color="green"
style={{
borderRadius: "8px",
cursor: "pointer",
fontSize: "14px",
}}
rightSection={<ChevronRight size={16} />}
/>
className="fsb-child"
data-active={childActive}
onClick={(e) => navigateTo(e, child.href!)}
>
<span className="fsb-dot" />
<span className="fsb-item-label">{child.label}</span>
</a>
);
});
const renderIconWell = (icon: React.ReactNode, active: boolean) => {
if (!icon) return null;
return (
<Box
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: "30px",
height: "30px",
borderRadius: "8px",
flexShrink: 0,
background: active ? freightBrand.gradient : "var(--mantine-color-gray-1)",
color: active ? "white" : "var(--mantine-color-gray-6)",
boxShadow: active ? freightBrand.shadowSm : "none",
transition: "all 0.2s ease",
}}
>
{icon}
</Box>
);
};
const renderTopLevelItem = (item: SidebarItem) => {
if (!item.href) return null;
@@ -207,132 +171,92 @@ const FreightSidebar = ({
const isCurrentItem = hasChildren
? activePath === itemHref
: isHrefActive(itemHref);
const isSectionActive = childActive && !isCurrentItem;
const isActive = isCurrentItem || isSectionActive;
const isActive = isCurrentItem || childActive;
const isOpen = expanded[item.href] ?? false;
const leafActive = isCurrentItem && !hasChildren;
return (
<Stack key={item.href} gap={0}>
<NavLink
component="a"
<Box key={item.href}>
<a
href={item.href}
onClick={(e) => navigateTo(e as any, item.href!)}
label={item.label}
leftSection={renderIconWell(item.icon, isActive)}
active={leafActive}
color="green"
variant="light"
style={{
borderRadius: "10px",
cursor: "pointer",
fontSize: "14px",
fontWeight: 500,
padding: "8px 10px",
}}
rightSection={
hasChildren ? (
<ChevronDown
size={16}
style={{
transform: isOpen ? "rotate(0deg)" : "rotate(-90deg)",
transition: "transform 0.2s",
}}
onClick={(e) => {
e.preventDefault();
toggleExpanded(item.href!);
}}
/>
) : (
<ChevronRight size={16} />
)
}
/>
className="fsb-item"
data-active={isActive}
onClick={(e) => 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)",
}}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
toggleExpanded(item.href!);
}}
/>
)}
</a>
{hasChildren && isOpen && (
<Stack gap={4} style={{ paddingLeft: "16px", borderLeft: `2px solid ${freightBrand.mutedBorder}` }}>
<div className="fsb-branch">
{renderNavBranch(item.children!, 0, item.href)}
</Stack>
</div>
)}
</Stack>
</Box>
);
};
return (
<Box
component="aside"
style={{
height: "100%",
maxHeight: "100%",
width: "280px",
flexShrink: 0,
borderRadius: "12px",
border: "1px solid var(--mantine-color-gray-2)",
background: "white",
boxShadow: "0 1px 3px rgba(0, 0, 0, 0.05)",
display: "flex",
flexDirection: "column",
overflow: "hidden",
}}
>
<Group
gap={12}
px="lg"
py="md"
style={{
borderBottom: "1px solid var(--mantine-color-gray-2)",
flexShrink: 0,
height: "80px",
}}
wrap="nowrap"
>
<Box
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: "44px",
height: "44px",
borderRadius: "12px",
background: freightBrand.gradient,
boxShadow: freightBrand.shadow,
flexShrink: 0,
}}
>
<Train size={24} color="white" strokeWidth={2} />
</Box>
<Stack gap={0} style={{ minWidth: 0 }}>
<Text size="md" fw={700} style={{ letterSpacing: "-0.3px", lineHeight: 1.2 }}>
<Box component="aside" className="fsb-aside">
<div className="fsb-brand">
<div className="fsb-logo">
<Train size={23} color="white" strokeWidth={2.1} />
</div>
<Stack gap={1} style={{ minWidth: 0, position: "relative", zIndex: 1 }}>
<Text
size="md"
fw={700}
style={{ letterSpacing: "-0.3px", lineHeight: 1.2, color: "#0f172a" }}
>
EDR Freight
</Text>
<Text size="xs" c="dimmed" fw={500} style={{ letterSpacing: "0.3px" }}>
Backoffice
<Text
size="xs"
fw={600}
style={{ letterSpacing: "0.4px", color: "#94a3b8" }}
>
Backoffice Console
</Text>
</Stack>
</Group>
</div>
<Stack
component="nav"
gap="lg"
p="md"
style={{
flex: 1,
minHeight: 0,
overflowY: "auto",
overscrollBehavior: "contain",
}}
>
<nav className="fsb-nav">
{sections.map((section) => (
<Stack key={section.title} gap={8}>
<Text size="xs" fw={600} c="dimmed" tt="uppercase" style={{ letterSpacing: "0.5px", paddingLeft: "8px" }}>
{section.title}
</Text>
<Stack gap={2}>
<div key={section.title}>
<div className="fsb-section-label">{section.title}</div>
<Stack gap={3}>
{section.items.map((item) => renderTopLevelItem(item))}
</Stack>
</Stack>
</div>
))}
</Stack>
</nav>
<div className="fsb-footer">
<div className="fsb-status">
<span className="fsb-pulse" />
<Stack gap={0} style={{ minWidth: 0 }}>
<Text size="xs" fw={600} style={{ color: "#15805F", lineHeight: 1.3 }}>
All systems operational
</Text>
<Text size="10px" style={{ color: "#94a3b8", lineHeight: 1.3 }}>
EDR Platform · v1.0
</Text>
</Stack>
</div>
</div>
</Box>
);
};

View File

@@ -1,4 +1,5 @@
import type { PageMeta } from "./types";
import { getFleetRouteMeta } from "@/pages/fleet/config/resources";
import {
RULE_ENGINE_CATEGORY_BASE_PATH,
RULE_ENGINE_RESOURCES,
@@ -35,6 +36,27 @@ const ROUTE_META: Array<{ prefix: string; meta: PageMeta }> = [
subtitle: "Dashboard summary and key metrics",
},
},
{
prefix: "/dashboard/operations/train-scheduling-v2/",
meta: {
title: "Train schedule",
subtitle: "Assign bookings, auto-pin wagons, finalize and dispatch",
},
},
{
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",
},
},
{
prefix: "/dashboard/routes",
meta: {
@@ -42,11 +64,12 @@ const ROUTE_META: Array<{ prefix: string; meta: PageMeta }> = [
subtitle: "Manage route definitions built from freight yards",
},
},
...getFleetRouteMeta(),
{
prefix: "/dashboard/locomotives",
prefix: "/dashboard/trains/",
meta: {
title: "Locomotives",
subtitle: "Manage locomotive master data and service status",
title: "Train detail",
subtitle: "Manage fleet consist and wagon assignments",
},
},
{
@@ -91,6 +114,13 @@ const ROUTE_META: Array<{ prefix: string; meta: PageMeta }> = [
subtitle: "Manage dropdown options used across the platform",
},
},
{
prefix: "/dashboard/configuration/train-scheduling-rules",
meta: {
title: "Train scheduling rules",
subtitle: "Global limits for train length, weight, wagons, and 20ft container balance",
},
},
{
prefix: RULE_ENGINE_CATEGORY_BASE_PATH.configuration,
meta: {

View File

@@ -0,0 +1,65 @@
import {
Area,
AreaChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { Paper, Stack, Text } from "@mantine/core";
import type { IOverviewTrendPoint } from "@/types/overview";
import { overviewChartColors } from "./overview.styles";
function formatDateLabel(date: string) {
const parsed = new Date(`${date}T00:00:00`);
return parsed.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}
export function OverviewBookingTrendChart({ data }: { data: IOverviewTrendPoint[] }) {
const hasData = data.some((point) => point.count > 0);
return (
<Paper p="lg" radius="lg" withBorder h="100%" style={{ minHeight: 320 }}>
<Stack gap="md" h="100%">
<Text fw={600}>Booking trend</Text>
{!hasData ? (
<Text size="sm" c="dimmed" ta="center" py="xl">
No bookings in this period
</Text>
) : (
<ResponsiveContainer width="100%" height={260}>
<AreaChart data={data} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
<defs>
<linearGradient id="bookingTrendFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={overviewChartColors.primary} stopOpacity={0.35} />
<stop offset="95%" stopColor={overviewChartColors.primary} stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis
dataKey="date"
tickFormatter={formatDateLabel}
tick={{ fontSize: 12 }}
stroke="#94a3b8"
/>
<YAxis allowDecimals={false} tick={{ fontSize: 12 }} stroke="#94a3b8" />
<Tooltip
labelFormatter={(value) => formatDateLabel(String(value))}
formatter={(value) => [value, "Bookings"]}
/>
<Area
type="monotone"
dataKey="count"
stroke={overviewChartColors.primary}
fill="url(#bookingTrendFill)"
strokeWidth={2}
/>
</AreaChart>
</ResponsiveContainer>
)}
</Stack>
</Paper>
);
}

View File

@@ -0,0 +1,70 @@
import {
Cell,
Pie,
PieChart,
ResponsiveContainer,
Tooltip,
} from "recharts";
import { Paper, Stack, Text } from "@mantine/core";
import { overviewChartColors } from "./overview.styles";
export interface DonutChartItem {
name: string;
value: number;
}
interface OverviewDonutChartProps {
title: string;
data: DonutChartItem[];
emptyMessage?: string;
}
export function OverviewDonutChart({
title,
data,
emptyMessage = "No data available",
}: OverviewDonutChartProps) {
const filtered = data.filter((item) => item.value > 0);
const hasData = filtered.length > 0;
return (
<Paper p="lg" radius="lg" withBorder h="100%" style={{ minHeight: 300 }}>
<Stack gap="md" h="100%">
<Text fw={600}>{title}</Text>
{!hasData ? (
<Text size="sm" c="dimmed" ta="center" py="xl">
{emptyMessage}
</Text>
) : (
<ResponsiveContainer width="100%" height={240}>
<PieChart>
<Pie
data={filtered}
dataKey="value"
nameKey="name"
cx="50%"
cy="50%"
innerRadius={55}
outerRadius={90}
paddingAngle={2}
>
{filtered.map((entry, index) => (
<Cell
key={entry.name}
fill={
overviewChartColors.pipeline[
index % overviewChartColors.pipeline.length
]
}
/>
))}
</Pie>
<Tooltip formatter={(value) => [value, "Count"]} />
</PieChart>
</ResponsiveContainer>
)}
</Stack>
</Paper>
);
}

View File

@@ -0,0 +1,81 @@
import {
Bar,
BarChart,
CartesianGrid,
Cell,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { Paper, Stack, Text } from "@mantine/core";
import { overviewChartColors } from "./overview.styles";
export interface HorizontalBarItem {
label: string;
value: number;
}
interface OverviewHorizontalBarChartProps {
title: string;
data: HorizontalBarItem[];
emptyMessage?: string;
valueLabel?: string;
}
export function OverviewHorizontalBarChart({
title,
data,
emptyMessage = "No data available",
valueLabel = "Count",
}: OverviewHorizontalBarChartProps) {
const chartData = data
.filter((item) => item.value > 0)
.map((item) => ({ name: item.label, value: item.value }));
const hasData = chartData.length > 0;
return (
<Paper p="lg" radius="lg" withBorder h="100%" style={{ minHeight: 300 }}>
<Stack gap="md" h="100%">
<Text fw={600}>{title}</Text>
{!hasData ? (
<Text size="sm" c="dimmed" ta="center" py="xl">
{emptyMessage}
</Text>
) : (
<ResponsiveContainer width="100%" height={Math.max(240, chartData.length * 36)}>
<BarChart
data={chartData}
layout="vertical"
margin={{ top: 4, right: 16, left: 8, bottom: 4 }}
>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" horizontal={false} />
<XAxis type="number" allowDecimals={false} tick={{ fontSize: 12 }} />
<YAxis
type="category"
dataKey="name"
width={120}
tick={{ fontSize: 11 }}
stroke="#94a3b8"
/>
<Tooltip formatter={(value) => [value, valueLabel]} />
<Bar dataKey="value" radius={[0, 6, 6, 0]} barSize={18}>
{chartData.map((entry, index) => (
<Cell
key={entry.name}
fill={
overviewChartColors.pipeline[
index % overviewChartColors.pipeline.length
]
}
/>
))}
</Bar>
</BarChart>
</ResponsiveContainer>
)}
</Stack>
</Paper>
);
}

View File

@@ -0,0 +1,155 @@
import type { LucideIcon } from "lucide-react";
import { Card, Group, Stack, Text } from "@mantine/core";
import {
overviewAccentGradients,
type OverviewAccent,
} from "./overview.styles";
/** Pale chip background per accent — matches the Pencil "tinted icon chip" look. */
const ACCENT_CHIP_BG: Record<string, string> = {
default: "#F1F5F4",
emerald: "#E7F8F2",
amber: "#FEF9C3",
rose: "#FFE4E6",
sky: "#E0F2FE",
violet: "#EDE9FE",
};
export interface OverviewKpiItem {
label: string;
value: number | string;
hint?: string;
icon: LucideIcon;
accent?: keyof typeof ACCENT_CHIP_BG;
/** Share 0..1 used as a baseline for the decorative trend sparkline. */
progress?: number;
}
/** Deterministic, gently-rising series seeded by the KPI label (purely decorative). */
function sparkHeights(seed: string, baseline: number, count = 9): number[] {
let h = 2166136261;
for (let i = 0; i < seed.length; i += 1) {
h ^= seed.charCodeAt(i);
h = Math.imul(h, 16777619) >>> 0;
}
const out: number[] = [];
let v = 0.35 + (baseline > 0 ? Math.min(0.35, baseline * 0.35) : 0.15);
for (let i = 0; i < count; i += 1) {
h = (Math.imul(h, 1103515245) + 12345) >>> 0;
const delta = ((h % 1000) / 1000 - 0.42) * 0.28;
v = Math.min(1, Math.max(0.22, v + delta));
out.push(v);
}
// Nudge the final bar up so the series reads as an upward trend.
out[out.length - 1] = Math.min(1, out[out.length - 1] + 0.15);
return out;
}
/** Compact bar sparkline; last bar highlighted in the accent colour. */
function KpiSparkline({
accent,
baseline,
seed,
}: {
accent: OverviewAccent;
baseline: number;
seed: string;
}) {
const [light, deep] = overviewAccentGradients[accent] ?? overviewAccentGradients.default;
const bars = sparkHeights(seed, baseline);
return (
<div
style={{
display: "flex",
alignItems: "flex-end",
gap: 4,
height: 38,
width: "100%",
}}
>
{bars.map((value, index) => (
<div
key={index}
style={{
flex: 1,
height: Math.round(8 + value * 30),
borderRadius: 3,
background: index === bars.length - 1 ? deep : light,
opacity: index === bars.length - 1 ? 1 : 0.55,
}}
/>
))}
</div>
);
}
export function OverviewKpiCard({ item }: { item: OverviewKpiItem }) {
const Icon = item.icon;
const accent = item.accent ?? "default";
const accentKey = accent as OverviewAccent;
const [, accentDeep] = overviewAccentGradients[accentKey] ?? overviewAccentGradients.default;
const chipBg = ACCENT_CHIP_BG[accent] ?? ACCENT_CHIP_BG.default;
return (
<Card
p="lg"
radius={16}
withBorder
style={{
background: "#ffffff",
border: "1px solid var(--mantine-color-gray-2)",
flex: "1 1 240px",
minWidth: 220,
transition: "transform 160ms ease, box-shadow 160ms ease",
}}
onMouseEnter={(e) => {
e.currentTarget.style.transform = "translateY(-3px)";
e.currentTarget.style.boxShadow = "0 12px 28px -12px rgba(15,23,42,0.18)";
}}
onMouseLeave={(e) => {
e.currentTarget.style.transform = "translateY(0)";
e.currentTarget.style.boxShadow = "none";
}}
>
<Stack gap={14}>
<Group justify="space-between" align="center" wrap="nowrap">
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: 38,
height: 38,
borderRadius: 11,
background: chipBg,
color: accentDeep,
flexShrink: 0,
}}
>
<Icon size={20} strokeWidth={2} />
</div>
</Group>
<Stack gap={3} style={{ minWidth: 0 }}>
<Text size="30px" fw={800} style={{ lineHeight: 1, letterSpacing: "-0.02em" }} truncate>
{item.value}
</Text>
<Group gap={6} wrap="nowrap">
<Text size="sm" fw={600} c="dimmed" truncate>
{item.label}
</Text>
{item.hint && (
<Text size="xs" c="dimmed" truncate>
· {item.hint}
</Text>
)}
</Group>
</Stack>
<KpiSparkline accent={accentKey} baseline={item.progress ?? 0} seed={item.label} />
</Stack>
</Card>
);
}

View File

@@ -0,0 +1,167 @@
import {
AlertCircle,
Banknote,
Box,
Clock,
Container,
CreditCard,
FileText,
Train,
Truck,
UserCheck,
Users,
Wallet,
} from "lucide-react";
import { Group, Paper, Stack, Text } from "@mantine/core";
import type { IOverviewKpis } from "@/types/overview";
import { OverviewKpiCard } from "./OverviewKpiCard";
function formatCurrency(amount: number, currency: "ETB" | "USD") {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency,
maximumFractionDigits: 0,
}).format(amount);
}
export function OverviewKpiSection({ kpis }: { kpis: IOverviewKpis }) {
const bookingItems = [
{
label: "Active bookings",
value: kpis.bookings.totalActive,
icon: FileText,
accent: "emerald" as const,
},
{
label: "Needs action",
value: kpis.bookings.needsAction,
icon: AlertCircle,
accent: "amber" as const,
},
{
label: "Urgent",
value: kpis.bookings.urgent,
icon: Clock,
accent: "rose" as const,
},
{
label: "In approval",
value: kpis.bookings.inApproval,
icon: UserCheck,
accent: "sky" as const,
},
{
label: "Submitted today",
value: kpis.bookings.submittedToday,
icon: FileText,
},
];
const operationsItems = [
{
label: "Active trains",
value: kpis.operations.trainsActive,
icon: Train,
accent: "emerald" as const,
},
{
label: "Wagons available",
value: kpis.operations.wagonsAvailable,
icon: Truck,
},
{
label: "Containers in transit",
value: kpis.operations.containersInTransit,
icon: Container,
},
{
label: "Cargoes loaded",
value: kpis.operations.cargoesLoaded,
icon: Box,
},
];
const billingItems = [
{
label: "Revenue MTD (ETB)",
value: formatCurrency(kpis.billing.revenueMtdEtb, "ETB"),
icon: Banknote,
accent: "emerald" as const,
},
{
label: "Revenue MTD (USD)",
value: formatCurrency(kpis.billing.revenueMtdUsd, "USD"),
icon: Wallet,
},
{
label: "Pending payments",
value: kpis.billing.pendingPayments,
icon: CreditCard,
accent: "amber" as const,
},
{
label: "Successful MTD",
value: kpis.billing.successfulPaymentsMtd,
icon: Banknote,
},
];
const peopleItems = [
{
label: "Total customers",
value: kpis.customers.totalCustomers,
icon: Users,
},
{
label: "New this month",
value: kpis.customers.newCustomersThisMonth,
icon: Users,
accent: "emerald" as const,
},
{
label: "Active employees",
value: kpis.staff.activeEmployees,
icon: UserCheck,
},
{
label: "Active users",
value: kpis.staff.activeUsers,
icon: Users,
},
];
const sections = [
{ title: "Bookings", items: bookingItems },
{ title: "Operations", items: operationsItems },
{ title: "Billing", items: billingItems },
{ title: "Customers & staff", items: peopleItems },
];
return (
<Stack gap="md">
{sections.map((section) => (
<Paper
key={section.title}
p="md"
radius="lg"
withBorder
style={{
background: "white",
border: "1px solid var(--mantine-color-gray-2)",
overflowX: "auto",
}}
>
<Text size="sm" fw={600} mb="sm" c="dimmed">
{section.title}
</Text>
<Group gap="md" style={{ flexWrap: "nowrap", minWidth: "min-content" }}>
{section.items.map((item) => (
<OverviewKpiCard key={item.label} item={item} />
))}
</Group>
</Paper>
))}
</Stack>
);
}

View File

@@ -0,0 +1,49 @@
import { Group, Paper, Text } from "@mantine/core";
import { OverviewKpiCard, type OverviewKpiItem } from "./OverviewKpiCard";
interface OverviewKpiStripProps {
title?: string;
items: OverviewKpiItem[];
}
/** Parse a numeric magnitude out of a KPI value (handles formatted currency strings). */
function toNumber(value: number | string): number {
if (typeof value === "number") return value;
const parsed = Number(String(value).replace(/[^0-9.-]/g, ""));
return Number.isFinite(parsed) ? parsed : 0;
}
export function OverviewKpiStrip({ title, items }: OverviewKpiStripProps) {
const max = Math.max(...items.map((item) => toNumber(item.value)), 0);
return (
<Paper
p="lg"
radius="lg"
withBorder
style={{
background: "#ffffff",
border: "1px solid var(--mantine-color-gray-2)",
}}
>
{title && (
<Text size="sm" fw={600} mb="md" c="dimmed">
{title}
</Text>
)}
<Group gap="md" align="stretch" wrap="wrap">
{items.map((item) => (
<OverviewKpiCard
key={item.label}
item={{
...item,
progress:
item.progress ?? (max > 0 ? toNumber(item.value) / max : 0),
}}
/>
))}
</Group>
</Paper>
);
}

View File

@@ -0,0 +1,177 @@
import {
ActionIcon,
Box,
Group,
SegmentedControl,
Stack,
Text,
Title,
} from "@mantine/core";
import { Activity, RefreshCw } from "lucide-react";
import { freightBrand } from "@/theme/freight-brand";
import type { OverviewRange } from "@/types/overview";
import "./overview.css";
const RANGE_OPTIONS = [
{ label: "7 days", value: "7d" },
{ label: "30 days", value: "30d" },
{ label: "90 days", value: "90d" },
];
const HERO_GRADIENT = `linear-gradient(125deg, ${freightBrand.primaryDark} 0%, ${freightBrand.primary} 50%, ${freightBrand.primaryLight} 125%)`;
function formatRelativeTime(iso: string | undefined) {
if (!iso) return "—";
const diffMs = Date.now() - new Date(iso).getTime();
const minutes = Math.floor(diffMs / 60_000);
if (minutes < 1) return "just now";
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
return new Date(iso).toLocaleString();
}
/** Decorative line-art locomotive + rails, sits faintly on the right of the hero. */
function TrainArtwork() {
return (
<Box
aria-hidden
style={{
position: "absolute",
right: -10,
bottom: -8,
width: 360,
height: 200,
opacity: 0.16,
pointerEvents: "none",
color: "white",
}}
>
<svg viewBox="0 0 360 200" fill="none" width="100%" height="100%">
{/* rails */}
<path d="M0 168 H360" stroke="currentColor" strokeWidth="2" strokeDasharray="2 10" strokeLinecap="round" />
<path d="M0 180 H360" stroke="currentColor" strokeWidth="2" />
{/* locomotive body */}
<path
d="M70 60 H250 a14 14 0 0 1 14 14 V150 H56 V94 a34 34 0 0 1 14-28 Z"
stroke="currentColor"
strokeWidth="3"
/>
{/* cab windows */}
<rect x="84" y="80" width="40" height="30" rx="6" stroke="currentColor" strokeWidth="3" />
<rect x="140" y="80" width="44" height="30" rx="6" stroke="currentColor" strokeWidth="3" />
<rect x="200" y="80" width="44" height="30" rx="6" stroke="currentColor" strokeWidth="3" />
{/* lower stripe */}
<path d="M56 130 H264" stroke="currentColor" strokeWidth="3" />
{/* wheels */}
<circle cx="96" cy="150" r="16" stroke="currentColor" strokeWidth="3" />
<circle cx="150" cy="150" r="16" stroke="currentColor" strokeWidth="3" />
<circle cx="214" cy="150" r="16" stroke="currentColor" strokeWidth="3" />
{/* coupling */}
<path d="M264 120 H300 a8 8 0 0 1 8 8 V150 H300" stroke="currentColor" strokeWidth="3" />
{/* headlight beam */}
<path d="M56 100 l-28 -10 M56 112 l-30 0 M56 124 l-28 10" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
</svg>
</Box>
);
}
interface OverviewPageHeaderProps {
range: OverviewRange;
onRangeChange: (range: OverviewRange) => void;
generatedAt?: string;
onRefresh: () => void;
isRefreshing?: boolean;
}
export function OverviewPageHeader({
range,
onRangeChange,
generatedAt,
onRefresh,
isRefreshing,
}: OverviewPageHeaderProps) {
return (
<Box
style={{
position: "relative",
overflow: "hidden",
borderRadius: 20,
padding: "28px 28px",
background: HERO_GRADIENT,
boxShadow: freightBrand.shadow,
}}
>
{/* decorative glows */}
<Box
style={{
position: "absolute",
top: -120,
right: 120,
width: 280,
height: 280,
borderRadius: "50%",
background: "rgba(255,255,255,0.10)",
pointerEvents: "none",
}}
/>
<TrainArtwork />
<Group justify="space-between" align="flex-end" wrap="wrap" gap="lg" style={{ position: "relative" }}>
<Stack gap={6} style={{ minWidth: 0 }}>
<Group gap={8} align="center">
<Box
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: 28,
height: 28,
borderRadius: 8,
background: "rgba(255,255,255,0.2)",
}}
>
<Activity size={16} color="white" />
</Box>
<Text size="xs" fw={700} c="rgba(255,255,255,0.85)" tt="uppercase" style={{ letterSpacing: 1.2 }}>
Freight Backoffice · Live
</Text>
</Group>
<Title order={1} c="white" style={{ letterSpacing: "-0.03em", fontSize: 34, lineHeight: 1.1 }}>
Operations Overview
</Title>
<Text size="sm" c="rgba(255,255,255,0.85)">
Real-time freight performance · updated {formatRelativeTime(generatedAt)}
</Text>
</Stack>
<Group gap="sm" style={{ position: "relative" }}>
<SegmentedControl
value={range}
onChange={(value) => onRangeChange(value as OverviewRange)}
data={RANGE_OPTIONS}
size="sm"
radius="lg"
classNames={{
root: "ov-seg-root",
indicator: "ov-seg-indicator",
label: "ov-seg-label",
}}
/>
<ActionIcon
variant="white"
color="green"
size="lg"
radius="lg"
aria-label="Refresh dashboard"
onClick={onRefresh}
loading={isRefreshing}
>
<RefreshCw size={18} />
</ActionIcon>
</Group>
</Group>
</Box>
);
}

View File

@@ -0,0 +1,79 @@
import {
Bar,
BarChart,
CartesianGrid,
Legend,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { Paper, Stack, Text } from "@mantine/core";
import type { IOverviewPaymentTrendPoint } from "@/types/overview";
import { overviewChartColors } from "./overview.styles";
function formatDateLabel(date: string) {
const parsed = new Date(`${date}T00:00:00`);
return parsed.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}
function formatAmount(value: number, currency: "ETB" | "USD") {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency,
maximumFractionDigits: 0,
}).format(value);
}
export function OverviewPaymentChart({ data }: { data: IOverviewPaymentTrendPoint[] }) {
const hasData = data.some((point) => point.amountEtb > 0 || point.amountUsd > 0);
return (
<Paper p="lg" radius="lg" withBorder h="100%" style={{ minHeight: 320 }}>
<Stack gap="md" h="100%">
<Text fw={600}>Payment trend</Text>
{!hasData ? (
<Text size="sm" c="dimmed" ta="center" py="xl">
No successful payments in this period
</Text>
) : (
<ResponsiveContainer width="100%" height={260}>
<BarChart data={data} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis
dataKey="date"
tickFormatter={formatDateLabel}
tick={{ fontSize: 12 }}
stroke="#94a3b8"
/>
<YAxis tick={{ fontSize: 12 }} stroke="#94a3b8" />
<Tooltip
labelFormatter={(value) => formatDateLabel(String(value))}
formatter={(value, name) => [
formatAmount(Number(value), name === "amountUsd" ? "USD" : "ETB"),
name === "amountUsd" ? "USD" : "ETB",
]}
/>
<Legend />
<Bar
dataKey="amountEtb"
name="ETB"
stackId="payments"
fill={overviewChartColors.etb}
radius={[0, 0, 0, 0]}
/>
<Bar
dataKey="amountUsd"
name="USD"
stackId="payments"
fill={overviewChartColors.usd}
radius={[4, 4, 0, 0]}
/>
</BarChart>
</ResponsiveContainer>
)}
</Stack>
</Paper>
);
}

View File

@@ -0,0 +1,72 @@
import { useNavigate } from "react-router-dom";
import { ArrowRight, FileText, Train, Users } from "lucide-react";
import { Card, Group, SimpleGrid, Stack, Text, ThemeIcon } from "@mantine/core";
const links = [
{
title: "Booking requests",
description: "Review and action incoming freight bookings",
href: "/dashboard/booking-requests",
icon: FileText,
},
{
title: "Train scheduling v2",
description: "Full allocation workflow — assign, pin wagons, finalize",
href: "/dashboard/operations/train-scheduling-v2",
icon: Train,
},
{
title: "Trains",
description: "Manage train master data and fleet status",
href: "/dashboard/trains",
icon: Train,
},
{
title: "User management",
description: "Employees, roles, and permissions",
href: "/dashboard/user-management",
icon: Users,
},
];
export function OverviewQuickLinks() {
const navigate = useNavigate();
return (
<Stack gap="md" h="100%">
<Text fw={600}>Quick links</Text>
<SimpleGrid cols={{ base: 1, sm: 2 }} spacing="sm">
{links.map((link) => {
const Icon = link.icon;
return (
<Card
key={link.href}
p="md"
radius="lg"
withBorder
style={{ cursor: "pointer" }}
onClick={() => navigate(link.href)}
>
<Group justify="space-between" align="flex-start" wrap="nowrap">
<Group align="flex-start" gap="sm" wrap="nowrap">
<ThemeIcon variant="light" color="green" size="lg" radius="md">
<Icon size={18} />
</ThemeIcon>
<Stack gap={2}>
<Text fw={600} size="sm">
{link.title}
</Text>
<Text size="xs" c="dimmed">
{link.description}
</Text>
</Stack>
</Group>
<ArrowRight size={16} color="var(--mantine-color-gray-5)" />
</Group>
</Card>
);
})}
</SimpleGrid>
</Stack>
);
}

View File

@@ -0,0 +1,78 @@
import { useNavigate } from "react-router-dom";
import { Paper, Stack, Table, Text } from "@mantine/core";
import { BookingPriorityBadge } from "@/components/bookings/BookingPriorityBadge";
import { BookingStatusBadge } from "@/components/bookings/BookingStatusBadge";
import type { IOverviewRecentBooking } from "@/types/overview";
function formatAmount(amount: number | null, currency: string | null) {
if (amount == null) return "—";
const code = currency === "USD" ? "USD" : "ETB";
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: code,
maximumFractionDigits: 0,
}).format(amount);
}
export function OverviewRecentBookingsTable({
bookings,
}: {
bookings: IOverviewRecentBooking[];
}) {
const navigate = useNavigate();
return (
<Paper p="lg" radius="lg" withBorder>
<Stack gap="md">
<Text fw={600}>Recent bookings</Text>
{bookings.length === 0 ? (
<Text size="sm" c="dimmed" ta="center" py="lg">
No recent bookings
</Text>
) : (
<Table highlightOnHover verticalSpacing="sm">
<Table.Thead>
<Table.Tr>
<Table.Th>Reference</Table.Th>
<Table.Th>Customer</Table.Th>
<Table.Th>Status</Table.Th>
<Table.Th>Priority</Table.Th>
<Table.Th>Amount</Table.Th>
<Table.Th>Created</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{bookings.map((booking) => (
<Table.Tr
key={booking.id}
style={{ cursor: "pointer" }}
onClick={() => navigate(`/dashboard/booking-requests/${booking.id}`)}
>
<Table.Td>
<Text fw={600} size="sm">
{booking.reference}
</Text>
</Table.Td>
<Table.Td>{booking.customerLabel}</Table.Td>
<Table.Td>
<BookingStatusBadge status={booking.status} />
</Table.Td>
<Table.Td>
<BookingPriorityBadge score={booking.priorityScore} />
</Table.Td>
<Table.Td>
{formatAmount(booking.totalAmount, booking.paymentCurrency)}
</Table.Td>
<Table.Td>
{new Date(booking.createdAt).toLocaleDateString()}
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
)}
</Stack>
</Paper>
);
}

View File

@@ -0,0 +1,69 @@
import {
Bar,
BarChart,
CartesianGrid,
Cell,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { Paper, Stack, Text } from "@mantine/core";
import { BOOKING_LIST_TABS } from "@/features/bookings/booking-status.config";
import type { IOverviewPipelineCount } from "@/types/overview";
import { overviewChartColors } from "./overview.styles";
function getPipelineLabel(stage: string) {
return BOOKING_LIST_TABS.find((tab) => tab.key === stage)?.label ?? stage;
}
export function OverviewStatusChart({ data }: { data: IOverviewPipelineCount[] }) {
const chartData = data.map((item) => ({
...item,
label: getPipelineLabel(item.stage),
}));
const hasData = chartData.some((item) => item.count > 0);
return (
<Paper p="lg" radius="lg" withBorder h="100%" style={{ minHeight: 320 }}>
<Stack gap="md" h="100%">
<Text fw={600}>Pipeline by stage</Text>
{!hasData ? (
<Text size="sm" c="dimmed" ta="center" py="xl">
No bookings in pipeline
</Text>
) : (
<ResponsiveContainer width="100%" height={260}>
<BarChart data={chartData} margin={{ top: 8, right: 8, left: 0, bottom: 24 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis
dataKey="label"
tick={{ fontSize: 11 }}
interval={0}
angle={-20}
textAnchor="end"
height={60}
stroke="#94a3b8"
/>
<YAxis allowDecimals={false} tick={{ fontSize: 12 }} stroke="#94a3b8" />
<Tooltip formatter={(value) => [value, "Bookings"]} />
<Bar dataKey="count" radius={[6, 6, 0, 0]}>
{chartData.map((entry, index) => (
<Cell
key={entry.stage}
fill={
overviewChartColors.pipeline[
index % overviewChartColors.pipeline.length
]
}
/>
))}
</Bar>
</BarChart>
</ResponsiveContainer>
)}
</Stack>
</Paper>
);
}

View File

@@ -0,0 +1,102 @@
import { AlertCircle } from "lucide-react";
import { Alert, Button, Center, Loader, Paper, Skeleton, Stack } from "@mantine/core";
import {
useOverviewBillingTab,
useOverviewBookingsTab,
useOverviewCustomersTab,
useOverviewOperationsTab,
useOverviewStaffTab,
} from "@/hooks/useOverview";
import type { OverviewRange, OverviewTabKey } from "@/types/overview";
import { OverviewBillingTabPanel } from "./tabs/OverviewBillingTabPanel";
import { OverviewBookingsTabPanel } from "./tabs/OverviewBookingsTabPanel";
import { OverviewCustomersTabPanel } from "./tabs/OverviewCustomersTabPanel";
import { OverviewOperationsTabPanel } from "./tabs/OverviewOperationsTabPanel";
import { OverviewStaffTabPanel } from "./tabs/OverviewStaffTabPanel";
function TabSkeleton() {
return (
<Stack gap="lg">
<Skeleton height={120} radius="lg" />
<Skeleton height={320} radius="lg" />
<Skeleton height={320} radius="lg" />
</Stack>
);
}
interface OverviewTabContentProps {
tab: OverviewTabKey;
range: OverviewRange;
}
export function OverviewTabContent({ tab, range }: OverviewTabContentProps) {
const bookings = useOverviewBookingsTab(range, tab === "bookings");
const billing = useOverviewBillingTab(range, tab === "billing");
const operations = useOverviewOperationsTab(tab === "operations");
const customers = useOverviewCustomersTab(range, tab === "customers");
const staff = useOverviewStaffTab(range, tab === "staff");
const query =
tab === "bookings"
? bookings
: tab === "billing"
? billing
: tab === "operations"
? operations
: tab === "customers"
? customers
: staff;
const { isLoading, isError, refetch, isFetching } = query;
if (isLoading) {
return <TabSkeleton />;
}
if (isError || !query.data) {
return (
<Paper p="xl" radius="lg" withBorder>
<Alert
icon={<AlertCircle size={16} />}
color="red"
title="Failed to load tab data"
variant="light"
>
<Stack gap="sm" align="flex-start">
<span>Could not load {tab} metrics. Please try again.</span>
<Button size="xs" variant="light" color="red" onClick={() => void refetch()}>
Retry
</Button>
</Stack>
</Alert>
</Paper>
);
}
return (
<Stack gap="md" pos="relative">
{isFetching && (
<Center style={{ position: "absolute", top: 8, right: 8, zIndex: 2 }}>
<Loader size="sm" color="green" />
</Center>
)}
{tab === "bookings" && bookings.data && (
<OverviewBookingsTabPanel data={bookings.data} />
)}
{tab === "billing" && billing.data && (
<OverviewBillingTabPanel data={billing.data} />
)}
{tab === "operations" && operations.data && (
<OverviewOperationsTabPanel data={operations.data} />
)}
{tab === "customers" && customers.data && (
<OverviewCustomersTabPanel data={customers.data} />
)}
{tab === "staff" && staff.data && (
<OverviewStaffTabPanel data={staff.data} />
)}
</Stack>
);
}

View File

@@ -0,0 +1,57 @@
/* ============================================================
EDR Freight — Overview page styles (hero controls + tabs)
============================================================ */
/* ---- Hero range segmented control (on gradient) ---- */
.ov-seg-root {
background: rgba(255, 255, 255, 0.18) !important;
border: 1px solid rgba(255, 255, 255, 0.28);
}
.ov-seg-indicator {
background: #ffffff !important;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
}
.ov-seg-label {
color: rgba(255, 255, 255, 0.9);
font-weight: 600;
}
.ov-seg-label[data-active] {
color: #15805f;
}
/* ---- Premium tab bar ---- */
.ov-tablist {
display: flex;
flex-wrap: wrap;
gap: 8px;
padding: 6px;
background: #f1f5f9;
border-radius: 16px;
border: 1px solid #e2e8f0;
}
.ov-tab {
border-radius: 11px;
padding: 10px 18px;
font-weight: 600;
color: #475569;
border: 1px solid transparent;
transition:
background-color 160ms ease,
color 160ms ease,
box-shadow 160ms ease,
transform 160ms ease;
}
.ov-tab:hover {
background: #ffffff;
color: #0f172a;
box-shadow: 0 2px 10px -4px rgba(15, 23, 42, 0.18);
}
.ov-tab[data-active] {
background: linear-gradient(135deg, #2dbf95 0%, #1b9e7a 100%) !important;
color: #ffffff !important;
box-shadow: 0 10px 20px -8px rgba(27, 158, 122, 0.55);
transform: translateY(-1px);
}
.ov-tab[data-active]:hover {
color: #ffffff;
}

View File

@@ -0,0 +1,40 @@
import { freightBrand } from "@/theme/freight-brand";
export const overviewChartColors = {
primary: freightBrand.primary,
primaryLight: freightBrand.primaryLight,
primaryDark: freightBrand.primaryDark,
muted: freightBrand.mutedBg,
etb: freightBrand.primary,
usd: "#0369a1",
/** Vibrant, well-separated categorical palette for charts. */
pipeline: [
"#1B9E7A", // brand green
"#0ea5e9", // sky
"#8b5cf6", // violet
"#f59e0b", // amber
"#14b8a6", // teal
"#ec4899", // pink
"#f43f5e", // rose
"#6366f1", // indigo
"#eab308", // yellow
"#06b6d4", // cyan
],
} as const;
/** Two-stop gradients keyed by KPI accent — used for radial gauges + accent bars. */
export const overviewAccentGradients = {
default: ["#94a3b8", "#475569"],
emerald: ["#34D9AE", "#1B9E7A"],
amber: ["#fbbf24", "#d97706"],
rose: ["#fb7185", "#e11d48"],
sky: ["#38bdf8", "#0284c7"],
violet: ["#a78bfa", "#7c3aed"],
} as const;
export type OverviewAccent = keyof typeof overviewAccentGradients;
export const overviewCardStyle = {
background: "white",
border: "1px solid var(--mantine-color-gray-2)",
} as const;

View File

@@ -0,0 +1,137 @@
import { Banknote, CreditCard, Wallet } from "lucide-react";
import {
Bar,
BarChart,
CartesianGrid,
Cell,
Legend,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { Grid, Paper, Stack, Text } from "@mantine/core";
import type { IOverviewBillingTab } from "@/types/overview";
import { OverviewDonutChart } from "../OverviewDonutChart";
import { OverviewKpiStrip } from "../OverviewKpiStrip";
import { OverviewPaymentChart } from "../OverviewPaymentChart";
import { overviewChartColors } from "../overview.styles";
function formatCurrency(amount: number, currency: "ETB" | "USD") {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency,
maximumFractionDigits: 0,
}).format(amount);
}
const METHOD_LABELS: Record<string, string> = {
telebirr: "Telebirr",
"cbe-birr": "CBE Birr",
ebirr: "eBirr",
};
interface OverviewBillingTabPanelProps {
data: IOverviewBillingTab;
}
export function OverviewBillingTabPanel({ data }: OverviewBillingTabPanelProps) {
const methodChartData = data.paymentsByMethod.map((item) => ({
name: METHOD_LABELS[item.method] ?? item.method,
count: item.count,
}));
return (
<Stack gap="lg">
<OverviewKpiStrip
items={[
{
label: "Revenue MTD (ETB)",
value: formatCurrency(data.kpis.revenueMtdEtb, "ETB"),
icon: Banknote,
accent: "emerald",
},
{
label: "Revenue MTD (USD)",
value: formatCurrency(data.kpis.revenueMtdUsd, "USD"),
icon: Wallet,
},
{
label: "Pending payments",
value: data.kpis.pendingPayments,
icon: CreditCard,
accent: "amber",
},
{
label: "Successful MTD",
value: data.kpis.successfulPaymentsMtd,
icon: Banknote,
},
]}
/>
<Grid gap="md">
<Grid.Col span={{ base: 12, lg: 8 }}>
<OverviewPaymentChart data={data.paymentTrend} />
</Grid.Col>
<Grid.Col span={{ base: 12, lg: 4 }}>
<OverviewDonutChart
title="Revenue by currency (MTD)"
data={data.revenueByCurrency.map((item) => ({
name: item.currency,
value: item.amount,
}))}
emptyMessage="No revenue this month"
/>
</Grid.Col>
</Grid>
<Grid gap="md">
<Grid.Col span={{ base: 12, md: 6 }}>
<OverviewDonutChart
title="Payments by status"
data={data.paymentsByStatus.map((item) => ({
name: item.status.replace(/-/g, " "),
value: item.count,
}))}
/>
</Grid.Col>
<Grid.Col span={{ base: 12, md: 6 }}>
<Paper p="lg" radius="lg" withBorder h="100%" style={{ minHeight: 300 }}>
<Stack gap="md">
<Text fw={600}>Payments by method</Text>
{methodChartData.length === 0 ? (
<Text size="sm" c="dimmed" ta="center" py="xl">
No payment methods recorded
</Text>
) : (
<ResponsiveContainer width="100%" height={260}>
<BarChart data={methodChartData} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis dataKey="name" tick={{ fontSize: 11 }} stroke="#94a3b8" />
<YAxis allowDecimals={false} tick={{ fontSize: 12 }} stroke="#94a3b8" />
<Tooltip />
<Legend />
<Bar dataKey="count" name="Transactions" radius={[6, 6, 0, 0]}>
{methodChartData.map((entry, index) => (
<Cell
key={entry.name}
fill={
overviewChartColors.pipeline[
index % overviewChartColors.pipeline.length
]
}
/>
))}
</Bar>
</BarChart>
</ResponsiveContainer>
)}
</Stack>
</Paper>
</Grid.Col>
</Grid>
</Stack>
);
}

View File

@@ -0,0 +1,106 @@
import {
AlertCircle,
Clock,
FileText,
UserCheck,
} from "lucide-react";
import { Grid, Stack } from "@mantine/core";
import { BOOKING_STATUS_META } from "@/features/bookings/booking-status.config";
import type { IOverviewBookingsTab } from "@/types/overview";
import { OverviewBookingTrendChart } from "../OverviewBookingTrendChart";
import { OverviewDonutChart } from "../OverviewDonutChart";
import { OverviewHorizontalBarChart } from "../OverviewHorizontalBarChart";
import { OverviewKpiStrip } from "../OverviewKpiStrip";
import { OverviewRecentBookingsTable } from "../OverviewRecentBookingsTable";
import { OverviewStatusChart } from "../OverviewStatusChart";
interface OverviewBookingsTabPanelProps {
data: IOverviewBookingsTab;
}
export function OverviewBookingsTabPanel({ data }: OverviewBookingsTabPanelProps) {
return (
<Stack gap="lg">
<OverviewKpiStrip
items={[
{
label: "Active bookings",
value: data.kpis.totalActive,
icon: FileText,
accent: "emerald",
hint: "Currently in workflow",
},
{
label: "Needs action",
value: data.kpis.needsAction,
icon: AlertCircle,
accent: "amber",
hint: "Awaiting your review",
},
{
label: "Urgent",
value: data.kpis.urgent,
icon: Clock,
accent: "rose",
hint: "High priority queue",
},
{
label: "In approval",
value: data.kpis.inApproval,
icon: UserCheck,
accent: "sky",
hint: "Pending sign-off",
},
{
label: "Submitted today",
value: data.kpis.submittedToday,
icon: FileText,
hint: "New since midnight",
},
]}
/>
<Grid gap="md">
<Grid.Col span={{ base: 12, lg: 7 }}>
<OverviewBookingTrendChart data={data.bookingTrend} />
</Grid.Col>
<Grid.Col span={{ base: 12, lg: 5 }}>
<OverviewStatusChart data={data.bookingsByPipeline} />
</Grid.Col>
</Grid>
<Grid gap="md">
<Grid.Col span={{ base: 12, md: 6 }}>
<OverviewDonutChart
title="By status"
data={data.bookingsByStatus.map((item) => ({
name: BOOKING_STATUS_META[item.status]?.title ?? item.status,
value: item.count,
}))}
emptyMessage="No bookings yet"
/>
</Grid.Col>
<Grid.Col span={{ base: 12, md: 6 }}>
<OverviewDonutChart
title="By freight type"
data={data.bookingsByFreightType.map((item) => ({
name: item.label,
value: item.count,
}))}
/>
</Grid.Col>
</Grid>
<OverviewHorizontalBarChart
title="By payment currency"
data={data.bookingsByCurrency.map((item) => ({
label: item.label,
value: item.count,
}))}
/>
<OverviewRecentBookingsTable bookings={data.recentBookings} />
</Stack>
);
}

View File

@@ -0,0 +1,120 @@
import { Users } from "lucide-react";
import {
Area,
AreaChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { Grid, Paper, Stack, Text } from "@mantine/core";
import type { IOverviewCustomersTab } from "@/types/overview";
import { OverviewDonutChart } from "../OverviewDonutChart";
import { OverviewHorizontalBarChart } from "../OverviewHorizontalBarChart";
import { OverviewKpiStrip } from "../OverviewKpiStrip";
import { overviewChartColors } from "../overview.styles";
function formatDateLabel(date: string) {
const parsed = new Date(`${date}T00:00:00`);
return parsed.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}
interface OverviewCustomersTabPanelProps {
data: IOverviewCustomersTab;
}
export function OverviewCustomersTabPanel({ data }: OverviewCustomersTabPanelProps) {
const hasGrowth = data.customerGrowthTrend.some((point) => point.count > 0);
return (
<Stack gap="lg">
<OverviewKpiStrip
items={[
{
label: "Total customers",
value: data.kpis.totalCustomers,
icon: Users,
},
{
label: "New this month",
value: data.kpis.newCustomersThisMonth,
icon: Users,
accent: "emerald",
},
]}
/>
<Grid gap="md">
<Grid.Col span={{ base: 12, lg: 7 }}>
<Paper p="lg" radius="lg" withBorder h="100%" style={{ minHeight: 320 }}>
<Stack gap="md">
<Text fw={600}>Customer growth</Text>
{!hasGrowth ? (
<Text size="sm" c="dimmed" ta="center" py="xl">
No new customers in this period
</Text>
) : (
<ResponsiveContainer width="100%" height={260}>
<AreaChart data={data.customerGrowthTrend}>
<defs>
<linearGradient id="customerGrowthFill" x1="0" y1="0" x2="0" y2="1">
<stop
offset="5%"
stopColor={overviewChartColors.primary}
stopOpacity={0.35}
/>
<stop
offset="95%"
stopColor={overviewChartColors.primary}
stopOpacity={0}
/>
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis
dataKey="date"
tickFormatter={formatDateLabel}
tick={{ fontSize: 12 }}
/>
<YAxis allowDecimals={false} tick={{ fontSize: 12 }} />
<Tooltip
labelFormatter={(value) => formatDateLabel(String(value))}
formatter={(value) => [value, "New customers"]}
/>
<Area
type="monotone"
dataKey="count"
stroke={overviewChartColors.primary}
fill="url(#customerGrowthFill)"
strokeWidth={2}
/>
</AreaChart>
</ResponsiveContainer>
)}
</Stack>
</Paper>
</Grid.Col>
<Grid.Col span={{ base: 12, lg: 5 }}>
<OverviewDonutChart
title="Customers by type"
data={data.customersByType.map((item) => ({
name: item.label,
value: item.count,
}))}
/>
</Grid.Col>
</Grid>
<OverviewHorizontalBarChart
title="Top customers by bookings"
data={data.topCustomersByBookings.map((item) => ({
label: item.label,
value: item.count,
}))}
valueLabel="Bookings"
/>
</Stack>
);
}

View File

@@ -0,0 +1,88 @@
import { Box, Container as ContainerIcon, Train, Truck } from "lucide-react";
import { Grid, Stack } from "@mantine/core";
import type { IOverviewOperationsTab } from "@/types/overview";
import { OverviewDonutChart } from "../OverviewDonutChart";
import { OverviewKpiStrip } from "../OverviewKpiStrip";
interface OverviewOperationsTabPanelProps {
data: IOverviewOperationsTab;
}
function formatStatusLabel(status: string) {
return status
.replace(/_/g, " ")
.toLowerCase()
.replace(/\b\w/g, (char) => char.toUpperCase());
}
export function OverviewOperationsTabPanel({ data }: OverviewOperationsTabPanelProps) {
return (
<Stack gap="lg">
<OverviewKpiStrip
items={[
{
label: "Active trains",
value: data.kpis.trainsActive,
icon: Train,
accent: "emerald",
},
{
label: "Wagons available",
value: data.kpis.wagonsAvailable,
icon: Truck,
},
{
label: "Containers in transit",
value: data.kpis.containersInTransit,
icon: ContainerIcon,
},
{
label: "Cargoes loaded",
value: data.kpis.cargoesLoaded,
icon: Box,
},
]}
/>
<Grid gap="md">
<Grid.Col span={{ base: 12, md: 6 }}>
<OverviewDonutChart
title="Train status"
data={data.trainStatusBreakdown.map((item) => ({
name: formatStatusLabel(item.status),
value: item.count,
}))}
/>
</Grid.Col>
<Grid.Col span={{ base: 12, md: 6 }}>
<OverviewDonutChart
title="Wagon status"
data={data.wagonStatusBreakdown.map((item) => ({
name: formatStatusLabel(item.status),
value: item.count,
}))}
/>
</Grid.Col>
<Grid.Col span={{ base: 12, md: 6 }}>
<OverviewDonutChart
title="Container status"
data={data.containerStatusBreakdown.map((item) => ({
name: formatStatusLabel(item.status),
value: item.count,
}))}
/>
</Grid.Col>
<Grid.Col span={{ base: 12, md: 6 }}>
<OverviewDonutChart
title="Cargo status"
data={data.cargoStatusBreakdown.map((item) => ({
name: formatStatusLabel(item.status),
value: item.count,
}))}
/>
</Grid.Col>
</Grid>
</Stack>
);
}

View File

@@ -0,0 +1,118 @@
import { UserCheck, Users } from "lucide-react";
import {
Area,
AreaChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { Grid, Paper, Stack, Text } from "@mantine/core";
import type { IOverviewStaffTab } from "@/types/overview";
import { OverviewDonutChart } from "../OverviewDonutChart";
import { OverviewKpiStrip } from "../OverviewKpiStrip";
import { overviewChartColors } from "../overview.styles";
function formatDateLabel(date: string) {
const parsed = new Date(`${date}T00:00:00`);
return parsed.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}
interface OverviewStaffTabPanelProps {
data: IOverviewStaffTab;
}
export function OverviewStaffTabPanel({ data }: OverviewStaffTabPanelProps) {
const hasGrowth = data.employeeGrowthTrend.some((point) => point.count > 0);
return (
<Stack gap="lg">
<OverviewKpiStrip
items={[
{
label: "Active employees",
value: data.kpis.activeEmployees,
icon: UserCheck,
accent: "emerald",
},
{
label: "Active users",
value: data.kpis.activeUsers,
icon: Users,
},
]}
/>
<Grid gap="md">
<Grid.Col span={{ base: 12, lg: 7 }}>
<Paper p="lg" radius="lg" withBorder h="100%" style={{ minHeight: 320 }}>
<Stack gap="md">
<Text fw={600}>Employee onboarding trend</Text>
{!hasGrowth ? (
<Text size="sm" c="dimmed" ta="center" py="xl">
No new employees in this period
</Text>
) : (
<ResponsiveContainer width="100%" height={260}>
<AreaChart data={data.employeeGrowthTrend}>
<defs>
<linearGradient id="employeeGrowthFill" x1="0" y1="0" x2="0" y2="1">
<stop
offset="5%"
stopColor={overviewChartColors.primaryDark}
stopOpacity={0.35}
/>
<stop
offset="95%"
stopColor={overviewChartColors.primaryDark}
stopOpacity={0}
/>
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis
dataKey="date"
tickFormatter={formatDateLabel}
tick={{ fontSize: 12 }}
/>
<YAxis allowDecimals={false} tick={{ fontSize: 12 }} />
<Tooltip
labelFormatter={(value) => formatDateLabel(String(value))}
formatter={(value) => [value, "New employees"]}
/>
<Area
type="monotone"
dataKey="count"
stroke={overviewChartColors.primaryDark}
fill="url(#employeeGrowthFill)"
strokeWidth={2}
/>
</AreaChart>
</ResponsiveContainer>
)}
</Stack>
</Paper>
</Grid.Col>
<Grid.Col span={{ base: 12, lg: 5 }}>
<OverviewDonutChart
title="Active vs inactive users"
data={data.activeUsersBreakdown.map((item) => ({
name: item.label,
value: item.count,
}))}
/>
</Grid.Col>
</Grid>
<OverviewDonutChart
title="Users by account status"
data={data.usersByStatus.map((item) => ({
name: item.status.replace(/_/g, " "),
value: item.count,
}))}
/>
</Stack>
);
}

View File

@@ -0,0 +1,354 @@
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import {
DragDropContext,
Draggable,
Droppable,
type DraggableProvided,
type DraggableStateSnapshot,
type DropResult,
} from "@hello-pangea/dnd";
import { GripVertical, Loader2 } from "lucide-react";
import {
Badge,
Box,
Button,
Group,
Modal,
Stack,
Tabs,
Text,
TextInput,
} from "@mantine/core";
import type { RuleEngineResourceConfig } from "@/pages/ruleEngine/config/resources";
import type { RuleEngineRecord } from "@/types/rule-engine";
import { getOrderItemLabel, getOrderValue } from "./ruleEngineOrder.utils";
interface OrderDraftItem {
id: string;
label: string;
code?: string;
order: number;
}
export interface ManageRuleEngineOrderDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
config: RuleEngineResourceConfig;
items: RuleEngineRecord[];
isLoading: boolean;
isSaving: boolean;
onSave: (payload: { ids: string[]; requiresDirectorApproval?: boolean }) => void;
}
const toDraftItems = (
rows: RuleEngineRecord[],
config: RuleEngineResourceConfig,
): OrderDraftItem[] => {
const field = config.orderConfig!.field;
return [...rows]
.sort((a, b) => getOrderValue(a, field) - getOrderValue(b, field))
.map((row) => ({
id: String(row.id),
label: getOrderItemLabel(row, config.slug),
code: row.code ? String(row.code) : undefined,
order: getOrderValue(row, field),
}));
};
/** Reparent dragged row to body — fixes position:fixed inside Modal transforms. */
const PortalAwareRow = ({
snapshot,
children,
}: {
snapshot: DraggableStateSnapshot;
children: ReactNode;
}) => {
if (snapshot.isDragging) {
return createPortal(children, document.body);
}
return <>{children}</>;
};
const OrderRow = ({
item,
index,
dragProvided,
snapshot,
}: {
item: OrderDraftItem;
index: number;
dragProvided: DraggableProvided;
snapshot: DraggableStateSnapshot;
}) => (
<PortalAwareRow snapshot={snapshot}>
<Group
ref={dragProvided.innerRef}
{...dragProvided.draggableProps}
{...dragProvided.dragHandleProps}
gap="sm"
wrap="nowrap"
p="sm"
style={{
...dragProvided.draggableProps.style,
border: "1px solid var(--mantine-color-gray-3)",
borderRadius: "var(--mantine-radius-md)",
background: snapshot.isDragging ? "var(--mantine-color-gray-0)" : "white",
boxShadow: snapshot.isDragging ? "0 8px 24px rgba(0, 0, 0, 0.12)" : undefined,
cursor: snapshot.isDragging ? "grabbing" : "grab",
userSelect: "none",
}}
>
<Box c="dimmed" style={{ display: "flex", alignItems: "center" }}>
<GripVertical size={18} />
</Box>
<Badge variant="light" color="gray" size="sm">
{index + 1}
</Badge>
<Stack gap={2} style={{ flex: 1, minWidth: 0 }}>
<Text size="sm" fw={500} truncate>
{item.label}
</Text>
{item.code ? (
<Text size="xs" c="dimmed" truncate>
{item.code}
</Text>
) : null}
</Stack>
</Group>
</PortalAwareRow>
);
const ManageRuleEngineOrderDialog = ({
open,
onOpenChange,
config,
items,
isLoading,
isSaving,
onSave,
}: ManageRuleEngineOrderDialogProps) => {
const isScoped = config.orderConfig?.scopeField === "requiresDirectorApproval";
const [tab, setTab] = useState<"standard" | "director">("standard");
const [filter, setFilter] = useState("");
const [standardItems, setStandardItems] = useState<OrderDraftItem[]>([]);
const [directorItems, setDirectorItems] = useState<OrderDraftItem[]>([]);
useEffect(() => {
if (!open) return;
if (isScoped) {
setStandardItems(
toDraftItems(
items.filter((row) => !row.requiresDirectorApproval),
config,
),
);
setDirectorItems(
toDraftItems(
items.filter((row) => row.requiresDirectorApproval),
config,
),
);
} else {
setStandardItems(toDraftItems(items, config));
}
setFilter("");
}, [open, items, config, isScoped]);
const activeItems = isScoped
? tab === "director"
? directorItems
: standardItems
: standardItems;
const setActiveItems = isScoped
? tab === "director"
? setDirectorItems
: setStandardItems
: setStandardItems;
const filteredItems = useMemo(() => {
const q = filter.trim().toLowerCase();
if (!q) return activeItems;
return activeItems.filter(
(item) =>
item.label.toLowerCase().includes(q) ||
(item.code?.toLowerCase().includes(q) ?? false),
);
}, [activeItems, filter]);
const droppableId = isScoped
? `rule-engine-order-${tab}`
: "rule-engine-order-list";
const onDragEnd = (result: DropResult) => {
if (!result.destination || filter.trim()) return;
const sourceIndex = result.source.index;
const destIndex = result.destination.index;
if (sourceIndex === destIndex) return;
setActiveItems((prev) => {
const next = [...prev];
const [removed] = next.splice(sourceIndex, 1);
next.splice(destIndex, 0, removed!);
return next.map((item, index) => ({ ...item, order: index + 1 }));
});
};
const handleSave = () => {
if (isScoped) {
onSave({
ids: (tab === "director" ? directorItems : standardItems).map((item) => item.id),
requiresDirectorApproval: tab === "director",
});
return;
}
onSave({ ids: standardItems.map((item) => item.id) });
};
const renderList = (listItems: OrderDraftItem[]) => (
<Droppable droppableId={droppableId}>
{(provided) => (
<Stack
gap="xs"
ref={provided.innerRef}
{...provided.droppableProps}
style={{ minHeight: 120 }}
>
{listItems.length === 0 ? (
<Text size="sm" c="dimmed" ta="center" py="xl">
No items to reorder.
</Text>
) : (
listItems.map((item, index) => (
<Draggable
key={item.id}
draggableId={item.id}
index={index}
isDragDisabled={Boolean(filter.trim())}
>
{(dragProvided, snapshot) => (
<OrderRow
item={item}
index={index}
dragProvided={dragProvided}
snapshot={snapshot}
/>
)}
</Draggable>
))
)}
{provided.placeholder}
</Stack>
)}
</Droppable>
);
return (
<Modal
opened={open}
onClose={() => onOpenChange(false)}
title={`Manage order · ${config.label}`}
centered
size="lg"
radius="lg"
transitionProps={{ duration: 0, transition: "fade" }}
styles={{
content: {
transform: "none",
overflow: "visible",
},
body: {
overflow: "visible",
},
}}
>
<DragDropContext onDragEnd={onDragEnd}>
<Stack gap="md">
<Text size="sm" c="dimmed">
Drag items anywhere in the list to set display order. Changes apply when you save.
</Text>
{isLoading ? (
<Group justify="center" py="xl">
<Loader2 size={28} style={{ animation: "spin 1s linear infinite" }} />
</Group>
) : isScoped ? (
<Tabs
value={tab}
onChange={(value) => setTab((value as "standard" | "director") ?? "standard")}
>
<Tabs.List>
<Tabs.Tab value="standard">Standard chain ({standardItems.length})</Tabs.Tab>
<Tabs.Tab value="director">Director chain ({directorItems.length})</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value="standard" pt="md">
<Stack gap="md">
<TextInput
placeholder="Filter items…"
value={filter}
onChange={(e) => setFilter(e.currentTarget.value)}
/>
<Box style={{ maxHeight: "50vh", overflowY: "auto", paddingRight: 4 }}>
{renderList(filteredItems)}
</Box>
</Stack>
</Tabs.Panel>
<Tabs.Panel value="director" pt="md">
<Stack gap="md">
<TextInput
placeholder="Filter items…"
value={filter}
onChange={(e) => setFilter(e.currentTarget.value)}
/>
<Box style={{ maxHeight: "50vh", overflowY: "auto", paddingRight: 4 }}>
{renderList(filteredItems)}
</Box>
</Stack>
</Tabs.Panel>
</Tabs>
) : (
<>
<TextInput
placeholder="Filter items…"
value={filter}
onChange={(e) => setFilter(e.currentTarget.value)}
/>
<Box style={{ maxHeight: "50vh", overflowY: "auto", paddingRight: 4 }}>
{renderList(filteredItems)}
</Box>
</>
)}
{filter.trim() ? (
<Text size="xs" c="dimmed">
Clear the filter to drag and reorder items.
</Text>
) : null}
<Group justify="flex-end" gap="sm">
<Button variant="default" onClick={() => onOpenChange(false)} disabled={isSaving}>
Cancel
</Button>
<Button
color="green"
onClick={handleSave}
disabled={isLoading || isSaving}
leftSection={
isSaving ? (
<Loader2 size={16} style={{ animation: "spin 1s linear infinite" }} />
) : undefined
}
>
{isSaving ? "Saving…" : "Save order"}
</Button>
</Group>
</Stack>
</DragDropContext>
</Modal>
);
};
export default ManageRuleEngineOrderDialog;

View File

@@ -1,8 +1,10 @@
import { Stack, Group, Text, Pagination, Card, SimpleGrid } from "@mantine/core";
import type { OnChangeFn, PaginationState } from "@tanstack/react-table";
import { Stack, Group, Text, Card, SimpleGrid } from "@mantine/core";
import type { RuleEngineResourceConfig } from "@/pages/ruleEngine/config/resources";
import type { RuleEngineRecord } from "@/types/rule-engine";
import RuleEngineListFooter from "./RuleEngineListFooter";
import RuleEngineRecordActions from "./RuleEngineRecordActions";
import { cardInitials, resolveCardPresentation } from "./ruleEngineCardMeta";
import { formatCell } from "./ruleEngineFormat";
@@ -13,12 +15,10 @@ export interface RuleEngineCardGridProps {
status: "loading" | "error" | "success";
emptyMessage: string;
itemLabel: string;
pagination: {
pageIndex: number;
pageSize: number;
pageCount: number;
totalCount: number;
};
pagination: PaginationState;
pageCount: number;
totalCount: number;
onPaginationChange: OnChangeFn<PaginationState>;
onEdit?: (record: RuleEngineRecord) => void;
onDelete?: (record: RuleEngineRecord) => void;
readOnly?: boolean;
@@ -71,6 +71,9 @@ const RuleEngineCardGrid = ({
emptyMessage,
itemLabel,
pagination,
pageCount,
totalCount,
onPaginationChange,
onEdit,
onDelete,
onViewChain,
@@ -249,19 +252,13 @@ const RuleEngineCardGrid = ({
})}
</SimpleGrid>
{pagination.pageCount > 1 && (
<Group justify="space-between" align="center" p="md" style={{ borderTop: "1px solid var(--mantine-color-gray-2)" }}>
<Text size="sm" c="dimmed">
Showing {Math.min(rows.length, pagination.pageSize)} of {pagination.totalCount} {itemLabel}
</Text>
<Pagination
value={pagination.pageIndex + 1}
total={pagination.pageCount}
size="sm"
radius="md"
/>
</Group>
)}
<RuleEngineListFooter
pagination={pagination}
pageCount={pageCount}
totalCount={totalCount}
itemLabel={itemLabel}
onPaginationChange={onPaginationChange}
/>
</Stack>
);
};

View File

@@ -20,6 +20,7 @@ import {
type FormFieldDef,
} from "@/pages/ruleEngine/config/resources";
import type { RuleEngineRecord } from "@/types/rule-engine";
import { RULE_ENGINE_POSITION_END } from "./ruleEngineOrder.utils";
export interface RuleEngineFormDialogProps {
open: boolean;
@@ -30,6 +31,8 @@ export interface RuleEngineFormDialogProps {
initialRecord?: RuleEngineRecord | null;
isSubmitting: boolean;
selectOptionsLoading?: boolean;
positionOptions?: { label: string; value: string }[];
positionLoading?: boolean;
onSubmit: (values: Record<string, unknown>) => void;
}
@@ -146,15 +149,19 @@ const RuleEngineFormDialog = ({
initialRecord,
isSubmitting,
selectOptionsLoading = false,
positionOptions,
positionLoading = false,
onSubmit,
}: RuleEngineFormDialogProps) => {
const [values, setValues] = useState<Record<string, unknown>>(() =>
buildInitialValues(fields, initialRecord),
);
const [position, setPosition] = useState(RULE_ENGINE_POSITION_END);
useEffect(() => {
if (open) {
setValues(buildInitialValues(fields, initialRecord));
setPosition(RULE_ENGINE_POSITION_END);
}
}, [open, fields, initialRecord]);
@@ -192,6 +199,10 @@ const RuleEngineFormDialog = ({
payload.code = String(payload.code).toUpperCase();
}
if (!initialRecord && positionOptions && position !== RULE_ENGINE_POSITION_END) {
payload.insertAfterId = position;
}
onSubmit(payload);
};
@@ -315,6 +326,23 @@ const RuleEngineFormDialog = ({
<Stack gap="lg">
<Box style={{ maxHeight: "calc(65vh - 120px)", overflowY: "auto", paddingRight: 4 }}>
<Stack gap="md">
{!initialRecord && positionOptions ? (
<Select
label="Position"
description="New items are appended to the end by default."
value={position}
onChange={(value) => setPosition(value ?? RULE_ENGINE_POSITION_END)}
data={[
{ label: "At end (default)", value: RULE_ENGINE_POSITION_END },
...positionOptions,
]}
searchable
disabled={positionLoading}
size="md"
radius="md"
styles={inputStyles}
/>
) : null}
{formRows.map((row) =>
row.kind === "pair" ? (
<SimpleGrid key={`${row.fields[0].name}-${row.fields[1].name}`} cols={2} spacing="md">

View File

@@ -0,0 +1,73 @@
import type { OnChangeFn, PaginationState } from "@tanstack/react-table";
import { Group, Pagination, Select, Text } from "@mantine/core";
export interface RuleEngineListFooterProps {
pagination: PaginationState;
pageCount: number;
totalCount: number;
itemLabel: string;
onPaginationChange: OnChangeFn<PaginationState>;
}
const PAGE_SIZE_OPTIONS = ["5", "10", "25", "50"];
const RuleEngineListFooter = ({
pagination,
pageCount,
totalCount,
itemLabel,
onPaginationChange,
}: RuleEngineListFooterProps) => {
const { pageIndex, pageSize } = pagination;
const start = totalCount === 0 ? 0 : pageIndex * pageSize + 1;
const end = Math.min((pageIndex + 1) * pageSize, totalCount);
const setPageIndex = (nextIndex: number) => {
onPaginationChange({ pageIndex: nextIndex, pageSize });
};
const setPageSize = (nextSize: number) => {
onPaginationChange({ pageIndex: 0, pageSize: nextSize });
};
return (
<Group
justify="space-between"
align="center"
wrap="wrap"
p="md"
style={{ borderTop: "1px solid var(--mantine-color-gray-2)" }}
>
<Group gap="md" align="center">
<Group gap="xs" align="center">
<Text size="sm" c="dimmed">
Rows per page
</Text>
<Select
value={String(pageSize)}
onChange={(value) => value && setPageSize(Number(value))}
data={PAGE_SIZE_OPTIONS}
size="xs"
w={70}
allowDeselect={false}
/>
</Group>
<Text size="sm" c="dimmed">
Showing {start}{end} of {totalCount} {itemLabel}
</Text>
</Group>
{pageCount > 1 && (
<Pagination
value={pageIndex + 1}
total={pageCount}
size="sm"
radius="md"
onChange={(page) => setPageIndex(page - 1)}
/>
)}
</Group>
);
};
export default RuleEngineListFooter;

View File

@@ -0,0 +1,60 @@
import { ActionIcon, Group, Tooltip } from "@mantine/core";
import { ChevronDown, ChevronUp } from "lucide-react";
import type { RuleEngineOrderConfig } from "@/pages/ruleEngine/config/resources";
import type { RuleEngineRecord } from "@/types/rule-engine";
import { getOrderValue } from "./ruleEngineOrder.utils";
export interface RuleEngineOrderControlsProps {
record: RuleEngineRecord;
orderConfig: RuleEngineOrderConfig;
totalCount: number;
disabled?: boolean;
onMove: (id: string, direction: "up" | "down") => void;
}
const RuleEngineOrderControls = ({
record,
orderConfig,
totalCount,
disabled = false,
onMove,
}: RuleEngineOrderControlsProps) => {
const id = String(record.id);
const order = getOrderValue(record, orderConfig.field);
const canMoveUp = order > 1;
const canMoveDown = orderConfig.scopeField ? true : order < totalCount;
return (
<Group gap={4} wrap="nowrap">
<Tooltip label="Move up">
<ActionIcon
variant="subtle"
color="gray"
size="sm"
disabled={disabled || !canMoveUp}
onClick={() => onMove(id, "up")}
aria-label="Move up"
>
<ChevronUp size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label="Move down">
<ActionIcon
variant="subtle"
color="gray"
size="sm"
disabled={disabled || !canMoveDown}
onClick={() => onMove(id, "down")}
aria-label="Move down"
>
<ChevronDown size={16} />
</ActionIcon>
</Tooltip>
</Group>
);
};
export default RuleEngineOrderControls;

View File

@@ -1,42 +1,50 @@
import { LayoutGrid, Plus, Search, Table2 } from "lucide-react";
import { LayoutGrid, ListOrdered, Plus, Search, Table2 } from "lucide-react";
import { Button, TextInput, Group, SegmentedControl } from "@mantine/core";
import type { RuleEngineViewMode } from "./useRuleEngineViewMode";
export interface RuleEngineToolbarProps {
search: string;
onSearchChange: (value: string) => void;
searchPlaceholder: string;
search?: string;
onSearchChange?: (value: string) => void;
searchPlaceholder?: string;
showSearch?: boolean;
onAdd?: () => void;
addLabel?: string;
onManageOrder?: () => void;
viewMode: RuleEngineViewMode;
onViewModeChange: (mode: RuleEngineViewMode) => void;
}
const RuleEngineToolbar = ({
search,
search = "",
onSearchChange,
searchPlaceholder,
searchPlaceholder = "Search…",
showSearch = true,
onAdd,
addLabel = "Add",
onManageOrder,
viewMode,
onViewModeChange,
}: RuleEngineToolbarProps) => (
<Group gap="md" justify="space-between" align="center" wrap="nowrap">
<TextInput
placeholder={searchPlaceholder}
value={search}
onChange={(e) => onSearchChange(e.currentTarget.value)}
leftSection={<Search size={18} />}
size="md"
radius="lg"
style={{ flex: 1, minWidth: 0 }}
styles={{
input: {
borderColor: "var(--mantine-color-gray-3)",
},
}}
/>
{showSearch && onSearchChange ? (
<TextInput
placeholder={searchPlaceholder}
value={search}
onChange={(e) => onSearchChange(e.currentTarget.value)}
leftSection={<Search size={18} />}
size="md"
radius="lg"
style={{ flex: 1, minWidth: 0 }}
styles={{
input: {
borderColor: "var(--mantine-color-gray-3)",
},
}}
/>
) : (
<div style={{ flex: 1 }} />
)}
<Group gap="md" align="center" justify="flex-end" wrap="nowrap">
<SegmentedControl
@@ -72,6 +80,21 @@ const RuleEngineToolbar = ({
}}
/>
{onManageOrder ? (
<Button
onClick={onManageOrder}
leftSection={<ListOrdered size={18} />}
size="sm"
radius="lg"
variant="light"
color="gray"
fw={600}
style={{ whiteSpace: "nowrap" }}
>
Manage order
</Button>
) : null}
{onAdd ? (
<Button
onClick={onAdd}

View File

@@ -0,0 +1,32 @@
import type { RuleEngineRecord, RuleEngineResourceSlug } from "@/types/rule-engine";
export const RULE_ENGINE_POSITION_END = "__end__";
export function getOrderItemLabel(
record: RuleEngineRecord,
slug: RuleEngineResourceSlug,
): string {
const code = String(record.code ?? "").trim();
switch (slug) {
case "cargo-types":
return String(record.cargoTypeName ?? (code || record.id));
case "container-types":
case "yards":
case "shipping-lines":
return String(record.label ?? (code || record.id));
case "service-types":
return String(record.serviceName ?? (code || record.id));
case "approval-rules":
return String(record.actionLabel ?? record.requiredRole ?? record.id);
default:
return String(record.label ?? record.code ?? record.id);
}
}
export function getOrderValue(
record: RuleEngineRecord,
field: "displayOrder" | "stepOrder",
): number {
const raw = record[field];
return typeof raw === "number" ? raw : Number(raw ?? 0);
}

View File

@@ -0,0 +1,662 @@
import { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { isAxiosError } from "axios";
import {
Button,
Card,
Checkbox,
Group,
Modal,
Paper,
Radio,
Select,
Stack,
Stepper,
Text,
} from "@mantine/core";
import { CheckCircle2 } from "lucide-react";
import {
useAvailableLocomotives,
useEligibleBookings,
useScheduleList,
useScheduleMutations,
} from "@/hooks/trainScheduling/useTrainScheduling";
import { useRoutes } from "@/hooks/useRoutes";
import { useToast } from "@/hooks/use-toast";
import { trainSchedulingService } from "@/services/trainScheduling.service";
import type { BookingDetail } from "@/types/booking";
import type {
ContainerPlacement,
FreightType,
ReschedulePlan,
TrainScheduleDetail,
TrainScheduleListItem,
TrainSchedulePreviewResponse,
} from "@/types/trainScheduling";
import { ContainerPlacementGrid } from "./ContainerPlacementGrid";
import {
autoFillPlacements,
mergePlacementsWithSaved,
placementsFromScheduleWagons,
validateLocalPlacements,
} from "./containerPlacement.util";
import { shouldShowContainerPlacementStep } from "./schedulingContainerStep.util";
import { FleetAvailabilitySummary } from "./FleetAvailabilitySummary";
import { ScheduleBookingsStep } from "./ScheduleBookingsStep";
import { PreviewSummary, ScheduleWarningsAlert } from "./ScheduleWarningsAlert";
import { SchedulingWorkflowHeader } from "./SchedulingWorkflowHeader";
import { schedulingWorkflow } from "./schedulingWorkflow.styles";
import { SchedulingStatusBadge } from "./ScheduleStatusBadge";
import { WagonPlanGrid } from "./WagonPlanGrid";
const parseError = (error: unknown, fallback: string) => {
if (isAxiosError(error)) {
const data = error.response?.data as Record<string, unknown> | undefined;
const message = data?.message;
if (Array.isArray(message)) return message.join(", ");
if (typeof message === "string") return message;
const violations = data?.violations;
if (Array.isArray(violations)) return violations.join(", ");
}
return fallback;
};
const formatCountdown = (expiresAt?: string | null) => {
if (!expiresAt) return null;
const diff = new Date(expiresAt).getTime() - Date.now();
if (diff <= 0) return "Hold expired";
const hours = Math.floor(diff / 3600000);
const mins = Math.floor((diff % 3600000) / 60000);
return `${hours}h ${mins}m remaining`;
};
export function AllocateBookingWizard({
booking,
opened,
onClose,
initialBookingIds,
}: {
booking: BookingDetail;
opened: boolean;
onClose: () => void;
initialBookingIds?: string[];
}) {
const navigate = useNavigate();
const { toast } = useToast();
const bookingFreightType = booking.freightType as FreightType;
const [activeStep, setActiveStep] = useState(0);
const [scheduleMode, setScheduleMode] = useState<"existing" | "new">("existing");
const [selectedScheduleId, setSelectedScheduleId] = useState<string | null>(null);
const [routeId, setRouteId] = useState("");
const scheduleDate = booking.scheduledDate;
const [locomotiveId, setLocomotiveId] = useState("");
const [extraBookingIds, setExtraBookingIds] = useState<string[]>([]);
const [forceAssign, setForceAssign] = useState(false);
const [previewResult, setPreviewResult] = useState<TrainSchedulePreviewResponse | null>(null);
const [containerPlacements, setContainerPlacements] = useState<ContainerPlacement[]>([]);
const [assignedSchedule, setAssignedSchedule] = useState<TrainScheduleDetail | null>(null);
const [reschedulePlan, setReschedulePlan] = useState<ReschedulePlan | null>(null);
const [confirmPreempt, setConfirmPreempt] = useState(false);
const [allocationComplete, setAllocationComplete] = useState(false);
const originId = booking.originYard?.id;
const destinationId = booking.destinationYard?.id;
const eligibleFilters = useMemo(
() => ({
originStationId: originId,
destinationStationId: destinationId,
}),
[originId, destinationId],
);
const eligibleQuery = useEligibleBookings(eligibleFilters, opened);
const schedulesQuery = useScheduleList();
const routesQuery = useRoutes();
const locomotivesQuery = useAvailableLocomotives();
const { create, preview, assign, finalize } = useScheduleMutations(selectedScheduleId ?? undefined);
const matchingSchedules = useMemo(
() =>
(schedulesQuery.data ?? []).filter(
(s: TrainScheduleListItem) =>
s.status === "DRAFT" &&
(!s.freightType || s.freightType === "MIXED" || s.freightType === bookingFreightType),
),
[schedulesQuery.data, bookingFreightType],
);
const allBookingIds = useMemo(
() => [booking.id, ...extraBookingIds.filter((id) => id !== booking.id)],
[booking.id, extraBookingIds],
);
const containerUnits = previewResult?.containerUnits ?? [];
const containerSlots = previewResult?.containerSlotSequenceNos ?? [];
const hasContainerStep = useMemo(
() =>
shouldShowContainerPlacementStep({
containerUnitCount: containerUnits.length,
scheduleFreightType: booking.freightType,
bookingFreightTypes: [
booking.freightType,
...(eligibleQuery.data?.items ?? [])
.filter((item) => allBookingIds.includes(item.id))
.map((item) => item.freightType),
],
}),
[
allBookingIds,
booking.freightType,
containerUnits.length,
eligibleQuery.data?.items,
],
);
const previewFreightType = previewResult?.summary?.freightMode as FreightType | undefined;
const finalizeStep = hasContainerStep ? 3 : 2;
const stepLabels = [
"Bookings",
"Wagon plan",
...(hasContainerStep ? ["Containers"] : []),
"Finalize",
];
useEffect(() => {
if (!opened) {
setActiveStep(0);
setPreviewResult(null);
setAssignedSchedule(null);
setExtraBookingIds([]);
setContainerPlacements([]);
setReschedulePlan(null);
setConfirmPreempt(false);
setAllocationComplete(false);
return;
}
if (initialBookingIds?.length) {
setExtraBookingIds(initialBookingIds.filter((id) => id !== booking.id));
}
}, [opened, booking.id, initialBookingIds]);
useEffect(() => {
if (matchingSchedules.length && !selectedScheduleId) {
setSelectedScheduleId(matchingSchedules[0].id);
}
}, [matchingSchedules, selectedScheduleId]);
const savedPlacementsFromSchedule = useMemo(
() =>
assignedSchedule?.trainSet?.wagons
? placementsFromScheduleWagons(assignedSchedule.trainSet.wagons)
: [],
[assignedSchedule?.trainSet?.wagons],
);
useEffect(() => {
if (!containerUnits.length || !containerSlots.length) return;
setContainerPlacements((current) => {
if (current.length && current.some((p) => p.containerNumber?.trim())) {
return current;
}
const autoFilled = autoFillPlacements(containerUnits, containerSlots);
if (savedPlacementsFromSchedule.length) {
return mergePlacementsWithSaved(autoFilled, savedPlacementsFromSchedule);
}
if (current.length) return current;
return autoFilled;
});
}, [containerUnits, containerSlots, savedPlacementsFromSchedule]);
const activeRoutes = useMemo(
() => (routesQuery.data ?? []).filter((r) => r.isActive),
[routesQuery.data],
);
const ensureSchedule = async (): Promise<string> => {
if (scheduleMode === "existing" && selectedScheduleId) return selectedScheduleId;
if (!routeId || !scheduleDate || !locomotiveId) {
throw new Error("Select route, date, and locomotive");
}
const created = await create.mutateAsync({
payload: { routeId, scheduleDate, locomotiveId },
});
setSelectedScheduleId(created.id);
return created.id;
};
const handlePreview = async () => {
if (!originId || !destinationId) {
toast({ title: "Booking missing origin or destination", variant: "destructive" });
return;
}
try {
const targetScheduleId =
scheduleMode === "existing" ? (selectedScheduleId ?? undefined) : undefined;
const result = await preview.mutateAsync({
payload: {
bookingIds: allBookingIds,
scheduleDate,
originStationId: originId,
destinationStationId: destinationId,
targetScheduleId,
},
});
setPreviewResult(result);
if (booking.isGovernment && targetScheduleId) {
const plan = (await trainSchedulingService.previewReschedule(targetScheduleId, {
incomingBookingIds: allBookingIds,
trigger: "GOVERNMENT_PREEMPT",
})) as ReschedulePlan;
setReschedulePlan(plan);
} else {
setReschedulePlan(null);
}
if (result.containerUnits?.length && result.containerSlotSequenceNos?.length) {
const autoFilled = autoFillPlacements(
result.containerUnits,
result.containerSlotSequenceNos,
);
setContainerPlacements(autoFilled);
}
setActiveStep(1);
} catch (err) {
toast({
title: "Preview failed",
description: parseError(err, "Could not preview"),
variant: "destructive",
});
}
};
const handleAssign = async () => {
if (hasContainerStep) {
const issues = validateLocalPlacements(containerUnits, containerPlacements);
if (issues.length) {
toast({
title: "Complete container assignments",
description: issues.join(", "),
variant: "destructive",
});
return;
}
}
if (reschedulePlan?.displaced.length && !confirmPreempt) {
toast({
title: "Confirm displacement",
description: "Acknowledge displaced bookings before assigning",
variant: "destructive",
});
return;
}
try {
const scheduleId = await ensureSchedule();
let result: TrainScheduleDetail;
if (reschedulePlan?.displaced.length) {
const executed = await trainSchedulingService.executeReschedule(scheduleId, {
incomingBookingIds: allBookingIds,
trigger: "GOVERNMENT_PREEMPT",
finalBookingIds: reschedulePlan.finalBookingIds,
displacedBookingIds: reschedulePlan.displaced.map((b) => b.id),
});
result = (executed as { schedule: TrainScheduleDetail }).schedule;
} else {
result = await assign.mutateAsync({
id: scheduleId,
freightType: previewFreightType,
payload: {
bookingIds: allBookingIds,
forceAssign,
containerPlacements: hasContainerStep ? containerPlacements : undefined,
},
});
}
setAssignedSchedule(result);
const saved = result.trainSet?.wagons
? placementsFromScheduleWagons(result.trainSet.wagons)
: [];
if (saved.length) {
setContainerPlacements(saved);
}
setActiveStep(finalizeStep);
toast({ title: "Bookings assigned — wagons auto-pinned" });
if (result.deferredBookings?.length) {
toast({
title: "Partial assignment",
description: `${result.deferredBookings.length} booking(s) deferred to next train`,
});
}
} catch (err) {
toast({
title: "Assign failed",
description: parseError(err, "Could not assign"),
variant: "destructive",
});
}
};
const handleFinalize = async () => {
const scheduleId = assignedSchedule?.id ?? selectedScheduleId;
if (!scheduleId) return;
try {
const finalized = await finalize.mutateAsync(scheduleId);
setAssignedSchedule(finalized);
setAllocationComplete(true);
toast({ title: "Schedule finalized — booking allocated" });
} catch (err) {
toast({
title: "Finalize failed",
description: parseError(err, "Could not finalize schedule"),
variant: "destructive",
});
}
};
const holdCountdown = formatCountdown(booking.holdExpiresAt);
const stepDescription =
activeStep === 0
? "Select & preview"
: activeStep === 1
? "Allocations"
: hasContainerStep && activeStep === 2
? "Map units"
: "Depart";
const stepIcon =
activeStep === 0
? "package"
: activeStep === 1
? "layout"
: hasContainerStep && activeStep === 2
? "container"
: "check";
return (
<Modal
opened={opened}
onClose={onClose}
title={<Text fw={600}>Allocate booking {booking.reference}</Text>}
size="90%"
radius="xl"
centered
styles={{ content: { maxWidth: 1200 } }}
>
<Stack gap="lg">
<SchedulingWorkflowHeader
title="Allocation workflow"
subtitle={`${booking.reference} · ${booking.originYard?.name ?? "Origin"}${booking.destinationYard?.name ?? "Destination"}`}
activeStep={activeStep}
totalSteps={stepLabels.length}
stepLabel={stepLabels[activeStep] ?? ""}
stepDescription={stepDescription}
stepIcon={stepIcon}
/>
<Stepper
active={activeStep}
onStepClick={setActiveStep}
color={schedulingWorkflow.stepper.color}
iconSize={schedulingWorkflow.stepper.iconSize}
size={schedulingWorkflow.stepper.size}
>
<Stepper.Step label="Bookings" description="Select & preview">
<Stack gap="md" mt="lg">
<Card withBorder padding="md" radius="xl">
<Stack gap="xs">
<Group justify="space-between">
<Text fw={600}>{booking.reference}</Text>
<SchedulingStatusBadge status={booking.schedulingStatus} />
</Group>
<Text size="sm" c="dimmed">
{booking.freightType} · {booking.cargoTotalWeightVgm}T
</Text>
<Text size="sm">
{booking.originYard?.name ?? "Origin"} {" "}
{booking.destinationYard?.name ?? "Destination"}
</Text>
{booking.freightType === "CONTAINER" && booking.bookingContainers?.length ? (
<Text size="sm" c="dimmed">
{booking.bookingContainers.map((c) => `${c.quantity}× container`).join(", ")}
</Text>
) : null}
{holdCountdown ? (
<Text size="sm" c={holdCountdown.includes("expired") ? "red" : "yellow"}>
Hold window: {holdCountdown}
</Text>
) : null}
</Stack>
</Card>
<Paper p="md" radius="xl" withBorder>
<Stack gap="md">
<Text fw={600} size="sm">
Train schedule
</Text>
<Radio.Group
value={scheduleMode}
onChange={(v) => setScheduleMode(v as "existing" | "new")}
>
<Stack gap="sm">
<Radio value="existing" label="Use existing draft schedule" />
<Radio value="new" label="Create new schedule" />
</Stack>
</Radio.Group>
{scheduleMode === "existing" ? (
<Select
label="Draft schedule"
data={matchingSchedules.map((s) => ({
value: s.id,
label: `${s.routeName ?? "Schedule"} · ${new Date(s.scheduleDate).toLocaleDateString()} · ${s.freightType ?? "MIXED"}`,
}))}
value={selectedScheduleId}
onChange={setSelectedScheduleId}
searchable
/>
) : (
<Stack gap="sm">
<Select
label="Route"
data={activeRoutes.map((r) => ({ value: r.id, label: r.name }))}
value={routeId || null}
onChange={(v) => setRouteId(v ?? "")}
searchable
/>
<Select
label="Locomotive"
data={(locomotivesQuery.data ?? []).map((l) => ({
value: l.id,
label: l.code,
}))}
value={locomotiveId || null}
onChange={(v) => setLocomotiveId(v ?? "")}
searchable
/>
</Stack>
)}
</Stack>
</Paper>
<ScheduleBookingsStep
assignedBookings={(assignedSchedule?.bookings ?? []).map((b) => ({
id: b.id,
reference: b.reference ?? b.id.slice(0, 8),
weightTons: b.weightTons,
}))}
eligibleItems={eligibleQuery.data?.items ?? []}
eligibleLoading={eligibleQuery.isLoading}
selectedIds={allBookingIds}
onSelectionChange={(ids) => {
setExtraBookingIds(ids.filter((id) => id !== booking.id));
}}
freightType={bookingFreightType}
/>
<Group align="center" wrap="wrap">
<Button loading={preview.isPending} onClick={handlePreview}>
Preview plan
</Button>
<Checkbox
label="Force assign (bypass hold/overweight warnings)"
checked={forceAssign}
onChange={(e) => setForceAssign(e.currentTarget.checked)}
/>
</Group>
{previewResult ? (
<Stack gap="sm">
<ScheduleWarningsAlert
violations={previewResult.violations}
warnings={previewResult.warnings}
/>
<FleetAvailabilitySummary
fleetAvailability={previewResult.fleetAvailability}
deferredBookings={previewResult.deferredBookings}
/>
<PreviewSummary summary={previewResult.summary} />
</Stack>
) : null}
</Stack>
</Stepper.Step>
<Stepper.Step label="Wagon plan" description="Allocations">
<Stack gap="md" mt="lg">
<ScheduleWarningsAlert
violations={previewResult?.violations}
warnings={previewResult?.warnings}
/>
{reschedulePlan?.displaced.length ? (
<Card withBorder padding="md" radius="xl">
<Stack gap="sm">
<Text fw={600} size="sm" c="orange">
Government preempt bookings to displace
</Text>
{reschedulePlan.displaced.map((b) => (
<Text key={b.id} size="sm">
{b.reference} (priority {b.priorityScore})
</Text>
))}
<Checkbox
label="I confirm displacing the bookings listed above"
checked={confirmPreempt}
onChange={(e) => setConfirmPreempt(e.currentTarget.checked)}
/>
</Stack>
</Card>
) : null}
<PreviewSummary summary={previewResult?.summary} />
<FleetAvailabilitySummary
fleetAvailability={previewResult?.fleetAvailability}
deferredBookings={previewResult?.deferredBookings}
/>
<WagonPlanGrid
wagonPlan={previewResult?.wagonPlan ?? []}
freightType={previewFreightType ?? bookingFreightType}
/>
<Group>
{!hasContainerStep ? (
<Button color="teal" loading={assign.isPending || create.isPending} onClick={handleAssign}>
Assign bookings
</Button>
) : (
<Button variant="light" onClick={() => setActiveStep(2)}>
Continue to containers
</Button>
)}
<Button variant="default" onClick={handlePreview}>
Refresh preview
</Button>
</Group>
</Stack>
</Stepper.Step>
{hasContainerStep ? (
<Stepper.Step label="Containers" description="Map units">
<Stack gap="md" mt="lg">
{!containerUnits.length ? (
<Paper p="md" radius="xl" withBorder bg="gray.0">
<Text size="sm" c="dimmed">
Run preview from the Bookings step to load container units for numbering.
</Text>
</Paper>
) : (
<ContainerPlacementGrid
units={containerUnits}
containerSlots={containerSlots}
placements={containerPlacements}
onChange={setContainerPlacements}
/>
)}
<Group>
<Button color="teal" loading={assign.isPending || create.isPending} onClick={handleAssign}>
Assign bookings
</Button>
<Button variant="light" onClick={() => setActiveStep(finalizeStep)}>
Skip to finalize
</Button>
</Group>
</Stack>
</Stepper.Step>
) : null}
<Stepper.Step label="Finalize" description="Depart">
<Stack gap="md" mt="lg">
{allocationComplete ? (
<Paper p="lg" radius="xl" withBorder bg="teal.0">
<Stack gap="md" align="center">
<CheckCircle2 size={40} color="var(--mantine-color-teal-7)" />
<Text fw={700} size="lg">
Allocation complete
</Text>
<Text size="sm" c="dimmed" ta="center">
Booking {booking.reference} is scheduled on train{" "}
{assignedSchedule?.trainSet?.locomotive?.code ?? "—"}.
</Text>
<Group>
<Button
color="teal"
onClick={() => {
onClose();
if (assignedSchedule?.id) {
navigate(
`/dashboard/operations/train-scheduling-v2/${assignedSchedule.id}`,
);
}
}}
>
View schedule
</Button>
<Button variant="default" onClick={onClose}>
Close
</Button>
</Group>
</Stack>
</Paper>
) : (
<>
<Paper p="md" radius="xl" withBorder bg="gray.0">
<Text size="sm" c="dimmed">
Finalize moves the schedule to SCHEDULED and completes the booking
allocation.
</Text>
</Paper>
<Group>
<Button color="teal" loading={finalize.isPending} onClick={handleFinalize}>
Finalize schedule
</Button>
</Group>
</>
)}
</Stack>
</Stepper.Step>
</Stepper>
</Stack>
</Modal>
);
}

View File

@@ -0,0 +1,202 @@
import { useMemo } from "react";
import {
Badge,
Button,
Card,
Group,
Paper,
Progress,
Select,
SimpleGrid,
Stack,
Text,
TextInput,
} from "@mantine/core";
import { CheckCircle2, Container } from "lucide-react";
import type { ContainerPlacement, ContainerUnitRow } from "@/types/trainScheduling";
import { autoFillPlacements, unitKey, validateLocalPlacements } from "./containerPlacement.util";
export function ContainerPlacementGrid({
units,
containerSlots,
placements,
onChange,
}: {
units: ContainerUnitRow[];
containerSlots: number[];
placements: ContainerPlacement[];
onChange: (placements: ContainerPlacement[]) => void;
}) {
const placementMap = useMemo(() => {
const map = new Map<string, ContainerPlacement>();
for (const placement of placements) {
map.set(unitKey(placement.bookingContainerId, placement.unitIndex), placement);
}
return map;
}, [placements]);
const issues = useMemo(() => validateLocalPlacements(units, placements), [units, placements]);
const completedCount = useMemo(
() =>
units.filter((unit) => {
const placement = placementMap.get(unitKey(unit.bookingContainerId, unit.unitIndex));
return placement?.sequenceNo && placement.containerNumber?.trim();
}).length,
[units, placementMap],
);
const slotOptions = containerSlots.map((seq) => ({
value: String(seq),
label: `Wagon #${seq}`,
}));
const updatePlacement = (unit: ContainerUnitRow, patch: Partial<ContainerPlacement>) => {
const key = unitKey(unit.bookingContainerId, unit.unitIndex);
const existing = placementMap.get(key);
const next: ContainerPlacement = {
bookingContainerId: unit.bookingContainerId,
unitIndex: unit.unitIndex,
sequenceNo: existing?.sequenceNo ?? containerSlots[0] ?? 1,
containerNumber: existing?.containerNumber,
sealNumber: existing?.sealNumber,
...patch,
};
onChange([
...placements.filter(
(p) => !(p.bookingContainerId === unit.bookingContainerId && p.unitIndex === unit.unitIndex),
),
next,
]);
};
if (!units.length) {
return (
<Text size="sm" c="dimmed">
No container units in this selection.
</Text>
);
}
const progress = units.length ? Math.round((completedCount / units.length) * 100) : 0;
return (
<Stack gap="md">
<Paper p="md" radius="xl" withBorder>
<Group justify="space-between" align="flex-start" wrap="wrap" gap="md">
<Stack gap={4}>
<Group gap="xs">
<Container size={18} />
<Text fw={600} size="sm">
Container assignment
</Text>
</Group>
<Text size="xs" c="dimmed">
Map each booking unit to a wagon slot and enter the container number. One wagon fits
either 1×40ft or 2×20ft containers.
</Text>
</Stack>
<Button
variant="light"
size="compact-sm"
onClick={() => onChange(autoFillPlacements(units, containerSlots))}
>
Auto-fill slots
</Button>
</Group>
<Stack gap={6} mt="md">
<Group justify="space-between">
<Text size="xs" c="dimmed">
{completedCount} of {units.length} units complete
</Text>
<Text size="xs" fw={500}>
{progress}%
</Text>
</Group>
<Progress
value={progress}
size="sm"
radius="xl"
color={issues.length ? "yellow" : "green"}
/>
</Stack>
</Paper>
{issues.length ? (
<Stack gap={6}>
{issues.map((issue) => (
<Badge key={issue} color="red" variant="light" size="sm" w="fit-content">
{issue}
</Badge>
))}
</Stack>
) : (
<Badge
color="green"
variant="light"
size="sm"
w="fit-content"
leftSection={<CheckCircle2 size={12} />}
>
All units mapped
</Badge>
)}
<SimpleGrid cols={{ base: 1, lg: 2 }} spacing="md">
{units.map((unit) => {
const key = unitKey(unit.bookingContainerId, unit.unitIndex);
const placement = placementMap.get(key);
const isComplete = placement?.sequenceNo && placement.containerNumber?.trim();
return (
<Card key={key} radius="xl" padding="md" withBorder>
<Stack gap="md">
<Group justify="space-between" align="flex-start">
<Stack gap={2}>
<Text size="sm" fw={600}>
{unit.bookingReference}
</Text>
<Text size="xs" c="dimmed">
{unit.label} · {unit.containerTypeCode} · {unit.grossWeightTons}T
</Text>
</Stack>
<Badge size="sm" variant="light" color={isComplete ? "green" : "gray"}>
{isComplete ? "Ready" : "Pending"}
</Badge>
</Group>
<SimpleGrid cols={{ base: 1, sm: 2 }} spacing="sm">
<Select
label="Wagon slot"
size="sm"
data={slotOptions}
value={placement?.sequenceNo ? String(placement.sequenceNo) : null}
onChange={(value) =>
updatePlacement(unit, { sequenceNo: Number(value ?? containerSlots[0]) })
}
placeholder="Select wagon"
searchable
/>
<TextInput
label="Container number"
size="sm"
placeholder="e.g. MSCU1234567"
value={placement?.containerNumber ?? ""}
onChange={(e) =>
updatePlacement(unit, {
containerNumber: e.currentTarget.value,
})
}
/>
</SimpleGrid>
</Stack>
</Card>
);
})}
</SimpleGrid>
</Stack>
);
}

View File

@@ -0,0 +1,248 @@
import { useMemo } from "react";
import { ArrowRight, Package } from "lucide-react";
import {
Accordion,
Badge,
Button,
Checkbox,
Group,
Loader,
Paper,
Stack,
Text,
} from "@mantine/core";
import { BookingPriorityBadge } from "@/components/bookings/BookingPriorityBadge";
import type { EligibleContainerBooking, FreightType } from "@/types/trainScheduling";
import { groupBookingsByThreeHourWindow } from "@/utils/groupBookingsByThreeHourWindow";
function EligibleBookingRow({
booking,
freightType,
selected,
onToggle,
}: {
booking: EligibleContainerBooking;
freightType?: FreightType;
selected: boolean;
onToggle: () => void;
}) {
const resolvedFreightType = booking.freightType ?? freightType;
const isBulk = resolvedFreightType === "BULK";
return (
<Group
align="flex-start"
wrap="nowrap"
p="sm"
style={{
border: `1px solid ${
selected ? "var(--mantine-color-green-3)" : "var(--mantine-color-gray-2)"
}`,
borderRadius: 12,
background: selected ? "var(--mantine-color-green-0)" : "white",
transition: "border-color 120ms ease, background 120ms ease",
}}
>
<Checkbox checked={selected} onChange={onToggle} mt={4} color="green" />
<Stack gap={4} style={{ flex: 1 }}>
<Group gap="xs" wrap="wrap">
<Package size={14} />
<Text fw={600} size="sm">
{booking.reference}
</Text>
{resolvedFreightType ? (
<Badge variant="outline" size="xs">
{resolvedFreightType}
</Badge>
) : null}
{booking.schedulingStatus ? (
<Badge variant="light" size="xs">
{booking.schedulingStatus}
</Badge>
) : null}
</Group>
<Text size="xs" c="dimmed">
{booking.customer}
</Text>
<Group gap={6}>
<Text size="xs">{booking.origin}</Text>
<ArrowRight size={12} />
<Text size="xs">{booking.destination}</Text>
</Group>
<Group gap="sm">
<BookingPriorityBadge score={booking.priorityScore ?? 0} />
<Text size="xs" c="dimmed">
{isBulk
? `${booking.weightTons}T`
: `${booking.quantity} × ${booking.containerType}`}
</Text>
{booking.preferredDepartureDate ? (
<Text size="xs" c="dimmed">
{new Date(booking.preferredDepartureDate).toLocaleString("en-GB", {
timeZone: "UTC",
day: "2-digit",
month: "short",
hour: "2-digit",
minute: "2-digit",
})}{" "}
UTC
</Text>
) : null}
</Group>
</Stack>
</Group>
);
}
export function EligibleBookingsPanel({
items,
isLoading,
selectedIds,
onSelectionChange,
assignedIds = [],
freightType,
}: {
items: EligibleContainerBooking[];
isLoading?: boolean;
selectedIds: string[];
onSelectionChange: (ids: string[]) => void;
assignedIds?: string[];
freightType?: FreightType;
}) {
const assignedSet = useMemo(() => new Set(assignedIds), [assignedIds]);
const availableItems = useMemo(
() => items.filter((b) => !assignedSet.has(b.id)),
[items, assignedSet],
);
const buckets = useMemo(
() => groupBookingsByThreeHourWindow(availableItems),
[availableItems],
);
const selectableIds = useMemo(() => {
return [...assignedIds, ...availableItems.map((b) => b.id)];
}, [availableItems, assignedIds]);
const toggle = (id: string) => {
if (selectedIds.includes(id)) {
onSelectionChange(selectedIds.filter((x) => x !== id));
} else {
onSelectionChange([...selectedIds, id]);
}
};
const toggleBucket = (bucketIds: string[], select: boolean) => {
if (select) {
const merged = new Set([...selectedIds, ...bucketIds]);
onSelectionChange([...merged]);
} else {
onSelectionChange(selectedIds.filter((id) => !bucketIds.includes(id)));
}
};
if (isLoading) {
return (
<Group justify="center" py="md">
<Loader size="sm" />
<Text size="sm" c="dimmed">
Loading eligible bookings
</Text>
</Group>
);
}
if (!items.length && !assignedIds.length) {
return (
<Paper p="lg" radius="lg" withBorder bg="gray.0">
<Text size="sm" c="dimmed" ta="center">
No eligible bookings for this corridor
</Text>
</Paper>
);
}
return (
<Stack gap="md">
<Group justify="space-between" wrap="wrap">
<Text size="sm" fw={500}>
Eligible bookings ({availableItems.length})
</Text>
<Group gap="sm">
<Button
variant="light"
size="compact-sm"
onClick={() => onSelectionChange(selectableIds)}
>
Select all
</Button>
<Button variant="subtle" size="compact-sm" onClick={() => onSelectionChange(assignedIds)}>
Clear
</Button>
</Group>
</Group>
{buckets.length > 0 ? (
<Accordion defaultValue={buckets[0]?.key} variant="separated" radius="lg">
{buckets.map((bucket) => {
const bucketIds = bucket.bookings.map((b) => b.id);
const selectedInBucket = bucketIds.filter((id) => selectedIds.includes(id));
const allSelected = bucketIds.length > 0 && selectedInBucket.length === bucketIds.length;
return (
<Accordion.Item key={bucket.key} value={bucket.key}>
<Accordion.Control>
<Group justify="space-between" wrap="nowrap" pr="md">
<Stack gap={2}>
<Text fw={600} size="sm">
{bucket.label}
</Text>
<Text size="xs" c="dimmed">
{bucket.bookings.length} booking
{bucket.bookings.length === 1 ? "" : "s"} · priority sorted
</Text>
</Stack>
<Group gap="xs" onClick={(e) => e.stopPropagation()}>
<Badge variant="light" color="green">
{selectedInBucket.length} selected
</Badge>
<Button
variant="subtle"
size="compact-xs"
onClick={(e) => {
e.stopPropagation();
toggleBucket(bucketIds, !allSelected);
}}
>
{allSelected ? "Deselect bucket" : "Select bucket"}
</Button>
</Group>
</Group>
</Accordion.Control>
<Accordion.Panel>
<Stack gap="sm">
{bucket.bookings.map((booking) => (
<EligibleBookingRow
key={booking.id}
booking={booking}
freightType={freightType}
selected={selectedIds.includes(booking.id)}
onToggle={() => toggle(booking.id)}
/>
))}
</Stack>
</Accordion.Panel>
</Accordion.Item>
);
})}
</Accordion>
) : (
<Text size="sm" c="dimmed">
No additional eligible bookings in this corridor.
</Text>
)}
</Stack>
);
}

View File

@@ -0,0 +1,135 @@
import {
Alert,
Badge,
Group,
Paper,
Progress,
SimpleGrid,
Stack,
Table,
Text,
} from "@mantine/core";
import { AlertTriangle, Train } from "lucide-react";
import type { DeferredBookingRow, FleetAvailabilityRow } from "@/types/trainScheduling";
export function FleetAvailabilitySummary({
fleetAvailability = [],
deferredBookings = [],
}: {
fleetAvailability?: FleetAvailabilityRow[];
deferredBookings?: DeferredBookingRow[];
}) {
if (!fleetAvailability.length && !deferredBookings.length) return null;
const totalNeeded = fleetAvailability.reduce((sum, row) => sum + row.needed, 0);
const totalAvailable = fleetAvailability.reduce((sum, row) => sum + row.available, 0);
const totalShortfall = fleetAvailability.reduce((sum, row) => sum + row.shortfall, 0);
const fillRate =
totalNeeded > 0 ? Math.round((Math.min(totalAvailable, totalNeeded) / totalNeeded) * 100) : 100;
return (
<Paper p="md" radius="xl" withBorder>
<Stack gap="md">
<Group justify="space-between" align="flex-start" wrap="wrap">
<Group gap="xs">
<Train size={18} />
<Stack gap={2}>
<Text fw={600} size="sm">
Fleet wagon availability
</Text>
<Text size="xs" c="dimmed">
Plan is capped to available physical wagons by type
</Text>
</Stack>
</Group>
<Badge variant="light" color={totalShortfall > 0 ? "yellow" : "green"}>
{fillRate}% fleet coverage
</Badge>
</Group>
{totalNeeded > 0 ? (
<Stack gap={6}>
<Group justify="space-between">
<Text size="xs" c="dimmed">
{Math.min(totalAvailable, totalNeeded)} of {totalNeeded} wagon slots can be filled
</Text>
</Group>
<Progress
value={fillRate}
size="sm"
radius="xl"
color={totalShortfall > 0 ? "yellow" : "green"}
/>
</Stack>
) : null}
{fleetAvailability.length > 0 ? (
<Table striped highlightOnHover withTableBorder>
<Table.Thead>
<Table.Tr>
<Table.Th>Wagon type</Table.Th>
<Table.Th>Needed</Table.Th>
<Table.Th>Available</Table.Th>
<Table.Th>Shortfall</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{fleetAvailability.map((row) => (
<Table.Tr key={row.wagonTypeId}>
<Table.Td>{row.wagonTypeCode}</Table.Td>
<Table.Td>{row.needed}</Table.Td>
<Table.Td>{row.available}</Table.Td>
<Table.Td>
{row.shortfall > 0 ? (
<Badge color="red" variant="light" size="sm">
{row.shortfall}
</Badge>
) : (
<Text size="sm" c="green">
0
</Text>
)}
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
) : null}
{totalShortfall > 0 || deferredBookings.length > 0 ? (
<Alert color="yellow" variant="light" radius="lg" icon={<AlertTriangle size={16} />}>
<Text size="sm">
Train will depart with available wagons only.
{deferredBookings.length
? ` ${deferredBookings.length} booking(s) will wait for the next train.`
: ""}
</Text>
</Alert>
) : null}
{deferredBookings.length > 0 ? (
<SimpleGrid cols={{ base: 1, md: 2 }} spacing="sm">
{deferredBookings.map((booking) => (
<Paper key={booking.id} p="sm" radius="lg" withBorder bg="gray.0">
<Group justify="space-between" align="flex-start" wrap="nowrap">
<Stack gap={2}>
<Text size="sm" fw={600}>
{booking.reference}
</Text>
<Text size="xs" c="dimmed">
{booking.reason}
</Text>
</Stack>
<Badge variant="light" color="orange" size="sm">
Next train
</Badge>
</Group>
</Paper>
))}
</SimpleGrid>
) : null}
</Stack>
</Paper>
);
}

View File

@@ -0,0 +1,207 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import {
Alert,
Badge,
Button,
Group,
Paper,
Progress,
Select,
SimpleGrid,
Stack,
Text,
ThemeIcon,
} from "@mantine/core";
import { AlertTriangle, Link2, Wand2 } from "lucide-react";
import { Freight } from "@edr/types";
import type { PinWagonAssignment, TrainScheduleDetail } from "@/types/trainScheduling";
import type { Wagon } from "@/services/wagon.service";
import { wagonMatchesScheduleDirection } from "@/utils/wagonAvailability";
import { autoFillWagonAssignments, countFilledSlots } from "./pinWagons.util";
export function PinWagonsForm({
schedule,
availableWagons,
isSubmitting,
onSubmit,
autoFillOnMount = true,
}: {
schedule: TrainScheduleDetail;
availableWagons: Wagon[];
isSubmitting?: boolean;
onSubmit: (assignments: PinWagonAssignment[]) => void;
autoFillOnMount?: boolean;
}) {
const slots = schedule.trainSet?.wagons ?? [];
const [assignments, setAssignments] = useState<Record<string, string>>({});
const wagonOptionsByType = useMemo(() => {
const map = new Map<string, Array<{ value: string; label: string }>>();
for (const wagon of availableWagons) {
const isPinnedOnSlot = slots.some((s) => s.physicalWagonId === wagon.id);
if (
!wagonMatchesScheduleDirection(wagon, schedule.direction, {
allowPinned: isPinnedOnSlot,
})
) {
continue;
}
if (wagon.status !== Freight.WagonStatus.Available && !isPinnedOnSlot) {
continue;
}
const typeId = wagon.wagonTypeId;
const list = map.get(typeId) ?? [];
list.push({ value: wagon.id, label: wagon.wagonNumber });
map.set(typeId, list);
}
return map;
}, [availableWagons, schedule.direction, slots]);
const runAutoFill = useCallback(
(preserveManual = false) => {
const existing = preserveManual ? assignments : {};
setAssignments(autoFillWagonAssignments(slots, wagonOptionsByType, existing));
},
[assignments, slots, wagonOptionsByType],
);
useEffect(() => {
if (!autoFillOnMount || !slots.length) return;
setAssignments(autoFillWagonAssignments(slots, wagonOptionsByType));
}, [schedule.id, slots, wagonOptionsByType, autoFillOnMount]);
const fillStats = useMemo(
() => countFilledSlots(slots, assignments),
[slots, assignments],
);
const progress =
fillStats.total > 0 ? Math.round((fillStats.filled / fillStats.total) * 100) : 0;
const handleSubmit = () => {
const payload: PinWagonAssignment[] = Object.entries(assignments)
.filter(([, wagonId]) => Boolean(wagonId))
.map(([trainSetWagonId, physicalWagonId]) => ({ trainSetWagonId, physicalWagonId }));
onSubmit(payload);
};
if (!slots.length) {
return (
<Text size="sm" c="dimmed">
Assign bookings first to create wagon slots.
</Text>
);
}
return (
<Stack gap="md">
<Paper p="md" radius="xl" withBorder>
<Group justify="space-between" align="flex-start" wrap="wrap" gap="md">
<Stack gap={4}>
<Group gap="xs">
<Link2 size={18} />
<Text fw={600} size="sm">
Pin physical wagons
</Text>
</Group>
<Text size="xs" c="dimmed">
Match each train slot to a fleet wagon. Slots are auto-filled when possible.
</Text>
</Stack>
<Button
variant="light"
size="compact-sm"
leftSection={<Wand2 size={14} />}
onClick={() => runAutoFill(false)}
>
Auto-fill all slots
</Button>
</Group>
<Stack gap={6} mt="md">
<Group justify="space-between">
<Text size="xs" c="dimmed">
{fillStats.filled} of {fillStats.total} slots filled
</Text>
<Badge variant="light" color={progress === 100 ? "teal" : "yellow"}>
{progress}%
</Badge>
</Group>
<Progress value={progress} size="sm" radius="xl" color={progress === 100 ? "teal" : "yellow"} />
</Stack>
</Paper>
{fillStats.unfilledSlotNumbers.length > 0 ? (
<Alert
color="yellow"
variant="light"
radius="lg"
icon={<AlertTriangle size={16} />}
title="Some slots could not be auto-filled"
>
<Text size="sm">
No matching fleet wagon for slot
{fillStats.unfilledSlotNumbers.length === 1 ? "" : "s"} #
{fillStats.unfilledSlotNumbers.join(", #")}. Select manually or add wagons to the fleet.
</Text>
</Alert>
) : null}
<SimpleGrid cols={{ base: 1, md: 2 }} spacing="md">
{slots.map((slot) => {
const typeId = slot.wagonType?.id ?? "";
const options =
wagonOptionsByType.get(typeId) ??
availableWagons.map((w) => ({
value: w.id,
label: w.wagonNumber,
}));
return (
<Paper key={slot.id} p="md" radius="lg" withBorder>
<Group align="flex-end" wrap="nowrap" gap="md">
<Stack gap={2} style={{ minWidth: 90 }}>
<Group gap={6}>
<ThemeIcon size="sm" radius="md" variant="light" color="teal">
<Text size="xs" fw={700}>
{slot.sequenceNo}
</Text>
</ThemeIcon>
<Text size="sm" fw={600}>
Slot #{slot.sequenceNo}
</Text>
</Group>
<Text size="xs" c="dimmed">
{slot.wagonType?.code ?? "—"} · {slot.capacityTons}T
</Text>
</Stack>
<Select
style={{ flex: 1 }}
placeholder="Select physical wagon"
data={options}
value={assignments[slot.id] ?? null}
onChange={(value) =>
setAssignments((current) => ({
...current,
[slot.id]: value ?? "",
}))
}
searchable
/>
</Group>
</Paper>
);
})}
</SimpleGrid>
<Group justify="flex-end">
<Button color="teal" loading={isSubmitting} onClick={handleSubmit}>
Pin wagons
</Button>
</Group>
</Stack>
);
}

View File

@@ -0,0 +1,76 @@
import { useState } from "react";
import { Button, Group, Modal, Stack, Text, TextInput, Textarea } from "@mantine/core";
import toast from "react-hot-toast";
import { trainSchedulingService } from "@/services/trainScheduling.service";
export function RescheduleTrainDialog({
scheduleId,
currentBookingIds,
opened,
onClose,
onComplete,
}: {
scheduleId: string;
currentBookingIds: string[];
opened: boolean;
onClose: () => void;
onComplete?: () => void;
}) {
const [newDepartureDate, setNewDepartureDate] = useState("");
const [reason, setReason] = useState("");
const [loading, setLoading] = useState(false);
const handleSubmit = async () => {
if (!newDepartureDate) {
toast.error("Select a new departure date");
return;
}
setLoading(true);
try {
await trainSchedulingService.maintenanceReschedule(scheduleId, {
incomingBookingIds: currentBookingIds,
newDepartureDate: new Date(newDepartureDate).toISOString(),
reason,
});
toast.success("Train rescheduled for maintenance");
onComplete?.();
onClose();
} catch {
toast.error("Reschedule failed");
} finally {
setLoading(false);
}
};
return (
<Modal opened={opened} onClose={onClose} title="Reschedule train (maintenance)" radius="lg">
<Stack gap="md">
<Text size="sm" c="dimmed">
Updates departure and rebalances bookings on this train. Displaced bookings return to
the operations queue when capacity is insufficient.
</Text>
<TextInput
label="New departure"
type="datetime-local"
value={newDepartureDate}
onChange={(e) => setNewDepartureDate(e.target.value)}
/>
<Textarea
label="Reason"
placeholder="e.g. Locomotive maintenance"
value={reason}
onChange={(e) => setReason(e.target.value)}
/>
<Group justify="flex-end">
<Button variant="default" onClick={onClose}>
Cancel
</Button>
<Button loading={loading} onClick={handleSubmit}>
Reschedule
</Button>
</Group>
</Stack>
</Modal>
);
}

View File

@@ -0,0 +1,138 @@
import { ArrowRight, Package, Train } from "lucide-react";
import {
Badge,
Button,
Group,
Paper,
Stack,
Tabs,
Text,
} from "@mantine/core";
import type { EligibleContainerBooking, FreightType } from "@/types/trainScheduling";
import { EligibleBookingsPanel } from "./EligibleBookingsPanel";
export type AssignedBookingRow = {
id: string;
reference: string;
weightTons?: number;
};
export function ScheduleBookingsStep({
assignedBookings,
eligibleItems,
eligibleLoading,
selectedIds,
onSelectionChange,
assignedIds,
freightType,
canRemove,
onRemove,
}: {
assignedBookings: AssignedBookingRow[];
eligibleItems: EligibleContainerBooking[];
eligibleLoading?: boolean;
selectedIds: string[];
onSelectionChange: (ids: string[]) => void;
assignedIds?: string[];
freightType?: FreightType;
canRemove?: boolean;
onRemove?: (bookingId: string) => void;
}) {
return (
<Paper p="md" radius="lg" withBorder style={{ borderColor: "var(--mantine-color-gray-2)" }}>
<Tabs
defaultValue={assignedBookings.length ? "on-train" : "add"}
radius="md"
variant="pills"
color="green"
>
<Tabs.List mb="md">
<Tabs.Tab
value="on-train"
leftSection={<Train size={14} />}
rightSection={
assignedBookings.length ? (
<Badge size="xs" variant="light" color="green" circle>
{assignedBookings.length}
</Badge>
) : undefined
}
>
On this train
</Tabs.Tab>
<Tabs.Tab value="add" leftSection={<Package size={14} />}>
Add bookings
</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value="on-train">
{assignedBookings.length ? (
<Stack gap="sm">
{assignedBookings.map((booking) => (
<Group
key={booking.id}
justify="space-between"
p="sm"
style={{
border: "1px solid var(--mantine-color-green-2)",
borderRadius: 12,
background: "var(--mantine-color-green-0)",
}}
>
<Stack gap={4}>
<Group gap="xs">
<Text fw={600} size="sm">
{booking.reference}
</Text>
{booking.weightTons != null ? (
<Badge variant="outline" size="xs" color="green">
{booking.weightTons}T
</Badge>
) : null}
</Group>
<Group gap={6}>
<Text size="xs" c="dimmed">
Assigned to this consist
</Text>
<ArrowRight size={12} />
<Text size="xs" c="green.7" fw={500}>
Ready for wagon plan
</Text>
</Group>
</Stack>
{canRemove && onRemove ? (
<Button
variant="subtle"
color="red"
size="compact-xs"
onClick={() => onRemove(booking.id)}
>
Remove
</Button>
) : null}
</Group>
))}
</Stack>
) : (
<Text size="sm" c="dimmed" ta="center" py="lg">
No bookings on this train yet. Use the Add bookings tab to select eligible cargo.
</Text>
)}
</Tabs.Panel>
<Tabs.Panel value="add">
<EligibleBookingsPanel
items={eligibleItems}
isLoading={eligibleLoading}
selectedIds={selectedIds}
onSelectionChange={onSelectionChange}
assignedIds={assignedIds}
freightType={freightType}
/>
</Tabs.Panel>
</Tabs>
</Paper>
);
}

View File

@@ -0,0 +1,44 @@
import { Badge } from "@mantine/core";
const STATUS_COLORS: Record<string, string> = {
DRAFT: "gray",
SCHEDULED: "blue",
DISPATCHED: "green",
ARRIVED: "teal",
CANCELLED: "red",
};
export function ScheduleStatusBadge({ status }: { status: string }) {
return (
<Badge variant="light" color={STATUS_COLORS[status] ?? "gray"} size="sm">
{status}
</Badge>
);
}
export function FreightTypeBadge({ freightType }: { freightType?: string | null }) {
if (!freightType) return <Badge variant="light" color="gray" size="sm"></Badge>;
const color =
freightType === "BULK" ? "orange" : freightType === "MIXED" ? "grape" : "cyan";
return (
<Badge variant="light" color={color} size="sm">
{freightType}
</Badge>
);
}
export function SchedulingStatusBadge({ status }: { status?: string | null }) {
if (!status) return null;
const colors: Record<string, string> = {
NOT_SCHEDULED: "gray",
HOLDING: "yellow",
ELIGIBLE: "blue",
SCHEDULED: "indigo",
DISPATCHED: "green",
};
return (
<Badge variant="light" color={colors[status] ?? "gray"} size="sm">
{status.replace(/_/g, " ")}
</Badge>
);
}

View File

@@ -0,0 +1,75 @@
import { Alert, List, Paper, SimpleGrid, Stack, Text } from "@mantine/core";
import { AlertTriangle, XCircle } from "lucide-react";
export function ScheduleWarningsAlert({
violations = [],
warnings = [],
}: {
violations?: string[];
warnings?: string[];
}) {
if (!violations.length && !warnings.length) return null;
return (
<Stack gap="sm">
{violations.length > 0 ? (
<Alert color="red" radius="xl" icon={<XCircle size={16} />} title="Violations">
<List size="sm" spacing={4}>
{violations.map((v) => (
<List.Item key={v}>{v}</List.Item>
))}
</List>
</Alert>
) : null}
{warnings.length > 0 ? (
<Alert color="yellow" radius="xl" icon={<AlertTriangle size={16} />} title="Warnings">
<List size="sm" spacing={4}>
{warnings.map((w) => (
<List.Item key={w}>{w}</List.Item>
))}
</List>
</Alert>
) : null}
</Stack>
);
}
export function PreviewSummary({
summary,
}: {
summary?: {
totalBookings: number;
totalWeightTons: number;
wagonType: string;
wagonsNeeded: number;
totalLengthMeters: number;
};
}) {
if (!summary) return null;
const stats = [
{ label: "Bookings", value: String(summary.totalBookings) },
{ label: "Wagons", value: String(summary.wagonsNeeded) },
{ label: "Wagon type", value: summary.wagonType },
{ label: "Total weight", value: `${summary.totalWeightTons}T` },
{ label: "Train length", value: `${summary.totalLengthMeters}m` },
];
return (
<Paper p="md" radius="xl" withBorder bg="green.0">
<Text size="sm" fw={600} mb="sm">
Plan summary
</Text>
<SimpleGrid cols={{ base: 2, sm: 3, md: 5 }} spacing="sm">
{stats.map((stat) => (
<Stack key={stat.label} gap={2}>
<Text size="xs" c="dimmed" tt="uppercase">
{stat.label}
</Text>
<Text size="sm" fw={600}>
{stat.value}
</Text>
</Stack>
))}
</SimpleGrid>
</Paper>
);
}

View File

@@ -0,0 +1,90 @@
import { Badge, Group, Paper, Progress, Stack, Text, ThemeIcon } from "@mantine/core";
import type { LucideIcon } from "lucide-react";
import {
CheckCircle2,
Container,
LayoutGrid,
Link2,
Package,
} from "lucide-react";
const stepIcons: Record<string, LucideIcon> = {
package: Package,
layout: LayoutGrid,
container: Container,
link: Link2,
check: CheckCircle2,
};
export function SchedulingWorkflowHeader({
title,
subtitle,
activeStep,
totalSteps,
stepLabel,
stepDescription,
stepIcon = "package",
}: {
title: string;
subtitle?: string;
activeStep: number;
totalSteps: number;
stepLabel: string;
stepDescription?: string;
stepIcon?: keyof typeof stepIcons;
}) {
const Icon = stepIcons[stepIcon] ?? Package;
const progress = totalSteps > 0 ? Math.round(((activeStep + 1) / totalSteps) * 100) : 0;
return (
<Paper
p="md"
radius="xl"
withBorder
style={{
background:
"linear-gradient(180deg, var(--mantine-color-white) 0%, var(--mantine-color-gray-0) 100%)",
}}
>
<Group justify="space-between" align="flex-start" wrap="wrap" gap="md">
<Group gap="md" align="flex-start">
<ThemeIcon size={42} radius="xl" variant="gradient" gradient={{ from: "green", to: "teal", deg: 135 }}>
<Icon size={20} />
</ThemeIcon>
<Stack gap={4}>
<Text fw={700} size="lg">
{title}
</Text>
{subtitle ? (
<Text size="sm" c="dimmed">
{subtitle}
</Text>
) : null}
</Stack>
</Group>
<Badge size="lg" variant="light" color="green">
Step {activeStep + 1} of {totalSteps}
</Badge>
</Group>
<Stack gap={6} mt="md">
<Group justify="space-between">
<Text size="sm" fw={600}>
{stepLabel}
{stepDescription ? (
<Text span c="dimmed" fw={400}>
{" "}
· {stepDescription}
</Text>
) : null}
</Text>
<Text size="xs" c="dimmed">
{progress}%
</Text>
</Group>
<Progress value={progress} size="sm" radius="xl" color="green" />
</Stack>
</Paper>
);
}

View File

@@ -0,0 +1,580 @@
import { useMemo } from "react";
import { Box, Group, Paper, Progress, Stack, Text, Tooltip } from "@mantine/core";
import { useElementSize } from "@mantine/hooks";
import { Box as BoxIcon, Container as ContainerIcon, Fuel, Gauge, TrainFront } from "lucide-react";
import { freightBrand } from "@/theme/freight-brand";
/**
* Visual train composition: a locomotive coupled to its wagons, drawn like a real
* consist. Long trains wrap into a serpentine (zig-zag) so the whole train stays on
* screen. Each wagon shows its load (container blocks or a bulk fill gauge), physical
* wagon number and tonnage.
*/
type DiagramWagonInput = {
sequenceNo: number;
capacityTons: number;
assignedWeightTons: number;
slotLoadType?: string | null;
wagonType?: { code?: string | null } | null;
wagonTypeCode?: string | null;
physicalWagonNumber?: string | null;
allocations?: Array<{
bookingReference?: string | null;
bookingId?: string;
loadType?: string | null;
containerItems?: Array<{ containerNumber?: string | null }> | null;
bulkLoad?: { weightTons?: number | null; cargoDescription?: string | null } | null;
}> | null;
};
type NormalizedWagon = {
sequenceNo: number;
capacityTons: number;
assignedWeightTons: number;
wagonTypeCode: string | null;
physicalWagonNumber: string | null;
isEmpty: boolean;
isBulk: boolean;
containerNumbers: string[];
bookingRefs: string[];
cargoDescription: string | null;
};
const CAR_WIDTH = 150; // car body + coupler footprint
function normalizeWagon(w: DiagramWagonInput, freightType?: string | null): NormalizedWagon {
const allocations = w.allocations ?? [];
const firstLoad = (
w.slotLoadType ??
allocations[0]?.loadType ??
freightType ??
""
)
.toString()
.toUpperCase();
const isBulk = firstLoad.includes("BULK");
const containerNumbers: string[] = [];
const bookingRefs: string[] = [];
let cargoDescription: string | null = null;
for (const alloc of allocations) {
if (alloc.bookingReference) bookingRefs.push(alloc.bookingReference);
for (const item of alloc.containerItems ?? []) {
containerNumbers.push(item.containerNumber?.trim() || "—");
}
if (alloc.bulkLoad?.cargoDescription) cargoDescription = alloc.bulkLoad.cargoDescription;
}
return {
sequenceNo: w.sequenceNo,
capacityTons: Number(w.capacityTons) || 0,
assignedWeightTons: Number(w.assignedWeightTons) || 0,
wagonTypeCode: w.wagonType?.code ?? w.wagonTypeCode ?? null,
physicalWagonNumber: w.physicalWagonNumber ?? null,
isEmpty: allocations.length === 0,
isBulk,
containerNumbers,
bookingRefs,
cargoDescription,
};
}
function chunk<T>(items: T[], size: number): T[][] {
if (size <= 0) return [items];
const rows: T[][] = [];
for (let i = 0; i < items.length; i += size) rows.push(items.slice(i, i + size));
return rows;
}
function Wheels({ count = 2, dark = false }: { count?: number; dark?: boolean }) {
return (
<Group gap={count > 2 ? 10 : 18} justify="center" wrap="nowrap" mt={2}>
{Array.from({ length: count }).map((_, i) => (
<Box
key={i}
style={{
width: 12,
height: 12,
borderRadius: "50%",
background: dark ? "#0f291b" : "var(--mantine-color-gray-7)",
border: "2px solid var(--mantine-color-gray-4)",
boxShadow: "inset 0 0 0 2px rgba(255,255,255,0.25)",
}}
/>
))}
</Group>
);
}
function Coupler() {
return (
<Box style={{ width: 16, height: 74, display: "flex", alignItems: "center", flexShrink: 0 }}>
<Box
style={{
width: "100%",
height: 6,
borderRadius: 3,
background:
"linear-gradient(90deg, var(--mantine-color-gray-4), var(--mantine-color-gray-6), var(--mantine-color-gray-4))",
}}
/>
</Box>
);
}
function LocomotiveCar({
code,
name,
maxPullWeightTons,
}: {
code: string;
name?: string | null;
maxPullWeightTons?: number | null;
}) {
return (
<Tooltip
label={`Locomotive ${code}${name ? ` · ${name}` : ""}${
maxPullWeightTons ? ` · pulls up to ${maxPullWeightTons}T` : ""
}`}
withArrow
>
<Box style={{ width: 134, flexShrink: 0 }}>
<Box
style={{
position: "relative",
height: 74,
borderRadius: "16px 22px 10px 10px",
background: freightBrand.gradient,
boxShadow: freightBrand.shadowSm,
border: "1px solid rgba(0,0,0,0.08)",
overflow: "hidden",
padding: "8px 10px",
color: "white",
}}
>
{/* cab windows */}
<Box
style={{
position: "absolute",
top: 8,
right: 10,
display: "flex",
gap: 4,
}}
>
<Box style={{ width: 14, height: 12, borderRadius: 3, background: "rgba(255,255,255,0.85)" }} />
<Box style={{ width: 14, height: 12, borderRadius: 3, background: "rgba(255,255,255,0.6)" }} />
</Box>
{/* headlight */}
<Box
style={{
position: "absolute",
bottom: 10,
right: 6,
width: 7,
height: 7,
borderRadius: "50%",
background: "#fde68a",
boxShadow: "0 0 8px 2px rgba(253,230,138,0.8)",
}}
/>
<Group gap={6} wrap="nowrap" align="center">
<TrainFront size={18} />
<Text size="sm" fw={800} style={{ letterSpacing: 0.3 }}>
{code}
</Text>
</Group>
<Text size="9px" mt={2} style={{ opacity: 0.85 }} lineClamp={1}>
{name ?? "Locomotive"}
</Text>
{maxPullWeightTons ? (
<Group gap={3} wrap="nowrap" mt={4} style={{ opacity: 0.95 }}>
<Gauge size={10} />
<Text size="9px" fw={600}>
{maxPullWeightTons}T pull
</Text>
</Group>
) : null}
</Box>
<Wheels count={3} dark />
<Text size="9px" ta="center" c="dimmed" mt={2} fw={700}>
HEAD
</Text>
</Box>
</Tooltip>
);
}
function WagonCar({ wagon }: { wagon: NormalizedWagon }) {
const utilization =
wagon.capacityTons > 0
? Math.min(100, Math.round((wagon.assignedWeightTons / wagon.capacityTons) * 100))
: 0;
const accent = wagon.isEmpty ? "gray" : wagon.isBulk ? "orange" : "cyan";
const accentVar = `var(--mantine-color-${accent}-6)`;
const tooltipLabel = wagon.isEmpty
? `Wagon #${wagon.sequenceNo} · empty / available`
: `Wagon #${wagon.sequenceNo}${wagon.physicalWagonNumber ? ` · ${wagon.physicalWagonNumber}` : ""}\n${
wagon.bookingRefs.length ? wagon.bookingRefs.join(", ") : ""
}${
wagon.containerNumbers.length ? `\nContainers: ${wagon.containerNumbers.join(", ")}` : ""
}${wagon.cargoDescription ? `\n${wagon.cargoDescription}` : ""}`;
// container blocks: one per container number (cap visual at 2 = TEU per wagon)
const blocks = wagon.containerNumbers.slice(0, 2);
return (
<Tooltip label={tooltipLabel} withArrow multiline maw={240} style={{ whiteSpace: "pre-line" }}>
<Box style={{ width: 134, flexShrink: 0 }}>
<Box
style={{
position: "relative",
height: 74,
borderRadius: 12,
background: wagon.isEmpty ? "var(--mantine-color-gray-0)" : "white",
border: wagon.isEmpty
? "1.5px dashed var(--mantine-color-gray-4)"
: "1px solid var(--mantine-color-gray-3)",
boxShadow: wagon.isEmpty ? "none" : "0 2px 8px rgba(15,41,27,0.06)",
overflow: "hidden",
display: "flex",
flexDirection: "column",
}}
>
{/* top accent strip */}
<Box
style={{
height: 4,
background: wagon.isEmpty
? "var(--mantine-color-gray-3)"
: `linear-gradient(90deg, ${accentVar}, var(--mantine-color-${accent}-4))`,
}}
/>
{/* header */}
<Group justify="space-between" px={8} pt={4} wrap="nowrap">
<Text size="10px" fw={800} c="gray.7">
#{wagon.sequenceNo}
</Text>
{wagon.isEmpty ? (
<Text size="9px" c="dimmed" fw={600}>
EMPTY
</Text>
) : (
<Group gap={3} wrap="nowrap">
{wagon.isBulk ? <Fuel size={11} color={accentVar} /> : <ContainerIcon size={11} color={accentVar} />}
<Text size="9px" fw={700} c={`${accent}.7`}>
{wagon.isBulk ? "BULK" : "CONT"}
</Text>
</Group>
)}
</Group>
{/* body */}
<Box style={{ flex: 1, padding: "4px 8px 6px", display: "flex", alignItems: "center" }}>
{wagon.isEmpty ? (
<Group gap={4} justify="center" style={{ width: "100%" }}>
<BoxIcon size={14} color="var(--mantine-color-gray-4)" />
<Text size="9px" c="dimmed">
Available
</Text>
</Group>
) : wagon.isBulk ? (
<Stack gap={3} style={{ width: "100%" }}>
<Box
style={{
height: 18,
borderRadius: 6,
background: "var(--mantine-color-orange-0)",
border: "1px solid var(--mantine-color-orange-2)",
overflow: "hidden",
position: "relative",
}}
>
<Box
style={{
position: "absolute",
inset: 0,
width: `${utilization}%`,
background: "linear-gradient(90deg, var(--mantine-color-orange-5), var(--mantine-color-orange-3))",
}}
/>
</Box>
<Text size="9px" c="dimmed" ta="center">
{wagon.assignedWeightTons}/{wagon.capacityTons}T
</Text>
</Stack>
) : (
<Group gap={4} justify="center" wrap="nowrap" style={{ width: "100%" }}>
{(blocks.length ? blocks : ["—"]).map((cn, i) => (
<Box
key={i}
style={{
flex: 1,
minWidth: 0,
height: 26,
borderRadius: 5,
background: "linear-gradient(180deg, var(--mantine-color-cyan-5), var(--mantine-color-cyan-7))",
border: "1px solid var(--mantine-color-cyan-8)",
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: "0 3px",
}}
>
<Text size="8px" fw={700} c="white" truncate>
{cn}
</Text>
</Box>
))}
</Group>
)}
</Box>
{/* footer */}
<Box
style={{
borderTop: "1px solid var(--mantine-color-gray-1)",
padding: "2px 8px",
background: wagon.isEmpty ? "transparent" : "var(--mantine-color-gray-0)",
}}
>
<Text size="8px" c="dimmed" truncate>
{wagon.physicalWagonNumber ?? wagon.wagonTypeCode ?? "Wagon"}
</Text>
</Box>
</Box>
<Wheels count={2} />
</Box>
</Tooltip>
);
}
export function TrainCompositionDiagram({
locomotive,
wagons,
freightType,
trainNumber,
totalLengthMeters,
}: {
locomotive?: { code?: string | null; name?: string | null; maxPullWeightTons?: number | null } | null;
wagons: DiagramWagonInput[];
freightType?: string | null;
trainNumber?: string | null;
totalLengthMeters?: number | null;
}) {
const { ref, width } = useElementSize();
const normalized = useMemo(
() => wagons.map((w) => normalizeWagon(w, freightType)),
[wagons, freightType],
);
const stats = useMemo(() => {
const assigned = normalized.filter((w) => !w.isEmpty).length;
const totalWeight = normalized.reduce((s, w) => s + w.assignedWeightTons, 0);
const totalCapacity = normalized.reduce((s, w) => s + w.capacityTons, 0);
return {
total: normalized.length,
assigned,
empty: normalized.length - assigned,
totalWeight: Math.round(totalWeight * 100) / 100,
totalCapacity,
pullUtil:
locomotive?.maxPullWeightTons && locomotive.maxPullWeightTons > 0
? Math.min(100, Math.round((totalWeight / locomotive.maxPullWeightTons) * 100))
: null,
};
}, [normalized, locomotive]);
// cars-per-row from measured width; locomotive counts as one car
const perRow = Math.max(1, Math.floor((width || CAR_WIDTH) / CAR_WIDTH));
const cars = useMemo(
() => [{ kind: "loco" as const }, ...normalized.map((w) => ({ kind: "wagon" as const, w }))],
[normalized],
);
const rows = useMemo(() => chunk(cars, perRow), [cars, perRow]);
if (!locomotive && !wagons.length) return null;
return (
<Paper
radius="lg"
p="lg"
withBorder
style={{
borderColor: "var(--mantine-color-gray-2)",
background:
"linear-gradient(180deg, var(--mantine-color-gray-0) 0%, white 40%)",
}}
>
<Stack gap="md">
{/* Header */}
<Group justify="space-between" align="flex-start" wrap="wrap" gap="sm">
<Group gap="sm" wrap="nowrap">
<Box
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: 38,
height: 38,
borderRadius: 10,
background: freightBrand.gradient,
color: "white",
}}
>
<TrainFront size={20} />
</Box>
<Stack gap={0}>
<Text fw={700}>Train composition</Text>
<Text size="xs" c="dimmed">
{trainNumber ? `${trainNumber} · ` : ""}
{stats.total} wagons · {stats.assigned} loaded · {stats.empty} empty
{totalLengthMeters ? ` · ${totalLengthMeters}m` : ""}
</Text>
</Stack>
</Group>
<Group gap="xs">
<LegendDot color="cyan" label="Container" />
<LegendDot color="orange" label="Bulk" />
<LegendDot color="gray" label="Empty" />
</Group>
</Group>
{/* Locomotive pull gauge */}
{stats.pullUtil != null ? (
<Box
p="xs"
style={{
borderRadius: 10,
background: "var(--mantine-color-green-0)",
border: "1px solid var(--mantine-color-green-1)",
}}
>
<Group justify="space-between" mb={4}>
<Text size="xs" fw={600} c="green.8">
Locomotive load · {stats.totalWeight}T of {locomotive?.maxPullWeightTons}T
</Text>
<Text size="xs" fw={700} c={stats.pullUtil > 95 ? "red.7" : "green.7"}>
{stats.pullUtil}%
</Text>
</Group>
<Progress
value={stats.pullUtil}
size="sm"
radius="xl"
color={stats.pullUtil > 95 ? "red" : stats.pullUtil > 80 ? "yellow" : "green"}
/>
</Box>
) : null}
{/* The train */}
<Box ref={ref} style={{ width: "100%" }}>
<Stack gap={0}>
{rows.map((row, rowIndex) => {
const reversed = rowIndex % 2 === 1;
const isLast = rowIndex === rows.length - 1;
// side where this row's track ends / turns down to the next row
const turnSide: "left" | "right" = rowIndex % 2 === 0 ? "right" : "left";
return (
<Box key={rowIndex}>
<Box style={{ position: "relative", paddingBottom: 6 }}>
{/* rail under the row */}
<Box
style={{
position: "absolute",
left: 4,
right: 4,
bottom: 8,
height: 4,
borderRadius: 2,
background:
"repeating-linear-gradient(90deg, var(--mantine-color-gray-5) 0 10px, var(--mantine-color-gray-3) 10px 16px)",
}}
/>
<Group
gap={0}
wrap="nowrap"
justify="flex-start"
style={{
flexDirection: reversed ? "row-reverse" : "row",
position: "relative",
}}
>
{row.map((car, carIndex) => (
<Group key={carIndex} gap={0} wrap="nowrap" style={{ flexDirection: reversed ? "row-reverse" : "row" }}>
{carIndex > 0 ? <Coupler /> : null}
{car.kind === "loco" ? (
locomotive ? (
<LocomotiveCar
code={locomotive.code ?? "LOCO"}
name={locomotive.name}
maxPullWeightTons={locomotive.maxPullWeightTons}
/>
) : null
) : (
<WagonCar wagon={car.w} />
)}
</Group>
))}
</Group>
</Box>
{/* serpentine turn connector to the next row */}
{!isLast ? (
<Box style={{ position: "relative", height: 16 }}>
<Box
style={{
position: "absolute",
top: -10,
height: 26,
width: 22,
borderBottom: "4px solid var(--mantine-color-gray-4)",
...(turnSide === "right"
? {
right: 4,
borderRight: "4px solid var(--mantine-color-gray-4)",
borderBottomRightRadius: 16,
}
: {
left: 4,
borderLeft: "4px solid var(--mantine-color-gray-4)",
borderBottomLeftRadius: 16,
}),
}}
/>
</Box>
) : null}
</Box>
);
})}
</Stack>
</Box>
</Stack>
</Paper>
);
}
function LegendDot({ color, label }: { color: string; label: string }) {
return (
<Group gap={5} wrap="nowrap">
<Box
style={{
width: 10,
height: 10,
borderRadius: 3,
background:
color === "gray"
? "var(--mantine-color-gray-2)"
: `var(--mantine-color-${color}-5)`,
border: color === "gray" ? "1.5px dashed var(--mantine-color-gray-4)" : "none",
}}
/>
<Text size="xs" c="dimmed">
{label}
</Text>
</Group>
);
}

View File

@@ -0,0 +1,185 @@
import { Badge, Card, Group, Progress, SimpleGrid, Stack, Text, ThemeIcon } from "@mantine/core";
import { Box, Package } from "lucide-react";
import type { TrainScheduleWagonAllocation, WagonPlanRow } from "@/types/trainScheduling";
type WagonSlot = (WagonPlanRow & { physicalWagonNumber?: string | null }) | {
sequenceNo: number;
capacityTons: number;
assignedWeightTons: number;
slotLoadType?: string;
wagonType?: { code: string } | null;
wagonTypeCode?: string;
physicalWagonNumber?: string | null;
allocations?: TrainScheduleWagonAllocation[] | Array<{
id?: string;
bookingId: string;
bookingReference?: string | null;
allocatedWeightTons: number;
loadType?: string | null;
containerItems?: Array<{ containerNumber: string | null; grossWeightTons?: number | null }>;
bulkLoad?: { weightTons: number; cargoDescription: string | null } | null;
}>;
};
function loadTypeColor(loadType: string | undefined, freightType?: string | null) {
const normalized = loadType?.toUpperCase() ?? "";
if (normalized.includes("BULK")) return "orange";
if (normalized.includes("CONTAINER")) return "cyan";
return freightType === "BULK" ? "orange" : "cyan";
}
function slotLabel(slot: WagonSlot, freightType?: string | null) {
if ("slotLoadType" in slot && slot.slotLoadType) return slot.slotLoadType;
const fromAlloc = slot.allocations?.[0]?.loadType?.toString().toUpperCase();
if (fromAlloc) return fromAlloc;
if (freightType === "MIXED") return "MIXED";
return freightType ?? "SLOT";
}
function wagonTypeLabel(slot: WagonSlot) {
if ("wagonType" in slot && slot.wagonType?.code) return slot.wagonType.code;
if ("wagonTypeCode" in slot && slot.wagonTypeCode) return slot.wagonTypeCode;
return null;
}
export function WagonPlanGrid({
wagonPlan,
freightType,
}: {
wagonPlan: WagonSlot[];
freightType?: string | null;
}) {
if (!wagonPlan?.length) {
return (
<Card radius="lg" padding="xl" withBorder bg="gray.0">
<Stack align="center" gap="sm">
<ThemeIcon size="lg" radius="xl" variant="light" color="gray">
<Package size={20} />
</ThemeIcon>
<Text size="sm" fw={500}>
No wagon plan yet
</Text>
<Text size="xs" c="dimmed" ta="center" maw={360}>
Select bookings and run <strong>Preview plan</strong> to generate wagon slots and
allocations.
</Text>
</Stack>
</Card>
);
}
const totalCapacity = wagonPlan.reduce((sum, w) => sum + w.capacityTons, 0);
const totalAssigned = wagonPlan.reduce((sum, w) => sum + w.assignedWeightTons, 0);
const usedSlots = wagonPlan.filter((w) => (w.allocations?.length ?? 0) > 0).length;
const isBulk = freightType === "BULK" || wagonPlan.every((w) => w.slotLoadType === "BULK" || (!w.slotLoadType && w.allocations?.[0]?.loadType === "Bulk"));
return (
<Stack gap="md">
<Group gap="lg">
<Text size="sm" c="dimmed">
<strong>{wagonPlan.length}</strong> wagons · <strong>{usedSlots}</strong> in use
</Text>
{isBulk ? (
<Text size="sm" c="dimmed">
Load: <strong>{totalAssigned}</strong> / {totalCapacity}T
</Text>
) : null}
</Group>
<SimpleGrid cols={{ base: 1, sm: 2, xl: 3 }} spacing="md">
{wagonPlan.map((wagon) => {
const seq = wagon.sequenceNo;
const capacity = wagon.capacityTons;
const assigned = wagon.assignedWeightTons;
const allocations = wagon.allocations ?? [];
const utilization = capacity > 0 ? Math.min(100, Math.round((assigned / capacity) * 100)) : 0;
const label = slotLabel(wagon, freightType);
const typeCode = wagonTypeLabel(wagon);
return (
<Card key={seq} radius="lg" padding="md" withBorder>
<Stack gap="sm">
<Group justify="space-between" align="flex-start" wrap="nowrap">
<Group gap="xs" wrap="nowrap">
<ThemeIcon size="md" radius="md" variant="light" color={loadTypeColor(label, freightType)}>
<Box size={16} />
</ThemeIcon>
<Stack gap={0}>
<Text fw={600} size="sm">
{wagon.physicalWagonNumber ?? `Wagon #${seq}`}
</Text>
<Text size="xs" c="dimmed">
{[typeCode, `Pos ${seq}`].filter(Boolean).join(" · ")}
</Text>
</Stack>
</Group>
<Badge variant="light" size="sm" color={loadTypeColor(label, freightType)}>
{label}
</Badge>
</Group>
{label === "BULK" ? (
<Stack gap={4}>
<Group justify="space-between">
<Text size="xs" c="dimmed">
Capacity
</Text>
<Text size="xs" fw={500}>
{assigned} / {capacity}T
</Text>
</Group>
<Progress
value={utilization}
size="sm"
radius="xl"
color={utilization > 95 ? "red" : utilization > 80 ? "yellow" : "green"}
/>
</Stack>
) : null}
<Stack gap={6}>
{allocations.length ? (
allocations.map((alloc, index) => (
<Card key={`${alloc.bookingId}-${index}`} padding="xs" radius="md" bg="gray.0">
<Stack gap={2}>
<Group justify="space-between" gap="xs">
<Text size="xs" fw={500} lineClamp={1}>
{alloc.bookingReference ?? alloc.bookingId}
</Text>
{label === "BULK" ? (
<Text size="xs" c="dimmed">
{alloc.allocatedWeightTons}T
</Text>
) : null}
</Group>
{"containerItems" in alloc && alloc.containerItems?.length ? (
<Text size="xs" c="dimmed">
{alloc.containerItems.length} container{alloc.containerItems.length > 1 ? "s" : ""}
</Text>
) : null}
{"bulkLoad" in alloc && alloc.bulkLoad ? (
<Text size="xs" c="dimmed" lineClamp={2}>
Bulk · {alloc.bulkLoad.weightTons}T
{alloc.bulkLoad.cargoDescription
? `${alloc.bulkLoad.cargoDescription}`
: ""}
</Text>
) : null}
</Stack>
</Card>
))
) : (
<Text size="xs" c="dimmed" fs="italic">
Empty slot
</Text>
)}
</Stack>
</Stack>
</Card>
);
})}
</SimpleGrid>
</Stack>
);
}

View File

@@ -0,0 +1,220 @@
import type { ReactNode } from "react";
import { Badge, Box, Collapse, Group, Stack, Text, UnstyledButton } from "@mantine/core";
import type { LucideIcon } from "lucide-react";
import { Check, ChevronDown, Lock } from "lucide-react";
import { freightBrand } from "@/theme/freight-brand";
export type WorkflowStepState = "complete" | "active" | "upcoming";
/**
* A single collapsible step in the scheduling workflow. Steps are stacked
* inside <WorkflowRail> which paints the continuous connector behind the
* status circles.
*/
export function WorkflowStep({
index,
icon: Icon,
title,
subtitle,
state,
open,
onToggle,
rightSlot,
locked = false,
children,
}: {
index: number;
icon: LucideIcon;
title: string;
subtitle?: string;
state: WorkflowStepState;
open: boolean;
onToggle: () => void;
rightSlot?: ReactNode;
locked?: boolean;
children: ReactNode;
}) {
const isComplete = state === "complete";
const isActive = state === "active";
const circle = (() => {
if (isComplete) {
return {
bg: freightBrand.primary,
color: "white",
border: freightBrand.primary,
shadow: `0 4px 10px ${freightBrand.ring}`,
};
}
if (isActive) {
return {
bg: "white",
color: freightBrand.primary,
border: freightBrand.primary,
shadow: `0 0 0 4px ${freightBrand.ring}`,
};
}
return {
bg: "var(--mantine-color-gray-1)",
color: "var(--mantine-color-gray-5)",
border: "var(--mantine-color-gray-3)",
shadow: "none",
};
})();
return (
<Group gap="md" align="stretch" wrap="nowrap">
{/* Status circle (sits above the rail) */}
<Box
style={{
width: 40,
flexShrink: 0,
display: "flex",
justifyContent: "center",
}}
>
<Box
style={{
width: 40,
height: 40,
borderRadius: "50%",
display: "flex",
alignItems: "center",
justifyContent: "center",
background: circle.bg,
color: circle.color,
border: `2px solid ${circle.border}`,
boxShadow: circle.shadow,
fontWeight: 700,
fontSize: 15,
transition: "all 150ms ease",
position: "relative",
zIndex: 1,
}}
>
{isComplete ? <Check size={20} /> : <Icon size={18} />}
</Box>
</Box>
{/* Step card */}
<Box
style={{
flex: 1,
minWidth: 0,
marginBottom: 4,
borderRadius: 16,
border: `1px solid ${
isActive ? freightBrand.mutedBorder : "var(--mantine-color-gray-2)"
}`,
background: isActive ? freightBrand.mutedBg : "white",
boxShadow: isActive ? `0 6px 20px ${freightBrand.ring}` : "none",
overflow: "hidden",
transition: "all 150ms ease",
}}
>
<UnstyledButton
onClick={onToggle}
style={{ display: "block", width: "100%", padding: "14px 18px" }}
>
<Group justify="space-between" wrap="nowrap" gap="sm">
<Stack gap={2} style={{ minWidth: 0 }}>
<Group gap={8} wrap="nowrap">
<Text
size="xs"
fw={700}
c={isComplete || isActive ? "green.7" : "dimmed"}
style={{ letterSpacing: 0.6 }}
>
STEP {index + 1}
</Text>
{isComplete ? (
<Badge size="xs" variant="light" color="green" radius="sm">
Done
</Badge>
) : null}
</Group>
<Text fw={700} size="md" lh={1.2} truncate>
{title}
</Text>
{subtitle ? (
<Text size="xs" c="dimmed" truncate>
{subtitle}
</Text>
) : null}
</Stack>
<Group gap="sm" wrap="nowrap" style={{ flexShrink: 0 }}>
{rightSlot}
<Box
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: 28,
height: 28,
borderRadius: 8,
background: open
? "var(--mantine-color-green-0)"
: "var(--mantine-color-gray-1)",
color: open
? "var(--mantine-color-green-7)"
: "var(--mantine-color-gray-6)",
}}
>
{locked ? (
<Lock size={14} />
) : (
<ChevronDown
size={16}
style={{
transform: open ? "rotate(180deg)" : "none",
transition: "transform 150ms ease",
}}
/>
)}
</Box>
</Group>
</Group>
</UnstyledButton>
<Collapse expanded={open}>
<Box
px="lg"
pb="lg"
pt={4}
style={{ borderTop: "1px solid var(--mantine-color-gray-1)" }}
>
<Box pt="md">{children}</Box>
</Box>
</Collapse>
</Box>
</Group>
);
}
/**
* Wraps a list of <WorkflowStep> and paints the continuous vertical rail that
* connects the status circles.
*/
export function WorkflowRail({ children }: { children: ReactNode }) {
return (
<Box style={{ position: "relative" }}>
{/* connector rail behind the circles (circle is 40px → center at 20) */}
<Box
style={{
position: "absolute",
left: 19,
top: 24,
bottom: 24,
width: 2,
background:
"linear-gradient(180deg, var(--mantine-color-green-3) 0%, var(--mantine-color-gray-3) 100%)",
borderRadius: 2,
pointerEvents: "none",
}}
/>
<Stack gap="md">{children}</Stack>
</Box>
);
}

View File

@@ -0,0 +1,260 @@
import { describe, it, expect } from 'vitest';
import { autoFillPlacements, unitKey, validateLocalPlacements } from './containerPlacement.util';
import type { ContainerUnitRow } from '@/types/trainScheduling';
function makeUnits(containerType: string, sizeFt: number, quantity: number): ContainerUnitRow[] {
const units: ContainerUnitRow[] = [];
const containersPerWagon = sizeFt >= 40 ? 1 : 2;
const wagonsPerUnit = sizeFt >= 40 ? 1 : 0.5;
for (let i = 0; i < quantity; i++) {
units.push({
bookingId: 'booking-1',
bookingReference: 'BKG-001',
bookingContainerId: 'bc-1',
unitIndex: i,
containerTypeId: 'ct-1',
containerTypeCode: containerType,
label: `${containerType} ${i + 1}/${quantity}`,
grossWeightTons: 25,
sizeFt,
wagonsPerUnit,
containersPerWagon,
teuSlots: sizeFt >= 40 ? 2 : 1,
});
}
return units;
}
describe('containerPlacement.util', () => {
describe('unitKey', () => {
it('creates unique keys for units', () => {
expect(unitKey('bc-1', 0)).toBe('bc-1:0');
expect(unitKey('bc-1', 1)).toBe('bc-1:1');
expect(unitKey('bc-2', 0)).toBe('bc-2:0');
});
});
describe('autoFillPlacements', () => {
it('returns empty array when no units or slots', () => {
expect(autoFillPlacements([], [1, 2, 3])).toEqual([]);
expect(autoFillPlacements(makeUnits('20GP', 20, 1), [])).toEqual([]);
});
it('places 2×20ft containers in 1 wagon slot', () => {
const units = makeUnits('20GP', 20, 2);
const slots = [1, 2, 3];
const placements = autoFillPlacements(units, slots);
expect(placements).toHaveLength(2);
// Both 20ft containers should be in slot 1
expect(placements[0]?.sequenceNo).toBe(1);
expect(placements[1]?.sequenceNo).toBe(1);
});
it('places 6×20ft containers in 3 wagon slots (2 per wagon)', () => {
const units = makeUnits('20GP', 20, 6);
const slots = [1, 2, 3, 4, 5];
const placements = autoFillPlacements(units, slots);
expect(placements).toHaveLength(6);
// Units 0,1 -> Slot 1
expect(placements[0]?.sequenceNo).toBe(1);
expect(placements[1]?.sequenceNo).toBe(1);
// Units 2,3 -> Slot 2
expect(placements[2]?.sequenceNo).toBe(2);
expect(placements[3]?.sequenceNo).toBe(2);
// Units 4,5 -> Slot 3
expect(placements[4]?.sequenceNo).toBe(3);
expect(placements[5]?.sequenceNo).toBe(3);
});
it('places 1×40ft container in 1 wagon slot', () => {
const units = makeUnits('40GP', 40, 1);
const slots = [1, 2, 3];
const placements = autoFillPlacements(units, slots);
expect(placements).toHaveLength(1);
expect(placements[0]?.sequenceNo).toBe(1);
});
it('places 3×40ft containers in 3 wagon slots (1 per wagon)', () => {
const units = makeUnits('40GP', 40, 3);
const slots = [1, 2, 3, 4, 5];
const placements = autoFillPlacements(units, slots);
expect(placements).toHaveLength(3);
// Each 40ft container gets its own slot
expect(placements[0]?.sequenceNo).toBe(1);
expect(placements[1]?.sequenceNo).toBe(2);
expect(placements[2]?.sequenceNo).toBe(3);
});
it('handles mixed 20ft and 40ft containers correctly', () => {
const units20 = makeUnits('20GP', 20, 2);
const units40 = makeUnits('40GP', 40, 1);
const units = [...units20, ...units40];
const slots = [1, 2, 3, 4, 5];
const placements = autoFillPlacements(units, slots);
expect(placements).toHaveLength(3);
// First two 20ft containers share slot 1
expect(placements[0]?.sequenceNo).toBe(1);
expect(placements[1]?.sequenceNo).toBe(1);
// 40ft container gets slot 2
expect(placements[2]?.sequenceNo).toBe(2);
});
it('never shares a wagon between a 40ft and a 20ft when the 40ft comes first', () => {
// Regression: a 40ft (2 TEU) must occupy its own wagon and never pair with a 20ft.
const units40 = makeUnits('40GP', 40, 1);
const units20 = makeUnits('20GP', 20, 2);
const units = [...units40, ...units20];
const slots = [1, 2, 3, 4];
const placements = autoFillPlacements(units, slots);
expect(placements).toHaveLength(3);
// 40ft alone on slot 1
expect(placements[0]?.sequenceNo).toBe(1);
// both 20ft together on slot 2 — NOT on slot 1 with the 40ft
expect(placements[1]?.sequenceNo).toBe(2);
expect(placements[2]?.sequenceNo).toBe(2);
});
it('falls back to last slot when running out of slots', () => {
const units = makeUnits('20GP', 20, 6);
const slots = [1, 2]; // Only 2 slots available
const placements = autoFillPlacements(units, slots);
expect(placements).toHaveLength(6);
// First 4 units fit in slots 1 and 2
expect(placements[0]?.sequenceNo).toBe(1);
expect(placements[1]?.sequenceNo).toBe(1);
expect(placements[2]?.sequenceNo).toBe(2);
expect(placements[3]?.sequenceNo).toBe(2);
// Remaining units fall back to last available slot (slot 2)
expect(placements[4]?.sequenceNo).toBe(2);
expect(placements[5]?.sequenceNo).toBe(2);
});
it('defaults to 2 containers per wagon when sizeFt is not provided', () => {
const units: ContainerUnitRow[] = [
{
bookingId: 'booking-1',
bookingReference: 'BKG-001',
bookingContainerId: 'bc-1',
unitIndex: 0,
containerTypeId: 'ct-1',
containerTypeCode: '20GP',
label: 'Container 1',
grossWeightTons: 25,
// sizeFt not provided, should default to 2 per wagon
},
{
bookingId: 'booking-1',
bookingReference: 'BKG-001',
bookingContainerId: 'bc-1',
unitIndex: 1,
containerTypeId: 'ct-1',
containerTypeCode: '20GP',
label: 'Container 2',
grossWeightTons: 25,
},
];
const slots = [1, 2, 3];
const placements = autoFillPlacements(units, slots);
expect(placements[0]?.sequenceNo).toBe(1);
expect(placements[1]?.sequenceNo).toBe(1);
});
it('uses 1 container per wagon for 40ft when sizeFt is 40', () => {
const units: ContainerUnitRow[] = [
{
bookingId: 'booking-1',
bookingReference: 'BKG-001',
bookingContainerId: 'bc-1',
unitIndex: 0,
containerTypeId: 'ct-1',
containerTypeCode: '40GP',
label: 'Container 1',
grossWeightTons: 25,
sizeFt: 40,
},
{
bookingId: 'booking-1',
bookingReference: 'BKG-001',
bookingContainerId: 'bc-1',
unitIndex: 1,
containerTypeId: 'ct-1',
containerTypeCode: '40GP',
label: 'Container 2',
grossWeightTons: 25,
sizeFt: 40,
},
];
const slots = [1, 2, 3];
const placements = autoFillPlacements(units, slots);
// Each 40ft container should get its own slot
expect(placements[0]?.sequenceNo).toBe(1);
expect(placements[1]?.sequenceNo).toBe(2);
});
});
describe('validateLocalPlacements', () => {
it('returns empty array for valid placements', () => {
const units = makeUnits('20GP', 20, 1);
const placements = [
{
bookingContainerId: 'bc-1',
unitIndex: 0,
sequenceNo: 1,
containerNumber: 'CNTR123',
},
];
expect(validateLocalPlacements(units, placements)).toEqual([]);
});
it('returns error for missing slot', () => {
const units = makeUnits('20GP', 20, 1);
const placements: ReturnType<typeof autoFillPlacements> = [];
const issues = validateLocalPlacements(units, placements);
expect(issues.some((i) => i.includes('Slot missing'))).toBe(true);
});
it('returns error for missing container number', () => {
const units = makeUnits('20GP', 20, 1);
const placements = [
{
bookingContainerId: 'bc-1',
unitIndex: 0,
sequenceNo: 1,
// No containerNumber or containerId
},
];
const issues = validateLocalPlacements(units, placements);
expect(issues.some((i) => i.includes('Enter a container number'))).toBe(true);
});
it('returns error for duplicate container numbers', () => {
const units = makeUnits('20GP', 20, 2);
const placements = [
{
bookingContainerId: 'bc-1',
unitIndex: 0,
sequenceNo: 1,
containerNumber: 'CNTR123',
},
{
bookingContainerId: 'bc-1',
unitIndex: 1,
sequenceNo: 1,
containerNumber: 'CNTR123', // Duplicate!
},
];
const issues = validateLocalPlacements(units, placements);
expect(issues.some((i) => i.includes('Duplicate container number'))).toBe(true);
});
});
});

View File

@@ -0,0 +1,133 @@
import type { ContainerPlacement, ContainerUnitRow } from "@/types/trainScheduling";
export function unitKey(bookingContainerId: string, unitIndex: number) {
return `${bookingContainerId}:${unitIndex}`;
}
type ScheduleWagonForPlacements = {
sequenceNo: number;
allocations?: Array<{
containerItems?: Array<{
bookingContainerId?: string | null;
positionOnWagon?: number | null;
containerId?: string | null;
containerNumber?: string | null;
}>;
}>;
};
export function placementsFromScheduleWagons(
wagons: ScheduleWagonForPlacements[],
): ContainerPlacement[] {
const placements: ContainerPlacement[] = [];
for (const wagon of wagons) {
for (const allocation of wagon.allocations ?? []) {
for (const containerItem of allocation.containerItems ?? []) {
if (containerItem.bookingContainerId && containerItem.positionOnWagon != null) {
placements.push({
bookingContainerId: containerItem.bookingContainerId,
unitIndex: containerItem.positionOnWagon - 1,
sequenceNo: wagon.sequenceNo,
containerNumber: containerItem.containerNumber ?? undefined,
});
}
}
}
}
return placements;
}
export function mergePlacementsWithSaved(
autoFilled: ContainerPlacement[],
saved: ContainerPlacement[],
): ContainerPlacement[] {
const savedMap = new Map(
saved.map((placement) => [unitKey(placement.bookingContainerId, placement.unitIndex), placement]),
);
return autoFilled.map((placement) => {
const existing = savedMap.get(unitKey(placement.bookingContainerId, placement.unitIndex));
if (existing?.containerNumber?.trim()) {
return {
...placement,
containerNumber: existing.containerNumber,
containerId: undefined,
sealNumber: existing.sealNumber,
};
}
return placement;
});
}
export function autoFillPlacements(
units: ContainerUnitRow[],
containerSlots: number[],
): ContainerPlacement[] {
if (!units.length || !containerSlots.length) return [];
const placements: ContainerPlacement[] = [];
// Pack by TEU: a wagon holds 2 TEU (one 40ft, or two 20ft). This MUST mirror the
// backend allocation (allocateContainersToSlots) so a placement's sequenceNo lands on
// the same wagon the booking is allocated to — and a 40ft never shares with a 20ft.
const MAX_TEU_PER_WAGON = 2;
let currentSlotIndex = 0;
let teuInCurrentSlot = 0;
for (const unit of units) {
const teu = unit.teuSlots ?? (unit.sizeFt && unit.sizeFt >= 40 ? 2 : 1);
if (teuInCurrentSlot > 0 && teuInCurrentSlot + teu > MAX_TEU_PER_WAGON) {
currentSlotIndex += 1;
teuInCurrentSlot = 0;
}
const sequenceNo =
containerSlots[Math.min(currentSlotIndex, containerSlots.length - 1)] ??
containerSlots[containerSlots.length - 1] ??
containerSlots[0];
placements.push({
bookingContainerId: unit.bookingContainerId,
unitIndex: unit.unitIndex,
sequenceNo,
containerNumber: unit.containerNumber ?? undefined,
});
teuInCurrentSlot += teu;
}
return placements;
}
export function validateLocalPlacements(
units: ContainerUnitRow[],
placements: ContainerPlacement[],
): string[] {
const issues: string[] = [];
const numbers = new Set<string>();
for (const unit of units) {
const placement = placements.find(
(p) =>
p.bookingContainerId === unit.bookingContainerId && p.unitIndex === unit.unitIndex,
);
if (!placement?.sequenceNo) {
issues.push(`Slot missing for ${unit.label}`);
continue;
}
if (!placement.containerNumber?.trim()) {
issues.push(`Enter a container number for ${unit.label}`);
}
if (placement.containerNumber?.trim()) {
const normalized = placement.containerNumber.trim().toUpperCase();
if (numbers.has(normalized)) {
issues.push(`Duplicate container number ${normalized}`);
}
numbers.add(normalized);
}
}
return issues;
}

View File

@@ -0,0 +1,56 @@
export interface WagonSlotForPin {
id: string;
sequenceNo: number;
physicalWagonId?: string | null;
wagonType?: { id: string } | null;
}
export function autoFillWagonAssignments(
slots: WagonSlotForPin[],
wagonOptionsByType: Map<string, Array<{ value: string; label: string }>>,
existingAssignments: Record<string, string> = {},
): Record<string, string> {
const next: Record<string, string> = {};
const assignedWagonIds = new Set<string>();
for (const slot of slots) {
const pinnedId = slot.physicalWagonId ?? existingAssignments[slot.id];
if (pinnedId) {
next[slot.id] = pinnedId;
assignedWagonIds.add(pinnedId);
}
}
for (const slot of slots) {
if (next[slot.id]) continue;
const typeId = slot.wagonType?.id ?? "";
const options = wagonOptionsByType.get(typeId) ?? [];
const availableWagon = options.find((option) => !assignedWagonIds.has(option.value));
if (availableWagon) {
next[slot.id] = availableWagon.value;
assignedWagonIds.add(availableWagon.value);
}
}
return next;
}
export function countFilledSlots(
slots: WagonSlotForPin[],
assignments: Record<string, string>,
): { filled: number; total: number; unfilledSlotNumbers: number[] } {
const unfilledSlotNumbers: number[] = [];
for (const slot of slots) {
if (!assignments[slot.id]) {
unfilledSlotNumbers.push(slot.sequenceNo);
}
}
return {
filled: slots.length - unfilledSlotNumbers.length,
total: slots.length,
unfilledSlotNumbers,
};
}

View File

@@ -0,0 +1,252 @@
import type { ReactNode } from "react";
import { Box, Group, Paper, Stack, Text } from "@mantine/core";
import type { LucideIcon } from "lucide-react";
import { MapPin } from "lucide-react";
import { freightBrand } from "@/theme/freight-brand";
/**
* Shared visual building blocks for the Train Scheduling V2 surfaces.
* Everything keys off the freight brand green so the list + detail pages
* read as one cohesive, premium product.
*/
export const scheduleBrand = {
/** Deep green → emerald hero wash used across scheduling surfaces. */
heroGradient: `linear-gradient(135deg, ${freightBrand.primaryDark} 0%, ${freightBrand.primary} 48%, ${freightBrand.primaryLight} 120%)`,
/** Soft tinted surface for cards on white backgrounds. */
softSurface: `linear-gradient(135deg, ${freightBrand.mutedBg} 0%, #ffffff 60%, var(--mantine-color-gray-0) 100%)`,
ring: freightBrand.ring,
shadow: freightBrand.shadow,
shadowSm: freightBrand.shadowSm,
mutedBorder: freightBrand.mutedBorder,
} as const;
const STATUS_META: Record<
string,
{ color: string; dot: string; label?: string }
> = {
DRAFT: { color: "gray", dot: "var(--mantine-color-gray-5)" },
SCHEDULED: { color: "green", dot: freightBrand.primary },
DISPATCHED: { color: "teal", dot: "var(--mantine-color-teal-6)" },
ARRIVED: { color: "blue", dot: "var(--mantine-color-blue-6)" },
CANCELLED: { color: "red", dot: "var(--mantine-color-red-6)" },
};
export function statusMeta(status: string) {
return STATUS_META[status] ?? STATUS_META.DRAFT;
}
/**
* Status pill with a leading status dot — clearer at a glance than a plain
* badge and consistent everywhere a schedule status appears.
*/
export function StatusPill({
status,
size = "sm",
}: {
status: string;
size?: "sm" | "md";
}) {
const meta = statusMeta(status);
const isMd = size === "md";
return (
<Group
gap={isMd ? 8 : 6}
wrap="nowrap"
style={{
display: "inline-flex",
padding: isMd ? "5px 12px" : "3px 10px",
borderRadius: 999,
background: `var(--mantine-color-${meta.color}-0)`,
border: `1px solid var(--mantine-color-${meta.color}-2)`,
}}
>
<Box
w={isMd ? 8 : 7}
h={isMd ? 8 : 7}
style={{
borderRadius: 999,
background: meta.dot,
boxShadow: `0 0 0 3px var(--mantine-color-${meta.color}-1)`,
flexShrink: 0,
}}
/>
<Text
size={isMd ? "sm" : "xs"}
fw={600}
c={`${meta.color}.8`}
style={{ letterSpacing: 0.2, lineHeight: 1 }}
>
{meta.label ?? status}
</Text>
</Group>
);
}
/**
* Compact metric tile used in hero strips. `onDark` flips colors for use on
* the green hero gradient.
*/
export function StatTile({
icon: Icon,
label,
value,
hint,
onDark = false,
accent = freightBrand.primary,
}: {
icon?: LucideIcon;
label: string;
value: ReactNode;
hint?: ReactNode;
onDark?: boolean;
accent?: string;
}) {
return (
<Paper
p="md"
radius="lg"
style={
onDark
? {
background: "rgba(255,255,255,0.12)",
border: "1px solid rgba(255,255,255,0.18)",
backdropFilter: "blur(6px)",
}
: {
background: "white",
border: "1px solid var(--mantine-color-gray-2)",
}
}
>
<Group gap="sm" wrap="nowrap" align="flex-start">
{Icon ? (
<Box
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: 36,
height: 36,
borderRadius: 10,
flexShrink: 0,
background: onDark ? "rgba(255,255,255,0.16)" : `${accent}1a`,
color: onDark ? "white" : accent,
}}
>
<Icon size={18} />
</Box>
) : null}
<Stack gap={2} style={{ minWidth: 0 }}>
<Text
size="xs"
fw={600}
tt="uppercase"
style={{ letterSpacing: 0.4 }}
c={onDark ? "rgba(255,255,255,0.75)" : "dimmed"}
>
{label}
</Text>
<Text
fw={700}
size="lg"
lh={1.1}
c={onDark ? "white" : undefined}
style={{ whiteSpace: "nowrap" }}
>
{value}
</Text>
{hint ? (
<Text size="xs" c={onDark ? "rgba(255,255,255,0.7)" : "dimmed"}>
{hint}
</Text>
) : null}
</Stack>
</Group>
</Paper>
);
}
/**
* Origin → destination corridor visual: two anchored stops joined by a rail
* line. `variant="compact"` is for dense table rows; `default` for cards.
*/
export function RouteCorridor({
origin,
destination,
variant = "default",
onDark = false,
}: {
origin?: string | null;
destination?: string | null;
variant?: "default" | "compact";
onDark?: boolean;
}) {
const compact = variant === "compact";
const dim = onDark ? "rgba(255,255,255,0.7)" : "var(--mantine-color-gray-5)";
const strong = onDark ? "white" : "var(--mantine-color-gray-8)";
const lineColor = onDark ? "rgba(255,255,255,0.4)" : "var(--mantine-color-gray-3)";
const accent = onDark ? "white" : freightBrand.primary;
return (
<Group gap={compact ? 6 : 8} wrap="nowrap" align="center" style={{ minWidth: 0 }}>
<Box
w={compact ? 7 : 9}
h={compact ? 7 : 9}
style={{
borderRadius: 999,
flexShrink: 0,
border: `2px solid ${accent}`,
background: onDark ? "transparent" : "white",
}}
/>
<Text
size={compact ? "sm" : "sm"}
fw={600}
c={strong}
style={{ whiteSpace: "nowrap" }}
>
{origin ?? "—"}
</Text>
<Box
style={{
flex: 1,
minWidth: compact ? 16 : 24,
height: 0,
borderTop: `2px dashed ${lineColor}`,
position: "relative",
}}
>
<MapPin
size={compact ? 11 : 13}
color={dim}
style={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
background: onDark ? "transparent" : "white",
}}
/>
</Box>
<Text
size={compact ? "sm" : "sm"}
fw={600}
c={strong}
style={{ whiteSpace: "nowrap" }}
>
{destination ?? "—"}
</Text>
<Box
w={compact ? 7 : 9}
h={compact ? 7 : 9}
style={{
borderRadius: 999,
flexShrink: 0,
background: accent,
}}
/>
</Group>
);
}

View File

@@ -0,0 +1,14 @@
import type { FreightType } from "@/types/trainScheduling";
const isContainerFreight = (freightType?: string | null) => freightType === "CONTAINER";
/** Show container number placement step when train includes container cargo. */
export function shouldShowContainerPlacementStep(params: {
containerUnitCount: number;
scheduleFreightType?: FreightType | string | null;
bookingFreightTypes: Array<FreightType | string | null | undefined>;
}): boolean {
if (params.containerUnitCount > 0) return true;
if (isContainerFreight(params.scheduleFreightType)) return true;
return params.bookingFreightTypes.some(isContainerFreight);
}

View File

@@ -0,0 +1,28 @@
import type { MantineTheme } from "@mantine/core";
export const schedulingWorkflow = {
stepper: {
color: "green" as const,
iconSize: 32,
size: "sm" as const,
},
card: {
radius: "xl" as const,
padding: "lg" as const,
withBorder: true,
},
heroGradient: (theme: MantineTheme) =>
`linear-gradient(135deg, ${theme.colors.green[0]} 0%, ${theme.white} 55%, ${theme.colors.gray[0]} 100%)`,
workflowGradient: (theme: MantineTheme) =>
`linear-gradient(180deg, ${theme.white} 0%, ${theme.colors.gray[0]} 100%)`,
accentColor: "green" as const,
successColor: "green" as const,
warningColor: "yellow" as const,
};
export const schedulingStepMeta = [
{ label: "Bookings", description: "Select & preview", icon: "package" },
{ label: "Wagon plan", description: "Allocations", icon: "layout" },
{ label: "Containers", description: "Map units", icon: "container" },
{ label: "Finalize", description: "Depart", icon: "check" },
] as const;

View File

@@ -1,19 +0,0 @@
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Train } from '@/services/trainService';
export function TrainDetailCard({ train }: { train: Train }) {
return (
<Card>
<CardHeader><CardTitle>{train.trainNumber || train.code} - {train.trainName || 'Unnamed'}</CardTitle></CardHeader>
<CardContent className="grid md:grid-cols-2 gap-4">
<div><span className="font-medium">Status:</span> {train.status}</div>
<div><span className="font-medium">Capacity:</span> {train.capacityTons} tons</div>
<div><span className="font-medium">Origin:</span> {train.originStationId || '-'}</div>
<div><span className="font-medium">Destination:</span> {train.destinationStationId || '-'}</div>
<div><span className="font-medium">Departure:</span> {train.departureTime ? new Date(train.departureTime).toLocaleString() : '-'}</div>
<div><span className="font-medium">Arrival:</span> {train.arrivalTime ? new Date(train.arrivalTime).toLocaleString() : '-'}</div>
{train.remarks && <div className="col-span-2"><span className="font-medium">Remarks:</span> {train.remarks}</div>}
</CardContent>
</Card>
);
}

View File

@@ -1,59 +0,0 @@
import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useCreateTrain, useUpdateTrain } from '@/hooks/useTrains';
import { useToast } from '@/hooks/use-toast';
interface TrainFormDialogProps {
trigger?: React.ReactNode;
train?: any;
onSuccess?: () => void;
}
export function TrainFormDialog({ trigger, train, onSuccess }: TrainFormDialogProps) {
const [open, setOpen] = useState(false);
const [form, setForm] = useState({ code: '', capacityTons: 0, trainNumber: '', trainName: '' });
const createTrain = useCreateTrain();
const updateTrain = useUpdateTrain();
const { toast } = useToast();
useEffect(() => {
if (train) setForm({
code: train.code,
capacityTons: train.capacityTons,
trainNumber: train.trainNumber || '',
trainName: train.trainName || '',
});
}, [train]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
if (train) await updateTrain.mutateAsync({ id: train.id, data: form });
else await createTrain.mutateAsync(form);
toast({ title: train ? 'Train updated' : 'Train created', description: `${form.code} saved.` });
setOpen(false);
onSuccess?.();
} catch {
toast({ title: 'Error', description: `Failed to ${train ? 'update' : 'create'} train.`, variant: 'destructive' });
}
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>{trigger || <Button>New Train</Button>}</DialogTrigger>
<DialogContent>
<DialogHeader><DialogTitle>{train ? 'Edit Train' : 'Create Train'}</DialogTitle></DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div><Label>Code*</Label><Input required value={form.code} onChange={e => setForm({...form, code: e.target.value})} /></div>
<div><Label>Capacity (tons)*</Label><Input type="number" required value={form.capacityTons} onChange={e => setForm({...form, capacityTons: parseFloat(e.target.value)})} /></div>
<div><Label>Train Number</Label><Input value={form.trainNumber} onChange={e => setForm({...form, trainNumber: e.target.value})} /></div>
<div><Label>Train Name</Label><Input value={form.trainName} onChange={e => setForm({...form, trainName: e.target.value})} /></div>
<Button type="submit" disabled={createTrain.isPending || updateTrain.isPending}>Save</Button>
</form>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,45 +0,0 @@
import { useTrains, useDeleteTrain } from '@/hooks/useTrains';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Eye, Trash2 } from 'lucide-react';
import { Link } from 'react-router-dom';
export function TrainsTable() {
const { data: trains, isLoading } = useTrains();
const deleteTrain = useDeleteTrain();
if (isLoading) return <div>Loading trains...</div>;
return (
<Table>
<TableHeader>
<TableRow>
<TableHead>Number</TableHead>
<TableHead>Name</TableHead>
<TableHead>Status</TableHead>
<TableHead>Capacity (tons)</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{trains?.map(train => (
<TableRow key={train.id}>
<TableCell>{train.trainNumber || train.code}</TableCell>
<TableCell>{train.trainName || '-'}</TableCell>
<TableCell><Badge variant="outline">{train.status}</Badge></TableCell>
<TableCell>{train.capacityTons}</TableCell>
<TableCell className="flex space-x-2">
<Link to={`/trains/${train.id}`}>
<Button variant="ghost" size="icon"><Eye className="h-4 w-4" /></Button>
</Link>
<Button variant="ghost" size="icon" onClick={() => deleteTrain.mutate(train.id)}>
<Trash2 className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
);
}

View File

@@ -1,53 +1,90 @@
import { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
// import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useWagons, useAssignWagonToTrain } from '@/hooks/useWagons';
import { useToast } from '@/hooks/use-toast';
import { Plus } from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@edr/ui-common';
import { useState } from "react";
import { Plus } from "lucide-react";
import { Button, Group, Modal, NumberInput, Select, Stack, Text } from "@mantine/core";
import { Freight } from "@edr/types";
import { useToast } from "@/hooks/use-toast";
import { useAssignWagonToTrain, useWagons } from "@/hooks/useWagons";
export function AssignWagonDialog({ trainId }: { trainId: string }) {
const [open, setOpen] = useState(false);
const [wagonId, setWagonId] = useState('');
const [sequence, setSequence] = useState<number>();
const [wagonId, setWagonId] = useState<string | null>(null);
const [sequence, setSequence] = useState<number | "">("");
const { data: wagons } = useWagons();
const assign = useAssignWagonToTrain();
const { toast } = useToast();
const available = wagons?.filter((w:any) => w.status === 'AVAILABLE' || !w.trainId);
const available = (wagons ?? []).filter(
(w) => w.status === Freight.WagonStatus.Available || !w.trainId,
);
const wagonOptions = available.map((w) => ({
value: w.id,
label: `${w.wagonNumber} (${w.readiness.replace("_", " ").toLowerCase()})`,
}));
const handleAssign = async () => {
if (!wagonId) return;
await assign.mutateAsync({ wagonId, trainId, sequenceNumber: sequence });
toast({ title: 'Assigned', description: 'Wagon attached to train.' });
setOpen(false);
try {
await assign.mutateAsync({
wagonId,
trainId,
sequenceNumber: sequence === "" ? undefined : Number(sequence),
});
toast({ title: "Wagon attached to train" });
setOpen(false);
setWagonId(null);
setSequence("");
} catch {
toast({ title: "Failed to assign wagon", variant: "destructive" });
}
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild><Button size="sm"><Plus className="mr-2 h-4 w-4" />Assign Wagon</Button></DialogTrigger>
<DialogContent>
<DialogHeader><DialogTitle>Assign Wagon to Train</DialogTitle></DialogHeader>
<div className="space-y-4">
<div>
<Label>Wagon</Label>
<Select value={wagonId} onValueChange={setWagonId}>
<SelectTrigger><SelectValue placeholder="Select wagon" /></SelectTrigger>
<SelectContent>
{available?.map((w:any) => <SelectItem key={w.id} value={w.id}>{w.wagonNumber}</SelectItem>)}
</SelectContent>
</Select>
</div>
<div>
<Label>Sequence (optional)</Label>
<Input type="number" value={sequence ?? ''} onChange={e => setSequence(parseInt(e.target.value) || undefined)} />
</div>
<Button onClick={handleAssign} disabled={assign.isPending}>Assign</Button>
</div>
</DialogContent>
</Dialog>
<>
<Button
color="green"
size="sm"
radius="lg"
leftSection={<Plus size={16} />}
onClick={() => setOpen(true)}
>
Assign wagon
</Button>
<Modal
opened={open}
onClose={() => setOpen(false)}
title={<Text fw={600}>Assign wagon to train</Text>}
radius="lg"
centered
>
<Stack gap="md">
<Select
label="Wagon"
placeholder="Select wagon"
data={wagonOptions}
value={wagonId}
onChange={setWagonId}
searchable
/>
<NumberInput
label="Sequence (optional)"
value={sequence}
onChange={(value) => setSequence(value === "" ? "" : Number(value))}
min={1}
/>
<Group justify="flex-end">
<Button variant="default" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button color="green" loading={assign.isPending} onClick={handleAssign}>
Assign
</Button>
</Group>
</Stack>
</Modal>
</>
);
}
}

View File

@@ -1,105 +0,0 @@
// src/components/wagons/WagonFormDialog.tsx
import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@edr/ui-common';
import { useWagonTypes } from '@/hooks/use-wagon-types';
import { useCreateWagon, useUpdateWagon } from '@/hooks/useWagons';
import { useToast } from '@/hooks/use-toast';
interface WagonFormDialogProps {
trigger?: React.ReactNode;
wagon?: any;
onSuccess?: () => void;
}
export function WagonFormDialog({ trigger, wagon, onSuccess }: WagonFormDialogProps) {
const [open, setOpen] = useState(false);
const [form, setForm] = useState({
wagonNumber: '',
wagonTypeId: '',
tareWeight: 0,
maxPayloadWeight: 0,
status: 'AVAILABLE',
notes: ''
});
const createWagon = useCreateWagon();
const updateWagon = useUpdateWagon();
const { data: wagonTypes = [], isLoading: wagonTypesLoading } = useWagonTypes();
const { toast } = useToast();
useEffect(() => {
if (wagon) setForm({
wagonNumber: wagon.wagonNumber,
wagonTypeId: wagon.wagonTypeId,
tareWeight: wagon.tareWeight,
maxPayloadWeight: wagon.maxPayloadWeight,
status: wagon.status,
notes: wagon.notes || ''
});
}, [wagon]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!form.wagonNumber || !form.wagonTypeId) {
toast({ title: 'Missing required field', description: 'Please select a wagon type.', variant: 'destructive' });
return;
}
try {
if (wagon) await updateWagon.mutateAsync({ id: wagon.id, data: form });
else await createWagon.mutateAsync(form);
toast({ title: wagon ? 'Wagon updated' : 'Wagon created', description: `${form.wagonNumber} saved.` });
setOpen(false);
onSuccess?.();
} catch {
toast({ title: 'Error', description: `Failed to ${wagon ? 'update' : 'create'} wagon.`, variant: 'destructive' });
}
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>{trigger || <Button>New Wagon</Button>}</DialogTrigger>
<DialogContent>
<DialogHeader><DialogTitle>{wagon ? 'Edit Wagon' : 'Create Wagon'}</DialogTitle></DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div><Label>Wagon Number*</Label><Input value={form.wagonNumber} onChange={e => setForm({...form, wagonNumber: e.target.value})} /></div>
<div>
<Label>Wagon Type*</Label>
<Select
value={form.wagonTypeId}
disabled={wagonTypesLoading}
onValueChange={(value) => {
const selectedType = wagonTypes.find((type: any) => type.id === value);
setForm((current) => ({
...current,
wagonTypeId: value,
maxPayloadWeight: current.maxPayloadWeight > 0
? current.maxPayloadWeight
: Number(selectedType?.capacityTons ?? current.maxPayloadWeight),
}));
}}
>
<SelectTrigger>
<SelectValue placeholder="Select wagon type" />
</SelectTrigger>
<SelectContent>
{wagonTypes.map((type: any) => (
<SelectItem key={type.id} value={type.id}>
{type.code} - {type.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div><Label>Tare Weight (kg)*</Label><Input type="number" value={form.tareWeight} onChange={e => setForm({...form, tareWeight: Number(e.target.value)})} /></div>
<div><Label>Max Payload (kg)*</Label><Input type="number" value={form.maxPayloadWeight} onChange={e => setForm({...form, maxPayloadWeight: Number(e.target.value)})} /></div>
<div><Label>Status</Label><Input value={form.status} onChange={e => setForm({...form, status: e.target.value})} /></div>
<div><Label>Notes</Label><Input value={form.notes} onChange={e => setForm({...form, notes: e.target.value})} /></div>
<Button type="submit" disabled={createWagon.isPending || updateWagon.isPending}>Save</Button>
</form>
</DialogContent>
</Dialog>
);
}

Some files were not shown because too many files have changed in this diff Show More