Merge freight/develop into feature/trains-management

This commit is contained in:
hagiye
2026-06-05 10:21:39 +03:00
179 changed files with 12700 additions and 3160 deletions

View File

@@ -0,0 +1,218 @@
import { useCallback, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
ArrowLeft,
Download,
FileSignature,
Loader2,
Printer,
} from "lucide-react";
import toast from "react-hot-toast";
import Breadcrumbs from "@/components/ui/Breadcrumbs";
import { ContractSignaturePad } from "@/components/bookings/ContractSignaturePad";
import { bookingSurface } from "@/components/bookings/booking-ui.styles";
import { QUERY_KEYS } from "@/constants/QUERY_KEYS";
import { invalidateBookingDetail } from "@/utils/queryInvalidation";
import {
bookingsService,
type ContractView,
type SignContractPayload,
} from "@/services/bookings.service";
import { cn } from "@/lib/utils";
import {
Button,
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
Input,
Label,
} from "@edr/ui-common";
export default function BookingContractPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const qc = useQueryClient();
const [signOpen, setSignOpen] = useState(false);
const [signerName, setSignerName] = useState("");
const [signatureData, setSignatureData] = useState<string | null>(null);
const { data, isLoading, isError } = useQuery({
queryKey: [...QUERY_KEYS.BOOKINGS.byId(id ?? ""), "contract-view"],
queryFn: () => bookingsService.getContractView(id!),
enabled: Boolean(id),
});
const signRole: "CUSTOMER" | "STAFF" | null = data?.canSignCustomer
? "CUSTOMER"
: data?.canSignStaff
? "STAFF"
: null;
const signMutation = useMutation({
mutationFn: (payload: SignContractPayload) =>
bookingsService.signContract(id!, payload),
onSuccess: async () => {
toast.success("Signature recorded");
setSignOpen(false);
await invalidateBookingDetail(qc, id!);
qc.invalidateQueries({
queryKey: [...QUERY_KEYS.BOOKINGS.byId(id ?? ""), "contract-view"],
});
},
onError: () => toast.error("Failed to sign contract"),
});
const downloadPdf = useCallback(async () => {
if (!id) return;
try {
const blob = await bookingsService.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("Contract PDF not available. Ask staff to generate it first.");
}
}, [id, data?.reference]);
const handlePrint = () => window.print();
const openSign = () => {
setSignerName("");
setSignatureData(null);
setSignOpen(true);
};
const confirmSign = () => {
if (!signRole || !signatureData || !signerName.trim()) return;
signMutation.mutate({
role: signRole,
signatureImageBase64: signatureData,
signerDisplayName: signerName.trim(),
consentText: "I agree to the terms of this contract.",
});
};
if (isLoading) {
return (
<div className="flex min-h-[40vh] items-center justify-center">
<Loader2 className="size-8 animate-spin text-primary" />
</div>
);
}
if (isError || !data) {
return (
<div className={bookingSurface.pageInner}>
<p className="text-muted-foreground">Could not load contract.</p>
<Button variant="outline" className="mt-4" onClick={() => navigate(-1)}>
Go back
</Button>
</div>
);
}
return (
<div className={bookingSurface.page}>
<div className={cn(bookingSurface.pageInner, "print:p-0")}>
<div className="print:hidden">
<Breadcrumbs
items={[
{ label: "Booking requests", href: "/dashboard/booking-requests" },
{
label: data.reference,
href: `/dashboard/booking-requests/${id}`,
},
{ label: "Contract" },
]}
/>
</div>
<div className="sticky top-0 z-10 mb-6 flex flex-wrap items-center justify-between gap-3 rounded-xl border bg-background/95 p-4 shadow-sm backdrop-blur print:hidden">
<Button variant="ghost" size="sm" className="gap-2" onClick={() => navigate(-1)}>
<ArrowLeft className="size-4" />
Back
</Button>
<div className="flex flex-wrap gap-2">
<Button variant="outline" size="sm" className="gap-2" onClick={handlePrint}>
<Printer className="size-4" />
Print
</Button>
<Button variant="outline" size="sm" className="gap-2" onClick={downloadPdf}>
<Download className="size-4" />
Download PDF
</Button>
{signRole && (
<Button size="sm" className="gap-2" onClick={openSign}>
<FileSignature className="size-4" />
Sign as {signRole === "CUSTOMER" ? "Customer" : "Staff"}
</Button>
)}
</div>
</div>
<article
className="contract-document mx-auto max-w-[210mm] rounded-xl border bg-white p-8 shadow-sm print:border-0 print:shadow-none"
dangerouslySetInnerHTML={{ __html: extractBodyHtml(data.html) }}
/>
<Dialog open={signOpen} onOpenChange={setSignOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>
{signRole === "CUSTOMER" ? "Customer signature" : "Staff signature"}
</DialogTitle>
<DialogDescription>
Sign to execute the contract for {data.reference}.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="signerName">Full name</Label>
<Input
id="signerName"
value={signerName}
onChange={(e) => setSignerName(e.target.value)}
placeholder="As shown on the contract"
/>
</div>
<ContractSignaturePad onChange={setSignatureData} />
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setSignOpen(false)}>
Cancel
</Button>
<Button
disabled={
signMutation.isPending ||
!signatureData ||
!signerName.trim()
}
onClick={confirmSign}
>
{signMutation.isPending ? (
<Loader2 className="size-4 animate-spin" />
) : (
"Confirm signature"
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</div>
);
}
/** Render server HTML body content inside our layout wrapper. */
function extractBodyHtml(fullHtml: string): string {
const match = fullHtml.match(/<body[^>]*>([\s\S]*)<\/body>/i);
return match ? match[1] : fullHtml;
}

View File

@@ -5,24 +5,33 @@ import {
ArrowRight,
Calendar,
Clock,
Eye,
FileText,
Filter,
MoreHorizontal,
Inbox,
LayoutList,
Package,
RefreshCw,
Search,
ShieldCheck,
Train,
User,
X,
} from "lucide-react";
import Breadcrumbs from "@/components/ui/Breadcrumbs";
import { cn } from "@/lib/utils";
import { BookingPriorityBadge } from "@/components/bookings/BookingPriorityBadge";
import {
getBookingRequests,
BOOKING_STATUSES,
type BookingRequest,
} from "./booking-requests.mock";
BookingStatusTabs,
type BookingStatusTabKey,
} from "@/components/bookings/BookingStatusTabs";
import { BookingStatGrid } from "@/components/bookings/BookingStatGrid";
import { BookingStatusBadge } from "@/components/bookings/BookingStatusBadge";
import { BookingActionsMenu } from "@/components/bookings/BookingActionsMenu";
import { BookingTableEmpty } from "@/components/bookings/BookingTableEmpty";
import { bookingInput, bookingSurface } from "@/components/bookings/booking-ui.styles";
import { BOOKING_LIST_TABS } from "@/features/bookings/booking-status.config";
import { toBookingListRow } from "@/features/bookings/mapBookingListRow";
import { useBookingList } from "@/hooks/bookings/useBookings";
import type { BookingListFilter } from "@/services/bookings.service";
import type { BookingListRow } from "@/types/booking";
import { cn } from "@/lib/utils";
import {
DataTable,
DataTableFooter,
@@ -30,184 +39,70 @@ import {
usePagination,
Badge,
Button,
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
Input,
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
Separator,
} from "@edr/ui-common";
const STATUS_STYLES: Record<string, { label: string; color: string }> = {
DRAFT: {
label: "Draft",
color: "bg-slate-100 text-slate-700 border-slate-300",
},
RFQ_SUBMITTED: {
label: "RFQ Submitted",
color: "bg-amber-50 text-amber-700 border-amber-200",
},
QUOTATION_SENT: {
label: "Quotation Sent",
color: "bg-sky-50 text-sky-700 border-sky-200",
},
QUOTATION_APPROVED: {
label: "Quotation Approved",
color: "bg-emerald-50 text-emerald-700 border-emerald-200",
},
QUOTATION_REJECTED: {
label: "Quotation Rejected",
color: "bg-red-50 text-red-700 border-red-200",
},
PENDING_APPROVAL: {
label: "Pending Approval",
color: "bg-amber-50 text-amber-700 border-amber-200",
},
APPROVED: {
label: "Approved",
color: "bg-emerald-50 text-emerald-700 border-emerald-200",
},
SIGNED_CUSTOMER: {
label: "Customer Signed",
color: "bg-sky-50 text-sky-700 border-sky-200",
},
FULLY_EXECUTED: {
label: "Fully Executed",
color: "bg-indigo-50 text-indigo-700 border-indigo-200",
},
PAID: {
label: "Paid",
color: "bg-emerald-50 text-emerald-700 border-emerald-200",
},
IN_TRANSIT: {
label: "In Transit",
color: "bg-sky-50 text-sky-700 border-sky-200",
},
COMPLETED: {
label: "Completed",
color: "bg-indigo-50 text-indigo-700 border-indigo-200",
},
CANCELLED: {
label: "Cancelled",
color: "bg-red-50 text-red-700 border-red-200",
},
PENDING_CONSOLIDATION: {
label: "Pending Consolidation",
color: "bg-amber-50 text-amber-700 border-amber-200",
},
CONSOLIDATED: {
label: "Consolidated",
color: "bg-indigo-50 text-indigo-700 border-indigo-200",
},
};
function StatusBadge({ status }: { status: string }) {
const style = STATUS_STYLES[status] ?? {
label: status,
color: "bg-muted text-muted-foreground border-border",
};
return (
<Badge
variant="outline"
className={cn(
"px-2 py-0.5 font-bold uppercase tracking-wider text-[9px]",
style.color,
)}
>
{style.label}
</Badge>
);
}
function PriorityBadge({ score }: { score: number }) {
if (score >= 3) {
return (
<span className="rounded-full bg-red-50 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-red-700">
Urgent
</span>
);
}
if (score === 2) {
return (
<span className="rounded-full bg-amber-50 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-amber-700">
High
</span>
);
}
return (
<span className="rounded-full bg-slate-100 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-slate-600">
Normal
</span>
);
function getStatusForTab(tab: BookingStatusTabKey): string | undefined {
const match = BOOKING_LIST_TABS.find((t) => t.key === tab);
return match?.status ?? undefined;
}
export default function BookingRequestsPage() {
const navigate = useNavigate();
const { pagination, setPagination } = usePagination({ pageSize: 10 });
const [query, setQuery] = useState("");
const [statusFilter, setStatusFilter] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState<BookingStatusTabKey>("SUBMITTED");
const bookingRequests = useMemo(() => getBookingRequests(), []);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
return bookingRequests.filter((b) => {
if (
q &&
!b.reference.toLowerCase().includes(q) &&
!b.customer.toLowerCase().includes(q)
) {
return false;
}
if (statusFilter && b.status !== statusFilter) {
return false;
}
return true;
});
}, [bookingRequests, query, statusFilter]);
const total = filtered.length;
const pageCount = Math.max(1, Math.ceil(total / pagination.pageSize));
const start = pagination.pageIndex * pagination.pageSize;
const end = Math.min(start + pagination.pageSize, total);
const paginatedData = useMemo(
() => filtered.slice(start, end),
[start, end, filtered],
const filter: BookingListFilter = useMemo(
() => ({
page: pagination.pageIndex + 1,
pageSize: pagination.pageSize,
sortBy: "createdAt",
sortOrder: "DESC",
...(getStatusForTab(activeTab) ? { status: getStatusForTab(activeTab) } : {}),
}),
[pagination.pageIndex, pagination.pageSize, activeTab],
);
const pendingCount = bookingRequests.filter(
(b) => b.status === "PENDING_APPROVAL" || b.status === "RFQ_SUBMITTED",
).length;
const activeCount = bookingRequests.filter(
(b) => !["COMPLETED", "CANCELLED"].includes(b.status),
).length;
const urgentCount = bookingRequests.filter(
(b) => b.priorityScore >= 3,
).length;
const { data, isLoading, isError, refetch, isFetching } = useBookingList(filter);
const columns: ColumnDef<BookingRequest>[] = [
const rows = useMemo(() => {
const items = (data?.items ?? []).map(toBookingListRow);
const q = query.trim().toLowerCase();
if (!q) return items;
return items.filter(
(b) =>
b.reference.toLowerCase().includes(q) ||
b.customerLabel.toLowerCase().includes(q),
);
}, [data?.items, query]);
const total = data?.total ?? 0;
const pageCount = Math.max(1, Math.ceil(total / pagination.pageSize));
const hasSearch = query.trim().length > 0;
const showEmpty = !isLoading && !isError && rows.length === 0;
const pendingCount = rows.filter(
(b) => b.status === "SUBMITTED" || b.status === "PENDING_APPROVAL",
).length;
const urgentCount = rows.filter((b) => b.priorityScore >= 1000).length;
const columns: ColumnDef<BookingListRow>[] = [
{
id: "booking",
header: "Booking",
header: () => <span className="text-xs font-semibold uppercase tracking-wider">Booking</span>,
cell: ({ row }) => {
const b = row.original;
return (
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary text-primary-foreground">
<Package className="h-5 w-5" />
<div className="flex items-center gap-3 py-1">
<div className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-primary to-primary/80 text-primary-foreground shadow-sm">
<Package className="size-4" />
</div>
<div>
<p className="font-medium text-slate-900">{b.reference}</p>
<p className="flex items-center gap-1 text-xs text-slate-500">
<User className="h-3 w-3" />
{b.customer}
<div className="min-w-0">
<p className="truncate font-semibold text-foreground">{b.reference}</p>
<p className="mt-0.5 flex items-center gap-1 truncate text-xs text-muted-foreground">
<User className="size-3 shrink-0" />
{b.customerLabel}
</p>
</div>
</div>
@@ -216,264 +111,225 @@ export default function BookingRequestsPage() {
},
{
id: "route",
header: "Route",
header: () => <span className="text-xs font-semibold uppercase tracking-wider">Route</span>,
cell: ({ row }) => {
const b = row.original;
return (
<div className="flex flex-col gap-0.5">
<div className="flex items-center gap-1 text-xs font-medium text-slate-700">
<span>{b.originYard}</span>
<ArrowRight className="h-3 w-3 text-slate-400" />
<span>{b.destinationYard}</span>
<div className="space-y-1 py-1">
<div className="flex items-center gap-1.5 text-sm font-medium text-foreground">
<span className="max-w-[8rem] truncate">{b.originLabel}</span>
<ArrowRight className="size-3.5 shrink-0 text-muted-foreground" />
<span className="max-w-[8rem] truncate">{b.destinationLabel}</span>
</div>
<div className="flex gap-1.5">
<Badge variant="outline" className="h-5 px-1.5 text-[10px] font-semibold uppercase">
{b.tradeDirection}
</Badge>
<Badge variant="secondary" className="h-5 px-1.5 text-[10px] font-medium">
{b.freightType}
</Badge>
</div>
<span className="text-[10px] uppercase tracking-wide text-slate-500">
{b.tradeDirection}
</span>
</div>
);
},
},
{
id: "status",
header: "Status",
cell: ({ row }) => <StatusBadge status={row.original.status} />,
header: () => <span className="text-xs font-semibold uppercase tracking-wider">Status</span>,
cell: ({ row }) => <BookingStatusBadge status={row.original.status} />,
},
{
id: "service",
header: "Service",
cell: ({ row }) => {
const b = row.original;
return (
<div className="flex flex-col gap-0.5">
<span className="text-xs font-medium text-slate-700">
{b.serviceType.replace(/_/g, " ")}
</span>
<span className="flex items-center gap-1 text-[10px] text-slate-500">
<Calendar className="h-3 w-3" />
{b.scheduledDate}
</span>
</div>
);
},
},
{
id: "cargo",
header: "Cargo",
cell: ({ row }) => {
const b = row.original;
return (
<div className="flex flex-col gap-0.5">
<span className="text-xs font-medium text-slate-700">
{b.cargoType}
</span>
<span className="text-[10px] text-slate-500">
{b.cargoTotalWeightVgm}T
</span>
</div>
);
},
id: "scheduled",
header: () => <span className="text-xs font-semibold uppercase tracking-wider">Scheduled</span>,
cell: ({ row }) => (
<span className="inline-flex items-center gap-1.5 text-sm text-muted-foreground">
<Calendar className="size-3.5" />
{row.original.scheduledDate}
</span>
),
},
{
id: "priority",
header: "Priority",
cell: ({ row }) => <PriorityBadge score={row.original.priorityScore} />,
header: () => <span className="text-xs font-semibold uppercase tracking-wider">Priority</span>,
cell: ({ row }) => (
<BookingPriorityBadge score={row.original.priorityScore} />
),
},
{
id: "amount",
header: "Amount",
header: () => (
<span className="text-xs font-semibold uppercase tracking-wider">Amount</span>
),
cell: ({ row }) => {
const b = row.original;
return (
<span className="font-mono text-xs font-semibold text-slate-900">
{b.paymentCurrency} {b.totalAmount.toLocaleString()}
<span className="font-mono text-sm font-semibold tabular-nums text-foreground">
{b.paymentCurrency}{" "}
{b.totalAmount.toLocaleString(undefined, {
minimumFractionDigits: 2,
})}
</span>
);
},
},
{
id: "actions",
size: 40,
cell: ({ row }) => {
const b = row.original;
return (
<div
className="flex justify-end"
onClick={(e) => e.stopPropagation()}
>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="icon">
<MoreHorizontal />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onSelect={() =>
navigate(`/dashboard/booking-requests/${b.id}`)
}
>
<Eye />
View Details
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
variant="destructive"
onSelect={() =>
navigate(`/dashboard/booking-requests/${b.id}`)
}
>
<AlertCircle />
Review
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
);
},
size: 140,
header: () => (
<span className="text-xs font-semibold uppercase tracking-wider">
Actions
</span>
),
cell: ({ row }) => (
<BookingActionsMenu row={row.original} variant="table" />
),
},
];
return (
<div className="min-h-screen p-6">
<div className="space-y-6">
<Breadcrumbs items={[{ label: "Booking Requests" }]} />
<div className={bookingSurface.page}>
<div className={bookingSurface.pageInner}>
<Breadcrumbs items={[{ label: "Operations" }, { label: "Booking requests" }]} />
<Card className="flex-row justify-between p-6">
<div>
<h1 className="text-3xl font-bold tracking-tight text-slate-900">
Booking Requests
</h1>
<p className="mt-1 text-sm text-secondary-foreground">
Review, approve, or reject customer booking requests across the
freight network.
</p>
<div className={bookingSurface.hero}>
<div className={bookingSurface.heroGlow} />
<div className="relative flex flex-col gap-6 p-6 sm:flex-row sm:items-center sm:justify-between sm:p-8">
<div className="flex items-start gap-4">
<div className="flex size-14 shrink-0 items-center justify-center rounded-2xl bg-primary text-primary-foreground shadow-lg shadow-primary/25">
<Inbox className="size-7" />
</div>
<div>
<h1 className="text-2xl font-bold tracking-tight text-foreground sm:text-3xl">
Booking requests
</h1>
<p className="mt-1.5 max-w-xl text-sm leading-relaxed text-muted-foreground">
Track bookings from submission through payment and operations.
</p>
</div>
</div>
<div className="flex shrink-0 items-center gap-2">
<Button
variant="outline"
size="sm"
className="gap-2"
disabled={isFetching}
onClick={() => refetch()}
>
<RefreshCw
className={cn("size-4", isFetching && "animate-spin")}
/>
Refresh
</Button>
</div>
</div>
</div>
<div className="flex flex-col items-stretch gap-3 sm:flex-row sm:items-center">
<div className="relative w-full sm:w-72">
<Search className="pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
<BookingStatGrid
items={[
{
label: "In queue",
value: total,
hint: "Total matching filter",
icon: LayoutList,
},
{
label: "On this page",
value: rows.length,
hint: "Current view",
icon: FileText,
},
{
label: "Needs action",
value: pendingCount,
hint: "Submitted or pending approval",
icon: Clock,
accent: "amber",
},
{
label: "Urgent",
value: urgentCount,
hint: "High priority score",
icon: AlertCircle,
accent: urgentCount > 0 ? "rose" : "default",
},
]}
/>
<BookingStatusTabs
active={activeTab}
onChange={(tab) => {
setActiveTab(tab);
setPagination({ pageIndex: 0, pageSize: pagination.pageSize });
}}
counts={{
[activeTab]: total,
}}
/>
<div className={bookingSurface.panel}>
<div className={bookingSurface.panelToolbar}>
<div className="relative min-w-[12rem] flex-1 sm:max-w-sm">
<Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
type="search"
value={query}
onChange={(e) => {
setQuery(e.target.value);
setPagination({
pageIndex: 0,
pageSize: pagination.pageSize,
});
}}
placeholder="Search reference or customer..."
className="pl-8!"
onChange={(e) => setQuery(e.target.value)}
placeholder="Search reference or customer…"
className={bookingInput.search}
/>
{query && (
<button
type="button"
className="absolute right-2 top-1/2 -translate-y-1/2 rounded-md p-1 text-muted-foreground hover:bg-muted hover:text-foreground"
onClick={() => setQuery("")}
aria-label="Clear search"
>
<X className="size-3.5" />
</button>
)}
</div>
<div className="flex flex-wrap items-center gap-2">
<span className="hidden text-xs text-muted-foreground sm:inline">
{total} record{total !== 1 ? "s" : ""}
</span>
</div>
</div>
</Card>
<div className="grid gap-4 md:grid-cols-4">
<StatCard
label="Total Requests"
value={bookingRequests.length}
icon={<FileText />}
/>
<StatCard
label="Pending Action"
value={pendingCount}
icon={<Clock />}
/>
<StatCard label="Active" value={activeCount} icon={<Train />} />
<StatCard label="Urgent" value={urgentCount} icon={<AlertCircle />} />
</div>
<Card className="gap-0">
<CardHeader className="flex flex-row items-center justify-between border-b">
<div>
<CardTitle>All Booking Requests</CardTitle>
<CardDescription>
{total} request{total !== 1 ? "s" : ""} found
</CardDescription>
</div>
<div className="flex items-center gap-2">
{statusFilter && (
<Button
variant="ghost"
size="sm"
onClick={() => setStatusFilter(null)}
>
Clear filter
</Button>
)}
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button variant="secondary" size="sm">
<Filter />
{statusFilter
? (STATUS_STYLES[statusFilter]?.label ?? "Filter")
: "Filter"}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{BOOKING_STATUSES.map((s) => (
<DropdownMenuItem
key={s}
onSelect={() => setStatusFilter(s)}
>
{STATUS_STYLES[s]?.label ?? s}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</div>
</CardHeader>
<CardContent className="px-0">
<DataTable
columns={columns}
data={paginatedData}
status="success"
onRowClick={(row) =>
navigate(`/dashboard/booking-requests/${row.id}`)
}
pagination={{
pageIndex: pagination.pageIndex,
pageSize: pagination.pageSize,
pageCount,
totalCount: total,
}}
tableOptions={{
state: { pagination },
onPaginationChange: setPagination,
}}
containerClassName="border-b shadow-none"
footer={DataTableFooter}
{showEmpty ? (
<BookingTableEmpty
isError={isError}
hasSearch={hasSearch}
onRetry={() => refetch()}
/>
</CardContent>
</Card>
) : (
<div className={bookingSurface.tableWrap}>
<DataTable
columns={columns}
data={rows}
status={isLoading ? "loading" : isError ? "error" : "success"}
onRowClick={(row) =>
navigate(`/dashboard/booking-requests/${row.id}`)
}
pagination={{
pageIndex: pagination.pageIndex,
pageSize: pagination.pageSize,
pageCount,
totalCount: total,
}}
tableOptions={{
state: { pagination },
onPaginationChange: setPagination,
manualPagination: true,
pageCount,
}}
containerClassName="border-0 shadow-none [&_tbody_tr]:group/tr [&_tbody_tr]:cursor-pointer [&_tbody_tr]:transition-colors [&_tbody_tr:hover]:bg-muted/40"
footer={DataTableFooter}
/>
</div>
)}
</div>
</div>
</div>
);
}
function StatCard({
label,
value,
icon,
}: {
label: string;
value: number;
icon: React.ReactNode;
}) {
return (
<Card>
<CardContent className="flex items-center justify-between">
<div>
<p className="text-sm text-slate-500">{label}</p>
<h3 className="mt-2 text-3xl font-bold text-slate-900">{value}</h3>
</div>
<div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
{icon}
</div>
</CardContent>
</Card>
);
}

View File

@@ -1,148 +1,2 @@
export interface BookingRequest {
id: string;
reference: string;
customer: string;
status: (typeof BOOKING_STATUSES)[number];
scheduledDate: string;
totalAmount: number;
paymentStatus: string;
contractType: string;
serviceType: string;
tradeDirection: string;
originYard: string;
destinationYard: string;
cargoType: string;
cargoTotalWeightVgm: number;
isHazardous: boolean;
paymentCurrency: string;
priorityScore: number;
firstMilePickupAddress: string | null;
lastMileDeliveryAddress: string | null;
shippingLine: string | null;
pnrCode: string | null;
createdBy: string;
createdAt: string;
updatedAt: string;
}
export const BOOKING_STATUSES = [
"DRAFT",
"RFQ_SUBMITTED",
"QUOTATION_SENT",
"QUOTATION_APPROVED",
"QUOTATION_REJECTED",
"PENDING_APPROVAL",
"APPROVED",
"SIGNED_CUSTOMER",
"FULLY_EXECUTED",
"PAID",
"IN_TRANSIT",
"COMPLETED",
"CANCELLED",
"PENDING_CONSOLIDATION",
"CONSOLIDATED",
] as const;
const customers = [
"Ethio Cargo Logistics",
"Djibouti Shipping PLC",
"Horn of Africa Traders",
"Addis Freight Forwarders",
"Red Sea Maritime Services",
"Dire Dawa Imports Ltd",
"Awash Agro Industry",
"Mieso Mineral Exports",
];
const yards = [
"Addis Ababa Dry Port",
"Mojo Inland Container Depot",
"Dire Dawa Freight Station",
"Djibouti Port Terminal",
"Adama Logistics Hub",
"Awash Cargo Center",
];
const serviceTypes = ["RAIL", "RAIL_AND_FORWARDING"];
const tradeDirections = ["EXPORT", "IMPORT", "DOMESTIC"];
const cargoTypes = ["Containerized", "Bulk", "Liquid", "Refrigerated", "Hazardous"];
const shippingLines = ["MSC", "CMA CGM", "Maersk", "COSCO", "Hapag-Lloyd", null];
function pick<T>(arr: T[], index: number): T {
return arr[index % arr.length];
}
function randDate(daysAgo: number): string {
const d = new Date(2026, 4, 28 - daysAgo);
return d.toISOString();
}
const now = Date.now();
const INITIAL_REQUESTS: BookingRequest[] = Array.from({ length: 25 }, (_, i) => {
const statusIndex = i % BOOKING_STATUSES.length;
const status = BOOKING_STATUSES[statusIndex];
const customer = pick(customers, i);
return {
id: String(i + 1),
reference: `EDR-BK-${String(2026001 + i).slice(-6)}`,
customer,
status,
scheduledDate: new Date(2026, 5, 1 + (i % 28)).toISOString().slice(0, 10),
totalAmount: 1500 + i * 320 + (i % 7) * 100,
paymentStatus: status === "PAID" || status === "COMPLETED" ? "PAID" : status === "CANCELLED" ? "REFUNDED" : "PENDING",
contractType: i % 5 === 0 ? "RENEWAL" : "NEW",
serviceType: pick(serviceTypes, i),
tradeDirection: pick(tradeDirections, i),
originYard: pick(yards, i),
destinationYard: pick(yards, i + 3),
cargoType: pick(cargoTypes, i),
cargoTotalWeightVgm: 10 + ((i * 7) % 90),
isHazardous: i % 7 === 0,
paymentCurrency: "USD",
priorityScore: i % 4 === 0 ? 3 : i % 3 === 0 ? 2 : 1,
firstMilePickupAddress: i % 3 === 0 ? "Bole Industrial Zone, Addis Ababa" : null,
lastMileDeliveryAddress: i % 4 === 0 ? "Port Boulevard, Djibouti City" : null,
shippingLine: pick(shippingLines, i),
pnrCode: i % 6 === 0 ? `PNR-${202600 + i}` : null,
createdBy: customer,
createdAt: randDate(30 - i),
updatedAt: randDate(2),
};
});
export function saveBookingRequestsToStorage(data: BookingRequest[]) {
if (typeof window !== "undefined" && window.localStorage) {
localStorage.setItem("edr_backoffice_booking_requests", JSON.stringify(data));
}
}
export function getBookingRequestById(id: string): BookingRequest | undefined {
const requests = getBookingRequests();
return requests.find((r) => r.id === id);
}
export function updateBookingRequestStatus(id: string, newStatus: (typeof BOOKING_STATUSES)[number]) {
const requests = getBookingRequests();
const idx = requests.findIndex((r) => r.id === id);
if (idx === -1) return;
requests[idx] = { ...requests[idx], status: newStatus, updatedAt: new Date().toISOString() };
saveBookingRequestsToStorage(requests);
}
export function getBookingRequests(): BookingRequest[] {
if (typeof window === "undefined" || !window.localStorage) {
return INITIAL_REQUESTS;
}
const data = localStorage.getItem("edr_backoffice_booking_requests");
if (!data) {
localStorage.setItem("edr_backoffice_booking_requests", JSON.stringify(INITIAL_REQUESTS));
return INITIAL_REQUESTS;
}
try {
return JSON.parse(data);
} catch {
return INITIAL_REQUESTS;
}
}
/** @deprecated Use BookingDetail from @/types/booking — kept for gradual migration */
export type { BookingListRow as BookingRequest } from "@/types/booking";

View File

@@ -0,0 +1,9 @@
/** Demo portal mock data — booking requests use the live API instead. */
export interface Booking {
id: number | string;
customerId: number | string;
reference?: string;
status?: string;
}
export const bookings: Booking[] = [];

View File

@@ -20,12 +20,16 @@ import ManageFileUploadFieldsDialog from "./ManageFileUploadFieldsDialog";
import DeleteFileUploadSettingDialog from "./DeleteFileUploadSettingDialog";
import Breadcrumbs from "@/components/ui/Breadcrumbs";
import { getMinFiles } from "@/types/fileUploadSettings";
import { useDeleteFileUploadSetting, useFileUploadSettings } from "@/hooks/useFileUploadSettings";
import { useQuery } from "@tanstack/react-query";
import { api } from "@/services/api";
import { useDeleteFileUploadSetting } from "@/hooks/useFileUploadSettings";
export default function FileUploadSettingsPage() {
const [query, setQuery] = useState("");
const { data, isLoading, isError, error } = useFileUploadSettings();
const { data, isLoading, isError, error } = useQuery(
api.fileUploadSettings.list.queryOptions(),
);
const deleteMutation = useDeleteFileUploadSetting();
const fileUploadSettings = useMemo(

View File

@@ -21,10 +21,9 @@ import Breadcrumbs from "@/components/ui/Breadcrumbs";
import EditDropdownSettingDialog from "./EditDropdownSettingDialog";
import ManageDropdownOptionsDialog from "./ManageDropdownOptionsDialog";
import DeleteDropdownSettingDialog from "./DeleteDropdownSettingDialog";
import {
useDeleteDropdownSetting,
useDropdownSettings,
} from "@/hooks/useDropdownSettings";
import { useQuery } from "@tanstack/react-query";
import { api } from "@/services/api";
import { useDeleteDropdownSetting } from "@/hooks/useDropdownSettings";
import type { DropdownSetting } from "@/types/dropdownSettings";
import {
DataTable,
@@ -86,7 +85,9 @@ export default function DropdownSettingsPage() {
return () => cancelAnimationFrame(id);
}, [activeDialog]);
const { data, isLoading, isError, error } = useDropdownSettings();
const { data, isLoading, isError, error } = useQuery(
api.dropdownSettings.list.queryOptions(),
);
const deleteMutation = useDeleteDropdownSetting();
const dropdownSettings = useMemo<DropdownSetting[]>(

View File

@@ -1,4 +1,4 @@
import { useMemo, useState } from "react";
import { useCallback, useMemo, useState } from "react";
import { Navigate, useLocation, useParams } from "react-router-dom";
import type { ColumnDef } from "@tanstack/react-table";
import { Loader2 } from "lucide-react";
@@ -9,7 +9,6 @@ import RuleEngineRecordActions from "@/components/ruleEngine/RuleEngineRecordAct
import RuleEngineToolbar from "@/components/ruleEngine/RuleEngineToolbar";
import { formatCell } from "@/components/ruleEngine/ruleEngineFormat";
import {
ruleEngineField,
ruleEngineSurface,
ruleEngineTable,
} from "@/components/ruleEngine/ruleEngineStyles";
@@ -26,6 +25,7 @@ import {
useApprovalChain,
useCargoTypeParentOptions,
useContainerTypeOptions,
useLiveRateOptions,
useRateWorkflow,
useRuleEngineList,
useRuleEngineMutations,
@@ -41,8 +41,6 @@ import {
DialogDescription,
DialogHeader,
DialogTitle,
Input,
Label,
getCoreRowModel,
usePagination,
useReactTable,
@@ -73,9 +71,6 @@ const RuleEngineResourcePage = () => {
const [editing, setEditing] = useState<RuleEngineRecord | null>(null);
const [deleteTarget, setDeleteTarget] = useState<RuleEngineRecord | null>(null);
const [chainOpen, setChainOpen] = useState(false);
const [approveTarget, setApproveTarget] = useState<RuleEngineRecord | null>(null);
const [ceoId, setCeoId] = useState("");
const { viewMode, setViewMode } = useRuleEngineViewMode(
config?.slug ?? DEFAULT_CONFIGURATION_SLUG,
);
@@ -103,33 +98,52 @@ const RuleEngineResourcePage = () => {
);
const editingId = editing?.id ? String(editing.id) : undefined;
const usesContainerTypeField = Boolean(
config?.formFields.some((f) => f.name === "containerTypeId"),
);
const usesLiveRateField = Boolean(
config?.formFields.some((f) => f.name === "rateId"),
);
const { data: cargoParentOptions, isLoading: cargoParentOptionsLoading } =
useCargoTypeParentOptions(editingId, config?.slug === "cargo-types");
const { data: containerTypeOptions, isLoading: containerTypeOptionsLoading } =
useContainerTypeOptions(config?.slug === "rates");
useContainerTypeOptions(
config?.slug === "rates",
usesContainerTypeField,
);
const { data: liveRateOptions, isLoading: liveRateOptionsLoading } =
useLiveRateOptions(usesLiveRateField);
const formFields = useMemo(() => {
if (!config) return [];
return config.formFields.map((field) =>
config.slug === "cargo-types" && field.name === "parentGroupId"
? {
...field,
options:
cargoParentOptions ?? [
{ label: "None", value: RULE_ENGINE_SELECT_NONE },
],
}
: config.slug === "rates" && field.name === "containerTypeId"
? {
...field,
options:
containerTypeOptions ?? [
{ label: "None", value: RULE_ENGINE_SELECT_NONE },
],
}
: field,
);
}, [config, cargoParentOptions, containerTypeOptions]);
return config.formFields.map((field) => {
if (config.slug === "cargo-types" && field.name === "parentGroupId") {
return {
...field,
options:
cargoParentOptions ?? [
{ label: "None", value: RULE_ENGINE_SELECT_NONE },
],
};
}
if (field.name === "containerTypeId") {
return {
...field,
type: "select" as const,
options: containerTypeOptions ?? [],
};
}
if (field.name === "rateId") {
return {
...field,
type: "select" as const,
options: liveRateOptions ?? [],
};
}
return field;
});
}, [config, cargoParentOptions, containerTypeOptions, liveRateOptions]);
const rows = data?.data ?? [];
const meta = data?.meta;
@@ -163,6 +177,13 @@ const RuleEngineResourcePage = () => {
onPaginationChange: setPagination,
});
const handleApproveRate = useCallback(
(record: RuleEngineRecord) => {
approve.mutate(String(record.id));
},
[approve],
);
const columns = useMemo((): ColumnDef<RuleEngineRecord>[] => {
if (!config) return [];
@@ -195,14 +216,14 @@ const RuleEngineResourcePage = () => {
config.slug === "approval-rules" ? () => setChainOpen(true) : undefined
}
onSubmitRate={(id) => submit.mutate(id)}
onApproveRate={setApproveTarget}
onApproveRate={handleApproveRate}
/>
</div>
),
});
return base;
}, [config, submit]);
}, [config, submit, handleApproveRate]);
const tableStatus = isLoading ? "loading" : isError ? "error" : "success";
@@ -318,7 +339,7 @@ const RuleEngineResourcePage = () => {
config.slug === "approval-rules" ? () => setChainOpen(true) : undefined
}
onSubmitRate={(id) => submit.mutate(id)}
onApproveRate={setApproveTarget}
onApproveRate={handleApproveRate}
/>
)}
</Card>
@@ -337,7 +358,8 @@ const RuleEngineResourcePage = () => {
isSubmitting={create.isPending || update.isPending}
selectOptionsLoading={
(config.slug === "cargo-types" && cargoParentOptionsLoading) ||
(config.slug === "rates" && containerTypeOptionsLoading)
(usesContainerTypeField && containerTypeOptionsLoading) ||
(usesLiveRateField && liveRateOptionsLoading)
}
onSubmit={handleFormSubmit}
/>
@@ -370,51 +392,6 @@ const RuleEngineResourcePage = () => {
</DialogContent>
</Dialog>
<Dialog open={Boolean(approveTarget)} onOpenChange={(o) => !o && setApproveTarget(null)}>
<DialogContent className={ruleEngineSurface.dialogSm}>
<DialogHeader>
<DialogTitle>Approve rate</DialogTitle>
<DialogDescription>Enter the CEO staff ID to approve this rate.</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-1.5">
<Label htmlFor="ceoId" className={ruleEngineField.label}>
CEO staff ID
</Label>
<Input
id="ceoId"
value={ceoId}
onChange={(e) => setCeoId(e.target.value)}
placeholder="UUID"
className={ruleEngineField.input}
/>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setApproveTarget(null)}>
Cancel
</Button>
<Button
disabled={!ceoId.trim() || approve.isPending}
onClick={() => {
if (!approveTarget) return;
approve.mutate(
{ id: approveTarget.id, payload: { approvedByCeoId: ceoId.trim() } },
{
onSuccess: () => {
setApproveTarget(null);
setCeoId("");
},
},
);
}}
>
{approve.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : "Approve"}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
<Dialog open={chainOpen} onOpenChange={setChainOpen}>
<DialogContent className={ruleEngineSurface.dialog}>
<DialogHeader>

View File

@@ -3,7 +3,16 @@ import type { RuleEngineResourceSlug } from "@/types/rule-engine";
export type RuleEngineNavCategory = "configuration" | "rules";
export type ColumnFormat = "text" | "code" | "boolean" | "activeBadge" | "rateStatus" | "date" | "number";
export type ColumnFormat =
| "text"
| "code"
| "boolean"
| "activeBadge"
| "rateStatus"
| "date"
| "number"
| "entityLabel"
| "rateLabel";
export type FormFieldType = "text" | "number" | "boolean" | "date" | "select" | "textarea";
@@ -187,7 +196,14 @@ export const RULE_ENGINE_RESOURCES: RuleEngineResourceConfig[] = [
formFields: [
{ name: "label", label: "Label", type: "text", required: true },
{ name: "score", label: "Score", type: "number", required: true },
{ name: "conditionCurrency", label: "Condition currency", type: "text", placeholder: "USD (optional)" },
{
name: "conditionCurrency",
label: "Condition currency",
type: "select",
optional: true,
options: [{ label: "Any", value: RULE_ENGINE_SELECT_NONE }, ...CURRENCIES],
placeholder: "Any currency (optional)",
},
{ name: "isActive", label: "Active", type: "boolean" },
],
},
@@ -226,7 +242,7 @@ export const RULE_ENGINE_RESOURCES: RuleEngineResourceConfig[] = [
codeColumn("code"),
{ id: "label", header: "Label", accessorKey: "label" },
{ id: "triggerCondition", header: "Trigger", accessorKey: "triggerCondition" },
{ id: "rateId", header: "Rate ID", accessorKey: "rateId" },
{ id: "rateId", header: "Rate", accessorKey: "rate", format: "rateLabel" },
activeColumn,
],
formFields: [
@@ -238,7 +254,13 @@ export const RULE_ENGINE_RESOURCES: RuleEngineResourceConfig[] = [
required: true,
options: SURCHARGE_TRIGGERS,
},
{ name: "rateId", label: "Rate ID", type: "text", required: true, placeholder: "UUID of LIVE rate" },
{
name: "rateId",
label: "Live rate",
type: "select",
required: true,
placeholder: "Select a LIVE rate",
},
{ name: "isActive", label: "Active", type: "boolean" },
],
},
@@ -249,14 +271,25 @@ export const RULE_ENGINE_RESOURCES: RuleEngineResourceConfig[] = [
subtitle: "VGM limits by container and trade direction",
searchPlaceholder: "Search weight limit rules...",
columns: [
{ id: "containerTypeId", header: "Container", accessorKey: "containerTypeId" },
{
id: "containerType",
header: "Container",
accessorKey: "containerType",
format: "entityLabel",
},
{ id: "tradeDirection", header: "Direction", accessorKey: "tradeDirection" },
{ id: "maxVgmTons", header: "Max VGM (t)", accessorKey: "maxVgmTons", format: "number" },
{ id: "effectiveFrom", header: "From", accessorKey: "effectiveFrom", format: "date" },
{ id: "effectiveTo", header: "To", accessorKey: "effectiveTo", format: "date" },
],
formFields: [
{ name: "containerTypeId", label: "Container type ID", type: "text", required: true },
{
name: "containerTypeId",
label: "Container type",
type: "select",
required: true,
placeholder: "Select container type",
},
{
name: "tradeDirection",
label: "Trade direction",
@@ -349,7 +382,6 @@ export const RULE_ENGINE_RESOURCES: RuleEngineResourceConfig[] = [
{ name: "currency", label: "Currency", type: "select", required: true, options: CURRENCIES },
{ name: "rateValue", label: "Rate value", type: "number", required: true },
{ name: "rateUnit", label: "Rate unit", type: "select", required: true, options: RATE_UNITS },
{ name: "proposedByStaffId", label: "Proposed by (staff ID)", type: "text", required: true },
{ name: "effectiveFrom", label: "Effective from", type: "date", required: true },
{ name: "effectiveTo", label: "Effective to", type: "date" },
],