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

@@ -1,5 +1,4 @@
import { Navigate, Outlet, Route, Routes, useLocation, useNavigate } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
Boxes,
FileText,
@@ -8,12 +7,17 @@ import {
Paperclip,
Settings,
SlidersHorizontal,
Train,
Truck,
Container,
Package,
} from "lucide-react";
import { FreightDashboardLayout, type SidebarItem, type SidebarSection } from "@/components/layout";
import LoadingScreen from "./components/LoadingScreen";
import { useAuth } from "./auth/useAuth";
import LoginPage from "./pages/auth/LoginPage";
import BookingContractPage from "./pages/bookings/BookingContractPage";
import BookingRequestDetailPage from "./pages/bookings/BookingRequestDetailPage";
import BookingRequestsPage from "./pages/bookings/BookingRequestsPage";
import DemoUser1Page from "./pages/dashboard/demo/DemoUser1Page";
@@ -30,16 +34,11 @@ import FileUploadSettingsPage from "./pages/documents/FileUploadSettingsPage";
import RuleEngineLegacyRedirect from "./pages/ruleEngine/RuleEngineLegacyRedirect";
import RuleEngineResourcePage from "./pages/ruleEngine/RuleEngineResourcePage";
import { getCategorySidebarChildren } from "./pages/ruleEngine/config/resources";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
refetchOnWindowFocus: false,
staleTime: 5 * 60 * 1000,
},
},
});
import TrainsPage from "./pages/trains/TrainsPage";
import TrainDetailPage from "./pages/trains/TrainDetailPage";
import WagonsPage from "./pages/wagons/WagonsPage";
import ContainersPage from "./pages/containers_management/ContainersPage";
import CargoesPage from "./pages/cargoes/CargoesPage";
const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [
{
@@ -59,6 +58,31 @@ const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [
...demoItems,
],
},
{
title: "Fleet Management",
items: [
{
label: "Trains",
href: "/dashboard/trains",
icon: <Train />,
},
{
label: "Wagons",
href: "/dashboard/wagons",
icon: <Truck />,
},
{
label: "Containers",
href: "/dashboard/containers",
icon: <Container />,
},
{
label: "Cargoes",
href: "/dashboard/cargoes",
icon: <Package />,
},
],
},
{
title: "Administration",
items: [
@@ -188,18 +212,15 @@ const App = () => {
if (!user) {
return (
<QueryClientProvider client={queryClient}>
<Routes>
<Route path="/auth" element={<LoginPage />} />
<Route path="*" element={<Navigate to="/auth" replace />} />
</Routes>
</QueryClientProvider>
<Routes>
<Route path="/auth" element={<LoginPage />} />
<Route path="*" element={<Navigate to="/auth" replace />} />
</Routes>
);
}
return (
<QueryClientProvider client={queryClient}>
<Routes>
<Routes>
<Route path="/" element={<Navigate to="/dashboard/overview" replace />} />
<Route path="/dashboard" element={<Navigate to="/dashboard/overview" replace />} />
@@ -208,6 +229,16 @@ const App = () => {
<Route path="booking-requests" element={<BookingRequestsPage />} />
<Route path="booking-requests/:id" element={<BookingRequestDetailPage />} />
<Route
path="booking-requests/:id/contract"
element={<BookingContractPage />}
/>
<Route path="trains" element={<TrainsPage />} />
<Route path="trains/:id" element={<TrainDetailPage />} />
<Route path="wagons" element={<WagonsPage />} />
<Route path="containers" element={<ContainersPage />} />
<Route path="cargoes" element={<CargoesPage />} />
<Route path="user-management" element={<UserManagementPage />} />
<Route path="user-management/users" element={<UsersPage />} />
@@ -251,8 +282,7 @@ const App = () => {
</Route>
<Route path="*" element={<Navigate to="/dashboard/overview" replace />} />
</Routes>
</QueryClientProvider>
</Routes>
);
};

View File

@@ -0,0 +1,116 @@
import { useMemo } from "react";
import { ShieldCheck } from "lucide-react";
import type { BookingApprovalStep, BookingDetail } from "@/types/booking";
import { getNextPendingApprovalStep } from "@/features/bookings/booking-actions.config";
import { Badge } from "@edr/ui-common";
import { cn } from "@/lib/utils";
interface ApprovalStepsCardProps {
booking: BookingDetail;
}
/** Read-only approval chain visualization; actions live in BookingActionsToolbar. */
export function ApprovalStepsCard({ booking }: ApprovalStepsCardProps) {
const steps = useMemo(
() =>
[...(booking.approvalSteps ?? [])].sort(
(a, b) => a.stepOrder - b.stepOrder,
),
[booking.approvalSteps],
);
const nextPending = getNextPendingApprovalStep(steps);
return (
<div className="overflow-hidden rounded-xl border border-amber-200/80 bg-gradient-to-b from-amber-50/40 to-card shadow-sm dark:from-amber-950/20">
<div className="flex items-center gap-3 border-b border-amber-200/50 bg-amber-50/50 px-5 py-4 dark:bg-amber-950/30">
<div className="flex size-9 items-center justify-center rounded-lg bg-amber-500/15 text-amber-800 dark:text-amber-300">
<ShieldCheck className="size-4" />
</div>
<div>
<h2 className="text-sm font-semibold text-foreground">
Approval chain
</h2>
<p className="text-xs text-muted-foreground">
Next:{" "}
{nextPending
? `${nextPending.requiredRole} · step ${nextPending.stepOrder}`
: steps.length
? "All steps complete"
: "Accept submission to begin"}
</p>
</div>
</div>
<div className="px-5 py-5">
{steps.length === 0 ? (
<p className="rounded-lg border border-dashed border-border bg-muted/20 px-4 py-6 text-center text-sm text-muted-foreground">
Use <strong className="font-semibold text-foreground">Accept for approval</strong>{" "}
in staff actions to instantiate steps.
</p>
) : (
<ul className="space-y-2">
{steps.map((step) => (
<StepRow
key={step.id}
step={step}
isNext={nextPending?.id === step.id}
/>
))}
</ul>
)}
</div>
</div>
);
}
function StepRow({
step,
isNext,
}: {
step: BookingApprovalStep;
isNext: boolean;
}) {
const statusStyles =
step.status === "APPROVED"
? "bg-emerald-500/15 text-emerald-800 dark:text-emerald-300"
: step.status === "REJECTED"
? "bg-red-500/15 text-red-800 dark:text-red-300"
: isNext
? "bg-amber-500/15 text-amber-800 dark:text-amber-300"
: "bg-muted text-muted-foreground";
return (
<li
className={cn(
"flex items-center justify-between gap-3 rounded-lg border px-4 py-3 transition-colors",
isNext
? "border-primary/30 bg-primary/[0.03] shadow-sm"
: "border-border/60 bg-card",
)}
>
<div className="flex min-w-0 items-center gap-3">
<span className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-xs font-bold text-muted-foreground">
{step.stepOrder}
</span>
<div className="min-w-0">
<p className="text-sm font-semibold text-foreground">
{step.requiredRole}
</p>
{step.remarks && (
<p className="truncate text-xs text-muted-foreground">
{step.remarks}
</p>
)}
</div>
</div>
<Badge
variant="outline"
className={cn("shrink-0 text-[9px] uppercase", statusStyles)}
>
{step.status}
</Badge>
</li>
);
}

View File

@@ -0,0 +1,233 @@
import { useNavigate } from "react-router-dom";
import {
ChevronRight,
ExternalLink,
Loader2,
MoreHorizontal,
Upload,
} from "lucide-react";
import { BookingConfirmDialog } from "./BookingConfirmDialog";
import { useBookingActionDialog } from "./useBookingActionDialog";
import {
listRowHasActions,
type BookingActionContext,
} from "@/features/bookings/booking-actions.config";
import type { BookingListRow } from "@/types/booking";
import { cn } from "@/lib/utils";
import {
Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@edr/ui-common";
interface BookingActionsMenuProps {
row: BookingListRow;
/** Compact table cell vs. larger detail toolbar */
variant?: "table" | "toolbar";
className?: string;
}
export function BookingActionsMenu({
row,
variant = "table",
className,
}: BookingActionsMenuProps) {
const navigate = useNavigate();
const context: BookingActionContext = {
status: row.status,
paymentCurrency: row.paymentCurrency,
reference: row.reference,
};
const flow = useBookingActionDialog(row.id, context);
const { actions, pendingAction, mutations } = flow;
const goToContract = () =>
navigate(`/dashboard/booking-requests/${row.id}/contract`);
const showUsdPaymentHint =
row.status === "FULLY_EXECUTED" && row.paymentCurrency === "USD";
const hasMenu = listRowHasActions(row) || showUsdPaymentHint;
const primary = actions.find((a) => a.primary) ?? actions[0];
if (!hasMenu && variant === "table") {
return (
<Button
variant="ghost"
size="icon"
className="size-8 text-muted-foreground hover:text-primary"
onClick={() => navigate(`/dashboard/booking-requests/${row.id}`)}
aria-label="View booking"
>
<ChevronRight className="size-4" />
</Button>
);
}
return (
<>
<div
className={cn(
"flex items-center justify-end gap-1",
variant === "table" && "opacity-80 transition-opacity group-hover/tr:opacity-100",
className,
)}
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => e.stopPropagation()}
>
{variant === "table" && primary && (
<Button
size="sm"
className="hidden h-8 gap-1.5 px-2.5 shadow-sm lg:inline-flex"
disabled={mutations.isPending}
onClick={() =>
primary.id === "viewContract"
? goToContract()
: flow.openAction(primary)
}
>
<primary.icon className="size-3.5" />
{primary.shortLabel}
</Button>
)}
{variant === "toolbar" && actions.length > 0 ? (
<div className="flex w-full flex-wrap gap-2">
{actions.map((action) => {
const Icon = action.icon;
return (
<Button
key={action.id}
size="sm"
variant={
action.variant === "destructive"
? "outline"
: action.primary
? "default"
: "outline"
}
className={cn(
"gap-2 shadow-sm",
action.variant === "destructive" &&
"border-red-200 text-red-700 hover:bg-red-50 dark:hover:bg-red-950/30",
)}
disabled={mutations.isPending}
onClick={() =>
action.id === "viewContract"
? goToContract()
: flow.openAction(action)
}
>
<Icon className="size-4" />
{action.label}
</Button>
);
})}
</div>
) : (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant={variant === "table" ? "ghost" : "outline"}
size={variant === "table" ? "icon" : "sm"}
className={cn(
variant === "table" ? "size-8" : "gap-2",
"shrink-0",
)}
disabled={mutations.isPending}
aria-label="Booking actions"
>
{mutations.isPending ? (
<Loader2 className="size-4 animate-spin" />
) : (
<MoreHorizontal className="size-4" />
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuLabel className="font-mono text-xs text-muted-foreground">
{row.reference}
</DropdownMenuLabel>
<DropdownMenuSeparator />
{actions.map((action) => {
const Icon = action.icon;
return (
<DropdownMenuItem
key={action.id}
className={cn(
"gap-2 cursor-pointer",
action.variant === "destructive" && "text-red-700 focus:text-red-700",
)}
onClick={() =>
action.id === "viewContract"
? goToContract()
: flow.openAction(action)
}
>
<Icon className="size-4 opacity-70" />
<span>{action.label}</span>
</DropdownMenuItem>
);
})}
{showUsdPaymentHint && (
<DropdownMenuItem
className="gap-2 cursor-pointer"
onClick={() =>
navigate(`/dashboard/booking-requests/${row.id}`)
}
>
<Upload className="size-4 opacity-70" />
Upload payment proof
</DropdownMenuItem>
)}
{(actions.length > 0 || showUsdPaymentHint) && (
<DropdownMenuSeparator />
)}
<DropdownMenuItem
className="gap-2 cursor-pointer"
onClick={() =>
navigate(`/dashboard/booking-requests/${row.id}`)
}
>
<ExternalLink className="size-4 opacity-70" />
Open full details
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
<BookingConfirmDialog
open={flow.dialogOpen}
onOpenChange={flow.setDialogOpen}
action={pendingAction}
reference={flow.mergedContext.reference}
inputValue={flow.inputValue}
onInputChange={flow.setInputValue}
onConfirm={flow.runAction}
isPending={mutations.isPending || flow.detailLoading}
confirmDisabled={flow.confirmDisabled}
extra={
flow.detailLoading ? (
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="size-4 animate-spin" />
Loading approval steps
</p>
) : pendingAction?.id === "approve" &&
!flow.mergedContext.approvalSteps?.length ? (
<p className="rounded-lg border border-amber-200/80 bg-amber-50/50 px-3 py-2 text-sm text-amber-900 dark:bg-amber-950/30 dark:text-amber-200">
No pending approval step found. Accept the submission on the detail
page first.
</p>
) : null
}
/>
</>
);
}

View File

@@ -0,0 +1,168 @@
import { useRef } from "react";
import { Download, Upload, Zap } from "lucide-react";
import type { BookingDetail } from "@/types/booking";
import { BookingActionsMenu } from "./BookingActionsMenu";
import { bookingSurface } from "./booking-ui.styles";
import { toBookingListRow } from "@/features/bookings/mapBookingListRow";
import type { useBookingMutations } from "@/hooks/bookings/useBookings";
import { Button } from "@edr/ui-common";
type Mutations = ReturnType<typeof useBookingMutations>;
interface BookingActionsToolbarProps {
booking: BookingDetail;
mutations: Mutations;
}
/** Detail-page actions: primary toolbar + payment uploads + downloads. */
export function BookingActionsToolbar({
booking,
mutations,
}: BookingActionsToolbarProps) {
const fileRef = useRef<HTMLInputElement>(null);
const row = toBookingListRow(booking);
const { status, paymentCurrency } = booking;
const pending = mutations.isPending;
const downloadBlob = async (fn: () => Promise<Blob>, filename: string) => {
const blob = await fn();
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
};
if (
status === "REJECTED" ||
status === "CANCELLED" ||
status === "COMPLETED"
) {
return null;
}
if (status === "CHANGES_REQUESTED") {
return (
<PanelShell title="Awaiting customer" description="No staff actions until resubmit.">
{booking.latestChangeRequestNote && (
<p className="rounded-lg border bg-muted/30 p-3 text-sm leading-relaxed">
{booking.latestChangeRequestNote}
</p>
)}
</PanelShell>
);
}
if (["DRAFT", "PENDING_CONSOLIDATION", "CONSOLIDATED"].includes(status)) {
return (
<PanelShell
title="No staff actions"
description="Monitor until the customer or system advances status."
muted
/>
);
}
return (
<div className="space-y-4">
<PanelShell
title="Staff actions"
description="Confirm each step before it is applied."
>
<BookingActionsMenu row={row} variant="toolbar" />
</PanelShell>
{status === "FULLY_EXECUTED" && paymentCurrency === "USD" && (
<PanelShell title="Payment (USD)" description="Upload proof of payment.">
<input
ref={fileRef}
type="file"
className="hidden"
accept=".pdf,.png,.jpg,.jpeg"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) mutations.submitPaymentProof.mutate(file);
}}
/>
<div className="flex flex-wrap gap-2">
<Button
variant="outline"
disabled={pending}
className="gap-2"
onClick={() => fileRef.current?.click()}
>
<Upload className="size-4" />
Upload payment proof
</Button>
<Button
variant="outline"
className="gap-2"
onClick={() =>
downloadBlob(
() => mutations.downloadPaymentLetter(),
`payment-letter-${booking.reference}.txt`,
)
}
>
<Download className="size-4" />
Request letter
</Button>
</div>
</PanelShell>
)}
{status === "CONTRACT_READY" && (
<PanelShell title="Documents" description="Download generated contract.">
<Button
variant="outline"
className="gap-2"
onClick={() =>
downloadBlob(
() => mutations.downloadContract(),
`contract-${booking.reference}.txt`,
)
}
>
<Download className="size-4" />
Download contract
</Button>
</PanelShell>
)}
</div>
);
}
function PanelShell({
title,
description,
children,
muted,
}: {
title: string;
description: string;
children: React.ReactNode;
muted?: boolean;
}) {
return (
<div
className={
muted
? bookingSurface.sectionCard
: `${bookingSurface.sectionCard} ring-1 ring-primary/10`
}
>
<div className={bookingSurface.sectionHeader}>
<div className="flex size-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
<Zap className="size-4" />
</div>
<div>
<h2 className="text-sm font-semibold text-foreground">{title}</h2>
<p className="text-xs text-muted-foreground">{description}</p>
</div>
</div>
<div className="flex flex-col gap-3 px-5 py-5">{children}</div>
</div>
);
}

View File

@@ -0,0 +1,134 @@
import { Loader2 } from "lucide-react";
import type { BookingActionDef } from "@/features/bookings/booking-actions.config";
import { cn } from "@/lib/utils";
import {
Button,
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
Textarea,
} from "@edr/ui-common";
interface BookingConfirmDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
action: BookingActionDef | null;
reference?: string;
inputValue: string;
onInputChange: (value: string) => void;
onConfirm: () => void;
isPending: boolean;
confirmDisabled?: boolean;
extra?: React.ReactNode;
}
export function BookingConfirmDialog({
open,
onOpenChange,
action,
reference,
inputValue,
onInputChange,
onConfirm,
isPending,
confirmDisabled = false,
extra,
}: BookingConfirmDialogProps) {
if (!action || !action.confirmTitle) return null;
const Icon = action.icon;
const needsInput = Boolean(action.input);
const inputMissing = needsInput && !inputValue.trim();
const isDestructive = action.variant === "destructive";
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="gap-0 overflow-hidden p-0 sm:max-w-md">
<div
className={cn(
"border-b px-6 py-5",
isDestructive
? "bg-gradient-to-br from-red-500/10 via-background to-background"
: "bg-gradient-to-br from-primary/8 via-background to-background",
)}
>
<DialogHeader className="gap-3 text-left">
<div className="flex items-start gap-3">
<div
className={cn(
"flex size-11 shrink-0 items-center justify-center rounded-xl shadow-sm",
isDestructive
? "bg-red-500/15 text-red-700 dark:text-red-300"
: "bg-primary/15 text-primary",
)}
>
<Icon className="size-5" />
</div>
<div className="min-w-0 space-y-1 pt-0.5">
<DialogTitle className="text-base leading-snug">
{action.confirmTitle}
</DialogTitle>
{reference && (
<p className="font-mono text-xs font-semibold text-muted-foreground">
{reference}
</p>
)}
</div>
</div>
<DialogDescription className="text-left text-sm leading-relaxed">
{action.confirmDescription}
</DialogDescription>
</DialogHeader>
</div>
<div className="space-y-4 px-6 py-5">
{needsInput && (
<div className="space-y-2">
<label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
{action.inputLabel}
<span className="text-red-600"> *</span>
</label>
<Textarea
value={inputValue}
onChange={(e) => onInputChange(e.target.value)}
placeholder={action.inputPlaceholder}
rows={4}
className="min-h-[100px] resize-y"
/>
</div>
)}
{extra}
</div>
<DialogFooter className="gap-2 border-t bg-muted/20 px-6 py-4 sm:justify-end">
<Button
type="button"
variant="outline"
disabled={isPending}
onClick={() => onOpenChange(false)}
>
Cancel
</Button>
<Button
type="button"
variant={isDestructive ? "destructive" : "default"}
disabled={isPending || inputMissing || confirmDisabled}
className="min-w-[7rem] gap-2"
onClick={onConfirm}
>
{isPending ? (
<Loader2 className="size-4 animate-spin" />
) : (
<Icon className="size-4" />
)}
{action.shortLabel}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,86 @@
import { Banknote, Receipt } from "lucide-react";
import type { BookingDetail } from "@/types/booking";
import { Separator } from "@edr/ui-common";
import { bookingSurface } from "./booking-ui.styles";
export function BookingPricingSummary({ booking }: { booking: BookingDetail }) {
const amount = Number(booking.totalAmount);
const modifiers = booking.cargoModifiers ?? [];
return (
<div className={bookingSurface.sectionCard}>
<div className={bookingSurface.sectionHeader}>
<div className="flex size-9 items-center justify-center rounded-lg bg-emerald-500/10 text-emerald-700 dark:text-emerald-400">
<Banknote className="size-4" />
</div>
<div>
<h2 className="text-sm font-semibold text-foreground">
Pricing & payment
</h2>
<p className="text-xs text-muted-foreground">Commercial terms</p>
</div>
</div>
<div className="space-y-4 px-5 py-5">
<div className="rounded-xl border border-primary/15 bg-gradient-to-br from-primary/[0.06] to-transparent p-4">
<p className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
Total amount
</p>
<p className="mt-1 font-mono text-2xl font-bold tracking-tight text-foreground">
{booking.paymentCurrency}{" "}
{amount.toLocaleString(undefined, { minimumFractionDigits: 2 })}
</p>
</div>
<Row label="Payment status" value={booking.paymentStatus} />
{booking.pnrCode && <Row label="PNR code" value={booking.pnrCode} mono />}
{modifiers.length > 0 && (
<>
<Separator />
<p className="flex items-center gap-2 text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
<Receipt className="size-3" />
Surcharges applied
</p>
<ul className="space-y-2">
{modifiers.map((m) => (
<li
key={m.id}
className="flex justify-between rounded-lg border border-border/60 bg-muted/20 px-3 py-2 text-sm"
>
<span className="text-muted-foreground">Modifier</span>
<span className="font-mono font-semibold tabular-nums">
{Number(m.calculatedAmount).toLocaleString()}
</span>
</li>
))}
</ul>
</>
)}
</div>
</div>
);
}
function Row({
label,
value,
mono,
}: {
label: string;
value: string;
mono?: boolean;
}) {
return (
<div className="flex items-center justify-between gap-2 text-sm">
<span className="text-muted-foreground">{label}</span>
<span
className={
mono
? "font-mono text-xs font-semibold text-foreground"
: "font-medium text-foreground"
}
>
{value}
</span>
</div>
);
}

View File

@@ -0,0 +1,21 @@
export function BookingPriorityBadge({ score }: { score: number }) {
if (score >= 1000) {
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 >= 500) {
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>
);
}

View File

@@ -0,0 +1,56 @@
import type { LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";
export interface StatItem {
label: string;
value: number | string;
hint?: string;
icon: LucideIcon;
accent?: "default" | "amber" | "emerald" | "rose";
}
const accentStyles = {
default: "bg-primary/10 text-primary",
amber: "bg-amber-500/10 text-amber-700 dark:text-amber-400",
emerald: "bg-emerald-500/10 text-emerald-700 dark:text-emerald-400",
rose: "bg-rose-500/10 text-rose-700 dark:text-rose-400",
};
export function BookingStatGrid({ items }: { items: StatItem[] }) {
return (
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
{items.map((item) => {
const Icon = item.icon;
const accent = item.accent ?? "default";
return (
<div
key={item.label}
className="group relative overflow-hidden rounded-xl border border-border bg-card p-5 shadow-sm transition-all duration-200 hover:border-primary/20 hover:shadow-md"
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
{item.label}
</p>
<p className="mt-2 text-3xl font-bold tabular-nums tracking-tight text-foreground">
{item.value}
</p>
{item.hint && (
<p className="mt-1 text-xs text-muted-foreground">{item.hint}</p>
)}
</div>
<div
className={cn(
"flex size-11 shrink-0 items-center justify-center rounded-xl transition-transform duration-200 group-hover:scale-105",
accentStyles[accent],
)}
>
<Icon className="size-5" strokeWidth={2} />
</div>
</div>
</div>
);
})}
</div>
);
}

View File

@@ -0,0 +1,21 @@
import { Badge } from "@edr/ui-common";
import { cn } from "@/lib/utils";
import { BOOKING_STATUS_STYLES } from "@/features/bookings/booking-status.config";
export function BookingStatusBadge({ status }: { status: string }) {
const style = BOOKING_STATUS_STYLES[status] ?? {
label: status,
color: "bg-muted text-muted-foreground border-border",
};
return (
<Badge
variant="outline"
className={cn(
"px-2 py-0.5 text-[9px] font-bold uppercase tracking-wider",
style.color,
)}
>
{style.label}
</Badge>
);
}

View File

@@ -0,0 +1,91 @@
import {
ClipboardCheck,
FileSignature,
FileText,
Inbox,
LayoutGrid,
ShieldCheck,
} from "lucide-react";
import {
BOOKING_LIST_TABS,
type BookingStatusTabKey,
} from "@/features/bookings/booking-status.config";
import { cn } from "@/lib/utils";
const TAB_ICONS: Record<BookingStatusTabKey, React.ReactNode> = {
all: <LayoutGrid className="size-4" />,
SUBMITTED: <Inbox className="size-4" />,
PENDING_APPROVAL: <ClipboardCheck className="size-4" />,
APPROVED_PENDING_SIGNATURE: <FileSignature className="size-4" />,
SIGNED_CUSTOMER: <FileText className="size-4" />,
PAYMENT_VERIFICATION_IN_PROGRESS: <ShieldCheck className="size-4" />,
};
interface BookingStatusTabsProps {
active: BookingStatusTabKey;
onChange: (tab: BookingStatusTabKey) => void;
counts?: Partial<Record<BookingStatusTabKey, number>>;
}
export function BookingStatusTabs({
active,
onChange,
counts,
}: BookingStatusTabsProps) {
return (
<div className="rounded-xl border border-border bg-muted/30 p-1.5">
<div
className="flex gap-1 overflow-x-auto pb-0.5 scrollbar-thin"
role="tablist"
aria-label="Booking status filters"
>
{BOOKING_LIST_TABS.map((tab) => {
const isActive = active === tab.key;
const count = counts?.[tab.key];
return (
<button
key={tab.key}
type="button"
role="tab"
aria-selected={isActive}
onClick={() => onChange(tab.key)}
className={cn(
"flex min-w-[7.5rem] shrink-0 flex-col items-start gap-0.5 rounded-lg px-3.5 py-2.5 text-left transition-all duration-200",
isActive
? "bg-background text-foreground shadow-sm ring-1 ring-border/80"
: "text-muted-foreground hover:bg-background/60 hover:text-foreground",
)}
>
<span className="flex w-full items-center justify-between gap-2">
<span
className={cn(
"flex items-center gap-2 text-sm font-semibold",
isActive && "text-primary",
)}
>
{TAB_ICONS[tab.key]}
{tab.label}
</span>
{count !== undefined && count > 0 && (
<span
className={cn(
"rounded-full px-2 py-0.5 text-[10px] font-bold tabular-nums",
isActive
? "bg-primary/15 text-primary"
: "bg-muted text-muted-foreground",
)}
>
{count}
</span>
)}
</span>
</button>
);
})}
</div>
</div>
);
}
export type { BookingStatusTabKey };

View File

@@ -0,0 +1,44 @@
import { Package, Search } from "lucide-react";
import { Button } from "@edr/ui-common";
import { bookingSurface } from "./booking-ui.styles";
interface BookingTableEmptyProps {
isError?: boolean;
hasSearch?: boolean;
onRetry?: () => void;
}
export function BookingTableEmpty({
isError,
hasSearch,
onRetry,
}: BookingTableEmptyProps) {
return (
<div className={bookingSurface.emptyState}>
<div className="flex size-14 items-center justify-center rounded-2xl bg-muted text-muted-foreground">
{hasSearch ? <Search className="size-6" /> : <Package className="size-6" />}
</div>
<div className="max-w-sm space-y-1">
<h3 className="text-base font-semibold text-foreground">
{isError
? "Could not load bookings"
: hasSearch
? "No matches on this page"
: "No bookings with this status"}
</h3>
<p className="text-sm text-muted-foreground">
{isError
? "Check your connection and try again."
: hasSearch
? "Try a different reference or customer name."
: "New customer submissions will appear when status is Submitted."}
</p>
</div>
{isError && onRetry && (
<Button variant="outline" size="sm" onClick={onRetry}>
Retry
</Button>
)}
</div>
);
}

View File

@@ -0,0 +1,124 @@
import {
Check,
CheckCircle2,
FileSignature,
FileText,
Train,
Wallet,
} from "lucide-react";
import { cn } from "@/lib/utils";
import {
getWorkflowStageIndex,
WORKFLOW_STAGES,
} from "@/features/bookings/booking-status.config";
import { bookingSurface } from "./booking-ui.styles";
const STAGE_ICONS = [FileText, FileSignature, FileSignature, Wallet, Train, Check];
interface BookingWorkflowStepperProps {
status: string;
title: string;
description: string;
titleColor: string;
}
export function BookingWorkflowStepper({
status,
title,
description,
titleColor,
}: BookingWorkflowStepperProps) {
const currentStage = getWorkflowStageIndex(status);
const isTerminal = currentStage < 0;
return (
<div className={bookingSurface.sectionCard}>
<div className={bookingSurface.sectionHeader}>
<div className="flex size-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
<Train className="size-4" />
</div>
<div>
<h2 className="text-sm font-semibold text-foreground">
Workflow progress
</h2>
<p className="text-xs text-muted-foreground">
Customer submission through completion
</p>
</div>
</div>
<div className="space-y-8 px-5 py-6">
<div className="relative px-2">
<div className="absolute left-4 right-4 top-5 h-0.5 bg-border" />
<div
className="absolute left-4 top-5 h-0.5 bg-primary transition-all duration-700 ease-out"
style={{
width:
!isTerminal && currentStage >= 0
? `calc(${(currentStage / (WORKFLOW_STAGES.length - 1)) * 100}% - 2rem)`
: "0%",
}}
/>
<div className="relative flex justify-between">
{WORKFLOW_STAGES.map((stage, idx) => {
const Icon = STAGE_ICONS[idx] ?? FileText;
const isCompleted = !isTerminal && idx < currentStage;
const isActive = !isTerminal && idx === currentStage;
return (
<div
key={stage.label}
className="flex max-w-[4.5rem] flex-col items-center gap-2.5 sm:max-w-none"
>
<div
className={cn(
"flex size-10 items-center justify-center rounded-full border-2 bg-card transition-all duration-300",
isCompleted &&
"border-primary bg-primary text-primary-foreground shadow-sm",
isActive &&
"scale-110 border-primary bg-background text-primary shadow-md ring-4 ring-primary/15",
!isCompleted &&
!isActive &&
"border-border text-muted-foreground",
)}
>
{isCompleted ? (
<CheckCircle2 className="size-4" />
) : (
<Icon className="size-4" />
)}
</div>
<span
className={cn(
"text-center text-[10px] font-bold uppercase leading-tight tracking-wide",
isActive ? "text-primary" : "text-muted-foreground",
)}
>
{stage.label}
</span>
</div>
);
})}
</div>
</div>
<div
className={cn(
"rounded-xl border px-5 py-4",
isTerminal
? "border-destructive/20 bg-destructive/5"
: "border-primary/15 bg-primary/[0.04]",
)}
>
<h4
className={cn("text-sm font-bold tracking-tight", titleColor)}
>
{title}
</h4>
<p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">
{description}
</p>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,107 @@
import { useEffect, useRef, useState } from "react";
import { Eraser } from "lucide-react";
import { Button } from "@edr/ui-common";
import { cn } from "@/lib/utils";
interface ContractSignaturePadProps {
onChange: (dataUrl: string | null) => void;
className?: string;
}
export function ContractSignaturePad({
onChange,
className,
}: ContractSignaturePadProps) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const drawing = useRef(false);
const [empty, setEmpty] = useState(true);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
const dpr = window.devicePixelRatio || 1;
const w = canvas.offsetWidth;
const h = canvas.offsetHeight;
canvas.width = w * dpr;
canvas.height = h * dpr;
ctx.scale(dpr, dpr);
ctx.strokeStyle = "#111";
ctx.lineWidth = 2;
ctx.lineCap = "round";
}, []);
const getPos = (e: React.MouseEvent | React.TouchEvent) => {
const canvas = canvasRef.current!;
const rect = canvas.getBoundingClientRect();
if ("touches" in e) {
const t = e.touches[0];
return { x: t.clientX - rect.left, y: t.clientY - rect.top };
}
return { x: e.clientX - rect.left, y: e.clientY - rect.top };
};
const start = (e: React.MouseEvent | React.TouchEvent) => {
drawing.current = true;
const ctx = canvasRef.current?.getContext("2d");
const { x, y } = getPos(e);
ctx?.beginPath();
ctx?.moveTo(x, y);
};
const move = (e: React.MouseEvent | React.TouchEvent) => {
if (!drawing.current) return;
const ctx = canvasRef.current?.getContext("2d");
const { x, y } = getPos(e);
ctx?.lineTo(x, y);
ctx?.stroke();
setEmpty(false);
onChange(canvasRef.current?.toDataURL("image/png") ?? null);
};
const end = () => {
drawing.current = false;
};
const clear = () => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
setEmpty(true);
onChange(null);
};
return (
<div className={cn("space-y-2", className)}>
<div className="overflow-hidden rounded-lg border-2 border-dashed border-border bg-white">
<canvas
ref={canvasRef}
className="h-36 w-full touch-none cursor-crosshair"
onMouseDown={start}
onMouseMove={move}
onMouseUp={end}
onMouseLeave={end}
onTouchStart={start}
onTouchMove={move}
onTouchEnd={end}
/>
</div>
<div className="flex items-center justify-between">
<p className="text-xs text-muted-foreground">
Draw your signature above
</p>
<Button type="button" variant="ghost" size="sm" className="gap-1" onClick={clear}>
<Eraser className="size-3.5" />
Clear
</Button>
</div>
{empty && (
<p className="text-xs text-amber-700">Signature is required before confirming.</p>
)}
</div>
);
}

View File

@@ -0,0 +1,32 @@
/** Shared surfaces for booking list & detail — aligned with rule-engine polish. */
export const bookingSurface = {
page: "min-h-screen bg-gradient-to-b from-muted/40 via-background to-background",
pageInner: "mx-auto max-w-[1600px] space-y-6 p-6 lg:p-8",
hero:
"relative overflow-hidden rounded-2xl border border-border/80 bg-card shadow-sm",
heroGlow:
"pointer-events-none absolute -right-20 -top-20 size-64 rounded-full bg-primary/10 blur-3xl",
panel:
"overflow-hidden rounded-xl border border-border bg-card shadow-sm",
panelToolbar:
"flex flex-wrap items-center justify-between gap-3 border-b border-border bg-muted/25 px-4 py-3.5 sm:px-5",
tableWrap: "px-0",
sectionCard:
"overflow-hidden rounded-xl border border-border bg-card shadow-sm transition-shadow hover:shadow-md",
sectionHeader:
"flex items-center gap-3 border-b border-border/60 bg-muted/20 px-5 py-4",
sectionBody: "px-5 py-5",
detailHero:
"relative overflow-hidden rounded-2xl border border-border bg-gradient-to-br from-card via-card to-primary/[0.04] shadow-sm",
stickySidebar: "lg:sticky lg:top-6 lg:self-start",
metricTile:
"rounded-lg border border-border/70 bg-background/80 px-4 py-3 shadow-xs",
emptyState:
"flex flex-col items-center justify-center gap-3 px-6 py-16 text-center",
} as const;
export const bookingInput = {
search:
"h-10 w-full rounded-lg border border-input bg-background pl-10 text-sm shadow-xs transition-[box-shadow,border-color] placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/25 sm:max-w-xs",
} as const;

View File

@@ -0,0 +1,132 @@
import { useCallback, useState } from "react";
import {
getBookingActions,
getNextPendingApprovalStep,
type BookingActionContext,
type BookingActionDef,
} from "@/features/bookings/booking-actions.config";
import { useBookingDetail, useBookingMutations } from "@/hooks/bookings/useBookings";
export function useBookingActionDialog(
bookingId: string,
context: BookingActionContext,
) {
const [pendingAction, setPendingAction] = useState<BookingActionDef | null>(null);
const [inputValue, setInputValue] = useState("");
const [dialogOpen, setDialogOpen] = useState(false);
const needsApprovalSteps =
pendingAction?.id === "approve" || pendingAction?.id === "rejectApproval";
const { data: detail, isLoading: detailLoading } = useBookingDetail(
needsApprovalSteps ? bookingId : undefined,
);
const mergedContext: BookingActionContext = {
...context,
approvalSteps: detail?.approvalSteps ?? context.approvalSteps,
reference: detail?.reference ?? context.reference,
};
const mutations = useBookingMutations(bookingId);
const actions = getBookingActions(mergedContext);
const openAction = useCallback((action: BookingActionDef) => {
setPendingAction(action);
setInputValue("");
setDialogOpen(true);
}, []);
const closeDialog = useCallback(() => {
setDialogOpen(false);
setPendingAction(null);
setInputValue("");
}, []);
const runAction = useCallback(() => {
if (!pendingAction) return;
const onSuccess = () => closeDialog();
switch (pendingAction.id) {
case "accept":
mutations.staffAccept.mutate(undefined, { onSuccess });
break;
case "requestChanges":
mutations.requestChanges.mutate(inputValue.trim(), { onSuccess });
break;
case "reject":
mutations.staffReject.mutate(inputValue.trim(), { onSuccess });
break;
case "approve": {
const step = getNextPendingApprovalStep(mergedContext.approvalSteps);
if (!step) return;
mutations.approveStep.mutate(
{ stepId: step.id, requiredRole: step.requiredRole },
{ onSuccess },
);
break;
}
case "rejectApproval": {
const step = getNextPendingApprovalStep(mergedContext.approvalSteps);
if (!step) return;
mutations.rejectStep.mutate(
{ stepId: step.id, reason: inputValue.trim() },
{ onSuccess },
);
break;
}
case "generateContract":
mutations.generateContract.mutate(undefined, { onSuccess });
break;
case "viewContract":
break;
case "generatePnr":
mutations.generatePnr.mutate(undefined, { onSuccess });
break;
case "verifyPayment":
mutations.verifyPayment.mutate(undefined, { onSuccess });
break;
case "startTransit":
mutations.startTransit.mutate(undefined, { onSuccess });
break;
case "complete":
mutations.complete.mutate(undefined, { onSuccess });
break;
default:
break;
}
}, [
pendingAction,
inputValue,
mergedContext.approvalSteps,
mutations,
closeDialog,
]);
const confirmDisabled =
mutations.isPending ||
(needsApprovalSteps && detailLoading) ||
(pendingAction?.id === "approve" &&
!getNextPendingApprovalStep(mergedContext.approvalSteps));
return {
actions,
pendingAction,
inputValue,
setInputValue,
dialogOpen,
setDialogOpen: (open: boolean) => {
if (!open) closeDialog();
else setDialogOpen(true);
},
openAction,
closeDialog,
runAction,
mutations,
confirmDisabled,
detailLoading,
mergedContext,
};
}

View File

@@ -3,6 +3,7 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { LoadCargoDialog } from './LoadCargoDialog';
import type { Cargo } from '@/services/cargoService';
export function CargoesTable({ containerId }: { containerId: string }) {
const { data: cargoes, refetch } = useCargoesByContainer(containerId);
@@ -24,7 +25,7 @@ export function CargoesTable({ containerId }: { containerId: string }) {
</TableRow>
</TableHeader>
<TableBody>
{cargoes.map(cargo => (
{cargoes.map((cargo: Cargo) => (
<TableRow key={cargo.id}>
<TableCell>{cargo.cargoReference}</TableCell>
<TableCell>{cargo.description || '-'}</TableCell>
@@ -41,4 +42,5 @@ export function CargoesTable({ containerId }: { containerId: string }) {
</TableBody>
</Table>
);
}
}

View File

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

View File

@@ -61,5 +61,45 @@ export const formatCell = (value: unknown, format?: ColumnFormat): ReactNode =>
return Number.isNaN(d.getTime()) ? String(value) : d.toLocaleDateString();
}
if (format === "entityLabel" && value && typeof value === "object") {
const entity = value as { label?: string; code?: string; cargoTypeName?: string };
const label =
entity.label?.trim() ||
entity.cargoTypeName?.trim() ||
entity.code?.trim();
return label ? (
<span>{label}</span>
) : (
<span className="text-muted-foreground"></span>
);
}
if (format === "rateLabel") {
if (!value || typeof value !== "object") {
return value ? (
<span className="font-mono text-xs text-muted-foreground">{String(value)}</span>
) : (
<span className="text-muted-foreground"></span>
);
}
const rate = value as {
rateType?: string;
currency?: string;
rateValue?: number;
rateUnit?: string;
};
const parts = [
rate.rateType?.replace(/_/g, " "),
rate.currency,
rate.rateValue != null ? String(rate.rateValue) : "",
rate.rateUnit?.replace(/_/g, " "),
].filter(Boolean);
return parts.length > 0 ? (
<span>{parts.join(" · ")}</span>
) : (
<span className="text-muted-foreground"></span>
);
}
return String(value);
};

View File

@@ -0,0 +1,47 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { Slot } from "radix-ui";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary: "bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90",
outline:
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
link: "text-primary underline-offset-4 [a&]:hover:underline",
},
},
defaultVariants: {
variant: "default",
},
},
);
function Badge({
className,
variant = "default",
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "span";
return (
<Comp
data-slot="badge"
data-variant={variant}
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
);
}
export { Badge, badgeVariants };

View File

@@ -0,0 +1,8 @@
export * from './table';
export * from './badge';
export * from './button';
export * from './dialog';
export * from './input';
export * from './label';
export * from './textarea';
export * from './Breadcrumbs';

View File

@@ -0,0 +1,114 @@
import * as React from "react";
import { cn } from "@/lib/utils";
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
);
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b outline-ring/50", className)}
{...props}
/>
);
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
);
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className,
)}
{...props}
/>
);
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"border-b transition-colors bg-background hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
className,
)}
{...props}
/>
);
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"h-10 bg-muted first-of-type:pl-4 last-of-type:pr-4 first-of-type: p-2 py-4 text-left align-middle font-medium whitespace-nowrap text-secondary-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle first-of-type:pl-4 last-of-type:pr-4 whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
);
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
};

View File

@@ -0,0 +1,50 @@
import type { BookingListFilter } from "@/services/bookings.service";
import type { RuleEngineListParams } from "@/services/ruleEngine/ruleEngine.service";
import type { RuleEngineResourceSlug } from "@/types/rule-engine";
export const QUERY_KEYS = {
USERS: {
ROOT: ["users"] as const,
ADD: ["users", "add"] as const,
},
FILES: {
ROOT: ["file-upload-settings"] as const,
list: () => ["file-upload-settings", "list"] as const,
byId: (id: string) => ["file-upload-settings", "detail", id] as const,
byCode: (code: string) => ["file-upload-settings", "by-code", code] as const,
},
DROPDOWN_SETTINGS: {
ROOT: ["dropdown-settings"] as const,
list: () => ["dropdown-settings", "list"] as const,
byId: (id: string) => ["dropdown-settings", "detail", id] as const,
byCode: (code: string) => ["dropdown-settings", "by-code", code] as const,
},
CUSTOMERS: {
ROOT: ["customers"] as const,
list: () => ["customers", "list"] as const,
byId: (id: string) => ["customers", "detail", id] as const,
},
BOOKINGS: {
ROOT: ["bookings"] as const,
list: (filter?: BookingListFilter) =>
["bookings", "list", filter ?? {}] as const,
byId: (id: string) => ["bookings", "detail", id] as const,
},
RULE_ENGINE: {
ROOT: ["rule-engine"] as const,
list: (resource: RuleEngineResourceSlug | string, params?: RuleEngineListParams) =>
["rule-engine", "list", resource, params ?? {}] as const,
detail: (resource: RuleEngineResourceSlug | string, id: string) =>
["rule-engine", "detail", resource, id] as const,
chain: ["rule-engine", "approval-rules", "chain"] as const,
selectOptions: (
resource: RuleEngineResourceSlug | string,
params?: Record<string, unknown>,
) => ["rule-engine", "select-options", resource, params ?? {}] as const,
},
} as const;

View File

@@ -1,25 +0,0 @@
export const QUERY_KEYS = {
USERS: "users",
ADD_USER: "add_user",
CUSTOMER: "Customers",
FILES: {
FILE_UPLOAD_SETTINGS: "file-upload-settings",
BY_CODE: "by-code"
},
DROPDOWN_SETTINGS: {
ROOT: "dropdown-settings",
LIST: "list",
BY_ID: "by-id",
BY_CODE: "by-code"
},
CUSTOMERS: {
ROOT: "customers",
LIST: "list",
BY_ID: "by-id"
},
RULE_ENGINE: {
ROOT: "rule-engine",
list: (resource: string) => ["rule-engine", resource, "list"] as const,
chain: ["rule-engine", "approval-rules", "chain"] as const,
},
}

View File

@@ -77,9 +77,33 @@ export const URL_CONSTANTS = {
BOOKINGS: {
BASE: "/bookings",
BY_ID: (id: string | number) => `/bookings/${id}`,
CANCEL: (id: string | number) => `/bookings/${id}/cancel`,
CONFIRM: (id: string | number) => `/bookings/${id}/confirm`,
BY_ID: (id: string) => `/bookings/${id}`,
QUEUE: (queue: string) => `/bookings/queues/${queue}`,
STAFF_ACCEPT: (id: string) => `/bookings/${id}/staff/accept`,
STAFF_REQUEST_CHANGES: (id: string) =>
`/bookings/${id}/staff/request-changes`,
STAFF_REJECT: (id: string) => `/bookings/${id}/staff/reject`,
APPROVE_STEP: (id: string, stepId: string) =>
`/bookings/${id}/approval-steps/${stepId}/approve`,
REJECT_STEP: (id: string, stepId: string) =>
`/bookings/${id}/approval-steps/${stepId}/reject`,
CONTRACT_GENERATE: (id: string) => `/bookings/${id}/contract/generate`,
CONTRACT_VIEW: (id: string) => `/bookings/${id}/contract/view`,
CONTRACT_DOCUMENT: (id: string) => `/bookings/${id}/contract/document`,
CONTRACT_SIGN: (id: string) => `/bookings/${id}/contract/sign`,
CONTRACT_DOWNLOAD: (id: string) => `/bookings/${id}/contract`,
SUMMARY: (id: string) => `/bookings/${id}/summary`,
CUSTOMER_SIGN: (id: string) => `/bookings/${id}/customer/sign`,
MARKETING_APPROVE: (id: string) => `/bookings/${id}/marketing/approve`,
PAYMENT_PNR: (id: string) => `/bookings/${id}/payment/pnr`,
PAYMENT_PROOF: (id: string) => `/bookings/${id}/payment/proof`,
PAYMENT_VERIFY: (id: string) => `/bookings/${id}/payment/verify`,
PAYMENT_REQUEST_LETTER: (id: string) =>
`/bookings/${id}/payment/request-letter`,
START_TRANSIT: (id: string) => `/bookings/${id}/operations/start-transit`,
COMPLETE: (id: string) => `/bookings/${id}/operations/complete`,
CANCEL: (id: string) => `/bookings/${id}/cancel`,
CONSOLIDATION: (id: string) => `/bookings/${id}/consolidation`,
},
OTP: {

View File

@@ -0,0 +1,268 @@
import type { LucideIcon } from "lucide-react";
import {
Ban,
Check,
FileSignature,
FileText,
MessageSquareWarning,
Play,
ShieldCheck,
Truck,
Wallet,
XCircle,
} from "lucide-react";
import type {
BookingApprovalStep,
BookingDetail,
BookingStatus,
} from "@/types/booking";
export type BookingActionId =
| "accept"
| "requestChanges"
| "reject"
| "approve"
| "rejectApproval"
| "generateContract"
| "viewContract"
| "generatePnr"
| "verifyPayment"
| "startTransit"
| "complete";
export type BookingActionInputKind = "note" | "reason";
export interface BookingActionDef {
id: BookingActionId;
label: string;
shortLabel: string;
description: string;
confirmTitle: string;
confirmDescription: string;
variant: "default" | "destructive" | "outline";
icon: LucideIcon;
input?: BookingActionInputKind;
inputLabel?: string;
inputPlaceholder?: string;
primary?: boolean;
}
export type BookingActionContext = Pick<
BookingDetail,
"status" | "paymentCurrency" | "approvalSteps" | "reference"
>;
export function getNextPendingApprovalStep(
steps?: BookingApprovalStep[] | null,
): BookingApprovalStep | undefined {
if (!steps?.length) return undefined;
return [...steps]
.sort((a, b) => a.stepOrder - b.stepOrder)
.find((s) => s.status === "PENDING");
}
function approvalActions(
steps?: BookingApprovalStep[] | null,
): BookingActionDef[] {
const next = getNextPendingApprovalStep(steps);
if (!next) return [];
return [
{
id: "approve",
label: `Approve (${next.requiredRole})`,
shortLabel: "Approve",
description: `Complete step ${next.stepOrder} as ${next.requiredRole}`,
confirmTitle: `Approve as ${next.requiredRole}?`,
confirmDescription:
"This records your approval and advances the booking to the next step in the chain.",
variant: "default",
icon: Check,
primary: true,
},
{
id: "rejectApproval",
label: "Reject approval",
shortLabel: "Reject",
description: "Reject at the current approval step",
confirmTitle: "Reject at approval step?",
confirmDescription:
"The booking will be marked rejected. This action cannot be undone from the UI.",
variant: "destructive",
icon: XCircle,
input: "reason",
inputLabel: "Rejection reason",
inputPlaceholder: "Explain why this booking is rejected…",
},
];
}
const SUBMITTED_ACTIONS: BookingActionDef[] = [
{
id: "accept",
label: "Accept for approval",
shortLabel: "Accept",
description: "Start the formal approval chain",
confirmTitle: "Accept submission?",
confirmDescription:
"The booking moves to pending approval and approval steps are created from the rule engine.",
variant: "default",
icon: ShieldCheck,
primary: true,
},
{
id: "requestChanges",
label: "Request changes",
shortLabel: "Changes",
description: "Ask the customer to update and resubmit",
confirmTitle: "Request changes from customer?",
confirmDescription:
"The customer will see your note and can edit the booking before resubmitting.",
variant: "outline",
icon: MessageSquareWarning,
input: "note",
inputLabel: "Message to customer",
inputPlaceholder: "Describe what needs to be corrected or added…",
},
{
id: "reject",
label: "Reject booking",
shortLabel: "Reject",
description: "Reject this submission",
confirmTitle: "Reject booking?",
confirmDescription:
"The booking will be marked rejected and removed from active queues.",
variant: "destructive",
icon: Ban,
input: "reason",
inputLabel: "Rejection reason",
inputPlaceholder: "Reason for rejection…",
},
];
/** Actions available for the current booking status (detail or list). */
export function getBookingActions(ctx: BookingActionContext): BookingActionDef[] {
const { status, paymentCurrency, approvalSteps } = ctx;
switch (status) {
case "SUBMITTED":
return SUBMITTED_ACTIONS;
case "PENDING_APPROVAL":
case "APPROVED_PENDING_SIGNATURE":
return approvalActions(approvalSteps);
case "APPROVED":
return [
{
id: "generateContract",
label: "Generate contract",
shortLabel: "Contract",
description: "Create contract document",
confirmTitle: "Generate contract?",
confirmDescription:
"A contract will be generated and the booking moves to contract ready.",
variant: "default",
icon: FileText,
primary: true,
},
];
case "CONTRACT_READY":
case "SIGNED_CUSTOMER":
case "FULLY_EXECUTED":
return [
{
id: "viewContract",
label:
status === "SIGNED_CUSTOMER"
? "View & sign contract (staff)"
: status === "CONTRACT_READY"
? "View contract"
: "View executed contract",
shortLabel: "Contract",
description: "Open contract document and signatures",
confirmTitle: "",
confirmDescription: "",
variant: "default",
icon: FileSignature,
primary: true,
},
];
case "FULLY_EXECUTED":
if (paymentCurrency === "ETB") {
return [
{
id: "generatePnr",
label: "Generate PNR",
shortLabel: "PNR",
description: "Issue PNR for ETB bank payment",
confirmTitle: "Generate PNR?",
confirmDescription:
"A payment reference number will be issued for the customer.",
variant: "default",
icon: Wallet,
primary: true,
},
];
}
return [];
case "PAYMENT_VERIFICATION_IN_PROGRESS":
return [
{
id: "verifyPayment",
label: "Verify payment",
shortLabel: "Verify",
description: "Confirm USD payment proof",
confirmTitle: "Verify payment?",
confirmDescription:
"Finance confirms the uploaded proof and marks the booking as paid.",
variant: "default",
icon: Check,
primary: true,
},
];
case "PAID":
case "PNR_GENERATED":
return [
{
id: "startTransit",
label: "Start transit",
shortLabel: "Transit",
description: "Begin rail movement",
confirmTitle: "Start transit?",
confirmDescription: "The booking will move to in transit status.",
variant: "default",
icon: Truck,
primary: true,
},
];
case "IN_TRANSIT":
return [
{
id: "complete",
label: "Complete booking",
shortLabel: "Complete",
description: "Mark journey finished",
confirmTitle: "Complete booking?",
confirmDescription:
"Marks the booking as completed. No further staff transitions apply.",
variant: "default",
icon: Play,
primary: true,
},
];
default:
return [];
}
}
export function listRowHasActions(row: {
status: BookingStatus;
paymentCurrency: string;
}): boolean {
const actions = getBookingActions({
status: row.status,
paymentCurrency: row.paymentCurrency,
reference: "",
});
if (actions.length > 0) return true;
return row.status === "FULLY_EXECUTED" && row.paymentCurrency === "USD";
}

View File

@@ -0,0 +1,260 @@
import type { BookingStatus } from "@/types/booking";
export interface StatusStyle {
label: string;
color: string;
}
export const BOOKING_STATUS_STYLES: Record<string, StatusStyle> = {
DRAFT: {
label: "Draft",
color: "bg-slate-100 text-slate-700 border-slate-300",
},
SUBMITTED: {
label: "Submitted",
color: "bg-amber-50 text-amber-700 border-amber-200",
},
CHANGES_REQUESTED: {
label: "Changes Requested",
color: "bg-orange-50 text-orange-700 border-orange-200",
},
PENDING_APPROVAL: {
label: "Pending Approval",
color: "bg-amber-50 text-amber-700 border-amber-200",
},
APPROVED_PENDING_SIGNATURE: {
label: "Pending Signature",
color: "bg-sky-50 text-sky-700 border-sky-200",
},
APPROVED: {
label: "Approved",
color: "bg-emerald-50 text-emerald-700 border-emerald-200",
},
CONTRACT_READY: {
label: "Contract Ready",
color: "bg-indigo-50 text-indigo-700 border-indigo-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",
},
PNR_GENERATED: {
label: "PNR Generated",
color: "bg-violet-50 text-violet-700 border-violet-200",
},
PAYMENT_VERIFICATION_IN_PROGRESS: {
label: "Payment Verification",
color: "bg-amber-50 text-amber-800 border-amber-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",
},
REJECTED: {
label: "Rejected",
color: "bg-red-50 text-red-700 border-red-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",
},
};
export interface StatusMeta {
title: string;
description: string;
color: string;
stage: number;
}
export const BOOKING_STATUS_META: Record<string, StatusMeta> = {
DRAFT: {
title: "Draft",
description: "Booking is being prepared by the customer.",
color: "text-slate-500",
stage: 0,
},
SUBMITTED: {
title: "Submitted",
description: "Awaiting staff review.",
color: "text-amber-600",
stage: 0,
},
CHANGES_REQUESTED: {
title: "Changes Requested",
description: "Returned to customer for updates.",
color: "text-orange-600",
stage: 0,
},
PENDING_APPROVAL: {
title: "Pending Approval",
description: "Moving through internal approval chain.",
color: "text-amber-600",
stage: 1,
},
APPROVED_PENDING_SIGNATURE: {
title: "Pending Signature",
description: "Awaiting director or CEO signature steps.",
color: "text-sky-600",
stage: 1,
},
APPROVED: {
title: "Approved",
description: "Ready to generate contract.",
color: "text-emerald-600",
stage: 2,
},
CONTRACT_READY: {
title: "Contract Ready",
description: "Contract generated; awaiting customer signature.",
color: "text-indigo-600",
stage: 2,
},
SIGNED_CUSTOMER: {
title: "Customer Signed",
description: "Awaiting contract execution.",
color: "text-sky-600",
stage: 2,
},
FULLY_EXECUTED: {
title: "Fully Executed",
description: "Contract locked; proceed to payment.",
color: "text-indigo-600",
stage: 3,
},
PNR_GENERATED: {
title: "PNR Generated",
description: "ETB payment reference issued.",
color: "text-violet-600",
stage: 3,
},
PAYMENT_VERIFICATION_IN_PROGRESS: {
title: "Payment Verification",
description: "USD payment proof under review.",
color: "text-amber-700",
stage: 3,
},
PAID: {
title: "Paid",
description: "Payment confirmed; ready for operations.",
color: "text-emerald-600",
stage: 4,
},
IN_TRANSIT: {
title: "In Transit",
description: "Shipment is on the railway network.",
color: "text-sky-600",
stage: 4,
},
COMPLETED: {
title: "Completed",
description: "Booking fulfilled.",
color: "text-indigo-600",
stage: 5,
},
REJECTED: {
title: "Rejected",
description: "Booking was rejected.",
color: "text-red-600",
stage: -1,
},
CANCELLED: {
title: "Cancelled",
description: "Booking was cancelled.",
color: "text-red-600",
stage: -1,
},
PENDING_CONSOLIDATION: {
title: "Pending Consolidation",
description: "Waiting for consolidation partner.",
color: "text-amber-600",
stage: 4,
},
CONSOLIDATED: {
title: "Consolidated",
description: "Paired with another booking.",
color: "text-indigo-600",
stage: 4,
},
};
export const BOOKING_LIST_TABS = [
{ key: "all", label: "All bookings", status: null },
{ key: "SUBMITTED", label: "Submitted", status: "SUBMITTED" },
{ key: "PENDING_APPROVAL", label: "Pending Approval", status: "PENDING_APPROVAL" },
{
key: "APPROVED_PENDING_SIGNATURE",
label: "Pending Signature",
status: "APPROVED_PENDING_SIGNATURE",
},
{ key: "SIGNED_CUSTOMER", label: "Customer Signed", status: "SIGNED_CUSTOMER" },
{
key: "PAYMENT_VERIFICATION_IN_PROGRESS",
label: "Payment Verification",
status: "PAYMENT_VERIFICATION_IN_PROGRESS",
},
] as const;
export type BookingStatusTabKey = (typeof BOOKING_LIST_TABS)[number]["key"];
export const WORKFLOW_STAGES = [
{ label: "Submission", statuses: ["DRAFT", "SUBMITTED", "CHANGES_REQUESTED"] },
{
label: "Approval",
statuses: ["PENDING_APPROVAL", "APPROVED_PENDING_SIGNATURE"],
},
{
label: "Contract",
statuses: ["APPROVED", "CONTRACT_READY", "SIGNED_CUSTOMER", "FULLY_EXECUTED"],
},
{
label: "Payment",
statuses: [
"PNR_GENERATED",
"PAYMENT_VERIFICATION_IN_PROGRESS",
"PAID",
],
},
{
label: "Operations",
statuses: ["IN_TRANSIT", "PENDING_CONSOLIDATION", "CONSOLIDATED"],
},
{ label: "Done", statuses: ["COMPLETED"] },
] as const;
export function getStatusMeta(status: BookingStatus | string): StatusMeta {
return (
BOOKING_STATUS_META[status] ?? {
title: status,
description: "",
color: "text-muted-foreground",
stage: 0,
}
);
}
export function getWorkflowStageIndex(status: BookingStatus | string): number {
const meta = getStatusMeta(status);
if (meta.stage < 0) return -1;
return meta.stage;
}

View File

@@ -0,0 +1,35 @@
import type { BookingDetail, BookingListRow } from "@/types/booking";
function labelFromRef(
ref?: { name?: string; label?: string; code?: string; companyName?: string },
fallback = "—",
): string {
if (!ref) return fallback;
return (
ref.companyName ??
ref.label ??
ref.name ??
ref.code ??
fallback
);
}
export function toBookingListRow(booking: BookingDetail): BookingListRow {
return {
id: booking.id,
reference: booking.reference,
customerLabel: labelFromRef(booking.company, booking.companyId),
// customerLabel: labelFromRef(booking.customer, booking.customerId),
status: booking.status,
scheduledDate: booking.scheduledDate,
totalAmount: Number(booking.totalAmount),
paymentCurrency: booking.paymentCurrency,
paymentStatus: booking.paymentStatus,
tradeDirection: booking.tradeDirection,
freightType: booking.freightType,
originLabel: labelFromRef(booking.originYard),
destinationLabel: labelFromRef(booking.destinationYard),
priorityScore: booking.priorityScore ?? 0,
createdAt: booking.createdAt,
};
}

View File

@@ -0,0 +1,178 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";
import { QUERY_KEYS } from "@/constants/QUERY_KEYS";
import { api } from "@/services/api";
import {
bookingsService,
type BookingListFilter,
} from "@/services/bookings.service";
import { invalidateBookingDetail } from "@/utils/queryInvalidation";
export function useBookingList(filter?: BookingListFilter, enabled = true) {
return useQuery({
queryKey: QUERY_KEYS.BOOKINGS.list(filter),
queryFn: () => bookingsService.list(filter),
enabled,
});
}
export function useBookingDetail(id: string | undefined) {
return useQuery({
queryKey: QUERY_KEYS.BOOKINGS.byId(id ?? ""),
queryFn: () => bookingsService.getById(id!),
enabled: Boolean(id),
});
}
export function useBookingMutations(bookingId: string) {
const qc = useQueryClient();
const onSuccess = (data: { id: string }, message: string) => {
toast.success(message);
void invalidateBookingDetail(qc, data.id);
};
const staffAccept = useMutation({
mutationFn: () => api.bookings.staffAccept.call({ id: bookingId }),
onSuccess: (data) => onSuccess(data, "Booking accepted for approval"),
onError: () => toast.error("Failed to accept booking"),
});
const requestChanges = useMutation({
mutationFn: (note: string) =>
api.bookings.requestChanges.call({ id: bookingId, note }),
onSuccess: (data) => onSuccess(data, "Changes requested from customer"),
onError: () => toast.error("Failed to request changes"),
});
const staffReject = useMutation({
mutationFn: (reason: string) =>
api.bookings.staffReject.call({ id: bookingId, reason }),
onSuccess: (data) => onSuccess(data, "Booking rejected"),
onError: () => toast.error("Failed to reject booking"),
});
const approveStep = useMutation({
mutationFn: ({
stepId,
requiredRole,
}: {
stepId: string;
requiredRole: string;
}) =>
api.bookings.approveStep.call({
id: bookingId,
stepId,
requiredRole,
}),
onSuccess: (data) => onSuccess(data, "Approval step completed"),
onError: () => toast.error("Failed to approve step"),
});
const rejectStep = useMutation({
mutationFn: ({
stepId,
reason,
}: {
stepId: string;
reason: string;
}) =>
api.bookings.rejectStep.call({
id: bookingId,
stepId,
reason,
}),
onSuccess: (data) => onSuccess(data, "Booking rejected at approval step"),
onError: () => toast.error("Failed to reject step"),
});
const generateContract = useMutation({
mutationFn: () => api.bookings.generateContract.call({ id: bookingId }),
onSuccess: (data) => onSuccess(data, "Contract generated"),
onError: () => toast.error("Failed to generate contract"),
});
const signContract = useMutation({
mutationFn: (payload: {
role: "CUSTOMER" | "STAFF";
signatureImageBase64: string;
signerDisplayName: string;
consentText?: string;
}) => bookingsService.signContract(bookingId, payload),
onSuccess: (data) => onSuccess(data, "Contract signed"),
onError: () => toast.error("Failed to sign contract"),
});
const generatePnr = useMutation({
mutationFn: () => api.bookings.generatePnr.call({ id: bookingId }),
onSuccess: (data) => onSuccess(data, "PNR generated"),
onError: () => toast.error("Failed to generate PNR"),
});
const submitPaymentProof = useMutation({
mutationFn: (file: File) =>
bookingsService.submitPaymentProof(bookingId, file),
onSuccess: (data) => onSuccess(data, "Payment proof uploaded"),
onError: () => toast.error("Failed to upload payment proof"),
});
const verifyPayment = useMutation({
mutationFn: () => api.bookings.verifyPayment.call({ id: bookingId }),
onSuccess: (data) => onSuccess(data, "Payment verified"),
onError: () => toast.error("Failed to verify payment"),
});
const startTransit = useMutation({
mutationFn: () => api.bookings.startTransit.call({ id: bookingId }),
onSuccess: (data) => onSuccess(data, "Marked in transit"),
onError: () => toast.error("Failed to start transit"),
});
const complete = useMutation({
mutationFn: () => api.bookings.complete.call({ id: bookingId }),
onSuccess: (data) => onSuccess(data, "Booking completed"),
onError: () => toast.error("Failed to complete booking"),
});
const cancel = useMutation({
mutationFn: (reason: string) =>
api.bookings.cancel.call({ id: bookingId, reason }),
onSuccess: (data) => onSuccess(data, "Booking cancelled"),
onError: () => toast.error("Failed to cancel booking"),
});
const isPending =
staffAccept.isPending ||
requestChanges.isPending ||
staffReject.isPending ||
approveStep.isPending ||
rejectStep.isPending ||
generateContract.isPending ||
signContract.isPending ||
generatePnr.isPending ||
submitPaymentProof.isPending ||
verifyPayment.isPending ||
startTransit.isPending ||
complete.isPending ||
cancel.isPending;
return {
staffAccept,
requestChanges,
staffReject,
approveStep,
rejectStep,
generateContract,
signContract,
generatePnr,
submitPaymentProof,
verifyPayment,
startTransit,
complete,
cancel,
isPending,
downloadContract: () => bookingsService.downloadContract(bookingId),
downloadPaymentLetter: () =>
bookingsService.downloadPaymentRequestLetter(bookingId),
};
}

View File

@@ -1,16 +0,0 @@
import { useQuery } from "@tanstack/react-query";
import { bookingsService } from "../services/bookings.service";
export const useBookings = () =>
useQuery({
queryKey: ["bookings"],
queryFn: bookingsService.list,
});
export const useBooking = (id: string) =>
useQuery({
queryKey: ["bookings", id],
queryFn: () => bookingsService.get(id),
enabled: Boolean(id),
});

View File

@@ -1,16 +0,0 @@
import { useQuery } from "@tanstack/react-query";
import { consignmentsService } from "../services/consignments.service";
export const useConsignments = () =>
useQuery({
queryKey: ["consignments"],
queryFn: consignmentsService.list,
});
export const useConsignment = (id: string) =>
useQuery({
queryKey: ["consignments", id],
queryFn: () => consignmentsService.get(id),
enabled: Boolean(id),
});

View File

@@ -1,50 +0,0 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { customersService } from "@/services/customers.service";
import type {
CreateCustomerDto,
UpdateCustomerDto,
} from "@/types/customers";
const KEY = ["customers"] as const;
export const useCustomers = () =>
useQuery({
queryKey: KEY,
queryFn: customersService.list,
});
export const useCustomer = (id: string | undefined) =>
useQuery({
queryKey: [...KEY, "id", id],
queryFn: () => customersService.getById(id!),
enabled: Boolean(id),
});
export const useCreateCustomer = () => {
const qc = useQueryClient();
return useMutation({
mutationFn: (dto: CreateCustomerDto) => customersService.create(dto),
onSuccess: () => qc.invalidateQueries({ queryKey: KEY }),
});
};
export const useUpdateCustomer = () => {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ id, dto }: { id: string; dto: UpdateCustomerDto }) =>
customersService.update(id, dto),
onSuccess: (_data, { id }) => {
qc.invalidateQueries({ queryKey: KEY });
qc.invalidateQueries({ queryKey: [...KEY, "id", id] });
},
});
};
export const useDeleteCustomer = () => {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: string) => customersService.remove(id),
onSuccess: () => qc.invalidateQueries({ queryKey: KEY }),
});
};

View File

@@ -1,10 +0,0 @@
import { useQuery } from "@tanstack/react-query";
import { trackingService } from "../services/tracking.service";
export const useTracking = (consignmentId: string) =>
useQuery({
queryKey: ["tracking", consignmentId],
queryFn: () => trackingService.forConsignment(consignmentId),
enabled: Boolean(consignmentId),
});

View File

@@ -1,17 +1,18 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";
import { QUERY_KEYS } from "@/constants/TANSTACK_QUEY_KEY";
import {
ruleEngineService,
type RuleEngineListParams,
} from "@/services/ruleEngine/ruleEngine.service";
import { QUERY_KEYS } from "@/constants/QUERY_KEYS";
import { api } from "@/services/api";
import { ruleEngineService, type RuleEngineListParams } from "@/services/ruleEngine/ruleEngine.service";
import { RULE_ENGINE_SELECT_NONE } from "@/pages/ruleEngine/config/resources";
import type {
ApproveRatePayload,
RuleEngineRecord,
RuleEngineResourceSlug,
} from "@/types/rule-engine";
import {
invalidateRuleEngineList,
patchRuleEngineListRecord,
} from "@/utils/queryInvalidation";
const CARGO_TYPE_PARENT_PAGE_SIZE = 500;
const CONTAINER_TYPE_OPTIONS_PAGE_SIZE = 500;
@@ -21,17 +22,13 @@ export const useRuleEngineList = (
params: RuleEngineListParams,
) =>
useQuery({
queryKey: [...QUERY_KEYS.RULE_ENGINE.list(resource), params],
queryFn: () => ruleEngineService.list<RuleEngineRecord>(resource, params),
queryKey: QUERY_KEYS.RULE_ENGINE.list(resource, params),
queryFn: () => ruleEngineService.list(resource, params),
});
export const useCargoTypeParentOptions = (excludeId?: string, enabled = true) =>
useQuery({
queryKey: [
...QUERY_KEYS.RULE_ENGINE.list("cargo-types"),
"parent-options",
excludeId ?? "",
],
queryKey: QUERY_KEYS.RULE_ENGINE.selectOptions("cargo-types"),
queryFn: () =>
ruleEngineService.list<RuleEngineRecord>("cargo-types", {
page: 1,
@@ -53,34 +50,72 @@ export const useCargoTypeParentOptions = (excludeId?: string, enabled = true) =>
},
});
export const useContainerTypeOptions = (enabled = true) =>
export function buildContainerTypeSelectOptions(
rows: RuleEngineRecord[],
includeNone: boolean,
): { label: string; value: string }[] {
const options = rows
.filter((row) => row.id)
.map((row) => {
const label = String(row.label ?? "").trim();
const code = String(row.code ?? "").trim();
const size = row.sizeFt ? `${String(row.sizeFt)}ft` : "";
const parts = [label || code || String(row.id), size].filter(Boolean);
return {
label: parts.join(" - "),
value: String(row.id),
};
});
if (!includeNone) return options;
return [{ label: "None", value: RULE_ENGINE_SELECT_NONE }, ...options];
}
export const useContainerTypeOptions = (
includeNone = true,
enabled = true,
) =>
useQuery({
queryKey: [
...QUERY_KEYS.RULE_ENGINE.list("container-types"),
"select-options",
],
queryKey: api.ruleEngine.list.queryKey(),
queryFn: () =>
ruleEngineService.list<RuleEngineRecord>("container-types", {
page: 1,
pageSize: CONTAINER_TYPE_OPTIONS_PAGE_SIZE,
api.ruleEngine.list.call({
resource: "container-types",
params: {
page: 1,
pageSize: CONTAINER_TYPE_OPTIONS_PAGE_SIZE,
},
}),
enabled,
select: (result) => {
const noneOption = { label: "None", value: RULE_ENGINE_SELECT_NONE };
const options = (result.data ?? []).map((row) => {
const label = String(row.label ?? "").trim();
const code = String(row.code ?? "").trim();
const size = row.sizeFt ? `${String(row.sizeFt)}ft` : "";
const parts = [label || code || String(row.id), size].filter(Boolean);
select: (result) =>
buildContainerTypeSelectOptions(result.data ?? [], includeNone),
});
return {
label: parts.join(" - "),
value: String(row.id),
};
});
const LIVE_RATE_PAGE_SIZE = 500;
return [noneOption, ...options];
},
export const useLiveRateOptions = (enabled = true) =>
useQuery({
queryKey: QUERY_KEYS.RULE_ENGINE.selectOptions("rates", { status: "LIVE" }),
queryFn: () =>
ruleEngineService.list<RuleEngineRecord>("rates", {
page: 1,
pageSize: LIVE_RATE_PAGE_SIZE,
status: "LIVE",
}),
enabled,
select: (result) =>
(result.data ?? [])
.filter((row) => row.id)
.map((row) => {
const rateType = String(row.rateType ?? "").replace(/_/g, " ");
const currency = String(row.currency ?? "");
const value = row.rateValue != null ? String(row.rateValue) : "";
const unit = row.rateUnit ? String(row.rateUnit).replace(/_/g, " ") : "";
const parts = [rateType, currency, value, unit].filter(Boolean);
return {
label: parts.join(" · "),
value: String(row.id),
};
}),
});
export const useApprovalChain = (enabled: boolean) =>
@@ -92,15 +127,14 @@ export const useApprovalChain = (enabled: boolean) =>
export const useRuleEngineMutations = (resource: RuleEngineResourceSlug) => {
const qc = useQueryClient();
const invalidate = () =>
qc.invalidateQueries({ queryKey: QUERY_KEYS.RULE_ENGINE.list(resource) });
const create = useMutation({
mutationFn: (payload: Record<string, unknown>) =>
ruleEngineService.create(resource, payload),
onSuccess: () => {
api.ruleEngine.create.call({ resource, payload }),
onSuccess: async (created) => {
toast.success("Created successfully");
invalidate();
patchRuleEngineListRecord(qc, resource, created);
await invalidateRuleEngineList(qc, resource);
},
onError: () => toast.error("Failed to create record"),
});
@@ -112,19 +146,21 @@ export const useRuleEngineMutations = (resource: RuleEngineResourceSlug) => {
}: {
id: string;
payload: Record<string, unknown>;
}) => ruleEngineService.update(resource, id, payload),
onSuccess: () => {
}) => api.ruleEngine.update.call({ resource, id, payload }),
onSuccess: async (updated) => {
toast.success("Updated successfully");
invalidate();
patchRuleEngineListRecord(qc, resource, updated);
await invalidateRuleEngineList(qc, resource);
},
onError: () => toast.error("Failed to update record"),
});
const remove = useMutation({
mutationFn: (id: string) => ruleEngineService.remove(resource, id),
onSuccess: () => {
mutationFn: (id: string) =>
api.ruleEngine.remove.call({ resource, id }),
onSuccess: async () => {
toast.success("Deleted successfully");
invalidate();
await invalidateRuleEngineList(qc, resource);
},
onError: () => toast.error("Failed to delete record"),
});
@@ -134,24 +170,23 @@ export const useRuleEngineMutations = (resource: RuleEngineResourceSlug) => {
export const useRateWorkflow = () => {
const qc = useQueryClient();
const invalidate = () =>
qc.invalidateQueries({ queryKey: QUERY_KEYS.RULE_ENGINE.list("rates") });
const submit = useMutation({
mutationFn: (id: string) => ruleEngineService.submitRate(id),
onSuccess: () => {
mutationFn: (id: string) => api.ruleEngine.submitRate.call({ id }),
onSuccess: async (updated) => {
toast.success("Rate submitted for approval");
invalidate();
patchRuleEngineListRecord(qc, "rates", updated);
await invalidateRuleEngineList(qc, "rates");
},
onError: () => toast.error("Failed to submit rate"),
});
const approve = useMutation({
mutationFn: ({ id, payload }: { id: string; payload: ApproveRatePayload }) =>
ruleEngineService.approveRate(id, payload),
onSuccess: () => {
mutationFn: (id: string) => api.ruleEngine.approveRate.call({ id }),
onSuccess: async (updated) => {
toast.success("Rate approved");
invalidate();
patchRuleEngineListRecord(qc, "rates", updated);
await invalidateRuleEngineList(qc, "rates");
},
onError: () => toast.error("Failed to approve rate"),
});

View File

@@ -0,0 +1,24 @@
import toast from 'react-hot-toast';
interface ToastOptions {
title?: string;
description?: string;
variant?: 'default' | 'destructive';
duration?: number;
}
export function useToast() {
const showToast = (options: ToastOptions) => {
const { title, description, variant = 'default', duration = 3000 } = options;
const message = title ? `${title}${description ? ': ' + description : ''}` : description || '';
if (variant === 'destructive') {
toast.error(message, { duration });
} else {
toast.success(message, { duration });
}
};
return { toast: showToast };
}

View File

@@ -0,0 +1,5 @@
export {
useBookingList,
useBookingDetail,
useBookingMutations,
} from "./bookings/useBookings";

View File

@@ -1,6 +1,6 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { dropdownSettingsService } from "@/services/dropdownSettings.service";
import { api } from "@/services/api";
import type {
CreateDropdownOptionDto,
CreateDropdownSettingDto,
@@ -8,38 +8,15 @@ import type {
UpdateDropdownSettingDto,
} from "@/types/dropdownSettings";
const KEY = ["dropdown-settings"] as const;
/* ------------------------------ Queries ------------------------------ */
export const useDropdownSettings = () =>
useQuery({
queryKey: KEY,
queryFn: dropdownSettingsService.list,
});
export const useDropdownSetting = (id: string) =>
useQuery({
queryKey: [...KEY, "id", id],
queryFn: () => dropdownSettingsService.getById(id),
enabled: Boolean(id),
});
export const useDropdownSettingByCode = (code: string) =>
useQuery({
queryKey: [...KEY, "code", code],
queryFn: () => dropdownSettingsService.getByCode(code),
enabled: Boolean(code),
});
/* ----------------------------- Mutations ----------------------------- */
export const useCreateDropdownSetting = () => {
const qc = useQueryClient();
return useMutation({
mutationFn: (dto: CreateDropdownSettingDto) =>
dropdownSettingsService.create(dto),
onSuccess: () => qc.invalidateQueries({ queryKey: KEY }),
api.dropdownSettings.create.call(dto),
onSuccess: () =>
qc.invalidateQueries({ queryKey: api.dropdownSettings.list.queryKey() }),
});
};
@@ -52,10 +29,12 @@ export const useUpdateDropdownSetting = () => {
}: {
id: string;
dto: UpdateDropdownSettingDto;
}) => dropdownSettingsService.update(id, dto),
}) => api.dropdownSettings.update.call({ id, dto }),
onSuccess: (_data, { id }) => {
qc.invalidateQueries({ queryKey: KEY });
qc.invalidateQueries({ queryKey: [...KEY, "id", id] });
qc.invalidateQueries({ queryKey: api.dropdownSettings.list.queryKey() });
qc.invalidateQueries({
queryKey: api.dropdownSettings.getById.queryKey({ id }),
});
},
});
};
@@ -63,8 +42,9 @@ export const useUpdateDropdownSetting = () => {
export const useDeleteDropdownSetting = () => {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: string) => dropdownSettingsService.remove(id),
onSuccess: () => qc.invalidateQueries({ queryKey: KEY }),
mutationFn: (id: string) => api.dropdownSettings.remove.call({ id }),
onSuccess: () =>
qc.invalidateQueries({ queryKey: api.dropdownSettings.list.queryKey() }),
});
};
@@ -77,10 +57,12 @@ export const useReplaceDropdownOptions = () => {
}: {
settingId: string;
options: CreateDropdownOptionDto[];
}) => dropdownSettingsService.replaceOptions(settingId, options),
}) => api.dropdownSettings.replaceOptions.call({ id: settingId, options }),
onSuccess: (_data, { settingId }) => {
qc.invalidateQueries({ queryKey: KEY });
qc.invalidateQueries({ queryKey: [...KEY, "id", settingId] });
qc.invalidateQueries({ queryKey: api.dropdownSettings.list.queryKey() });
qc.invalidateQueries({
queryKey: api.dropdownSettings.getById.queryKey({ id: settingId }),
});
},
});
};
@@ -94,10 +76,12 @@ export const useAddDropdownOption = () => {
}: {
settingId: string;
dto: CreateDropdownOptionDto;
}) => dropdownSettingsService.addOption(settingId, dto),
}) => api.dropdownSettings.addOption.call({ id: settingId, dto }),
onSuccess: (_data, { settingId }) => {
qc.invalidateQueries({ queryKey: KEY });
qc.invalidateQueries({ queryKey: [...KEY, "id", settingId] });
qc.invalidateQueries({ queryKey: api.dropdownSettings.list.queryKey() });
qc.invalidateQueries({
queryKey: api.dropdownSettings.getById.queryKey({ id: settingId }),
});
},
});
};
@@ -111,8 +95,9 @@ export const useUpdateDropdownOption = () => {
}: {
optionId: string;
dto: UpdateDropdownOptionDto;
}) => dropdownSettingsService.updateOption(optionId, dto),
onSuccess: () => qc.invalidateQueries({ queryKey: KEY }),
}) => api.dropdownSettings.updateOption.call({ optionId, dto }),
onSuccess: () =>
qc.invalidateQueries({ queryKey: api.dropdownSettings.list.queryKey() }),
});
};
@@ -120,7 +105,8 @@ export const useRemoveDropdownOption = () => {
const qc = useQueryClient();
return useMutation({
mutationFn: (optionId: string) =>
dropdownSettingsService.removeOption(optionId),
onSuccess: () => qc.invalidateQueries({ queryKey: KEY }),
api.dropdownSettings.removeOption.call({ optionId }),
onSuccess: () =>
qc.invalidateQueries({ queryKey: api.dropdownSettings.list.queryKey() }),
});
};

View File

@@ -1,6 +1,6 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { fileUploadSettingsService } from "@/services/fileUploadSettings.service";
import { api } from "@/services/api";
import type {
CreateFileUploadFieldDto,
CreateFileUploadSettingDto,
@@ -8,38 +8,17 @@ import type {
UpdateFileUploadSettingDto,
} from "@/types/fileUploadSettings";
const KEY = ["file-upload-settings"] as const;
/* ------------------------------ Queries ------------------------------ */
export const useFileUploadSettings = () =>
useQuery({
queryKey: KEY,
queryFn: fileUploadSettingsService.list,
});
export const useFileUploadSetting = (id: string) =>
useQuery({
queryKey: [...KEY, "id", id],
queryFn: () => fileUploadSettingsService.getById(id),
enabled: Boolean(id),
});
export const useFileUploadSettingByCode = (code: string) =>
useQuery({
queryKey: [...KEY, "code", code],
queryFn: () => fileUploadSettingsService.getByCode(code),
enabled: Boolean(code),
});
/* ----------------------------- Mutations ----------------------------- */
export const useCreateFileUploadSetting = () => {
const qc = useQueryClient();
return useMutation({
mutationFn: (dto: CreateFileUploadSettingDto) =>
fileUploadSettingsService.create(dto),
onSuccess: () => qc.invalidateQueries({ queryKey: KEY }),
api.fileUploadSettings.create.call(dto),
onSuccess: () =>
qc.invalidateQueries({
queryKey: api.fileUploadSettings.list.queryKey(),
}),
});
};
@@ -52,10 +31,14 @@ export const useUpdateFileUploadSetting = () => {
}: {
id: string;
dto: UpdateFileUploadSettingDto;
}) => fileUploadSettingsService.update(id, dto),
}) => api.fileUploadSettings.update.call({ id, dto }),
onSuccess: (_data, { id }) => {
qc.invalidateQueries({ queryKey: KEY });
qc.invalidateQueries({ queryKey: [...KEY, "id", id] });
qc.invalidateQueries({
queryKey: api.fileUploadSettings.list.queryKey(),
});
qc.invalidateQueries({
queryKey: api.fileUploadSettings.getById.queryKey({ id }),
});
},
});
};
@@ -63,8 +46,11 @@ export const useUpdateFileUploadSetting = () => {
export const useDeleteFileUploadSetting = () => {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: string) => fileUploadSettingsService.remove(id),
onSuccess: () => qc.invalidateQueries({ queryKey: KEY }),
mutationFn: (id: string) => api.fileUploadSettings.remove.call({ id }),
onSuccess: () =>
qc.invalidateQueries({
queryKey: api.fileUploadSettings.list.queryKey(),
}),
});
};
@@ -77,10 +63,14 @@ export const useReplaceFileUploadFields = () => {
}: {
settingId: string;
fields: CreateFileUploadFieldDto[];
}) => fileUploadSettingsService.replaceFields(settingId, fields),
}) => api.fileUploadSettings.replaceFields.call({ id: settingId, fields }),
onSuccess: (_data, { settingId }) => {
qc.invalidateQueries({ queryKey: KEY });
qc.invalidateQueries({ queryKey: [...KEY, "id", settingId] });
qc.invalidateQueries({
queryKey: api.fileUploadSettings.list.queryKey(),
});
qc.invalidateQueries({
queryKey: api.fileUploadSettings.getById.queryKey({ id: settingId }),
});
},
});
};
@@ -94,10 +84,14 @@ export const useAddFileUploadField = () => {
}: {
settingId: string;
dto: CreateFileUploadFieldDto;
}) => fileUploadSettingsService.addField(settingId, dto),
}) => api.fileUploadSettings.addField.call({ settingId, dto }),
onSuccess: (_data, { settingId }) => {
qc.invalidateQueries({ queryKey: KEY });
qc.invalidateQueries({ queryKey: [...KEY, "id", settingId] });
qc.invalidateQueries({
queryKey: api.fileUploadSettings.list.queryKey(),
});
qc.invalidateQueries({
queryKey: api.fileUploadSettings.getById.queryKey({ id: settingId }),
});
},
});
};
@@ -111,8 +105,11 @@ export const useUpdateFileUploadField = () => {
}: {
fieldId: string;
dto: UpdateFileUploadFieldDto;
}) => fileUploadSettingsService.updateField(fieldId, dto),
onSuccess: () => qc.invalidateQueries({ queryKey: KEY }),
}) => api.fileUploadSettings.updateField.call({ fieldId, dto }),
onSuccess: () =>
qc.invalidateQueries({
queryKey: api.fileUploadSettings.list.queryKey(),
}),
});
};
@@ -120,7 +117,10 @@ export const useRemoveFileUploadField = () => {
const qc = useQueryClient();
return useMutation({
mutationFn: (fieldId: string) =>
fileUploadSettingsService.removeField(fieldId),
onSuccess: () => qc.invalidateQueries({ queryKey: KEY }),
api.fileUploadSettings.removeField.call({ fieldId }),
onSuccess: () =>
qc.invalidateQueries({
queryKey: api.fileUploadSettings.list.queryKey(),
}),
});
};

View File

@@ -0,0 +1,12 @@
import { QueryClient } from "@tanstack/react-query";
/** Single app-wide React Query client (do not nest additional providers). */
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
refetchOnWindowFocus: false,
staleTime: 30_000,
},
},
});

View File

@@ -9,7 +9,8 @@ import { Toaster } from "react-hot-toast";
import App from "./App";
import { AuthProvider } from "./auth/AuthProvider";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { QueryClientProvider } from "@tanstack/react-query";
import { queryClient } from "./lib/queryClient";
const THEME_STORAGE_KEY = "edr-theme";
@@ -38,8 +39,6 @@ if (!rootElement) {
throw new Error("Root element not found");
}
const queryClient = new QueryClient();
createRoot(rootElement).render(
<QueryClientProvider client={queryClient}>

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" },
],

View File

@@ -0,0 +1,338 @@
import { QUERY_KEYS } from "@/constants/QUERY_KEYS";
import { endpoint } from "@/utils/endpoint";
import type {
CreateFileUploadFieldDto,
CreateFileUploadSettingDto,
FileUploadField,
FileUploadSetting,
UpdateFileUploadFieldDto,
UpdateFileUploadSettingDto,
} from "@/types/fileUploadSettings";
import {
CreateDropdownOptionDto,
CreateDropdownSettingDto,
DropdownOption,
DropdownSetting,
UpdateDropdownOptionDto,
UpdateDropdownSettingDto,
} from "@/types/dropdownSettings";
import {
RuleEngineListResult,
RuleEngineRecord,
RuleEngineResourceSlug,
} from "@/types/rule-engine";
import { fileUploadSettingsService } from "./fileUploadSettings.service";
import { dropdownSettingsService } from "./dropdownSettings.service";
import {
ruleEngineService,
RuleEngineListParams,
} from "./ruleEngine/ruleEngine.service";
import {
bookingsService,
BookingListFilter,
type ApproveStepPayload,
type PaginatedBookings,
type RejectStepPayload,
} from "./bookings.service";
import type { BookingDetail } from "@/types/booking";
export const api = {
fileUploadSettings: {
list: endpoint<void, FileUploadSetting[]>(
"file-upload-settings",
"list",
fileUploadSettingsService.list,
),
getById: endpoint<{ id: string }, FileUploadSetting>(
"file-upload-settings",
"getById",
({ id }) => fileUploadSettingsService.getById(id),
),
getByCode: endpoint<{ code: string }, FileUploadSetting>(
"file-upload-settings",
"getByCode",
({ code }) => fileUploadSettingsService.getByCode(code),
),
create: endpoint<CreateFileUploadSettingDto, FileUploadSetting>(
"file-upload-settings",
"create",
(payload) => fileUploadSettingsService.create(payload),
),
update: endpoint<
{ id: string; dto: UpdateFileUploadSettingDto },
FileUploadSetting
>("file-upload-settings", "update", ({ id, dto }) =>
fileUploadSettingsService.update(id, dto),
),
remove: endpoint<{ id: string }, void>(
"file-upload-settings",
"remove",
({ id }) => fileUploadSettingsService.remove(id),
),
replaceFields: endpoint<
{ id: string; fields: CreateFileUploadFieldDto[] },
FileUploadField[]
>("file-upload-settings", "replaceFields", ({ id, fields }) =>
fileUploadSettingsService.replaceFields(id, fields),
),
addField: endpoint<
{ settingId: string; dto: CreateFileUploadFieldDto },
FileUploadField
>("file-upload-settings", "addField", ({ settingId, dto }) =>
fileUploadSettingsService.addField(settingId, dto),
),
updateField: endpoint<
{ fieldId: string; dto: UpdateFileUploadFieldDto },
FileUploadField
>("file-upload-settings", "updateField", ({ fieldId, dto }) =>
fileUploadSettingsService.updateField(fieldId, dto),
),
removeField: endpoint<{ fieldId: string }, void>(
"file-upload-settings",
"removeField",
({ fieldId }) => fileUploadSettingsService.removeField(fieldId),
),
},
dropdownSettings: {
list: endpoint<void, DropdownSetting[]>(
"dropdown-settings",
"list",
dropdownSettingsService.list,
),
getById: endpoint<{ id: string }, DropdownSetting>(
"dropdown-settings",
"getById",
({ id }) => dropdownSettingsService.getById(id),
),
getByCode: endpoint<{ code: string }, DropdownSetting>(
"dropdown-settings",
"getByCode",
({ code }) => dropdownSettingsService.getByCode(code),
),
create: endpoint<CreateDropdownSettingDto, DropdownSetting>(
"dropdown-settings",
"create",
(payload) => dropdownSettingsService.create(payload),
),
update: endpoint<
{ id: string; dto: UpdateDropdownSettingDto },
DropdownSetting
>("dropdown-settings", "update", ({ id, dto }) =>
dropdownSettingsService.update(id, dto),
),
remove: endpoint<{ id: string }, void>(
"dropdown-settings",
"remove",
({ id }) => dropdownSettingsService.remove(id),
),
replaceOptions: endpoint<
{ id: string; options: CreateDropdownOptionDto[] },
DropdownOption[]
>("dropdown-settings", "replaceOptions", ({ id, options }) =>
dropdownSettingsService.replaceOptions(id, options),
),
addOption: endpoint<
{ id: string; dto: CreateDropdownOptionDto },
DropdownOption
>("dropdown-settings", "addOption", ({ id, dto }) =>
dropdownSettingsService.addOption(id, dto),
),
updateOption: endpoint<
{ optionId: string; dto: UpdateDropdownOptionDto },
DropdownOption
>("dropdown-settings", "updateOption", ({ optionId, dto }) =>
dropdownSettingsService.updateOption(optionId, dto),
),
removeOption: endpoint<{ optionId: string }, void>(
"dropdown-settings",
"removeOption",
({ optionId }) => dropdownSettingsService.removeOption(optionId),
),
},
ruleEngine: {
list: endpoint<
{ resource: RuleEngineResourceSlug; params?: RuleEngineListParams },
RuleEngineListResult<RuleEngineRecord>
>(
"rule-engine",
"list",
({ resource, params }) => ruleEngineService.list(resource, params),
({ resource, params }) => QUERY_KEYS.RULE_ENGINE.list(resource, params),
),
getById: endpoint<
{ resource: RuleEngineResourceSlug; id: string },
RuleEngineRecord
>(
"rule-engine",
"getById",
({ resource, id }) => ruleEngineService.getById(resource, id),
({ resource, id }) => QUERY_KEYS.RULE_ENGINE.detail(resource, id),
),
create: endpoint<
{ resource: RuleEngineResourceSlug; payload: Record<string, unknown> },
RuleEngineRecord
>("rule-engine", "create", ({ resource, payload }) =>
ruleEngineService.create(resource, payload),
),
update: endpoint<
{
resource: RuleEngineResourceSlug;
id: string;
payload: Record<string, unknown>;
},
RuleEngineRecord
>("rule-engine", "update", ({ resource, id, payload }) =>
ruleEngineService.update(resource, id, payload),
),
remove: endpoint<
{ resource: RuleEngineResourceSlug; id: string },
void
>("rule-engine", "remove", ({ resource, id }) =>
ruleEngineService.remove(resource, id),
),
submitRate: endpoint<{ id: string }, RuleEngineRecord>(
"rule-engine",
"submitRate",
({ id }) => ruleEngineService.submitRate(id),
),
approveRate: endpoint<{ id: string }, RuleEngineRecord>(
"rule-engine",
"approveRate",
({ id }) => ruleEngineService.approveRate(id),
),
getApprovalChain: endpoint<void, RuleEngineRecord[]>(
"rule-engine",
"getApprovalChain",
() => ruleEngineService.getApprovalChain(),
() => QUERY_KEYS.RULE_ENGINE.chain,
),
},
bookings: {
list: endpoint<{ filter?: BookingListFilter }, PaginatedBookings>(
"bookings",
"list",
({ filter }) => bookingsService.list(filter),
({ filter }) => QUERY_KEYS.BOOKINGS.list(filter),
),
getById: endpoint<{ id: string }, BookingDetail>(
"bookings",
"getById",
({ id }) => bookingsService.getById(id),
({ id }) => QUERY_KEYS.BOOKINGS.byId(id),
),
remove: endpoint<{ id: string }, void>(
"bookings",
"remove",
({ id }) => bookingsService.remove(id),
),
staffAccept: endpoint<{ id: string }, BookingDetail>(
"bookings",
"staffAccept",
({ id }) => bookingsService.staffAccept(id),
),
requestChanges: endpoint<{ id: string; note: string }, BookingDetail>(
"bookings",
"requestChanges",
({ id, note }) => bookingsService.requestChanges(id, note),
),
staffReject: endpoint<{ id: string; reason: string }, BookingDetail>(
"bookings",
"staffReject",
({ id, reason }) => bookingsService.staffReject(id, reason),
),
approveStep: endpoint<ApproveStepPayload, BookingDetail>(
"bookings",
"approveStep",
(payload) => bookingsService.approveStep(payload),
),
rejectStep: endpoint<RejectStepPayload, BookingDetail>(
"bookings",
"rejectStep",
(payload) => bookingsService.rejectStep(payload),
),
generateContract: endpoint<{ id: string }, BookingDetail>(
"bookings",
"generateContract",
({ id }) => bookingsService.generateContract(id),
),
getContractView: endpoint<{ id: string }, import("./bookings.service").ContractView>(
"bookings",
"getContractView",
({ id }) => bookingsService.getContractView(id),
),
signContract: endpoint<
{ id: string } & import("./bookings.service").SignContractPayload,
BookingDetail
>("bookings", "signContract", ({ id, ...payload }) =>
bookingsService.signContract(id, payload),
),
generatePnr: endpoint<{ id: string }, BookingDetail>(
"bookings",
"generatePnr",
({ id }) => bookingsService.generatePnr(id),
),
verifyPayment: endpoint<{ id: string }, BookingDetail>(
"bookings",
"verifyPayment",
({ id }) => bookingsService.verifyPayment(id),
),
startTransit: endpoint<{ id: string }, BookingDetail>(
"bookings",
"startTransit",
({ id }) => bookingsService.startTransit(id),
),
complete: endpoint<{ id: string }, BookingDetail>(
"bookings",
"complete",
({ id }) => bookingsService.complete(id),
),
cancel: endpoint<{ id: string; reason: string }, BookingDetail>(
"bookings",
"cancel",
({ id, reason }) => bookingsService.cancel(id, reason),
),
},
};

View File

@@ -0,0 +1,173 @@
import { api as client } from "../auth/http";
import { unwrap } from "@/utils/endpoint";
import { URL_CONSTANTS } from "@/constants/URLS";
import type { BookingDetail } from "@/types/booking";
const B = URL_CONSTANTS.BOOKINGS;
export interface BookingListFilter {
status?: string;
// customerId?: string;
companyId?: string;
freightType?: string;
tradeDirection?: string;
paymentCurrency?: string;
page?: number;
pageSize?: number;
sortBy?: string;
sortOrder?: "ASC" | "DESC";
}
export interface PaginatedBookings {
items: BookingDetail[];
total: number;
}
export interface ApproveStepPayload {
id: string;
stepId: string;
requiredRole: string;
}
export interface RejectStepPayload {
id: string;
stepId: string;
reason: string;
}
export interface ContractView {
bookingId: string;
reference: string;
status: string;
templateKey: string;
title: string;
html: string;
canSignCustomer: boolean;
canSignStaff: boolean;
hasContractDocument: boolean;
signatures: Array<{
role: string;
signerDisplayName: string;
signedAt: string;
signatureImageUrl?: string | null;
}>;
}
export interface SignContractPayload {
role: "CUSTOMER" | "STAFF";
signatureImageBase64: string;
signerDisplayName: string;
consentText?: string;
}
async function postBooking<T>(url: string, body?: unknown): Promise<T> {
const response = await client.post<T>(url, body ?? {});
return unwrap(response.data);
}
export const bookingsService = {
list: async (filter?: BookingListFilter): Promise<PaginatedBookings> => {
const response = await client.get<PaginatedBookings>(B.BASE, {
params: filter,
});
const data = unwrap(response.data);
return {
items: (data.items ?? []) as BookingDetail[],
total: data.total ?? 0,
};
},
getById: async (id: string): Promise<BookingDetail> => {
const response = await client.get<BookingDetail>(B.BY_ID(id));
return unwrap(response.data) as BookingDetail;
},
remove: async (id: string): Promise<void> => {
await client.delete(B.BY_ID(id));
},
staffAccept: (id: string) => postBooking<BookingDetail>(B.STAFF_ACCEPT(id)),
requestChanges: (id: string, note: string) =>
postBooking<BookingDetail>(B.STAFF_REQUEST_CHANGES(id), { note }),
staffReject: (id: string, reason: string) =>
postBooking<BookingDetail>(B.STAFF_REJECT(id), { reason }),
approveStep: ({ id, stepId, requiredRole }: ApproveStepPayload) =>
postBooking<BookingDetail>(B.APPROVE_STEP(id, stepId), { requiredRole }),
rejectStep: ({ id, stepId, reason }: RejectStepPayload) =>
postBooking<BookingDetail>(B.REJECT_STEP(id, stepId), { reason }),
generateContract: (id: string) =>
postBooking<BookingDetail>(B.CONTRACT_GENERATE(id)),
getContractView: async (id: string): Promise<ContractView> => {
const response = await client.get<ContractView>(B.CONTRACT_VIEW(id));
return unwrap(response.data) as ContractView;
},
downloadContract: async (id: string): Promise<Blob> => {
const response = await client.get(B.CONTRACT_DOWNLOAD(id), {
responseType: "blob",
});
return response.data as Blob;
},
downloadContractDocument: async (id: string): Promise<Blob> => {
const response = await client.get(B.CONTRACT_DOCUMENT(id), {
responseType: "blob",
});
return response.data as Blob;
},
signContract: (id: string, payload: SignContractPayload) =>
postBooking<BookingDetail>(B.CONTRACT_SIGN(id), payload),
getSummary: async (id: string): Promise<{ summary: string }> => {
const response = await client.get<{ summary: string }>(B.SUMMARY(id));
return unwrap(response.data);
},
customerSign: (id: string, payload: SignContractPayload) =>
postBooking<BookingDetail>(B.CUSTOMER_SIGN(id), {
...payload,
role: "CUSTOMER",
}),
marketingApprove: (id: string, payload: SignContractPayload) =>
postBooking<BookingDetail>(B.MARKETING_APPROVE(id), {
...payload,
role: "STAFF",
}),
generatePnr: (id: string) => postBooking<BookingDetail>(B.PAYMENT_PNR(id)),
submitPaymentProof: async (id: string, file: File): Promise<BookingDetail> => {
const form = new FormData();
form.append("file", file);
const response = await client.post<BookingDetail>(B.PAYMENT_PROOF(id), form, {
headers: { "Content-Type": "multipart/form-data" },
});
return unwrap(response.data) as BookingDetail;
},
verifyPayment: (id: string) =>
postBooking<BookingDetail>(B.PAYMENT_VERIFY(id)),
downloadPaymentRequestLetter: async (id: string): Promise<Blob> => {
const response = await client.get(B.PAYMENT_REQUEST_LETTER(id), {
responseType: "blob",
});
return response.data as Blob;
},
startTransit: (id: string) =>
postBooking<BookingDetail>(B.START_TRANSIT(id)),
complete: (id: string) => postBooking<BookingDetail>(B.COMPLETE(id)),
cancel: (id: string, reason: string) =>
postBooking<BookingDetail>(B.CANCEL(id), { reason }),
};

View File

@@ -23,4 +23,4 @@ export const cargoService = {
apiClient.post(`/cargoes/${cargoId}/load`, { quantity, weight, volume }),
deliver: (cargoId: string) => apiClient.post(`/cargoes/${cargoId}/deliver`),
unload: (cargoId: string) => apiClient.post(`/cargoes/${cargoId}/unload`),
};
};

View File

@@ -8,10 +8,8 @@ import type {
UpdateFileUploadFieldDto,
UpdateFileUploadSettingDto,
} from "@/types/fileUploadSettings";
import { URL_CONSTANTS } from "@/constants/URLS";
import { QUERY_KEYS } from "@/constants/TANSTACK_QUEY_KEY";
import { ApiResponse } from "@/types/apiResponse";
import { endpoint, unwrap } from "@/utils/endpoint";
import { unwrap } from "@/utils/endpoint";
const BASE = "/file-upload-settings";
@@ -124,14 +122,3 @@ export const fileUploadSettingsService = {
await client.delete(`${BASE}/fields/${fieldId}`);
},
};
export const getFileUploadSettingByCode = endpoint<string, FileUploadSetting>(
QUERY_KEYS.FILES.FILE_UPLOAD_SETTINGS,
QUERY_KEYS.FILES.BY_CODE,
(code: any) =>
client
.get<
ApiResponse<FileUploadSetting>
>(`${URL_CONSTANTS.FILES.FILE_UPLOAD_SETTINGS_BY_CODE}/${code}`)
.then((res: any) => res.data.data),
);

View File

@@ -1,7 +1,6 @@
import { api as client } from "@/auth/http";
import { URL_CONSTANTS } from "@/constants/URLS";
import type {
ApproveRatePayload,
RuleEngineListMeta,
RuleEngineListResult,
RuleEngineRecord,
@@ -143,11 +142,8 @@ export const ruleEngineService = {
return normalizeEntity<T>(response.data);
},
approveRate: async <T extends RuleEngineRecord>(
id: string,
payload: ApproveRatePayload,
): Promise<T> => {
const response = await client.post(URL_CONSTANTS.RULE_ENGINE.RATE_APPROVE(id), payload);
approveRate: async <T extends RuleEngineRecord>(id: string): Promise<T> => {
const response = await client.post(URL_CONSTANTS.RULE_ENGINE.RATE_APPROVE(id));
return normalizeEntity<T>(response.data);
},

View File

@@ -0,0 +1,128 @@
/** Mirrors API BOOKING_STATUSES from edr-freight-api booking.entity */
export const BOOKING_STATUSES = [
"DRAFT",
"SUBMITTED",
"CHANGES_REQUESTED",
"PENDING_APPROVAL",
"APPROVED_PENDING_SIGNATURE",
"APPROVED",
"CONTRACT_READY",
"SIGNED_CUSTOMER",
"FULLY_EXECUTED",
"PNR_GENERATED",
"PAYMENT_VERIFICATION_IN_PROGRESS",
"PAID",
"IN_TRANSIT",
"COMPLETED",
"REJECTED",
"CANCELLED",
"PENDING_CONSOLIDATION",
"CONSOLIDATED",
] as const;
export type BookingStatus = (typeof BOOKING_STATUSES)[number];
export interface BookingNamedRef {
id: string;
name?: string;
code?: string;
label?: string;
companyName?: string;
}
export interface BookingContainerLine {
id: string;
containerTypeId: string;
quantity: number;
vgmPerUnitTons: number;
containerType?: {
id: string;
code?: string;
label?: string;
sizeFt?: number;
isReefer?: boolean;
};
}
export interface BookingApprovalStep {
id: string;
stepOrder: number;
requiredRole: string;
status: "PENDING" | "APPROVED" | "REJECTED" | "SKIPPED";
actionedAt?: string | null;
remarks?: string | null;
}
export interface BookingReviewNote {
id: string;
note: string;
type: string;
createdAt: string;
}
export interface BookingFile {
id: string;
name: string;
mimeType?: string;
code?: string;
}
export interface BookingDetail {
id: string;
reference: string;
// customerId: string;
companyId: string;
status: BookingStatus;
scheduledDate: string;
totalAmount: number;
paymentStatus: string;
paymentCurrency: string;
contractType: string;
freightType: "CONTAINER" | "BULK";
tradeDirection: string;
cargoTotalWeightVgm: number;
isHazardous: boolean;
allowConsolidation: boolean;
priorityScore: number;
pnrCode?: string | null;
firstMilePickupAddress?: string | null;
lastMileDeliveryAddress?: string | null;
equipmentReturn?: string;
contractSummary?: string | null;
latestChangeRequestNote?: string | null;
createdAt: string;
updatedAt: string;
// customer?: BookingNamedRef & { companyName?: string };
company?: BookingNamedRef;
originYard?: BookingNamedRef;
destinationYard?: BookingNamedRef;
serviceType?: BookingNamedRef & { code?: string };
cargoType?: BookingNamedRef;
shippingLine?: BookingNamedRef;
bookingContainers?: BookingContainerLine[];
approvalSteps?: BookingApprovalStep[];
reviewNotes?: BookingReviewNote[];
files?: BookingFile[];
cargoModifiers?: Array<{
id: string;
calculatedAmount: number;
triggerValue?: number | null;
}>;
}
export interface BookingListRow {
id: string;
reference: string;
customerLabel: string;
status: BookingStatus;
scheduledDate: string;
totalAmount: number;
paymentCurrency: string;
paymentStatus: string;
tradeDirection: string;
freightType: string;
originLabel: string;
destinationLabel: string;
priorityScore: number;
createdAt: string;
}

View File

@@ -23,7 +23,3 @@ export interface RuleEngineListResult<T> {
}
export type RuleEngineRecord = Record<string, unknown> & { id: string };
export interface ApproveRatePayload {
approvedByCeoId: string;
}

View File

@@ -44,11 +44,19 @@ export function endpoint<TInput, TResponse>(
service: string,
action: string,
execute: (input: TInput) => Promise<TResponse>,
queryKeyBuilder?: (input: TInput) => readonly unknown[],
) {
const buildKey = (input?: TInput): readonly unknown[] =>
input === undefined
const buildKey = (input?: TInput): readonly unknown[] => {
if (queryKeyBuilder && input !== undefined) {
return queryKeyBuilder(input as TInput);
}
if (queryKeyBuilder && input === undefined) {
return queryKeyBuilder(undefined as TInput);
}
return input === undefined
? [service, action]
: [service, action, input];
};
const call = (input: TInput) => execute(input);

View File

@@ -0,0 +1,56 @@
import type { QueryClient } from "@tanstack/react-query";
import { QUERY_KEYS } from "@/constants/QUERY_KEYS";
import type {
RuleEngineListResult,
RuleEngineRecord,
RuleEngineResourceSlug,
} from "@/types/rule-engine";
export function invalidateBookings(qc: QueryClient): Promise<void> {
return qc.invalidateQueries({ queryKey: QUERY_KEYS.BOOKINGS.ROOT });
}
export function invalidateBookingDetail(
qc: QueryClient,
id: string,
): Promise<void> {
return Promise.all([
qc.invalidateQueries({ queryKey: QUERY_KEYS.BOOKINGS.byId(id) }),
invalidateBookings(qc),
]).then(() => undefined);
}
/** Update a single row in all cached list queries for a rule-engine resource. */
export function patchRuleEngineListRecord(
qc: QueryClient,
resource: RuleEngineResourceSlug | string,
updated: RuleEngineRecord,
): void {
const updatedId = String(updated.id);
qc.setQueriesData<RuleEngineListResult<RuleEngineRecord>>(
{ queryKey: ["rule-engine", "list", resource] },
(old) => {
if (!old?.data?.length) return old;
const index = old.data.findIndex((row) => String(row.id) === updatedId);
if (index === -1) return old;
const data = old.data.slice();
data[index] = { ...data[index], ...updated };
return { ...old, data };
},
);
}
/** Invalidate and refetch active rule-engine list queries for a resource. */
export async function invalidateRuleEngineList(
qc: QueryClient,
resource: RuleEngineResourceSlug | string,
): Promise<void> {
const queryKey = ["rule-engine", "list", resource] as const;
await qc.invalidateQueries({ queryKey });
await qc.refetchQueries({ queryKey, type: "active" });
}
export function invalidateRuleEngineRoot(qc: QueryClient): Promise<void> {
return qc.invalidateQueries({ queryKey: QUERY_KEYS.RULE_ENGINE.ROOT });
}

View File

@@ -0,0 +1,29 @@
export type Result<T, E = { code: string; message: string; statusCode?: number }> =
| { success: true; data: T }
| { success: false; error: E };
export type ApiError = {
code: string;
message: string;
statusCode?: number;
};
export function extractApiError(err: unknown): ApiError {
if (err && typeof err === "object") {
const obj = err as Record<string, unknown>;
const response = obj.response as Record<string, unknown> | undefined;
if (response) {
const statusCode = response.status as number | undefined;
const data = response.data as Record<string, unknown> | undefined;
return {
code: (data?.error as string) || (data?.message as string) || "api_error",
message: (data?.message as string) || (data?.error as string) || "An unexpected error occurred",
statusCode,
};
}
if (obj.message && typeof obj.message === "string") {
return { code: "client_error", message: obj.message };
}
}
return { code: "unknown_error", message: "An unexpected error occurred" };
}

View File

@@ -14,11 +14,13 @@ import {
Home,
Loader2,
User,
Settings,
} from "lucide-react";
import useAuth from "./hooks/useAuth";
import ProfilePage from "./pages/ProfilePage";
import SettingsPage from "./pages/SettingsPage";
import MyPortalPage from "./pages/MyPortalPage";
import EDRFreightLandingPage from "./pages/EDRFreightLandingPage";
import SignupPage from "./pages/accounts/SignupPage";
@@ -27,13 +29,12 @@ import VerificationOtpPage from "./pages/accounts/VerificationOtpPage";
import SetPasswordPage from "./pages/accounts/SetPasswordPage";
import LoginPage from "./pages/accounts/LoginPage";
import MyBookings from "./pages/bookings/MyBookings";
import BookingContractPage from "./pages/bookings/BookingContractPage";
import BookingDetailPage from "./pages/bookings/BookingDetailPage";
import NewBookingPage from "./pages/bookings/NewBookingPage";
import TrackingPage from "./pages/tracking/TrackingPage";
import BillingPage from "./pages/billing/BillingPage";
import { useEffect } from "react";
import CustomerOnBoarding from "./pages/customers/on_boarding/TransportrOnBoarding";
import CustomerOnboardingPage from "./pages/customers/on_boarding/CustomerOnboardingPage";
const sidebarItems: SidebarItem[] = [
{ label: "Home", href: "/portal", icon: <Home /> },
@@ -41,17 +42,20 @@ const sidebarItems: SidebarItem[] = [
{ label: "Tracking", href: "/tracking", icon: <MapPin /> },
{ label: "Billing", href: "/billing", icon: <Receipt /> },
{ label: "Profile", href: "/profile", icon: <User /> },
{ label: "Settings", href: "/settings", icon: <Settings /> },
];
const App = () => {
const navigate = useNavigate();
const location = useLocation();
const { user, isPending, logout, customer } = useAuth();
const { user, isPending, logout, customer, customerQuery } = useAuth();
useEffect(() => {
if (isPending) return;
const isInProtectedRoutes = sidebarItems.find((item) =>
location.pathname.startsWith(item.href),
);
console.log({ isInProtectedRoutes, location });
if (!user) {
if (isInProtectedRoutes) return navigate("/login");
return;
@@ -103,9 +107,11 @@ const App = () => {
<Route path="/bookings" element={<MyBookings />} />
<Route path="/bookings/new" element={<NewBookingPage />} />
<Route path="/bookings/:id" element={<BookingDetailPage />} />
<Route path="/bookings/:id/contract" element={<BookingContractPage />} />
<Route path="/tracking" element={<TrackingPage />} />
<Route path="/billing" element={<BillingPage />} />
<Route path="/profile" element={<ProfilePage />} />
<Route path="/settings" element={<SettingsPage />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>

View File

@@ -0,0 +1,105 @@
import { useEffect, useRef, useState } from "react";
import { Eraser } from "lucide-react";
import { Button } from "@edr/ui-common";
import { cn } from "@/lib/utils";
interface ContractSignaturePadProps {
onChange: (dataUrl: string | null) => void;
className?: string;
}
export function ContractSignaturePad({
onChange,
className,
}: ContractSignaturePadProps) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const drawing = useRef(false);
const [empty, setEmpty] = useState(true);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
const dpr = window.devicePixelRatio || 1;
const w = canvas.offsetWidth;
const h = canvas.offsetHeight;
canvas.width = w * dpr;
canvas.height = h * dpr;
ctx.scale(dpr, dpr);
ctx.strokeStyle = "#111";
ctx.lineWidth = 2;
ctx.lineCap = "round";
}, []);
const getPos = (e: React.MouseEvent | React.TouchEvent) => {
const canvas = canvasRef.current!;
const rect = canvas.getBoundingClientRect();
if ("touches" in e) {
const t = e.touches[0];
return { x: t.clientX - rect.left, y: t.clientY - rect.top };
}
return { x: e.clientX - rect.left, y: e.clientY - rect.top };
};
const start = (e: React.MouseEvent | React.TouchEvent) => {
drawing.current = true;
const ctx = canvasRef.current?.getContext("2d");
const { x, y } = getPos(e);
ctx?.beginPath();
ctx?.moveTo(x, y);
};
const move = (e: React.MouseEvent | React.TouchEvent) => {
if (!drawing.current) return;
const ctx = canvasRef.current?.getContext("2d");
const { x, y } = getPos(e);
ctx?.lineTo(x, y);
ctx?.stroke();
setEmpty(false);
onChange(canvasRef.current?.toDataURL("image/png") ?? null);
};
const end = () => {
drawing.current = false;
};
const clear = () => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
setEmpty(true);
onChange(null);
};
return (
<div className={cn("space-y-2", className)}>
<div className="overflow-hidden rounded-lg border-2 border-dashed border-border bg-white">
<canvas
ref={canvasRef}
className="h-36 w-full touch-none cursor-crosshair"
onMouseDown={start}
onMouseMove={move}
onMouseUp={end}
onMouseLeave={end}
onTouchStart={start}
onTouchMove={move}
onTouchEnd={end}
/>
</div>
<div className="flex items-center justify-between">
<p className="text-xs text-muted-foreground">Draw your signature above</p>
<Button type="button" variant="ghost" size="sm" className="gap-1" onClick={clear}>
<Eraser className="size-3.5" />
Clear
</Button>
</div>
{empty && (
<p className="text-xs text-amber-700">Signature is required before confirming.</p>
)}
</div>
);
}

View File

@@ -0,0 +1,47 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { Slot } from "radix-ui";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary: "bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90",
outline:
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
link: "text-primary underline-offset-4 [a&]:hover:underline",
},
},
defaultVariants: {
variant: "default",
},
},
);
function Badge({
className,
variant = "default",
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "span";
return (
<Comp
data-slot="badge"
data-variant={variant}
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
);
}
export { Badge, badgeVariants };

View File

@@ -0,0 +1,8 @@
export * from './table';
export * from './badge';
export * from './button';
export * from './dialog';
export * from './input';
export * from './label';
export * from './textarea';
export * from './Breadcrumbs';

View File

@@ -0,0 +1,114 @@
import * as React from "react";
import { cn } from "@/lib/utils";
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
);
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b outline-ring/50", className)}
{...props}
/>
);
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
);
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className,
)}
{...props}
/>
);
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"border-b transition-colors bg-background hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
className,
)}
{...props}
/>
);
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"h-10 bg-muted first-of-type:pl-4 last-of-type:pr-4 first-of-type: p-2 py-4 text-left align-middle font-medium whitespace-nowrap text-secondary-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle first-of-type:pl-4 last-of-type:pr-4 whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
);
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
};

View File

@@ -79,9 +79,20 @@ export const URL_CONSTANTS = {
BY_USER_ID: (id: string) => `/api/customers/user/${id}`,
},
COMPANIES_API: {
GET_INFO: "/api/companies/getInfo",
CREATE: "/api/companies/create",
PROFILE: "/api/companies/profile",
DOCUMENTS: (id: string) => `/api/companies/${id}/documents`,
},
BOOKINGS: {
BASE: "/bookings",
BY_ID: (id: string | number) => `/bookings/${id}`,
CONTRACT_VIEW: (id: string) => `/bookings/${id}/contract/view`,
CONTRACT_DOCUMENT: (id: string) => `/bookings/${id}/contract/document`,
CONTRACT_SIGN: (id: string) => `/bookings/${id}/contract/sign`,
CONTRACT_DOWNLOAD: (id: string) => `/bookings/${id}/contract`,
CANCEL: (id: string | number) => `/bookings/${id}/cancel`,
CONFIRM: (id: string | number) => `/bookings/${id}/confirm`,
},

View File

@@ -29,15 +29,13 @@ const useAuth = () => {
const authQuery = useQuery(
api.auth.getMyInfo.queryOptions({
enabled: !!getCookie("auth-token"),
retry: false,
staleTime: 10 * 60 * 1000,
}),
);
const customerQuery = useQuery(
api.customers.getByUserId.queryOptions({
input: { id: authQuery.data?.id ?? "" },
const companyQuery = useQuery(
api.companies.getInfo.queryOptions({
enabled: !!authQuery.data?.id,
retry: false,
staleTime: 10 * 60 * 1000,
@@ -48,12 +46,12 @@ const useAuth = () => {
useEffect(() => {
console.log({
user: authQuery.data,
customer: customerQuery.data,
isCustomer: !!customerQuery.data,
company: companyQuery.data,
isCompany: !!companyQuery.data,
isUserPending: authQuery.isPending,
isCustomerPending: customerQuery.isPending,
isCompanyPending: companyQuery.isPending,
});
}, [authQuery, customerQuery]);
}, [authQuery, companyQuery]);
const hasToken = !!getCookie("auth-token");
const isPending = authQuery.isPending && hasToken;
@@ -180,7 +178,8 @@ const useAuth = () => {
return {
isPending,
user: authQuery.data ?? null,
customer: customerQuery.data ?? null,
company: companyQuery.data ?? null,
customer: companyQuery.data ?? null,
login,
signup,
setPassword,
@@ -189,7 +188,8 @@ const useAuth = () => {
generateVerificationCode,
logout,
authQuery,
customerQuery,
companyQuery,
customerQuery: companyQuery,
};
};

View File

@@ -1,4 +1,4 @@
import { useMemo } from "react";
import { useMemo, useState } from "react";
import { Link } from "react-router-dom";
import {
ArrowRight,
@@ -14,6 +14,8 @@ import {
Plus,
Receipt,
Truck,
UploadCloud,
X,
} from "lucide-react";
import {
@@ -48,6 +50,7 @@ export default function MyPortalPage() {
const outstandingInvoices = myInvoices.filter(
(inv) => inv.status === "Sent" || inv.status === "Overdue",
);
const [dismissed, setDismissed] = useState(false);
const totalOutstanding = outstandingInvoices
.filter((inv) => inv.currency === "USD")
.reduce((sum, inv) => sum + inv.amount, 0);
@@ -61,6 +64,34 @@ export default function MyPortalPage() {
return (
<div className="min-h-screen bg-background p-6">
<div className="mx-auto max-w-7xl space-y-6">
{/* Documents banner */}
{!me.documentsComplete && !dismissed && (
<div className="flex items-start gap-3 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">
<UploadCloud className="mt-0.5 h-5 w-5 shrink-0 text-amber-500" />
<div className="flex-1">
<p className="font-semibold">Upload your documents</p>
<p className="mt-0.5 text-amber-700">
To enable all account features, please upload your Business
License, TIN Certificate, and National ID / Passport.
</p>
<Link
to="/settings?tab=documents"
className="mt-2 inline-flex items-center gap-1 font-medium text-amber-900 underline underline-offset-2 transition hover:text-amber-700"
>
Upload now
</Link>
</div>
<button
type="button"
onClick={() => setDismissed(true)}
className="shrink-0 rounded-lg p-1 text-amber-400 transition hover:bg-amber-100 hover:text-amber-600"
aria-label="Dismiss"
>
<X className="h-4 w-4" />
</button>
</div>
)}
{/* Welcome banner */}
<div className="overflow-hidden rounded-3xl bg-gradient-to-r from-[#059669] to-[#10B981] p-6 text-white shadow-sm">
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">

View File

@@ -1,135 +1,46 @@
import { useMemo } from "react";
import {
User,
Building2,
Phone,
Mail,
MapPin,
ShieldCheck,
Briefcase,
UserCheck,
Building,
Globe,
Fingerprint,
FileCheck,
Settings2,
ExternalLink,
} from "lucide-react";
import useAuth from "@/hooks/useAuth";
import {
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
CardAction,
Badge,
Separator,
SmartFileInput,
Button,
} from "@edr/ui-common";
import type { IFileUploadSetting } from "@edr/types/freight";
import { cn } from "@/lib/utils";
import { User, Building2, Phone, Mail, MapPin, ShieldCheck, Briefcase, UserCheck, Fingerprint, FileCheck, Globe, Building } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { api } from "@/services/api";
import { Card, CardHeader, CardTitle, CardDescription, CardContent, Badge, Separator } from "@edr/ui-common";
function InfoItem({ icon, label, value }: { icon?: React.ReactNode; label: string; value?: string | null }) {
return (
<div className="flex items-start gap-3">
{icon && <div className="mt-1 text-muted-foreground [&_svg]:size-4">{icon}</div>}
<div className="flex flex-col gap-0.5">
<p className="text-[10px] font-bold uppercase tracking-tight text-muted-foreground">{label}</p>
<p className="text-sm font-bold text-foreground">{value || "—"}</p>
</div>
</div>
);
}
export default function ProfilePage() {
const { user, customer, isPending } = useAuth();
const documentSettings = useMemo<IFileUploadSetting>(() => ({
id: "profile-docs",
code: "customer_documents",
label: "Customer Documents",
entity: "customer",
createdAt: new Date(),
updatedAt: new Date(),
fields: [
{
id: "doc-tin",
settingId: "profile-docs",
fileKey: "tin_certificate",
fileLabel: "TIN Certificate",
isRequired: true,
isMultiple: false,
maxFiles: 1,
allowedExtensions: [".pdf", ".jpg", ".jpeg", ".png"],
maxSizeMb: 5,
order: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "doc-license",
settingId: "profile-docs",
fileKey: "business_license",
fileLabel: "Business/Investment License",
isRequired: true,
isMultiple: false,
maxFiles: 1,
allowedExtensions: [".pdf", ".jpg", ".jpeg", ".png"],
maxSizeMb: 5,
order: 2,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "doc-reg",
settingId: "profile-docs",
fileKey: "registration_certificate",
fileLabel: "Business Registration Certificate",
isRequired: true,
isMultiple: false,
maxFiles: 1,
allowedExtensions: [".pdf", ".jpg", ".jpeg", ".png"],
maxSizeMb: 5,
order: 3,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "doc-id",
settingId: "profile-docs",
fileKey: "national_id",
fileLabel: "National ID",
isRequired: true,
isMultiple: false,
maxFiles: 1,
allowedExtensions: [".pdf", ".jpg", ".jpeg", ".png"],
maxSizeMb: 5,
order: 4,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "doc-poa",
settingId: "profile-docs",
fileKey: "power_of_attorney",
fileLabel: "Power of Attorney",
isRequired: false,
isMultiple: false,
maxFiles: 1,
allowedExtensions: [".pdf", ".jpg", ".jpeg", ".png"],
maxSizeMb: 5,
order: 5,
createdAt: new Date(),
updatedAt: new Date(),
},
],
}), []);
const { data: profile, isPending } = useQuery(
api.companies.getProfile.queryOptions(),
);
if (isPending) {
return (
<div className="flex h-full items-center justify-center">
<div className="h-8 w-8 animate-spin rounded-full border-b-2 border-primary"></div>
<div className="h-8 w-8 animate-spin rounded-full border-b-2 border-primary" />
</div>
);
}
const displayName = user?.name?.en || user?.username || user?.email || "User";
if (!profile) {
return (
<div className="flex h-full items-center justify-center">
<p className="text-muted-foreground">No company profile found.</p>
</div>
);
}
return (
<div className="container mx-auto max-w-7xl px-4 py-8">
<div className="flex flex-col gap-8">
{/* Header Section */}
<div className="flex flex-col gap-6 md:flex-row md:items-center md:justify-between">
<div className="px-4 py-8">
<div className="mx-auto max-w-7xl">
<div className="flex flex-col gap-8">
{/* Header */}
<div className="flex items-center gap-6">
<div className="flex size-24 items-center justify-center rounded-2xl bg-primary/10 text-primary shadow-inner">
<User className="size-12" />
@@ -137,7 +48,7 @@ export default function ProfilePage() {
<div className="flex flex-col gap-1">
<div className="flex items-center gap-3">
<h1 className="text-3xl font-black tracking-tight text-foreground">
{displayName}
{profile.companyName}
</h1>
<Badge variant="secondary" className="font-bold uppercase tracking-wider">
Verified
@@ -145,182 +56,129 @@ export default function ProfilePage() {
</div>
<p className="flex items-center gap-2 font-medium text-muted-foreground">
<Building className="size-4" />
{customer?.companyName || "No Company Linked"}
{profile.companyName}
</p>
</div>
</div>
<div className="flex items-center gap-3">
<Button variant="outline">
<Settings2 data-icon="inline-start" />
Account Settings
</Button>
</div>
</div>
<Separator />
<Separator />
<div className="grid grid-cols-1 gap-8 lg:grid-cols-3">
{/* Left Column - Personal & Company Info */}
<div className="flex flex-col gap-8 lg:col-span-2">
<div className="grid grid-cols-1 gap-8 md:grid-cols-2">
{/* Personal Details Card */}
<div className="grid grid-cols-1 gap-8 lg:grid-cols-3">
{/* Left Column */}
<div className="flex flex-col gap-8 lg:col-span-2">
<div className="grid grid-cols-1 gap-8 md:grid-cols-2">
{/* Company Details */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Building2 className="size-5 text-primary" />
Company Details
</CardTitle>
<CardDescription>Business registration information</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<InfoItem icon={<Globe />} label="Location" value={profile.companyLocation} />
<InfoItem icon={<MapPin />} label="Address" value={profile.companyAddress} />
<InfoItem icon={<FileCheck />} label="TIN Number" value={profile.tinNumber} />
<InfoItem icon={<ShieldCheck />} label="FAN Number" value={profile.fanNumber} />
<InfoItem icon={<Mail />} label="Email" value={profile.companyEmail} />
<InfoItem icon={<Phone />} label="Phone" value={profile.companyPhone} />
</CardContent>
</Card>
{/* Personal Details (from ExternalProfile) */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Fingerprint className="size-5 text-primary" />
Profile Details
</CardTitle>
<CardDescription>Your linked user profile</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<InfoItem icon={<User />} label="Profile" value="Primary Contact" />
</CardContent>
</Card>
</div>
{/* Personnel Card */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Fingerprint className="size-5 text-primary" />
Personal Details
<Briefcase className="size-5 text-primary" />
Key Personnel
</CardTitle>
<CardDescription>Your account contact information</CardDescription>
<CardAction>
<Button variant="ghost" size="icon">
<ExternalLink />
</Button>
</CardAction>
<CardDescription>Management and contact persons</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<InfoItem icon={<Mail />} label="Email Address" value={user?.email} />
<InfoItem icon={<Phone />} label="Phone Number" value={user?.phoneNumber} />
<InfoItem icon={<UserCheck />} label="Username" value={user?.username} />
<CardContent className="grid grid-cols-1 gap-8 md:grid-cols-2">
<div className="flex flex-col gap-4">
<h3 className="border-l-4 border-primary pl-3 text-sm font-bold uppercase tracking-wide text-foreground">
Contact Person
</h3>
<div className="flex flex-col gap-3 pl-4">
<InfoItem label="Name" value={profile.contactPersonName} />
<InfoItem label="Phone" value={profile.contactPersonPhone} />
</div>
</div>
<div className="flex flex-col gap-4">
<h3 className="border-l-4 border-accent pl-3 text-sm font-bold uppercase tracking-wide text-foreground">
General Manager
</h3>
<div className="flex flex-col gap-3 pl-4">
<InfoItem label="Name" value={profile.generalManagerName} />
<InfoItem label="Email" value={profile.generalManagerEmail} />
<InfoItem label="Phone" value={profile.generalManagerPhone} />
</div>
</div>
</CardContent>
</Card>
{/* Company Details Card */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Building2 className="size-5 text-primary" />
Company Details
</CardTitle>
<CardDescription>Business registration information</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<InfoItem icon={<Globe />} label="Location" value={customer?.companyLocation} />
<InfoItem icon={<MapPin />} label="Address" value={customer?.companyAddress} />
<InfoItem icon={<FileCheck />} label="TIN Number" value={customer?.tinNumber} />
<InfoItem icon={<ShieldCheck />} label="FAN Number" value={customer?.fanNumber} />
{/* Power of Attorney */}
{profile.poaName && (
<Card className="border-dashed">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<UserCheck className="size-5 text-accent" />
Power of Attorney
</CardTitle>
<CardDescription>Authorized representative details</CardDescription>
</CardHeader>
<CardContent className="grid grid-cols-1 gap-4 md:grid-cols-2">
<InfoItem label="PoA Name" value={profile.poaName} />
<InfoItem label="PoA Email" value={profile.poaEmail} />
<InfoItem label="PoA Phone" value={profile.poaPhone} />
<InfoItem label="PoA Location" value={profile.poaLocation} />
</CardContent>
</Card>
)}
</div>
{/* Right Column */}
<div className="flex flex-col gap-8">
<Card className="relative overflow-hidden border-none bg-foreground text-background shadow-xl">
<div className="absolute right-0 top-0 p-4 opacity-10">
<ShieldCheck className="size-32" />
</div>
<CardContent className="relative z-10 flex flex-col gap-4 px-6 py-8">
<h3 className="text-xl font-black">Secure Account</h3>
<p className="text-sm leading-relaxed text-muted-foreground/80">
Your information is protected by enterprise-grade security.
Contact support for verified information updates.
</p>
<div className="pt-2">
<a
href="/settings"
className="inline-flex h-9 items-center justify-center rounded-md bg-background px-4 text-sm font-medium text-foreground hover:bg-background/90"
>
Edit Settings
</a>
</div>
</CardContent>
</Card>
</div>
{/* Personnel Card */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Briefcase className="size-5 text-primary" />
Key Personnel
</CardTitle>
<CardDescription>Management and contact persons</CardDescription>
</CardHeader>
<CardContent className="grid grid-cols-1 gap-8 md:grid-cols-2">
<div className="flex flex-col gap-4">
<h3 className="border-l-4 border-primary pl-3 text-sm font-bold uppercase tracking-wide text-foreground">
Contact Person
</h3>
<div className="flex flex-col gap-3 pl-4">
<InfoItem label="Name" value={customer?.contactPersonName} />
<InfoItem label="Phone" value={customer?.contactPersonPhone} />
</div>
</div>
<div className="flex flex-col gap-4">
<h3 className="border-l-4 border-accent pl-3 text-sm font-bold uppercase tracking-wide text-foreground">
General Manager
</h3>
<div className="flex flex-col gap-3 pl-4">
<InfoItem label="Name" value={customer?.generalManagerName} />
<InfoItem label="Email" value={customer?.generalManagerEmail} />
<InfoItem label="Phone" value={customer?.generalManagerPhone} />
</div>
</div>
</CardContent>
</Card>
{/* Power of Attorney Section (Conditional) */}
{customer?.poaName && (
<Card className="border-dashed">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<UserCheck className="size-5 text-accent" />
Power of Attorney
</CardTitle>
<CardDescription>Authorized representative details</CardDescription>
</CardHeader>
<CardContent className="grid grid-cols-1 gap-4 md:grid-cols-2">
<InfoItem label="PoA Name" value={customer.poaName} />
<InfoItem label="PoA Email" value={customer.poaEmail} />
<InfoItem label="PoA Phone" value={customer.poaPhone} />
<InfoItem label="PoA Location" value={customer.poaLocation} />
</CardContent>
</Card>
)}
</div>
{/* Right Column - Documents */}
<div className="flex flex-col gap-8">
<Card className="border-primary/20 bg-primary/[0.02] shadow-md">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<FileCheck className="size-6 text-primary" />
Documents
</CardTitle>
<CardDescription>Manage required business documents</CardDescription>
</CardHeader>
<CardContent className="px-6 pb-6 pt-0">
<SmartFileInput
file={documentSettings}
variant="minimal"
className="flex flex-col gap-4"
/>
</CardContent>
</Card>
<Card className="relative overflow-hidden border-none bg-foreground text-background shadow-xl">
<div className="absolute right-0 top-0 p-4 opacity-10">
<ShieldCheck className="size-32" />
</div>
<CardContent className="relative z-10 flex flex-col gap-4 px-6 py-8">
<h3 className="text-xl font-black">Secure Account</h3>
<p className="text-sm leading-relaxed text-muted-foreground/80">
Your information is protected by enterprise-grade security.
Contact support for verified information updates.
</p>
<div className="pt-2">
<Button variant="secondary" size="sm">
Contact Support
</Button>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
</div>
);
}
function InfoItem({
icon,
label,
value,
}: {
icon?: React.ReactNode;
label: string;
value?: string | null;
}) {
return (
<div className="flex items-start gap-3">
{icon && (
<div className="mt-1 text-muted-foreground [&_svg]:size-4">
{icon}
</div>
)}
<div className="flex flex-col gap-0.5">
<p className="text-[10px] font-bold uppercase tracking-tight text-muted-foreground">
{label}
</p>
<p className="text-sm font-bold text-foreground">
{value || "—"}
</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,617 @@
import { useState, useMemo } from "react";
import { useSearchParams } from "react-router-dom";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
Building2,
User,
Briefcase,
UserCheck,
FileCheck,
Loader2,
Save,
UploadCloud,
CheckCircle2,
XCircle,
} from "lucide-react";
import { api } from "@/services/api";
import { companiesService } from "@/services/companies.service";
import PhoneInput from "@/components/auth/PhoneInput";
import {
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
CardFooter,
Button,
Input,
Field,
FieldLabel,
FieldError,
FieldGroup,
SmartFileInput,
Badge,
} from "@edr/ui-common";
import { cn } from "@/lib/utils";
type SettingsTab =
| "company"
| "contact"
| "gm"
| "poa"
| "documents";
const settingsSchema = z.object({
companyName: z.string().min(1, "Company name is required"),
companyEmail: z.string().email("Invalid email address"),
companyPhone: z.string().min(1, "Company phone is required"),
companyPhoneCountryCode: z.string().min(1, "Country code is required"),
companyLocation: z.string().min(1, "Location is required"),
companyAddress: z.string().min(1, "Address is required"),
tinNumber: z.string().length(10, "TIN must be exactly 10 digits"),
fanNumber: z.string().length(16, "FAN must be exactly 16 digits"),
contactPersonName: z.string().min(1, "Contact person name is required"),
contactPersonPhone: z.string().min(1, "Contact person phone is required"),
contactPersonPhoneCountryCode: z.string().min(1, "Country code is required"),
generalManagerName: z.string().min(1, "GM name is required"),
generalManagerEmail: z.string().email("Invalid GM email"),
generalManagerPhone: z.string().min(1, "GM phone is required"),
generalManagerPhoneCountryCode: z.string().min(1, "Country code is required"),
poaName: z.string().optional(),
poaEmail: z.string().optional(),
poaPhone: z.string().optional(),
poaPhoneCountryCode: z.string().optional(),
poaLocation: z.string().optional(),
poaAddress: z.string().optional(),
});
type FormData = z.infer<typeof settingsSchema>;
const TABS: { id: SettingsTab; label: string; icon: React.ReactNode }[] = [
{ id: "company", label: "Company Profile", icon: <Building2 className="size-4" /> },
{ id: "contact", label: "Contact Person", icon: <User className="size-4" /> },
{ id: "gm", label: "General Manager", icon: <Briefcase className="size-4" /> },
{ id: "poa", label: "Power of Attorney", icon: <UserCheck className="size-4" /> },
{ id: "documents", label: "Documents", icon: <FileCheck className="size-4" /> },
];
function splitPhone(fullPhone?: string | null): { code: string; number: string } {
if (!fullPhone) return { code: "+251", number: "" };
const match = fullPhone.match(/^(\+\d{1,3})(.*)$/);
if (match) return { code: match[1], number: match[2] };
return { code: "+251", number: fullPhone };
}
export default function SettingsPage() {
const queryClient = useQueryClient();
const [searchParams, setSearchParams] = useSearchParams();
const tab = (searchParams.get("tab") as SettingsTab) || "company";
const setTab = (t: SettingsTab) => {
setSearchParams((prev) => {
const next = new URLSearchParams(prev);
next.set("tab", t);
return next;
}, { replace: true });
};
const [documentFiles, setDocumentFiles] = useState<
Record<string, File | File[] | null>
>({});
const profileQuery = useQuery(
api.companies.getProfile.queryOptions(),
);
const docSettingQuery = useQuery(
api.fileUploadSettings.getByCode.queryOptions({
input: { code: "customer_documents" },
enabled: tab === "documents",
}),
);
const profile = profileQuery.data;
const defaultValues = useMemo((): FormData => {
if (!profile) {
return {
companyName: "",
companyEmail: "",
companyPhone: "",
companyPhoneCountryCode: "+251",
companyLocation: "",
companyAddress: "",
tinNumber: "",
fanNumber: "",
contactPersonName: "",
contactPersonPhone: "",
contactPersonPhoneCountryCode: "+251",
generalManagerName: "",
generalManagerEmail: "",
generalManagerPhone: "",
generalManagerPhoneCountryCode: "+251",
poaName: "",
poaEmail: "",
poaPhone: "",
poaPhoneCountryCode: "+251",
poaLocation: "",
poaAddress: "",
};
}
const contactPhone = splitPhone(profile.contactPersonPhone);
const gmPhone = splitPhone(profile.generalManagerPhone);
const poaPhone = splitPhone(profile.poaPhone);
return {
companyName: profile.companyName,
companyEmail: profile.companyEmail ?? "",
companyPhone: profile.companyPhone ?? "",
companyPhoneCountryCode: splitPhone(profile.companyPhone).code,
companyLocation: profile.companyLocation,
companyAddress: profile.companyAddress ?? "",
tinNumber: profile.tinNumber,
fanNumber: profile.fanNumber ?? "",
contactPersonName: profile.contactPersonName ?? "",
contactPersonPhone: contactPhone.number,
contactPersonPhoneCountryCode: contactPhone.code,
generalManagerName: profile.generalManagerName ?? "",
generalManagerEmail: profile.generalManagerEmail ?? "",
generalManagerPhone: gmPhone.number,
generalManagerPhoneCountryCode: gmPhone.code,
poaName: profile.poaName ?? "",
poaEmail: profile.poaEmail ?? "",
poaPhone: poaPhone.number,
poaPhoneCountryCode: poaPhone.code,
poaLocation: profile.poaLocation ?? "",
poaAddress: profile.poaAddress ?? "",
};
}, [profile]);
const {
register,
handleSubmit,
reset,
formState: { errors, isDirty },
} = useForm<FormData>({
resolver: zodResolver(settingsSchema),
values: defaultValues,
});
const updateMutation = useMutation({
mutationFn: (data: FormData) =>
api.companies.updateProfile.call({
companyName: data.companyName,
companyEmail: data.companyEmail,
companyPhone: `${data.companyPhoneCountryCode}${data.companyPhone}`,
companyLocation: data.companyLocation,
companyAddress: data.companyAddress,
tin: data.tinNumber,
fanNumber: data.fanNumber,
contactPersonName: data.contactPersonName,
contactPersonPhone: `${data.contactPersonPhoneCountryCode}${data.contactPersonPhone}`,
generalManagerName: data.generalManagerName,
generalManagerEmail: data.generalManagerEmail,
generalManagerPhone: `${data.generalManagerPhoneCountryCode}${data.generalManagerPhone}`,
poaName: data.poaName || undefined,
poaPhone:
data.poaPhone && data.poaPhoneCountryCode
? `${data.poaPhoneCountryCode}${data.poaPhone}`
: undefined,
poaEmail: data.poaEmail || undefined,
poaLocation: data.poaLocation || undefined,
poaAddress: data.poaAddress || undefined,
}),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: api.companies.getProfile.queryKey(),
});
},
});
const docUploadMutation = useMutation({
mutationFn: (files: Record<string, File | File[] | null>) =>
companiesService.uploadDocuments(profile!.companyId, files),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: api.companies.getProfile.queryKey(),
});
},
});
const isPending = profileQuery.isPending || updateMutation.isPending || docUploadMutation.isPending;
if (profileQuery.isPending) {
return (
<div className="flex h-full items-center justify-center">
<div className="h-8 w-8 animate-spin rounded-full border-b-2 border-primary" />
</div>
);
}
if (!profile) {
return (
<div className="flex h-full items-center justify-center">
<p className="text-muted-foreground">No company profile found.</p>
</div>
);
}
const onSubmit = (data: FormData) => {
updateMutation.mutate(data);
};
return (
<div className="px-4 py-8">
<div className="mb-8 flex items-center justify-between">
<div>
<h1 className="text-2xl font-black tracking-tight text-foreground">
Account Settings
</h1>
<p className="mt-1 text-sm text-muted-foreground">
Manage your company profile, personnel, and documents
</p>
</div>
<Badge variant="secondary" className="font-bold uppercase tracking-wider">
Verified
</Badge>
</div>
{/* Tab Bar */}
<div className="mb-6 flex flex-wrap gap-1 border-b border-border">
{TABS.map((t) => (
<button
key={t.id}
type="button"
onClick={() => setTab(t.id)}
className={cn(
"flex items-center gap-2 border-b-2 px-4 py-3 text-sm font-semibold transition-colors",
tab === t.id
? "border-primary text-primary"
: "border-transparent text-muted-foreground hover:text-foreground",
)}
>
{t.icon}
{t.label}
</button>
))}
</div>
<form onSubmit={handleSubmit(onSubmit)}>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
{tab === "company" && <><Building2 className="size-5 text-primary" /> Company Profile</>}
{tab === "contact" && <><User className="size-5 text-primary" /> Contact Person</>}
{tab === "gm" && <><Briefcase className="size-5 text-primary" /> General Manager</>}
{tab === "poa" && <><UserCheck className="size-5 text-accent" /> Power of Attorney</>}
{tab === "documents" && <><FileCheck className="size-5 text-primary" /> Documents</>}
</CardTitle>
<CardDescription>
{tab === "company" && "Edit your company registration details"}
{tab === "contact" && "Manage the primary contact person for your account"}
{tab === "gm" && "Manage the general manager information"}
{tab === "poa" && "Power of Attorney details are optional"}
{tab === "documents" && "Upload and manage required business documents"}
</CardDescription>
</CardHeader>
<CardContent>
<FieldGroup className="gap-4">
{/* Company Profile Tab */}
{tab === "company" && (
<>
<Field data-invalid={Boolean(errors.companyName)}>
<FieldLabel>Company Name</FieldLabel>
<Input
placeholder="Global Logistics Ltd"
aria-invalid={Boolean(errors.companyName)}
{...register("companyName")}
/>
<FieldError errors={[errors.companyName]} />
</Field>
<div className="grid grid-cols-2 gap-4">
<Field data-invalid={Boolean(errors.companyEmail)}>
<FieldLabel>Company Email</FieldLabel>
<Input
type="email"
placeholder="ops@company.com"
aria-invalid={Boolean(errors.companyEmail)}
{...register("companyEmail")}
/>
<FieldError errors={[errors.companyEmail]} />
</Field>
<PhoneInput
countryCode={{ ...register("companyPhoneCountryCode") }}
phone={{
...register("companyPhone"),
placeholder: "912345678",
}}
countryCodeError={errors.companyPhoneCountryCode}
phoneError={errors.companyPhone}
label="Company Phone"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<Field data-invalid={Boolean(errors.companyLocation)}>
<FieldLabel>Location</FieldLabel>
<Input
placeholder="Addis Ababa, Ethiopia"
aria-invalid={Boolean(errors.companyLocation)}
{...register("companyLocation")}
/>
<FieldError errors={[errors.companyLocation]} />
</Field>
<Field data-invalid={Boolean(errors.companyAddress)}>
<FieldLabel>Address</FieldLabel>
<Input
placeholder="Bole Subcity, Woreda 03"
aria-invalid={Boolean(errors.companyAddress)}
{...register("companyAddress")}
/>
<FieldError errors={[errors.companyAddress]} />
</Field>
</div>
<div className="grid grid-cols-2 gap-4">
<Field data-invalid={Boolean(errors.tinNumber)}>
<FieldLabel>TIN Number (10 digits)</FieldLabel>
<Input
placeholder="1234567890"
maxLength={10}
aria-invalid={Boolean(errors.tinNumber)}
{...register("tinNumber")}
/>
<FieldError errors={[errors.tinNumber]} />
</Field>
<Field data-invalid={Boolean(errors.fanNumber)}>
<FieldLabel>FAN Number (16 digits)</FieldLabel>
<Input
placeholder="1234567890123456"
maxLength={16}
aria-invalid={Boolean(errors.fanNumber)}
{...register("fanNumber")}
/>
<FieldError errors={[errors.fanNumber]} />
</Field>
</div>
</>
)}
{/* Contact Person Tab */}
{tab === "contact" && (
<>
<Field data-invalid={Boolean(errors.contactPersonName)}>
<FieldLabel>Full Name</FieldLabel>
<Input
placeholder="Jane Smith"
aria-invalid={Boolean(errors.contactPersonName)}
{...register("contactPersonName")}
/>
<FieldError errors={[errors.contactPersonName]} />
</Field>
<PhoneInput
countryCode={{ ...register("contactPersonPhoneCountryCode") }}
phone={{
...register("contactPersonPhone"),
placeholder: "912345678",
}}
countryCodeError={errors.contactPersonPhoneCountryCode}
phoneError={errors.contactPersonPhone}
label="Phone Number"
/>
</>
)}
{/* General Manager Tab */}
{tab === "gm" && (
<>
<Field data-invalid={Boolean(errors.generalManagerName)}>
<FieldLabel>Full Name</FieldLabel>
<Input
placeholder="Abebe Bikila"
aria-invalid={Boolean(errors.generalManagerName)}
{...register("generalManagerName")}
/>
<FieldError errors={[errors.generalManagerName]} />
</Field>
<div className="grid grid-cols-2 gap-4">
<Field data-invalid={Boolean(errors.generalManagerEmail)}>
<FieldLabel>Email Address</FieldLabel>
<Input
type="email"
placeholder="gm@company.com"
aria-invalid={Boolean(errors.generalManagerEmail)}
{...register("generalManagerEmail")}
/>
<FieldError errors={[errors.generalManagerEmail]} />
</Field>
<PhoneInput
countryCode={{ ...register("generalManagerPhoneCountryCode") }}
phone={{
...register("generalManagerPhone"),
placeholder: "912345678",
}}
countryCodeError={errors.generalManagerPhoneCountryCode}
phoneError={errors.generalManagerPhone}
label="Phone Number"
/>
</div>
</>
)}
{/* Power of Attorney Tab */}
{tab === "poa" && (
<>
<p className="text-sm text-muted-foreground">
Power of Attorney details are optional. Fill them in if you have
an authorized representative, or leave blank.
</p>
<Field data-invalid={Boolean(errors.poaName)}>
<FieldLabel>PoA Full Name</FieldLabel>
<Input
placeholder="Authorized Representative Name"
aria-invalid={Boolean(errors.poaName)}
{...register("poaName")}
/>
<FieldError errors={[errors.poaName]} />
</Field>
<div className="grid grid-cols-2 gap-4">
<Field data-invalid={Boolean(errors.poaEmail)}>
<FieldLabel>PoA Email</FieldLabel>
<Input
type="email"
placeholder="poa@company.com"
aria-invalid={Boolean(errors.poaEmail)}
{...register("poaEmail")}
/>
<FieldError errors={[errors.poaEmail]} />
</Field>
<PhoneInput
countryCode={{ ...register("poaPhoneCountryCode") }}
phone={{ ...register("poaPhone"), placeholder: "912345678" }}
label="PoA Phone"
countryCodeError={errors.poaPhoneCountryCode}
phoneError={errors.poaPhone}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<Field data-invalid={Boolean(errors.poaLocation)}>
<FieldLabel>PoA Location</FieldLabel>
<Input
placeholder="City, Country"
aria-invalid={Boolean(errors.poaLocation)}
{...register("poaLocation")}
/>
<FieldError errors={[errors.poaLocation]} />
</Field>
<Field data-invalid={Boolean(errors.poaAddress)}>
<FieldLabel>PoA Address</FieldLabel>
<Input
placeholder="Full Address"
aria-invalid={Boolean(errors.poaAddress)}
{...register("poaAddress")}
/>
<FieldError errors={[errors.poaAddress]} />
</Field>
</div>
</>
)}
{/* Documents Tab */}
{tab === "documents" && (
<>
{docSettingQuery.isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="size-6 animate-spin text-muted-foreground" />
</div>
) : !docSettingQuery.data ? (
<p className="text-sm text-muted-foreground text-center py-4">
No document requirements configured for your account.
</p>
) : (
<SmartFileInput
file={docSettingQuery.data}
value={documentFiles}
onChange={setDocumentFiles}
/>
)}
{docSettingQuery.data && (
<div className="flex items-center justify-between pt-4">
<div className="flex items-center gap-2">
{docUploadMutation.isSuccess && (
<span className="flex items-center gap-1.5 text-sm font-medium text-emerald-600">
<CheckCircle2 className="size-4" />
Documents uploaded successfully
</span>
)}
{docUploadMutation.isError && (
<span className="flex items-center gap-1.5 text-sm font-medium text-red-600">
<XCircle className="size-4" />
Upload failed
</span>
)}
</div>
<Button
type="button"
onClick={() => docUploadMutation.mutate(documentFiles)}
disabled={docUploadMutation.isPending}
>
{docUploadMutation.isPending ? (
<>
<Loader2 className="size-4 animate-spin" />
Uploading...
</>
) : (
<>
<UploadCloud className="size-4" />
Upload Documents
</>
)}
</Button>
</div>
)}
</>
)}
</FieldGroup>
</CardContent>
{tab !== "documents" && (
<CardFooter className="flex items-center justify-between gap-4 border-t border-border px-6 py-4">
<div className="flex items-center gap-2">
{updateMutation.isSuccess && (
<span className="flex items-center gap-1.5 text-sm font-medium text-emerald-600">
<CheckCircle2 className="size-4" />
Saved successfully
</span>
)}
{updateMutation.isError && (
<span className="flex items-center gap-1.5 text-sm font-medium text-red-600">
<XCircle className="size-4" />
Save failed
</span>
)}
</div>
<div className="flex items-center gap-3">
<Button
type="button"
variant="outline"
disabled={isPending || !isDirty}
onClick={() => reset()}
>
Reset
</Button>
<Button type="submit" disabled={isPending}>
{updateMutation.isPending ? (
<>
<Loader2 className="size-4 animate-spin" />
Saving...
</>
) : (
<>
<Save className="size-4" />
Save Changes
</>
)}
</Button>
</div>
</CardFooter>
)}
</Card>
</form>
</div>
);
}

View File

@@ -1,5 +1,6 @@
import { useState } from "react";
import { useForm } from "react-hook-form";
import { useQuery } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
@@ -11,10 +12,10 @@ import {
CheckCircle2,
Loader2,
ChevronLeft,
UploadCloud,
} from "lucide-react";
import type { OnboardingUserType } from "./types";
import type { AuthUser } from "@/types/auth";
import type { CreateCustomerDto } from "@/types/customers";
import type { CreateCompanyPayload } from "@/services/companies.service";
import PhoneInput from "@/components/auth/PhoneInput";
import {
Button,
@@ -23,9 +24,11 @@ import {
FieldLabel,
FieldError,
FieldGroup,
SmartFileInput,
} from "@edr/ui-common";
import { api } from "@/services/api";
type CompanyStep = "company" | "personnel" | "poa";
type CompanyStep = "company" | "personnel" | "poa" | "documents" | "confirm";
const onboardingSchema = z.object({
companyName: z.string().min(1, "Company name is required"),
@@ -79,82 +82,76 @@ const stepFields: Record<CompanyStep, (keyof FormData)[]> = {
"generalManagerPhoneCountryCode",
],
poa: [],
documents: [],
confirm: [],
};
const POA_FIELDS: (keyof FormData)[] = [
"poaName",
"poaPhone",
"poaPhoneCountryCode",
"poaAddress",
"poaEmail",
"poaLocation",
];
const POA_LABELS: Record<string, string> = {
poaName: "PoA name",
poaPhone: "PoA phone",
poaPhoneCountryCode: "PoA country code",
poaAddress: "PoA address",
poaEmail: "PoA email",
poaLocation: "PoA location",
};
function buildPayload(data: FormData, user: AuthUser): CreateCustomerDto {
const nameParts = (user.name?.en ?? "").split(" ");
function buildPayload(data: FormData, _user: AuthUser): CreateCompanyPayload {
return {
userId: user.id,
firstName: nameParts[0] || "",
lastName: nameParts.slice(-1)[0] || "",
email: user.email,
phone: user.phoneNumber,
companyName: data.companyName,
companyEmail: data.companyEmail,
companyPhone: `${data.companyPhoneCountryCode}${data.companyPhone}`,
companyLocation: data.companyLocation,
companyAddress: data.companyAddress,
contactPersonName: data.contactPersonName,
contactPersonPhone: `${data.contactPersonPhoneCountryCode}${data.contactPersonPhone}`,
tinNumber: data.tinNumber,
tin: data.tinNumber,
vatNumber: data.vatNumber,
fanNumber: data.fanNumber,
generalManagerName: data.generalManagerName,
generalManagerEmail: data.generalManagerEmail,
generalManagerPhone: `${data.generalManagerPhoneCountryCode}${data.generalManagerPhone}`,
poaName: data.poaName || undefined,
poaPhone:
data.poaPhone && data.poaPhoneCountryCode
? `${data.poaPhoneCountryCode}${data.poaPhone}`
: undefined,
poaAddress: data.poaAddress || undefined,
poaEmail: data.poaEmail || undefined,
poaLocation: data.poaLocation || undefined,
attributes: {
contactPersonName: data.contactPersonName,
contactPersonPhone: `${data.contactPersonPhoneCountryCode}${data.contactPersonPhone}`,
generalManagerName: data.generalManagerName,
generalManagerEmail: data.generalManagerEmail,
generalManagerPhone: `${data.generalManagerPhoneCountryCode}${data.generalManagerPhone}`,
poaName: data.poaName || undefined,
poaPhone:
data.poaPhone && data.poaPhoneCountryCode
? `${data.poaPhoneCountryCode}${data.poaPhone}`
: undefined,
poaAddress: data.poaAddress || undefined,
poaEmail: data.poaEmail || undefined,
poaLocation: data.poaLocation || undefined,
},
};
}
export default function CompanyProfileForm({
userType,
documentSettingCode,
documentFiles: controlledFiles,
onDocumentFilesChange,
user,
onSubmit,
isPending,
onBack,
}: {
userType: OnboardingUserType;
documentSettingCode: string;
documentFiles?: Record<string, File | File[] | null>;
onDocumentFilesChange?: (
files: Record<string, File | File[] | null>,
) => void;
user: AuthUser;
onSubmit: (data: CreateCustomerDto) => void;
onSubmit: (data: CreateCompanyPayload) => void;
isPending: boolean;
onBack: () => void;
}) {
const requirePoA = userType === "freight-forwarder-et";
const [step, setStep] = useState<CompanyStep>("company");
const [internalFiles, setInternalFiles] = useState<
Record<string, File | File[] | null>
>({});
const documentFiles = controlledFiles ?? internalFiles;
const setDocumentFiles = onDocumentFilesChange ?? setInternalFiles;
const { data: uploadSetting, isLoading: loadingDocuments } = useQuery(
api.fileUploadSettings.getByCode.queryOptions({
input: { code: documentSettingCode },
refetchOnMount: false,
}),
);
const {
register,
handleSubmit,
trigger,
setError,
clearErrors,
getValues,
watch,
formState: { errors },
} = useForm<FormData>({
resolver: zodResolver(onboardingSchema),
@@ -184,26 +181,20 @@ export default function CompanyProfileForm({
},
});
const formValues = watch();
const hasDocuments = Boolean(uploadSetting?.fields?.length);
const totalSteps = 5;
const nextStep = async () => {
if (step === "poa") {
if (requirePoA) {
clearErrors(POA_FIELDS);
const values = getValues();
let hasError = false;
for (const field of POA_FIELDS) {
const val = values[field];
if (!val || val.toString().trim().length === 0) {
setError(field, {
message: `${
POA_LABELS[field].charAt(0).toUpperCase() +
POA_LABELS[field].slice(1)
} is required for Freight Forwarders`,
});
hasError = true;
}
}
if (hasError) return;
}
setStep("documents");
return;
}
if (step === "documents") {
setStep("confirm");
return;
}
if (step === "confirm") {
handleSubmit((data) => onSubmit(buildPayload(data, user)))();
return;
}
@@ -220,6 +211,10 @@ export default function CompanyProfileForm({
setStep("company");
} else if (step === "poa") {
setStep("personnel");
} else if (step === "documents") {
setStep("poa");
} else {
setStep("documents");
}
};
@@ -245,24 +240,41 @@ export default function CompanyProfileForm({
<StepIcon
icon={<User className="size-5" />}
active={step === "personnel"}
completed={step === "poa"}
completed={
step === "poa" || step === "documents" || step === "confirm"
}
/>
<StepIcon
icon={<FileText className="size-5" />}
active={step === "poa"}
completed={step === "documents" || step === "confirm"}
/>
<StepIcon
icon={<UploadCloud className="size-5" />}
active={step === "documents"}
completed={step === "confirm"}
/>
<StepIcon
icon={<CheckCircle2 className="size-5" />}
active={step === "confirm"}
completed={false}
/>
</div>
<p className="text-center text-sm text-muted-foreground mt-3">
{step === "company" && "Step 1 of 3 — Company Information"}
{step === "personnel" && "Step 2 of 3 — Personnel Details"}
{step === "company" &&
`Step 1 of ${totalSteps} — Company Information`}
{step === "personnel" &&
`Step 2 of ${totalSteps} — Personnel Details`}
{step === "poa" &&
`Step 3 of 3 — Power of Attorney ${requirePoA ? "(Required)" : "(Optional)"}`}
`Step 3 of ${totalSteps} — Power of Attorney (Optional)`}
{step === "documents" &&
`Step 4 of ${totalSteps} — Upload Documents (Optional)`}
{step === "confirm" && `Step 5 of ${totalSteps} — Review & Confirm`}
</p>
</div>
<form
onSubmit={handleSubmit((data) => onSubmit(buildPayload(data, user)))}
onSubmit={(e) => e.preventDefault()}
className="flex flex-col gap-4"
>
<FieldGroup className="gap-4">
@@ -363,11 +375,6 @@ export default function CompanyProfileForm({
{step === "personnel" && (
<>
<p className="text-sm text-muted-foreground">
Personal details are pulled from your account. Contact and
management info is collected below.
</p>
<div>
<h3 className="text-sm font-semibold text-foreground mb-3">
Contact Person
@@ -449,16 +456,12 @@ export default function CompanyProfileForm({
{step === "poa" && (
<>
<p className="text-sm text-muted-foreground">
{requirePoA
? "Power of Attorney details are required for Freight Forwarder registration."
: "Power of Attorney details are optional. Skip if not applicable."}
Power of Attorney details are optional. Fill them in if you have
them, or skip to continue.
</p>
<Field data-invalid={Boolean(errors.poaName)}>
<FieldLabel>
PoA Name
{requirePoA && <span className="text-destructive ml-1">*</span>}
</FieldLabel>
<FieldLabel>PoA Name</FieldLabel>
<Input
placeholder="Authorized Representative Name"
aria-invalid={Boolean(errors.poaName)}
@@ -469,10 +472,7 @@ export default function CompanyProfileForm({
<div className="grid grid-cols-2 gap-4">
<Field data-invalid={Boolean(errors.poaEmail)}>
<FieldLabel>
PoA Email
{requirePoA && <span className="text-destructive ml-1">*</span>}
</FieldLabel>
<FieldLabel>PoA Email</FieldLabel>
<Input
type="email"
placeholder="poa@company.com"
@@ -485,7 +485,7 @@ export default function CompanyProfileForm({
<PhoneInput
countryCode={{ ...register("poaPhoneCountryCode") }}
phone={{ ...register("poaPhone"), placeholder: "912345678" }}
label={`PoA Phone${requirePoA ? " *" : ""}`}
label="PoA Phone"
countryCodeError={errors.poaPhoneCountryCode}
phoneError={errors.poaPhone}
/>
@@ -493,10 +493,7 @@ export default function CompanyProfileForm({
<div className="grid grid-cols-2 gap-4">
<Field data-invalid={Boolean(errors.poaLocation)}>
<FieldLabel>
PoA Location
{requirePoA && <span className="text-destructive ml-1">*</span>}
</FieldLabel>
<FieldLabel>PoA Location</FieldLabel>
<Input
placeholder="City, Country"
aria-invalid={Boolean(errors.poaLocation)}
@@ -506,10 +503,7 @@ export default function CompanyProfileForm({
</Field>
<Field data-invalid={Boolean(errors.poaAddress)}>
<FieldLabel>
PoA Address
{requirePoA && <span className="text-destructive ml-1">*</span>}
</FieldLabel>
<FieldLabel>PoA Address</FieldLabel>
<Input
placeholder="Full Address"
aria-invalid={Boolean(errors.poaAddress)}
@@ -520,35 +514,158 @@ export default function CompanyProfileForm({
</div>
</>
)}
{step === "documents" && (
<>
{loadingDocuments ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="size-6 animate-spin text-muted-foreground" />
</div>
) : !uploadSetting ? (
<p className="text-sm text-muted-foreground text-center py-4">
No document requirements found for your account type.
</p>
) : (
<div className="flex flex-col gap-6">
<SmartFileInput
file={uploadSetting}
value={documentFiles}
onChange={setDocumentFiles}
/>
</div>
)}
</>
)}
{step === "confirm" && (
<div className="space-y-4 rounded-xl border border-border bg-card p-4">
<div>
<h3 className="text-base font-semibold text-foreground">
Review your registration
</h3>
<p className="text-sm text-muted-foreground mt-1">
Confirm the company details below before saving.
</p>
</div>
<div className="grid gap-3 md:grid-cols-2">
<ReviewRow
label="Company name"
value={formValues.companyName}
/>
<ReviewRow
label="Company email"
value={formValues.companyEmail}
/>
<ReviewRow
label="Company phone"
value={formValues.companyPhone}
/>
<ReviewRow
label="Location"
value={formValues.companyLocation}
/>
<ReviewRow label="Address" value={formValues.companyAddress} />
<ReviewRow label="TIN" value={formValues.tinNumber} />
<ReviewRow label="VAT" value={formValues.vatNumber} />
<ReviewRow label="FAN" value={formValues.fanNumber} />
<ReviewRow
label="Contact person"
value={formValues.contactPersonName}
/>
<ReviewRow
label="Contact phone"
value={`${formValues.contactPersonPhoneCountryCode}${formValues.contactPersonPhone}`}
/>
<ReviewRow
label="General manager"
value={formValues.generalManagerName}
/>
<ReviewRow
label="GM email"
value={formValues.generalManagerEmail}
/>
<ReviewRow
label="GM phone"
value={`${formValues.generalManagerPhoneCountryCode}${formValues.generalManagerPhone}`}
/>
<ReviewRow
label="PoA name"
value={formValues.poaName || undefined}
/>
<ReviewRow
label="PoA phone"
value={
formValues.poaPhone && formValues.poaPhoneCountryCode
? `${formValues.poaPhoneCountryCode}${formValues.poaPhone}`
: undefined
}
/>
<ReviewRow
label="PoA email"
value={formValues.poaEmail || undefined}
/>
<ReviewRow
label="PoA location"
value={formValues.poaLocation || undefined}
/>
</div>
</div>
)}
</FieldGroup>
<div className="flex items-center justify-between pt-2">
<Button type="button" variant="outline" onClick={prevStep}>
<ArrowLeft />
{step === "company" ? "Change Type" : "Back"}
{step === "company"
? "Change Type"
: step === "confirm"
? "Back to Documents"
: "Back"}
</Button>
<Button type="button" onClick={nextStep} disabled={isPending}>
{isPending ? (
<>
<Loader2 className="animate-spin" />
Submitting...
</>
) : step === "poa" ? (
"Complete Registration"
) : (
<>
Next Step
<ArrowRight />
</>
)}
</Button>
<div className="flex items-center gap-3">
<Button
type="button"
onClick={step === "confirm" ? handleSubmit((data) => onSubmit(buildPayload(data, user))) : nextStep}
disabled={isPending || (step === "documents" && !hasDocuments && loadingDocuments)}
>
{isPending ? (
<>
<Loader2 className="animate-spin" />
Submitting...
</>
) : step === "documents" ? (
"Continue"
) : step === "confirm" ? (
"Submit Registration"
) : (
<>
Next Step
<ArrowRight />
</>
)}
</Button>
</div>
</div>
</form>
</>
);
}
function ReviewRow({ label, value }: { label: string; value?: string | null }) {
return (
<div className="rounded-lg border border-border bg-muted/20 p-3">
<div className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
{label}
</div>
<div className="mt-1 text-sm font-medium text-foreground">
{value?.trim() ? value : "Not provided"}
</div>
</div>
);
}
function StepIcon({
icon,
active,
@@ -560,13 +677,12 @@ function StepIcon({
}) {
return (
<div
className={`relative z-10 flex h-10 w-10 items-center justify-center rounded-full border-2 transition-all ${
completed
className={`relative z-10 flex h-10 w-10 items-center justify-center rounded-full border-2 transition-all ${completed
? "bg-primary border-primary text-primary-foreground"
: active
? "bg-background border-primary text-primary shadow-md"
: "bg-background border-border text-muted-foreground"
}`}
}`}
>
{completed ? <CheckCircle2 className="size-5" /> : icon}
</div>

View File

@@ -1,5 +1,6 @@
import { useState } from "react";
import { useForm } from "react-hook-form";
import { useQuery } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
@@ -10,9 +11,10 @@ import {
CheckCircle2,
Loader2,
ChevronLeft,
UploadCloud,
} from "lucide-react";
import type { AuthUser } from "@/types/auth";
import type { CreateCustomerDto } from "@/types/customers";
import type { CreateCompanyPayload } from "@/services/companies.service";
import PhoneInput from "@/components/auth/PhoneInput";
import {
Button,
@@ -21,9 +23,11 @@ import {
FieldLabel,
FieldError,
FieldGroup,
SmartFileInput,
} from "@edr/ui-common";
import { api } from "@/services/api";
type DjiboutiStep = "company" | "representative";
type DjiboutiStep = "company" | "representative" | "documents" | "confirm";
const djiboutiSchema = z.object({
companyName: z.string().min(1, "Company name is required"),
@@ -40,52 +44,81 @@ const djiboutiSchema = z.object({
type FormData = z.infer<typeof djiboutiSchema>;
const stepLabels: Record<DjiboutiStep, string> = {
company: "Step 1 of 2 — Company Information",
representative: "Step 2 of 2 — Representative Details",
const stepFields: Record<DjiboutiStep, (keyof FormData)[]> = {
company: [
"companyName",
"companyEmail",
"companyPhone",
"companyPhoneCountryCode",
"companyLocation",
"companyAddress",
],
representative: [
"repName",
"repEmail",
"repPhone",
"repPhoneCountryCode",
],
documents: [],
confirm: [],
};
function buildPayload(data: FormData, user: AuthUser): CreateCustomerDto {
const nameParts = (user.name?.en ?? "").split(" ");
function buildPayload(data: FormData, _user: AuthUser): CreateCompanyPayload {
return {
userId: user.id,
firstName: nameParts[0] || "",
lastName: nameParts.slice(-1)[0] || "",
email: user.email,
phone: user.phoneNumber,
companyName: data.companyName,
companyEmail: data.companyEmail,
companyPhone: `${data.companyPhoneCountryCode}${data.companyPhone}`,
companyLocation: data.companyLocation,
companyAddress: data.companyAddress,
contactPersonName: data.repName,
contactPersonPhone: `${data.repPhoneCountryCode}${data.repPhone}`,
tinNumber: "",
tin: "",
vatNumber: "",
fanNumber: "",
generalManagerName: "",
generalManagerEmail: "",
generalManagerPhone: "",
attributes: {
repName: data.repName,
repEmail: data.repEmail,
repPhone: `${data.repPhoneCountryCode}${data.repPhone}`,
},
};
}
export default function DjiboutiAgentForm({
documentSettingCode,
documentFiles: controlledFiles,
onDocumentFilesChange,
user,
onSubmit,
isPending,
onBack,
}: {
documentSettingCode: string;
documentFiles?: Record<string, File | File[] | null>;
onDocumentFilesChange?: (
files: Record<string, File | File[] | null>,
) => void;
user: AuthUser;
onSubmit: (data: CreateCustomerDto) => void;
onSubmit: (data: CreateCompanyPayload) => void;
isPending: boolean;
onBack: () => void;
}) {
const [step, setStep] = useState<DjiboutiStep>("company");
const [internalFiles, setInternalFiles] = useState<
Record<string, File | File[] | null>
>({});
const documentFiles = controlledFiles ?? internalFiles;
const setDocumentFiles = onDocumentFilesChange ?? setInternalFiles;
const { data: uploadSetting, isLoading: loadingDocuments } = useQuery(
api.fileUploadSettings.getByCode.queryOptions({
input: { code: documentSettingCode },
refetchOnMount: false,
}),
);
const {
register,
handleSubmit,
trigger,
watch,
formState: { errors },
} = useForm<FormData>({
resolver: zodResolver(djiboutiSchema),
@@ -103,32 +136,42 @@ export default function DjiboutiAgentForm({
},
});
const formValues = watch();
const hasDocuments = Boolean(uploadSetting?.fields?.length);
const totalSteps = 4;
const nextStep = async () => {
if (step === "representative") {
setStep("documents");
return;
}
if (step === "documents") {
setStep("confirm");
return;
}
if (step === "confirm") {
handleSubmit((data) => onSubmit(buildPayload(data, user)))();
return;
}
const fields: (keyof FormData)[] =
step === "company"
? [
"companyName",
"companyEmail",
"companyPhone",
"companyPhoneCountryCode",
"companyLocation",
"companyAddress",
]
: ["repName", "repEmail", "repPhone", "repPhoneCountryCode"];
const fields = stepFields[step];
const isValid = await trigger(fields);
if (!isValid) return;
setStep("representative");
};
const skipDocuments = () => {
setStep("confirm");
};
const prevStep = () => {
if (step === "company") {
onBack();
} else {
} else if (step === "representative") {
setStep("company");
} else if (step === "documents") {
setStep("representative");
} else {
setStep("documents");
}
};
@@ -149,21 +192,34 @@ export default function DjiboutiAgentForm({
<StepIcon
icon={<Building2 className="size-5" />}
active={step === "company"}
completed={step === "representative"}
completed={step !== "company"}
/>
<StepIcon
icon={<UserRound className="size-5" />}
active={step === "representative"}
completed={step === "documents" || step === "confirm"}
/>
<StepIcon
icon={<UploadCloud className="size-5" />}
active={step === "documents"}
completed={step === "confirm"}
/>
<StepIcon
icon={<CheckCircle2 className="size-5" />}
active={step === "confirm"}
completed={false}
/>
</div>
<p className="text-center text-sm text-muted-foreground mt-3">
{stepLabels[step]}
{step === "company" && `Step 1 of ${totalSteps} — Company Information`}
{step === "representative" && `Step 2 of ${totalSteps} — Representative Details`}
{step === "documents" && `Step 3 of ${totalSteps} — Upload Documents (Optional)`}
{step === "confirm" && `Step 4 of ${totalSteps} — Review & Confirm`}
</p>
</div>
<form
onSubmit={handleSubmit((data) => onSubmit(buildPayload(data, user)))}
onSubmit={(e) => e.preventDefault()}
className="flex flex-col gap-4"
>
<FieldGroup className="gap-4">
@@ -268,35 +324,120 @@ export default function DjiboutiAgentForm({
</div>
</>
)}
{step === "documents" && (
<>
{loadingDocuments ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="size-6 animate-spin text-muted-foreground" />
</div>
) : !uploadSetting ? (
<p className="text-sm text-muted-foreground text-center py-4">
No document requirements found for your account type.
</p>
) : (
<div className="flex flex-col gap-6">
<SmartFileInput
file={uploadSetting}
value={documentFiles}
onChange={setDocumentFiles}
/>
</div>
)}
</>
)}
{step === "confirm" && (
<div className="space-y-4 rounded-xl border border-border bg-card p-4">
<div>
<h3 className="text-base font-semibold text-foreground">
Review your registration
</h3>
<p className="text-sm text-muted-foreground mt-1">
Confirm the company details below before saving.
</p>
</div>
<div className="grid gap-3 md:grid-cols-2">
<ReviewRow label="Company name" value={formValues.companyName} />
<ReviewRow label="Company email" value={formValues.companyEmail} />
<ReviewRow label="Company phone" value={formValues.companyPhone} />
<ReviewRow label="Location" value={formValues.companyLocation} />
<ReviewRow label="Address" value={formValues.companyAddress} />
<ReviewRow label="Rep. name" value={formValues.repName} />
<ReviewRow label="Rep. email" value={formValues.repEmail} />
<ReviewRow
label="Rep. phone"
value={`${formValues.repPhoneCountryCode}${formValues.repPhone}`}
/>
</div>
</div>
)}
</FieldGroup>
<div className="flex items-center justify-between pt-2">
<Button type="button" variant="outline" onClick={prevStep}>
<ArrowLeft />
{step === "company" ? "Change Type" : "Back"}
{step === "company"
? "Change Type"
: step === "confirm"
? "Back to Documents"
: "Back"}
</Button>
<Button type="button" onClick={nextStep} disabled={isPending}>
{isPending ? (
<>
<Loader2 className="animate-spin" />
Submitting...
</>
) : step === "representative" ? (
"Complete Registration"
) : (
<>
Next Step
<ArrowRight />
</>
<div className="flex items-center gap-3">
{step === "documents" && (
<Button
type="button"
variant="outline"
onClick={skipDocuments}
disabled={isPending}
>
Skip for now
</Button>
)}
</Button>
<Button
type="button"
onClick={step === "confirm" ? handleSubmit((data) => onSubmit(buildPayload(data, user))) : nextStep}
disabled={isPending || (step === "documents" && !hasDocuments && loadingDocuments)}
>
{isPending ? (
<>
<Loader2 className="animate-spin" />
Submitting...
</>
) : step === "documents" ? (
"Continue"
) : step === "confirm" ? (
"Submit Registration"
) : (
<>
Next Step
<ArrowRight />
</>
)}
</Button>
</div>
</div>
</form>
</>
);
}
function ReviewRow({ label, value }: { label: string; value?: string | null }) {
return (
<div className="rounded-lg border border-border bg-muted/20 p-3">
<div className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
{label}
</div>
<div className="mt-1 text-sm font-medium text-foreground">
{value?.trim() ? value : "Not provided"}
</div>
</div>
);
}
function StepIcon({
icon,
active,

View File

@@ -1,6 +1,6 @@
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { useQuery } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
@@ -11,11 +11,11 @@ import {
FileText,
CheckCircle2,
Loader2,
ChevronLeft,
UploadCloud,
} from "lucide-react";
import useAuth from "@/hooks/useAuth";
import { api } from "@/services/api";
import type { CreateCustomerDto } from "@/types/customers";
import AuthLayout from "@/components/auth/AuthLayout";
import type { AuthUser } from "@/types/auth";
import type { CreateCompanyPayload } from "@/services/companies.service";
import PhoneInput from "@/components/auth/PhoneInput";
import {
Button,
@@ -24,14 +24,13 @@ import {
FieldLabel,
FieldError,
FieldGroup,
SmartFileInput,
} from "@edr/ui-common";
import TransporterOnboarding from "./TransportrOnBoarding";
import DjiboutiForwardingAgentForm from "./DjiboutiFreightForwardingAgent";
import ImportExportOnBoarding from "./ImportExportOnBoarding";
import { api } from "@/services/api";
type OnboardingStep = "company" | "personnel" | "poa";
type ForwarderStep = "company" | "personnel" | "poa" | "documents" | "confirm";
const onboardingSchema = z.object({
const forwarderSchema = z.object({
companyName: z.string().min(1, "Company name is required"),
companyEmail: z.string().email("Invalid email address"),
companyPhone: z.string().min(1, "Company phone is required"),
@@ -59,9 +58,9 @@ const onboardingSchema = z.object({
poaLocation: z.string().optional(),
});
type FormData = z.infer<typeof onboardingSchema>;
type FormData = z.infer<typeof forwarderSchema>;
const stepFields: Record<OnboardingStep, (keyof FormData)[]> = {
const stepFields: Record<ForwarderStep, (keyof FormData)[]> = {
company: [
"companyName",
"companyEmail",
@@ -83,20 +82,79 @@ const stepFields: Record<OnboardingStep, (keyof FormData)[]> = {
"generalManagerPhoneCountryCode",
],
poa: [],
documents: [],
confirm: [],
};
export default function CustomerOnboardingPage() {
const queryClient = useQueryClient();
const { user } = useAuth();
const [step, setStep] = useState<OnboardingStep>("company");
function buildPayload(data: FormData, _user: AuthUser): CreateCompanyPayload {
return {
companyName: data.companyName,
companyEmail: data.companyEmail,
companyPhone: `${data.companyPhoneCountryCode}${data.companyPhone}`,
companyLocation: data.companyLocation,
companyAddress: data.companyAddress,
tin: data.tinNumber,
vatNumber: data.vatNumber,
fanNumber: data.fanNumber,
attributes: {
contactPersonName: data.contactPersonName,
contactPersonPhone: `${data.contactPersonPhoneCountryCode}${data.contactPersonPhone}`,
generalManagerName: data.generalManagerName,
generalManagerEmail: data.generalManagerEmail,
generalManagerPhone: `${data.generalManagerPhoneCountryCode}${data.generalManagerPhone}`,
poaName: data.poaName || undefined,
poaPhone:
data.poaPhone && data.poaPhoneCountryCode
? `${data.poaPhoneCountryCode}${data.poaPhone}`
: undefined,
poaAddress: data.poaAddress || undefined,
poaEmail: data.poaEmail || undefined,
poaLocation: data.poaLocation || undefined,
},
};
}
export default function ForwarderForm({
documentSettingCode,
documentFiles: controlledFiles,
onDocumentFilesChange,
user,
onSubmit,
isPending,
onBack,
}: {
documentSettingCode: string;
documentFiles?: Record<string, File | File[] | null>;
onDocumentFilesChange?: (
files: Record<string, File | File[] | null>,
) => void;
user: AuthUser;
onSubmit: (data: CreateCompanyPayload) => void;
isPending: boolean;
onBack: () => void;
}) {
const [step, setStep] = useState<ForwarderStep>("company");
const [internalFiles, setInternalFiles] = useState<
Record<string, File | File[] | null>
>({});
const documentFiles = controlledFiles ?? internalFiles;
const setDocumentFiles = onDocumentFilesChange ?? setInternalFiles;
const { data: uploadSetting, isLoading: loadingDocuments } = useQuery(
api.fileUploadSettings.getByCode.queryOptions({
input: { code: documentSettingCode },
refetchOnMount: false,
}),
);
const {
register,
handleSubmit,
trigger,
watch,
formState: { errors },
} = useForm<FormData>({
resolver: zodResolver(onboardingSchema),
resolver: zodResolver(forwarderSchema),
defaultValues: {
companyName: "",
companyEmail: "",
@@ -123,20 +181,21 @@ export default function CustomerOnboardingPage() {
},
});
const createCustomerMutation = useMutation({
mutationFn: (payload: CreateCustomerDto) =>
api.customers.create.call(payload),
onSuccess: () => {
if (user)
queryClient.invalidateQueries({
queryKey: api.customers.getByUserId.queryKey({ id: user.id }),
});
},
});
const formValues = watch();
const hasDocuments = Boolean(uploadSetting?.fields?.length);
const totalSteps = 5;
const nextStep = async () => {
if (step === "poa") {
handleSubmit(onSubmit)();
setStep("documents");
return;
}
if (step === "documents") {
setStep("confirm");
return;
}
if (step === "confirm") {
handleSubmit((data) => onSubmit(buildPayload(data, user)))();
return;
}
const fields = stepFields[step];
@@ -145,69 +204,36 @@ export default function CustomerOnboardingPage() {
setStep(step === "company" ? "personnel" : "poa");
};
const prevStep = () => {
if (step === "personnel") setStep("company");
else if (step === "poa") setStep("personnel");
const skipDocuments = () => {
setStep("confirm");
};
const onSubmit = async (data: FormData) => {
const nameParts = (user?.name?.en ?? "").split(" ");
const payload: CreateCustomerDto = {
userId: user!.id,
firstName: nameParts[0] || "",
lastName: nameParts.slice(-1)[0] || "",
email: user!.email,
phone: user!.phoneNumber,
companyName: data.companyName,
companyEmail: data.companyEmail,
companyPhone: `${data.companyPhoneCountryCode}${data.companyPhone}`,
companyLocation: data.companyLocation,
companyAddress: data.companyAddress,
contactPersonName: data.contactPersonName,
contactPersonPhone: `${data.contactPersonPhoneCountryCode}${data.contactPersonPhone}`,
tinNumber: data.tinNumber,
vatNumber: data.vatNumber,
fanNumber: data.fanNumber,
generalManagerName: data.generalManagerName,
generalManagerEmail: data.generalManagerEmail,
generalManagerPhone: `${data.generalManagerPhoneCountryCode}${data.generalManagerPhone}`,
poaName: data.poaName || undefined,
poaPhone:
data.poaPhone && data.poaPhoneCountryCode
? `${data.poaPhoneCountryCode}${data.poaPhone}`
: undefined,
poaAddress: data.poaAddress || undefined,
poaEmail: data.poaEmail || undefined,
poaLocation: data.poaLocation || undefined,
};
createCustomerMutation.mutate(payload);
const prevStep = () => {
if (step === "company") {
onBack();
} else if (step === "personnel") {
setStep("company");
} else if (step === "poa") {
setStep("personnel");
} else if (step === "documents") {
setStep("poa");
} else {
setStep("documents");
}
};
return (
<AuthLayout
left={{
badge: "Complete Your Profile",
title: "Set up your company profile",
description:
"Provide your business details to start using EDR Freight for managing shipments, tracking consignments, and streamlining logistics operations across Ethiopia and Djibouti.",
features: [
"Company registration details",
"Contact and management personnel",
"Power of Attorney (optional)",
],
stats: {
label: "Active Customers",
value: "500+",
footer: "And growing",
progress: "w-[95%]",
},
}}
>
<>
<div className="mb-8">
<button
type="button"
onClick={prevStep}
className="mb-4 flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ChevronLeft className="size-4" />
Change account type
</button>
<TransporterOnboarding />
{/* <DjiboutiForwardingAgentForm /> */}
{/* <ImportExportOnBoarding /> */}
{/* <div className="mb-8 lg:col-span-2">
<div className="flex items-center justify-between max-w-lg mx-auto relative px-2">
<div className="absolute top-1/2 left-0 w-full h-0.5 bg-border -translate-y-1/2 z-0" />
<StepIcon
@@ -218,22 +244,41 @@ export default function CustomerOnboardingPage() {
<StepIcon
icon={<User className="size-5" />}
active={step === "personnel"}
completed={step === "poa"}
completed={step === "poa" || step === "documents" || step === "confirm"}
/>
<StepIcon
icon={<FileText className="size-5" />}
active={step === "poa"}
completed={step === "documents" || step === "confirm"}
/>
<StepIcon
icon={<UploadCloud className="size-5" />}
active={step === "documents"}
completed={step === "confirm"}
/>
<StepIcon
icon={<CheckCircle2 className="size-5" />}
active={step === "confirm"}
completed={false}
/>
</div>
<p className="text-center text-sm text-muted-foreground mt-3">
{step === "company" && "Step 1 of 3 — Company Information"}
{step === "personnel" && "Step 2 of 3 — Personnel Details"}
{step === "poa" && "Step 3 of 3 — Power of Attorney (Optional)"}
{step === "company" &&
`Step 1 of ${totalSteps} — Company Information`}
{step === "personnel" &&
`Step 2 of ${totalSteps} — Personnel Details`}
{step === "poa" &&
`Step 3 of ${totalSteps} — Power of Attorney (Optional)`}
{step === "documents" &&
`Step 4 of ${totalSteps} — Upload Documents (Optional)`}
{step === "confirm" && `Step 5 of ${totalSteps} — Review & Confirm`}
</p>
</div> */}
</div>
{/* <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
<form
onSubmit={(e) => e.preventDefault()}
className="flex flex-col gap-4"
>
<FieldGroup className="gap-4">
{step === "company" && (
<>
@@ -332,11 +377,6 @@ export default function CustomerOnboardingPage() {
{step === "personnel" && (
<>
<p className="text-sm text-muted-foreground">
Personal details are pulled from your account. Contact and
management info is collected below.
</p>
<div>
<h3 className="text-sm font-semibold text-foreground mb-3">
Contact Person
@@ -418,88 +458,212 @@ export default function CustomerOnboardingPage() {
{step === "poa" && (
<>
<p className="text-sm text-muted-foreground">
Power of Attorney details are optional. Skip if not applicable.
Power of Attorney details are optional. Fill them in if you have
them, or skip to continue.
</p>
<Field>
<Field data-invalid={Boolean(errors.poaName)}>
<FieldLabel>PoA Name</FieldLabel>
<Input
placeholder="Authorized Representative Name"
aria-invalid={Boolean(errors.poaName)}
{...register("poaName")}
/>
<FieldError errors={[errors.poaName]} />
</Field>
<div className="grid grid-cols-2 gap-4">
<Field>
<Field data-invalid={Boolean(errors.poaEmail)}>
<FieldLabel>PoA Email</FieldLabel>
<Input
type="email"
placeholder="poa@company.com"
aria-invalid={Boolean(errors.poaEmail)}
{...register("poaEmail")}
/>
<FieldError errors={[errors.poaEmail]} />
</Field>
<PhoneInput
countryCode={{ ...register("poaPhoneCountryCode") }}
phone={{ ...register("poaPhone"), placeholder: "912345678" }}
label="PoA Phone"
countryCodeError={errors.poaPhoneCountryCode}
phoneError={errors.poaPhone}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<Field>
<Field data-invalid={Boolean(errors.poaLocation)}>
<FieldLabel>PoA Location</FieldLabel>
<Input
placeholder="City, Country"
aria-invalid={Boolean(errors.poaLocation)}
{...register("poaLocation")}
/>
<FieldError errors={[errors.poaLocation]} />
</Field>
<Field>
<Field data-invalid={Boolean(errors.poaAddress)}>
<FieldLabel>PoA Address</FieldLabel>
<Input
placeholder="Full Address"
aria-invalid={Boolean(errors.poaAddress)}
{...register("poaAddress")}
/>
<FieldError errors={[errors.poaAddress]} />
</Field>
</div>
</>
)}
{step === "documents" && (
<>
{loadingDocuments ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="size-6 animate-spin text-muted-foreground" />
</div>
) : !uploadSetting ? (
<p className="text-sm text-muted-foreground text-center py-4">
No document requirements found for your account type.
</p>
) : (
<div className="flex flex-col gap-6">
<SmartFileInput
file={uploadSetting}
value={documentFiles}
onChange={setDocumentFiles}
/>
</div>
)}
</>
)}
{step === "confirm" && (
<div className="space-y-4 rounded-xl border border-border bg-card p-4">
<div>
<h3 className="text-base font-semibold text-foreground">
Review your registration
</h3>
<p className="text-sm text-muted-foreground mt-1">
Confirm the company details below before saving.
</p>
</div>
<div className="grid gap-3 md:grid-cols-2">
<ReviewRow label="Company name" value={formValues.companyName} />
<ReviewRow label="Company email" value={formValues.companyEmail} />
<ReviewRow label="Company phone" value={formValues.companyPhone} />
<ReviewRow label="Location" value={formValues.companyLocation} />
<ReviewRow label="Address" value={formValues.companyAddress} />
<ReviewRow label="TIN" value={formValues.tinNumber} />
<ReviewRow label="VAT" value={formValues.vatNumber} />
<ReviewRow label="FAN" value={formValues.fanNumber} />
<ReviewRow
label="Contact person"
value={formValues.contactPersonName}
/>
<ReviewRow
label="Contact phone"
value={`${formValues.contactPersonPhoneCountryCode}${formValues.contactPersonPhone}`}
/>
<ReviewRow
label="General manager"
value={formValues.generalManagerName}
/>
<ReviewRow
label="GM email"
value={formValues.generalManagerEmail}
/>
<ReviewRow
label="GM phone"
value={`${formValues.generalManagerPhoneCountryCode}${formValues.generalManagerPhone}`}
/>
<ReviewRow
label="PoA name"
value={formValues.poaName || undefined}
/>
<ReviewRow
label="PoA phone"
value={
formValues.poaPhone && formValues.poaPhoneCountryCode
? `${formValues.poaPhoneCountryCode}${formValues.poaPhone}`
: undefined
}
/>
<ReviewRow
label="PoA email"
value={formValues.poaEmail || undefined}
/>
<ReviewRow
label="PoA location"
value={formValues.poaLocation || undefined}
/>
</div>
</div>
)}
</FieldGroup>
<div className="flex items-center justify-between pt-2">
<Button
type="button"
variant="outline"
onClick={prevStep}
disabled={step === "company"}
>
<Button type="button" variant="outline" onClick={prevStep}>
<ArrowLeft />
Back
{step === "company"
? "Change Type"
: step === "confirm"
? "Back to Documents"
: "Back"}
</Button>
<Button
type="button"
onClick={nextStep}
disabled={createCustomerMutation.isPending}
>
{createCustomerMutation.isPending ? (
<>
<Loader2 className="animate-spin" />
Submitting...
</>
) : step === "poa" ? (
"Complete Registration"
) : (
<>
Next Step
<ArrowRight />
</>
<div className="flex items-center gap-3">
{step === "documents" && (
<Button
type="button"
variant="outline"
onClick={skipDocuments}
disabled={isPending}
>
Skip for now
</Button>
)}
</Button>
<Button
type="button"
onClick={step === "confirm" ? handleSubmit((data) => onSubmit(buildPayload(data, user))) : nextStep}
disabled={isPending || (step === "documents" && !hasDocuments && loadingDocuments)}
>
{isPending ? (
<>
<Loader2 className="animate-spin" />
Submitting...
</>
) : step === "documents" ? (
"Continue"
) : step === "confirm" ? (
"Submit Registration"
) : (
<>
Next Step
<ArrowRight />
</>
)}
</Button>
</div>
</div>
</form> */}
</AuthLayout>
</form>
</>
);
}
function ReviewRow({ label, value }: { label: string; value?: string | null }) {
return (
<div className="rounded-lg border border-border bg-muted/20 p-3">
<div className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
{label}
</div>
<div className="mt-1 text-sm font-medium text-foreground">
{value?.trim() ? value : "Not provided"}
</div>
</div>
);
}

View File

@@ -10,9 +10,11 @@ import {
} from "lucide-react";
import useAuth from "@/hooks/useAuth";
import { api } from "@/services/api";
import type { CreateCustomerDto } from "@/types/customers";
import { companiesService } from "@/services/companies.service";
import type { CreateCompanyPayload } from "@/services/companies.service";
import AuthLayout from "@/components/auth/AuthLayout";
import CompanyProfileForm from "./CompanyProfileForm";
import ForwarderForm from "./ForwarderForm";
import DjiboutiAgentForm from "./DjiboutiAgentForm";
import TransporterForm from "./TransporterForm";
import type { OnboardingUserType } from "./types";
@@ -23,40 +25,37 @@ const USER_TYPE_CARDS: {
description: string;
icon: React.ReactNode;
}[] = [
{
id: "importer",
label: "Importer",
description: "Import goods into Ethiopia via the railway corridor.",
icon: <ArrowDownToLine className="size-6" />,
},
{
id: "exporter",
label: "Exporter",
description: "Export goods from Ethiopia via rail.",
icon: <ArrowUpFromLine className="size-6" />,
},
{
id: "freight-forwarder-et",
label: "Freight Forwarder (Ethiopia)",
description:
"Ethiopian freight forwarding company handling client cargo.",
icon: <Building2 className="size-6" />,
},
{
id: "freight-forwarder-dj",
label: "FF Agent (Djibouti)",
description:
"Djibouti-based agent coordinating cross-border logistics.",
icon: <Ship className="size-6" />,
},
{
id: "transporter",
label: "Transporter",
description:
"Trucking company providing first/last-mile services.",
icon: <Truck className="size-6" />,
},
];
{
id: "importer",
label: "Importer",
description: "Import goods into Ethiopia via the railway corridor.",
icon: <ArrowDownToLine className="size-6" />,
},
{
id: "exporter",
label: "Exporter",
description: "Export goods from Ethiopia via rail.",
icon: <ArrowUpFromLine className="size-6" />,
},
{
id: "freight-forwarder-et",
label: "Freight Forwarder (Ethiopia)",
description: "Ethiopian freight forwarding company handling client cargo.",
icon: <Building2 className="size-6" />,
},
{
id: "freight-forwarder-dj",
label: "FF Agent (Djibouti)",
description: "Djibouti-based agent coordinating cross-border logistics.",
icon: <Ship className="size-6" />,
},
{
id: "transporter",
label: "Transporter",
description: "Trucking company providing first/last-mile services.",
icon: <Truck className="size-6" />,
},
];
const USER_TYPE_LEFT_MAP: Record<
OnboardingUserType,
@@ -116,26 +115,54 @@ const PREFLIGHT_LEFT = {
},
};
const DOCUMENT_SETTING_CODE_MAP: Record<OnboardingUserType, string> = {
importer: "company_onboarding_documents_customer",
exporter: "company_onboarding_documents_customer",
"freight-forwarder-et": "company_onboarding_documents_forwarder",
"freight-forwarder-dj": "company_onboarding_documents_forwarder_dj",
transporter: "company_onboarding_documents_transporter",
};
export default function OnboardingPage() {
const queryClient = useQueryClient();
const { user } = useAuth();
const [userType, setUserType] = useState<OnboardingUserType | null>(null);
const [documentFiles, setDocumentFiles] = useState<
Record<string, File | File[] | null>
>({});
const createCustomerMutation = useMutation({
mutationFn: (payload: CreateCustomerDto) =>
api.customers.create.call(payload),
onSuccess: () => {
if (user)
queryClient.invalidateQueries({
queryKey: api.customers.getByUserId.queryKey({ id: user.id }),
});
const COMPANY_TYPE_MAP: Record<OnboardingUserType, string> = {
importer: "customer",
exporter: "customer",
"freight-forwarder-et": "forwarder",
"freight-forwarder-dj": "forwarder",
transporter: "transporter",
};
const createCompanyMutation = useMutation({
mutationFn: (payload: CreateCompanyPayload) =>
api.companies.create.call(payload),
onSuccess: async (data) => {
const hasFiles = Object.values(documentFiles).some(
(f) => f !== null && (Array.isArray(f) ? f.length > 0 : true),
);
if (hasFiles) {
await companiesService.uploadDocuments(data.company.id, documentFiles);
}
await queryClient.invalidateQueries({
queryKey: api.companies.getInfo.queryKey(),
});
},
});
if (!user) return null;
const handleSubmit = (payload: CreateCustomerDto) => {
createCustomerMutation.mutate(payload);
const handleSubmit = (payload: CreateCompanyPayload) => {
const enriched: CreateCompanyPayload = {
...payload,
companyType: COMPANY_TYPE_MAP[userType!],
};
createCompanyMutation.mutate(enriched);
};
const handleSelectType = (type: OnboardingUserType) => {
@@ -172,9 +199,7 @@ export default function OnboardingPage() {
{card.icon}
</div>
<div>
<p className="font-semibold text-foreground">
{card.label}
</p>
<p className="font-semibold text-foreground">{card.label}</p>
<p className="mt-0.5 text-xs text-muted-foreground leading-relaxed">
{card.description}
</p>
@@ -197,21 +222,21 @@ export default function OnboardingPage() {
features:
userType === "transporter"
? [
"Vehicle & fleet registration",
"TIN & FAN verification",
"First-mile / Last-mile eligibility",
]
"Vehicle & fleet registration",
"TIN & FAN verification",
"First-mile / Last-mile eligibility",
]
: userType === "freight-forwarder-dj"
? [
"Company details",
"Representative information",
"Cross-border operations",
]
"Company details",
"Representative information",
"Cross-border operations",
]
: [
"Company registration details",
"Contact and management personnel",
"Power of Attorney (optional)",
],
"Company registration details",
"Contact and management personnel",
"Power of Attorney (optional)",
],
stats: {
label: "Active Customers",
value: "500+",
@@ -224,24 +249,42 @@ export default function OnboardingPage() {
<AuthLayout left={leftProps}>
{userType === "transporter" ? (
<TransporterForm
documentSettingCode={DOCUMENT_SETTING_CODE_MAP[userType]}
documentFiles={documentFiles}
onDocumentFilesChange={setDocumentFiles}
user={user}
onSubmit={handleSubmit}
isPending={createCustomerMutation.isPending}
isPending={createCompanyMutation.isPending}
onBack={handleBack}
/>
) : userType === "freight-forwarder-dj" ? (
<DjiboutiAgentForm
documentSettingCode={DOCUMENT_SETTING_CODE_MAP[userType]}
documentFiles={documentFiles}
onDocumentFilesChange={setDocumentFiles}
user={user}
onSubmit={handleSubmit}
isPending={createCustomerMutation.isPending}
isPending={createCompanyMutation.isPending}
onBack={handleBack}
/>
) : userType === "freight-forwarder-et" ? (
<ForwarderForm
documentSettingCode={DOCUMENT_SETTING_CODE_MAP[userType]}
documentFiles={documentFiles}
onDocumentFilesChange={setDocumentFiles}
user={user}
onSubmit={handleSubmit}
isPending={createCompanyMutation.isPending}
onBack={handleBack}
/>
) : (
<CompanyProfileForm
userType={userType}
documentSettingCode={DOCUMENT_SETTING_CODE_MAP[userType]}
documentFiles={documentFiles}
onDocumentFilesChange={setDocumentFiles}
user={user}
onSubmit={handleSubmit}
isPending={createCustomerMutation.isPending}
isPending={createCompanyMutation.isPending}
onBack={handleBack}
/>
)}

View File

@@ -1,14 +1,19 @@
import { useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { useQuery } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
Loader2,
ArrowRight,
ArrowLeft,
ChevronLeft,
Truck,
Info,
CheckCircle2,
Loader2,
UploadCloud,
} from "lucide-react";
import type { AuthUser } from "@/types/auth";
import type { CreateCustomerDto } from "@/types/customers";
import type { CreateCompanyPayload } from "@/services/companies.service";
import {
Button,
Input,
@@ -20,8 +25,10 @@ import {
SelectItem,
SelectTrigger,
SelectValue,
SmartFileInput,
} from "@edr/ui-common";
import { cn } from "@/lib/utils";
import { api } from "@/services/api";
const TRUCK_TYPES = [
"Casoni",
@@ -31,6 +38,8 @@ const TRUCK_TYPES = [
"Others",
] as const;
type TransporterStep = "vehicle" | "documents" | "confirm";
const transporterSchema = z
.object({
tinNumber: z.string().length(10, "TIN must be exactly 10 digits"),
@@ -45,7 +54,10 @@ const transporterSchema = z
.regex(/^\d{4}$/, "Enter a valid year (e.g. 2023)"),
})
.superRefine((data, ctx) => {
if (data.truckType === "Casoni" && (!data.plateNumber2 || data.plateNumber2.trim().length === 0)) {
if (
data.truckType === "Casoni" &&
(!data.plateNumber2 || data.plateNumber2.trim().length === 0)
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["plateNumber2"],
@@ -56,51 +68,63 @@ const transporterSchema = z
type FormData = z.infer<typeof transporterSchema>;
function buildPayload(data: FormData, user: AuthUser): CreateCustomerDto {
const nameParts = (user.name?.en ?? "").split(" ");
function buildPayload(data: FormData, user: AuthUser): CreateCompanyPayload {
return {
userId: user.id,
firstName: nameParts[0] || "",
lastName: nameParts.slice(-1)[0] || "",
email: user.email,
phone: user.phoneNumber,
companyName: "",
companyEmail: "",
companyPhone: "",
companyName: user.name?.en ?? "",
companyEmail: user.email,
companyPhone: user.phoneNumber,
companyLocation: "",
companyAddress: "",
contactPersonName: "",
contactPersonPhone: "",
tinNumber: data.tinNumber,
tin: data.tinNumber,
vatNumber: "",
fanNumber: data.fanNumber,
generalManagerName: "",
generalManagerEmail: "",
generalManagerPhone: "",
notes: JSON.stringify({
attributes: {
truckType: data.truckType,
plateNumber: data.plateNumber,
plateNumber2: data.plateNumber2 || null,
vehicleModel: data.vehicleModel,
yearOfManufacturing: data.yearOfManufacturing,
}),
},
};
}
export default function TransporterForm({
documentSettingCode,
documentFiles: controlledFiles,
onDocumentFilesChange,
user,
onSubmit,
isPending,
onBack,
}: {
documentSettingCode: string;
documentFiles?: Record<string, File | File[] | null>;
onDocumentFilesChange?: (
files: Record<string, File | File[] | null>,
) => void;
user: AuthUser;
onSubmit: (data: CreateCustomerDto) => void;
onSubmit: (data: CreateCompanyPayload) => void;
isPending: boolean;
onBack: () => void;
}) {
const [step, setStep] = useState<TransporterStep>("vehicle");
const [internalFiles, setInternalFiles] = useState<
Record<string, File | File[] | null>
>({});
const documentFiles = controlledFiles ?? internalFiles;
const setDocumentFiles = onDocumentFilesChange ?? setInternalFiles;
const { data: uploadSetting, isLoading: loadingDocuments } = useQuery(
api.fileUploadSettings.getByCode.queryOptions({
input: { code: documentSettingCode },
refetchOnMount: false,
}),
);
const {
register,
handleSubmit,
trigger,
watch,
control,
formState: { errors },
@@ -119,187 +143,341 @@ export default function TransporterForm({
const truckType = watch("truckType");
const isCasoni = truckType === "Casoni";
const formValues = watch();
const hasDocuments = Boolean(uploadSetting?.fields?.length);
const totalSteps = 3;
const nextStep = async () => {
if (step === "documents") {
setStep("confirm");
return;
}
if (step === "confirm") {
handleSubmit((data) => onSubmit(buildPayload(data, user)))();
return;
}
const fields: (keyof FormData)[] = [
"tinNumber",
"fanNumber",
"truckType",
"plateNumber",
"vehicleModel",
"yearOfManufacturing",
];
const isValid = await trigger(fields);
if (!isValid) return;
setStep("documents");
};
const skipDocuments = () => {
setStep("confirm");
};
const prevStep = () => {
if (step === "vehicle") {
onBack();
} else if (step === "documents") {
setStep("vehicle");
} else {
setStep("documents");
}
};
return (
<>
<div className="mb-8">
<button
type="button"
onClick={onBack}
onClick={prevStep}
className="mb-4 flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ChevronLeft className="size-4" />
Change account type
</button>
<div className="flex items-center justify-center relative px-2">
<div className="flex h-10 w-10 items-center justify-center rounded-full border-2 border-primary bg-background text-primary shadow-md">
<Truck className="size-5" />
</div>
<div className="flex items-center justify-between max-w-lg mx-auto relative px-2">
<div className="absolute top-1/2 left-0 w-full h-0.5 bg-border -translate-y-1/2 z-0" />
<StepIcon
icon={<Truck className="size-5" />}
active={step === "vehicle"}
completed={step !== "vehicle"}
/>
<StepIcon
icon={<UploadCloud className="size-5" />}
active={step === "documents"}
completed={step === "confirm"}
/>
<StepIcon
icon={<CheckCircle2 className="size-5" />}
active={step === "confirm"}
completed={false}
/>
</div>
<p className="text-center text-sm text-muted-foreground mt-3">
Transporter Registration
{step === "vehicle" && `Step 1 of ${totalSteps} — Vehicle Information`}
{step === "documents" && `Step 2 of ${totalSteps} — Upload Documents (Optional)`}
{step === "confirm" && `Step 3 of ${totalSteps} — Review & Confirm`}
</p>
</div>
<form
onSubmit={handleSubmit((data) => onSubmit(buildPayload(data, user)))}
onSubmit={(e) => e.preventDefault()}
className="flex flex-col gap-4"
>
{/* Personal Info (read-only) */}
<div className="rounded-lg bg-muted/30 p-4 text-sm text-muted-foreground">
<div className="flex items-center gap-2 mb-2">
<Info className="size-4" />
<span className="font-medium text-foreground">Account Holder</span>
{step === "vehicle" && (
<>
<div className="grid grid-cols-2 gap-4">
<Field data-invalid={Boolean(errors.tinNumber)}>
<FieldLabel>TIN Number (10 digits)</FieldLabel>
<Input
placeholder="1234567890"
maxLength={10}
aria-invalid={Boolean(errors.tinNumber)}
{...register("tinNumber")}
/>
<FieldError errors={[errors.tinNumber]} />
</Field>
<Field data-invalid={Boolean(errors.fanNumber)}>
<FieldLabel>FAN Number (16 digits)</FieldLabel>
<Input
placeholder="1234567890123456"
maxLength={16}
aria-invalid={Boolean(errors.fanNumber)}
{...register("fanNumber")}
/>
<FieldError errors={[errors.fanNumber]} />
</Field>
</div>
<hr className="border-border" />
<h3 className="text-sm font-semibold text-foreground">
Vehicle / Truck Information
</h3>
<Controller
name="truckType"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={Boolean(fieldState.error)}>
<FieldLabel>Truck Type</FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger
className={cn(
"w-full",
fieldState.error ? "border-destructive!" : "",
)}
aria-invalid={Boolean(fieldState.error)}
>
<SelectValue placeholder="Select truck type..." />
</SelectTrigger>
<SelectContent>
{TRUCK_TYPES.map((type) => (
<SelectItem key={type} value={type}>
{type}
</SelectItem>
))}
</SelectContent>
</Select>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
<div className="grid grid-cols-2 gap-4">
<Field data-invalid={Boolean(errors.plateNumber)}>
<FieldLabel>Plate Number{isCasoni ? " (Front)" : ""}</FieldLabel>
<Input
placeholder={isCasoni ? "AA-12345" : "AA-12345"}
aria-invalid={Boolean(errors.plateNumber)}
{...register("plateNumber")}
/>
<FieldError errors={[errors.plateNumber]} />
</Field>
{isCasoni && (
<Field data-invalid={Boolean(errors.plateNumber2)}>
<FieldLabel>Plate Number (Trailer)</FieldLabel>
<Input
placeholder="AA-67890"
aria-invalid={Boolean(errors.plateNumber2)}
{...register("plateNumber2")}
/>
<FieldError errors={[errors.plateNumber2]} />
</Field>
)}
{!isCasoni && (
<Field data-invalid={Boolean(errors.vehicleModel)}>
<FieldLabel>Vehicle Model</FieldLabel>
<Input
placeholder="Isuzu FVR 2024"
aria-invalid={Boolean(errors.vehicleModel)}
{...register("vehicleModel")}
/>
<FieldError errors={[errors.vehicleModel]} />
</Field>
)}
</div>
<div className="grid grid-cols-2 gap-4">
{isCasoni && (
<Field data-invalid={Boolean(errors.vehicleModel)}>
<FieldLabel>Vehicle Model</FieldLabel>
<Input
placeholder="Isuzu FVR 2024"
aria-invalid={Boolean(errors.vehicleModel)}
{...register("vehicleModel")}
/>
<FieldError errors={[errors.vehicleModel]} />
</Field>
)}
<Field data-invalid={Boolean(errors.yearOfManufacturing)}>
<FieldLabel>Year of Manufacturing</FieldLabel>
<Input
placeholder="2023"
maxLength={4}
aria-invalid={Boolean(errors.yearOfManufacturing)}
{...register("yearOfManufacturing")}
/>
<FieldError errors={[errors.yearOfManufacturing]} />
</Field>
</div>
</>
)}
{step === "documents" && (
<>
{loadingDocuments ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="size-6 animate-spin text-muted-foreground" />
</div>
) : !uploadSetting ? (
<p className="text-sm text-muted-foreground text-center py-4">
No document requirements found for your account type.
</p>
) : (
<div className="flex flex-col gap-6">
<SmartFileInput
file={uploadSetting}
value={documentFiles}
onChange={setDocumentFiles}
/>
</div>
)}
</>
)}
{step === "confirm" && (
<div className="space-y-4 rounded-xl border border-border bg-card p-4">
<div>
<h3 className="text-base font-semibold text-foreground">
Review your registration
</h3>
<p className="text-sm text-muted-foreground mt-1">
Confirm the details below before saving.
</p>
</div>
<div className="grid gap-3 md:grid-cols-2">
<ReviewRow label="TIN Number" value={formValues.tinNumber} />
<ReviewRow label="FAN Number" value={formValues.fanNumber} />
<ReviewRow label="Truck Type" value={formValues.truckType} />
<ReviewRow label="Plate Number" value={formValues.plateNumber} />
{formValues.plateNumber2 && (
<ReviewRow label="Plate (Trailer)" value={formValues.plateNumber2} />
)}
<ReviewRow label="Vehicle Model" value={formValues.vehicleModel} />
<ReviewRow label="Year" value={formValues.yearOfManufacturing} />
</div>
</div>
<p>
{user.name?.en} {user.email} {user.phoneNumber}
</p>
</div>
<div className="grid grid-cols-2 gap-4">
<Field data-invalid={Boolean(errors.tinNumber)}>
<FieldLabel>TIN Number (10 digits)</FieldLabel>
<Input
placeholder="1234567890"
maxLength={10}
aria-invalid={Boolean(errors.tinNumber)}
{...register("tinNumber")}
/>
<FieldError errors={[errors.tinNumber]} />
</Field>
<Field data-invalid={Boolean(errors.fanNumber)}>
<FieldLabel>FAN Number (16 digits)</FieldLabel>
<Input
placeholder="1234567890123456"
maxLength={16}
aria-invalid={Boolean(errors.fanNumber)}
{...register("fanNumber")}
/>
<FieldError errors={[errors.fanNumber]} />
</Field>
</div>
<hr className="border-border" />
<h3 className="text-sm font-semibold text-foreground">
Vehicle / Truck Information
</h3>
<Controller
name="truckType"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={Boolean(fieldState.error)}>
<FieldLabel>Truck Type</FieldLabel>
<Select
value={field.value}
onValueChange={field.onChange}
>
<SelectTrigger
className={cn(
"w-full",
fieldState.error ? "border-destructive!" : "",
)}
aria-invalid={Boolean(fieldState.error)}
>
<SelectValue placeholder="Select truck type..." />
</SelectTrigger>
<SelectContent>
{TRUCK_TYPES.map((type) => (
<SelectItem key={type} value={type}>
{type}
</SelectItem>
))}
</SelectContent>
</Select>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
<div className="grid grid-cols-2 gap-4">
<Field data-invalid={Boolean(errors.plateNumber)}>
<FieldLabel>
Plate Number{isCasoni ? " (Front)" : ""}
</FieldLabel>
<Input
placeholder={isCasoni ? "AA-12345" : "AA-12345"}
aria-invalid={Boolean(errors.plateNumber)}
{...register("plateNumber")}
/>
<FieldError errors={[errors.plateNumber]} />
</Field>
{isCasoni && (
<Field data-invalid={Boolean(errors.plateNumber2)}>
<FieldLabel>Plate Number (Trailer)</FieldLabel>
<Input
placeholder="AA-67890"
aria-invalid={Boolean(errors.plateNumber2)}
{...register("plateNumber2")}
/>
<FieldError errors={[errors.plateNumber2]} />
</Field>
)}
{!isCasoni && (
<Field data-invalid={Boolean(errors.vehicleModel)}>
<FieldLabel>Vehicle Model</FieldLabel>
<Input
placeholder="Isuzu FVR 2024"
aria-invalid={Boolean(errors.vehicleModel)}
{...register("vehicleModel")}
/>
<FieldError errors={[errors.vehicleModel]} />
</Field>
)}
</div>
<div className="grid grid-cols-2 gap-4">
{isCasoni && (
<Field data-invalid={Boolean(errors.vehicleModel)}>
<FieldLabel>Vehicle Model</FieldLabel>
<Input
placeholder="Isuzu FVR 2024"
aria-invalid={Boolean(errors.vehicleModel)}
{...register("vehicleModel")}
/>
<FieldError errors={[errors.vehicleModel]} />
</Field>
)}
<Field data-invalid={Boolean(errors.yearOfManufacturing)}>
<FieldLabel>Year of Manufacturing</FieldLabel>
<Input
placeholder="2023"
maxLength={4}
aria-invalid={Boolean(errors.yearOfManufacturing)}
{...register("yearOfManufacturing")}
/>
<FieldError errors={[errors.yearOfManufacturing]} />
</Field>
</div>
)}
<div className="flex items-center justify-between pt-2">
<Button type="button" variant="outline" onClick={onBack}>
<ChevronLeft />
Change Type
<Button type="button" variant="outline" onClick={prevStep}>
<ArrowLeft />
{step === "vehicle"
? "Change Type"
: step === "confirm"
? "Back to Documents"
: "Back"}
</Button>
<Button type="submit" disabled={isPending}>
{isPending ? (
<>
<Loader2 className="animate-spin" />
Submitting...
</>
) : (
"Complete Registration"
<div className="flex items-center gap-3">
{step === "documents" && (
<Button
type="button"
variant="outline"
onClick={skipDocuments}
disabled={isPending}
>
Skip for now
</Button>
)}
</Button>
<Button
type="button"
onClick={step === "confirm" ? handleSubmit((data) => onSubmit(buildPayload(data, user))) : nextStep}
disabled={isPending || (step === "documents" && !hasDocuments && loadingDocuments)}
>
{isPending ? (
<>
<Loader2 className="animate-spin" />
Submitting...
</>
) : step === "documents" ? (
"Continue"
) : step === "confirm" ? (
"Submit Registration"
) : (
<>
Next Step
<ArrowRight />
</>
)}
</Button>
</div>
</div>
</form>
</>
);
}
function ReviewRow({ label, value }: { label: string; value?: string | null }) {
return (
<div className="rounded-lg border border-border bg-muted/20 p-3">
<div className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
{label}
</div>
<div className="mt-1 text-sm font-medium text-foreground">
{value?.trim() ? value : "Not provided"}
</div>
</div>
);
}
function StepIcon({
icon,
active,
completed,
}: {
icon: React.ReactNode;
active: boolean;
completed: boolean;
}) {
return (
<div
className={`relative z-10 flex h-10 w-10 items-center justify-center rounded-full border-2 transition-all ${
completed
? "bg-primary border-primary text-primary-foreground"
: active
? "bg-background border-primary text-primary shadow-md"
: "bg-background border-border text-muted-foreground"
}`}
>
{completed ? <CheckCircle2 className="size-5" /> : icon}
</div>
);
}

View File

@@ -0,0 +1,165 @@
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 { ContractSignaturePad } from "@/components/bookings/ContractSignaturePad";
import {
bookingsService,
type SignContractPayload,
} from "@/services/bookings.service";
import { Button } 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, refetch } = useQuery({
queryKey: ["booking-contract-view", id],
queryFn: () => bookingsService.getContractView(id!),
enabled: Boolean(id),
});
const signMutation = useMutation({
mutationFn: (payload: SignContractPayload) =>
bookingsService.signContract(id!, payload),
onSuccess: () => {
toast.success("Contract signed successfully");
setSignOpen(false);
void refetch();
qc.invalidateQueries({ queryKey: ["booking", id] });
},
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("PDF not ready yet. Contact EDR if this persists.");
}
}, [id, data?.reference]);
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="p-8">
<p className="text-muted-foreground">Could not load contract.</p>
<Button variant="outline" className="mt-4" onClick={() => navigate(-1)}>
Go back
</Button>
</div>
);
}
const bodyHtml = extractBodyHtml(data.html);
return (
<div className="min-h-screen bg-muted/30 p-4 md:p-8">
<div className="mx-auto max-w-4xl">
<div className="mb-4 flex flex-wrap items-center justify-between gap-3 print:hidden">
<Button variant="ghost" size="sm" onClick={() => navigate(`/bookings/${id}`)}>
<ArrowLeft className="mr-2 size-4" />
Back to booking
</Button>
<div className="flex flex-wrap gap-2">
<Button variant="outline" size="sm" onClick={() => window.print()}>
<Printer className="mr-2 size-4" />
Print
</Button>
<Button variant="outline" size="sm" onClick={downloadPdf}>
<Download className="mr-2 size-4" />
PDF
</Button>
{data.canSignCustomer && (
<Button size="sm" onClick={() => setSignOpen(true)}>
<FileSignature className="mr-2 size-4" />
Sign contract
</Button>
)}
</div>
</div>
<article
className="contract-document rounded-lg border bg-white p-6 shadow-sm print:shadow-none md:p-10"
dangerouslySetInnerHTML={{ __html: bodyHtml }}
/>
</div>
{signOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 print:hidden">
<div className="w-full max-w-md rounded-xl bg-background p-6 shadow-xl">
<h2 className="text-lg font-semibold">Sign contract</h2>
<p className="mt-1 text-sm text-muted-foreground">
{data.reference} your signature will be stored securely.
</p>
<div className="mt-4 space-y-3">
<label className="text-sm font-medium" htmlFor="portalSigner">
Full name
</label>
<input
id="portalSigner"
className="w-full rounded-md border px-3 py-2 text-sm"
value={signerName}
onChange={(e) => setSignerName(e.target.value)}
/>
<ContractSignaturePad onChange={setSignatureData} />
</div>
<div className="mt-6 flex justify-end gap-2">
<Button variant="outline" onClick={() => setSignOpen(false)}>
Cancel
</Button>
<Button
disabled={
signMutation.isPending ||
!signatureData ||
!signerName.trim()
}
onClick={() =>
signMutation.mutate({
role: "CUSTOMER",
signatureImageBase64: signatureData!,
signerDisplayName: signerName.trim(),
consentText: "I agree to the terms of this contract.",
})
}
>
Confirm signature
</Button>
</div>
</div>
</div>
)}
</div>
);
}
function extractBodyHtml(fullHtml: string): string {
const match = fullHtml.match(/<body[^>]*>([\s\S]*)<\/body>/i);
return match ? match[1] : fullHtml;
}

View File

@@ -1,4 +1,5 @@
import { useNavigate, useParams } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import {
Calendar,
MapPin,
@@ -22,10 +23,12 @@ import {
CreditCard,
FileSignature,
PackageCheck,
LoaderCircle,
} from "lucide-react";
import Breadcrumbs from "@/components/Breadcrumbs";
import { getBookingById } from "./bookings.mock";
import { api } from "@/services/api";
import type { Freight } from "@edr/types";
import {
Card,
CardHeader,
@@ -37,45 +40,67 @@ import {
} from "@edr/ui-common";
import { cn } from "@/lib/utils";
// Grouping the 15 granular statuses into 6 logical progress stages for the UI tracker
const PROGRESS_STAGES = [
{ label: "Request", icon: FileText, statuses: ["DRAFT", "RFQ_SUBMITTED"] },
{ label: "Quotation", icon: ClipboardCheck, statuses: ["QUOTATION_SENT", "QUOTATION_APPROVED", "QUOTATION_REJECTED"] },
{ label: "Approval", icon: ShieldCheck, statuses: ["PENDING_APPROVAL", "APPROVED"] },
{ label: "Execution", icon: FileSignature, statuses: ["SIGNED_CUSTOMER", "FULLY_EXECUTED", "PAID"] },
{ label: "In Transit", icon: Train, statuses: ["IN_TRANSIT", "PENDING_CONSOLIDATION", "CONSOLIDATED"] },
{ label: "Complete", icon: PackageCheck, statuses: ["COMPLETED"] },
{ label: "Request", icon: FileText, statuses: ["DRAFT"] },
{ label: "Approval", icon: ClipboardCheck, statuses: ["CONFIRMED"] },
{ label: "In Transit", icon: Train, statuses: ["IN_TRANSIT"] },
{ label: "Complete", icon: PackageCheck, statuses: ["DELIVERED"] },
];
const STATUS_MAP: Record<string, { title: string; description: string; color: string; stage: number }> = {
DRAFT: { title: "Drafting Request", description: "Booking is being prepared and has not been submitted.", color: "text-slate-500", stage: 0 },
RFQ_SUBMITTED: { title: "RFQ Submitted", description: "Request for Quotation has been sent to the operations team.", color: "text-amber-600", stage: 0 },
QUOTATION_SENT: { title: "Quotation Received", description: "EDR has sent a formal quotation for your review.", color: "text-sky-600", stage: 1 },
QUOTATION_APPROVED: { title: "Quotation Approved", description: "You have accepted the quotation terms.", color: "text-emerald-600", stage: 1 },
QUOTATION_REJECTED: { title: "Quotation Rejected", description: "The quotation was not accepted.", color: "text-red-600", stage: 1 },
PENDING_APPROVAL: { title: "Internal Approval", description: "Booking is undergoing final administrative review.", color: "text-amber-600", stage: 2 },
APPROVED: { title: "Booking Approved", description: "Request is fully approved and ready for execution.", color: "text-emerald-600", stage: 2 },
SIGNED_CUSTOMER: { title: "Customer Signed", description: "Contract has been signed by the customer.", color: "text-sky-600", stage: 3 },
FULLY_EXECUTED: { title: "Contract Executed", description: "All parties have signed. Operational setup in progress.", color: "text-indigo-600", stage: 3 },
PAID: { title: "Payment Received", description: "Initial payments confirmed. Cargo ready for dispatch.", color: "text-emerald-600", stage: 3 },
IN_TRANSIT: { title: "Cargo Moving", description: "Shipment is currently moving through the rail network.", color: "text-sky-600", stage: 4 },
PENDING_CONSOLIDATION: { title: "Consolidation Node", description: "Cargo is waiting to be consolidated with other shipments.", color: "text-amber-500", stage: 4 },
CONSOLIDATED: { title: "Load Consolidated", description: "Cargo has been successfully merged into a larger shipment.", color: "text-indigo-500", stage: 4 },
COMPLETED: { title: "Service Complete", description: "Cargo delivered and service successfully terminated.", color: "text-emerald-600", stage: 5 },
CONFIRMED: { title: "Booking Confirmed", description: "Booking has been confirmed and approved.", color: "text-emerald-600", stage: 1 },
IN_TRANSIT: { title: "Cargo Moving", description: "Shipment is currently moving through the rail network.", color: "text-sky-600", stage: 2 },
DELIVERED: { title: "Service Complete", description: "Cargo delivered and service successfully terminated.", color: "text-emerald-600", stage: 3 },
CANCELLED: { title: "Cancelled", description: "This booking process has been terminated.", color: "text-red-600", stage: -1 },
};
export default function BookingDetailPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const booking = id ? getBookingById(id) : undefined;
const { data: booking, isLoading, isError, error } = useQuery(
api.bookings.get.queryOptions({
input: { id: id! },
enabled: !!id,
}),
);
if (isLoading) {
return (
<div className="container mx-auto flex items-center justify-center p-12">
<div className="flex flex-col items-center gap-4">
<LoaderCircle className="size-8 animate-spin text-primary" />
<p className="text-sm text-muted-foreground">Loading booking details</p>
</div>
</div>
);
}
if (isError) {
return (
<div className="container mx-auto p-6">
<Card className="flex flex-col items-center p-12 text-center">
<div className="flex size-16 items-center justify-center rounded-full bg-red-50 text-red-400">
<AlertTriangle className="size-8" />
</div>
<h1 className="mt-4 text-2xl font-bold text-slate-900">
Failed to load booking
</h1>
<p className="mt-2 text-sm text-muted-foreground">
{error instanceof Error ? error.message : "An unexpected error occurred."}
</p>
</Card>
</div>
);
}
if (!booking) {
return (
<div className="container mx-auto p-6">
<Card className="flex flex-col items-center p-12 text-center">
<div className="flex size-16 items-center justify-center rounded-full bg-slate-100 text-slate-400">
<Package className="size-8" />
<Package className="size-8" />
</div>
<h1 className="mt-4 text-2xl font-bold text-slate-900">
Booking not found
@@ -85,16 +110,17 @@ export default function BookingDetailPage() {
);
}
// Normalize status to upper case for mapping
const normalizedStatus = (booking.status === "In Transit" ? "IN_TRANSIT" : booking.status === "Pending" ? "RFQ_SUBMITTED" : booking.status.toUpperCase()) as keyof typeof STATUS_MAP;
const normalizedStatus = booking.status as keyof typeof STATUS_MAP;
const statusConfig = STATUS_MAP[normalizedStatus] || STATUS_MAP.DRAFT;
const currentStageIndex = statusConfig.stage;
const containerCount = booking.containers?.reduce((sum, c) => sum + c.qty, 0) ?? 0;
const containerType = booking.containers?.[0]?.type ?? null;
return (
<div className="container mx-auto max-w-7xl px-4 py-8">
<div className="flex flex-col gap-8">
{/* Breadcrumbs Restored */}
<Breadcrumbs
items={[
{ label: "Bookings", href: "/bookings" },
@@ -102,7 +128,6 @@ export default function BookingDetailPage() {
]}
/>
{/* Compact Header Card */}
<Card>
<CardHeader>
<div className="flex items-center gap-6">
@@ -117,11 +142,9 @@ export default function BookingDetailPage() {
<StatusBadge status={normalizedStatus} />
</div>
<div className="flex items-center gap-3 text-xs text-muted-foreground">
<span className="font-semibold">{booking.customer}</span>
<Separator orientation="vertical" className="h-3" />
<span className="flex items-center gap-1">
<Calendar className="size-3" />
{booking.requestedDate}
{booking.scheduledDate ?? booking.createdAt}
</span>
</div>
</div>
@@ -129,7 +152,27 @@ export default function BookingDetailPage() {
</CardHeader>
</Card>
{/* Granular Status Lifecycle */}
{(booking.status === "CONFIRMED" || booking.status === "IN_TRANSIT") && (
<Card className="border-primary/30 bg-primary/5">
<CardContent className="flex flex-col gap-4 p-6 sm:flex-row sm:items-center sm:justify-between">
<div>
<p className="font-semibold text-foreground">Contract ready</p>
<p className="text-sm text-muted-foreground">
Review the agreement and apply your digital signature.
</p>
</div>
<button
type="button"
className="inline-flex items-center justify-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground"
onClick={() => navigate(`/bookings/${booking.id}/contract`)}
>
<FileSignature className="size-4" />
View &amp; sign contract
</button>
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
@@ -140,7 +183,6 @@ export default function BookingDetailPage() {
</CardHeader>
<CardContent className="flex flex-col gap-8">
<div className="relative flex w-full justify-between px-2">
{/* Progress Line */}
<div className="absolute top-4 left-0 h-0.5 w-full bg-muted">
<div
className="h-full bg-primary transition-all duration-500"
@@ -185,7 +227,7 @@ export default function BookingDetailPage() {
{statusConfig.description}
</p>
</div>
{normalizedStatus !== "CANCELLED" && normalizedStatus !== "COMPLETED" && (
{normalizedStatus !== "CANCELLED" && normalizedStatus !== "DELIVERED" && (
<div className="ml-auto flex items-center gap-4 border-l border-border pl-6">
<div className="flex flex-col">
<p className="text-[9px] font-bold uppercase text-muted-foreground">Est. Waiting</p>
@@ -200,7 +242,6 @@ export default function BookingDetailPage() {
<div className="grid grid-cols-1 gap-8 lg:grid-cols-3">
<div className="flex flex-col gap-8 lg:col-span-2">
{/* Route & Core Service Card */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
@@ -232,14 +273,13 @@ export default function BookingDetailPage() {
</div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
<InfoItem icon={<Layers />} label="Service" value="Rail & Forwarding" />
<InfoItem icon={<ShieldCheck />} label="Return" value="With Return" />
<InfoItem icon={<FileText />} label="Customs" value="Enabled" />
<InfoItem icon={<Layers />} label="Service" value={booking.serviceType === "RAIL_AND_FORWARDING" ? "Rail & Forwarding" : "Rail Only"} />
<InfoItem icon={<ShieldCheck />} label="Return" value={booking.equipmentReturn === "WITH_RETURN" ? "With Return" : "Without Return"} />
<InfoItem icon={<FileText />} label="Trade" value={booking.tradeDirection === "IMPORT" ? "Import" : "Export"} />
</div>
</CardContent>
</Card>
{/* Mile Services Card */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
@@ -252,18 +292,19 @@ export default function BookingDetailPage() {
<h3 className="border-l-4 border-primary pl-3 text-xs font-bold uppercase tracking-wide text-foreground">
First Mile
</h3>
<InfoItem label="Address" value="Inside Addis Ababa Yard, Gate 2" />
<InfoItem label="Address" value={booking.firstMileEnabled && booking.firstMilePickupAddress ? booking.firstMilePickupAddress : "Not requested"} />
</div>
<div className="flex flex-col gap-3">
<h3 className="border-l-4 border-primary pl-3 text-xs font-bold uppercase tracking-wide text-foreground">
Last Mile
</h3>
<p className="pl-4 text-xs text-muted-foreground italic">Not requested</p>
<p className="pl-4 text-xs text-muted-foreground italic">
{booking.lastMileEnabled && booking.lastMileDeliveryAddress ? booking.lastMileDeliveryAddress : "Not requested"}
</p>
</div>
</CardContent>
</Card>
{/* Cargo Specifications Card */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
@@ -273,40 +314,44 @@ export default function BookingDetailPage() {
</CardHeader>
<CardContent className="flex flex-col gap-6">
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
<InfoItem icon={<Package />} label="Category" value={booking.cargoType} />
<InfoItem icon={<Weight />} label="Weight" value={`${booking.weightTons} Tons`} />
<InfoItem icon={<Ship />} label="Shipping Line" value="MSC" />
<InfoItem icon={<Package />} label="Freight Type" value={booking.freightType === "BULK" ? "Bulk" : "Break Bulk"} />
<InfoItem icon={<Weight />} label="Weight (VGM)" value={`${booking.cargoTotalWeightVgm} Tons`} />
<InfoItem icon={<Ship />} label="Currency" value={booking.paymentCurrency} />
</div>
<Separator />
<div className="flex flex-col gap-3">
<h3 className="text-xs font-bold uppercase tracking-wide text-foreground">Load Details</h3>
<div className="rounded-lg border overflow-hidden">
<table className="w-full text-left text-xs">
<thead className="bg-muted text-muted-foreground">
<tr>
<th className="px-3 py-2 font-semibold">Description</th>
<th className="px-3 py-2 font-semibold text-center">Unit</th>
<th className="px-3 py-2 font-semibold text-right">Value</th>
</tr>
</thead>
<tbody className="divide-y">
<tr>
<td className="px-3 py-2 font-medium">Main Equipment</td>
<td className="px-3 py-2 text-center">20FT Container</td>
<td className="px-3 py-2 text-right">4 Units</td>
</tr>
</tbody>
</table>
</div>
</div>
{booking.containers && booking.containers.length > 0 && (
<>
<Separator />
<div className="flex flex-col gap-3">
<h3 className="text-xs font-bold uppercase tracking-wide text-foreground">Load Details</h3>
<div className="rounded-lg border overflow-hidden">
<table className="w-full text-left text-xs">
<thead className="bg-muted text-muted-foreground">
<tr>
<th className="px-3 py-2 font-semibold">Type</th>
<th className="px-3 py-2 font-semibold text-center">Quantity</th>
<th className="px-3 py-2 font-semibold text-right">VGM (Tons)</th>
</tr>
</thead>
<tbody className="divide-y">
{booking.containers.map((c, i) => (
<tr key={i}>
<td className="px-3 py-2 font-medium">{c.type}</td>
<td className="px-3 py-2 text-center">{c.qty} Units</td>
<td className="px-3 py-2 text-right">{c.vgm}t</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</>
)}
</CardContent>
</Card>
</div>
<div className="flex flex-col gap-8">
{/* Contract Card */}
<Card className="border-primary/20 bg-primary/[0.02]">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
@@ -315,40 +360,48 @@ export default function BookingDetailPage() {
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<InfoItem label="Type" value="Renewal" />
<InfoItem label="Ref" value="EDR-2024-88123" />
<InfoItem label="Type" value={booking.contractType === "RENEWAL" ? "Renewal" : "New"} />
<InfoItem label="Customer ID" value={booking.customerId} />
<Separator />
<div className="flex flex-wrap gap-2">
<Badge variant="outline" className="bg-background text-[9px]">
Hazardous: No
Hazardous: {booking.isHazardous ? "Yes" : "No"}
</Badge>
<Badge variant="outline" className="bg-background text-[9px]">
Refrigerated: No
Refrigerated: {booking.isRefrigerated ? "Yes" : "No"}
</Badge>
</div>
</CardContent>
</Card>
{/* Notes Card */}
<Card>
<CardHeader>
<CardTitle className="text-base">Additional Info</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="flex flex-col gap-1">
<p className="text-[9px] font-bold uppercase tracking-tight text-muted-foreground">Description</p>
<p className="text-xs text-foreground leading-relaxed italic">"{booking.cargoDescription}"</p>
</div>
<Separator />
<div className="flex flex-col gap-1">
<p className="text-[9px] font-bold uppercase tracking-tight text-muted-foreground">Instructions</p>
<div className="rounded-lg bg-amber-50/50 border border-amber-100 p-2">
<p className="text-xs text-amber-900 flex gap-2">
<StickyNote className="size-3 shrink-0 mt-0.5 text-amber-500" />
{booking.specialInstructions}
</p>
</div>
</div>
{booking.freightSubtype && (
<div className="flex flex-col gap-1">
<p className="text-[9px] font-bold uppercase tracking-tight text-muted-foreground">Cargo Description</p>
<p className="text-xs text-foreground leading-relaxed italic">"{booking.freightSubtype}"</p>
</div>
)}
{booking.financialTerms && (
<>
<Separator />
<div className="flex flex-col gap-1">
<p className="text-[9px] font-bold uppercase tracking-tight text-muted-foreground">Financial Terms</p>
<div className="rounded-lg bg-amber-50/50 border border-amber-100 p-2">
<p className="text-xs text-amber-900 flex gap-2">
<StickyNote className="size-3 shrink-0 mt-0.5 text-amber-500" />
{booking.financialTerms}
</p>
</div>
</div>
</>
)}
{!booking.freightSubtype && !booking.financialTerms && (
<p className="text-xs text-muted-foreground italic">No additional information provided.</p>
)}
</CardContent>
</Card>
</div>
@@ -396,7 +449,7 @@ function InfoItem({
{icon && <div className="mt-0.5 text-muted-foreground [&_svg]:size-3.5">{icon}</div>}
<div className="flex flex-col">
<p className="text-[9px] font-bold uppercase tracking-tight text-muted-foreground">{label}</p>
<p className="text-xs font-bold text-foreground">{value || "—"}</p>
<p className="text-xs font-bold text-foreground">{value ?? "—"}</p>
</div>
</div>
);
@@ -405,20 +458,10 @@ function InfoItem({
function StatusBadge({ status }: { status: string }) {
const statusColors: Record<string, string> = {
DRAFT: "bg-slate-50 text-slate-700 border-slate-200",
RFQ_SUBMITTED: "bg-amber-50 text-amber-700 border-amber-200",
QUOTATION_SENT: "bg-sky-50 text-sky-700 border-sky-200",
QUOTATION_APPROVED: "bg-emerald-50 text-emerald-700 border-emerald-200",
QUOTATION_REJECTED: "bg-red-50 text-red-700 border-red-200",
PENDING_APPROVAL: "bg-amber-50 text-amber-700 border-amber-200",
APPROVED: "bg-emerald-50 text-emerald-700 border-emerald-200",
SIGNED_CUSTOMER: "bg-sky-50 text-sky-700 border-sky-200",
FULLY_EXECUTED: "bg-indigo-50 text-indigo-700 border-indigo-200",
PAID: "bg-emerald-50 text-emerald-700 border-emerald-200",
CONFIRMED: "bg-emerald-50 text-emerald-700 border-emerald-200",
IN_TRANSIT: "bg-sky-50 text-sky-700 border-sky-200",
COMPLETED: "bg-indigo-50 text-indigo-700 border-indigo-200",
DELIVERED: "bg-indigo-50 text-indigo-700 border-indigo-200",
CANCELLED: "bg-red-50 text-red-700 border-red-200",
PENDING_CONSOLIDATION: "bg-amber-50 text-amber-700 border-amber-200",
CONSOLIDATED: "bg-indigo-50 text-indigo-700 border-indigo-200",
};
return (

View File

@@ -1,5 +1,6 @@
import { useMemo, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import {
ArrowRight,
Clock,
@@ -9,13 +10,11 @@ import {
Package,
Plus,
Search,
Trash2,
Truck,
} from "lucide-react";
import DeleteBookingDialog from "./DeleteBookingDialog";
import { getMyBookings } from "@/lib/currentCustomer";
import { deleteBooking, type Booking, type BookingStatus } from "./bookings.mock";
import { api } from "@/services/api";
import type { Freight } from "@edr/types";
import {
DataTable,
DataTableFooter,
@@ -32,32 +31,30 @@ import {
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
} from "@edr/ui-common";
export default function MyBookings() {
const navigate = useNavigate();
const { pagination, setPagination } = usePagination({ pageSize: 10 });
const [searchTerm, setSearchTerm] = useState("");
const [myBookings, setMyBookings] = useState(() => getMyBookings());
const handleDeleteConfirm = (id: number) => {
deleteBooking(id);
setMyBookings(getMyBookings());
};
const { data, isLoading, isError } = useQuery(
api.bookings.list.queryOptions(),
);
const bookings = data?.items ?? [];
const filteredData = useMemo(() => {
return myBookings.filter((b) => {
return bookings.filter((b) => {
const term = searchTerm.toLowerCase();
return (
b.reference.toLowerCase().includes(term) ||
b.originStation.toLowerCase().includes(term) ||
b.destinationStation.toLowerCase().includes(term) ||
b.cargoDescription.toLowerCase().includes(term) ||
b.status.toLowerCase().includes(term)
);
});
}, [myBookings, searchTerm]);
}, [bookings, searchTerm]);
const total = filteredData.length;
const pageCount = Math.ceil(total / pagination.pageSize);
@@ -67,16 +64,16 @@ export default function MyBookings() {
const paginatedData = useMemo(() => filteredData.slice(start, end), [filteredData, start, end]);
const activeCount = useMemo(() => {
return myBookings.filter(
(b) => b.status === "Confirmed" || b.status === "In Transit",
return bookings.filter(
(b) => b.status === "CONFIRMED" || b.status === "IN_TRANSIT",
).length;
}, [myBookings]);
}, [bookings]);
const pendingCount = useMemo(() => {
return myBookings.filter((b) => b.status === "Pending").length;
}, [myBookings]);
return bookings.filter((b) => b.status === "DRAFT").length;
}, [bookings]);
const columns: ColumnDef<Booking>[] = [
const columns: ColumnDef<Freight.IBooking>[] = [
{
accessorKey: "reference",
header: "Reference",
@@ -89,7 +86,7 @@ export default function MyBookings() {
</div>
<div>
<p className="font-medium text-slate-900">{booking.reference}</p>
<p className="text-sm text-slate-500">{booking.requestedDate}</p>
<p className="text-sm text-slate-500">{booking.scheduledDate ?? booking.createdAt}</p>
</div>
</div>
);
@@ -111,22 +108,24 @@ export default function MyBookings() {
header: "Cargo",
cell: ({ row }) => {
const b = row.original;
const containerCount = b.containers?.reduce((sum, c) => sum + c.qty, 0) ?? 0;
const containerType = b.containers?.[0]?.type ?? null;
return (
<div className="text-sm text-slate-700">
<p>{b.cargoType}</p>
<p>{b.freightType === "BULK" ? "Bulk" : "Break Bulk"}</p>
<p className="text-xs text-slate-500">
{b.containerCount > 0 ? `${b.containerCount} × ${b.containerType} · ` : ""}{b.weightTons}t
{containerType && containerCount > 0 ? `${containerCount} × ${containerType} · ` : ""}{b.cargoTotalWeightVgm}t
</p>
</div>
);
},
},
{
accessorKey: "transportMode",
id: "transportMode",
header: "Transport",
cell: ({ row }) => (
<span className="text-sm text-slate-700">
{row.original.transportMode}
{row.original.serviceType === "RAIL_AND_FORWARDING" ? "Rail & Forwarding" : "Rail"}
</span>
),
},
@@ -158,19 +157,6 @@ export default function MyBookings() {
<Eye />
View
</DropdownMenuItem>
<DropdownMenuSeparator />
<DeleteBookingDialog
bookingReference={booking.reference}
onConfirm={() => handleDeleteConfirm(booking.id)}
>
<DropdownMenuItem
onSelect={(e: Event) => e.preventDefault()}
variant="destructive"
>
<Trash2 />
Delete
</DropdownMenuItem>
</DeleteBookingDialog>
</DropdownMenuContent>
</DropdownMenu>
</div>
@@ -179,10 +165,11 @@ export default function MyBookings() {
},
];
const dataTableStatus = isLoading ? "loading" : isError ? "error" : "success";
return (
<div className="min-h-screen p-6">
<div className="space-y-6">
{/* Header Section Card */}
<Card className="p-6 flex-row justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight text-slate-900">
@@ -214,14 +201,13 @@ export default function MyBookings() {
</div>
</Card>
{/* Stat Cards */}
<div className="grid gap-4 md:grid-cols-3">
<Card>
<CardContent className="flex items-center justify-between">
<div>
<p className="text-sm text-slate-500">Total Bookings</p>
<h3 className="mt-2 text-3xl font-bold text-slate-900">
{myBookings.length}
{bookings.length}
</h3>
</div>
<div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
@@ -259,7 +245,6 @@ export default function MyBookings() {
</Card>
</div>
{/* Data Table */}
<Card className="gap-0">
<CardHeader className="flex flex-row items-center justify-between border-b">
<div>
@@ -276,7 +261,7 @@ export default function MyBookings() {
</CardHeader>
<CardContent className="px-0">
{total === 0 ? (
{total === 0 && dataTableStatus === "success" ? (
<div className="flex flex-col items-center justify-center py-12 px-6 text-center">
<Package className="h-12 w-12 text-slate-300 mb-4" />
<h3 className="text-sm font-semibold text-slate-900">No bookings found</h3>
@@ -288,8 +273,8 @@ export default function MyBookings() {
<DataTable
columns={columns}
data={paginatedData}
status="success"
onRowClick={(row) => navigate(`/bookings/${(row as Booking).id}`)}
status={dataTableStatus}
onRowClick={(row) => navigate(`/bookings/${(row as Freight.IBooking).id}`)}
pagination={{
pageIndex: pagination.pageIndex,
pageSize: pagination.pageSize,
@@ -311,20 +296,20 @@ export default function MyBookings() {
);
}
function StatusBadge({ status }: { status: BookingStatus }) {
const styles: Record<BookingStatus, string> = {
Pending: "bg-amber-100 text-amber-700",
Confirmed: "bg-sky-100 text-sky-700",
"In Transit": "bg-indigo-100 text-indigo-700",
Delivered: "bg-emerald-100 text-emerald-700",
Cancelled: "bg-red-100 text-red-700",
function StatusBadge({ status }: { status: string }) {
const styles: Record<string, string> = {
DRAFT: "bg-amber-100 text-amber-700",
CONFIRMED: "bg-sky-100 text-sky-700",
IN_TRANSIT: "bg-indigo-100 text-indigo-700",
DELIVERED: "bg-emerald-100 text-emerald-700",
CANCELLED: "bg-red-100 text-red-700",
};
return (
<span
className={`inline-flex rounded-full px-3 py-1 text-xs font-medium ${styles[status]}`}
className={`inline-flex rounded-full px-3 py-1 text-xs font-medium ${styles[status] ?? "bg-slate-100 text-slate-700"}`}
>
{status}
{status.replace(/_/g, ' ')}
</span>
);
}

View File

@@ -13,6 +13,7 @@ import {
} from "lucide-react";
import { Button } from "@edr/ui-common";
import { api } from "@/services/api";
import { Freight } from "@edr/types";
import type { CreateBookingPayload } from "@/services/bookings.service";
import {
BookingFormInputValues,
@@ -120,7 +121,6 @@ export default function NewBookingPage() {
const group = cargoTree.find(
(g) => g.code === "CONTAINER" || /container/i.test(g.name),
);
console.log(group, cargoTree);
return group?.id ?? "";
};
@@ -132,14 +132,14 @@ export default function NewBookingPage() {
return "";
};
const cargoTypeId = cargoTree[0].id;
// data.cargoType === "container"
// ? findContainerCargoTypeId()
// : (findCargoTypeId(
// data.freightType === "bulk"
// ? data.bulkCommodity
// : data.breakBulkType,
// ) ?? "");
const cargoTypeId =
data.cargoType === "container"
? findContainerCargoTypeId()
: (findCargoTypeId(
data.freightType === "bulk"
? data.bulkCommodity
: data.breakBulkType,
) ?? "");
const cargoFreeText =
data.cargoType === "container"
@@ -168,7 +168,11 @@ export default function NewBookingPage() {
: direction === "domestic"
? "DOMESTIC"
: "IMPORT",
cargoTypeId,
freightType:
data.cargoType === "container"
? Freight.FreightType.Container
: Freight.FreightType.Bulk,
cargoTypeId: data.cargoType === "container" ? undefined : cargoTypeId,
cargoTotalWeightVgm: totalWeight,
isHazardous: data.isHazardous,
paymentCurrency: "USD",
@@ -181,7 +185,7 @@ export default function NewBookingPage() {
vgmPerUnitTons: Number(c.vgm || 0),
}))
: [],
...(customer ? { customerId: customer.id } : {}),
...(customer?.company?.id ? { companyId: customer.company.id } : {}),
...(data.previousContractRef
? { previousContractId: data.previousContractRef }
: {}),

View File

@@ -130,7 +130,7 @@ export function Step5CargoDetails({
<div className="mb-2 flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10">
<Package className="h-4 w-4 text-primary" />
</div>
<p className="font-semibold">Container</p>
<p className="font-semibold">Containerized</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Pre-packed containerized cargo (20ft / 40ft).
</p>
@@ -145,7 +145,7 @@ export function Step5CargoDetails({
<div className="mb-2 flex h-9 w-9 items-center justify-center rounded-lg bg-amber-100">
<Weight className="h-4 w-4 text-amber-600" />
</div>
<p className="font-semibold">Bulk</p>
<p className="font-semibold">General Cargo</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Bulk commodities or break-bulk cargo.
</p>

View File

@@ -14,6 +14,7 @@ export interface Customer {
country: string;
address: string;
notes: string;
documentsComplete: boolean;
}
const seedCustomers: Customer[] = [
@@ -30,6 +31,7 @@ const seedCustomers: Customer[] = [
country: "Ethiopia",
address: "Bole Road, Sub-City 03, Building 17",
notes: "Top-tier importer. Prefers weekly invoicing.",
documentsComplete: false,
},
{
id: 2,
@@ -44,6 +46,7 @@ const seedCustomers: Customer[] = [
country: "Ethiopia",
address: "Industrial Park, Zone B, Warehouse 4",
notes: "Awaiting compliance documents.",
documentsComplete: false,
},
{
id: 3,
@@ -58,6 +61,7 @@ const seedCustomers: Customer[] = [
country: "Djibouti",
address: "Port Quarter, Avenue 26, Block 9",
notes: "Account paused since last quarter.",
documentsComplete: true,
},
];
@@ -99,6 +103,7 @@ const generated: Customer[] = extras.map((entry, i) => {
country: entry.country,
address: `Block ${i + 1}, Street ${10 + i}, Quarter ${(i % 5) + 1}`,
notes: `Mock customer #${id}.`,
documentsComplete: i % 3 === 0,
};
});

View File

@@ -15,6 +15,7 @@ import { fileUploadSettingsService } from "./fileUploadSettings.service";
import { dropdownSettingsService } from "./dropdownSettings.service";
import { authService } from "./auth.service";
import { customersService } from "./customers.service";
import { companiesService } from "./companies.service";
import {
CreateDropdownOptionDto,
CreateDropdownSettingDto,
@@ -28,6 +29,11 @@ import {
Customer,
UpdateCustomerDto,
} from "@/types/customers";
import type {
CompanyInfoResponse,
CreateCompanyPayload,
} from "./companies.service";
import type { ProfileResponse, UpdateProfilePayload } from "@/types/profile";
import type {
AuthUser,
GenerateVerificationCodePayload,
@@ -84,37 +90,29 @@ export const api = {
logout: endpoint<void, void>("auth", "logout", authService.logout),
},
customers: {
list: endpoint<void, Customer[]>(
"customers",
"list",
customersService.list,
companies: {
getInfo: endpoint<void, CompanyInfoResponse | null>(
"companies",
"getInfo",
companiesService.getInfo,
),
get: endpoint<{ id: string }, Customer>("customers", "get", ({ id }) =>
customersService.getById(id),
),
create: endpoint<CreateCustomerDto, Customer>(
"customers",
create: endpoint<CreateCompanyPayload, CompanyInfoResponse>(
"companies",
"create",
customersService.create,
companiesService.create,
),
update: endpoint<{ id: string; dto: UpdateCustomerDto }, Customer>(
"customers",
"update",
({ id, dto }) => customersService.update(id, dto),
getProfile: endpoint<void, ProfileResponse>(
"companies",
"getProfile",
companiesService.getProfile,
),
remove: endpoint<{ id: string }, void>("customers", "remove", ({ id }) =>
customersService.remove(id),
),
getByUserId: endpoint<{ id: string }, Customer | null>(
"customers",
"getByUserId",
({ id }) => customersService.getByUserId(id),
updateProfile: endpoint<UpdateProfilePayload, ProfileResponse>(
"companies",
"updateProfile",
companiesService.updateProfile,
),
},
@@ -190,6 +188,12 @@ export const api = {
({ code }) => fileUploadSettingsService.getByCode(code),
),
getByEntity: endpoint<{ entity: string }, FileUploadSetting[]>(
"file-upload-settings",
"getByEntity",
({ entity }) => fileUploadSettingsService.getByEntity(entity),
),
create: endpoint<CreateFileUploadSettingDto, FileUploadSetting>(
"file-upload-settings",
"create",

View File

@@ -1,27 +1,75 @@
import type { Freight, PaginatedResponse } from "@edr/types";
import { URL_CONSTANTS } from "@/constants/URLS";
import { client } from "../utils/api";
const B = URL_CONSTANTS.BOOKINGS;
export type CreateBookingPayload = Freight.CreateBookingDto;
export interface ContractView {
bookingId: string;
reference: string;
status: string;
templateKey: string;
title: string;
html: string;
canSignCustomer: boolean;
canSignStaff: boolean;
hasContractDocument: boolean;
signatures: Array<{
role: string;
signerDisplayName: string;
signedAt: string;
signatureImageUrl?: string | null;
}>;
}
export interface SignContractPayload {
role: "CUSTOMER" | "STAFF";
signatureImageBase64: string;
signerDisplayName: string;
consentText?: string;
}
export const bookingsService = {
list: async (): Promise<PaginatedResponse<Freight.IBooking>> => {
const { data } = await client.get("/bookings");
const { data } = await client.get("/api/bookings");
return data.data;
},
get: async (id: string): Promise<Freight.IBooking> => {
const { data } = await client.get(`/bookings/${id}`);
const { data } = await client.get(`/api/bookings/${id}`);
return data.data;
},
create: async (payload: CreateBookingPayload): Promise<Freight.IBooking> => {
const { data } = await client.post("/api/bookings", payload);
return data.data;
return data.data.booking;
},
getReferenceData: async (): Promise<Freight.BookingReferenceData> => {
const { data } = await client.get("/api/bookings/reference-data");
return data.data;
},
remove: async (id: string): Promise<void> => {
await client.delete(`/bookings/${id}`);
await client.delete(`/api/bookings/${id}`);
},
getContractView: async (id: string): Promise<ContractView> => {
const { data } = await client.get(B.CONTRACT_VIEW(id));
return data.data ?? data;
},
downloadContractDocument: async (id: string): Promise<Blob> => {
const { data } = await client.get(B.CONTRACT_DOCUMENT(id), {
responseType: "blob",
});
return data;
},
signContract: async (
id: string,
payload: SignContractPayload,
): Promise<Freight.IBooking> => {
const { data } = await client.post(B.CONTRACT_SIGN(id), payload);
return data.data ?? data;
},
};

View File

@@ -0,0 +1,117 @@
import { client } from "@/utils/api";
import { unwrap } from "@/utils/endpoint";
import { URL_CONSTANTS } from "@/constants/URLS";
import type { ApiResponse } from "@/types/apiResponse";
import type { ProfileResponse, UpdateProfilePayload } from "@/types/profile";
import { isAxiosError } from "axios";
export interface ExternalProfileResponse {
id: string;
userId: string;
companyId: string;
firstName: string;
lastName: string;
email: string;
phone: string | null;
nationalId: string | null;
jobTitle: string | null;
isPrimaryContact: boolean;
createdAt: string;
updatedAt: string;
}
export interface CompanyResponse {
id: string;
name: string;
type: string;
status: string;
tin: string;
vatNumber: string | null;
businessLicense: string | null;
fanNumber: string | null;
country: string;
address: string | null;
phone: string | null;
email: string | null;
website: string | null;
attributes: Record<string, any> | null;
createdAt: string;
updatedAt: string;
}
export interface CompanyInfoResponse {
profile: ExternalProfileResponse;
company: CompanyResponse;
}
export interface CreateCompanyPayload {
companyType?: string;
companyName: string;
companyEmail?: string;
companyPhone?: string;
companyLocation?: string;
companyAddress?: string;
tin?: string;
vatNumber?: string;
fanNumber?: string;
jobTitle?: string;
isPrimaryContact?: boolean;
attributes?: Record<string, any>;
}
export const companiesService = {
getInfo: async (): Promise<CompanyInfoResponse | null> => {
try {
const response = await client.get<ApiResponse<CompanyInfoResponse>>(
URL_CONSTANTS.COMPANIES_API.GET_INFO,
);
return unwrap(response.data);
} catch (e) {
if (isAxiosError(e) && e.response?.status === 404) {
return null;
}
throw e;
}
},
create: async (payload: CreateCompanyPayload): Promise<CompanyInfoResponse> => {
const response = await client.post<ApiResponse<CompanyInfoResponse>>(
URL_CONSTANTS.COMPANIES_API.CREATE,
payload,
);
return unwrap(response.data);
},
getProfile: async (): Promise<ProfileResponse> => {
const response = await client.get<ApiResponse<ProfileResponse>>(
URL_CONSTANTS.COMPANIES_API.PROFILE,
);
return unwrap(response.data);
},
updateProfile: async (payload: UpdateProfilePayload): Promise<ProfileResponse> => {
const response = await client.patch<ApiResponse<ProfileResponse>>(
URL_CONSTANTS.COMPANIES_API.PROFILE,
payload,
);
return unwrap(response.data);
},
uploadDocuments: async (
companyId: string,
files: Record<string, File | File[] | null>,
): Promise<void> => {
const formData = new FormData();
for (const [fieldName, fileOrFiles] of Object.entries(files)) {
if (!fileOrFiles) continue;
if (Array.isArray(fileOrFiles)) {
for (const f of fileOrFiles) {
formData.append(fieldName, f);
}
} else {
formData.append(fieldName, fileOrFiles);
}
}
await client.post(URL_CONSTANTS.COMPANIES_API.DOCUMENTS(companyId), formData);
},
};

View File

@@ -1,57 +0,0 @@
import { client } from "@/utils/api";
import { unwrap } from "@/utils/endpoint";
import { URL_CONSTANTS } from "@/constants/URLS";
import type { ApiResponse } from "@/types/apiResponse";
import type {
CreateCustomerDto,
Customer,
UpdateCustomerDto,
} from "@/types/customers";
import { isAxiosError } from "axios";
const BASE = URL_CONSTANTS.CUSTOMERS_API.BASE;
export const customersService = {
list: async (): Promise<Customer[]> => {
const response = await client.get<ApiResponse<Customer[]>>(BASE);
return unwrap(response.data);
},
getById: async (id: string): Promise<Customer> => {
const response = await client.get<ApiResponse<Customer>>(
URL_CONSTANTS.CUSTOMERS_API.BY_ID(id),
);
return unwrap(response.data);
},
getByUserId: async (userId: string): Promise<Customer | null> => {
try {
const response = await client.get<ApiResponse<Customer>>(
URL_CONSTANTS.CUSTOMERS_API.BY_USER_ID(userId),
);
return unwrap(response.data);
} catch (e) {
if (isAxiosError(e) && e.response?.status === 404) {
return null;
}
throw e;
}
},
create: async (payload: CreateCustomerDto): Promise<Customer> => {
const response = await client.post<ApiResponse<Customer>>(BASE, payload);
return unwrap(response.data);
},
update: async (id: string, payload: UpdateCustomerDto): Promise<Customer> => {
const response = await client.patch<ApiResponse<Customer>>(
URL_CONSTANTS.CUSTOMERS_API.BY_ID(id),
payload,
);
return unwrap(response.data);
},
remove: async (id: string): Promise<void> => {
await client.delete(URL_CONSTANTS.CUSTOMERS_API.BY_ID(id));
},
};

View File

@@ -43,6 +43,14 @@ export const fileUploadSettingsService = {
return unwrap(response.data);
},
// GET /file-upload-settings/by-entity/:entity
getByEntity: async (entity: string): Promise<FileUploadSetting[]> => {
const response = await client.get<ApiResponse<FileUploadSetting[]>>(
`${BASE}/by-entity/${encodeURIComponent(entity)}`,
);
return unwrap(response.data);
},
// GET /file-upload-settings/by-code/:code
getByCode: async (code: string): Promise<FileUploadSetting> => {
const response = await client.get<ApiResponse<FileUploadSetting>>(

View File

@@ -0,0 +1,43 @@
export interface ProfileResponse {
companyId: string;
companyName: string;
companyEmail: string | null;
companyPhone: string | null;
companyLocation: string;
companyAddress: string | null;
tinNumber: string;
vatNumber: string | null;
fanNumber: string | null;
contactPersonName: string | null;
contactPersonPhone: string | null;
generalManagerName: string | null;
generalManagerEmail: string | null;
generalManagerPhone: string | null;
poaName: string | null;
poaPhone: string | null;
poaEmail: string | null;
poaLocation: string | null;
poaAddress: string | null;
profileId: string;
}
export interface UpdateProfilePayload {
companyName?: string;
companyEmail?: string;
companyPhone?: string;
companyLocation?: string;
companyAddress?: string;
tin?: string;
vatNumber?: string;
fanNumber?: string;
contactPersonName?: string;
contactPersonPhone?: string;
generalManagerName?: string;
generalManagerEmail?: string;
generalManagerPhone?: string;
poaName?: string;
poaPhone?: string;
poaEmail?: string;
poaLocation?: string;
poaAddress?: string;
}