Customer Truck Assignment and Portal Delivary Approval

This commit is contained in:
hagiye
2026-07-02 15:54:16 +03:00
319 changed files with 24989 additions and 5041 deletions

View File

@@ -6,6 +6,7 @@ import {
FileText,
LayoutDashboard,
LayoutGrid,
MapPin,
Network,
Package,
PackageCheck,
@@ -14,13 +15,22 @@ import {
Send,
Settings,
ShieldCheck,
Ship,
SlidersHorizontal,
Train,
Truck,
Users,
Wallet,
} from "lucide-react";
import { Navigate, Outlet, Route, Routes, useLocation, useNavigate } from "react-router-dom";
import {
Navigate,
Outlet,
Route,
Routes,
useLocation,
useNavigate,
useParams,
} from "react-router-dom";
import { FreightDashboardLayout, type SidebarItem, type SidebarSection } from "@/components/layout";
import { useAuth } from "./auth/useAuth";
@@ -35,8 +45,12 @@ import ContractRequestDetailPage from "./pages/contracts/ContractRequestDetailPa
import ContractViewPage from "./pages/contracts/ContractViewPage";
import ContractClearanceListPage from "./pages/contracts/ContractClearanceListPage";
import ContractClearanceDetailPage from "./pages/contracts/ContractClearanceDetailPage";
import GlDjiboutiClearanceListPage from "./pages/contracts/GlDjiboutiClearanceListPage";
import GlClearanceDetailPage from "./pages/contracts/GlClearanceDetailPage";
import ShipmentRequestsPage from "./pages/contracts/ShipmentRequestsPage";
import ShipmentRequestDetailPage from "./pages/contracts/ShipmentRequestDetailPage";
import GlCreateBookingForm from "./components/contracts/GlCreateBookingForm";
import BookingMilestonesPage from "./pages/contracts/BookingMilestonesPage";
import DocumentClearanceDetailPage from "./pages/bookings/DocumentClearanceDetailPage";
import CustomerDetailPage from "./pages/customers/CustomerDetailPage";
import CustomersPage from "./pages/customers/CustomersPage";
import DemoUser1Page from "./pages/dashboard/demo/DemoUser1Page";
@@ -57,6 +71,12 @@ import FileUploadSettingsPage from "./pages/documents/FileUploadSettingsPage";
import DropdownSettingsPage from "./pages/dropdown_settings/DropdownSettingsPage";
import FleetResourcePage from "./pages/fleet/FleetResourcePage";
import RoutesPage from "./pages/fleet/RoutesPage";
import FuelPurchasePage from "./pages/fleet/FuelPurchasePage";
import FuelStatsPage from "./pages/fleet/FuelStatsPage";
import { MaintenancePage } from "./pages/fleet/MaintenancePage";
import { FinancialReportsPage } from "./pages/fleet/FinancialReportsPage";
import { FleetDashboard } from "./pages/fleet/FleetDashboard";
import { TrackingPage } from "./pages/fleet/TrackingPage";
import { getCategorySidebarChildren } from "./pages/ruleEngine/config/resources";
import RuleEngineLegacyRedirect from "./pages/ruleEngine/RuleEngineLegacyRedirect";
import RuleEngineResourcePage from "./pages/ruleEngine/RuleEngineResourcePage";
@@ -67,6 +87,7 @@ import BatchScheduleDetailPage from "./pages/trainScheduling/BatchScheduleDetail
import TrainScheduleV2DetailPage from "./pages/trainScheduling/TrainScheduleV2DetailPage";
import TrainScheduleTrackPage from "./pages/trainScheduling/TrainScheduleTrackPage";
import TrainSchedulingGlobalRulesPage from "./pages/trainScheduling/TrainSchedulingGlobalRulesPage";
import ContractValidityPeriodsPage from "./pages/configuration/ContractValidityPeriodsPage";
import FirstMilePage from "./pages/operations/FirstMilePage";
import LastMilePage from "./pages/operations/LastMilePage";
import TrainDetailPage from "./pages/trains/TrainDetailPage";
@@ -133,7 +154,22 @@ const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [
label: "Document Clearance",
href: "/dashboard/contracts/clearance",
icon: <ShieldCheck />,
permission: FREIGHT_PERMS.contracts.clearanceReview,
permission: [
FREIGHT_PERMS.contracts.clearanceReview,
FREIGHT_PERMS.contracts.clearanceEtActions,
],
},
// {
// label: "Shipment Requests",
// href: "/dashboard/shipment-requests",
// icon: <Send />,
// permission: FREIGHT_PERMS.contracts.createBooking,
// },
{
label: "GL Djibouti Clearance",
href: "/dashboard/gl-djibouti/clearance",
icon: <Ship />,
permission: FREIGHT_PERMS.contracts.clearanceDjActions,
},
{
label: "Train Schedules",
@@ -164,6 +200,12 @@ const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [
{
title: "Fleet Management",
items: [
{
label: "Fleet Dashboard",
href: "/dashboard/fleet-dashboard",
icon: <LayoutDashboard />,
permission: FREIGHT_PERMS.fleet.view,
},
{
label: "Routes",
href: "/dashboard/routes",
@@ -200,6 +242,36 @@ const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [
icon: <Users />,
permission: FREIGHT_PERMS.fleet.view,
},
{
label: "Track Vehicles",
href: "/dashboard/tracking",
icon: <MapPin />,
permission: FREIGHT_PERMS.fleet.view,
},
{
label: "Fuel Purchases",
href: "/dashboard/fuel-purchases",
icon: <Truck />,
permission: FREIGHT_PERMS.fleet.view,
},
{
label: "Fuel Analytics",
href: "/dashboard/fuel-stats",
icon: <Truck />,
permission: FREIGHT_PERMS.fleet.view,
},
{
label: "Maintenance",
href: "/dashboard/maintenance",
icon: <Truck />,
permission: FREIGHT_PERMS.fleet.view,
},
{
label: "Financial Reports",
href: "/dashboard/financial-reports",
icon: <Wallet />,
permission: FREIGHT_PERMS.fleet.view,
},
// {
// label: "Containers",
// href: "/dashboard/containers",
@@ -343,6 +415,10 @@ const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [
icon: <Boxes />,
children: [
...getCategorySidebarChildren("configuration"),
{
label: "Contract validity",
href: "/dashboard/configuration/contract-validity-periods",
},
// {
// label: "Train scheduling rules",
// href: "/dashboard/configuration/train-scheduling-rules",
@@ -459,7 +535,11 @@ const App = () => {
/>
<Route
path="clearance/:id"
element={<Navigate to="/dashboard/contracts/clearance" replace />}
element={
<RequirePermission permission={FREIGHT_PERMS.bookings.clearanceView}>
<DocumentClearanceDetailPage />
</RequirePermission>
}
/>
{/* Contracts (Path A/B) */}
@@ -487,11 +567,40 @@ const App = () => {
</RequirePermission>
}
/>
<Route
path="bookings/:bookingId/clearance"
element={
<RequirePermission permission={FREIGHT_PERMS.bookings.clearanceView}>
<DocumentClearanceDetailPage />
</RequirePermission>
}
/>
<Route
path="shipment-requests"
element={
<RequirePermission permission={FREIGHT_PERMS.contracts.createBooking}>
<ShipmentRequestsPage />
</RequirePermission>
}
/>
<Route
path="shipment-requests/:id"
element={
<RequirePermission permission={FREIGHT_PERMS.contracts.createBooking}>
<ShipmentRequestDetailPage />
</RequirePermission>
}
/>
{/* GL (Path B) contract clearance review hub */}
<Route
path="contracts/clearance"
element={
<RequirePermission permission={FREIGHT_PERMS.contracts.clearanceReview}>
<RequirePermission
permission={[
FREIGHT_PERMS.contracts.clearanceReview,
FREIGHT_PERMS.contracts.clearanceEtActions,
]}
>
<ContractClearanceListPage />
</RequirePermission>
}
@@ -499,11 +608,34 @@ const App = () => {
<Route
path="contracts/clearance/:id"
element={
<RequirePermission permission={FREIGHT_PERMS.contracts.clearanceReview}>
<RequirePermission
permission={[
FREIGHT_PERMS.contracts.clearanceReview,
FREIGHT_PERMS.contracts.clearanceEtActions,
]}
>
<ContractClearanceDetailPage />
</RequirePermission>
}
/>
<Route path="gl-ethiopia/clearance" element={<LegacyGlEthiopiaClearanceRedirect />} />
<Route path="gl-ethiopia/clearance/:id" element={<LegacyGlEthiopiaClearanceRedirect />} />
<Route
path="gl-djibouti/clearance"
element={
<RequirePermission permission={FREIGHT_PERMS.contracts.clearanceDjActions}>
<GlDjiboutiClearanceListPage />
</RequirePermission>
}
/>
<Route
path="gl-djibouti/clearance/:id"
element={
<RequirePermission permission={FREIGHT_PERMS.contracts.clearanceDjActions}>
<GlClearanceDetailPage />
</RequirePermission>
}
/>
{/* Path A ops queue out of scope for now → fold into the GL hub. */}
<Route
path="contracts/ops-clearance"
@@ -519,11 +651,7 @@ const App = () => {
/>
<Route
path="bookings/:id/milestones"
element={
<RequirePermission permission={FREIGHT_PERMS.contracts.clearanceReview}>
<BookingMilestonesPage />
</RequirePermission>
}
element={<BookingMilestonesRedirect />}
/>
<Route path="warehouses" element={<WarehouseListPage />} />
<Route path="warehouses/:id" element={<WarehouseDetailPage />} />
@@ -725,6 +853,54 @@ const App = () => {
</RequirePermission>
}
/>
<Route
path="fuel-purchases"
element={
<RequirePermission permission={FREIGHT_PERMS.fleet.view}>
<FuelPurchasePage />
</RequirePermission>
}
/>
<Route
path="fuel-stats"
element={
<RequirePermission permission={FREIGHT_PERMS.fleet.view}>
<FuelStatsPage />
</RequirePermission>
}
/>
<Route
path="maintenance"
element={
<RequirePermission permission={FREIGHT_PERMS.fleet.view}>
<MaintenancePage />
</RequirePermission>
}
/>
<Route
path="financial-reports"
element={
<RequirePermission permission={FREIGHT_PERMS.fleet.view}>
<FinancialReportsPage />
</RequirePermission>
}
/>
<Route
path="fleet-dashboard"
element={
<RequirePermission permission={FREIGHT_PERMS.fleet.view}>
<FleetDashboard />
</RequirePermission>
}
/>
<Route
path="tracking"
element={
<RequirePermission permission={FREIGHT_PERMS.fleet.view}>
<TrackingPage />
</RequirePermission>
}
/>
<Route
path="locomotives"
element={
@@ -811,6 +987,14 @@ const App = () => {
</RequirePermission>
}
/>
<Route
path="configuration/contract-validity-periods"
element={
<RequirePermission permission={FREIGHT_PERMS.admin}>
<ContractValidityPeriodsPage />
</RequirePermission>
}
/>
<Route path="configuration/cargo-types" element={<CargoTypesPage />} />
<Route path="configuration/cargo-types/:id" element={<CargoTypesPage />} />
<Route path="configuration/:resource" element={<RuleEngineResourcePage />} />
@@ -839,4 +1023,21 @@ const App = () => {
);
};
/** Redirect removed milestones page to document clearance. */
function BookingMilestonesRedirect() {
const { id } = useParams();
return (
<Navigate to={`/dashboard/bookings/${id}/clearance`} replace />
);
}
/** Redirect legacy GL Ethiopia clearance URLs to the unified document clearance hub. */
function LegacyGlEthiopiaClearanceRedirect() {
const { id } = useParams();
if (id) {
return <Navigate to={`/dashboard/contracts/clearance/${id}`} replace />;
}
return <Navigate to="/dashboard/contracts/clearance" replace />;
}
export default App;

View File

@@ -65,7 +65,6 @@ export function BookingActionsMenu({
};
const hasMenu = listRowHasActions(row, user);
const primary = actions.find((a) => a.primary) ?? actions[0];
if (!hasMenu && variant === "table") {
return (
@@ -117,19 +116,6 @@ export function BookingActionsMenu({
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => e.stopPropagation()}
>
{variant === "table" && primary && (
<Button
size="compact-sm"
color="edr-green"
visibleFrom="lg"
leftSection={<primary.icon size={14} />}
disabled={mutations.isPending}
onClick={() => handleAction(primary)}
>
{primary.shortLabel}
</Button>
)}
<Menu position="bottom-end" width={220} withinPortal>
<Menu.Target>
<ActionIcon

View File

@@ -41,6 +41,12 @@ export interface ClearanceReviewSectionProps {
onChanged?: () => void;
/** Hide the inline progress summary (e.g. when the parent renders its own). */
hideSummary?: boolean;
/** Lock approve actions after document review phase completes. */
approvalsLocked?: boolean;
/** Block new queries after pre-clearance finalization. */
queriesLocked?: boolean;
/** Read-only audit view — no approve/query actions. */
readOnly?: boolean;
}
const STATUS_META: Record<
@@ -64,6 +70,9 @@ export function ClearanceReviewSection({
bookingId,
onChanged,
hideSummary,
approvalsLocked = false,
queriesLocked = false,
readOnly = false,
}: ClearanceReviewSectionProps) {
const qc = useQueryClient();
const [queryNotes, setQueryNotes] = useState<Record<string, string>>({});
@@ -147,6 +156,11 @@ export function ClearanceReviewSection({
return { total, approved, queried, pending, pct };
}, [customerDocs]);
const hasDocsAwaitingApproval = customerDocs.some(
(d) => d.file && d.reviewStatus !== "APPROVED",
);
const effectiveApprovalsLocked = approvalsLocked && !hasDocsAwaitingApproval;
if (isLoading || !clearance) {
return (
<Group justify="center" py="xl" gap={10}>
@@ -194,6 +208,9 @@ export function ClearanceReviewSection({
<DocReviewCard
key={`${doc.settingCode}:${doc.fileKey}`}
doc={doc}
approvalsLocked={effectiveApprovalsLocked}
queriesLocked={queriesLocked}
readOnly={readOnly}
note={queryNotes[doc.fileKey] ?? ""}
queryOpen={openQuery[doc.fileKey] ?? false}
onToggleQuery={(open) =>
@@ -397,6 +414,9 @@ function StatPill({
function DocReviewCard({
doc,
approvalsLocked,
queriesLocked,
readOnly,
note,
queryOpen,
onToggleQuery,
@@ -407,6 +427,9 @@ function DocReviewCard({
busy,
}: {
doc: Freight.ClearanceDocument;
approvalsLocked: boolean;
queriesLocked: boolean;
readOnly: boolean;
note: string;
queryOpen: boolean;
onToggleQuery: (open: boolean) => void;
@@ -419,6 +442,7 @@ function DocReviewCard({
const status = doc.reviewStatus ?? "PENDING";
const meta = STATUS_META[status];
const hasFile = !!doc.file;
const isApproved = status === "APPROVED";
return (
<Paper
@@ -499,31 +523,35 @@ function DocReviewCard({
</Alert>
)}
{hasFile && (
{hasFile && !readOnly && (
<Box mt="sm">
{!queryOpen ? (
<Group justify="flex-end" gap={8}>
<Button
size="compact-sm"
variant="light"
color="red"
radius="md"
leftSection={<MessageSquareWarning size={14} />}
disabled={busy}
onClick={() => onToggleQuery(true)}
>
Open query
</Button>
<Button
size="compact-sm"
color="edr-green"
radius="md"
leftSection={<CheckCircle2 size={14} />}
disabled={busy}
onClick={onApprove}
>
Approve
</Button>
{!queriesLocked && (
<Button
size="compact-sm"
variant="light"
color="red"
radius="md"
leftSection={<MessageSquareWarning size={14} />}
disabled={busy}
onClick={() => onToggleQuery(true)}
>
Open query
</Button>
)}
{!isApproved && !approvalsLocked && (
<Button
size="compact-sm"
color="edr-green"
radius="md"
leftSection={<CheckCircle2 size={14} />}
disabled={busy}
onClick={onApprove}
>
Approve
</Button>
)}
</Group>
) : (
<Box

View File

@@ -0,0 +1,128 @@
import type { ReactNode } from "react";
import { Badge, Stack, Tabs, Text } from "@mantine/core";
import { AlertTriangle, FileText, ShieldAlert } from "lucide-react";
import type { Freight } from "@edr/types";
import { SectionCard } from "@/components/bookings/detail/SectionCard";
import { AssignRiskCard } from "@/components/contracts/gl-actions/AssignRiskCard";
import { IncidentReportCard } from "@/components/contracts/gl-actions/IncidentReportCard";
import { ClearanceUploadedDocumentsPanel } from "@/components/contracts/ClearanceUploadedDocumentsPanel";
export interface ClearanceOpsTabsProps {
bookingId: string | undefined;
milestones?: Freight.IClearanceMilestone[];
/** When false, only the clearance tab content is rendered (no tab bar). */
showOpsTabs?: boolean;
clearanceTab: ReactNode;
/** Phased customs workflow files — enables the Uploaded documents tab. */
workflowFiles?: Freight.ClearanceWorkflowFile[];
showWorkflowFilesTab?: boolean;
tradeDirection?: string;
onViewFile?: (file: { name: string; url: string }) => void;
onDownloadFile?: (file: { id: string; name: string }) => void;
}
function findMilestone(
milestones: Freight.IClearanceMilestone[] | undefined,
code: string,
): Freight.IClearanceMilestone | undefined {
return milestones?.find((m) => m.milestoneCode === code);
}
/**
* Document Clearance detail layout: primary clearance workflow plus optional
* uploaded documents, post-booking risk assignment, and incident reporting tabs.
*/
export function ClearanceOpsTabs({
bookingId,
milestones,
showOpsTabs = true,
clearanceTab,
workflowFiles = [],
showWorkflowFilesTab = false,
tradeDirection = "IMPORT",
onViewFile,
onDownloadFile,
}: ClearanceOpsTabsProps) {
const riskMs = findMilestone(milestones, "RISK_ASSIGNED");
const hasOps = Boolean(bookingId);
const isExport = tradeDirection === "EXPORT";
const uploadedDocCount = workflowFiles.filter((f) => {
if (!f.file) return false;
if (isExport) return f.category !== "duty";
return true;
}).length;
const showDocuments = showWorkflowFilesTab && Boolean(onViewFile);
const hasTabs = (showOpsTabs && hasOps) || showDocuments;
if (!hasTabs) {
return <>{clearanceTab}</>;
}
return (
<Tabs defaultValue="clearance" keepMounted={false}>
<Tabs.List mb="md">
<Tabs.Tab value="clearance">Clearance</Tabs.Tab>
{showDocuments ? (
<Tabs.Tab
value="documents"
leftSection={<FileText size={14} />}
rightSection={
uploadedDocCount > 0 ? (
<Badge size="xs" variant="light" color="edr-green" circle>
{uploadedDocCount}
</Badge>
) : undefined
}
>
Uploaded documents
</Tabs.Tab>
) : null}
{showOpsTabs && riskMs ? (
<Tabs.Tab value="risk" leftSection={<ShieldAlert size={14} />}>
Risk assignment
</Tabs.Tab>
) : null}
{showOpsTabs && bookingId ? (
<Tabs.Tab value="incidents" leftSection={<AlertTriangle size={14} />}>
Incidents
</Tabs.Tab>
) : null}
</Tabs.List>
<Tabs.Panel value="clearance">{clearanceTab}</Tabs.Panel>
{showDocuments ? (
<Tabs.Panel value="documents">
<ClearanceUploadedDocumentsPanel
files={workflowFiles}
tradeDirection={tradeDirection}
onView={onViewFile!}
onDownload={onDownloadFile}
/>
</Tabs.Panel>
) : null}
{showOpsTabs && riskMs && bookingId ? (
<Tabs.Panel value="risk">
<SectionCard icon={ShieldAlert} title="Customs risk" accent="edr-green">
<AssignRiskCard bookingId={bookingId} milestone={riskMs} />
</SectionCard>
</Tabs.Panel>
) : null}
{showOpsTabs && bookingId ? (
<Tabs.Panel value="incidents">
<SectionCard icon={AlertTriangle} title="Incident reports" accent="edr-green">
<Stack gap="sm">
<Text size="sm" c="dimmed">
Log container or seal issues discovered during clearance handling.
</Text>
<IncidentReportCard bookingId={bookingId} />
</Stack>
</SectionCard>
</Tabs.Panel>
) : null}
</Tabs>
);
}

View File

@@ -0,0 +1,112 @@
import { Check } from "lucide-react";
import { Box, Group, Stack, Text } from "@mantine/core";
import type { Freight } from "@edr/types";
const BRAND_GREEN = "var(--freight-brand, #0A6F4D)";
const IMPORT_PHASES = [
"CUSTOMER_INTAKE",
"GL_ET_REVIEW",
"GL_ET_OUTPUT",
"CUSTOMER_DUTY",
"GL_ET_POST_CLEARANCE",
"GL_DJ_COLLECTION",
] as const;
const PHASE_LABELS: Record<string, string> = {
CUSTOMER_INTAKE: "Customer docs",
GL_ET_REVIEW: "GL ET review",
GL_DJ_COLLECTION: "GL Djibouti DO",
GL_ET_OUTPUT: "Declaration",
CUSTOMER_DUTY: "Duty / customer pays",
GL_ET_POST_CLEARANCE: "Transit & finalize",
GL_DJ_LOADING: "Loading",
POST_TRANSIT: "Transit",
};
const EXPORT_PHASES = [
"CUSTOMER_INTAKE",
"GL_ET_REVIEW",
"GL_DJ_COLLECTION",
"GL_ET_OUTPUT",
"GL_ET_POST_CLEARANCE",
] as const;
function phaseIndex(phases: readonly string[], current?: string | null): number {
if (!current) return 0;
const idx = phases.indexOf(current);
return idx >= 0 ? idx : 0;
}
export function ClearancePhaseStepper({
clearance,
tradeDirection,
compact = false,
}: {
clearance?: Freight.ContractClearanceView | Freight.ClearanceView | null;
tradeDirection?: string;
compact?: boolean;
}) {
const phases = tradeDirection === "EXPORT" ? EXPORT_PHASES : IMPORT_PHASES;
const current = clearance?.phase ?? phases[0];
const activeIdx = phaseIndex(phases, current);
return (
<Group gap={0} wrap="nowrap" align="flex-start" style={{ overflowX: "auto" }}>
{phases.map((phase, index) => {
const isComplete = index < activeIdx;
const isActive = index === activeIdx;
const isLast = index === phases.length - 1;
return (
<Box key={phase} style={{ flex: isLast ? "0 0 auto" : 1, minWidth: compact ? 72 : 88 }}>
<Group gap={0} wrap="nowrap" align="center">
<Stack gap={4} align="center" style={{ flexShrink: 0 }}>
<Box
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: compact ? 28 : 34,
height: compact ? 28 : 34,
borderRadius: "50%",
background: isComplete ? BRAND_GREEN : isActive ? "white" : "var(--mantine-color-gray-1)",
border: isActive
? `2px solid ${BRAND_GREEN}`
: isComplete
? "2px solid transparent"
: "2px solid var(--mantine-color-gray-3)",
color: isComplete ? "white" : isActive ? BRAND_GREEN : "var(--mantine-color-gray-5)",
}}
>
{isComplete ? <Check size={compact ? 14 : 16} strokeWidth={3} /> : null}
</Box>
<Text
size={compact ? "10px" : "xs"}
fw={isActive ? 600 : 500}
c={isActive ? "edr-green.7" : isComplete ? "dark" : "dimmed"}
ta="center"
style={{ whiteSpace: "nowrap" }}
>
{PHASE_LABELS[phase] ?? phase}
</Text>
</Stack>
{!isLast && (
<Box
style={{
flex: 1,
height: 2,
marginInline: 6,
marginBottom: compact ? 16 : 20,
borderRadius: 2,
background: isComplete ? BRAND_GREEN : "var(--mantine-color-gray-2)",
}}
/>
)}
</Group>
</Box>
);
})}
</Group>
);
}

View File

@@ -0,0 +1,205 @@
import { useMemo } from "react";
import { Badge, Box, Stack, Tabs, Text, ThemeIcon } from "@mantine/core";
import { FileText, Receipt, Ship, Truck } from "lucide-react";
import type { Freight } from "@edr/types";
import { SectionCard } from "@/components/bookings/detail/SectionCard";
import { PhasedUploadedFileRow } from "@/components/contracts/PhasedUploadedFileRow";
type TabValue = Freight.ClearanceWorkflowFileCategory;
type TabConfig = {
value: TabValue;
label: string;
icon: typeof FileText;
emptyHint: string;
};
function tabConfigForTradeDirection(tradeDirection: string): TabConfig[] {
if (tradeDirection === "EXPORT") {
return [
{
value: "declaration",
label: "Declaration",
icon: FileText,
emptyHint: "No declaration uploaded yet.",
},
{
value: "djibouti",
label: "Release order",
icon: Ship,
emptyHint: "No release order uploaded yet.",
},
{
value: "transit",
label: "Transit Permit",
icon: Truck,
emptyHint: "No transit permit uploaded yet.",
},
];
}
return [
{
value: "declaration",
label: "Declaration",
icon: FileText,
emptyHint: "No declaration uploaded yet.",
},
{
value: "duty",
label: "Duty notice",
icon: Receipt,
emptyHint: "No duty notice or payment slip uploaded yet.",
},
{
value: "transit",
label: "Transit permit",
icon: Truck,
emptyHint: "No transit permit uploaded yet.",
},
];
}
function subtitleForTradeDirection(tradeDirection: string): string {
return tradeDirection === "EXPORT"
? "Declaration, release order, and transit permit files for this clearance."
: "Declaration, duty notice, and transit permit files for this clearance.";
}
function footerHintForTradeDirection(tradeDirection: string): string {
return tradeDirection === "EXPORT"
? "Files appear here once GL uploads the declaration and release order, and after booking when the transit permit is uploaded."
: "Files appear here once GL Ethiopia uploads declaration, duty notice, or transit permit documents.";
}
export interface ClearanceUploadedDocumentsPanelProps {
files: Freight.ClearanceWorkflowFile[];
tradeDirection?: string;
onView: (file: { name: string; url: string }) => void;
onDownload?: (file: { id: string; name: string }) => void;
}
export function ClearanceUploadedDocumentsPanel({
files,
tradeDirection = "IMPORT",
onView,
onDownload,
}: ClearanceUploadedDocumentsPanelProps) {
const tabConfig = useMemo(
() => tabConfigForTradeDirection(tradeDirection),
[tradeDirection],
);
const isExport = tradeDirection === "EXPORT";
const visibleFiles = useMemo(
() =>
isExport ? files.filter((f) => f.category !== "duty") : files,
[files, isExport],
);
const uploadedCount = visibleFiles.filter((f) => f.file).length;
const defaultTab =
tabConfig.find((tab) =>
visibleFiles.some((f) => f.category === tab.value && f.file),
)?.value ?? tabConfig[0]?.value ?? "declaration";
return (
<SectionCard
icon={FileText}
title="Uploaded customs documents"
subtitle={subtitleForTradeDirection(tradeDirection)}
accent="edr-green"
>
<Tabs defaultValue={defaultTab} keepMounted={false}>
<Tabs.List mb="md">
{tabConfig.map((tab) => {
const count = visibleFiles.filter(
(f) => f.category === tab.value && f.file,
).length;
const Icon = tab.icon;
return (
<Tabs.Tab
key={tab.value}
value={tab.value}
leftSection={<Icon size={14} />}
rightSection={
count > 0 ? (
<Badge size="xs" variant="light" color="edr-green" circle>
{count}
</Badge>
) : undefined
}
>
{tab.label}
</Tabs.Tab>
);
})}
</Tabs.List>
{tabConfig.map((tab) => {
const items = visibleFiles.filter(
(f) => f.category === tab.value && f.file,
);
const Icon = tab.icon;
return (
<Tabs.Panel key={tab.value} value={tab.value}>
{items.length > 0 ? (
<Stack gap="sm">
{items.map((item) => (
<PhasedUploadedFileRow
key={item.code}
label={item.label}
file={item.file!}
onView={onView}
onDownload={onDownload}
/>
))}
</Stack>
) : (
<EmptyTabState icon={Icon} hint={tab.emptyHint} />
)}
</Tabs.Panel>
);
})}
</Tabs>
{uploadedCount === 0 ? (
<Text size="xs" c="dimmed" mt="md">
{footerHintForTradeDirection(tradeDirection)}
</Text>
) : null}
</SectionCard>
);
}
function EmptyTabState({
icon: Icon,
hint,
}: {
icon: typeof FileText;
hint: string;
}) {
return (
<Box
py={40}
style={{
borderRadius: 12,
border: "1px dashed var(--mantine-color-gray-4)",
background: "var(--mantine-color-gray-0)",
textAlign: "center",
}}
>
<Stack gap={8} align="center">
<ThemeIcon variant="light" color="gray" radius="xl" size={44}>
<Icon size={20} />
</ThemeIcon>
<Text size="sm" c="dimmed" maw={320}>
{hint}
</Text>
</Stack>
</Box>
);
}

View File

@@ -0,0 +1,155 @@
import {
Badge,
Box,
Button,
Group,
Paper,
Stack,
Text,
ThemeIcon,
Tooltip,
} from "@mantine/core";
import { Download, Eye, FileText } from "lucide-react";
import type { Freight } from "@edr/types";
import { isViewable } from "@edr/ui-common";
import { SectionCard } from "@/components/bookings/detail/SectionCard";
import { fileViewUrl } from "@/constants/apiConfig";
const CATEGORY_LABELS: Record<
Freight.ClearanceWorkflowFileCategory,
string
> = {
declaration: "Declaration",
duty: "Duty & taxes",
transit: "Transit",
djibouti: "Djibouti",
};
const CATEGORY_ORDER: Freight.ClearanceWorkflowFileCategory[] = [
"declaration",
"duty",
"transit",
"djibouti",
];
const OWNER_LABELS: Record<Freight.ClearanceWorkflowFileOwner, string> = {
customer: "Customer",
gl_et: "GL Ethiopia",
gl_dj: "GL Djibouti",
};
export interface ClearanceWorkflowFilesPanelProps {
files: Freight.ClearanceWorkflowFile[];
onView: (file: { name: string; url: string }) => void;
onDownload?: (file: { id: string; name: string }) => void;
title?: string;
}
export function ClearanceWorkflowFilesPanel({
files,
onView,
onDownload,
title = "Customs workflow documents",
}: ClearanceWorkflowFilesPanelProps) {
if (files.length === 0) return null;
const grouped = CATEGORY_ORDER.map((category) => ({
category,
label: CATEGORY_LABELS[category],
items: files.filter((f) => f.category === category),
})).filter((g) => g.items.length > 0);
return (
<SectionCard icon={FileText} title={title} accent="edr-green">
<Stack gap="md">
{grouped.map((group) => (
<Box key={group.category}>
<Text size="xs" fw={700} c="dimmed" tt="uppercase" mb={8}>
{group.label}
</Text>
<Stack gap={8}>
{group.items.map((item) => (
<WorkflowFileRow
key={item.code}
item={item}
onView={onView}
onDownload={onDownload}
/>
))}
</Stack>
</Box>
))}
</Stack>
</SectionCard>
);
}
function WorkflowFileRow({
item,
onView,
onDownload,
}: {
item: Freight.ClearanceWorkflowFile;
onView: (file: { name: string; url: string }) => void;
onDownload?: (file: { id: string; name: string }) => void;
}) {
const file = item.file;
if (!file) return null;
const viewUrl = fileViewUrl(file.id);
const canPreview = isViewable({ name: file.name, url: viewUrl });
return (
<Paper withBorder radius="md" p="sm">
<Group justify="space-between" wrap="nowrap" align="center">
<Group gap={10} wrap="nowrap" style={{ minWidth: 0 }}>
<ThemeIcon variant="light" color="edr-green" radius="md" size={36}>
<FileText size={17} />
</ThemeIcon>
<Box style={{ minWidth: 0 }}>
<Text size="sm" fw={600} truncate>
{item.label}
</Text>
<Group gap={6} wrap="nowrap" mt={2}>
<Badge size="xs" variant="light" color="gray" radius="sm" tt="none">
{OWNER_LABELS[item.uploadedBy]}
</Badge>
<Text size="xs" c="dimmed" truncate>
{file.name}
</Text>
</Group>
</Box>
</Group>
<Group gap={6} wrap="nowrap">
{canPreview ? (
<Tooltip label="Preview">
<Button
size="compact-xs"
variant="default"
radius="md"
leftSection={<Eye size={13} />}
onClick={() => onView({ name: file.name, url: viewUrl })}
>
View
</Button>
</Tooltip>
) : null}
{onDownload ? (
<Tooltip label="Download">
<Button
size="compact-xs"
variant="light"
radius="md"
leftSection={<Download size={13} />}
onClick={() => onDownload({ id: file.id, name: file.name })}
>
Download
</Button>
</Tooltip>
) : null}
</Group>
</Group>
</Paper>
);
}

View File

@@ -1,6 +1,14 @@
import { useMemo } from "react";
import { useMemo, useState } from "react";
import { Check, ShieldCheck } from "lucide-react";
import { Stack, Group, Text, Badge, Button, Box } from "@mantine/core";
import {
Stack,
Group,
Text,
Badge,
Button,
Box,
Modal,
} from "@mantine/core";
import type { Freight } from "@edr/types";
import { formatContractApprovalProgress } from "@/features/contracts/contract-approval-progress";
@@ -19,6 +27,10 @@ export function ContractApprovalStepsCard({
contract,
mutations,
}: ContractApprovalStepsCardProps) {
const [confirmOpen, setConfirmOpen] = useState(false);
const [pendingStep, setPendingStep] =
useState<Freight.IContractApprovalStep | null>(null);
const steps = useMemo(
() =>
[...(contract.approvalSteps ?? [])].sort(
@@ -30,6 +42,24 @@ export function ContractApprovalStepsCard({
const nextPending = steps.find((s) => s.status === "PENDING");
const summary = formatContractApprovalProgress(contract.status, steps);
const openApprove = (step: Freight.IContractApprovalStep) => {
setPendingStep(step);
setConfirmOpen(true);
};
const closeApprove = () => {
setConfirmOpen(false);
setPendingStep(null);
};
const runApprove = () => {
if (!pendingStep) return;
mutations.approveStep.mutate(
{ stepId: pendingStep.id, requiredRole: pendingStep.requiredRole },
{ onSuccess: () => closeApprove() },
);
};
const subtitle =
summary.detail ||
(nextPending
@@ -39,54 +69,87 @@ export function ContractApprovalStepsCard({
: "Accept submission to begin");
return (
<SectionCard
icon={ShieldCheck}
title="Approval chain"
extra={
<Badge color="edr-green" variant="light" radius="sm">
{steps.filter((s) => s.status === "APPROVED").length}/{steps.length}
</Badge>
}
>
<Text size="xs" c="dimmed" mb="sm">
{subtitle}
</Text>
{steps.length === 0 ? (
<Text
size="sm"
c="dimmed"
ta="center"
py="lg"
px="md"
style={{
borderRadius: 8,
border: "1px dashed var(--mantine-color-gray-3)",
background: "var(--mantine-color-gray-0)",
}}
>
Use <strong>Accept for approval</strong> in staff actions to
instantiate steps.
<>
<SectionCard
icon={ShieldCheck}
title="Approval chain"
extra={
<Badge color="edr-green" variant="light" radius="sm">
{steps.filter((s) => s.status === "APPROVED").length}/{steps.length}
</Badge>
}
>
<Text size="xs" c="dimmed" mb="sm">
{subtitle}
</Text>
) : (
<Stack gap="xs">
{steps.map((step) => (
<StepRow
key={step.id}
step={step}
isNext={nextPending?.id === step.id}
isPending={mutations.approveStep.isPending}
onApprove={() =>
mutations.approveStep.mutate({
stepId: step.id,
requiredRole: step.requiredRole,
})
}
/>
))}
{steps.length === 0 ? (
<Text
size="sm"
c="dimmed"
ta="center"
py="lg"
px="md"
style={{
borderRadius: 8,
border: "1px dashed var(--mantine-color-gray-3)",
background: "var(--mantine-color-gray-0)",
}}
>
Use <strong>Accept for approval</strong> in staff actions to
instantiate steps.
</Text>
) : (
<Stack gap="xs">
{steps.map((step) => (
<StepRow
key={step.id}
step={step}
isNext={nextPending?.id === step.id}
isPending={mutations.approveStep.isPending}
onApprove={() => openApprove(step)}
/>
))}
</Stack>
)}
</SectionCard>
<Modal
opened={confirmOpen}
onClose={closeApprove}
title="Approve this step?"
radius="md"
centered
>
<Stack gap="md">
<Text size="sm" c="dimmed">
You are about to approve the{" "}
<Text span fw={600} c="dark">
{pendingStep?.requiredRole}
</Text>{" "}
step for contract{" "}
<Text span fw={600} c="dark">
{contract.reference}
</Text>
. This action cannot be undone from this screen.
</Text>
<Group justify="flex-end" gap="sm">
<Button variant="default" radius="md" onClick={closeApprove}>
Cancel
</Button>
<Button
color="edr-green"
radius="md"
leftSection={<Check size={16} />}
loading={mutations.approveStep.isPending}
onClick={runApprove}
>
Confirm approval
</Button>
</Group>
</Stack>
)}
</SectionCard>
</Modal>
</>
);
}

View File

@@ -54,6 +54,21 @@ export interface ContractClearanceReviewSectionProps {
* by whom, when) but hide all approve / query / finalize actions.
*/
readOnly?: boolean;
/**
* Document approvals are locked (e.g. after all docs approved in phased flow)
* but queries remain available until {@link queriesLocked} or {@link readOnly}.
*/
approvalsLocked?: boolean;
/**
* Pre-clearance finalized — block opening new queries on customer documents.
*/
queriesLocked?: boolean;
/**
* ONE_TIME customs contracts use the phased milestone workflow. Hides the
* legacy "Finalize clearance" shortcut; booking readiness follows delivery
* order (import) or export release.
*/
phasedCustoms?: boolean;
}
const STATUS_META: Record<
@@ -89,6 +104,9 @@ export function ContractClearanceReviewSection({
hideSummary,
selfClear = false,
readOnly = false,
phasedCustoms = false,
approvalsLocked = false,
queriesLocked = false,
}: ContractClearanceReviewSectionProps) {
const [queryNotes, setQueryNotes] = useState<Record<string, string>>({});
const [openQuery, setOpenQuery] = useState<Record<string, boolean>>({});
@@ -137,6 +155,11 @@ export function ContractClearanceReviewSection({
.filter((d) => d.file && d.reviewStatus !== "APPROVED")
.map((d) => d.fileKey);
const hasDocsAwaitingApproval = customerDocs.some(
(d) => d.file && d.reviewStatus !== "APPROVED",
);
const effectiveApprovalsLocked = approvalsLocked && !hasDocsAwaitingApproval;
if (isLoading || !clearance) {
return (
<Group justify="center" py="xl" gap={10}>
@@ -170,14 +193,16 @@ export function ContractClearanceReviewSection({
subtitle={
readOnly
? `Reviewed by the ${reviewerTeam} team.`
: "Approve each document, or open a query to tell the customer what to fix."
: effectiveApprovalsLocked
? "Documents are approved — you can still open a query if something needs fixing."
: "Approve each document, or open a query to tell the customer what to fix."
}
extra={
<Group gap={10} wrap="nowrap" align="center">
<Text size="xs" c="dimmed" fw={600}>
{stats.approved}/{stats.total} approved
</Text>
{!readOnly && approvableKeys.length > 0 && (
{!readOnly && !effectiveApprovalsLocked && approvableKeys.length > 0 && (
<Button
size="compact-sm"
color="edr-green"
@@ -221,6 +246,8 @@ export function ContractClearanceReviewSection({
doc={doc}
reviewerTeam={reviewerTeam}
readOnly={readOnly}
approvalsLocked={effectiveApprovalsLocked}
queriesLocked={queriesLocked}
note={queryNotes[doc.fileKey] ?? ""}
queryOpen={openQuery[doc.fileKey] ?? false}
onToggleQuery={(open) =>
@@ -241,7 +268,7 @@ export function ContractClearanceReviewSection({
</Stack>
</SectionCard>
{glDocs.length > 0 && (
{glDocs.length > 0 && !phasedCustoms && (
<SectionCard
icon={Upload}
title="GL output documents"
@@ -372,8 +399,42 @@ export function ContractClearanceReviewSection({
<CheckCircle2 size={15} />
</ThemeIcon>
<Text fz="12.5px" c="dimmed">
Clearance was finalized by the {reviewerTeam} team. This is a
read-only record of the approved documents.
{phasedCustoms
? "Document review is complete. Continue customs milestones in the action panel."
: `Clearance was finalized by the ${reviewerTeam} team. This is a read-only record of the approved documents.`}
</Text>
</Group>
</Paper>
) : phasedCustoms && effectiveApprovalsLocked ? (
<Paper withBorder radius="md" p="md">
<Group gap={8} wrap="nowrap" style={{ minWidth: 0 }}>
<ThemeIcon variant="light" color="edr-green" radius="md" size={28}>
<CheckCircle2 size={15} />
</ThemeIcon>
<Text fz="12.5px" c="dimmed">
Document review is complete. Use the action panel for declaration, duty, and
transit steps
{queriesLocked
? ". Pre-clearance is finalized — customer documents can no longer be queried."
: " — or open a query above if a customer document needs correction."}
</Text>
</Group>
</Paper>
) : phasedCustoms ? (
<Paper withBorder radius="md" p="md">
<Group gap={8} wrap="nowrap" style={{ minWidth: 0 }}>
<ThemeIcon
variant="light"
color={clearance.allApproved ? "edr-green" : "gray"}
radius="md"
size={28}
>
<FileCheck2 size={15} />
</ThemeIcon>
<Text fz="12.5px" c="dimmed">
{clearance.allApproved
? "All required documents are approved. Continue declaration, duty, and transit in the action panel."
: "Approve every required document to unlock the customs milestone steps."}
</Text>
</Group>
</Paper>
@@ -450,6 +511,8 @@ function DocReviewCard({
doc,
reviewerTeam,
readOnly,
approvalsLocked,
queriesLocked,
note,
queryOpen,
onToggleQuery,
@@ -462,6 +525,8 @@ function DocReviewCard({
doc: Freight.ContractClearanceDocument;
reviewerTeam: string;
readOnly: boolean;
approvalsLocked: boolean;
queriesLocked: boolean;
note: string;
queryOpen: boolean;
onToggleQuery: (open: boolean) => void;
@@ -583,31 +648,35 @@ function DocReviewCard({
</Alert>
)}
{!readOnly && hasFile && !isApproved && (
{!readOnly && hasFile && (
<Box mt="sm">
{!queryOpen ? (
<Group justify="flex-end" gap={8}>
<Button
size="sm"
variant="light"
color="red"
radius="md"
leftSection={<MessageSquareWarning size={15} />}
disabled={busy}
onClick={() => onToggleQuery(true)}
>
Open query
</Button>
<Button
size="sm"
color="edr-green"
radius="md"
leftSection={<CheckCircle2 size={15} />}
disabled={busy}
onClick={onApprove}
>
Approve
</Button>
{!queriesLocked && (
<Button
size="sm"
variant="light"
color="red"
radius="md"
leftSection={<MessageSquareWarning size={15} />}
disabled={busy}
onClick={() => onToggleQuery(true)}
>
Open query
</Button>
)}
{!isApproved && !approvalsLocked && (
<Button
size="sm"
color="edr-green"
radius="md"
leftSection={<CheckCircle2 size={15} />}
disabled={busy}
onClick={onApprove}
>
Approve
</Button>
)}
</Group>
) : (
<Box

View File

@@ -0,0 +1,43 @@
import { Button, Group, Modal, Stack, Text, ThemeIcon } from "@mantine/core";
import { CheckCircle2 } from "lucide-react";
export interface ContractSignSuccessModalProps {
opened: boolean;
onClose: () => void;
reference: string;
message?: string;
confirmLabel?: string;
}
export function ContractSignSuccessModal({
opened,
onClose,
reference,
message = "The contract has been signed and recorded.",
confirmLabel = "Back to contract request",
}: ContractSignSuccessModalProps) {
return (
<Modal
opened={opened}
onClose={onClose}
title="Contract signed successfully"
centered
radius="lg"
>
<Stack gap="md" align="center" ta="center">
<ThemeIcon size={56} radius="xl" color="edr-green" variant="light">
<CheckCircle2 size={28} />
</ThemeIcon>
<Text fw={600}>{reference}</Text>
<Text size="sm" c="dimmed">
{message}
</Text>
<Group justify="center" mt="xs">
<Button color="edr-green" onClick={onClose}>
{confirmLabel}
</Button>
</Group>
</Stack>
</Modal>
);
}

View File

@@ -0,0 +1,154 @@
import { useState } from "react";
import { Button, Group, Modal, Stack, Text } from "@mantine/core";
import { DateInput } from "@mantine/dates";
import { Ship, Upload } from "lucide-react";
import toast from "react-hot-toast";
import { PhasedFileDropzone } from "@/components/contracts/PhasedFileDropzone";
import { findWorkflowFile } from "@/components/contracts/PhasedUploadedFileRow";
import { contractsService } from "@/services/contracts.service";
import { bookingsService } from "@/services/bookings.service";
import type { Freight } from "@edr/types";
export type GlClearanceUploadKind = "do" | "ro";
export interface GlClearanceUploadModalProps {
opened: boolean;
kind: GlClearanceUploadKind | null;
onClose: () => void;
entityId: string;
isBooking: boolean;
workflowFiles?: Freight.ClearanceWorkflowFile[];
vesselDepartureDate?: string | null;
onSuccess?: () => void;
onPreview?: (file: { name: string; url: string }) => void;
}
export function GlClearanceUploadModal({
opened,
kind,
onClose,
entityId,
isBooking,
workflowFiles = [],
vesselDepartureDate,
onSuccess,
onPreview,
}: GlClearanceUploadModalProps) {
const [file, setFile] = useState<File | null>(null);
const [vesselDate, setVesselDate] = useState<Date | null>(
vesselDepartureDate ? new Date(vesselDepartureDate) : null,
);
const [loading, setLoading] = useState(false);
const isDo = kind === "do";
const isRo = kind === "ro";
const replaceMode = isDo
? Boolean(findWorkflowFile(workflowFiles, "delivery_order"))
: Boolean(findWorkflowFile(workflowFiles, "release_order"));
const close = () => {
setFile(null);
onClose();
};
const submit = async () => {
if (!file || !kind) return;
if (isRo && !vesselDate) {
toast.error("Vessel departure date is required.");
return;
}
setLoading(true);
try {
if (isDo) {
if (isBooking) {
await bookingsService.uploadDeliveryOrder(entityId, file);
} else {
await contractsService.uploadDeliveryOrder(entityId, file);
}
toast.success(replaceMode ? "Delivery Order updated" : "Delivery Order uploaded");
} else {
const iso = vesselDate!.toISOString().slice(0, 10);
const result = isBooking
? await bookingsService.uploadReleaseOrder(entityId, file, iso)
: await contractsService.uploadReleaseOrder(entityId, file, iso);
if (result.hold) {
toast.error(result.holdReason ?? "Vessel date too soon");
} else {
toast.success(replaceMode ? "Release Order updated" : "Release Order uploaded");
}
}
setFile(null);
onSuccess?.();
close();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Upload failed");
} finally {
setLoading(false);
}
};
return (
<Modal
opened={opened && kind != null}
onClose={close}
title={
<Group gap={8}>
<Ship size={18} />
<Text fw={700}>{isDo ? "Upload Delivery Order" : "Upload Release Order"}</Text>
</Group>
}
radius="md"
size="md"
>
<Stack gap="md">
<Text size="sm" c="dimmed">
{isDo
? "Upload the Djibouti Delivery Order (DO) for this import shipment."
: "Upload the Release Order and confirm the vessel departure date."}
</Text>
{isRo ? (
<DateInput
label="Vessel departure date"
value={vesselDate}
onChange={(v) => setVesselDate(v ? new Date(v) : null)}
size="sm"
required
/>
) : null}
<PhasedFileDropzone
label={isDo ? "Delivery Order file" : "Release Order file"}
description="PDF or image."
value={file}
onChange={setFile}
replaceMode={replaceMode}
onPreview={onPreview}
/>
<Group justify="flex-end" gap="sm">
<Button variant="default" onClick={close} disabled={loading}>
Cancel
</Button>
<Button
color="edr-green"
loading={loading}
disabled={!file || (isRo && !vesselDate)}
leftSection={<Upload size={16} />}
onClick={() => void submit()}
>
{replaceMode
? isDo
? "Replace DO"
: "Replace RO"
: isDo
? "Upload DO"
: "Upload RO"}
</Button>
</Group>
</Stack>
</Modal>
);
}

View File

@@ -0,0 +1,122 @@
import { Box, Button, Group, Paper, Stack, Text } from "@mantine/core";
import { FileText, Upload } from "lucide-react";
import type { Freight } from "@edr/types";
import { PhasedFileDropzone } from "@/components/contracts/PhasedFileDropzone";
import { PhasedUploadedFileRow, findWorkflowFile } from "@/components/contracts/PhasedUploadedFileRow";
export interface PhasedDocumentUploadFieldProps {
fields: Array<{ key: string; label: string }>;
files: Record<string, File | null>;
onChange: (key: string, file: File | null) => void;
workflowFiles?: Freight.ClearanceWorkflowFile[];
helperText: string;
replaceMode?: boolean;
loading?: boolean;
disabled?: boolean;
submitLabel?: string;
onSubmit: () => void;
onViewFile?: (file: { name: string; url: string }) => void;
onDownloadFile?: (file: { id: string; name: string }) => void;
}
/** Consistent phased customs document upload with drag-and-drop, preview, and uploaded rows. */
export function PhasedDocumentUploadField({
fields,
files,
onChange,
workflowFiles = [],
helperText,
replaceMode = false,
loading = false,
disabled = false,
submitLabel,
onSubmit,
onViewFile,
onDownloadFile,
}: PhasedDocumentUploadFieldProps) {
const hasStaged = Object.values(files).some(Boolean);
const uploaded = fields
.map((f) => ({ ...f, file: findWorkflowFile(workflowFiles, f.key) }))
.filter((f) => f.file);
const multiField = fields.length > 1;
return (
<Stack gap="md">
{uploaded.length > 0 ? (
<Stack gap={8}>
<Text size="xs" fw={700} c="dimmed" tt="uppercase">
Current file{uploaded.length > 1 ? "s" : ""}
</Text>
{uploaded.map((row) => (
<PhasedUploadedFileRow
key={row.key}
label={row.label}
file={row.file!}
onView={onViewFile}
onDownload={onDownloadFile}
/>
))}
</Stack>
) : null}
<Paper withBorder radius="md" p="md" bg="var(--mantine-color-gray-0)">
<Group gap={8} mb="sm" wrap="nowrap">
<Box
c="edr-green"
style={{
width: 32,
height: 32,
borderRadius: 8,
display: "flex",
alignItems: "center",
justifyContent: "center",
background: "var(--mantine-color-edr-green-1)",
}}
>
<FileText size={16} />
</Box>
<Box>
<Text size="sm" fw={700}>
{replaceMode ? "Replace document" : "Upload document"}
</Text>
<Text size="xs" c="dimmed">
{helperText}
</Text>
</Box>
</Group>
<Stack gap="md">
{fields.map((f) => (
<PhasedFileDropzone
key={f.key}
label={multiField ? f.label : "Choose file"}
description={
multiField
? uploaded.some((u) => u.key === f.key)
? "Drop a new file to replace the current one."
: `Upload ${f.label} (optional if another declaration type is provided).`
: undefined
}
value={files[f.key] ?? null}
onChange={(file) => onChange(f.key, file)}
replaceMode={replaceMode || uploaded.some((u) => u.key === f.key)}
onPreview={onViewFile}
/>
))}
</Stack>
</Paper>
<Button
color="edr-green"
loading={loading}
disabled={disabled || !hasStaged}
leftSection={<Upload size={16} />}
onClick={onSubmit}
fullWidth
>
{submitLabel ?? (replaceMode ? "Replace document" : "Upload document")}
</Button>
</Stack>
);
}

View File

@@ -0,0 +1,403 @@
import { useEffect, useMemo, useRef, useState } from "react";
import {
ActionIcon,
Box,
Button,
Group,
Stack,
Text,
ThemeIcon,
UnstyledButton,
} from "@mantine/core";
import { Eye, FileText, Trash2, UploadCloud } from "lucide-react";
import { isViewable } from "@edr/ui-common";
export interface PhasedFileDropzoneProps {
label: string;
description?: string;
value: File | null;
onChange: (file: File | null) => void;
accept?: string;
replaceMode?: boolean;
onPreview?: (file: { name: string; url: string; mimeType?: string | null }) => void;
disabled?: boolean;
}
function formatBytes(bytes: number): string {
if (bytes === 0) return "0 B";
const k = 1024;
const sizes = ["B", "KB", "MB", "GB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / k ** i).toFixed(1))} ${sizes[i]}`;
}
function isImageFile(file: File): boolean {
if (file.type.startsWith("image/")) return true;
const ext = file.name.split(".").pop()?.toLowerCase() ?? "";
return ["png", "jpg", "jpeg", "webp", "gif", "bmp", "svg"].includes(ext);
}
export function PhasedFileDropzone({
label,
description,
value,
onChange,
accept = "application/pdf,image/*",
replaceMode = false,
onPreview,
disabled = false,
}: PhasedFileDropzoneProps) {
const inputRef = useRef<HTMLInputElement>(null);
const [dragOver, setDragOver] = useState(false);
const previewUrl = useMemo(
() => (value ? URL.createObjectURL(value) : null),
[value],
);
useEffect(() => {
return () => {
if (previewUrl) URL.revokeObjectURL(previewUrl);
};
}, [previewUrl]);
const pickFile = (file: File | null) => {
if (disabled) return;
onChange(file);
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
setDragOver(false);
if (disabled) return;
const file = e.dataTransfer.files[0];
if (file) pickFile(file);
};
if (value && previewUrl) {
const canPreview = onPreview && isViewable({ name: value.name, url: previewUrl, mimeType: value.type });
const image = isImageFile(value);
return (
<Stack gap={6}>
<Text size="sm" fw={600}>
{label}
</Text>
<Box
p="sm"
style={{
borderRadius: 12,
border: "1px solid var(--mantine-color-edr-green-4)",
background:
"linear-gradient(135deg, var(--mantine-color-edr-green-0) 0%, #fff 70%)",
}}
>
<Group justify="space-between" wrap="nowrap" align="center">
<Group gap={12} wrap="nowrap" style={{ minWidth: 0 }}>
{image ? (
<UnstyledButton
onClick={() =>
canPreview && onPreview?.({ name: value.name, url: previewUrl, mimeType: value.type })
}
style={{
width: 52,
height: 52,
flexShrink: 0,
borderRadius: 10,
overflow: "hidden",
border: "1px solid var(--mantine-color-gray-3)",
cursor: canPreview ? "pointer" : "default",
}}
>
<img
src={previewUrl}
alt=""
style={{ width: "100%", height: "100%", objectFit: "cover" }}
/>
</UnstyledButton>
) : (
<ThemeIcon variant="light" color="edr-green" radius="md" size={52}>
<FileText size={22} />
</ThemeIcon>
)}
<Box style={{ minWidth: 0 }}>
<Text size="xs" fw={700} c="edr-green" tt="uppercase">
Ready to upload
</Text>
<Text size="sm" fw={600} truncate>
{value.name}
</Text>
<Text size="xs" c="dimmed">
{formatBytes(value.size)}
</Text>
</Box>
</Group>
<Group gap={6} wrap="nowrap">
{canPreview ? (
<Button
size="compact-xs"
variant="default"
leftSection={<Eye size={13} />}
onClick={() =>
onPreview({ name: value.name, url: previewUrl, mimeType: value.type })
}
>
Preview
</Button>
) : null}
<ActionIcon
variant="subtle"
color="red"
radius="md"
aria-label="Remove file"
onClick={() => pickFile(null)}
disabled={disabled}
>
<Trash2 size={15} />
</ActionIcon>
</Group>
</Group>
</Box>
</Stack>
);
}
return (
<Stack gap={6}>
<Text size="sm" fw={600}>
{label}
</Text>
{description ? (
<Text size="xs" c="dimmed">
{description}
</Text>
) : null}
<Box
onDragOver={(e) => {
e.preventDefault();
if (!disabled) setDragOver(true);
}}
onDragLeave={() => setDragOver(false)}
onDrop={handleDrop}
onClick={() => !disabled && inputRef.current?.click()}
style={{
borderRadius: 12,
border: `2px dashed ${
dragOver
? "var(--mantine-color-edr-green-5)"
: "var(--mantine-color-gray-4)"
}`,
background: dragOver
? "var(--mantine-color-edr-green-0)"
: "var(--mantine-color-gray-0)",
padding: "28px 20px",
textAlign: "center",
cursor: disabled ? "not-allowed" : "pointer",
opacity: disabled ? 0.6 : 1,
transition: "border-color 120ms ease, background 120ms ease",
}}
>
<input
ref={inputRef}
type="file"
accept={accept}
hidden
disabled={disabled}
onChange={(e) => pickFile(e.target.files?.[0] ?? null)}
/>
<Stack gap={8} align="center">
<ThemeIcon
variant="light"
color={dragOver ? "edr-green" : "gray"}
radius="xl"
size={48}
>
<UploadCloud size={24} />
</ThemeIcon>
<Box>
<Text size="sm" fw={600}>
{dragOver
? "Drop to upload"
: replaceMode
? "Drag & drop to replace"
: "Drag & drop your file here"}
</Text>
<Text size="xs" c="dimmed" mt={4}>
or <span style={{ color: "var(--mantine-color-edr-green-7)", fontWeight: 600 }}>browse</span>{" "}
PDF or image
</Text>
</Box>
</Stack>
</Box>
</Stack>
);
}
export interface PhasedMultiFileDropzoneProps {
label: string;
description?: string;
value: File[];
onChange: (files: File[]) => void;
accept?: string;
replaceMode?: boolean;
disabled?: boolean;
}
export function PhasedMultiFileDropzone({
label,
description,
value,
onChange,
accept = "application/pdf,image/*",
replaceMode = false,
disabled = false,
}: PhasedMultiFileDropzoneProps) {
const inputRef = useRef<HTMLInputElement>(null);
const [dragOver, setDragOver] = useState(false);
const addFiles = (incoming: FileList | File[]) => {
if (disabled) return;
const next = [...value];
for (const file of Array.from(incoming)) {
if (!next.some((f) => f.name === file.name && f.size === file.size)) {
next.push(file);
}
}
onChange(next);
};
const removeAt = (index: number) => {
if (disabled) return;
onChange(value.filter((_, i) => i !== index));
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
setDragOver(false);
if (e.dataTransfer.files.length > 0) addFiles(e.dataTransfer.files);
};
return (
<Stack gap={6}>
<Text size="sm" fw={600}>
{label}
</Text>
{description ? (
<Text size="xs" c="dimmed">
{description}
</Text>
) : null}
{value.length > 0 ? (
<Stack gap={8}>
{value.map((file, index) => (
<Box
key={`${file.name}-${file.size}-${index}`}
p="sm"
style={{
borderRadius: 12,
border: "1px solid var(--mantine-color-edr-green-4)",
background:
"linear-gradient(135deg, var(--mantine-color-edr-green-0) 0%, #fff 70%)",
}}
>
<Group justify="space-between" wrap="nowrap" align="center">
<Group gap={12} wrap="nowrap" style={{ minWidth: 0 }}>
<ThemeIcon variant="light" color="edr-green" radius="md" size={44}>
<FileText size={18} />
</ThemeIcon>
<Box style={{ minWidth: 0 }}>
<Text size="xs" fw={700} c="edr-green" tt="uppercase">
Ready to upload
</Text>
<Text size="sm" fw={600} truncate>
{file.name}
</Text>
<Text size="xs" c="dimmed">
{formatBytes(file.size)}
</Text>
</Box>
</Group>
<ActionIcon
variant="subtle"
color="red"
radius="md"
aria-label="Remove file"
onClick={() => removeAt(index)}
disabled={disabled}
>
<Trash2 size={15} />
</ActionIcon>
</Group>
</Box>
))}
</Stack>
) : null}
<Box
onDragOver={(e) => {
e.preventDefault();
if (!disabled) setDragOver(true);
}}
onDragLeave={() => setDragOver(false)}
onDrop={handleDrop}
onClick={() => !disabled && inputRef.current?.click()}
style={{
borderRadius: 12,
border: `2px dashed ${
dragOver
? "var(--mantine-color-edr-green-5)"
: "var(--mantine-color-gray-4)"
}`,
background: dragOver
? "var(--mantine-color-edr-green-0)"
: "var(--mantine-color-gray-0)",
padding: "28px 20px",
textAlign: "center",
cursor: disabled ? "not-allowed" : "pointer",
opacity: disabled ? 0.6 : 1,
transition: "border-color 120ms ease, background 120ms ease",
}}
>
<input
ref={inputRef}
type="file"
accept={accept}
multiple
hidden
disabled={disabled}
onChange={(e) => {
if (e.target.files?.length) addFiles(e.target.files);
e.target.value = "";
}}
/>
<Stack gap={8} align="center">
<ThemeIcon
variant="light"
color={dragOver ? "edr-green" : "gray"}
radius="xl"
size={48}
>
<UploadCloud size={24} />
</ThemeIcon>
<Box>
<Text size="sm" fw={600}>
{dragOver
? "Drop to add files"
: replaceMode
? "Drag & drop to replace declaration files"
: "Drag & drop declaration files here"}
</Text>
<Text size="xs" c="dimmed" mt={4}>
or{" "}
<span style={{ color: "var(--mantine-color-edr-green-7)", fontWeight: 600 }}>
browse
</span>{" "}
select one or more PDF or image files
</Text>
</Box>
</Stack>
</Box>
</Stack>
);
}

View File

@@ -0,0 +1,94 @@
import { Badge, Box, Button, Group, Paper, Text, ThemeIcon, Tooltip } from "@mantine/core";
import { Download, Eye, FileText } from "lucide-react";
import { isViewable } from "@edr/ui-common";
import { fileViewUrl } from "@/constants/apiConfig";
export interface PhasedUploadedFileRowProps {
label: string;
file: { id: string; name: string };
onView?: (file: { name: string; url: string }) => void;
onDownload?: (file: { id: string; name: string }) => void;
compact?: boolean;
}
/** Inline preview row for a phased customs upload (declaration, transit permit, DO, etc.). */
export function PhasedUploadedFileRow({
label,
file,
onView,
onDownload,
compact = false,
}: PhasedUploadedFileRowProps) {
const viewUrl = fileViewUrl(file.id);
const canPreview = isViewable({ name: file.name, url: viewUrl });
return (
<Paper
withBorder
radius="md"
p={compact ? "xs" : "sm"}
style={{
borderColor: "var(--mantine-color-edr-green-3)",
background:
"linear-gradient(135deg, var(--mantine-color-edr-green-0) 0%, #FFFFFF 75%)",
}}
>
<Group justify="space-between" wrap="nowrap" align="center">
<Group gap={10} wrap="nowrap" style={{ minWidth: 0 }}>
<ThemeIcon variant="light" color="edr-green" radius="md" size={compact ? 32 : 36}>
<FileText size={compact ? 15 : 17} />
</ThemeIcon>
<Box style={{ minWidth: 0 }}>
<Text size="sm" fw={600} truncate>
{label}
</Text>
<Group gap={6} wrap="nowrap" mt={2}>
<Badge size="xs" variant="light" color="edr-green" radius="sm">
Uploaded
</Badge>
<Text size="xs" c="dimmed" truncate>
{file.name}
</Text>
</Group>
</Box>
</Group>
<Group gap={6} wrap="nowrap">
{canPreview && onView ? (
<Tooltip label="Preview">
<Button
size="compact-xs"
variant="default"
radius="md"
leftSection={<Eye size={13} />}
onClick={() => onView({ name: file.name, url: viewUrl })}
>
View
</Button>
</Tooltip>
) : null}
{onDownload ? (
<Tooltip label="Download">
<Button
size="compact-xs"
variant="light"
radius="md"
leftSection={<Download size={13} />}
onClick={() => onDownload({ id: file.id, name: file.name })}
>
Download
</Button>
</Tooltip>
) : null}
</Group>
</Group>
</Paper>
);
}
export function findWorkflowFile(
files: Array<{ code: string; file: { id: string; name: string } | null }> | undefined,
code: string,
): { id: string; name: string } | null {
return files?.find((f) => f.code === code)?.file ?? null;
}

View File

@@ -0,0 +1,106 @@
import { useState } from "react";
import { Button, Paper, Stack, Text } from "@mantine/core";
import { Upload } from "lucide-react";
import { PhasedMultiFileDropzone } from "@/components/contracts/PhasedFileDropzone";
import { PhasedUploadedFileRow } from "@/components/contracts/PhasedUploadedFileRow";
export type TransitPermitUploadedRow = {
code: string;
label: string;
file: { id: string; name: string };
};
export interface TransitPermitMultiUploadProps {
title?: string;
uploaded?: TransitPermitUploadedRow[];
replaceMode?: boolean;
submitLabel?: string;
fileFieldPrefix: string;
disabled?: boolean;
onSubmit: (files: Record<string, File>) => Promise<void>;
onViewFile?: (file: { name: string; url: string }) => void;
onDownloadFile?: (file: { id: string; name: string }) => void;
}
/** Multi-file transit permit upload — import pre-booking and export post-booking. */
export function TransitPermitMultiUpload({
title = "Transit Permit",
uploaded = [],
replaceMode = false,
submitLabel,
fileFieldPrefix,
disabled = false,
onSubmit,
onViewFile,
onDownloadFile,
}: TransitPermitMultiUploadProps) {
const [files, setFiles] = useState<File[]>([]);
const [loading, setLoading] = useState(false);
const label = submitLabel ?? (replaceMode ? "Replace transit permit" : "Upload transit permit");
return (
<Stack gap="md">
<Text size="sm" fw={700}>
{title}
</Text>
{uploaded.length > 0 ? (
<Stack gap={8}>
<Text size="xs" fw={700} c="dimmed" tt="uppercase">
Current file{uploaded.length > 1 ? "s" : ""}
</Text>
{uploaded.map((row) => (
<PhasedUploadedFileRow
key={row.code}
label={row.label}
file={row.file}
onView={onViewFile}
onDownload={onDownloadFile}
/>
))}
</Stack>
) : null}
<Paper withBorder radius="md" p="md" bg="var(--mantine-color-gray-0)">
<PhasedMultiFileDropzone
label="Transit permit documents"
description={
replaceMode
? "Replace transit permit files — upload one or more documents (PDF or image)."
: "Upload one or more transit permit documents (PDF or image)."
}
value={files}
onChange={setFiles}
replaceMode={replaceMode}
disabled={disabled || loading}
/>
</Paper>
<Button
color="edr-green"
loading={loading}
disabled={disabled || files.length === 0}
leftSection={<Upload size={16} />}
fullWidth
onClick={async () => {
setLoading(true);
try {
const payload = Object.fromEntries(
files.map((file, index) => [`${fileFieldPrefix}_${index}`, file]),
) as Record<string, File>;
await onSubmit(payload);
setFiles([]);
} catch {
// Caller shows toast for upload errors.
} finally {
setLoading(false);
}
}}
>
{label}
</Button>
</Stack>
);
}

View File

@@ -0,0 +1,322 @@
import type { LucideIcon } from "lucide-react";
import {
Building2,
Download,
Eye,
FileCheck,
FileText,
Globe,
Hash,
Mail,
MapPin,
Phone,
ShieldCheck,
User,
} from "lucide-react";
import {
ActionIcon,
Badge,
Divider,
Group,
Loader,
Stack,
Text,
ThemeIcon,
Tooltip,
} from "@mantine/core";
import { useQuery } from "@tanstack/react-query";
import type { Freight } from "@edr/types";
import { clearanceWorkflowFileLabel } from "@edr/types";
import { SectionCard } from "@/components/bookings/detail/SectionCard";
import { detailStyles } from "@/components/bookings/detail/booking-detail.styles";
import { customersService } from "@/services/customers.service";
type ContractFile = NonNullable<Freight.IContract["files"]>[number];
// ── shared bits ──────────────────────────────────────────────────────────────
interface InfoRowProps {
icon: LucideIcon;
label: string;
value?: string | null;
}
function InfoRow({ icon: Icon, label, value }: InfoRowProps) {
return (
<Group justify="space-between" wrap="nowrap" py={6} gap="md">
<Group gap="xs" wrap="nowrap">
<Icon size={15} color="var(--mantine-color-gray-5)" />
<Text size="sm" c="dimmed">
{label}
</Text>
</Group>
<Text size="sm" fw={600} ta="right" style={{ minWidth: 0 }} truncate>
{value || "—"}
</Text>
</Group>
);
}
function InfoRows({ rows }: { rows: InfoRowProps[] }) {
const visible = rows.filter((r) => r.value);
if (visible.length === 0) {
return (
<Text size="sm" c="dimmed">
No details available.
</Text>
);
}
return (
<Stack gap={0}>
{visible.map((row, i) => (
<div key={row.label}>
{i > 0 && <Divider color="var(--mantine-color-gray-2)" />}
<InfoRow {...row} />
</div>
))}
</Stack>
);
}
// ── Customer tab ─────────────────────────────────────────────────────────────
/**
* Customer info for the contract. The contract detail payload only carries a
* `companyId`, so we fetch the full company record to surface contact + manager
* details (mirrors the booking-request customer card).
*/
export function ContractCustomerCard({
contract,
}: {
contract: Freight.IContract;
}) {
const companyId = contract.companyId ?? undefined;
const { data: company, isLoading } = useQuery({
queryKey: ["companies", "byId", companyId],
queryFn: () => customersService.getById(companyId!),
enabled: Boolean(companyId) && !contract.isGovernment,
});
// Government contracts carry an institution name instead of a company.
if (contract.isGovernment) {
return (
<SectionCard icon={Building2} title="Customer" accent="blue">
<InfoRows
rows={[
{
icon: Building2,
label: "Government",
value: contract.governmentInstitution ?? "Government",
},
]}
/>
</SectionCard>
);
}
if (isLoading) {
return (
<SectionCard icon={Building2} title="Customer" accent="blue">
<Group gap="sm" py="sm">
<Loader size="sm" color="gray" />
<Text size="sm" c="dimmed">
Loading customer
</Text>
</Group>
</SectionCard>
);
}
if (!company) {
return (
<SectionCard icon={Building2} title="Customer" accent="blue">
<Text size="sm" c="dimmed">
No customer linked to this contract.
</Text>
</SectionCard>
);
}
return (
<Stack gap="lg">
<SectionCard
icon={Building2}
title="Customer"
subtitle={company.name}
accent="blue"
>
<InfoRows
rows={[
{ icon: FileCheck, label: "TIN", value: company.tin },
{ icon: Hash, label: "VAT number", value: company.vatNumber },
{ icon: ShieldCheck, label: "FAN number", value: company.fanNumber },
{ icon: Globe, label: "Country", value: company.country },
{ icon: Mail, label: "Email", value: company.email },
{ icon: Phone, label: "Phone", value: company.phone },
{ icon: MapPin, label: "Address", value: company.address },
{ icon: Globe, label: "Website", value: company.website },
]}
/>
</SectionCard>
<SectionCard icon={User} title="Contact person" accent="teal">
<InfoRows
rows={[
{ icon: User, label: "Name", value: company.contactPersonName },
{ icon: Phone, label: "Phone", value: company.contactPersonPhone },
]}
/>
</SectionCard>
<SectionCard icon={User} title="General manager" accent="grape">
<InfoRows
rows={[
{ icon: User, label: "Name", value: company.generalManagerName },
{ icon: Mail, label: "Email", value: company.generalManagerEmail },
{ icon: Phone, label: "Phone", value: company.generalManagerPhone },
]}
/>
</SectionCard>
</Stack>
);
}
// ── Documents tab ────────────────────────────────────────────────────────────
function formatBytes(bytes?: number | null): string {
if (!bytes || bytes <= 0) return "—";
const units = ["B", "KB", "MB", "GB"];
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
unit += 1;
}
return `${value.toFixed(value >= 10 || unit === 0 ? 0 : 1)} ${units[unit]}`;
}
/** Human label for a file's `code` (e.g. "business_license" → "Business license"). */
function codeLabel(code?: string | null): string | null {
if (!code) return null;
return (
clearanceWorkflowFileLabel(code) ??
code.replace(/[_-]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())
);
}
export interface ContractDocumentsCardProps {
files: ContractFile[];
/** Open the file inline in a viewer modal. */
onView?: (file: ContractFile) => void;
/** Download the file to disk. */
onDownload?: (file: ContractFile) => void;
}
/** Rich list of the contract's attached documents: type, size, view + download. */
export function ContractDocumentsCard({
files,
onView,
onDownload,
}: ContractDocumentsCardProps) {
return (
<SectionCard
icon={FileText}
title="Documents"
accent="indigo"
extra={
<Badge color="gray" variant="light" radius="sm">
{files.length}
</Badge>
}
>
{files.length === 0 ? (
<Text size="sm" c="dimmed">
No documents attached to this contract.
</Text>
) : (
<Stack gap="xs">
{files.map((file) => {
const label = codeLabel(file.code);
return (
<Group
key={file.id}
justify="space-between"
wrap="nowrap"
p="xs"
style={detailStyles.fileRow}
onMouseEnter={(e) => {
e.currentTarget.style.background =
"var(--mantine-color-gray-0)";
e.currentTarget.style.borderColor =
"var(--freight-brand-border)";
}}
onMouseLeave={(e) => {
e.currentTarget.style.background = "transparent";
e.currentTarget.style.borderColor =
"var(--mantine-color-gray-2)";
}}
>
<Group gap="sm" wrap="nowrap" style={{ minWidth: 0 }}>
<ThemeIcon size={36} radius="md" variant="light" color="indigo">
<FileText size={17} />
</ThemeIcon>
<Stack gap={2} style={{ minWidth: 0 }}>
<Text size="sm" fw={500} truncate>
{file.name}
</Text>
<Group gap={6} wrap="nowrap">
{label ? (
<Badge
variant="light"
color="gray"
radius="sm"
size="xs"
tt="none"
>
{label}
</Badge>
) : null}
<Text size="xs" c="dimmed">
{formatBytes(file.size)}
</Text>
</Group>
</Stack>
</Group>
<Group gap={4} wrap="nowrap">
{onView ? (
<Tooltip label="View" withArrow>
<ActionIcon
variant="subtle"
color="indigo"
radius="md"
onClick={() => onView(file)}
aria-label={`View ${file.name}`}
>
<Eye size={16} />
</ActionIcon>
</Tooltip>
) : null}
{onDownload ? (
<Tooltip label="Download" withArrow>
<ActionIcon
variant="subtle"
color="gray"
radius="md"
onClick={() => onDownload(file)}
aria-label={`Download ${file.name}`}
>
<Download size={16} />
</ActionIcon>
</Tooltip>
) : null}
</Group>
</Group>
);
})}
</Stack>
)}
</SectionCard>
);
}

View File

@@ -0,0 +1,275 @@
import type { LucideIcon } from "lucide-react";
import {
Building2,
FileCheck,
FileText,
Mail,
MapPin,
Package,
Phone,
Ship,
Truck,
User,
Warehouse,
} from "lucide-react";
import { Badge, Box, Divider, Group, Stack, Text } from "@mantine/core";
import type { Freight } from "@edr/types";
import { SectionCard } from "@/components/bookings/detail/SectionCard";
type ReqContract = NonNullable<Freight.IBookingRequest["contract"]>;
interface InfoRowProps {
icon: LucideIcon;
label: string;
value?: string | null;
}
function InfoRow({ icon: Icon, label, value }: InfoRowProps) {
return (
<Group justify="space-between" wrap="nowrap" py={6} gap="md">
<Group gap="xs" wrap="nowrap">
<Icon size={15} color="var(--mantine-color-gray-5)" />
<Text size="sm" c="dimmed">
{label}
</Text>
</Group>
<Text size="sm" fw={600} ta="right" style={{ minWidth: 0 }} truncate>
{value || "—"}
</Text>
</Group>
);
}
function InfoRows({ rows }: { rows: InfoRowProps[] }) {
const visible = rows.filter((r) => r.value);
if (visible.length === 0) {
return (
<Text size="sm" c="dimmed">
No details available.
</Text>
);
}
return (
<Stack gap={0}>
{visible.map((row, i) => (
<div key={row.label}>
{i > 0 && <Divider color="var(--mantine-color-gray-2)" />}
<InfoRow {...row} />
</div>
))}
</Stack>
);
}
/** Customer (company) on the request's contract. */
export function RequestCustomerCard({ contract }: { contract?: ReqContract | null }) {
const company = contract?.company;
if (!company) {
return (
<SectionCard icon={Building2} title="Customer" accent="blue">
<Text size="sm" c="dimmed">
No customer linked to this request.
</Text>
</SectionCard>
);
}
return (
<SectionCard
icon={Building2}
title="Customer"
subtitle={company.name ?? undefined}
accent="blue"
>
<InfoRows
rows={[
{ icon: FileCheck, label: "TIN", value: company.tin },
{ icon: Mail, label: "Email", value: company.email },
{ icon: Phone, label: "Phone", value: company.phone },
{ icon: MapPin, label: "Address", value: company.address },
{ icon: User, label: "Contact", value: company.contactPersonName },
{ icon: Phone, label: "Contact phone", value: company.contactPersonPhone },
]}
/>
</SectionCard>
);
}
const fmtDate = (iso?: string | null) =>
iso
? new Intl.DateTimeFormat("en-GB", {
day: "2-digit",
month: "short",
year: "numeric",
}).format(new Date(iso))
: "—";
const titleCase = (s?: string | null) =>
s ? s.charAt(0) + s.slice(1).toLowerCase() : "—";
/** Contract identity + commercial terms. */
export function RequestContractSummaryCard({
contract,
}: {
contract?: ReqContract | null;
}) {
if (!contract) return null;
return (
<SectionCard
icon={FileText}
title="Contract"
subtitle={contract.reference}
accent="grape"
>
<InfoRows
rows={[
{
icon: FileText,
label: "Kind",
value: contract.contractKind === "GENERAL" ? "General" : "One-time",
},
{
icon: Package,
label: "Cargo",
value: contract.freightType === "CONTAINER" ? "Container" : "Bulk",
},
{ icon: Ship, label: "Trade", value: titleCase(contract.tradeDirection) },
{ icon: FileCheck, label: "Currency", value: contract.paymentCurrency },
{
icon: FileCheck,
label: "Customs",
value: contract.customsClearingEnabled
? "Included (Global Logistics)"
: "Not included",
},
{
icon: FileText,
label: "Valid until",
value: contract.contractValidUntil
? fmtDate(contract.contractValidUntil)
: "Not active yet",
},
]}
/>
</SectionCard>
);
}
/** Routes + cargo scope of the contract. */
export function RequestRouteCargoCard({
contract,
}: {
contract?: ReqContract | null;
}) {
const routes = contract?.routes ?? [];
const cargo = contract?.cargoScope ?? [];
const isContainer = contract?.freightType === "CONTAINER";
return (
<SectionCard icon={MapPin} title="Route & cargo" accent="teal">
<Stack gap="md">
<Box>
<Text size="xs" c="dimmed" fw={600} mb={6} tt="uppercase">
Routes
</Text>
{routes.length === 0 ? (
<Text size="sm" c="dimmed">
No routes recorded.
</Text>
) : (
<Stack gap={6}>
{routes.map((r) => (
<Group key={r.id} gap={8} wrap="nowrap">
<MapPin size={14} color="var(--mantine-color-gray-5)" />
<Text size="sm" fw={500} truncate>
{r.originYard?.label ?? r.originYardId} {" "}
{r.destinationYard?.label ?? r.destinationYardId}
</Text>
</Group>
))}
</Stack>
)}
</Box>
<Box>
<Text size="xs" c="dimmed" fw={600} mb={6} tt="uppercase">
Cargo scope
</Text>
{cargo.length === 0 ? (
<Text size="sm" c="dimmed">
No cargo scope recorded.
</Text>
) : (
<Group gap={6} wrap="wrap">
{cargo.map((c) => (
<Badge
key={c.id}
variant="light"
color="teal"
radius="sm"
leftSection={<Package size={11} />}
>
{c.containerSize ??
c.cargoFreeText ??
(isContainer ? "Container" : "Bulk commodity")}
</Badge>
))}
</Group>
)}
</Box>
</Stack>
</SectionCard>
);
}
/** Service type — what the contracted service bundles (rail-only vs logistics/customs). */
export function RequestServiceTypeCard({
contract,
}: {
contract?: ReqContract | null;
}) {
const st = contract?.serviceType;
if (!st) return null;
const firstMile = st.includesFirstMile ?? false;
const lastMile = st.includesLastMile ?? false;
const customs = st.includesCustoms ?? false;
const railOnly = !firstMile && !lastMile && !customs;
const chips: Array<{ label: string; color: string; icon: LucideIcon }> = [];
if (railOnly) chips.push({ label: "Rail only", color: "blue", icon: Ship });
if (firstMile)
chips.push({ label: "First-mile pickup", color: "teal", icon: Truck });
if (lastMile)
chips.push({ label: "Last-mile delivery", color: "teal", icon: Warehouse });
if (customs)
chips.push({ label: "Customs clearance (GL)", color: "grape", icon: FileCheck });
return (
<SectionCard
icon={Ship}
title="Service"
subtitle={st.serviceName}
accent="indigo"
>
<Stack gap="sm">
<Group gap={6} wrap="wrap">
{chips.map((c) => (
<Badge
key={c.label}
variant="light"
color={c.color}
radius="sm"
leftSection={<c.icon size={11} />}
>
{c.label}
</Badge>
))}
</Group>
{st.description ? (
<Text size="sm" c="dimmed">
{st.description}
</Text>
) : null}
</Stack>
</SectionCard>
);
}

View File

@@ -9,6 +9,7 @@ import { AssignStationCard } from "./AssignStationCard";
import { AssignRiskCard } from "./AssignRiskCard";
import { AdviseDutyCard } from "./AdviseDutyCard";
import { GlDocumentUploadCard } from "./GlDocumentUploadCard";
import { TransportDocumentCard } from "./TransportDocumentCard";
import { IncidentReportCard } from "./IncidentReportCard";
export interface GlActionsPanelProps {
@@ -39,6 +40,16 @@ export function GlActionsPanel({ bookingId, milestones }: GlActionsPanelProps) {
() => findMilestone(milestones, "DUTY_TAXES_ADVISED"),
[milestones],
);
const wagonMs = useMemo(
() => findMilestone(milestones, "WAGON_ALLOCATED"),
[milestones],
);
const transportMs = useMemo(
() => findMilestone(milestones, "EXPORT_TRANSPORT_ISSUED"),
[milestones],
);
const showTransport =
wagonMs?.status === "COMPLETED" && transportMs?.status !== "COMPLETED";
return (
<SectionCard icon={Flag} title="Global Logistics actions" accent="edr-green">
@@ -56,6 +67,8 @@ export function GlActionsPanel({ bookingId, milestones }: GlActionsPanelProps) {
<GlDocumentUploadCard bookingId={bookingId} />
{showTransport ? <TransportDocumentCard bookingId={bookingId} /> : null}
{riskMs ? (
<AssignRiskCard bookingId={bookingId} milestone={riskMs} />
) : null}

View File

@@ -0,0 +1,49 @@
import { useState } from "react";
import { Button, FileInput, Stack } from "@mantine/core";
import { FileText } from "lucide-react";
import toast from "react-hot-toast";
import { ActionShell } from "./ActionShell";
import { contractsService } from "@/services/contracts.service";
export function TransportDocumentCard({ bookingId }: { bookingId: string }) {
const [file, setFile] = useState<File | null>(null);
const [loading, setLoading] = useState(false);
return (
<ActionShell
icon={FileText}
title="Transit permit"
subtitle="Upload after wagon allocation (GL Ethiopia)"
done={false}
>
<Stack gap="sm">
<FileInput
label="Transit permit"
value={file}
onChange={setFile}
size="sm"
/>
<Button
color="edr-green"
loading={loading}
disabled={!file}
onClick={async () => {
if (!file) return;
setLoading(true);
try {
await contractsService.uploadTransportDocument(bookingId, file);
toast.success("Transport document uploaded");
} catch (e) {
toast.error(e instanceof Error ? e.message : "Upload failed");
} finally {
setLoading(false);
}
}}
>
Upload document
</Button>
</Stack>
</ActionShell>
);
}

View File

@@ -0,0 +1,52 @@
import { Alert, Badge, Group, Stack, Text } from "@mantine/core";
import { Boxes } from "lucide-react";
import { useContractCapacity } from "@/hooks/contracts/useContracts";
export function ContractCapacityNotice({
contractId,
isContainer,
}: {
contractId: string;
isContainer: boolean;
}) {
const { data: lines = [] } = useContractCapacity(contractId);
if (lines.length === 0) return null;
const allFull = lines.every((l) => l.remaining === 0);
const unit = isContainer ? "" : " tons";
return (
<Alert
color={allFull ? "red" : "edr-green"}
variant="light"
radius="md"
icon={<Boxes size={16} />}
title={allFull ? "Contract capacity reached" : "Remaining contract capacity"}
>
{allFull ? (
<Text fz={13}>
This contract has been fully booked. No further shipments can be created
against it.
</Text>
) : (
<Stack gap={6} mt={4}>
{lines.map((l, i) => (
<Group key={i} justify="space-between" wrap="nowrap">
<Text fz={13}>{l.containerSize ?? "Bulk"}</Text>
<Badge
color={l.remaining === 0 ? "red" : "edr-green"}
variant="light"
radius="sm"
>
{l.remaining}
{unit} of {l.cap} left
</Badge>
</Group>
))}
</Stack>
)}
</Alert>
);
}

View File

@@ -0,0 +1,93 @@
import { Box, Group, Paper, Text, Title } from "@mantine/core";
import type { ReactNode } from "react";
const INK = "#10202F";
const MUTED = "#6B7C8E";
const BORDER = "#E6ECF2";
const GREEN_DARK = "#0A6F4D";
export const fieldStyles = {
label: { fontWeight: 600, fontSize: 13, color: INK, marginBottom: 6 },
input: {
borderRadius: 12,
minHeight: 46,
height: 46,
fontSize: 14,
borderColor: BORDER,
},
};
export function StepLabel({ children }: { children: ReactNode }) {
return (
<Text
fz={11}
fw={700}
tt="uppercase"
c={MUTED}
style={{ letterSpacing: "0.07em" }}
>
{children}
</Text>
);
}
export function StepCard({
children,
eyebrow,
}: {
children: ReactNode;
eyebrow?: ReactNode;
}) {
return (
<Paper
radius={20}
p={{ base: "lg", sm: 28 }}
withBorder
bg="white"
style={{ borderColor: BORDER, boxShadow: "0 2px 14px rgba(16,24,40,0.04)" }}
>
{eyebrow}
{children}
</Paper>
);
}
export function StepHeader({
title,
description,
icon,
}: {
title: string;
description: string;
icon?: ReactNode;
}) {
return (
<Group gap={14} align="flex-start" wrap="nowrap" mb={22}>
{icon ? (
<Box
style={{
flexShrink: 0,
width: 44,
height: 44,
borderRadius: 13,
display: "flex",
alignItems: "center",
justifyContent: "center",
background: "linear-gradient(135deg, #ECF6F1, #E4F3EC)",
color: GREEN_DARK,
}}
>
{icon}
</Box>
) : null}
<Box>
<Title order={3} fz={20} fw={800} c={INK} style={{ letterSpacing: "-0.01em" }}>
{title}
</Title>
<Text size="sm" c={MUTED} mt={4} style={{ lineHeight: 1.5 }}>
{description}
</Text>
</Box>
</Group>
);
}

View File

@@ -184,6 +184,13 @@ const ROUTE_META: Array<{ prefix: string; meta: PageMeta }> = [
subtitle: "Manage dropdown options used across the platform",
},
},
{
prefix: "/dashboard/configuration/contract-validity-periods",
meta: {
title: "Contract validity periods",
subtitle: "Validity options staff choose when accepting a submitted contract",
},
},
{
prefix: "/dashboard/configuration/train-scheduling-rules",
meta: {

View File

@@ -307,6 +307,14 @@ const RuleEngineFormDialog = ({
size="md"
radius="md"
styles={inputStyles}
rightSection={
field.suffix ? (
<Text size="sm" c="dimmed" fw={600} pr={4}>
{field.suffix}
</Text>
) : undefined
}
rightSectionWidth={field.suffix ? 52 : undefined}
/>
);
};

View File

@@ -94,6 +94,15 @@ export const formatCell = (value: unknown, format?: ColumnFormat): ReactNode =>
return <Text size="sm">{Number.isNaN(num) ? String(value) : num.toLocaleString()}</Text>;
}
if (format === "currency") {
const num = Number(value);
return (
<Text size="sm" fw={500}>
{Number.isNaN(num) ? String(value) : `USD ${num.toLocaleString()}`}
</Text>
);
}
if (format === "date") {
const d = new Date(String(value));
if (Number.isNaN(d.getTime())) return <Text size="sm">{String(value)}</Text>;

View File

@@ -34,6 +34,7 @@ import {
import { useMutation, useQuery } from "@tanstack/react-query";
import { api } from "@/services/api";
import { formatRouteLabel } from "@/services/routes.service";
import { useToast } from "@/hooks/use-toast";
import { trainSchedulingService } from "@/services/trainScheduling.service";
import type { BookingDetail } from "@/types/booking";
@@ -138,7 +139,9 @@ export function AllocateBookingWizard({
const schedulesQuery = useQuery(
api.trainScheduling.scheduleList.queryOptions({ input: {} }),
);
const routesQuery = useQuery(api.routes.list.queryOptions());
const routesQuery = useQuery(
api.routes.list.queryOptions({ input: { status: "AVAILABLE" } }),
);
const locomotivesQuery = useQuery(
api.trainScheduling.availableLocomotives.queryOptions({
input: {
@@ -244,7 +247,7 @@ export function AllocateBookingWizard({
}, [containerUnits, containerSlots, savedPlacementsFromSchedule]);
const activeRoutes = useMemo(
() => (routesQuery.data ?? []).filter((r) => r.isActive),
() => routesQuery.data ?? [],
[routesQuery.data],
);
@@ -522,7 +525,7 @@ export function AllocateBookingWizard({
<SimpleGrid cols={{ base: 1, sm: 2 }} spacing="sm">
<Select
label="Route"
data={activeRoutes.map((r) => ({ value: r.id, label: r.name }))}
data={activeRoutes.map((r) => ({ value: r.id, label: formatRouteLabel(r) }))}
value={routeId || null}
onChange={(v) => setRouteId(v ?? "")}
searchable

View File

@@ -31,9 +31,6 @@ export interface WarehouseHandoverPdfContext {
const escapePdfText = (value: string) =>
value.replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
const money = (amount: unknown, currency = 'USD') =>
`${Number(amount ?? 0).toLocaleString()} ${currency === 'ETB' ? 'Birr (ETB)' : currency}`;
const fmtDate = (value: unknown) => {
if (!value) return '-';
const date = new Date(value as string | Date);
@@ -96,12 +93,6 @@ const textOp = (
color = '0 0 0',
) => `BT\n${color} rg\n/${bold ? 'F2' : 'F1'} ${size} Tf\n${x} ${y} Td\n(${escapePdfText(text)}) Tj\nET`;
const buildAuthorizationBand = (label: 'PAID' | 'CLEARED') => [
lineOp(60, 242, 535, 242),
textOp('AUTHORIZED SEAL', 382, 218, 9, true, GREEN),
buildCircularSeal(452, 155, label),
];
const buildWarehouseOfficerSealBand = () => [
lineOp(60, 218, 535, 218),
textOp('WAREHOUSE OFFICER SEAL', 92, 194, 9, true, GREEN),
@@ -146,57 +137,6 @@ function buildSimplePdf(lines: PdfLine[], rawOps: string[] = []): Blob {
return new Blob([pdf], { type: 'application/pdf' });
}
export function buildWarehouseInvoicePdf(invoice: WarehouseFeeInvoice, kind: 'INVOICE' | 'RECEIPT') {
const paid = kind === 'RECEIPT' || invoice.status === 'PAID';
const title = `Warehouse Fee ${kind === 'RECEIPT' ? 'Receipt' : 'Invoice'}`;
const bookingReference = firstText(invoice.bookingReference);
const customerName = firstText(invoice.customerName);
const inventoryReference = firstText(invoice.inventoryReference);
const inventoryInfo = firstText(invoice.inventoryInfo, invoice.containerNumber, invoice.cargoDescription);
const clearanceStatus = firstText(
invoice.clearanceStatus,
paid ? 'FEE PAID - READY FOR RELEASE' : 'PENDING PAYMENT',
);
const lines: PdfLine[] = [
{ text: 'Ethio-Djibouti Railway S.C.', size: 12, bold: true, yGap: 0, align: 'center' },
{ text: title, size: 23, bold: true, yGap: 28, align: 'center' },
{ text: `Document No: ${invoice.invoiceNumber}`, size: 12, bold: true, yGap: 32, align: 'center' },
{ text: `Status: ${invoice.status.replace(/_/g, ' ')} Type: ${invoice.invoiceType.replace(/_/g, ' ')}`, align: 'center' },
{ text: `Booking Reference: ${bookingReference} Customer: ${customerName}`, align: 'center' },
{ text: `Inventory Reference: ${inventoryReference} Inventory Info: ${inventoryInfo}`, align: 'center' },
{ text: `Clearance: ${clearanceStatus}`, align: 'center' },
{ text: `Issued: ${fmtDate(invoice.issuedAt)} Paid At: ${fmtDate(invoice.paidAt)}`, align: 'center' },
{ text: 'ITEMS', size: 13, bold: true, yGap: 30, align: 'center' },
...(invoice.items ?? []).flatMap((item) => [
{ text: item.description, bold: true, align: 'center' as const },
{
text: `${item.feeType.replace(/_/g, ' ')} | Qty ${Number(item.quantity ?? 0).toLocaleString()} | Rate ${money(item.unitRate, item.currency)} | Amount ${money(item.amount, item.currency)}`,
yGap: 13,
align: 'center' as const,
},
]),
{ text: 'TOTALS', size: 13, bold: true, yGap: 30, align: 'center' },
{ text: `Subtotal: ${money(invoice.subtotalAmount, invoice.currency)}`, align: 'center' },
{ text: `Tax: ${money(invoice.taxAmount, invoice.currency)}`, align: 'center' },
{ text: `Total: ${money(invoice.totalAmount, invoice.currency)}`, bold: true, align: 'center' },
{ text: `Paid: ${money(invoice.paidAmount, invoice.currency)}`, align: 'center' },
{ text: `Balance: ${money(invoice.balanceAmount, invoice.currency)}`, bold: true, align: 'center' },
];
const authorizationOps = [
...buildAuthorizationBand('PAID'),
textOp('Prepared by EDR warehouse finance', 72, 196, 10),
textOp('Finance officer name / signature / date:', 72, 164, 10),
lineOp(245, 162, 360, 162, '0 0 0'),
];
const invoiceOps = [
lineOp(60, 242, 535, 242),
textOp('Prepared by EDR warehouse finance', 72, 196, 10),
textOp('Finance officer name / signature / date:', 72, 164, 10),
lineOp(245, 162, 360, 162, '0 0 0'),
];
return buildSimplePdf(lines, paid ? authorizationOps : invoiceOps);
}
const firstText = (...values: Array<unknown>) => {
for (const value of values) {
if (value !== null && value !== undefined && String(value).trim()) return String(value);

View File

@@ -44,6 +44,8 @@ export const QUERY_KEYS = {
listSummary: (filter?: BookingListFilter) =>
["bookings", "list-summary", filter ?? {}] as const,
byId: (id: string) => ["bookings", "detail", id] as const,
clearanceQueue: (region?: string) =>
["bookings", "clearance-queue", region ?? "ET"] as const,
},
CONTRACTS: {
@@ -98,6 +100,12 @@ export const QUERY_KEYS = {
list: (resource: FleetResourceSlug | string) => ["fleet", "list", resource] as const,
},
VEHICLES: {
ROOT: ["vehicles"] as const,
list: (filter?: Record<string, unknown>) => ["vehicles", "list", filter ?? {}] as const,
byId: (id: string) => ["vehicles", "detail", id] as const,
},
FIRST_MILE: {
ROOT: ["first-mile"] as const,
list: (filter?: Record<string, unknown>) => ["first-mile", "list", filter ?? {}] as const,
@@ -135,4 +143,24 @@ export const QUERY_KEYS = {
customersTab: (range?: string) => ["overview", "customers", range ?? "30d"] as const,
staffTab: (range?: string) => ["overview", "staff", range ?? "30d"] as const,
},
FUEL: {
ROOT: ["fuel"] as const,
purchases: (vehicleId?: string) => ["fuel", "purchases", vehicleId ?? "all"] as const,
stats: (vehicleId?: string) => ["fuel", "stats", vehicleId ?? "all"] as const,
},
MAINTENANCE: {
ROOT: ["maintenance"] as const,
schedules: (vehicleId?: string) => ["maintenance", "schedules", vehicleId ?? "all"] as const,
upcoming: (vehicleId?: string) => ["maintenance", "upcoming", vehicleId ?? "all"] as const,
history: (vehicleId?: string) => ["maintenance", "history", vehicleId ?? "all"] as const,
stats: (vehicleId?: string) => ["maintenance", "stats", vehicleId ?? "all"] as const,
},
FINANCIAL_REPORTS: {
ROOT: ["financial-reports"] as const,
fleet: (vehicleId?: string, months?: number) =>
["financial-reports", "fleet", vehicleId ?? "all", months ?? 12] as const,
},
} as const;

View File

@@ -123,6 +123,18 @@ export const URL_CONSTANTS = {
COMPLETE: (id: string) => `/bookings/${id}/operations/complete`,
CANCEL: (id: string) => `/bookings/${id}/cancel`,
CONSOLIDATION: (id: string) => `/bookings/${id}/consolidation`,
CLEARANCE: (id: string) => `/bookings/${id}/clearance`,
CLEARANCE_DECLARATION: (id: string) => `/bookings/${id}/clearance/declaration`,
CLEARANCE_DUTY: (id: string) => `/bookings/${id}/clearance/duty`,
CLEARANCE_FINALIZE_PRE: (id: string) =>
`/bookings/${id}/clearance/finalize-pre-clearance`,
CLEARANCE_TRANSIT_PERMIT: (id: string) => `/bookings/${id}/clearance/transit-permit`,
CLEARANCE_DELIVERY_ORDER: (id: string) => `/bookings/${id}/clearance/delivery-order`,
CLEARANCE_RELEASE_ORDER: (id: string) => `/bookings/${id}/clearance/release-order`,
CLEARANCE_RO_AMENDMENT: (id: string) => `/bookings/${id}/clearance/ro-amendment`,
CLEARANCE_EXPORT_RELEASE: (id: string) => `/bookings/${id}/clearance/export-release`,
CLEARANCE_ET_QUEUE: "/bookings/clearance/et-queue",
CLEARANCE_DJ_QUEUE: "/bookings/clearance/dj-queue",
},
CONTRACTS: {
@@ -137,6 +149,7 @@ export const URL_CONSTANTS = {
`/contracts/${id}/approval-steps/${stepId}/approve`,
CONTRACT_GENERATE: (id: string) => `/contracts/${id}/contract/generate`,
CONTRACT_VIEW: (id: string) => `/contracts/${id}/contract/view`,
CONTRACT_DOCUMENT: (id: string) => `/contracts/${id}/contract/document`,
CONTRACT_SIGN: (id: string) => `/contracts/${id}/contract/sign`,
CLEARANCE_QUEUE: "/contracts/clearance/queue",
CLEARANCE: (id: string) => `/contracts/${id}/clearance`,
@@ -144,6 +157,25 @@ export const URL_CONSTANTS = {
CLEARANCE_OUTPUT_DOCUMENTS: (id: string) =>
`/contracts/${id}/clearance/output-documents`,
CLEARANCE_FINALIZE: (id: string) => `/contracts/${id}/clearance/finalize`,
CLEARANCE_DECLARATION: (id: string) => `/contracts/${id}/clearance/declaration`,
CLEARANCE_DUTY: (id: string) => `/contracts/${id}/clearance/duty`,
CLEARANCE_DUTY_SLIP: (id: string) => `/contracts/${id}/clearance/duty-slip`,
CLEARANCE_FINALIZE_PRE: (id: string) =>
`/contracts/${id}/clearance/finalize-pre-clearance`,
CLEARANCE_TRANSIT_PERMIT: (id: string) =>
`/contracts/${id}/clearance/transit-permit`,
CLEARANCE_DELIVERY_ORDER: (id: string) =>
`/contracts/${id}/clearance/delivery-order`,
CLEARANCE_RELEASE_ORDER: (id: string) =>
`/contracts/${id}/clearance/release-order`,
CLEARANCE_RO_AMENDMENT: (id: string) =>
`/contracts/${id}/clearance/ro-amendment`,
CLEARANCE_EXPORT_RELEASE: (id: string) =>
`/contracts/${id}/clearance/export-release`,
CLEARANCE_FINALIZE_EXPORT: (id: string) =>
`/contracts/${id}/clearance/finalize-export-clearance`,
CLEARANCE_ET_QUEUE: "/contracts/clearance/et-queue",
CLEARANCE_DJ_QUEUE: "/contracts/clearance/dj-queue",
// Path A self-clearance — Operations reviews the customer's own clearance docs.
OPS_CLEARANCE_QUEUE: "/contracts/clearance/ops-queue",
OPS_CLEARANCE_REVIEW: (id: string) =>
@@ -177,6 +209,8 @@ export const URL_CONSTANTS = {
`/contracts/bookings/${bookingId}/station-assign`,
BOOKING_GL_DOCUMENTS: (bookingId: string) =>
`/contracts/bookings/${bookingId}/documents`,
BOOKING_TRANSPORT_DOCUMENT: (bookingId: string) =>
`/contracts/bookings/${bookingId}/transport-document`,
BOOKING_INCIDENTS: (bookingId: string) =>
`/contracts/bookings/${bookingId}/incidents`,
},

View File

@@ -1,12 +1,7 @@
//export const API_BASE_URL = 'https://edrfreightapi.triaplc.com';
export const API_BASE_URL = 'http://localhost:3001';
export const API_BASE_URL = import.meta.env.VITE_BASE_API_URL;
// export const API_BASE_URL = 'http://localhost:3001';
/**
* URL that streams an uploaded file through the API by its UUID. Routes the
* bytes through `GET /api/files/:id` (served from MinIO with backend

View File

@@ -0,0 +1,64 @@
import type { Freight } from "@edr/types";
export interface ShipmentListRow {
id: string;
reference: string;
contractId: string;
contractReference: string;
scheduledDate?: string | null;
summary: string;
status: Freight.BookingRequestStatus;
createdBookingId?: string | null;
}
export type ShipmentRowAction =
| {
kind: "navigate";
label: string;
to: (row: ShipmentListRow) => string;
variant: "filled" | "light" | "default";
}
| {
kind: "reject";
label: string;
variant: "light";
};
/** Primary staff action for a shipment request list row. */
export function getShipmentStaffRowAction(
row: Pick<
ShipmentListRow,
"status" | "contractId" | "id" | "createdBookingId"
>,
): ShipmentRowAction {
if (row.status === "PENDING") {
return {
kind: "navigate",
label: "Accept",
to: (r) =>
`/dashboard/contracts/${r.contractId}/create-booking?requestId=${r.id}`,
variant: "filled",
};
}
if (row.status === "ACCEPTED" && row.createdBookingId) {
return {
kind: "navigate",
label: "View clearance",
to: (r) => `/dashboard/clearance/${r.createdBookingId}`,
variant: "light",
};
}
return {
kind: "navigate",
label: "Review",
to: (r) => `/dashboard/shipment-requests/${r.id}`,
variant: "default",
};
}
export function getShipmentRejectAction(
row: Pick<ShipmentListRow, "status">,
): ShipmentRowAction | null {
if (row.status !== "PENDING") return null;
return { kind: "reject", label: "Reject", variant: "light" };
}

View File

@@ -188,3 +188,19 @@ export function useBookingMutations(bookingId: string) {
downloadContract: () => bookingsService.downloadContract(bookingId),
};
}
export function useBookingEtClearanceQueue(enabled = true) {
return useQuery({
queryKey: QUERY_KEYS.BOOKINGS.clearanceQueue("ET"),
queryFn: () => bookingsService.getEtClearanceQueue(),
enabled,
});
}
export function useBookingDjClearanceQueue(enabled = true) {
return useQuery({
queryKey: QUERY_KEYS.BOOKINGS.clearanceQueue("DJ"),
queryFn: () => bookingsService.getDjClearanceQueue(),
enabled,
});
}

View File

@@ -52,6 +52,22 @@ export function useContractClearanceQueue(enabled = true) {
});
}
export function useEtClearanceQueue(enabled = true) {
return useQuery({
queryKey: QUERY_KEYS.CONTRACTS.clearanceQueue("ET"),
queryFn: () => contractsService.getEtClearanceQueue(),
enabled,
});
}
export function useDjClearanceQueue(enabled = true) {
return useQuery({
queryKey: QUERY_KEYS.CONTRACTS.clearanceQueue("DJ"),
queryFn: () => contractsService.getDjClearanceQueue(),
enabled,
});
}
/** Path A self-clearance queue (Operations reviews non-customs contracts). */
export function useOpsClearanceQueue(enabled = true) {
return useQuery({
@@ -248,7 +264,10 @@ export function useContractClearanceMutations(
);
refresh();
},
onError: () => toast.error("Could not update document"),
onError: (e) =>
toast.error(
e instanceof Error ? e.message : "Could not update document",
),
});
// Approve every still-pending customer document in one click. There is no

View File

@@ -0,0 +1,30 @@
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
/**
* Scroll to the element whose `id` matches the URL hash. Retries for a short
* window so it still lands on sections that mount after an async fetch (there is
* no router-level hash handling). Deep-link targets give a card an `id`.
*/
export function useScrollToHash(): void {
const { hash } = useLocation();
useEffect(() => {
if (!hash) return;
const id = decodeURIComponent(hash.slice(1));
let tries = 0;
let timer: ReturnType<typeof setTimeout>;
const tick = () => {
const el = document.getElementById(id);
if (el) {
el.scrollIntoView({ behavior: "smooth", block: "start" });
return;
}
if (tries++ < 20) timer = setTimeout(tick, 100);
};
timer = setTimeout(tick, 100);
return () => clearTimeout(timer);
}, [hash]);
}

View File

@@ -33,7 +33,9 @@ export const FREIGHT_PERMS = {
clearanceReview: "edr_freight_app:contracts:clearance_review",
finalizeClearance: "edr_freight_app:contracts:finalize_clearance",
createBooking: "edr_freight_app:contracts:create_booking",
opsClearanceReview: "edr_freight_app:contracts:ops_clearance_review",
clearanceDutyAdvise: "edr_freight_app:contracts:clearance_duty_advise",
clearanceEtActions: "edr_freight_app:contracts:clearance_et_actions",
clearanceDjActions: "edr_freight_app:contracts:clearance_dj_actions",
},
trainScheduling: {
view: "edr_freight_app:train_scheduling:view",

View File

@@ -50,6 +50,7 @@ import {
useBookingDetail,
useBookingMutations,
} from "@/hooks/bookings/useBookings";
import { useScrollToHash } from "@/hooks/useScrollToHash";
import toast from "react-hot-toast";
// Signature / generated-contract files are surfaced on the contract page, not
@@ -65,6 +66,8 @@ export default function BookingRequestDetailPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
// Deep-link from a warehouse fee invoice → this booking's warehouse section.
useScrollToHash();
const {
data: booking,
isLoading,
@@ -281,24 +284,28 @@ export default function BookingRequestDetailPage() {
<Stack gap="lg">
<BookingCompanyCard booking={booking} />
<BookingPricingSummary booking={booking} />
<WarehouseInfoCard
bookingId={booking.id}
bookingReference={booking.reference}
/>
<Box id="warehouse-payments">
<WarehouseInfoCard
bookingId={booking.id}
bookingReference={booking.reference}
/>
</Box>
<BookingActionsToolbar
booking={booking}
mutations={mutations}
/>
<Button
fullWidth
variant="default"
leftSection={<Milestone size={16} />}
onClick={() =>
navigate(`/dashboard/bookings/${booking.id}/milestones`)
}
>
View clearance milestones
</Button>
{booking.customsClearingEnabled && (
<Button
fullWidth
variant="default"
leftSection={<Milestone size={16} />}
onClick={() =>
navigate(`/dashboard/bookings/${booking.id}/clearance`)
}
>
View document clearance
</Button>
)}
{showContractButton && (
<Button
fullWidth

View File

@@ -25,27 +25,39 @@ import {
} from "lucide-react";
import type { Freight } from "@edr/types";
import { ClearanceOpsTabs } from "@/components/contracts/ClearanceOpsTabs";
import { PageContainer } from "@/components/page/PageContainer";
import { PageHeader } from "@/components/page/PageHeader";
import { SectionCard } from "@/components/bookings/detail";
import { ClearanceReviewSection } from "@/components/bookings/detail/ClearanceReviewSection";
import { ClearancePhaseStepper } from "@/components/contracts/ClearancePhaseStepper";
import { PhasedClearanceActionPanel } from "@/components/contracts/PhasedClearanceActionPanel";
import { ClearanceMilestoneTimeline } from "@/components/contracts/ClearanceMilestoneTimeline";
import { useFileViewer } from "@/hooks/useFileViewer";
import { useBookingMilestones } from "@/hooks/contracts/useContracts";
import { bookingsService } from "@/services/bookings.service";
import { downloadBookingFile } from "@/services/files.service";
import { useBookingDetail } from "@/hooks/bookings/useBookings";
export default function DocumentClearanceDetailPage() {
const { id } = useParams<{ id: string }>();
const params = useParams<{ id?: string; bookingId?: string }>();
const id = params.id ?? params.bookingId;
const { view, viewer } = useFileViewer();
const { data: booking } = useBookingDetail(id);
const {
data: clearance,
isLoading,
isError,
refetch,
} = useQuery({
queryKey: ["clearance", id],
queryFn: () => bookingsService.getClearance(id!),
enabled: Boolean(id),
});
const { data: bookingMilestones } = useBookingMilestones(id);
const stats = useMemo(() => {
const docs = (clearance?.documents ?? []).filter(
(d) => d.uploadedBy === "customer",
@@ -59,6 +71,20 @@ export default function DocumentClearanceDetailPage() {
}, [clearance]);
const reference = booking?.reference ?? "Clearance";
const isPhasedGeneral =
Boolean(booking?.customsClearingEnabled) &&
booking?.contractKind === "GENERAL" &&
Boolean(clearance?.phase);
const docsPhaseComplete =
clearance?.milestones?.some(
(m) => m.milestoneCode === "DOCUMENTS_APPROVED" && m.status === "COMPLETED",
) ?? false;
const queriesLocked = Boolean(
(clearance as Freight.ContractClearanceView | undefined)?.preClearanceFinalized,
);
const workflowFiles =
(clearance as Freight.ContractClearanceView | undefined)?.workflowFiles ?? [];
if (isLoading) {
return (
@@ -76,9 +102,9 @@ export default function DocumentClearanceDetailPage() {
<PageContainer>
<PageHeader
title="Clearance not found"
backTo="/dashboard/clearance"
backTo="/dashboard/contracts/clearance"
breadcrumbs={[
{ label: "Document Clearance", href: "/dashboard/clearance" },
{ label: "Document Clearance", href: "/dashboard/contracts/clearance" },
{ label: "Not found" },
]}
/>
@@ -94,9 +120,9 @@ export default function DocumentClearanceDetailPage() {
<Stack gap="lg">
<PageHeader
title={reference}
backTo="/dashboard/clearance"
backTo="/dashboard/contracts/clearance"
breadcrumbs={[
{ label: "Document Clearance", href: "/dashboard/clearance" },
{ label: "Document Clearance", href: "/dashboard/contracts/clearance" },
{ label: reference },
]}
meta={
@@ -124,60 +150,103 @@ export default function DocumentClearanceDetailPage() {
<ClearanceHero booking={booking} clearance={clearance} stats={stats} />
<Grid gap="lg">
{/* LEFT — document review (shared with the Marketing booking detail) */}
<Grid.Col span={{ base: 12, lg: 8 }}>
<ClearanceReviewSection bookingId={id!} hideSummary />
</Grid.Col>
{isPhasedGeneral ? (
<Paper withBorder radius="md" p="lg">
<ClearancePhaseStepper
clearance={clearance as Freight.ContractClearanceView}
tradeDirection={booking?.tradeDirection ?? "IMPORT"}
/>
</Paper>
) : null}
{/* RIGHT — sticky progress gauge */}
<Grid.Col span={{ base: 12, lg: 4 }}>
<Box style={{ position: "sticky", top: 24 }}>
<SectionCard
icon={PackageCheck}
title="Review progress"
accent="edr-green"
>
<Stack align="center" gap="sm">
<RingProgress
size={140}
thickness={12}
roundCaps
sections={[{ value: stats.pct, color: "edr-green" }]}
label={
<Stack gap={0} align="center">
<Text fw={800} fz={26} lh={1}>
{stats.pct}%
</Text>
<Text size="xs" c="dimmed">
approved
</Text>
</Stack>
}
<ClearanceOpsTabs
bookingId={id}
milestones={bookingMilestones}
showOpsTabs={Boolean(id)}
showWorkflowFilesTab={isPhasedGeneral}
tradeDirection={booking?.tradeDirection ?? "IMPORT"}
workflowFiles={workflowFiles}
onViewFile={view}
onDownloadFile={(f) => void downloadBookingFile(f.id, f.name)}
clearanceTab={
<Grid gap="lg">
<Grid.Col span={{ base: 12, lg: isPhasedGeneral ? 7 : 8 }}>
<ClearanceReviewSection
bookingId={id!}
hideSummary
approvalsLocked={isPhasedGeneral && docsPhaseComplete}
queriesLocked={queriesLocked}
onChanged={() => void refetch()}
/>
</Grid.Col>
<Grid.Col span={{ base: 12, lg: isPhasedGeneral ? 5 : 4 }}>
{isPhasedGeneral ? (
<PhasedClearanceActionPanel
bookingId={id!}
clearance={clearance}
tradeDirection={booking?.tradeDirection ?? "IMPORT"}
workflowFiles={workflowFiles}
roleMode="ET"
onChanged={() => void refetch()}
onViewFile={view}
onDownloadFile={(f) => void downloadBookingFile(f.id, f.name)}
/>
<Group gap="lg" justify="center">
<ProgressStat
color="edr-green"
label="Approved"
value={stats.approved}
/>
<ProgressStat
color="red"
label="Queried"
value={stats.queried}
/>
<ProgressStat
color="gray"
label="Pending"
value={stats.pending}
/>
</Group>
</Stack>
</SectionCard>
</Box>
</Grid.Col>
</Grid>
) : (
<Box style={{ position: "sticky", top: 24 }}>
<SectionCard
icon={PackageCheck}
title="Review progress"
accent="edr-green"
>
<Stack align="center" gap="sm">
<RingProgress
size={140}
thickness={12}
roundCaps
sections={[{ value: stats.pct, color: "edr-green" }]}
label={
<Stack gap={0} align="center">
<Text fw={800} fz={26} lh={1}>
{stats.pct}%
</Text>
<Text size="xs" c="dimmed">
approved
</Text>
</Stack>
}
/>
<Group gap="lg" justify="center">
<ProgressStat
color="edr-green"
label="Approved"
value={stats.approved}
/>
<ProgressStat
color="red"
label="Queried"
value={stats.queried}
/>
<ProgressStat
color="gray"
label="Pending"
value={stats.pending}
/>
</Group>
</Stack>
</SectionCard>
</Box>
)}
</Grid.Col>
</Grid>
}
/>
{isPhasedGeneral && clearance.milestones && clearance.milestones.length > 0 ? (
<ClearanceMilestoneTimeline milestones={clearance.milestones} />
) : null}
</Stack>
{viewer}
</PageContainer>
);
}

View File

@@ -70,7 +70,6 @@ interface RefCargoChild {
id: string;
name: string;
code: string;
show_free_text_box?: boolean;
}
interface RefCargoGroup {
id: string;
@@ -307,20 +306,18 @@ export default function NewBookingPage() {
[refData?.containers],
);
const { cargoData, freeTextById } = useMemo(() => {
const { cargoData } = useMemo(() => {
const groups = refData?.cargo_type ?? [];
const freeText = new Map<string, boolean>();
const data = groups.map((g) => {
if (g.children?.length) {
g.children.forEach((c) => freeText.set(c.id, Boolean(c.show_free_text_box)));
return { group: g.name, items: g.children.map((c) => ({ value: c.id, label: c.name })) };
}
return { value: g.id, label: g.name };
});
return { cargoData: data, freeTextById: freeText };
return { cargoData: data };
}, [refData?.cargo_type]);
const showFreeText = cargoTypeId ? freeTextById.get(cargoTypeId) : false;
const showFreeText = freightType === "BULK" && Boolean(cargoTypeId);
// ---- derived totals ----
const totalContainers = lines.reduce((s, l) => s + (l.quantity || 0), 0);
@@ -376,7 +373,7 @@ export default function NewBookingPage() {
lastMileDeliveryAddress: lastMileDeliveryAddress.trim() || undefined,
cargoTotalWeightVgm,
cargoTypeId: freightType === "BULK" ? cargoTypeId : undefined,
cargoFreeText: freightType === "BULK" && showFreeText ? cargoFreeText.trim() || undefined : undefined,
cargoFreeText: freightType === "BULK" ? cargoFreeText.trim() || undefined : undefined,
containers:
freightType === "CONTAINER"
? lines.map((l) => ({

View File

@@ -0,0 +1,145 @@
import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
Badge,
Button,
Center,
Group,
Loader,
Paper,
Stack,
Table,
Text,
Title,
} from "@mantine/core";
import { CalendarClock, Pencil } from "lucide-react";
import { PageContainer } from "@/components/page";
import Breadcrumbs from "@/components/ui/Breadcrumbs";
import { api } from "@/services/api";
import ManageDropdownOptionsDialog from "@/pages/dropdown_settings/ManageDropdownOptionsDialog";
const CONTRACT_VALIDITY_PERIODS_CODE = "contract_validity_periods";
/**
* Admin UI for contract validity options used when staff accepts a submitted
* contract (SUBMITTED → PENDING_APPROVAL). Backed by dropdown_settings.
*/
export default function ContractValidityPeriodsPage() {
const [editOpen, setEditOpen] = useState(false);
const { data: setting, isLoading, isError } = useQuery(
api.dropdownSettings.getByCode.queryOptions({
input: { code: CONTRACT_VALIDITY_PERIODS_CODE },
}),
);
const options = useMemo(
() =>
[...(setting?.children ?? [])].sort(
(a, b) => (a.order ?? 0) - (b.order ?? 0),
),
[setting],
);
return (
<PageContainer>
<Breadcrumbs
items={[
{ label: "Configuration", href: "/dashboard/configuration" },
{ label: "Contract validity periods" },
]}
/>
<Stack gap="lg" mt="md">
<Group justify="space-between" align="flex-start" wrap="wrap">
<Stack gap={4}>
<Title order={2}>Contract validity periods</Title>
<Text size="sm" c="dimmed" maw={560}>
Options shown when line staff accepts a submitted contract. Each
value is the number of days the contract stays valid from the
accept date.
</Text>
</Stack>
{setting && (
<Button
leftSection={<Pencil size={16} />}
color="edr-green"
onClick={() => setEditOpen(true)}
>
Edit options
</Button>
)}
</Group>
<Paper withBorder radius="lg" p="lg">
{isLoading ? (
<Center py="xl">
<Loader color="edr-green" />
</Center>
) : isError || !setting ? (
<Text c="dimmed">
Could not load contract validity settings. Ensure{" "}
<Text span ff="monospace" size="sm">
{CONTRACT_VALIDITY_PERIODS_CODE}
</Text>{" "}
is seeded in dropdown settings.
</Text>
) : options.length === 0 ? (
<Stack align="center" gap="md" py="xl">
<CalendarClock size={32} color="var(--mantine-color-gray-5)" />
<Text c="dimmed">No validity periods configured yet.</Text>
<Button
variant="light"
color="edr-green"
onClick={() => setEditOpen(true)}
>
Add options
</Button>
</Stack>
) : (
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th>Label</Table.Th>
<Table.Th>Days (value)</Table.Th>
<Table.Th>Order</Table.Th>
<Table.Th>Status</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{options.map((opt) => (
<Table.Tr key={opt.id}>
<Table.Td>{opt.label}</Table.Td>
<Table.Td>
<Text ff="monospace" size="sm">
{opt.value}
</Text>
</Table.Td>
<Table.Td>{opt.order ?? "—"}</Table.Td>
<Table.Td>
<Badge
color={opt.disabled ? "gray" : "edr-green"}
variant="light"
>
{opt.disabled ? "Disabled" : "Active"}
</Badge>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
)}
</Paper>
</Stack>
{setting ? (
<ManageDropdownOptionsDialog
setting={setting}
open={editOpen}
onOpenChange={setEditOpen}
/>
) : null}
</PageContainer>
);
}

View File

@@ -23,23 +23,33 @@ import {
PackageCheck,
ShieldCheck,
} from "lucide-react";
import { Link } from "react-router-dom";
import { ClearanceOpsTabs } from "@/components/contracts/ClearanceOpsTabs";
import { PageContainer } from "@/components/page/PageContainer";
import { PageHeader } from "@/components/page/PageHeader";
import { SectionCard } from "@/components/bookings/detail/SectionCard";
import { ContractClearanceReviewSection } from "@/components/contracts/ContractClearanceReviewSection";
import { PhasedClearanceActionPanel } from "@/components/contracts/PhasedClearanceActionPanel";
import { QUERY_KEYS } from "@/constants/QUERY_KEYS";
import { useFileViewer } from "@/hooks/useFileViewer";
import { contractsService } from "@/services/contracts.service";
import { useContractDetail } from "@/hooks/contracts/useContracts";
import { downloadBookingFile } from "@/services/files.service";
import {
useBookingMilestones,
useContractDetail,
} from "@/hooks/contracts/useContracts";
export default function ContractClearanceDetailPage() {
const { id } = useParams<{ id: string }>();
const { view, viewer } = useFileViewer();
const { data: contract } = useContractDetail(id);
const {
data: clearance,
isLoading,
isError,
refetch,
} = useQuery({
queryKey: QUERY_KEYS.CONTRACTS.clearance(id ?? ""),
queryFn: () => contractsService.getClearance(id!),
@@ -59,9 +69,40 @@ export default function ContractClearanceDetailPage() {
}, [clearance]);
const reference = contract?.reference ?? "Clearance";
// Customs (Path B) hub. The customer always creates the booking in the portal
// after GL finalizes clearance — there is no GL "Create booking" action here.
const ready = clearance?.clearanceStatus === "CLEARANCE_READY_FOR_BOOKING";
const phasedCustoms =
contract?.contractKind === "ONE_TIME" && Boolean(contract.customsClearingEnabled);
const docsPhaseComplete =
clearance?.milestones?.some(
(m) => m.milestoneCode === "DOCUMENTS_APPROVED" && m.status === "COMPLETED",
) ?? false;
const ready = clearance?.bookingReady === true;
const docReviewLocked = phasedCustoms
? docsPhaseComplete
: clearance?.clearanceStatus === "CLEARANCE_READY_FOR_BOOKING";
const shipmentLocked = Boolean(
contract?.status &&
[
"ACTIVE_SHIPMENT_IN_PROGRESS",
"FULLY_EXECUTED",
"CONTRACT_ACTIVE",
"CONTRACT_CLOSED",
"EXPIRED",
].includes(contract.status),
);
const linkedBookingId = useMemo(() => {
const cycle = contract?.clearanceCycles?.find(
(c) => c.cycleNumber === (contract?.clearanceCycleNumber ?? 1),
);
return cycle?.bookingId ?? undefined;
}, [contract]);
const bookingAlreadyCreated = Boolean(linkedBookingId) || shipmentLocked;
const canCreateBooking = ready && !bookingAlreadyCreated;
const reviewReadOnly = shipmentLocked;
const queriesLocked = Boolean(clearance?.preClearanceFinalized);
const bookingHref = `/dashboard/contracts/${id}/create-booking`;
const { data: bookingMilestones, refetch: refetchBookingMilestones } =
useBookingMilestones(linkedBookingId);
if (isLoading) {
return (
@@ -95,6 +136,8 @@ export default function ContractClearanceDetailPage() {
);
}
const workflowFiles = clearance.workflowFiles ?? [];
return (
<PageContainer>
<Stack gap="lg">
@@ -109,14 +152,23 @@ export default function ContractClearanceDetailPage() {
{ label: reference },
]}
meta={
ready ? (
bookingAlreadyCreated ? (
<Badge
variant="light"
color="blue"
radius="sm"
leftSection={<PackageCheck size={13} />}
>
Booking created
</Badge>
) : ready ? (
<Badge
variant="light"
color="edr-green"
radius="sm"
leftSection={<PackageCheck size={13} />}
>
Ready customer books
Ready create booking
</Badge>
) : clearance.allApproved ? (
<Badge
@@ -142,75 +194,139 @@ export default function ContractClearanceDetailPage() {
<ClearanceHero contract={contract} stats={stats} />
{ready ? (
{bookingAlreadyCreated ? (
<Alert
color="blue"
radius="md"
icon={<PackageCheck size={16} />}
title="Shipment booking created"
>
GL Ethiopia has created the shipment booking for this contract.
{linkedBookingId ? (
<>
{" "}
<Text
component={Link}
to={`/dashboard/bookings/${linkedBookingId}/clearance`}
inherit
fw={600}
c="blue.7"
>
View booking
</Text>
</>
) : null}
</Alert>
) : canCreateBooking ? (
<Alert
color="edr-green"
radius="md"
icon={<PackageCheck size={16} />}
title="Clearance finalized"
title="Clearance complete"
>
Customs clearance is complete. The customer can now create the
shipment booking from the portal no further action is needed here.
Pre-booking clearance is complete. GL Ethiopia can create the shipment booking.
</Alert>
) : null}
<Grid gap="lg">
<Grid.Col span={{ base: 12, lg: 8 }}>
<ContractClearanceReviewSection
contractId={id!}
hideSummary
selfClear={false}
readOnly={ready}
/>
</Grid.Col>
<ClearanceOpsTabs
bookingId={linkedBookingId}
milestones={bookingMilestones}
showOpsTabs={Boolean(linkedBookingId)}
showWorkflowFilesTab={phasedCustoms}
tradeDirection={contract?.tradeDirection ?? "IMPORT"}
workflowFiles={workflowFiles}
onViewFile={view}
onDownloadFile={(f) => void downloadBookingFile(f.id, f.name)}
clearanceTab={
<Grid>
<Grid.Col span={{ base: 12, lg: 7 }}>
<ContractClearanceReviewSection
contractId={id!}
hideSummary
selfClear={false}
readOnly={reviewReadOnly}
approvalsLocked={phasedCustoms && docReviewLocked}
queriesLocked={queriesLocked}
phasedCustoms={phasedCustoms}
onChanged={() => {
void refetch();
void refetchBookingMilestones();
}}
/>
</Grid.Col>
<Grid.Col span={{ base: 12, lg: 4 }}>
<Box style={{ position: "sticky", top: 24 }}>
<SectionCard
icon={PackageCheck}
title="Review progress"
accent="edr-green"
>
<Stack align="center" gap="sm">
<RingProgress
size={140}
thickness={12}
roundCaps
sections={[{ value: stats.pct, color: "edr-green" }]}
label={
<Stack gap={0} align="center">
<Text fw={800} fz={26} lh={1}>
{stats.pct}%
</Text>
<Text size="xs" c="dimmed">
approved
</Text>
</Stack>
}
/>
<Group gap="lg" justify="center">
<ProgressStat
color="edr-green"
label="Approved"
value={stats.approved}
<Grid.Col span={{ base: 12, lg: 5 }}>
<Stack gap="md">
{phasedCustoms ? (
<PhasedClearanceActionPanel
contractId={id!}
bookingId={linkedBookingId}
bookingMilestones={bookingMilestones ?? []}
clearance={clearance}
tradeDirection={contract?.tradeDirection ?? "IMPORT"}
workflowFiles={workflowFiles}
roleMode="ET"
onChanged={() => {
void refetch();
void refetchBookingMilestones();
}}
onViewFile={view}
onDownloadFile={(f) => void downloadBookingFile(f.id, f.name)}
bookingCreateHref={canCreateBooking ? bookingHref : undefined}
bookingCreated={bookingAlreadyCreated}
/>
<ProgressStat
color="red"
label="Queried"
value={stats.queried}
/>
<ProgressStat
color="gray"
label="Pending"
value={stats.pending}
/>
</Group>
) : (
<Box style={{ position: "sticky", top: 24 }}>
<SectionCard
icon={PackageCheck}
title="Review progress"
accent="edr-green"
>
<Stack align="center" gap="sm">
<RingProgress
size={140}
thickness={12}
roundCaps
sections={[{ value: stats.pct, color: "edr-green" }]}
label={
<Stack gap={0} align="center">
<Text fw={800} fz={26} lh={1}>
{stats.pct}%
</Text>
<Text size="xs" c="dimmed">
approved
</Text>
</Stack>
}
/>
<Group gap="lg" justify="center">
<ProgressStat
color="edr-green"
label="Approved"
value={stats.approved}
/>
<ProgressStat
color="red"
label="Queried"
value={stats.queried}
/>
<ProgressStat
color="gray"
label="Pending"
value={stats.pending}
/>
</Group>
</Stack>
</SectionCard>
</Box>
)}
</Stack>
</SectionCard>
</Box>
</Grid.Col>
</Grid>
</Grid.Col>
</Grid>
}
/>
</Stack>
{viewer}
</PageContainer>
);
}

View File

@@ -1,4 +1,4 @@
import { useCallback, useMemo, useState } from "react";
import { useCallback, useMemo, useState, type ReactNode } from "react";
import { useNavigate } from "react-router-dom";
import {
ActionIcon,
@@ -18,6 +18,7 @@ import {
ArrowRight,
ChevronRight,
FileText,
Flag,
Inbox,
LayoutGrid,
PackageCheck,
@@ -43,9 +44,15 @@ import { PageContainer } from "@/components/page/PageContainer";
import { PageHeader } from "@/components/page/PageHeader";
import { KpiStrip } from "@/components/page/KpiStrip";
import { bookingTable } from "@/components/bookings/booking-ui.styles";
import { useContractClearanceQueue } from "@/hooks/contracts/useContracts";
import { useAuth } from "@/auth/useAuth";
import {
useContractClearanceQueue,
useEtClearanceQueue,
} from "@/hooks/contracts/useContracts";
import { FREIGHT_PERMS, hasPermission } from "@/lib/permissions";
type ViewMode = "table" | "cards";
type QueueTab = "all" | "et";
interface ClearanceRow {
id: string;
@@ -59,8 +66,10 @@ interface ClearanceRow {
serviceTypeName: string;
customs: boolean;
status: string;
/** true once GL has finalized clearance — customer now books in the portal. */
/** true once GL has finalized clearance — customer may book in the portal. */
ready: boolean;
/** true once GL Ethiopia created the shipment booking. */
bookingCreated: boolean;
}
function yardLabel(
@@ -93,6 +102,7 @@ function toClearanceRow(contract: Freight.IContract): ClearanceRow {
contract.serviceType?.includesCustoms ?? contract.customsClearingEnabled,
status: contract.status,
ready: contract.status === "CLEARANCE_READY_FOR_BOOKING",
bookingCreated: contract.status === "ACTIVE_SHIPMENT_IN_PROGRESS",
};
}
@@ -134,6 +144,21 @@ function DirectionIcon({ direction }: { direction: string }) {
}
function StatusBadge({ row }: { row: ClearanceRow }) {
if (row.bookingCreated) {
return (
<Tooltip label="GL Ethiopia created the shipment booking" withArrow>
<Badge
size="sm"
variant="light"
color="blue"
radius="sm"
leftSection={<PackagePlus size={12} />}
>
Booking created
</Badge>
</Tooltip>
);
}
if (row.ready) {
return (
<Tooltip
@@ -160,19 +185,61 @@ function StatusBadge({ row }: { row: ClearanceRow }) {
}
/**
* Document Clearance hub. Lists every customs (Path B) contract that still needs
* customs clearance — awaiting documents, under GL review, or finalized and
* waiting for the customer to create the booking in the portal. A single list,
* no queue/history/direction tabs.
* Document Clearance hub. Lists every customs (Path B) contract in phased clearance,
* including after booking is created — stays visible for reference and follow-up.
*/
export default function ContractClearanceListPage() {
const navigate = useNavigate();
const { user } = useAuth();
const canReview = hasPermission(user, FREIGHT_PERMS.contracts.clearanceReview);
const canEt = hasPermission(user, FREIGHT_PERMS.contracts.clearanceEtActions);
const defaultQueue: QueueTab = canReview ? "all" : "et";
const [queueTab, setQueueTab] = useState<QueueTab>(defaultQueue);
const [query, setQuery] = useState("");
const [view, setView] = useState<ViewMode>("table");
const { pagination, setPagination } = usePagination({ pageSize: 10 });
const { data, isLoading, isError, isFetching, refetch } =
useContractClearanceQueue(true);
const { data: allData, isLoading: allLoading, isError: allError, isFetching: allFetching, refetch: refetchAll } =
useContractClearanceQueue(queueTab === "all");
const { data: etData, isLoading: etLoading, isError: etError, isFetching: etFetching, refetch: refetchEt } =
useEtClearanceQueue(queueTab === "et");
const data = queueTab === "et" ? etData : allData;
const isLoading = queueTab === "et" ? etLoading : allLoading;
const isError = queueTab === "et" ? etError : allError;
const isFetching = queueTab === "et" ? etFetching : allFetching;
const refetch = () => {
if (queueTab === "et") void refetchEt();
else void refetchAll();
};
const queueTabOptions = useMemo(() => {
const opts: { value: QueueTab; label: ReactNode }[] = [];
if (canReview) {
opts.push({
value: "all",
label: (
<Group gap={6} wrap="nowrap">
<ShieldCheck size={15} />
<Box visibleFrom="sm">All</Box>
</Group>
),
});
}
if (canEt) {
opts.push({
value: "et",
label: (
<Group gap={6} wrap="nowrap">
<Flag size={15} />
<Box visibleFrom="sm">ET queue</Box>
</Group>
),
});
}
return opts;
}, [canReview, canEt]);
const allRows = useMemo(
() => (data?.items ?? []).map(toClearanceRow),
@@ -183,7 +250,8 @@ export default function ContractClearanceListPage() {
() => ({
all: allRows.length,
ready: allRows.filter((r) => r.ready).length,
review: allRows.filter((r) => !r.ready).length,
booked: allRows.filter((r) => r.bookingCreated).length,
review: allRows.filter((r) => !r.ready && !r.bookingCreated).length,
}),
[allRows],
);
@@ -329,7 +397,7 @@ export default function ContractClearanceListPage() {
<Stack gap="lg">
<PageHeader
title="Document Clearance"
subtitle="Review pre-booking customs documents on contracts and finalize clearance. Once finalized, the customer creates the shipment booking in the portal."
subtitle="All customs contracts in phased clearance — stays visible after booking is created."
meta={
<Badge
variant="light"
@@ -337,7 +405,7 @@ export default function ContractClearanceListPage() {
radius="sm"
leftSection={<ShieldCheck size={13} />}
>
{counts.all} need clearance
{counts.all} in clearance
</Badge>
}
action={
@@ -358,7 +426,7 @@ export default function ContractClearanceListPage() {
loading={isLoading}
items={[
{
label: "Need clearance",
label: "In clearance",
value: counts.all,
icon: Inbox,
color: "edr-green",
@@ -370,8 +438,8 @@ export default function ContractClearanceListPage() {
color: "yellow",
},
{
label: "Ready — customer books",
value: counts.ready,
label: "Ready / booked",
value: counts.ready + counts.booked,
icon: PackageCheck,
color: "edr-green",
},
@@ -380,6 +448,20 @@ export default function ContractClearanceListPage() {
<Card p={0} withBorder shadow="sm" radius="lg">
<Stack gap={0}>
{queueTabOptions.length > 1 ? (
<Box px="md" pt="md">
<SegmentedControl
size="sm"
radius="md"
value={queueTab}
onChange={(v) => {
setQueueTab(v as QueueTab);
setPagination({ pageIndex: 0, pageSize: pagination.pageSize });
}}
data={queueTabOptions}
/>
</Box>
) : null}
<Box px="md" pt="md" pb="sm">
<Group justify="space-between" gap="md" wrap="wrap">
<TextInput

View File

@@ -1,4 +1,5 @@
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import {
ArrowLeft,
ArrowRight,
@@ -6,14 +7,19 @@ import {
Building2,
Calendar,
CalendarClock,
Download,
FileSignature,
FileText,
Files,
Flame,
LayoutGrid,
Package,
Receipt,
RefreshCw,
Route as RouteIcon,
ShieldCheck,
Snowflake,
Users,
} from "lucide-react";
import {
Badge,
@@ -31,6 +37,8 @@ import {
Title,
} from "@mantine/core";
import toast from "react-hot-toast";
import "@/components/overview/overview.css";
import { PageContainer } from "@/components/page";
import Breadcrumbs from "@/components/ui/Breadcrumbs";
@@ -41,11 +49,22 @@ import { ContractWorkflowStepper } from "@/components/contracts/ContractWorkflow
import { ContractActionsToolbar } from "@/components/contracts/ContractActionsToolbar";
import { ContractApprovalStepsCard } from "@/components/contracts/ContractApprovalStepsCard";
import { ContractClearanceReviewSection } from "@/components/contracts/ContractClearanceReviewSection";
import { ClearanceWorkflowFilesPanel } from "@/components/contracts/ClearanceWorkflowFilesPanel";
import {
ContractCustomerCard,
ContractDocumentsCard,
} from "@/components/contracts/detail/ContractDetailTabCards";
import { getContractStatusMeta } from "@/features/contracts/contract-status.config";
import { useFileViewer } from "@/hooks/useFileViewer";
import {
useContractDetail,
useContractMutations,
} from "@/hooks/contracts/useContracts";
import { contractsService } from "@/services/contracts.service";
import { QUERY_KEYS } from "@/constants/QUERY_KEYS";
import { fileViewUrl } from "@/constants/apiConfig";
import { downloadBookingFile } from "@/services/files.service";
import type { Freight } from "@edr/types";
// Clearance phase — staff can still ACT (approve / query / finalize).
const CLEARANCE_ACTIVE_STATUSES = [
@@ -94,7 +113,8 @@ export default function ContractRequestDetailPage() {
} = useContractDetail(id);
const mutations = useContractMutations(id ?? "");
const [searchParams, setSearchParams] = useSearchParams();
const activeTab = searchParams.get("tab") === "clearance" ? "clearance" : "details";
const { view, viewer } = useFileViewer();
const requestedTab = searchParams.get("tab");
const setTab = (tab: string) =>
setSearchParams(
(prev) => {
@@ -106,6 +126,48 @@ export default function ContractRequestDetailPage() {
{ replace: true },
);
const handleViewFile = (file: NonNullable<Freight.IContract["files"]>[number]) =>
view({
name: file.name,
url: file.signedUrl ?? file.url,
mimeType: file.mimeType,
});
const handleDownloadFile = async (
file: NonNullable<Freight.IContract["files"]>[number],
) => {
try {
await downloadBookingFile(file.id, file.name);
} catch {
toast.error("Could not download file.");
}
};
const showClearanceTabQuery = Boolean(
contract && CLEARANCE_REVIEW_STATUSES.includes(contract.status),
);
const { data: clearanceView } = useQuery({
queryKey: QUERY_KEYS.CONTRACTS.clearance(id ?? ""),
queryFn: () => contractsService.getClearance(id!),
enabled: Boolean(id) && showClearanceTabQuery,
});
const downloadContractPdf = async () => {
if (!contract?.id) return;
try {
const blob = await contractsService.downloadContractDocument(contract.id);
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
const contractPdf = contract.files?.find((f) => f.code === "contract");
a.download = contractPdf?.name ?? `contract-${contract.reference}.pdf`;
a.click();
URL.revokeObjectURL(url);
} catch {
toast.error("Could not download contract PDF.");
}
};
if (isLoading) {
return (
<PageContainer>
@@ -172,13 +234,36 @@ export default function ContractRequestDetailPage() {
contract.status === "APPROVED_PENDING_SIGNATURE";
const showClearanceTab = CLEARANCE_REVIEW_STATUSES.includes(contract.status);
const phasedCustoms =
contract.contractKind === "ONE_TIME" && Boolean(contract.customsClearingEnabled);
const docsPhaseComplete =
clearanceView?.milestones?.some(
(m) => m.milestoneCode === "DOCUMENTS_APPROVED" && m.status === "COMPLETED",
) ?? false;
const clearanceApprovalsLocked = phasedCustoms && docsPhaseComplete;
// Once clearance is finalized the tab is informational only — no approve/query.
const clearanceReadOnly = CLEARANCE_DONE_STATUSES.includes(contract.status);
// Path A (no customs) → Operations reviews; Path B (customs) → GL reviews.
const selfClear = !contract.customsClearingEnabled;
// If the tab param points at clearance but the contract isn't in a clearance
// phase, fall back to details so we never show an empty tab.
const currentTab = activeTab === "clearance" && showClearanceTab ? "clearance" : "details";
const files = contract.files ?? [];
const contractPdf = files.find((f) => f.code === "contract");
const hasContractDocument = Boolean(
contractPdf || contract.contractGeneratedAt,
);
const canViewSign =
(contract.status === "CONTRACT_READY" ||
contract.status === "SIGNED_CUSTOMER") &&
Boolean(contract.contractGeneratedAt);
// Resolve the active tab from the URL, falling back to details when the
// requested tab isn't available for this contract (e.g. clearance pre-phase).
const currentTab =
requestedTab === "documents"
? "documents"
: requestedTab === "customer"
? "customer"
: requestedTab === "clearance" && showClearanceTab
? "clearance"
: "details";
const customerLabel = contract.isGovernment
? (contract.governmentInstitution ?? "Government")
@@ -254,6 +339,48 @@ export default function ContractRequestDetailPage() {
/>
) : null}
</Group>
{hasContractDocument && (
<Group gap="sm" mt="sm">
{canViewSign && (
<Button
color="edr-green"
size="compact-sm"
radius="lg"
leftSection={<FileSignature size={15} />}
onClick={() =>
navigate(`/dashboard/contract-requests/${contract.id}/view`)
}
>
View &amp; sign contract
</Button>
)}
{contractPdf && (
<Button
variant="default"
size="compact-sm"
radius="lg"
leftSection={<FileText size={15} />}
onClick={() =>
handleViewFile({
...contractPdf,
url: fileViewUrl(contractPdf.id),
})
}
>
View contract
</Button>
)}
<Button
variant="default"
size="compact-sm"
radius="lg"
leftSection={<Download size={15} />}
onClick={() => void downloadContractPdf()}
>
Download PDF
</Button>
</Group>
)}
</Stack>
</Stack>
</Paper>
@@ -264,38 +391,83 @@ export default function ContractRequestDetailPage() {
description={statusMeta.description}
/>
{showClearanceTab && (
<Tabs
value={currentTab}
onChange={(v) => setTab(v ?? "details")}
variant="pills"
color="edr-green"
classNames={{ list: "ov-tablist", tab: "ov-tab" }}
>
<Tabs.List>
<Tabs.Tab value="details" leftSection={<FileText size={16} />}>
Details
</Tabs.Tab>
<Tabs
value={currentTab}
onChange={(v) => setTab(v ?? "details")}
variant="pills"
color="edr-green"
classNames={{ list: "ov-tablist", tab: "ov-tab" }}
>
<Tabs.List>
<Tabs.Tab value="details" leftSection={<LayoutGrid size={16} />}>
Details
</Tabs.Tab>
<Tabs.Tab
value="documents"
leftSection={<Files size={16} />}
rightSection={
files.length > 0 ? (
<Badge size="xs" variant="light" color="gray" radius="sm">
{files.length}
</Badge>
) : null
}
>
Documents
</Tabs.Tab>
<Tabs.Tab value="customer" leftSection={<Users size={16} />}>
Customer
</Tabs.Tab>
{showClearanceTab && (
<Tabs.Tab
value="clearance"
leftSection={<ShieldCheck size={16} />}
>
Clearance Review
</Tabs.Tab>
</Tabs.List>
</Tabs>
)}
)}
</Tabs.List>
</Tabs>
<Grid gap="lg">
{/* LEFT — primary content */}
<Grid.Col span={{ base: 12, lg: 8 }}>
{currentTab === "clearance" ? (
<ContractClearanceReviewSection
contractId={id!}
selfClear={selfClear}
readOnly={clearanceReadOnly}
onChanged={() => refetch()}
/>
<Stack gap="lg">
<ContractClearanceReviewSection
contractId={id!}
selfClear={selfClear}
readOnly={clearanceReadOnly}
phasedCustoms={phasedCustoms}
approvalsLocked={clearanceApprovalsLocked}
onChanged={() => refetch()}
/>
{(clearanceView?.workflowFiles?.length ?? 0) > 0 ? (
<ClearanceWorkflowFilesPanel
files={clearanceView!.workflowFiles!}
onView={view}
onDownload={(f) => void handleDownloadFile({ id: f.id, name: f.name } as never)}
/>
) : null}
</Stack>
) : currentTab === "documents" ? (
<Stack gap="lg">
<ContractDocumentsCard
files={files}
onView={handleViewFile}
onDownload={handleDownloadFile}
/>
{(clearanceView?.workflowFiles?.length ?? 0) > 0 ? (
<ClearanceWorkflowFilesPanel
files={clearanceView!.workflowFiles!}
title="Customs workflow documents"
onView={view}
onDownload={(f) => void handleDownloadFile({ id: f.id, name: f.name } as never)}
/>
) : null}
</Stack>
) : currentTab === "customer" ? (
<ContractCustomerCard contract={contract} />
) : (
<Stack gap="lg">
<SectionCard icon={RouteIcon} title="Routes">
@@ -453,6 +625,8 @@ export default function ContractRequestDetailPage() {
</Grid.Col>
</Grid>
</Stack>
{viewer}
</PageContainer>
);
}

View File

@@ -1,4 +1,4 @@
import { useRef, useState } from "react";
import { useCallback, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
@@ -13,18 +13,17 @@ import {
Text,
TextInput,
} from "@mantine/core";
import { ArrowLeft, FileSignature, Printer } from "lucide-react";
import { ArrowLeft, Download, FileSignature, Printer } from "lucide-react";
import toast from "react-hot-toast";
import { ContractSignSuccessModal } from "@/components/contracts/ContractSignSuccessModal";
import { ContractSignaturePad } from "@/components/bookings/ContractSignaturePad";
import { contractsService } from "@/services/contracts.service";
import { QUERY_KEYS } from "@/constants/QUERY_KEYS";
/**
* Staff contract preview + sign. Staff must open and read the generated
* contract here before signing — there is no sign action on the detail page or
* the list table. Signing as STAFF is only possible once the contract has been
* generated and is in CONTRACT_READY / SIGNED_CUSTOMER.
* contract here before signing.
*/
export default function ContractViewPage() {
const { id } = useParams<{ id: string }>();
@@ -33,9 +32,9 @@ export default function ContractViewPage() {
const iframeRef = useRef<HTMLIFrameElement>(null);
const [signOpen, setSignOpen] = useState(false);
const [successOpen, setSuccessOpen] = useState(false);
const [signerName, setSignerName] = useState("");
const [signatureData, setSignatureData] = useState<string | null>(null);
// Offer the staff member's saved signature first; they can draw a fresh one.
const [drawNew, setDrawNew] = useState(false);
const { data, isLoading, isError, refetch } = useQuery({
@@ -58,8 +57,8 @@ export default function ContractViewPage() {
consentText: "I confirm this contract on behalf of EDR.",
}),
onSuccess: () => {
toast.success("Contract signed");
setSignOpen(false);
setSuccessOpen(true);
void refetch();
void qc.invalidateQueries({ queryKey: QUERY_KEYS.CONTRACTS.byId(id!) });
void qc.invalidateQueries({ queryKey: QUERY_KEYS.CONTRACTS.ROOT });
@@ -69,6 +68,21 @@ export default function ContractViewPage() {
const handlePrint = () => iframeRef.current?.contentWindow?.print();
const downloadPdf = useCallback(async () => {
if (!id) return;
try {
const blob = await contractsService.downloadContractDocument(id);
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `contract-${data?.reference ?? id}.pdf`;
a.click();
URL.revokeObjectURL(url);
} catch {
toast.error("Could not download contract PDF.");
}
}, [id, data?.reference]);
const openSign = () => {
setSignerName(data?.savedSignature?.signerDisplayName ?? "");
setSignatureData(null);
@@ -124,6 +138,13 @@ export default function ContractViewPage() {
>
Print
</Button>
<Button
variant="default"
leftSection={<Download size={16} />}
onClick={() => void downloadPdf()}
>
Download PDF
</Button>
{data.canSignStaff && (
<Button
color="edr-green"
@@ -217,6 +238,16 @@ export default function ContractViewPage() {
</Group>
</Stack>
</Modal>
<ContractSignSuccessModal
opened={successOpen}
reference={data.reference}
message="The contract has been counter-signed. The customer will be notified of the next steps."
onClose={() => {
setSuccessOpen(false);
navigate(`/dashboard/contract-requests/${data.contractId}`);
}}
/>
</Box>
);
}

View File

@@ -0,0 +1,262 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useParams } from "react-router-dom";
import {
Alert,
Badge,
Box,
Button,
Grid,
Group,
Loader,
Stack,
Tabs,
Text,
ThemeIcon,
} from "@mantine/core";
import { AlertCircle, ClipboardList, FileText, Upload } from "lucide-react";
import type { Freight } from "@edr/types";
import { PageContainer } from "@/components/page/PageContainer";
import { PageHeader } from "@/components/page/PageHeader";
import { ClearanceReviewSection } from "@/components/bookings/detail/ClearanceReviewSection";
import { ContractClearanceReviewSection } from "@/components/contracts/ContractClearanceReviewSection";
import { ClearanceWorkflowFilesPanel } from "@/components/contracts/ClearanceWorkflowFilesPanel";
import {
GlClearanceUploadModal,
type GlClearanceUploadKind,
} from "@/components/contracts/GlClearanceUploadModal";
import { PhasedClearanceActionPanel } from "@/components/contracts/PhasedClearanceActionPanel";
import { findWorkflowFile } from "@/components/contracts/PhasedUploadedFileRow";
import { useFileViewer } from "@/hooks/useFileViewer";
import { contractsService } from "@/services/contracts.service";
import { bookingsService } from "@/services/bookings.service";
import { downloadBookingFile } from "@/services/files.service";
type GlClearanceDetail =
| {
kind: "contract";
reference: string;
tradeDirection: string;
clearance: Freight.ContractClearanceView;
}
| {
kind: "booking";
reference: string;
tradeDirection: string;
clearance: Freight.ClearanceView;
};
async function loadGlClearanceDetail(id: string): Promise<GlClearanceDetail> {
try {
const [clearance, contract] = await Promise.all([
contractsService.getClearance(id),
contractsService.getById(id),
]);
return {
kind: "contract",
reference: contract.reference,
tradeDirection: contract.tradeDirection,
clearance,
};
} catch {
const [clearance, booking] = await Promise.all([
bookingsService.getClearance(id),
bookingsService.getById(id),
]);
return {
kind: "booking",
reference: booking.reference,
tradeDirection: booking.tradeDirection,
clearance,
};
}
}
/** Djibouti GL clearance detail — RO/DO upload and read-only upstream context. */
export default function GlClearanceDetailPage() {
const { id } = useParams<{ id: string }>();
const { view, viewer } = useFileViewer();
const [uploadKind, setUploadKind] = useState<GlClearanceUploadKind | null>(null);
const { data, isLoading, isError, refetch } = useQuery({
queryKey: ["gl-clearance-detail", id],
queryFn: () => loadGlClearanceDetail(id!),
enabled: Boolean(id),
});
if (isLoading) {
return (
<PageContainer>
<Stack align="center" py={80}>
<Loader color="edr-green" />
<Text c="dimmed">Loading clearance</Text>
</Stack>
</PageContainer>
);
}
if (isError || !data) {
return (
<PageContainer>
<Alert color="red" icon={<AlertCircle size={16} />}>
Could not load clearance for this item.
</Alert>
</PageContainer>
);
}
const backTo = "/dashboard/gl-djibouti/clearance";
const workflowFiles = data.clearance.workflowFiles ?? [];
const workflowFileCount = workflowFiles.filter((f) => f.file).length;
const isImport = data.tradeDirection === "IMPORT";
const hasDo = Boolean(findWorkflowFile(workflowFiles, "delivery_order"));
const hasRo = Boolean(findWorkflowFile(workflowFiles, "release_order"));
const canUploadDo = isImport && Boolean(data.clearance.preClearanceFinalized || hasDo);
const vesselDepartureDate =
"vesselDepartureDate" in data.clearance
? (data.clearance.vesselDepartureDate ?? null)
: null;
return (
<PageContainer>
<Stack gap="lg">
<PageHeader
title={data.reference}
backTo={backTo}
breadcrumbs={[
{ label: "GL Djibouti Clearance", href: backTo },
{ label: data.reference },
]}
meta={
<Badge variant="light" color={isImport ? "edr-green" : "gray"} radius="sm">
{data.tradeDirection}
</Badge>
}
action={
<Group gap="sm">
{isImport ? (
<Button
color="edr-green"
leftSection={<Upload size={16} />}
disabled={!canUploadDo}
onClick={() => setUploadKind("do")}
>
{hasDo ? "Replace DO" : "Upload DO"}
</Button>
) : (
<Button
color="edr-green"
leftSection={<Upload size={16} />}
onClick={() => setUploadKind("ro")}
>
{hasRo ? "Replace RO" : "Upload RO"}
</Button>
)}
</Group>
}
/>
<Tabs defaultValue="workflow" keepMounted={false}>
<Tabs.List mb="md">
<Tabs.Tab value="workflow" leftSection={<ClipboardList size={14} />}>
Clearance workflow
</Tabs.Tab>
<Tabs.Tab
value="documents"
leftSection={<FileText size={14} />}
rightSection={
workflowFileCount > 0 ? (
<Badge size="xs" variant="light" color="edr-green" circle>
{workflowFileCount}
</Badge>
) : undefined
}
>
Customs documents (all steps)
</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value="workflow">
<Grid gutter="lg">
<Grid.Col span={{ base: 12, lg: 7 }}>
{data.kind === "booking" ? (
<ClearanceReviewSection bookingId={id!} hideSummary readOnly />
) : (
<ContractClearanceReviewSection
contractId={id!}
hideSummary
selfClear={false}
readOnly
phasedCustoms
/>
)}
</Grid.Col>
<Grid.Col span={{ base: 12, lg: 5 }}>
<PhasedClearanceActionPanel
contractId={data.kind === "contract" ? id : undefined}
bookingId={data.kind === "booking" ? id : undefined}
clearance={data.clearance}
tradeDirection={data.tradeDirection}
workflowFiles={workflowFiles}
roleMode="DJ"
useUploadModals
onUploadDoRequest={() => setUploadKind("do")}
onUploadRoRequest={() => setUploadKind("ro")}
onChanged={() => void refetch()}
onViewFile={view}
onDownloadFile={(f) => void downloadBookingFile(f.id, f.name)}
/>
</Grid.Col>
</Grid>
</Tabs.Panel>
<Tabs.Panel value="documents">
{workflowFiles.length > 0 ? (
<ClearanceWorkflowFilesPanel
files={workflowFiles}
title="Customs documents (all steps)"
onView={view}
onDownload={(f) => void downloadBookingFile(f.id, f.name)}
/>
) : (
<Box
py={48}
style={{
borderRadius: 12,
border: "1px dashed var(--mantine-color-gray-4)",
background: "var(--mantine-color-gray-0)",
textAlign: "center",
}}
>
<Stack gap={8} align="center">
<ThemeIcon variant="light" color="gray" radius="xl" size={48}>
<FileText size={22} />
</ThemeIcon>
<Text size="sm" c="dimmed" maw={360}>
No customs workflow documents uploaded yet. Files from Ethiopia-side
clearance and your DO/RO uploads will appear here.
</Text>
</Stack>
</Box>
)}
</Tabs.Panel>
</Tabs>
</Stack>
<GlClearanceUploadModal
opened={uploadKind != null}
kind={uploadKind}
onClose={() => setUploadKind(null)}
entityId={id!}
isBooking={data.kind === "booking"}
workflowFiles={workflowFiles}
vesselDepartureDate={vesselDepartureDate}
onSuccess={() => void refetch()}
onPreview={view}
/>
{viewer}
</PageContainer>
);
}

View File

@@ -0,0 +1,123 @@
import { useNavigate } from "react-router-dom";
import { Badge, Card, Group, Loader, Stack, Tabs, Text } from "@mantine/core";
import { ChevronRight, Container, Ship } from "lucide-react";
import { PageContainer } from "@/components/page/PageContainer";
import { PageHeader } from "@/components/page/PageHeader";
import { useDjClearanceQueue } from "@/hooks/contracts/useContracts";
import { useBookingDjClearanceQueue } from "@/hooks/bookings/useBookings";
export default function GlDjiboutiClearanceListPage() {
const navigate = useNavigate();
const { data: contractQueue, isLoading: contractsLoading } = useDjClearanceQueue();
const { data: bookingQueue, isLoading: bookingsLoading } = useBookingDjClearanceQueue();
const contractItems = contractQueue?.items ?? [];
const bookingItems = bookingQueue ?? [];
return (
<PageContainer>
<PageHeader
title="GL Djibouti — Clearance"
subtitle="All customs contracts and bookings handed off to Djibouti GL — stays visible after DO/RO upload and booking creation."
/>
<Tabs defaultValue="contracts" keepMounted={false}>
<Tabs.List mb="md">
<Tabs.Tab value="contracts">Contracts ({contractItems.length})</Tabs.Tab>
<Tabs.Tab value="bookings">Bookings ({bookingItems.length})</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value="contracts">
{contractsLoading ? (
<Group justify="center" py={60}>
<Loader color="edr-green" />
</Group>
) : (
<Stack gap="sm">
{contractItems.length === 0 ? (
<Text c="dimmed" ta="center" py="xl">
No Djibouti customs contracts yet. Items appear here once Ethiopia-side
pre-clearance is finalized.
</Text>
) : (
contractItems.map((c) => (
<Card
key={c.id}
withBorder
radius="md"
padding="md"
style={{ cursor: "pointer" }}
onClick={() => navigate(`/dashboard/gl-djibouti/clearance/${c.id}`)}
>
<Group justify="space-between" wrap="nowrap">
<Group gap="sm">
<Ship size={18} className="text-[color:var(--freight-brand)]" />
<div>
<Text fw={700}>{c.reference}</Text>
<Text size="sm" c="dimmed">
{c.tradeDirection} · {c.status}
</Text>
</div>
</Group>
<Group gap="xs">
<Badge variant="light" color="edr-green">
Contract
</Badge>
<ChevronRight size={18} className="text-muted-foreground" />
</Group>
</Group>
</Card>
))
)}
</Stack>
)}
</Tabs.Panel>
<Tabs.Panel value="bookings">
{bookingsLoading ? (
<Group justify="center" py={60}>
<Loader color="edr-green" />
</Group>
) : (
<Stack gap="sm">
{bookingItems.length === 0 ? (
<Text c="dimmed" ta="center" py="xl">
No Djibouti customs bookings yet.
</Text>
) : (
bookingItems.map((b) => (
<Card
key={b.id}
withBorder
radius="md"
padding="md"
style={{ cursor: "pointer" }}
onClick={() => navigate(`/dashboard/gl-djibouti/clearance/${b.id}`)}
>
<Group justify="space-between" wrap="nowrap">
<Group gap="sm">
<Container size={18} className="text-[color:var(--freight-brand)]" />
<div>
<Text fw={700}>{b.reference}</Text>
<Text size="sm" c="dimmed">
{b.tradeDirection} · {b.status}
</Text>
</div>
</Group>
<Group gap="xs">
<Badge variant="light" color="blue">
Booking
</Badge>
<ChevronRight size={18} className="text-muted-foreground" />
</Group>
</Group>
</Card>
))
)}
</Stack>
)}
</Tabs.Panel>
</Tabs>
</PageContainer>
);
}

View File

@@ -6,6 +6,7 @@ import {
Badge,
Box,
Button,
Grid,
Group,
Loader,
Modal,
@@ -24,6 +25,12 @@ import type { Freight } from "@edr/types";
import { PageContainer } from "@/components/page/PageContainer";
import { PageHeader } from "@/components/page/PageHeader";
import { SectionCard } from "@/components/bookings/detail/SectionCard";
import {
RequestCustomerCard,
RequestContractSummaryCard,
RequestRouteCargoCard,
RequestServiceTypeCard,
} from "@/components/contracts/detail/RequestDetailCards";
import { contractsService } from "@/services/contracts.service";
const fmtDate = (iso?: string | null) =>
@@ -167,49 +174,67 @@ export default function ShipmentRequestDetailPage() {
}
/>
<SectionCard icon={CalendarDays} title="Requested shipment">
<Stack gap="sm">
<Group justify="space-between">
<Text size="sm" c="dimmed">
Preferred date (informational)
</Text>
<Text size="sm" fw={600}>
{fmtDate(request.scheduledDate)}
</Text>
</Group>
<Box>
<Text size="sm" c="dimmed" mb={6}>
Quantities
</Text>
<Stack gap={4}>
{lineRows(request.requestedLines ?? {}).map((l, i) => (
<Badge
key={i}
variant="light"
color="edr-green"
radius="sm"
size="lg"
>
{l}
</Badge>
))}
</Stack>
</Box>
{request.notes ? (
<Box>
<Text size="sm" c="dimmed" mb={4}>
Customer note
</Text>
<Text size="sm">{request.notes}</Text>
</Box>
) : null}
{request.reviewNote ? (
<Alert color="red" variant="light" radius="md" mt="sm">
Rejected: {request.reviewNote}
</Alert>
) : null}
</Stack>
</SectionCard>
<Grid gap="lg">
{/* LEFT — the request itself + route/cargo scope */}
<Grid.Col span={{ base: 12, lg: 7 }}>
<Stack gap="lg">
<SectionCard icon={CalendarDays} title="Requested shipment">
<Stack gap="sm">
<Group justify="space-between">
<Text size="sm" c="dimmed">
Preferred date (informational)
</Text>
<Text size="sm" fw={600}>
{fmtDate(request.scheduledDate)}
</Text>
</Group>
<Box>
<Text size="sm" c="dimmed" mb={6}>
Quantities
</Text>
<Stack gap={4}>
{lineRows(request.requestedLines ?? {}).map((l, i) => (
<Badge
key={i}
variant="light"
color="edr-green"
radius="sm"
size="lg"
>
{l}
</Badge>
))}
</Stack>
</Box>
{request.notes ? (
<Box>
<Text size="sm" c="dimmed" mb={4}>
Customer note
</Text>
<Text size="sm">{request.notes}</Text>
</Box>
) : null}
{request.reviewNote ? (
<Alert color="red" variant="light" radius="md" mt="sm">
Rejected: {request.reviewNote}
</Alert>
) : null}
</Stack>
</SectionCard>
<RequestRouteCargoCard contract={request.contract} />
</Stack>
</Grid.Col>
{/* RIGHT — customer, contract + service-type context */}
<Grid.Col span={{ base: 12, lg: 5 }}>
<Stack gap="lg">
<RequestCustomerCard contract={request.contract} />
<RequestContractSummaryCard contract={request.contract} />
<RequestServiceTypeCard contract={request.contract} />
</Stack>
</Grid.Col>
</Grid>
</Stack>
<Modal

View File

@@ -1,22 +1,30 @@
import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
ActionIcon,
Badge,
Box,
Button,
Group,
Modal,
Stack,
Text,
Textarea,
TextInput,
} from "@mantine/core";
import { ChevronRight, Inbox, PackageSearch, RefreshCw, Search } from "lucide-react";
import { Inbox, PackageSearch, RefreshCw, Search } from "lucide-react";
import { DataTable, type ColumnDef } from "@edr/ui-common";
import type { Freight } from "@edr/types";
import { PageContainer } from "@/components/page/PageContainer";
import { PageHeader } from "@/components/page/PageHeader";
import { ruleEngineTable } from "@/components/ruleEngine/ruleEngineStyles";
import {
getShipmentRejectAction,
getShipmentStaffRowAction,
type ShipmentListRow,
} from "@/features/contracts/mapShipmentListRow";
import { contractsService } from "@/services/contracts.service";
const cellMeta = {
@@ -33,7 +41,6 @@ const fmtDate = (iso?: string | null) =>
}).format(new Date(iso))
: "—";
/** Summarize requested quantities for the list row. */
function summarizeLines(lines: Freight.RequestedShipmentLines): string {
if (lines.containers?.length) {
return lines.containers
@@ -49,17 +56,13 @@ function summarizeLines(lines: Freight.RequestedShipmentLines): string {
return "—";
}
interface RequestRow {
id: string;
reference: string;
contractReference: string;
scheduledDate?: string | null;
summary: string;
}
export default function ShipmentRequestsPage() {
const navigate = useNavigate();
const queryClient = useQueryClient();
const [query, setQuery] = useState("");
const [rejectTarget, setRejectTarget] = useState<ShipmentListRow | null>(null);
const [rejectNote, setRejectNote] = useState("");
const [acceptTarget, setAcceptTarget] = useState<ShipmentListRow | null>(null);
const { data, isLoading, isError, isFetching, refetch } = useQuery({
queryKey: ["shipment-request-queue"],
@@ -67,13 +70,26 @@ export default function ShipmentRequestsPage() {
refetchInterval: 30_000,
});
const rows = useMemo<RequestRow[]>(() => {
const reject = useMutation({
mutationFn: () =>
contractsService.rejectBookingRequest(rejectTarget!.id, rejectNote),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["shipment-request-queue"] });
setRejectTarget(null);
setRejectNote("");
},
});
const rows = useMemo<ShipmentListRow[]>(() => {
const all = (data ?? []).map((r) => ({
id: r.id,
reference: r.reference || r.id.slice(0, 8),
contractId: r.contractId,
contractReference: r.contract?.reference ?? r.contractId,
scheduledDate: r.scheduledDate,
summary: summarizeLines(r.requestedLines ?? {}),
status: r.status,
createdBookingId: r.createdBookingId,
}));
const q = query.trim().toLowerCase();
if (!q) return all;
@@ -85,7 +101,7 @@ export default function ShipmentRequestsPage() {
);
}, [data, query]);
const columns = useMemo<ColumnDef<RequestRow>[]>(
const columns = useMemo<ColumnDef<ShipmentListRow>[]>(
() => [
{
id: "reference",
@@ -126,16 +142,55 @@ export default function ShipmentRequestsPage() {
),
},
{
id: "go",
size: 56,
cell: () => (
<Group justify="flex-end" pr="xs">
<ChevronRight size={16} className="text-muted-foreground" />
</Group>
),
id: "actions",
header: () => <span className={ruleEngineTable.headerCell}>Action</span>,
meta: cellMeta,
cell: ({ row }) => {
const primary = getShipmentStaffRowAction(row.original);
const rejectAction = getShipmentRejectAction(row.original);
return (
<Group gap={6} wrap="nowrap" justify="flex-end">
{rejectAction ? (
<Button
size="compact-sm"
radius="md"
variant="light"
color="red"
onClick={(e) => {
e.stopPropagation();
setRejectTarget(row.original);
}}
>
{rejectAction.label}
</Button>
) : null}
{primary.kind === "navigate" ? (
<Button
size="compact-sm"
radius="md"
variant={primary.variant === "filled" ? "filled" : primary.variant}
color="edr-green"
onClick={(e) => {
e.stopPropagation();
if (
primary.label === "Accept" &&
row.original.status === "PENDING"
) {
setAcceptTarget(row.original);
} else {
navigate(primary.to(row.original));
}
}}
>
{primary.label}
</Button>
) : null}
</Group>
);
},
},
],
[],
[navigate],
);
return (
@@ -203,6 +258,95 @@ export default function ShipmentRequestsPage() {
/>
)}
</Stack>
<Modal
opened={rejectTarget !== null}
onClose={() => {
if (!reject.isPending) {
setRejectTarget(null);
setRejectNote("");
}
}}
title="Reject shipment request"
radius="md"
centered
>
<Stack gap="md">
<Text size="sm" c="dimmed">
Reject request{" "}
<Text span fw={600}>
{rejectTarget?.reference}
</Text>
? The customer will be notified.
</Text>
<Textarea
label="Reason"
placeholder="Explain why this request cannot be accepted…"
value={rejectNote}
onChange={(e) => setRejectNote(e.currentTarget.value)}
minRows={3}
radius="md"
/>
<Group justify="flex-end" gap="sm">
<Button
variant="default"
radius="md"
onClick={() => {
setRejectTarget(null);
setRejectNote("");
}}
>
Cancel
</Button>
<Button
color="red"
radius="md"
loading={reject.isPending}
disabled={!rejectNote.trim()}
onClick={() => reject.mutate()}
>
Reject request
</Button>
</Group>
</Stack>
</Modal>
<Modal
opened={acceptTarget !== null}
onClose={() => setAcceptTarget(null)}
title="Accept shipment request"
radius="md"
centered
>
<Stack gap="md">
<Text size="sm" c="dimmed">
Proceed to create a booking for request{" "}
<Text span fw={600}>
{acceptTarget?.reference}
</Text>
? You will confirm the shipment price before submitting.
</Text>
<Group justify="flex-end" gap="sm">
<Button variant="default" radius="md" onClick={() => setAcceptTarget(null)}>
Cancel
</Button>
<Button
color="edr-green"
radius="md"
onClick={() => {
if (!acceptTarget) return;
const to = getShipmentStaffRowAction(acceptTarget);
if (to.kind === "navigate") {
navigate(to.to(acceptTarget));
}
setAcceptTarget(null);
}}
>
Continue
</Button>
</Group>
</Stack>
</Modal>
</PageContainer>
);
}

View File

@@ -0,0 +1,251 @@
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Card, Button, Stack, Group, Grid, Select, Text, ThemeIcon, RingProgress, Container } from '@mantine/core';
import { QUERY_KEYS } from '@/constants/QUERY_KEYS';
import { api } from '@/services/api';
import { vehiclesService } from '@/services/vehicles.service';
import { freightBrand } from '@/theme/freight-brand';
interface FuelStats {
vehicleId: string;
totalPurchases: number;
totalFuel: number;
totalCost: number;
averageCostPerLiter: number;
}
interface MaintenanceStats {
vehicleId: string;
totalCost: number;
numberOfMaintenanceItems: number;
averageCostPerMaintenance: number;
costByType: Record<string, number>;
}
interface CombinedReport {
vehicleId: string;
fuelCost: number;
maintenanceCost: number;
totalOperatingCost: number;
fuelPercentage: number;
maintenancePercentage: number;
}
export function FinancialReportsPage() {
const [selectedVehicle, setSelectedVehicle] = useState<string | null>(null);
const [months, setMonths] = useState('12');
const { data: vehicles } = useQuery({
queryKey: QUERY_KEYS.VEHICLES.list(),
queryFn: async () => {
const res = await vehiclesService.getAll({ limit: 1000 });
return res.data || [];
},
});
const { data: fuelStats } = useQuery({
queryKey: QUERY_KEYS.FUEL.stats(selectedVehicle || ''),
queryFn: () => selectedVehicle ? api.get(`/fuel/stats/${selectedVehicle}?months=${months}`) : Promise.resolve(null),
enabled: !!selectedVehicle,
});
const { data: maintenanceStats } = useQuery({
queryKey: QUERY_KEYS.MAINTENANCE.stats(selectedVehicle || ''),
queryFn: () => selectedVehicle ? api.get(`/maintenance/stats/${selectedVehicle}`) : Promise.resolve(null),
enabled: !!selectedVehicle,
});
const vehicleOptions = useMemo(
() => vehicles?.map(v => ({ label: v.registrationNumber || v.id, value: v.id })) || [],
[vehicles]
);
const report = useMemo(() => {
if (!fuelStats || !maintenanceStats) return null;
const fuelCost = Number(fuelStats.totalCost) || 0;
const maintenanceCost = Number(maintenanceStats.totalCost) || 0;
const total = fuelCost + maintenanceCost;
return {
vehicleId: selectedVehicle!,
fuelCost,
maintenanceCost,
totalOperatingCost: total,
fuelPercentage: total > 0 ? Math.round((fuelCost / total) * 100) : 0,
maintenancePercentage: total > 0 ? Math.round((maintenanceCost / total) * 100) : 0,
};
}, [fuelStats, maintenanceStats, selectedVehicle]);
const StatCard = ({ label, value }: { label: string; value: string }) => (
<Card withBorder>
<Card.Section p="md">
<Text size="sm" c="dimmed">
{label}
</Text>
<Text fw={700} size="lg">
{value}
</Text>
</Card.Section>
</Card>
);
return (
<Container size="xl" py="xl" px="lg">
<Stack gap="md">
<Card>
<Card.Section p="md" withBorder>
<Text fw={500}>Fleet Financial Analysis</Text>
</Card.Section>
<Card.Section p="md">
<Group>
<Select
label="Vehicle"
placeholder="Select a vehicle"
data={vehicleOptions}
value={selectedVehicle}
onChange={setSelectedVehicle}
style={{ flex: 1 }}
/>
<Select
label="Period"
data={[
{ label: 'Last 3 months', value: '3' },
{ label: 'Last 6 months', value: '6' },
{ label: 'Last 12 months', value: '12' },
]}
value={months}
onChange={v => setMonths(v || '12')}
style={{ flex: 1 }}
/>
</Group>
</Card.Section>
</Card>
{report && (
<>
<Grid>
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<StatCard label="Total Operating Cost" value={`$${report.totalOperatingCost.toFixed(2)}`} />
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<StatCard label="Fuel Cost" value={`$${report.fuelCost.toFixed(2)}`} />
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<StatCard label="Maintenance Cost" value={`$${report.maintenanceCost.toFixed(2)}`} />
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<Card withBorder>
<Card.Section p="md">
<Text size="sm" c="dimmed">
Monthly Avg
</Text>
<Text fw={700} size="lg">
${(report.totalOperatingCost / parseInt(months)).toFixed(2)}
</Text>
</Card.Section>
</Card>
</Grid.Col>
</Grid>
<Grid>
<Grid.Col span={{ base: 12, sm: 6 }}>
<Card>
<Card.Section p="md" withBorder>
<Text fw={500}>Cost Breakdown</Text>
</Card.Section>
<Card.Section p="md">
<Stack gap="lg">
<Group justify="space-between">
<Stack gap={0}>
<Text size="sm" c="dimmed">
Fuel
</Text>
<Text fw={500}>{report.fuelPercentage}%</Text>
</Stack>
<RingProgress
sections={[{ value: report.fuelPercentage, color: 'edr-accent' }]}
label={
<Text size="xs" align="center">
{report.fuelPercentage}%
</Text>
}
size={100}
thickness={4}
/>
</Group>
<Group justify="space-between">
<Stack gap={0}>
<Text size="sm" c="dimmed">
Maintenance
</Text>
<Text fw={500}>{report.maintenancePercentage}%</Text>
</Stack>
<RingProgress
sections={[{ value: report.maintenancePercentage, color: 'edr-red' }]}
label={
<Text size="xs" align="center">
{report.maintenancePercentage}%
</Text>
}
size={100}
thickness={4}
/>
</Group>
</Stack>
</Card.Section>
</Card>
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 6 }}>
<Card>
<Card.Section p="md" withBorder>
<Text fw={500}>Operational Insights</Text>
</Card.Section>
<Card.Section p="md">
<Stack gap="sm">
<div>
<Text size="sm" c="dimmed">
Fuel Purchases
</Text>
<Text fw={500}>{fuelStats?.totalPurchases || 0} transactions</Text>
</div>
<div>
<Text size="sm" c="dimmed">
Fuel Efficiency
</Text>
<Text fw={500}>
{fuelStats?.fuelEfficiency?.toFixed(2) || 'N/A'} km/L
</Text>
</div>
<div>
<Text size="sm" c="dimmed">
Maintenance Items
</Text>
<Text fw={500}>{maintenanceStats?.numberOfMaintenanceItems || 0} records</Text>
</div>
<div>
<Text size="sm" c="dimmed">
Avg Maintenance Cost
</Text>
<Text fw={500}>${maintenanceStats?.averageCostPerMaintenance?.toFixed(2) || '0.00'}</Text>
</div>
</Stack>
</Card.Section>
</Card>
</Grid.Col>
</Grid>
</>
)}
{!selectedVehicle && (
<Card>
<Card.Section p="md">
<Text c="dimmed">Select a vehicle to view financial reports</Text>
</Card.Section>
</Card>
)}
</Stack>
</Container>
);
}

View File

@@ -0,0 +1,361 @@
import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Card, Stack, Group, Grid, Text, ThemeIcon, Progress, Badge, Table, RingProgress, Container, Title, Box, Tabs, Button } from '@mantine/core';
import { Truck, Fuel, Wrench, TrendingUp, AlertCircle, Users, User, MapPin, Calendar, BarChart3 } from 'lucide-react';
import Breadcrumbs from '@/components/ui/Breadcrumbs';
import { QUERY_KEYS } from '@/constants/QUERY_KEYS';
import { api } from '@/auth/http';
import { vehiclesService } from '@/services/vehicles.service';
import { freightBrand } from '@/theme/freight-brand';
interface Vehicle {
id: string;
registrationNumber: string;
plateNumber: string;
manufacturer: string;
model: string;
status?: string;
}
interface Driver {
id: string;
firstName: string;
lastName: string;
licenseNumber?: string;
email?: string;
phone?: string;
assignedVehicle?: string;
}
interface FleetMetrics {
totalVehicles: number;
activeVehicles: number;
maintenanceOverdue: number;
totalFuelSpend: number;
totalMaintenanceSpend: number;
averageFuelEfficiency: number;
costPerKm: number;
totalDrivers: number;
assignedDrivers: number;
}
const StatCard = ({ icon: Icon, label, value, color = 'edr-green', change }: any) => (
<Card withBorder p="lg" style={{ borderTop: `3px solid ${freightBrand.primary}` }}>
<Group justify="space-between" mb="sm">
<ThemeIcon size="xl" radius="md" color={color} variant="light">
<Icon size={28} />
</ThemeIcon>
</Group>
<Stack gap="xs">
<Text size="xs" c="dimmed" fw={500} tt="uppercase">
{label}
</Text>
<Group justify="space-between">
<Text fw={700} size="xl" c="edr-ink">
{value}
</Text>
{change && <Badge color={change > 0 ? 'edr-green' : 'edr-red'} size="lg">{change > 0 ? '+' : ''}{change}%</Badge>}
</Group>
</Stack>
</Card>
);
export function FleetDashboard() {
const { data: vehicles = [] } = useQuery({
queryKey: QUERY_KEYS.VEHICLES.list(),
queryFn: async () => {
const res = await vehiclesService.getAll({ limit: 1000 });
return res.data || [];
},
});
const { data: drivers = [] } = useQuery({
queryKey: ['drivers'],
queryFn: async () => {
try {
const res = await api.get('/drivers');
return res.data || [];
} catch {
return [];
}
},
});
const { data: fuelStats } = useQuery({
queryKey: ['fleet-fuel-stats'],
queryFn: async () => {
try {
const res = await api.get('/fuel/stats');
return res.data || {};
} catch {
return {};
}
},
});
const { data: maintenanceStats } = useQuery({
queryKey: ['fleet-maintenance-stats'],
queryFn: async () => {
try {
const res = await api.get('/maintenance/stats');
return res.data || {};
} catch {
return {};
}
},
});
const metrics = useMemo((): FleetMetrics => {
const totalVehicles = (vehicles as Vehicle[]).length;
const activeVehicles = (vehicles as Vehicle[]).filter(v => v.status === 'ACTIVE').length;
const totalDrivers = (drivers as Driver[]).length;
const assignedDrivers = (drivers as Driver[]).filter(d => d.assignedVehicle).length;
const fuelTotal = fuelStats?.totalCost || 0;
const maintenanceTotal = maintenanceStats?.totalCost || 0;
return {
totalVehicles,
activeVehicles,
maintenanceOverdue: 0, // TODO: fetch from API
totalFuelSpend: fuelTotal,
totalMaintenanceSpend: maintenanceTotal,
averageFuelEfficiency: fuelStats?.averageEfficiency || 0,
costPerKm: (fuelTotal + maintenanceTotal) / 100000, // Placeholder
totalDrivers,
assignedDrivers,
};
}, [vehicles, drivers, fuelStats, maintenanceStats]);
const operatingCost = metrics.totalFuelSpend + metrics.totalMaintenanceSpend;
const fuelPercent = operatingCost > 0 ? Math.round((metrics.totalFuelSpend / operatingCost) * 100) : 0;
return (
<Container size="xl" py="xl" px="lg">
<Breadcrumbs items={[{ label: 'Fleet' }, { label: 'Dashboard' }]} />
<Box mb="xl">
<Title order={1} mb="xs">
Fleet Management Dashboard
</Title>
<Text c="dimmed" size="sm">
Real-time fleet overview, vehicle & driver management
</Text>
</Box>
{/* Primary Metrics */}
<Grid mb="xl">
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<StatCard icon={Truck} label="Total Vehicles" value={metrics.totalVehicles} color="edr-green" />
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<StatCard icon={Users} label="Total Drivers" value={metrics.totalDrivers} color="edr-blue" />
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<StatCard icon={Fuel} label="Fuel Spend" value={`$${metrics.totalFuelSpend.toFixed(0)}`} color="edr-accent" />
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<StatCard icon={Wrench} label="Maintenance" value={`$${metrics.totalMaintenanceSpend.toFixed(0)}`} color="edr-red" />
</Grid.Col>
</Grid>
{/* Fleet Status */}
<Grid mb="lg">
<Grid.Col span={{ base: 12, md: 6 }}>
<Card withBorder>
<Card.Section p="md" withBorder>
<Text fw={500}>Fleet Status</Text>
</Card.Section>
<Card.Section p="md">
<Stack gap="lg">
<div>
<Group justify="space-between" mb="xs">
<Text size="sm">Active Vehicles</Text>
<Text fw={700}>{metrics.activeVehicles} / {metrics.totalVehicles}</Text>
</Group>
<Progress value={(metrics.activeVehicles / metrics.totalVehicles) * 100} color="edr-green" />
</div>
<div>
<Group justify="space-between" mb="xs">
<Text size="sm">Maintenance Overdue</Text>
<Badge color="edr-red">{metrics.maintenanceOverdue}</Badge>
</Group>
<Progress value={0} color="edr-red" />
</div>
<div>
<Group justify="space-between" mb="xs">
<Text size="sm">Idle / Under Maintenance</Text>
<Text fw={700}>{metrics.totalVehicles - metrics.activeVehicles}</Text>
</Group>
<Progress value={((metrics.totalVehicles - metrics.activeVehicles) / metrics.totalVehicles) * 100} color="edr-amber-soft" />
</div>
</Stack>
</Card.Section>
</Card>
</Grid.Col>
<Grid.Col span={{ base: 12, md: 6 }}>
<Card withBorder>
<Card.Section p="md" withBorder>
<Text fw={500}>Operating Cost Breakdown</Text>
</Card.Section>
<Card.Section p="md">
<Stack gap="lg">
<Group justify="center">
<RingProgress
sections={[
{ value: fuelPercent, color: 'edr-accent' },
{ value: 100 - fuelPercent, color: 'edr-red' },
]}
label={
<div style={{ textAlign: 'center' }}>
<Text fw={700} size="sm">
${operatingCost.toFixed(0)}
</Text>
<Text size="xs" c="dimmed">
Total Cost
</Text>
</div>
}
size={120}
thickness={4}
/>
</Group>
<div>
<Group justify="space-between">
<Group gap="xs">
<ThemeIcon size="sm" color="edr-accent" variant="light">
<Fuel size={14} />
</ThemeIcon>
<Text size="sm">Fuel</Text>
</Group>
<Text fw={700}>{fuelPercent}%</Text>
</Group>
</div>
<div>
<Group justify="space-between">
<Group gap="xs">
<ThemeIcon size="sm" color="edr-red" variant="light">
<Wrench size={14} />
</ThemeIcon>
<Text size="sm">Maintenance</Text>
</Group>
<Text fw={700}>{100 - fuelPercent}%</Text>
</Group>
</div>
</Stack>
</Card.Section>
</Card>
</Grid.Col>
</Grid>
{/* Vehicles & Drivers Tabs */}
<Card withBorder>
<Tabs defaultValue="vehicles" p="md">
<Tabs.List>
<Tabs.Tab value="vehicles" leftSection={<Truck size={16} />}>
Vehicles ({(vehicles as Vehicle[]).length})
</Tabs.Tab>
<Tabs.Tab value="drivers" leftSection={<Users size={16} />}>
Drivers ({(drivers as Driver[]).length})
</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value="vehicles" pt="md">
{(vehicles as Vehicle[]).length > 0 ? (
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th>Registration</Table.Th>
<Table.Th>Plate</Table.Th>
<Table.Th>Model</Table.Th>
<Table.Th>Status</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{(vehicles as Vehicle[]).slice(0, 15).map(v => (
<Table.Tr key={v.id}>
<Table.Td fw={500}>{v.registrationNumber}</Table.Td>
<Table.Td>{v.plateNumber}</Table.Td>
<Table.Td>
{v.manufacturer} {v.model}
</Table.Td>
<Table.Td>
<Badge color={v.status === 'ACTIVE' ? 'edr-green' : v.status === 'MAINTENANCE' ? 'edr-amber-soft' : 'gray'}>
{v.status || 'UNKNOWN'}
</Badge>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
) : (
<Group gap="xs" p="md">
<AlertCircle size={20} />
<Text c="dimmed">No vehicles in fleet</Text>
</Group>
)}
</Tabs.Panel>
<Tabs.Panel value="drivers" pt="md">
{(drivers as Driver[]).length > 0 ? (
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th>Name</Table.Th>
<Table.Th>License</Table.Th>
<Table.Th>Contact</Table.Th>
<Table.Th>Assigned Vehicle</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{(drivers as Driver[]).slice(0, 15).map(d => (
<Table.Tr key={d.id}>
<Table.Td fw={500}>
<Group gap="xs">
<ThemeIcon size="sm" radius="xl" variant="light" color="blue">
<User size={14} />
</ThemeIcon>
{d.firstName} {d.lastName}
</Group>
</Table.Td>
<Table.Td>{d.licenseNumber || 'N/A'}</Table.Td>
<Table.Td>
<Stack gap={0} size="xs">
{d.phone && (
<Text size="xs">
<Group gap={4} inline>
<MapPin size={12} /> {d.phone}
</Group>
</Text>
)}
{d.email && <Text size="xs">{d.email}</Text>}
</Stack>
</Table.Td>
<Table.Td>
{d.assignedVehicle ? (
<Badge color="edr-green">Assigned</Badge>
) : (
<Badge color="edr-slate">Unassigned</Badge>
)}
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
) : (
<Group gap="xs" p="md">
<AlertCircle size={20} />
<Text c="dimmed">No drivers in system</Text>
</Group>
)}
</Tabs.Panel>
</Tabs>
</Card>
</Container>
);
}

View File

@@ -0,0 +1,316 @@
import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
Box,
Button,
Card,
Container,
Group,
Modal,
NumberInput,
Select,
Stack,
Table,
Text,
TextInput,
Title,
Badge,
Grid,
} from "@mantine/core";
import { Plus, Trash2 } from "lucide-react";
import Breadcrumbs from "@/components/ui/Breadcrumbs";
import { useToast } from "@/hooks/use-toast";
import { api } from "@/auth/http";
import { QUERY_KEYS } from "@/constants/QUERY_KEYS";
import { vehiclesService, type Vehicle as VehicleType } from "@/services/vehicles.service";
import { freightBrand } from "@/theme/freight-brand";
interface FuelPurchase {
id: string;
vehicleId: string;
vehicleName?: string;
purchaseDate: string;
liters: number;
costPerLiter: number;
totalCost: number;
fuelStation?: string;
paymentMethod: string;
odometerReading?: number;
receiptNumber?: string;
notes?: string;
}
export default function FuelPurchasePage() {
const { toast } = useToast();
const qc = useQueryClient();
const [modalOpen, setModalOpen] = useState(false);
const [formData, setFormData] = useState({
vehicleId: "",
purchaseDate: new Date().toISOString().split("T")[0],
liters: 0,
costPerLiter: 0,
fuelStation: "",
paymentMethod: "CASH",
odometerReading: undefined as number | undefined,
receiptNumber: "",
notes: "",
});
// Fetch vehicles
const { data: vehiclesData } = useQuery({
queryKey: QUERY_KEYS.VEHICLES.list(),
queryFn: async () => {
const res = await vehiclesService.getAll({ limit: 1000 });
return res.data || [];
},
});
// Fetch fuel purchases
const { data: purchasesData = [] } = useQuery({
queryKey: ["fuel-purchases"],
queryFn: async () => {
const res = await api.get("/fuel/purchases");
return res.data || [];
},
});
// Record purchase mutation
const recordMutation = useMutation({
mutationFn: async (data: typeof formData) => {
const res = await api.post("/fuel/purchases", {
...data,
liters: parseFloat(data.liters.toString()),
costPerLiter: parseFloat(data.costPerLiter.toString()),
});
return res.data;
},
onSuccess: () => {
toast({ title: "Fuel purchase recorded" });
setModalOpen(false);
setFormData({
vehicleId: "",
purchaseDate: new Date().toISOString().split("T")[0],
liters: 0,
costPerLiter: 0,
fuelStation: "",
paymentMethod: "CASH",
odometerReading: undefined,
receiptNumber: "",
notes: "",
});
qc.invalidateQueries({ queryKey: ["fuel-purchases"] });
},
onError: (error: any) => {
toast({
title: "Error recording purchase",
message: error?.response?.data?.message || "Failed to record fuel purchase",
color: "red",
});
},
});
const vehicleOptions =
vehiclesData?.map((v: VehicleType) => ({
value: v.id,
label: `${v.plateNumber} - ${v.manufacturer} ${v.model}`,
})) || [];
const totalCost = formData.liters * formData.costPerLiter;
return (
<Container size="xl" py="xl" px="lg">
<Breadcrumbs items={[{ label: "Fleet" }, { label: "Fuel Management" }, { label: "Record Purchase" }]} />
<Group justify="space-between" mb="lg">
<Title order={1}>Fuel Purchases</Title>
<Button leftSection={<Plus size={16} />} onClick={() => setModalOpen(true)} color="edr-green">
Record Purchase
</Button>
</Group>
{/* Stats Cards */}
<Grid mb="lg">
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<Card withBorder padding="lg">
<Text size="sm" c="dimmed" fw={500}>
Total Purchases
</Text>
<Text fw={700} size="lg">
{purchasesData.length}
</Text>
</Card>
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<Card withBorder padding="lg">
<Text size="sm" c="dimmed" fw={500}>
Total Liters
</Text>
<Text fw={700} size="lg">
{purchasesData
.reduce((sum: number, p: FuelPurchase) => sum + Number(p.liters), 0)
.toFixed(2)}{" "}
L
</Text>
</Card>
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<Card withBorder padding="lg">
<Text size="sm" c="dimmed" fw={500}>
Total Cost
</Text>
<Text fw={700} size="lg">
ETB {purchasesData
.reduce((sum: number, p: FuelPurchase) => sum + Number(p.totalCost), 0)
.toLocaleString("en-US", { maximumFractionDigits: 2 })}
</Text>
</Card>
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<Card withBorder padding="lg">
<Text size="sm" c="dimmed" fw={500}>
Avg Price/L
</Text>
<Text fw={700} size="lg">
ETB{" "}
{(
purchasesData.reduce((sum: number, p: FuelPurchase) => sum + Number(p.totalCost), 0) /
purchasesData.reduce((sum: number, p: FuelPurchase) => sum + Number(p.liters), 0) || 0
).toFixed(2)}
</Text>
</Card>
</Grid.Col>
</Grid>
{/* Purchases Table */}
<Card withBorder>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th>Vehicle</Table.Th>
<Table.Th>Date</Table.Th>
<Table.Th align="right">Liters</Table.Th>
<Table.Th align="right">Cost/L</Table.Th>
<Table.Th align="right">Total</Table.Th>
<Table.Th>Station</Table.Th>
<Table.Th>Payment</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{(purchasesData as FuelPurchase[])?.map((purchase) => (
<Table.Tr key={purchase.id}>
<Table.Td>{(purchase as any).vehicle?.registrationNumber || (purchase as any).vehicle?.plateNumber || purchase.vehicleId}</Table.Td>
<Table.Td>{new Date(purchase.purchaseDate).toLocaleDateString()}</Table.Td>
<Table.Td align="right">{Number(purchase.liters).toFixed(2)}</Table.Td>
<Table.Td align="right">ETB {Number(purchase.costPerLiter).toFixed(2)}</Table.Td>
<Table.Td align="right">ETB {Number(purchase.totalCost).toLocaleString("en-US", { maximumFractionDigits: 2 })}</Table.Td>
<Table.Td>{purchase.fuelStation || "—"}</Table.Td>
<Table.Td>
<Badge size="sm">{purchase.paymentMethod}</Badge>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
</Card>
{/* Modal */}
<Modal opened={modalOpen} onClose={() => setModalOpen(false)} title="Record Fuel Purchase" size="lg">
<Stack gap="md">
<Select
label="Vehicle"
placeholder="Select vehicle"
data={vehicleOptions}
value={formData.vehicleId}
onChange={(val) => setFormData({ ...formData, vehicleId: val || "" })}
required
/>
<TextInput
label="Purchase Date"
type="date"
value={formData.purchaseDate}
onChange={(e) => setFormData({ ...formData, purchaseDate: e.currentTarget.value })}
required
/>
<NumberInput
label="Liters"
placeholder="0.00"
value={formData.liters}
onChange={(val) => setFormData({ ...formData, liters: val as number })}
decimalScale={2}
min={0}
required
/>
<NumberInput
label="Cost per Liter"
placeholder="0.00"
value={formData.costPerLiter}
onChange={(val) => setFormData({ ...formData, costPerLiter: val as number })}
decimalScale={2}
min={0}
required
/>
<Card withBorder bg="gray.0" padding="md">
<Text fw={600} size="lg">
Total Cost: ETB {totalCost.toFixed(2)}
</Text>
</Card>
<TextInput
label="Fuel Station"
placeholder="Station name"
value={formData.fuelStation}
onChange={(e) => setFormData({ ...formData, fuelStation: e.currentTarget.value })}
/>
<Select
label="Payment Method"
data={["CASH", "CARD", "FUEL_CARD", "TRANSFER", "CHEQUE"]}
value={formData.paymentMethod}
onChange={(val) => setFormData({ ...formData, paymentMethod: val || "CASH" })}
/>
<NumberInput
label="Odometer Reading (KM)"
placeholder="Optional"
value={formData.odometerReading}
onChange={(val) => setFormData({ ...formData, odometerReading: val as number | undefined })}
decimalScale={0}
min={0}
/>
<TextInput
label="Receipt Number"
placeholder="Optional"
value={formData.receiptNumber}
onChange={(e) => setFormData({ ...formData, receiptNumber: e.currentTarget.value })}
/>
<TextInput
label="Notes"
placeholder="Optional notes"
value={formData.notes}
onChange={(e) => setFormData({ ...formData, notes: e.currentTarget.value })}
/>
<Group justify="flex-end">
<Button variant="light" onClick={() => setModalOpen(false)}>
Cancel
</Button>
<Button
onClick={() => recordMutation.mutate(formData)}
loading={recordMutation.isPending}
disabled={!formData.vehicleId || formData.liters <= 0 || formData.costPerLiter <= 0}
>
Record Purchase
</Button>
</Group>
</Stack>
</Modal>
</Container>
);
}

View File

@@ -0,0 +1,200 @@
import { useQuery } from "@tanstack/react-query";
import { Box, Card, Container, Grid, Group, Select, Stack, Table, Text, Title, Badge } from "@mantine/core";
import Breadcrumbs from "@/components/ui/Breadcrumbs";
import { api } from "@/auth/http";
import { QUERY_KEYS } from "@/constants/QUERY_KEYS";
import { vehiclesService, type Vehicle as VehicleType } from "@/services/vehicles.service";
import { useState } from "react";
interface FuelStats {
vehicleId: string;
totalPurchases: number;
totalLiters: number;
totalCost: number;
averagePricePerLiter: number;
dateRange: { startDate: string; endDate: string };
}
export default function FuelStatsPage() {
const [selectedVehicleId, setSelectedVehicleId] = useState<string>("");
const [monthsBack, setMonthsBack] = useState<string>("12");
// Fetch vehicles
const { data: vehiclesData } = useQuery({
queryKey: QUERY_KEYS.VEHICLES.list(),
queryFn: async () => {
const res = await vehiclesService.getAll({ limit: 1000 });
return res.data || [];
},
});
// Fetch fuel stats
const { data: statsData } = useQuery({
queryKey: ["fuel-stats", selectedVehicleId, monthsBack],
queryFn: async () => {
if (!selectedVehicleId) return null;
const res = await api.get(`/fuel/stats/${selectedVehicleId}?months=${monthsBack}`);
return res.data;
},
enabled: !!selectedVehicleId,
});
const vehicleOptions =
vehiclesData?.map((v: VehicleType) => ({
value: v.id,
label: `${v.plateNumber} - ${v.manufacturer} ${v.model}`,
})) || [];
const selectedVehicle = vehiclesData?.find((v: VehicleType) => v.id === selectedVehicleId);
const costPerKm =
statsData && selectedVehicle?.actualDistanceKm
? (statsData.totalCost / selectedVehicle.actualDistanceKm).toFixed(2)
: "—";
const efficiency = statsData
? (statsData.totalLiters > 0 ? (selectedVehicle?.actualDistanceKm || 0) / statsData.totalLiters : 0).toFixed(2)
: "—";
return (
<Container size="xl" py="xl" px="lg">
<Breadcrumbs items={[{ label: "Fleet" }, { label: "Fuel Management" }, { label: "Statistics" }]} />
<Group justify="space-between" mb="lg">
<Title order={1}>Fuel Consumption Analysis</Title>
</Group>
{/* Filters */}
<Card withBorder mb="lg" padding="md">
<Grid>
<Grid.Col span={{ base: 12, sm: 6 }}>
<Select
label="Vehicle"
placeholder="Select vehicle to analyze"
data={vehicleOptions}
value={selectedVehicleId}
onChange={(val) => setSelectedVehicleId(val || "")}
searchable
/>
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 6 }}>
<Select
label="Period"
data={[
{ value: "3", label: "Last 3 months" },
{ value: "6", label: "Last 6 months" },
{ value: "12", label: "Last 12 months" },
]}
value={monthsBack}
onChange={(val) => setMonthsBack(val || "12")}
/>
</Grid.Col>
</Grid>
</Card>
{selectedVehicleId && statsData ? (
<>
{/* Stats Cards */}
<Grid mb="lg">
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<Card withBorder padding="lg">
<Text size="sm" c="dimmed" fw={500}>
Total Purchases
</Text>
<Text fw={700} size="lg">
{statsData.totalPurchases}
</Text>
</Card>
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<Card withBorder padding="lg">
<Text size="sm" c="dimmed" fw={500}>
Total Fuel
</Text>
<Text fw={700} size="lg">
{statsData.totalLiters.toFixed(2)} L
</Text>
</Card>
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<Card withBorder padding="lg">
<Text size="sm" c="dimmed" fw={500}>
Total Cost
</Text>
<Text fw={700} size="lg">
ETB {statsData.totalCost.toLocaleString("en-US", { maximumFractionDigits: 2 })}
</Text>
</Card>
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 6, md: 3 }}>
<Card withBorder padding="lg">
<Text size="sm" c="dimmed" fw={500}>
Avg Price/L
</Text>
<Text fw={700} size="lg">
ETB {statsData.averagePricePerLiter.toFixed(2)}
</Text>
</Card>
</Grid.Col>
</Grid>
{/* Efficiency Metrics */}
<Grid mb="lg">
<Grid.Col span={{ base: 12, sm: 6 }}>
<Card withBorder padding="lg">
<Text size="sm" c="dimmed" fw={500}>
Fuel Efficiency
</Text>
<Text fw={700} size="lg">
{efficiency} km/L
</Text>
</Card>
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 6 }}>
<Card withBorder padding="lg">
<Text size="sm" c="dimmed" fw={500}>
Cost per KM
</Text>
<Text fw={700} size="lg">
ETB {costPerKm}
</Text>
</Card>
</Grid.Col>
</Grid>
{/* Summary */}
<Card withBorder padding="lg">
<Stack gap="md">
<div>
<Text fw={600} mb="xs">
Summary
</Text>
<Text size="sm">
{selectedVehicle?.plateNumber} consumed{" "}
<Text fw={700} span>
{statsData.totalLiters.toFixed(2)} liters
</Text>{" "}
over the last {monthsBack} months, costing{" "}
<Text fw={700} span>
ETB {statsData.totalCost.toLocaleString("en-US", { maximumFractionDigits: 2 })}
</Text>
. Average fuel price was{" "}
<Text fw={700} span>
ETB {statsData.averagePricePerLiter.toFixed(2)} per liter
</Text>
.
</Text>
</div>
</Stack>
</Card>
</>
) : (
<Card withBorder padding="lg">
<Text c="dimmed" ta="center">
Select a vehicle to view fuel consumption statistics
</Text>
</Card>
)}
</Container>
);
}

View File

@@ -0,0 +1,206 @@
import { useState, useMemo } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Card, Button, Modal, Stack, Group, Grid, Select, TextInput, NumberInput, Table, Badge, Text, Container } from '@mantine/core';
import { DateInput } from '@mantine/dates';
import { Plus } from 'lucide-react';
import { QUERY_KEYS } from '@/constants/QUERY_KEYS';
import { api } from '@/services/api';
import { vehiclesService } from '@/services/vehicles.service';
import { freightBrand } from '@/theme/freight-brand';
interface MaintenanceSchedule {
id: string;
vehicleId: string;
maintenanceType: string;
description: string;
scheduledDate: string;
completedDate?: string;
status: string;
estimatedCost?: number;
actualCost?: number;
serviceProvider?: string;
}
export function MaintenancePage() {
const [selectedVehicle, setSelectedVehicle] = useState<string | null>(null);
const [openScheduleModal, setOpenScheduleModal] = useState(false);
const [formData, setFormData] = useState({
maintenanceType: 'PREVENTIVE',
description: '',
scheduledDate: new Date(),
estimatedCost: 0,
serviceProvider: '',
notes: '',
});
const queryClient = useQueryClient();
const { data: vehicles } = useQuery({
queryKey: QUERY_KEYS.VEHICLES.list(),
queryFn: async () => {
const res = await vehiclesService.getAll({ limit: 1000 });
return res.data || [];
},
});
const { data: upcoming, isLoading } = useQuery({
queryKey: QUERY_KEYS.MAINTENANCE.upcoming(selectedVehicle || ''),
queryFn: () => selectedVehicle ? api.get(`/maintenance/upcoming/${selectedVehicle}`) : Promise.resolve([]),
enabled: !!selectedVehicle,
});
const scheduleMutation = useMutation({
mutationFn: async () => {
if (!selectedVehicle) return;
return api.post('/maintenance/schedules', {
vehicleId: selectedVehicle,
...formData,
});
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: QUERY_KEYS.MAINTENANCE.upcoming(selectedVehicle || '') });
setOpenScheduleModal(false);
setFormData({
maintenanceType: 'PREVENTIVE',
description: '',
scheduledDate: new Date(),
estimatedCost: 0,
serviceProvider: '',
notes: '',
});
},
});
const vehicleOptions = useMemo(
() => vehicles?.map(v => ({ label: v.registrationNumber || v.id, value: v.id })) || [],
[vehicles]
);
const statusColor = (status: string) => {
const colors: Record<string, string> = {
SCHEDULED: 'edr-blue',
IN_PROGRESS: 'edr-amber-soft',
COMPLETED: 'edr-green',
OVERDUE: 'edr-red',
};
return colors[status] || 'edr-slate';
};
return (
<Container size="xl" py="xl" px="lg">
<Stack gap="md">
<Card>
<Card.Section p="md" withBorder>
<Group justify="space-between">
<Text fw={500}>Schedule Maintenance</Text>
<Button onClick={() => setOpenScheduleModal(true)} color="edr-green" leftSection={<Plus size={16} />}>
New Schedule
</Button>
</Group>
</Card.Section>
<Card.Section p="md">
<Select
label="Select Vehicle"
placeholder="Pick a vehicle"
data={vehicleOptions}
value={selectedVehicle}
onChange={setSelectedVehicle}
/>
</Card.Section>
</Card>
{selectedVehicle && (
<Card>
<Card.Section p="md" withBorder>
<Text fw={500}>Upcoming Maintenance</Text>
</Card.Section>
<Card.Section p="md">
{isLoading ? (
<Text>Loading...</Text>
) : (upcoming || []).length > 0 ? (
<Table>
<Table.Thead>
<Table.Tr>
<Table.Th>Type</Table.Th>
<Table.Th>Description</Table.Th>
<Table.Th>Scheduled</Table.Th>
<Table.Th>Est. Cost</Table.Th>
<Table.Th>Status</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{(upcoming as MaintenanceSchedule[]).map(m => (
<Table.Tr key={m.id}>
<Table.Td>{m.maintenanceType}</Table.Td>
<Table.Td>{m.description}</Table.Td>
<Table.Td>{new Date(m.scheduledDate).toLocaleDateString()}</Table.Td>
<Table.Td>${m.estimatedCost?.toFixed(2) || '—'}</Table.Td>
<Table.Td>
<Badge color={statusColor(m.status)}>{m.status}</Badge>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
) : (
<Text c="dimmed">No upcoming maintenance</Text>
)}
</Card.Section>
</Card>
)}
<Modal
opened={openScheduleModal}
onClose={() => setOpenScheduleModal(false)}
title="Schedule Maintenance"
size="md"
>
<Stack gap="md">
<Select
label="Type"
data={['PREVENTIVE', 'CORRECTIVE', 'INSPECTION', 'REPAIR']}
value={formData.maintenanceType}
onChange={v => setFormData({ ...formData, maintenanceType: v || 'PREVENTIVE' })}
/>
<TextInput
label="Description"
placeholder="What needs to be done?"
value={formData.description}
onChange={e => setFormData({ ...formData, description: e.currentTarget.value })}
/>
<DateInput
label="Scheduled Date"
value={formData.scheduledDate}
onChange={d => setFormData({ ...formData, scheduledDate: d || new Date() })}
/>
<NumberInput
label="Estimated Cost"
value={formData.estimatedCost}
onChange={v => setFormData({ ...formData, estimatedCost: Number(v) })}
/>
<TextInput
label="Service Provider"
placeholder="e.g., John's Auto Repair"
value={formData.serviceProvider}
onChange={e => setFormData({ ...formData, serviceProvider: e.currentTarget.value })}
/>
<TextInput
label="Notes"
placeholder="Additional notes"
value={formData.notes}
onChange={e => setFormData({ ...formData, notes: e.currentTarget.value })}
/>
<Group justify="flex-end">
<Button variant="light" onClick={() => setOpenScheduleModal(false)}>
Cancel
</Button>
<Button onClick={() => scheduleMutation.mutate()} loading={scheduleMutation.isPending}>
Schedule
</Button>
</Group>
</Stack>
</Modal>
</Stack>
</Container>
);
}

View File

@@ -1,5 +1,14 @@
import { FormEvent, useMemo, useState } from "react";
import { Ban, CircleCheck, Edit, Eye, Plus, Route as RouteIcon, Trash2 } from "lucide-react";
import {
ArrowRight,
Ban,
CircleCheck,
Edit,
Eye,
Plus,
Route as RouteIcon,
Trash2,
} from "lucide-react";
import type { ColumnDef } from "@edr/ui-common";
import {
ActionIcon,
@@ -7,13 +16,16 @@ import {
Box,
Button,
Card,
Divider,
Group,
Modal,
NumberInput,
Select,
SimpleGrid,
Stack,
Text,
TextInput,
ThemeIcon,
Tooltip,
} from "@mantine/core";
@@ -26,22 +38,51 @@ import RuleEngineListFooter from "@/components/ruleEngine/RuleEngineListFooter";
import { ruleEngineTable } from "@/components/ruleEngine/ruleEngineStyles";
import { api } from "@/services/api";
import { useToast } from "@/hooks/use-toast";
import type { RouteRecord, YardRef } from "@/services/routes.service";
import {
formatRouteLabel,
ROUTE_STATUS_OPTIONS,
totalRouteDistanceKm,
type RouteRecord,
type RouteStatus,
type YardRef,
} from "@/services/routes.service";
import { DataTable, DataTableFooter, usePagination } from "@edr/ui-common";
type MilestoneFormRow = { yardId: string; distanceKm: string };
type RouteFormState = {
name: string;
milestones: string[];
status: RouteStatus;
milestones: MilestoneFormRow[];
};
const emptyForm = (): RouteFormState => ({ name: "", milestones: ["", ""] });
const emptyForm = (): RouteFormState => ({
status: "AVAILABLE",
milestones: [
{ yardId: "", distanceKm: "0" },
{ yardId: "", distanceKm: "" },
],
});
const yardLabel = (yard?: YardRef | null) => (yard ? `${yard.label} (${yard.code})` : "—");
const yardLabel = (yard?: YardRef | null) =>
yard ? `${yard.label} (${yard.code})` : "—";
const routeStops = (route: RouteRecord) =>
(route.milestones ?? [])
.sort((left, right) => left.sequenceNo - right.sequenceNo)
.map((milestone) => milestone.yard?.label ?? milestone.yard?.code ?? milestone.yardId);
const statusColor = (status: RouteStatus) => {
switch (status) {
case "AVAILABLE":
return "edr-green";
case "MAINTENANCE":
return "yellow";
case "DAMAGED":
return "red";
case "STOP_WORKING":
return "gray";
default:
return "gray";
}
};
const statusLabel = (status: RouteStatus) =>
ROUTE_STATUS_OPTIONS.find((o) => o.value === status)?.label ?? status;
const normalizeRouteError = (error: unknown) => {
const responseData = (error as { response?: { data?: unknown } })?.response?.data;
@@ -57,6 +98,60 @@ const normalizeRouteError = (error: unknown) => {
: "Save failed";
};
function RouteTimeline({ route }: { route: RouteRecord }) {
const stops = [...(route.milestones ?? [])].sort(
(a, b) => a.sequenceNo - b.sequenceNo,
);
const total = totalRouteDistanceKm(route);
return (
<Stack gap="sm">
{stops.map((milestone, index) => {
const label =
milestone.yard?.label ?? milestone.yard?.code ?? milestone.yardId;
const role =
index === 0
? "Origin"
: index === stops.length - 1
? "Destination"
: `Milestone ${index}`;
const km = Number(milestone.distanceKm ?? 0);
return (
<Box key={milestone.id ?? `${milestone.yardId}-${index}`}>
{index > 0 && (
<Group gap={8} pl={18} py={6}>
<ThemeIcon size={22} radius="xl" variant="light" color="gray">
<ArrowRight size={12} />
</ThemeIcon>
<Text size="xs" c="dimmed" fw={600}>
{km} km
</Text>
</Group>
)}
<Group gap="sm" wrap="nowrap">
<Badge size="sm" variant="light" color={index === 0 ? "teal" : "gray"}>
{role}
</Badge>
<Text size="sm" fw={500}>
{label}
</Text>
</Group>
</Box>
);
})}
<Divider />
<Group justify="space-between">
<Text size="sm" fw={600}>
Total distance
</Text>
<Text size="sm" fw={700}>
{total} km
</Text>
</Group>
</Stack>
);
}
export default function RoutesPage() {
const [search, setSearch] = useState("");
const [formOpen, setFormOpen] = useState(false);
@@ -78,12 +173,14 @@ export default function RoutesPage() {
if (!query) return routesQuery.data ?? [];
return (routesQuery.data ?? []).filter((route) => {
const searchable = [
route.name,
formatRouteLabel(route),
route.originYard?.label,
route.originYard?.code,
route.destinationYard?.label,
route.destinationYard?.code,
...routeStops(route),
...(route.milestones ?? []).map(
(m) => m.yard?.label ?? m.yard?.code ?? m.yardId,
),
]
.filter(Boolean)
.join(" ")
@@ -99,7 +196,7 @@ export default function RoutesPage() {
}, [filteredRoutes, pagination.pageIndex, pagination.pageSize]);
const allRoutes = routesQuery.data ?? [];
const activeCount = allRoutes.filter((route) => route.isActive).length;
const availableCount = allRoutes.filter((r) => r.status === "AVAILABLE").length;
const yardOptions = useMemo(
() =>
@@ -110,6 +207,16 @@ export default function RoutesPage() {
[yardsQuery.data],
);
const formTotalKm = useMemo(
() =>
form.milestones.reduce(
(sum, row, index) =>
index === 0 ? sum : sum + Number(row.distanceKm || 0),
0,
),
[form.milestones],
);
const resetForm = () => {
setFormOpen(false);
setEditing(null);
@@ -125,41 +232,52 @@ export default function RoutesPage() {
const openEdit = (route: RouteRecord) => {
setEditing(route);
setForm({
name: route.name,
milestones: (route.milestones ?? [])
.sort((left, right) => left.sequenceNo - right.sequenceNo)
.map((milestone) => milestone.yardId),
status: route.status,
milestones: [...(route.milestones ?? [])]
.sort((a, b) => a.sequenceNo - b.sequenceNo)
.map((m, index) => ({
yardId: m.yardId,
distanceKm: String(index === 0 ? 0 : (m.distanceKm ?? "")),
})),
});
setFormOpen(true);
};
const setMilestone = (index: number, yardId: string) => {
const setMilestone = (index: number, patch: Partial<MilestoneFormRow>) => {
setForm((current) => ({
...current,
milestones: current.milestones.map((value, currentIndex) =>
currentIndex === index ? yardId : value,
milestones: current.milestones.map((row, i) =>
i === index ? { ...row, ...patch } : row,
),
}));
};
const addMilestone = () => {
setForm((current) => ({ ...current, milestones: [...current.milestones, ""] }));
setForm((current) => ({
...current,
milestones: [...current.milestones, { yardId: "", distanceKm: "" }],
}));
};
const removeMilestone = (index: number) => {
setForm((current) => ({
...current,
milestones: current.milestones.filter((_, currentIndex) => currentIndex !== index),
milestones: current.milestones.filter((_, i) => i !== index),
}));
};
const buildPayload = () => ({
status: form.status,
milestones: form.milestones.map((row, index) => ({
yardId: row.yardId,
distanceKm:
index === 0 ? 0 : row.distanceKm ? Number(row.distanceKm) : undefined,
})),
});
const handleSubmit = async (event: FormEvent) => {
event.preventDefault();
if (!form.name.trim()) {
toast({ title: "Save failed", description: "Route name is required", variant: "destructive" });
return;
}
if (form.milestones.length < 2 || form.milestones.some((yardId) => !yardId)) {
if (form.milestones.length < 2 || form.milestones.some((row) => !row.yardId)) {
toast({
title: "Save failed",
description: "Select at least an origin and destination yard",
@@ -167,13 +285,20 @@ export default function RoutesPage() {
});
return;
}
for (let i = 1; i < form.milestones.length; i++) {
const km = Number(form.milestones[i].distanceKm);
if (!form.milestones[i].distanceKm || Number.isNaN(km) || km < 0) {
toast({
title: "Save failed",
description: `Enter segment KM for stop ${i + 1}`,
variant: "destructive",
});
return;
}
}
try {
const payload = {
name: form.name.trim(),
milestones: form.milestones.map((yardId) => ({ yardId })),
isActive: editing?.isActive ?? true,
};
const payload = buildPayload();
if (editing) {
await updateMutation.mutateAsync({ id: editing.id, data: payload });
toast({ title: "Route updated" });
@@ -190,9 +315,19 @@ export default function RoutesPage() {
const handleDeactivate = async (route: RouteRecord) => {
try {
await deactivateMutation.mutateAsync(route.id);
toast({ title: "Route deactivated" });
toast({ title: "Route marked stop working" });
} catch {
toast({ title: "Deactivate failed", description: "Could not deactivate route", variant: "destructive" });
toast({ title: "Update failed", description: "Could not update route status", variant: "destructive" });
}
};
const handleStatusChange = async (route: RouteRecord, status: RouteStatus) => {
try {
await updateMutation.mutateAsync({ id: route.id, data: { status } });
setViewing((current) => (current?.id === route.id ? { ...current, status } : current));
toast({ title: "Status updated" });
} catch (error) {
toast({ title: "Update failed", description: normalizeRouteError(error), variant: "destructive" });
}
};
@@ -200,10 +335,14 @@ export default function RoutesPage() {
const availableOptionsForIndex = (index: number) => {
const selectedByOthers = new Set(
form.milestones.filter((value, currentIndex) => currentIndex !== index && value),
form.milestones
.filter((row, i) => i !== index && row.yardId)
.map((row) => row.yardId),
);
return yardOptions.filter(
(option) => option.value === form.milestones[index] || !selectedByOthers.has(option.value),
(option) =>
option.value === form.milestones[index]?.yardId ||
!selectedByOthers.has(option.value),
);
};
@@ -217,7 +356,16 @@ export default function RoutesPage() {
const headerClassName = ruleEngineTable.headerCell;
const cellClassName = ruleEngineTable.bodyCell;
return [
{ id: "name", header: "Name", meta: { headerClassName, cellClassName }, cell: ({ row }) => row.original.name },
{
id: "corridor",
header: "Corridor",
meta: { headerClassName, cellClassName },
cell: ({ row }) => (
<Text fw={600} size="sm">
{formatRouteLabel(row.original)}
</Text>
),
},
{
id: "origin",
header: "Origin",
@@ -231,18 +379,24 @@ export default function RoutesPage() {
cell: ({ row }) => yardLabel(row.original.destinationYard),
},
{
id: "milestones",
header: "Milestones",
id: "distance",
header: "Total KM",
meta: { headerClassName, cellClassName },
cell: ({ row }) => Math.max((row.original.milestones?.length ?? 0) - 2, 0),
cell: ({ row }) => `${totalRouteDistanceKm(row.original)} km`,
},
{
id: "milestones",
header: "Stops",
meta: { headerClassName, cellClassName },
cell: ({ row }) => row.original.milestones?.length ?? 0,
},
{
id: "status",
header: "Status",
meta: { headerClassName, cellClassName },
cell: ({ row }) => (
<Badge color={row.original.isActive ? "edr-green" : "gray"} variant="light" size="sm">
{row.original.isActive ? "Active" : "Inactive"}
<Badge color={statusColor(row.original.status)} variant="light" size="sm">
{statusLabel(row.original.status)}
</Badge>
),
},
@@ -262,11 +416,11 @@ export default function RoutesPage() {
<Edit size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label="Deactivate">
<Tooltip label="Mark stop working">
<ActionIcon
variant="subtle"
color="red"
disabled={!row.original.isActive || deactivateMutation.isPending}
disabled={row.original.status === "STOP_WORKING" || deactivateMutation.isPending}
onClick={() => handleDeactivate(row.original)}
>
<Trash2 size={16} />
@@ -282,7 +436,7 @@ export default function RoutesPage() {
<PageContainer>
<PageHeader
title="Routes"
subtitle="Define rail corridors and their ordered yard stops used by train scheduling."
subtitle="Define rail corridors, segment distances, and operational status for train scheduling."
action={
<Button leftSection={<Plus size={18} />} onClick={openCreate}>
Add route
@@ -294,10 +448,10 @@ export default function RoutesPage() {
loading={routesQuery.isLoading}
items={[
{ label: "Total routes", value: allRoutes.length, icon: RouteIcon },
{ label: "Active", value: activeCount, icon: CircleCheck, color: "edr-green" },
{ label: "Available", value: availableCount, icon: CircleCheck, color: "edr-green" },
{
label: "Inactive",
value: allRoutes.length - activeCount,
label: "Unavailable",
value: allRoutes.length - availableCount,
icon: Ban,
color: "gray",
},
@@ -310,7 +464,7 @@ export default function RoutesPage() {
<FleetToolbar
search={search}
onSearchChange={setSearch}
searchPlaceholder="Search routes…"
searchPlaceholder="Search corridors…"
viewMode={viewMode}
onViewModeChange={setViewMode}
/>
@@ -359,16 +513,13 @@ export default function RoutesPage() {
<Card key={route.id} radius="lg" padding="lg" withBorder>
<Stack gap="sm">
<Group justify="space-between">
<Text fw={600}>{route.name}</Text>
<Badge color={route.isActive ? "edr-green" : "gray"} variant="light" size="sm">
{route.isActive ? "Active" : "Inactive"}
<Text fw={600}>{formatRouteLabel(route)}</Text>
<Badge color={statusColor(route.status)} variant="light" size="sm">
{statusLabel(route.status)}
</Badge>
</Group>
<Text size="sm" c="dimmed">
{yardLabel(route.originYard)} {yardLabel(route.destinationYard)}
</Text>
<Text size="xs" c="dimmed">
{Math.max((route.milestones?.length ?? 0) - 2, 0)} intermediate milestones
{totalRouteDistanceKm(route)} km · {route.milestones?.length ?? 0} stops
</Text>
<Group gap={6} justify="flex-end">
<Button variant="light" size="compact-sm" onClick={() => setViewing(route)}>
@@ -405,26 +556,25 @@ export default function RoutesPage() {
>
<form onSubmit={handleSubmit}>
<Stack gap="md">
<TextInput
label="Name"
value={form.name}
onChange={(e) => {
// Capture the value before the state updater runs — React may
// recycle the synthetic event, nulling currentTarget by the time
// the updater executes ("Cannot read properties of null").
const name = e.currentTarget.value;
setForm((current) => ({ ...current, name }));
}}
/>
{editing && (
<Select
label="Status"
data={ROUTE_STATUS_OPTIONS}
value={form.status}
onChange={(value) =>
value && setForm((current) => ({ ...current, status: value as RouteStatus }))
}
/>
)}
<Group justify="space-between">
<Text size="sm" fw={500}>
Stops
Stops & segment distances
</Text>
<Button type="button" variant="light" size="compact-sm" onClick={addMilestone}>
Add milestone
</Button>
</Group>
{form.milestones.map((yardId, index) => {
{form.milestones.map((row, index) => {
const role =
index === 0
? "Origin"
@@ -432,18 +582,32 @@ export default function RoutesPage() {
? "Destination"
: "Milestone";
return (
<Group key={`${role}-${index}`} align="flex-end" wrap="nowrap">
<Text w={100} size="sm" fw={500}>
<Group key={`${role}-${index}`} align="flex-end" wrap="nowrap" gap="sm">
<Text w={90} size="sm" fw={500}>
{role}
</Text>
<Select
style={{ flex: 1 }}
data={availableOptionsForIndex(index)}
value={yardId || null}
onChange={(value) => value && setMilestone(index, value)}
value={row.yardId || null}
onChange={(value) => value && setMilestone(index, { yardId: value })}
placeholder="Select yard"
searchable
/>
{index > 0 ? (
<NumberInput
w={120}
label="KM"
min={0}
decimalScale={2}
value={row.distanceKm ? Number(row.distanceKm) : ""}
onChange={(value) =>
setMilestone(index, { distanceKm: String(value ?? "") })
}
/>
) : (
<Box w={120} />
)}
<ActionIcon
variant="subtle"
color="red"
@@ -455,6 +619,9 @@ export default function RoutesPage() {
</Group>
);
})}
<Text size="sm" c="dimmed">
Total route distance: <strong>{formTotalKm} km</strong>
</Text>
<Group justify="flex-end">
<Button variant="default" type="button" onClick={resetForm}>
Cancel
@@ -470,44 +637,37 @@ export default function RoutesPage() {
<Modal
opened={Boolean(viewing)}
onClose={() => setViewing(null)}
title={<Text fw={600}>Route details</Text>}
title={<Text fw={600}>{viewing ? formatRouteLabel(viewing) : "Route details"}</Text>}
radius="lg"
centered
size="md"
>
{viewing ? (
<Stack gap="sm">
<Stack gap="md">
<Group justify="space-between" align="flex-end">
<div>
<Text size="sm" fw={500}>
Status
</Text>
<Badge mt={4} color={statusColor(viewing.status)} variant="light">
{statusLabel(viewing.status)}
</Badge>
</div>
<Select
w={200}
label="Update status"
data={ROUTE_STATUS_OPTIONS}
value={viewing.status}
onChange={(value) =>
value && handleStatusChange(viewing, value as RouteStatus)
}
/>
</Group>
<div>
<Text size="sm" fw={500}>
Name
<Text size="sm" fw={500} mb={8}>
Road timeline
</Text>
<Text size="sm" c="dimmed">
{viewing.name}
</Text>
</div>
<div>
<Text size="sm" fw={500}>
Status
</Text>
<Text size="sm" c="dimmed">
{viewing.isActive ? "Active" : "Inactive"}
</Text>
</div>
<div>
<Text size="sm" fw={500}>
Stops
</Text>
<Stack gap={6} mt={6}>
{routeStops(viewing).map((stop, index, stops) => (
<Text key={`${stop}-${index}`} size="sm" c="dimmed">
{index === 0
? "Origin"
: index === stops.length - 1
? "Destination"
: `Milestone ${index}`}
: {stop}
</Text>
))}
</Stack>
<RouteTimeline route={viewing} />
</div>
</Stack>
) : null}

View File

@@ -0,0 +1,359 @@
import { useState, useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Container, Grid, Card, Stack, Group, Select, Text, Badge, Button, Box, Table, ThemeIcon, SimpleGrid } from '@mantine/core';
import { MapPin, Navigation, Radio, Activity } from 'lucide-react';
import Breadcrumbs from '@/components/ui/Breadcrumbs';
import { QUERY_KEYS } from '@/constants/QUERY_KEYS';
import { vehiclesService } from '@/services/vehicles.service';
import { freightBrand } from '@/theme/freight-brand';
interface Vehicle {
id: string;
registrationNumber: string;
plateNumber: string;
manufacturer: string;
model: string;
status?: string;
}
interface GPSLocation {
lat: number;
lng: number;
speed?: number;
heading?: number;
lastUpdate?: string;
}
// Mock GPS data for demo
const generateMockGPS = (index: number): GPSLocation => ({
lat: 9.0 + Math.random() * 0.5,
lng: 38.7 + Math.random() * 0.5,
speed: Math.floor(Math.random() * 120),
heading: Math.floor(Math.random() * 360),
lastUpdate: new Date(Date.now() - Math.random() * 300000).toLocaleTimeString(),
});
export function TrackingPage() {
const [selectedVehicleId, setSelectedVehicleId] = useState<string | null>(null);
const [mapCenter] = useState({ lat: 9.0, lng: 38.8 });
const mapZoom = 10;
const { data: vehicles = [] } = useQuery({
queryKey: QUERY_KEYS.VEHICLES.list(),
queryFn: async () => {
const res = await vehiclesService.getAll({ limit: 1000 });
return res.data || [];
},
});
// Generate mock GPS data for each vehicle
const vehiclesWithGPS = useMemo(() => {
return (vehicles as Vehicle[]).map((v, idx) => ({
...v,
gps: generateMockGPS(idx),
}));
}, [vehicles]);
// For demo: show all vehicles as trackable (or filter by ACTIVE if status data available)
const trackableVehicles = useMemo(
() => vehiclesWithGPS.slice(0, 10), // Limit to first 10 for demo
[vehiclesWithGPS]
);
const selectedVehicle = trackableVehicles.find(v => v.id === selectedVehicleId);
const vehicleOptions = useMemo(
() => trackableVehicles.map(v => ({ label: v.registrationNumber, value: v.id })),
[trackableVehicles]
);
// Map dimensions
const mapWidth = 800;
const mapHeight = 500;
const pixelsPerLat = mapHeight / 0.6;
const pixelsPerLng = mapWidth / 0.6;
const getMapCoords = (lat: number, lng: number) => ({
x: ((lng - (mapCenter.lng - 0.3)) * pixelsPerLng),
y: ((mapCenter.lat + 0.3 - lat) * pixelsPerLat),
});
return (
<Container size="xl" py="xl" px="lg">
<Breadcrumbs items={[{ label: 'Fleet' }, { label: 'Vehicle Tracking' }]} />
<Stack gap="xl">
<Group justify="space-between">
<div>
<Text fw={700} size="xl">
Real-Time Vehicle Tracking
</Text>
<Text c="dimmed" size="sm">
Monitor vehicle locations, speed, and status
</Text>
</div>
</Group>
<Grid>
{/* Map Section */}
<Grid.Col span={{ base: 12, lg: 8 }}>
<Card withBorder p="lg">
<Card.Section p="md" withBorder>
<Group justify="space-between">
<Text fw={500}>Map View</Text>
<Group gap="xs">
<Badge color="edr-green" leftSection={<Radio size={12} />}>
{trackableVehicles.length} Tracked
</Badge>
</Group>
</Group>
</Card.Section>
<Card.Section p="md">
<Box
pos="relative"
style={{
width: mapWidth,
height: mapHeight,
backgroundColor: '#f0f8f7',
border: `2px solid ${freightBrand.primary}`,
borderRadius: '8px',
overflow: 'hidden',
}}
>
{/* Grid background */}
<svg
width={mapWidth}
height={mapHeight}
style={{ position: 'absolute', top: 0, left: 0 }}
>
{/* Latitude lines */}
{[0, 1, 2, 3, 4, 5, 6].map(i => (
<line
key={`lat-${i}`}
x1={0}
y1={(i / 6) * mapHeight}
x2={mapWidth}
y2={(i / 6) * mapHeight}
stroke="#e0e0e0"
strokeWidth={1}
/>
))}
{/* Longitude lines */}
{[0, 1, 2, 3, 4, 5, 6].map(i => (
<line
key={`lng-${i}`}
x1={(i / 6) * mapWidth}
y1={0}
x2={(i / 6) * mapWidth}
y2={mapHeight}
stroke="#e0e0e0"
strokeWidth={1}
/>
))}
</svg>
{/* Vehicle markers */}
{trackableVehicles.map((vehicle) => {
const coords = getMapCoords(vehicle.gps.lat, vehicle.gps.lng);
const isSelected = vehicle.id === selectedVehicleId;
return (
<Box
key={vehicle.id}
pos="absolute"
style={{
left: coords.x - 15,
top: coords.y - 15,
width: 30,
height: 30,
cursor: 'pointer',
zIndex: isSelected ? 100 : 10,
}}
onClick={() => setSelectedVehicleId(vehicle.id)}
title={vehicle.registrationNumber}
>
<Box
pos="absolute"
inset={0}
style={{
backgroundColor: isSelected ? freightBrand.primary : '#3498db',
borderRadius: '50%',
border: isSelected ? `3px solid ${freightBrand.primaryDark}` : 'none',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: 'white',
fontSize: '16px',
boxShadow: isSelected ? `0 0 0 8px ${freightBrand.ring}` : 'none',
}}
>
<Navigation size={16} />
</Box>
</Box>
);
})}
{/* Map labels */}
<Box pos="absolute" bottom={8} left={8} style={{ zIndex: 50 }}>
<Text size="xs" c="dimmed">
📍 Addis Ababa, Ethiopia
</Text>
</Box>
</Box>
</Card.Section>
</Card>
</Grid.Col>
{/* Sidebar */}
<Grid.Col span={{ base: 12, lg: 4 }}>
<Stack gap="md">
{/* Vehicle Selector */}
<Card withBorder p="lg">
<Stack gap="md">
<Select
label="Track Vehicle"
placeholder="Select a vehicle to track"
data={vehicleOptions}
value={selectedVehicleId}
onChange={setSelectedVehicleId}
searchable
/>
{selectedVehicle && (
<Box p="md" style={{ backgroundColor: freightBrand.mutedBg, borderRadius: '8px' }}>
<Stack gap="sm">
<div>
<Text size="sm" c="dimmed">
Registration
</Text>
<Text fw={600}>{selectedVehicle.registrationNumber}</Text>
</div>
<div>
<Text size="sm" c="dimmed">
Vehicle
</Text>
<Text fw={600}>
{selectedVehicle.manufacturer} {selectedVehicle.model}
</Text>
</div>
<div>
<Text size="sm" c="dimmed">
Status
</Text>
<Badge color={selectedVehicle.status === 'ACTIVE' ? 'edr-green' : 'gray'}>
{selectedVehicle.status || 'Unknown'}
</Badge>
</div>
</Stack>
</Box>
)}
</Stack>
</Card>
{/* GPS Details */}
{selectedVehicle && (
<Card withBorder p="lg">
<Stack gap="md">
<Group justify="space-between">
<Text fw={500}>GPS Location</Text>
<Badge color="edr-green" leftSection={<Activity size={12} />}>
Live
</Badge>
</Group>
<SimpleGrid cols={2} spacing="sm">
<Box p="sm" style={{ backgroundColor: '#f8f9fa', borderRadius: '8px' }}>
<Text size="xs" c="dimmed">
Latitude
</Text>
<Text fw={600} size="sm">
{selectedVehicle.gps.lat.toFixed(4)}°
</Text>
</Box>
<Box p="sm" style={{ backgroundColor: '#f8f9fa', borderRadius: '8px' }}>
<Text size="xs" c="dimmed">
Longitude
</Text>
<Text fw={600} size="sm">
{selectedVehicle.gps.lng.toFixed(4)}°
</Text>
</Box>
<Box p="sm" style={{ backgroundColor: '#f8f9fa', borderRadius: '8px' }}>
<Text size="xs" c="dimmed">
Speed
</Text>
<Text fw={600} size="sm">
{selectedVehicle.gps.speed} km/h
</Text>
</Box>
<Box p="sm" style={{ backgroundColor: '#f8f9fa', borderRadius: '8px' }}>
<Text size="xs" c="dimmed">
Heading
</Text>
<Text fw={600} size="sm">
{selectedVehicle.gps.heading}°
</Text>
</Box>
</SimpleGrid>
<div>
<Text size="xs" c="dimmed">
Last Update
</Text>
<Text fw={500}>{selectedVehicle.gps.lastUpdate}</Text>
</div>
<Button color="edr-green" fullWidth leftSection={<MapPin size={16} />}>
View Full History
</Button>
</Stack>
</Card>
)}
{/* Tracked Vehicles List */}
<Card withBorder p="lg">
<Stack gap="md">
<Text fw={500}>Tracked Vehicles ({trackableVehicles.length})</Text>
<div style={{ maxHeight: '300px', overflowY: 'auto' }}>
<Table size="sm">
<Table.Tbody>
{trackableVehicles.map(v => (
<Table.Tr
key={v.id}
style={{
cursor: 'pointer',
backgroundColor: v.id === selectedVehicleId ? freightBrand.mutedBg : 'transparent',
}}
onClick={() => setSelectedVehicleId(v.id)}
>
<Table.Td>
<Stack gap={0}>
<Text size="sm" fw={600}>
{v.registrationNumber}
</Text>
<Text size="xs" c="dimmed">
{v.gps.speed} km/h
</Text>
</Stack>
</Table.Td>
<Table.Td align="right">
<Badge
color={v.status === 'ACTIVE' ? 'edr-green' : 'gray'}
size="sm"
>
{v.status || 'N/A'}
</Badge>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
</div>
</Stack>
</Card>
</Stack>
</Grid.Col>
</Grid>
</Stack>
</Container>
);
}

View File

@@ -0,0 +1,16 @@
/** Shared formatting helpers for the fleet-management pages. */
/** Format a number as Ethiopian Birr, e.g. 12345.6 → "ETB 12,346". */
export function formatETB(amount: number, fractionDigits = 0): string {
const value = Number.isFinite(amount) ? amount : 0;
return `ETB ${value.toLocaleString("en-US", {
minimumFractionDigits: fractionDigits,
maximumFractionDigits: fractionDigits,
})}`;
}
/** Safe percentage of `part` over `total`, rounded, 0 when total is 0. */
export function pct(part: number, total: number): number {
if (!total || !Number.isFinite(total) || !Number.isFinite(part)) return 0;
return Math.round((part / total) * 100);
}

View File

@@ -445,10 +445,10 @@ const FirstMilePage = () => {
});
const allocateMutation = useMutation({
mutationFn: (data) => apiClient.post(`/first-mile/${containerAllocationFirstMileId}/allocate-containers`, data),
mutationFn: (data) => api.post(`/first-mile/${containerAllocationFirstMileId}/allocate-containers`, data),
onSuccess: () => {
toast({ title: "Containers allocated" });
void qc.invalidateQueries({ queryKey: QUERY_KEYS.FIRST_MILE.detail(containerAllocationFirstMileId ?? "") });
void qc.invalidateQueries({ queryKey: QUERY_KEYS.FIRST_MILE.byId(containerAllocationFirstMileId ?? "") });
setContainerAllocationOpen(false);
setContainerAllocationFirstMileId(null);
},
@@ -785,9 +785,25 @@ const FirstMilePage = () => {
meta: { headerClassName, cellClassName },
cell: ({ row }) => {
const hasDistance = row.original.exactKm != null && row.original.exactKm > 0;
const isPaid = (row.original as any).paid;
if (!hasDistance) {
return <Text c="dimmed"></Text>;
}
if (isPaid) {
return (
<Group gap="xs" wrap="nowrap">
<UnstyledButton
onClick={() => openInvoice(row.original)}
c="blue"
fw={500}
style={{ textDecoration: "underline", cursor: "pointer" }}
>
#345
</UnstyledButton>
<Badge color="green" variant="light" size="sm">Paid</Badge>
</Group>
);
}
return (
<UnstyledButton
onClick={() => openInvoice(row.original)}

View File

@@ -473,7 +473,7 @@ const LastMilePage = () => {
api.post(`/last-mile/${activeId}/allocate-containers`, data),
onSuccess: () => {
toast({ title: "Containers allocated", variant: "default" });
void qc.invalidateQueries({ queryKey: QUERY_KEYS.LAST_MILE.detail(activeId ?? "") });
void qc.invalidateQueries({ queryKey: QUERY_KEYS.LAST_MILE.byId(activeId ?? "") });
closeAllocation();
},
onError: () => {
@@ -870,9 +870,25 @@ const LastMilePage = () => {
meta: { headerClassName, cellClassName },
cell: ({ row }) => {
const hasDistance = row.original.exactKm != null && row.original.exactKm > 0;
const isPaid = (row.original as any).paid;
if (!hasDistance) {
return <Text c="dimmed"></Text>;
}
if (isPaid) {
return (
<Group gap="xs" wrap="nowrap">
<UnstyledButton
onClick={() => openInvoice(row.original)}
c="blue"
fw={500}
style={{ textDecoration: "underline", cursor: "pointer" }}
>
#345
</UnstyledButton>
<Badge color="green" variant="light" size="sm">Paid</Badge>
</Group>
);
}
return (
<UnstyledButton
onClick={() => openInvoice(row.original)}

View File

@@ -51,7 +51,6 @@ interface CargoNode extends RuleEngineRecord {
cargoTypeName?: string;
code?: string;
parentGroupId?: string | null;
showFreeTextBox?: boolean;
requiresDirectorApproval?: boolean;
/** How this cargo is measured (PER_TON / PER_ITEM); null for groups/unset. */
unitOfMeasure?: string | null;
@@ -80,7 +79,6 @@ const FORM_FIELDS: FormFieldDef[] = [
{ label: "Per item (break-bulk)", value: "PER_ITEM" },
],
},
{ name: "showFreeTextBox", label: "Show free text box", type: "boolean" },
{ name: "requiresDirectorApproval", label: "Requires director approval", type: "boolean" },
{ name: "isActive", label: "Active", type: "boolean" },
];
@@ -474,19 +472,6 @@ function CargoRow({
</Badge>
</Tooltip>
) : null}
{node.showFreeTextBox ? (
<Tooltip label="Shows a free-text box on booking" withArrow>
<Badge
size="xs"
variant="light"
color="blue"
radius="sm"
leftSection={<FileText size={11} />}
>
Free text
</Badge>
</Tooltip>
) : null}
{node.unitOfMeasure ? (
<Tooltip label="How bookings measure this cargo" withArrow>
<Badge size="xs" variant="light" color="teal" radius="sm">

View File

@@ -11,6 +11,7 @@ export type ColumnFormat =
| "rateStatus"
| "date"
| "number"
| "currency"
| "entityLabel"
| "rateLabel";
@@ -36,6 +37,8 @@ export interface FormFieldDef {
placeholder?: string;
description?: string;
disabled?: boolean;
/** Trailing unit label shown inside the input (e.g. "USD" on a rate value). */
suffix?: string;
/** Hide this field when another field currently equals one of these values. */
hideWhen?: { field: string; equals: string[] };
/**
@@ -174,7 +177,6 @@ export const RULE_ENGINE_RESOURCES: RuleEngineResourceConfig[] = [
optional: true,
placeholder: "Select parent cargo type (optional)",
},
{ name: "showFreeTextBox", label: "Show free text box", type: "boolean" },
{ name: "requiresDirectorApproval", label: "Requires director approval", type: "boolean" },
{ name: "isActive", label: "Active", type: "boolean" },
],
@@ -402,7 +404,7 @@ export const RULE_ENGINE_RESOURCES: RuleEngineResourceConfig[] = [
columns: [
{ id: "appliesTo", header: "Applies to", accessorKey: "appliesTo", format: "code" },
{ id: "trigger", header: "Trigger", accessorKey: "trigger" },
{ id: "rateValue", header: "Value", accessorKey: "rateValue", format: "number" },
{ id: "rateValue", header: "Value", accessorKey: "rateValue", format: "currency" },
{ id: "rateUnit", header: "Unit", accessorKey: "rateUnit" },
{ id: "status", header: "Status", accessorKey: "status", format: "rateStatus" },
{ id: "effectiveFrom", header: "From", accessorKey: "effectiveFrom", format: "date" },
@@ -454,7 +456,7 @@ export const RULE_ENGINE_RESOURCES: RuleEngineResourceConfig[] = [
placeholder: "Select bulk commodity (optional)",
showWhen: { field: "appliesTo", equals: ["BULK", "INTERCITY"] },
},
{ name: "rateValue", label: "Rate value", type: "number", required: true },
{ name: "rateValue", label: "Rate value", type: "number", required: true, suffix: "USD" },
{ name: "rateUnit", label: "Rate unit", type: "select", required: true, options: RATE_UNITS },
{ name: "effectiveFrom", label: "Effective from", type: "date", required: true },
{ name: "effectiveTo", label: "Effective to", type: "date" },

View File

@@ -42,6 +42,7 @@ import {
} from "@/components/trainScheduling/scheduleVisuals";
import { useMutation, useQuery } from "@tanstack/react-query";
import { api } from "@/services/api";
import { formatRouteLabel } from "@/services/routes.service";
import { useToast } from "@/hooks/use-toast";
import type { TrainScheduleListItem } from "@/types/trainScheduling";
import { DataTable, DataTableFooter, usePagination } from "@edr/ui-common";
@@ -88,7 +89,9 @@ export default function TrainScheduleV2ListPage() {
const schedulesQuery = useQuery(
api.trainScheduling.scheduleList.queryOptions({ input: {} }),
);
const routesQuery = useQuery(api.routes.list.queryOptions());
const routesQuery = useQuery(
api.routes.list.queryOptions({ input: { status: "AVAILABLE" } }),
);
const locomotivesQuery = useQuery(
api.trainScheduling.availableLocomotives.queryOptions({
input: { routeId: routeId || undefined },
@@ -97,10 +100,7 @@ export default function TrainScheduleV2ListPage() {
const create = useMutation(api.trainScheduling.createSchedule.mutationOptions());
const cancel = useMutation(api.trainScheduling.cancelSchedule.mutationOptions());
const activeRoutes = useMemo(
() => (routesQuery.data ?? []).filter((r) => r.isActive),
[routesQuery.data],
);
const activeRoutes = useMemo(() => routesQuery.data ?? [], [routesQuery.data]);
const selectedRoute = activeRoutes.find((r) => r.id === routeId);
@@ -529,7 +529,7 @@ export default function TrainScheduleV2ListPage() {
<Select
label="Route"
placeholder="Select route"
data={activeRoutes.map((r) => ({ value: r.id, label: r.name }))}
data={activeRoutes.map((r) => ({ value: r.id, label: formatRouteLabel(r) }))}
value={routeId || null}
onChange={(v) => setRouteId(v ?? "")}
searchable

View File

@@ -15,7 +15,8 @@ import {
Text,
TextInput,
} from '@mantine/core';
import { Ban, CreditCard, DoorOpen, Download, Eye, Receipt, Search } from 'lucide-react';
import { Ban, CreditCard, DoorOpen, Download, ExternalLink, Eye, Receipt, Search } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { DataTable, type ColumnDef } from '@edr/ui-common';
import { PageContainer, PageHeader } from '@/components/page';
@@ -32,7 +33,7 @@ import {
type WarehouseInvoiceStatus,
} from '@/types/warehouse';
import { openPdfBlob } from '@/components/warehouses/pdf';
import { buildWarehouseExitPaperPdf, buildWarehouseInvoicePdf } from '@/components/warehouses/warehousePdf';
import { buildWarehouseExitPaperPdf } from '@/components/warehouses/warehousePdf';
import { extractErrorMessage } from '@/components/warehouses/options';
const STATUS_COLOR: Record<WarehouseInvoiceStatus, string> = {
@@ -156,6 +157,7 @@ export default function WarehouseInvoicesPage() {
function InvoiceDetailModal({ id, onClose }: { id: string | null; onClose: () => void }) {
const { toast } = useToast();
const navigate = useNavigate();
const { data: inv, isLoading } = useQuery(
api.warehouses.invoice.queryOptions({
input: { id: id ?? '' },
@@ -181,13 +183,33 @@ function InvoiceDetailModal({ id, onClose }: { id: string | null; onClose: () =>
}, [inv?.id, inv?.currency]);
const downloadInvoicePdf = async (invoice: WarehouseFeeInvoice) => {
const blob = buildWarehouseInvoicePdf(invoice, 'INVOICE');
openPdfBlob(blob, `warehouse-invoice-${invoice.invoiceNumber}.pdf`);
const pdfWindow = window.open('', '_blank');
try {
const { data } = await warehouseService.downloadInvoiceDocument(invoice.id);
openPdfBlob(data, `warehouse-invoice-${invoice.invoiceNumber}.pdf`, pdfWindow);
} catch (error) {
pdfWindow?.close();
toast({
variant: 'destructive',
title: 'Download failed',
description: extractErrorMessage(error),
});
}
};
const downloadReceiptPdf = async (invoice: WarehouseFeeInvoice) => {
const blob = buildWarehouseInvoicePdf(invoice, 'RECEIPT');
openPdfBlob(blob, `warehouse-receipt-${invoice.invoiceNumber}.pdf`);
const pdfWindow = window.open('', '_blank');
try {
const { data } = await warehouseService.downloadInvoiceReceipt(invoice.id);
openPdfBlob(data, `warehouse-receipt-${invoice.invoiceNumber}.pdf`, pdfWindow);
} catch (error) {
pdfWindow?.close();
toast({
variant: 'destructive',
title: 'Download failed',
description: extractErrorMessage(error),
});
}
};
const getExitPaperContext = async (invoice: WarehouseFeeInvoice) => {
@@ -427,6 +449,20 @@ function InvoiceDetailModal({ id, onClose }: { id: string | null; onClose: () =>
)}
<Group justify="flex-end" mt="sm">
{inv.bookingId && (
<Button
variant="subtle"
color="gray"
leftSection={<ExternalLink size={16} />}
onClick={() =>
navigate(
`/dashboard/booking-requests/${inv.bookingId}#warehouse-payments`,
)
}
>
View booking
</Button>
)}
<Button
variant="light"
color="gray"

View File

@@ -1143,8 +1143,14 @@ export const api = {
},
routes: {
list: endpoint<void, RouteRecord[]>("routes", "list", () =>
routesService.getAll().then((r) => r.data),
list: endpoint<{ status?: import("./routes.service").RouteStatus } | void, RouteRecord[]>(
"routes",
"list",
(input) =>
routesService
.getAll(input?.status ? { status: input.status } : undefined)
.then((r) => r.data),
(input) => ["routes", input?.status ?? "all"],
),
yards: endpoint<void, YardRef[]>(

View File

@@ -301,6 +301,105 @@ export const bookingsService = {
governmentExpedite: (id: string) =>
postBooking<BookingDetail>(B.GOVERNMENT_EXPEDITE(id)),
getClearance: async (id: string): Promise<Freight.ClearanceView> => {
const response = await client.get(B.CLEARANCE(id));
return unwrap(response.data) as Freight.ClearanceView;
},
uploadDeclaration: async (
id: string,
files: Record<string, File | null>,
): Promise<BookingDetail> => {
const form = new FormData();
for (const [key, file] of Object.entries(files)) {
if (file) form.append(key, file);
}
const response = await client.post(B.CLEARANCE_DECLARATION(id), form, {
headers: { "Content-Type": "multipart/form-data" },
});
return unwrap(response.data) as BookingDetail;
},
adviseDuty: async (
id: string,
payload: {
dutyRequired: boolean;
amount?: number;
currency?: string;
declarationSerial?: string;
attachment?: File | null;
},
): Promise<BookingDetail> => {
const form = new FormData();
form.append("dutyRequired", String(payload.dutyRequired));
if (payload.amount != null) form.append("amount", String(payload.amount));
if (payload.currency) form.append("currency", payload.currency);
if (payload.declarationSerial) {
form.append("declarationSerial", payload.declarationSerial);
}
if (payload.attachment) form.append("attachment", payload.attachment);
const response = await client.post(B.CLEARANCE_DUTY(id), form, {
headers: { "Content-Type": "multipart/form-data" },
});
return unwrap(response.data) as BookingDetail;
},
finalizePreClearance: (id: string) =>
postBooking<BookingDetail>(B.CLEARANCE_FINALIZE_PRE(id)),
uploadTransitPermit: async (
id: string,
files: Record<string, File | null>,
): Promise<BookingDetail> => {
const form = new FormData();
for (const [key, file] of Object.entries(files)) {
if (file) form.append(key, file);
}
const response = await client.post(B.CLEARANCE_TRANSIT_PERMIT(id), form, {
headers: { "Content-Type": "multipart/form-data" },
});
return unwrap(response.data) as BookingDetail;
},
uploadDeliveryOrder: async (id: string, file: File): Promise<BookingDetail> => {
const form = new FormData();
form.append("file", file);
const response = await client.post(B.CLEARANCE_DELIVERY_ORDER(id), form, {
headers: { "Content-Type": "multipart/form-data" },
});
return unwrap(response.data) as BookingDetail;
},
uploadReleaseOrder: async (
id: string,
file: File,
vesselDepartureDate: string,
): Promise<{ hold?: boolean; holdReason?: string }> => {
const form = new FormData();
form.append("file", file);
form.append("vesselDepartureDate", vesselDepartureDate);
const response = await client.post(B.CLEARANCE_RELEASE_ORDER(id), form, {
headers: { "Content-Type": "multipart/form-data" },
});
return unwrap(response.data) as { hold?: boolean; holdReason?: string };
},
requestRoAmendment: (id: string, note?: string) =>
postBooking<BookingDetail>(B.CLEARANCE_RO_AMENDMENT(id), { note }),
confirmExportRelease: (id: string) =>
postBooking<BookingDetail>(B.CLEARANCE_EXPORT_RELEASE(id), {}),
getEtClearanceQueue: async (): Promise<BookingDetail[]> => {
const response = await client.get(B.CLEARANCE_ET_QUEUE);
return (unwrap(response.data) ?? []) as BookingDetail[];
},
getDjClearanceQueue: async (): Promise<BookingDetail[]> => {
const response = await client.get(B.CLEARANCE_DJ_QUEUE);
return (unwrap(response.data) ?? []) as BookingDetail[];
},
};
async function ensurePdfBlob(blob: Blob): Promise<Blob> {

View File

@@ -159,6 +159,13 @@ export const contractsService = {
return unwrap(response.data) as ContractView;
},
downloadContractDocument: async (id: string): Promise<Blob> => {
const response = await client.get(C.CONTRACT_DOCUMENT(id), {
responseType: "blob",
});
return response.data as Blob;
},
signContract: (id: string, payload: SignContractPayload) =>
postContract<Freight.IContract>(C.CONTRACT_SIGN(id), payload),
@@ -200,6 +207,132 @@ export const contractsService = {
finalizeClearance: (id: string) =>
postContract<Freight.IContract>(C.CLEARANCE_FINALIZE(id)),
getEtClearanceQueue: async (): Promise<PaginatedContracts> => {
const response = await client.get<PaginatedContracts>(C.CLEARANCE_ET_QUEUE);
const data = unwrap(response.data);
return {
items: (data.items ?? []) as Freight.IContract[],
total: data.total ?? 0,
};
},
getDjClearanceQueue: async (): Promise<PaginatedContracts> => {
const response = await client.get<PaginatedContracts>(C.CLEARANCE_DJ_QUEUE);
const data = unwrap(response.data);
return {
items: (data.items ?? []) as Freight.IContract[],
total: data.total ?? 0,
};
},
uploadDeclaration: async (
id: string,
files: Record<string, File | null>,
): Promise<Freight.IContract> => {
const form = new FormData();
for (const [key, file] of Object.entries(files)) {
if (file) form.append(key, file);
}
const response = await client.post(C.CLEARANCE_DECLARATION(id), form, {
headers: { "Content-Type": "multipart/form-data" },
});
return unwrap(response.data) as Freight.IContract;
},
adviseContractDuty: async (
id: string,
payload: {
dutyRequired: boolean;
amount?: number;
currency?: string;
declarationSerial?: string;
attachment?: File | null;
},
): Promise<Freight.IContract> => {
const form = new FormData();
form.append("dutyRequired", String(payload.dutyRequired));
if (payload.amount != null) form.append("amount", String(payload.amount));
if (payload.currency) form.append("currency", payload.currency);
if (payload.declarationSerial) {
form.append("declarationSerial", payload.declarationSerial);
}
if (payload.attachment) form.append("attachment", payload.attachment);
const response = await client.post(C.CLEARANCE_DUTY(id), form, {
headers: { "Content-Type": "multipart/form-data" },
});
return unwrap(response.data) as Freight.IContract;
},
finalizePreClearance: (id: string) =>
postContract<Freight.IContract>(C.CLEARANCE_FINALIZE_PRE(id)),
uploadContractTransitPermit: async (
id: string,
files: Record<string, File | null>,
): Promise<Freight.IContract> => {
const form = new FormData();
for (const [key, file] of Object.entries(files)) {
if (file) form.append(key, file);
}
const response = await client.post(C.CLEARANCE_TRANSIT_PERMIT(id), form, {
headers: { "Content-Type": "multipart/form-data" },
});
return unwrap(response.data) as Freight.IContract;
},
uploadDeliveryOrder: async (
id: string,
file: File,
): Promise<Freight.IContract> => {
const form = new FormData();
form.append("file", file);
const response = await client.post(C.CLEARANCE_DELIVERY_ORDER(id), form, {
headers: { "Content-Type": "multipart/form-data" },
});
return unwrap(response.data) as Freight.IContract;
},
uploadReleaseOrder: async (
id: string,
file: File,
vesselDepartureDate: string,
): Promise<{ contract: Freight.IContract; hold: boolean; holdReason?: string }> => {
const form = new FormData();
form.append("file", file);
form.append("vesselDepartureDate", vesselDepartureDate);
const response = await client.post(C.CLEARANCE_RELEASE_ORDER(id), form, {
headers: { "Content-Type": "multipart/form-data" },
});
return unwrap(response.data) as {
contract: Freight.IContract;
hold: boolean;
holdReason?: string;
};
},
requestRoAmendment: (id: string, note?: string) =>
postContract<Freight.IContract>(C.CLEARANCE_RO_AMENDMENT(id), { note }),
confirmExportRelease: (id: string) =>
postContract<Freight.IContract>(C.CLEARANCE_EXPORT_RELEASE(id)),
finalizeExportClearance: (id: string) =>
postContract<Freight.IContract>(C.CLEARANCE_FINALIZE_EXPORT(id)),
uploadTransportDocument: async (
bookingId: string,
files: Record<string, File | null>,
) => {
const form = new FormData();
for (const [key, file] of Object.entries(files)) {
if (file) form.append(key, file);
}
const response = await client.post(C.BOOKING_TRANSPORT_DOCUMENT(bookingId), form, {
headers: { "Content-Type": "multipart/form-data" },
});
return unwrap(response.data);
},
// ── Path A self-clearance (Operations review) ──
getOpsClearanceQueue: async (): Promise<PaginatedContracts> => {
const response = await client.get<PaginatedContracts>(

View File

@@ -2,6 +2,8 @@ import { api as apiClient } from '../auth/http';
import { URL_CONSTANTS } from '@/constants/URLS';
export type RouteStatus = 'AVAILABLE' | 'MAINTENANCE' | 'DAMAGED' | 'STOP_WORKING';
export interface YardRef {
id: string;
code: string;
@@ -14,32 +16,54 @@ export interface RouteMilestone {
routeId: string;
yardId: string;
sequenceNo: number;
distanceKm?: number | null;
yard?: YardRef | null;
}
export interface RouteRecord {
id: string;
name: string;
status: RouteStatus;
originYardId: string;
destinationYardId: string;
isActive: boolean;
originYard?: YardRef | null;
destinationYard?: YardRef | null;
milestones?: RouteMilestone[];
}
export interface SaveRoutePayload {
name: string;
milestones: Array<{ yardId: string }>;
isActive?: boolean;
milestones: Array<{ yardId: string; distanceKm?: number }>;
status?: RouteStatus;
}
export function formatRouteLabel(route: RouteRecord): string {
const origin =
route.originYard?.code ?? route.originYard?.label ?? 'Origin';
const dest =
route.destinationYard?.code ?? route.destinationYard?.label ?? 'Destination';
return `${origin}${dest}`;
}
export function totalRouteDistanceKm(route: RouteRecord): number {
return (route.milestones ?? []).reduce(
(sum, m) => sum + Number(m.distanceKm ?? 0),
0,
);
}
export const ROUTE_STATUS_OPTIONS: Array<{ value: RouteStatus; label: string }> = [
{ value: 'AVAILABLE', label: 'Available' },
{ value: 'MAINTENANCE', label: 'Maintenance' },
{ value: 'DAMAGED', label: 'Damaged' },
{ value: 'STOP_WORKING', label: 'Stop working' },
];
interface YardListResponse {
data: YardRef[];
}
export const routesService = {
getAll: () => apiClient.get<RouteRecord[]>(URL_CONSTANTS.ROUTES.BASE),
getAll: (params?: { status?: RouteStatus; search?: string }) =>
apiClient.get<RouteRecord[]>(URL_CONSTANTS.ROUTES.BASE, { params }),
getById: (id: string) => apiClient.get<RouteRecord>(URL_CONSTANTS.ROUTES.BY_ID(id)),
create: (data: SaveRoutePayload) => apiClient.post(URL_CONSTANTS.ROUTES.BASE, data),
update: (id: string, data: Partial<SaveRoutePayload>) =>

View File

@@ -177,6 +177,7 @@ export interface BookingDetail {
equipmentReturn?: string;
customsClearingEnabled?: boolean;
customsClearingAgent?: string | null;
contractKind?: "ONE_TIME" | "GENERAL" | null;
contractSummary?: string | null;
latestChangeRequestNote?: string | null;
nextStep?: BookingNextStep | null;