This commit is contained in:
natib21
2026-07-03 15:22:51 +00:00
209 changed files with 13780 additions and 2892 deletions

View File

@@ -62,10 +62,11 @@ export function GlClearanceUploadModal({
setLoading(true);
try {
if (isDo) {
const iso = vesselDate ? vesselDate.toISOString().slice(0, 10) : undefined;
if (isBooking) {
await bookingsService.uploadDeliveryOrder(entityId, file);
await bookingsService.uploadDeliveryOrder(entityId, file, iso);
} else {
await contractsService.uploadDeliveryOrder(entityId, file);
await contractsService.uploadDeliveryOrder(entityId, file, iso);
}
toast.success(replaceMode ? "Delivery Order updated" : "Delivery Order uploaded");
} else {
@@ -117,7 +118,15 @@ export function GlClearanceUploadModal({
size="sm"
required
/>
) : null}
) : (
<DateInput
label="Vessel departure date (optional)"
value={vesselDate}
onChange={(v) => setVesselDate(v ? new Date(v) : null)}
size="sm"
clearable
/>
)}
<PhasedFileDropzone
label={isDo ? "Delivery Order file" : "Release Order file"}

View File

@@ -1,3 +1,4 @@
import type { Freight } from "@edr/types";
import { Badge, Button, Group, Tooltip } from "@mantine/core";
import { useMutation } from "@tanstack/react-query";
import { api } from "@/services/api";
@@ -88,7 +89,13 @@ export function ProfileChips({
}) {
if (!profiles.length) {
return (
<Badge color="gray" variant="light" size="sm" radius="md" style={badgeStyle}>
<Badge
color="gray"
variant="light"
size="sm"
radius="md"
style={badgeStyle}
>
No profiles
</Badge>
);
@@ -118,7 +125,13 @@ export function ProfileChips({
</Tooltip>
))}
{extra > 0 ? (
<Badge color="gray" variant="light" size="sm" radius="md" style={badgeStyle}>
<Badge
color="gray"
variant="light"
size="sm"
radius="md"
style={badgeStyle}
>
+{extra}
</Badge>
) : null}
@@ -169,7 +182,11 @@ const BOOKING_STATUS_COLOR: Record<CustomerBookingStatus, string> = {
CANCELLED: "red",
};
export function BookingStatusBadge({ status }: { status: CustomerBookingStatus }) {
export function BookingStatusBadge({
status,
}: {
status: CustomerBookingStatus;
}) {
return (
<Badge
color={BOOKING_STATUS_COLOR[status] ?? "gray"}
@@ -194,7 +211,11 @@ const PAYMENT_STATUS_COLOR: Record<CustomerPaymentStatus, string> = {
refunded: "grape",
};
export function PaymentStatusBadge({ status }: { status: CustomerPaymentStatus }) {
export function PaymentStatusBadge({
status,
}: {
status: CustomerPaymentStatus;
}) {
return (
<Badge
color={PAYMENT_STATUS_COLOR[status] ?? "gray"}
@@ -210,6 +231,38 @@ export function PaymentStatusBadge({ status }: { status: CustomerPaymentStatus }
);
}
const INVOICE_STATUS_COLOR: Record<Freight.InvoiceStatus, string> = {
DRAFT: "gray",
ISSUED: "cyan",
PENDING: "yellow",
PARTIALLY_PAID: "orange",
PAID: "edr-green",
OVERDUE: "red",
CANCELLED: "gray",
REFUNDED: "grape",
EXPIRED: "red",
};
export function InvoiceStatusBadge({
status,
}: {
status: Freight.InvoiceStatus;
}) {
return (
<Badge
color={INVOICE_STATUS_COLOR[status] ?? "gray"}
variant="light"
size="sm"
radius="md"
tt="capitalize"
fw={600}
style={badgeStyle}
>
{humanize(status)}
</Badge>
);
}
/**
* Inline approval action buttons for a profile row.
* Transitions: pending → approve/reject | active → suspend | suspended → reactivate/blacklist | blacklisted → reinstate
@@ -225,8 +278,7 @@ export function ProfileApprovalActions({
api.customers.setProfileStatus.mutationOptions(),
);
const act = (next: ProfileStatus) =>
mutate({ profileId, status: next });
const act = (next: ProfileStatus) => mutate({ profileId, status: next });
if (status === "pending") {
return (

View File

@@ -2,6 +2,7 @@ export {
BookingStatusBadge,
CompanyStatusBadge,
CompanyTypeBadge,
InvoiceStatusBadge,
PaymentStatusBadge,
ProfileApprovalActions,
ProfileChips,

View File

@@ -179,7 +179,16 @@ const RuleEngineFormDialog = ({
const formRows = useMemo(() => buildFormRows(visibleFields), [visibleFields]);
const setField = (name: string, value: unknown) => {
setValues((current) => ({ ...current, [name]: value }));
setValues((current) => {
const next = { ...current, [name]: value };
// Changing what a rate applies to (or its surcharge trigger) can invalidate
// the previously-chosen unit — reset it so the admin re-picks from the new
// allowed set instead of submitting a stale, rejected unit.
if ((name === "appliesTo" || name === "trigger") && "rateUnit" in current) {
next.rateUnit = "";
}
return next;
});
};
const handleSubmit = (event: React.FormEvent) => {
@@ -250,6 +259,9 @@ const RuleEngineFormDialog = ({
const label = <FieldLabel label={field.label} required={field.required} />;
if (field.type === "select") {
// Dynamic options (e.g. rate unit) resolve from the live form values so
// the choices track the other fields the admin has picked.
const options = field.optionsFromValues ? field.optionsFromValues(values) : (field.options ?? []);
return (
<Select
key={field.name}
@@ -261,7 +273,7 @@ const RuleEngineFormDialog = ({
value={resolveSelectValue(field, values)}
onChange={(v) => setField(field.name, v === RULE_ENGINE_SELECT_NONE ? "" : v)}
disabled={selectOptionsLoading}
data={(field.options ?? [])
data={options
.filter((opt) => opt.value !== "")
.map((opt) => ({
label: opt.label,

View File

@@ -48,6 +48,7 @@ import type {
} from "@/types/trainScheduling";
import { ContainerPlacementGrid } from "./ContainerPlacementGrid";
import { locomotiveOption, showScheduleWarnings } from "./locomotiveOptions";
import {
autoFillPlacements,
mergePlacementsWithSaved,
@@ -274,6 +275,7 @@ export function AllocateBookingWizard({
const created = await create.mutateAsync({
payload: { routeId, scheduleDate, locomotiveIds },
});
showScheduleWarnings(created.warnings);
setSelectedScheduleId(created.id);
return created.id;
};
@@ -536,10 +538,9 @@ export function AllocateBookingWizard({
placeholder={
routeId ? "Select at least two locomotives" : "Select a route first"
}
data={(locomotivesQuery.data ?? []).map((l) => ({
value: l.id,
label: `${l.code}${l.name ? ` · ${l.name}` : ""}`,
}))}
data={(locomotivesQuery.data ?? []).map((l) =>
locomotiveOption(l, " · "),
)}
value={locomotiveIds}
onChange={setLocomotiveIds}
searchable

View File

@@ -0,0 +1,172 @@
import { useMemo, useState } from "react";
import { PackageCheck } from "lucide-react";
import { Badge, Button, Checkbox, Group, Loader, Paper, Stack, Text } from "@mantine/core";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";
import { api } from "@/services/api";
import type {
ImportLoadingBooking,
ImportLoadingBookingsResponse,
LoadingStatus,
} from "@/types/trainScheduling";
function ImportLoadingBookingRow({
booking,
selected,
onToggle,
}: {
booking: ImportLoadingBooking;
selected: boolean;
onToggle: () => void;
}) {
return (
<Group
align="flex-start"
wrap="nowrap"
p="sm"
style={{
border: `1px solid ${
selected ? "var(--mantine-color-edr-green-3)" : "var(--mantine-color-gray-2)"
}`,
borderRadius: 12,
background: selected ? "var(--mantine-color-edr-green-0)" : "white",
transition: "border-color 120ms ease, background 120ms ease",
}}
>
<Checkbox checked={selected} onChange={onToggle} mt={4} color="edr-green" />
<Stack gap={4} style={{ flex: 1 }}>
<Group gap="xs" wrap="wrap">
<PackageCheck size={14} />
<Text fw={600} size="sm">
{booking.reference ?? booking.id}
</Text>
<Badge
variant="light"
size="xs"
color={booking.loadingStatus === "LOADED" ? "edr-green" : "gray"}
>
{booking.loadingStatus}
</Badge>
</Group>
<Text size="xs" c="dimmed">
{booking.customer ?? "Unknown customer"}
</Text>
<Text size="xs" c="dimmed">
{booking.weightTons}T
</Text>
</Stack>
</Group>
);
}
export function ImportLoadingConfirmationPanel({
scheduleId,
items,
isLoading,
}: {
scheduleId: string;
items: ImportLoadingBooking[];
isLoading?: boolean;
}) {
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const queryClient = useQueryClient();
const updateStatus = useMutation<
ImportLoadingBookingsResponse,
Error,
{ id: string; bookingIds: string[]; loadingStatus: LoadingStatus }
>({
...api.trainScheduling.updateImportLoadingStatus.mutationOptions(),
onSuccess: () => {
setSelectedIds([]);
queryClient.invalidateQueries({
queryKey: api.trainScheduling.importLoadingBookings.queryKey({ id: scheduleId }),
});
},
onError: (error) => {
toast.error(error instanceof Error ? error.message : "Could not update loading status");
},
});
const toggle = (id: string) => {
setSelectedIds((prev) =>
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],
);
};
const allIds = useMemo(() => items.map((b) => b.id), [items]);
if (isLoading) {
return (
<Group justify="center" py="md">
<Loader size="sm" />
<Text size="sm" c="dimmed">
Loading import bookings
</Text>
</Group>
);
}
if (!items.length) {
return (
<Paper p="lg" radius="lg" withBorder bg="gray.0">
<Text size="sm" c="dimmed" ta="center">
No paid import bookings with wagons allocated on this schedule
</Text>
</Paper>
);
}
return (
<Stack gap="md">
<Group justify="space-between" wrap="wrap">
<Text size="sm" fw={500}>
Import bookings ({items.length})
</Text>
<Group gap="sm">
<Button variant="light" size="compact-sm" onClick={() => setSelectedIds(allIds)}>
Select all
</Button>
<Button variant="subtle" size="compact-sm" onClick={() => setSelectedIds([])}>
Clear
</Button>
</Group>
</Group>
<Stack gap="sm">
{items.map((booking) => (
<ImportLoadingBookingRow
key={booking.id}
booking={booking}
selected={selectedIds.includes(booking.id)}
onToggle={() => toggle(booking.id)}
/>
))}
</Stack>
<Group gap="sm">
<Button
color="edr-green"
disabled={!selectedIds.length}
loading={updateStatus.isPending}
onClick={() =>
updateStatus.mutate({ id: scheduleId, bookingIds: selectedIds, loadingStatus: "LOADED" })
}
>
Mark loaded
</Button>
<Button
variant="outline"
disabled={!selectedIds.length}
loading={updateStatus.isPending}
onClick={() =>
updateStatus.mutate({ id: scheduleId, bookingIds: selectedIds, loadingStatus: "UNLOADED" })
}
>
Mark unloaded
</Button>
</Group>
</Stack>
);
}

View File

@@ -1,6 +1,8 @@
import type { ReactNode } from "react";
import { Box, Group, Progress, Text, Tooltip } from "@mantine/core";
import type { BookingWindowPhase } from "@/types/trainScheduling";
import "./batchVisuals.css";
/**
@@ -213,3 +215,69 @@ export function HeroChip({
</Group>
);
}
const PHASE_META: Record<
BookingWindowPhase,
{ color: string; label: string; pulse: boolean }
> = {
PRE_WINDOW: { color: "gray", label: "Pre-window", pulse: false },
OPEN: { color: "edr-green", label: "Booking open", pulse: true },
DOC_REVIEW: { color: "yellow", label: "Doc review", pulse: true },
PAYMENT: { color: "blue", label: "Payment", pulse: true },
CLOSED_FOR_DAY: { color: "dark", label: "Closed for day", pulse: false },
DONE: { color: "dark", label: "Done", pulse: false },
};
/**
* Import booking-cycle phase pill (OPEN → DOC_REVIEW → PAYMENT → …) with an
* optional cycle number. Same visual language as `WindowStatusPill`.
*/
export function WindowPhasePill({
phase,
cycleNo,
size = "md",
}: {
phase: BookingWindowPhase;
cycleNo?: number;
size?: "sm" | "md";
}) {
const meta = PHASE_META[phase] ?? {
color: "gray",
label: phase,
pulse: false,
};
const compact = size === "sm";
return (
<Group
gap={6}
wrap="nowrap"
style={{
display: "inline-flex",
padding: compact ? "2px 8px" : "4px 11px",
borderRadius: 999,
background: `var(--mantine-color-${meta.color}-0)`,
border: `1px solid var(--mantine-color-${meta.color}-2)`,
}}
>
<Box
w={compact ? 6 : 7}
h={compact ? 6 : 7}
className={meta.pulse ? "bb-pulse-dot" : undefined}
style={{
borderRadius: 999,
flexShrink: 0,
background: `var(--mantine-color-${meta.color}-6)`,
}}
/>
<Text
size="xs"
fw={700}
c={`${meta.color}.8`}
style={{ letterSpacing: 0.3, lineHeight: 1, whiteSpace: "nowrap" }}
>
{meta.label}
{cycleNo && cycleNo > 1 ? ` · cycle ${cycleNo}` : ""}
</Text>
</Group>
);
}

View File

@@ -0,0 +1,50 @@
import hotToast from "react-hot-toast";
import type { LocomotiveRecord } from "@/types/trainScheduling";
/**
* Locomotives can now be scheduled in advance: not-at-origin-yard or
* already-on-future-schedules is allowed with a warning (only OUT_OF_SERVICE
* is blocked server-side). This returns the hint to surface in the picker,
* or null when the locomotive is ready at the origin yard.
*/
export function locomotiveWarning(loco: LocomotiveRecord): string | null {
const hints: string[] = [];
if (loco.atOriginYard === false) hints.push("not at origin yard");
const futureCount = loco.futureScheduleCount ?? 0;
if (futureCount > 0) {
hints.push(`on ${futureCount} future schedule${futureCount === 1 ? "" : "s"}`);
}
return hints.length ? hints.join(" · ") : null;
}
/** MultiSelect option for the schedule-creation locomotive picker. */
export function locomotiveOption(
loco: LocomotiveRecord,
nameSeparator = " — ",
): { value: string; label: string } {
const base = `${loco.code}${loco.name ? `${nameSeparator}${loco.name}` : ""}`;
const warning = locomotiveWarning(loco);
return {
value: loco.id,
label: warning ? `${base} · ⚠ ${warning}` : base,
};
}
/**
* Yellow toast listing create-schedule warnings (e.g. locomotive not at the
* origin yard yet). The shared `useToast` hook only knows success/error, so
* this styles a react-hot-toast directly.
*/
export function showScheduleWarnings(warnings?: string[] | null): void {
if (!warnings?.length) return;
hotToast(warnings.join("\n"), {
icon: "⚠️",
duration: 8000,
style: {
background: "var(--mantine-color-yellow-0)",
color: "var(--mantine-color-yellow-9)",
border: "1px solid var(--mantine-color-yellow-4)",
},
});
}