mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-29 23:28:11 +00:00
Merge freight/develop into feature/trains-management
This commit is contained in:
@@ -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>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 };
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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);
|
||||
};
|
||||
|
||||
47
apps/edr-freight-web/backoffice/src/components/ui/badge.tsx
Normal file
47
apps/edr-freight-web/backoffice/src/components/ui/badge.tsx
Normal 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 };
|
||||
@@ -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';
|
||||
114
apps/edr-freight-web/backoffice/src/components/ui/table.tsx
Normal file
114
apps/edr-freight-web/backoffice/src/components/ui/table.tsx
Normal 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,
|
||||
};
|
||||
50
apps/edr-freight-web/backoffice/src/constants/QUERY_KEYS.ts
Normal file
50
apps/edr-freight-web/backoffice/src/constants/QUERY_KEYS.ts
Normal 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;
|
||||
@@ -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,
|
||||
},
|
||||
}
|
||||
@@ -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: {
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
@@ -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),
|
||||
});
|
||||
@@ -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),
|
||||
});
|
||||
@@ -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 }),
|
||||
});
|
||||
};
|
||||
@@ -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),
|
||||
});
|
||||
@@ -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"),
|
||||
});
|
||||
|
||||
24
apps/edr-freight-web/backoffice/src/hooks/use-toast.ts
Normal file
24
apps/edr-freight-web/backoffice/src/hooks/use-toast.ts
Normal 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 };
|
||||
}
|
||||
5
apps/edr-freight-web/backoffice/src/hooks/useBookings.ts
Normal file
5
apps/edr-freight-web/backoffice/src/hooks/useBookings.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export {
|
||||
useBookingList,
|
||||
useBookingDetail,
|
||||
useBookingMutations,
|
||||
} from "./bookings/useBookings";
|
||||
@@ -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() }),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -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(),
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
12
apps/edr-freight-web/backoffice/src/lib/queryClient.ts
Normal file
12
apps/edr-freight-web/backoffice/src/lib/queryClient.ts
Normal 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,
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -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}>
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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[] = [];
|
||||
@@ -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(
|
||||
|
||||
@@ -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[]>(
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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" },
|
||||
],
|
||||
|
||||
338
apps/edr-freight-web/backoffice/src/services/api.ts
Normal file
338
apps/edr-freight-web/backoffice/src/services/api.ts
Normal 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),
|
||||
),
|
||||
},
|
||||
};
|
||||
173
apps/edr-freight-web/backoffice/src/services/bookings.service.ts
Normal file
173
apps/edr-freight-web/backoffice/src/services/bookings.service.ts
Normal 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 }),
|
||||
};
|
||||
@@ -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`),
|
||||
};
|
||||
};
|
||||
@@ -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),
|
||||
);
|
||||
|
||||
@@ -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);
|
||||
},
|
||||
|
||||
|
||||
128
apps/edr-freight-web/backoffice/src/types/booking.ts
Normal file
128
apps/edr-freight-web/backoffice/src/types/booking.ts
Normal 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;
|
||||
}
|
||||
@@ -23,7 +23,3 @@ export interface RuleEngineListResult<T> {
|
||||
}
|
||||
|
||||
export type RuleEngineRecord = Record<string, unknown> & { id: string };
|
||||
|
||||
export interface ApproveRatePayload {
|
||||
approvedByCeoId: string;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
29
apps/edr-freight-web/backoffice/src/utils/result.ts
Normal file
29
apps/edr-freight-web/backoffice/src/utils/result.ts
Normal 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" };
|
||||
}
|
||||
Reference in New Issue
Block a user