enhance shipment requests page with filtering and sorting options

- Added status and cargo filters to the ShipmentRequestsPage.
- Implemented date range filtering for preferred dates.
- Introduced sorting options for shipment requests based on submission date and reference.
- Enhanced the display of shipment request details, including status badges and customer information.
- Updated the UI to include a search input with clear functionality and improved layout for filters.

feat: add equipment return option in new shipment form

- Introduced a toggle for equipment return in the NewShipmentPage.
- Updated form schema to include  field for container contracts.
- Enhanced user experience with visual feedback on the equipment return selection.

fix: update booking DTO to include equipment return option

- Added  field to CreateBookingUnderContractDto for per-shipment override.
- Updated related types and schemas to accommodate the new field for better contract handling.
This commit is contained in:
Marshal
2026-07-10 10:32:41 +00:00
parent 2fb1917956
commit 1abef3ce34
19 changed files with 2130 additions and 294 deletions

View File

@@ -196,12 +196,12 @@ const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [
icon: <Send />,
permission: FREIGHT_PERMS.contracts.createBooking,
},
{
label: "Self-Clearance Review",
href: "/dashboard/contracts/ops-clearance",
icon: <ShieldCheck />,
permission: FREIGHT_PERMS.contracts.opsClearanceReview,
},
// {
// label: "Self-Clearance Review",
// href: "/dashboard/contracts/ops-clearance",
// icon: <ShieldCheck />,
// permission: FREIGHT_PERMS.contracts.opsClearanceReview,
// },
{
label: "GL Djibouti Clearance",
href: "/dashboard/gl-djibouti/clearance",

View File

@@ -38,6 +38,7 @@ import {
MapPin,
Package,
Receipt,
Repeat,
X,
} from "lucide-react";
import type { Freight } from "@edr/types";
@@ -192,9 +193,19 @@ export default function GlCreateBookingForm() {
const [notes, setNotes] = useState("");
const [containerLines, setContainerLines] = useState<ContainerLineDraft[]>([]);
const [bulkLines, setBulkLines] = useState<BulkLineDraft[]>([]);
const [withReturn, setWithReturn] = useState(false);
const [prefilled, setPrefilled] = useState(false);
const [priceOpen, setPriceOpen] = useState(false);
const seededRef = useRef(false);
const returnSeededRef = useRef(false);
// Seed the equipment-return toggle from the contract exactly once (also when
// the form is prefilled from a shipment request); GL can flip it per shipment.
useEffect(() => {
if (!contract || returnSeededRef.current) return;
returnSeededRef.current = true;
setWithReturn(contract.equipmentReturn === "WITH_RETURN");
}, [contract]);
const isContainer = contract?.freightType === "CONTAINER";
const routes = useMemo(
@@ -527,6 +538,10 @@ export default function GlCreateBookingForm() {
scheduledDate,
...(contractRouteId ? { contractRouteId } : {}),
...(notes.trim() ? { notes: notes.trim() } : {}),
// Equipment return is a container concern — bulk keeps the contract default.
...(isContainer
? { equipmentReturn: withReturn ? "WITH_RETURN" : "WITHOUT_RETURN" }
: {}),
};
if (isContainer) {
@@ -1091,6 +1106,67 @@ export default function GlCreateBookingForm() {
</StepCard>
)}
{isContainer ? (
<StepCard>
<StepHeader
icon={<Repeat size={22} />}
title="Equipment Return"
description="Choose whether the empty container(s) come back to EDR after unloading."
/>
<Paper
withBorder
radius="md"
p="md"
style={{
borderColor: withReturn ? "#CDEBDD" : "#E6ECF2",
background: withReturn ? "#F6FBF8" : "white",
cursor: "pointer",
transition: "border-color 150ms ease, background 150ms ease",
}}
onClick={() => setWithReturn((v) => !v)}
>
<Group justify="space-between" wrap="nowrap" gap="md">
<Group gap={13} wrap="nowrap" align="flex-start">
<Box
style={{
width: 38,
height: 38,
flexShrink: 0,
borderRadius: 11,
display: "flex",
alignItems: "center",
justifyContent: "center",
background: withReturn ? "#ECF6F1" : "#F1F4F7",
color: withReturn ? "#0A6F4D" : "#6B7C8E",
}}
>
<Repeat size={18} />
</Box>
<Box>
<Text fz={14} fw={700}>
With return
</Text>
<Text fz={12} c="dimmed" style={{ lineHeight: 1.4 }}>
{withReturn
? "Container(s) returned to EDR after unloading."
: "Container(s) retained by the customer after delivery."}
</Text>
</Box>
</Group>
<Switch
size="md"
color="edr-green"
aria-label="With return"
checked={withReturn}
onChange={(e) => setWithReturn(e.currentTarget.checked)}
onClick={(e) => e.stopPropagation()}
style={{ flexShrink: 0 }}
/>
</Group>
</Paper>
</StepCard>
) : null}
<StepCard>
<StepHeader
icon={<CalendarDays size={22} />}

View File

@@ -9,6 +9,12 @@ export interface ShipmentListRow {
summary: string;
status: Freight.BookingRequestStatus;
createdBookingId?: string | null;
/** When the customer submitted the request — the queue's default sort key. */
createdAt?: string | null;
customerName?: string | null;
freightKind?: "CONTAINER" | "BULK";
hazardous?: boolean;
reefer?: boolean;
}
export type ShipmentRowAction =

View File

@@ -1,15 +1,18 @@
import { useMemo, useState } from "react";
import { useMemo, useRef, useState } from "react";
import { useParams } from "react-router-dom";
import {
ActionIcon,
Badge,
Box,
Button,
Card,
Center,
Group,
Loader,
Menu,
Modal,
Paper,
ScrollArea,
Stack,
Switch,
Text,
@@ -19,13 +22,29 @@ import {
Tooltip,
} from "@mantine/core";
import {
AlertTriangle,
ArrowDown,
ArrowUp,
Banknote,
Building2,
CalendarClock,
CalendarDays,
CalendarRange,
ChevronDown,
Coins,
Hash,
ListOrdered,
ListPlus,
Mail,
MapPin,
Package,
Pencil,
Phone,
Plus,
RefreshCw,
Settings2,
Trash2,
Weight,
} from "lucide-react";
import { PageContainer, PageHeader } from "@/components/page";
@@ -41,7 +60,7 @@ import {
import type { ContractTemplateArticle } from "@/services/contract-templates.service";
const BODY_HINT =
'One clause per line — clauses are numbered automatically. Prefix a line with "- " to nest it as a bullet under the previous clause. Placeholders like {{client.companyName}}, {{contractDate}}, {{contractYear}} and {{reference}} are filled from the contract.';
'One clause per line — clauses are numbered automatically. Prefix a line with "- " to nest it as a bullet under the previous clause. Use the buttons above to drop a placeholder at the cursor — it is filled from the contract when the document is generated.';
interface ArticleDraft {
id?: string;
@@ -49,6 +68,254 @@ interface ArticleDraft {
body: string;
}
interface PlaceholderDef {
token: string;
label: string;
icon: typeof Building2;
hint: string;
}
/**
* Placeholders the renderer fills from the contract view model
* (contract-view-model.builder.ts). Quick row = the ones template authors
* reach for constantly; the rest live in the grouped "More" menu.
*/
const QUICK_PLACEHOLDERS: PlaceholderDef[] = [
{
token: "{{client.companyName}}",
label: "Client name",
icon: Building2,
hint: "Company name of the contracting client",
},
{
token: "{{reference}}",
label: "Reference",
icon: Hash,
hint: "Contract reference number",
},
{
token: "{{contractDate}}",
label: "Contract date",
icon: CalendarDays,
hint: "Full signature date of the contract",
},
{
token: "{{contractYear}}",
label: "Contract year",
icon: CalendarRange,
hint: "Year the contract is signed",
},
{
token: "{{pricing.totalAmount}}",
label: "Total price",
icon: Banknote,
hint: "Total contract price from the pricing schedule",
},
];
const MORE_PLACEHOLDER_GROUPS: { label: string; items: PlaceholderDef[] }[] = [
{
label: "Client",
items: [
{
token: "{{client.companyAddress}}",
label: "Client address",
icon: MapPin,
hint: "Street address of the client",
},
{
token: "{{client.companyLocation}}",
label: "Client location",
icon: MapPin,
hint: "Region / city of the client",
},
{
token: "{{client.phone}}",
label: "Client phone",
icon: Phone,
hint: "Client phone number",
},
{
token: "{{client.email}}",
label: "Client email",
icon: Mail,
hint: "Client email address",
},
{
token: "{{client.tinNumber}}",
label: "Client TIN",
icon: Hash,
hint: "Client tax identification number",
},
],
},
{
label: "Route & cargo",
items: [
{
token: "{{schedule.originLabel}}",
label: "Origin",
icon: MapPin,
hint: "Origin yard / station",
},
{
token: "{{schedule.destinationLabel}}",
label: "Destination",
icon: MapPin,
hint: "Destination yard / station",
},
{
token: "{{schedule.serviceType}}",
label: "Service type",
icon: Settings2,
hint: "Contracted service type name",
},
{
token: "{{schedule.cargoDescription}}",
label: "Cargo description",
icon: Package,
hint: "Description of the cargo",
},
{
token: "{{schedule.totalWeightVgm}}",
label: "Total weight",
icon: Weight,
hint: "Total verified gross mass",
},
{
token: "{{schedule.equipmentReturn}}",
label: "Equipment return",
icon: RefreshCw,
hint: "Empty-equipment return terms",
},
{
token: "{{schedule.scheduledDate}}",
label: "Scheduled date",
icon: CalendarClock,
hint: "Scheduled shipment date",
},
],
},
{
label: "Pricing",
items: [
{
token: "{{pricing.currency}}",
label: "Currency",
icon: Coins,
hint: "Payment currency (e.g. USD)",
},
],
},
{
label: "Service provider (EDR)",
items: [
{
token: "{{provider.name}}",
label: "Provider name",
icon: Building2,
hint: "EDR legal company name",
},
{
token: "{{provider.address}}",
label: "Provider address",
icon: MapPin,
hint: "EDR principal place of business",
},
{
token: "{{provider.phone}}",
label: "Provider phone",
icon: Phone,
hint: "EDR phone number",
},
{
token: "{{provider.email}}",
label: "Provider email",
icon: Mail,
hint: "EDR email address",
},
],
},
];
const ALL_PLACEHOLDERS: PlaceholderDef[] = [
...QUICK_PLACEHOLDERS,
...MORE_PLACEHOLDER_GROUPS.flatMap((g) => g.items),
];
const KNOWN_TOKENS = new Set<string>(ALL_PLACEHOLDERS.map((p) => p.token));
/** Any {{…}} tokens in the text the renderer does not know how to fill. */
function unknownTokens(text: string): string[] {
const found = text.match(/\{\{[^{}]+\}\}/g) ?? [];
return [...new Set(found.filter((t) => !KNOWN_TOKENS.has(t)))];
}
interface ParsedClause {
text: string;
bullets: string[];
}
interface ParsedBody {
/** Set (instead of clauses) when the body is one plain paragraph. */
paragraph?: string;
clauses: ParsedClause[];
}
/**
* Mirror of the API renderer's rules (contract-article.util.ts): one clause per
* line, "- " nests a bullet under the previous clause, and a single bullet-less
* clause renders as a plain paragraph instead of a numbered list of one.
*/
function parseArticleBody(body: string): ParsedBody {
const clauses: ParsedClause[] = [];
for (const raw of body.split("\n")) {
const line = raw.trim();
if (!line) continue;
if (line.startsWith("- ") && clauses.length > 0) {
clauses[clauses.length - 1].bullets.push(line.slice(2).trim());
} else {
clauses.push({ text: line.replace(/^- /, ""), bullets: [] });
}
}
if (clauses.length === 1 && clauses[0].bullets.length === 0) {
return { paragraph: clauses[0].text, clauses: [] };
}
return { clauses };
}
/** Render clause text with {{placeholders}} highlighted as green chips. */
function HighlightedText({ text }: { text: string }) {
const parts = text.split(/(\{\{[^{}]+\}\})/g);
return (
<>
{parts.map((part, i) =>
/^\{\{[^{}]+\}\}$/.test(part) ? (
<Text
key={i}
component="span"
size="xs"
fw={600}
c={KNOWN_TOKENS.has(part) ? "edr-green.8" : "red.7"}
px={4}
style={{
borderRadius: 4,
background: KNOWN_TOKENS.has(part)
? "var(--mantine-color-edr-green-0)"
: "var(--mantine-color-red-0)",
whiteSpace: "nowrap",
}}
>
{part}
</Text>
) : (
<span key={i}>{part}</span>
),
)}
</>
);
}
export default function ContractTemplateEditorPage() {
const { code } = useParams<{ code: string }>();
const { data: template, isLoading } = useContractTemplate(code);
@@ -79,15 +346,12 @@ export default function ContractTemplateEditorPage() {
);
};
const saveArticle = () => {
const saveArticle = (values: { title: string; body: string }) => {
if (!articleDraft) return;
if (articleDraft.id) {
updateArticle.mutate({
articleId: articleDraft.id,
payload: { title: articleDraft.title, body: articleDraft.body },
});
updateArticle.mutate({ articleId: articleDraft.id, payload: values });
} else {
addArticle.mutate({ title: articleDraft.title, body: articleDraft.body });
addArticle.mutate(values);
}
setArticleDraft(null);
};
@@ -264,55 +528,14 @@ export default function ContractTemplateEditorPage() {
</div>
{/* ── Add / edit article modal ───────────────────────────────────── */}
<Modal
opened={Boolean(articleDraft)}
onClose={() => setArticleDraft(null)}
title={articleDraft?.id ? "Edit article" : "Add article"}
size="xl"
>
{articleDraft && (
<Stack gap="sm">
<TextInput
label="Article title"
placeholder="e.g. Obligations of the Client"
value={articleDraft.title}
onChange={(event) =>
setArticleDraft({ ...articleDraft, title: event.currentTarget.value })
}
required
/>
<Textarea
label="Article body"
description={BODY_HINT}
value={articleDraft.body}
onChange={(event) =>
setArticleDraft({ ...articleDraft, body: event.currentTarget.value })
}
autosize
minRows={12}
maxRows={24}
styles={{ input: { fontFamily: "ui-monospace, monospace", fontSize: 13 } }}
required
/>
<Group justify="flex-end">
<Button variant="default" onClick={() => setArticleDraft(null)}>
Cancel
</Button>
<Button
color="edr-green"
disabled={
articleDraft.title.trim().length < 2 ||
articleDraft.body.trim().length < 2
}
loading={addArticle.isPending || updateArticle.isPending}
onClick={saveArticle}
>
{articleDraft.id ? "Save changes" : "Add article"}
</Button>
</Group>
</Stack>
)}
</Modal>
{articleDraft && (
<ArticleEditorModal
initial={articleDraft}
saving={addArticle.isPending || updateArticle.isPending}
onClose={() => setArticleDraft(null)}
onSave={saveArticle}
/>
)}
{/* ── Delete confirm ─────────────────────────────────────────────── */}
<Modal
@@ -364,6 +587,269 @@ export default function ContractTemplateEditorPage() {
);
}
interface ArticleEditorModalProps {
initial: ArticleDraft;
saving: boolean;
onClose: () => void;
onSave: (values: { title: string; body: string }) => void;
}
/**
* Rich add/edit article editor: placeholder buttons insert at the text cursor
* of whichever field (title or body) was focused last, with a live preview of
* the numbered clauses exactly as the renderer lays them out.
*/
function ArticleEditorModal({
initial,
saving,
onClose,
onSave,
}: ArticleEditorModalProps) {
const [title, setTitle] = useState(initial.title);
const [body, setBody] = useState(initial.body);
const titleRef = useRef<HTMLInputElement>(null);
const bodyRef = useRef<HTMLTextAreaElement>(null);
// Placeholders drop into whichever field held the cursor last (body default).
const lastFocused = useRef<"title" | "body">("body");
const insertAtCursor = (snippet: string) => {
const isTitle = lastFocused.current === "title";
const el = isTitle ? titleRef.current : bodyRef.current;
const value = isTitle ? title : body;
const start = el?.selectionStart ?? value.length;
const end = el?.selectionEnd ?? start;
const next = value.slice(0, start) + snippet + value.slice(end);
if (isTitle) setTitle(next);
else setBody(next);
// Refocus and place the caret right after the inserted snippet once the
// controlled re-render has flushed.
requestAnimationFrame(() => {
if (!el) return;
el.focus();
const caret = start + snippet.length;
el.setSelectionRange(caret, caret);
});
};
const insertLinePrefix = (prefix: string) => {
const el = bodyRef.current;
const start = el?.selectionStart ?? body.length;
// Start the snippet on its own line unless the caret already is.
const needsNewline = start > 0 && body[start - 1] !== "\n";
lastFocused.current = "body";
insertAtCursor(`${needsNewline ? "\n" : ""}${prefix}`);
};
const parsed = useMemo(() => parseArticleBody(body), [body]);
const clauseCount = parsed.paragraph ? 1 : parsed.clauses.length;
const unknown = useMemo(
() => unknownTokens(`${title}\n${body}`),
[title, body],
);
const canSave = title.trim().length >= 2 && body.trim().length >= 2;
return (
<Modal
opened
onClose={onClose}
title={initial.id ? "Edit article" : "Add article"}
size="min(1120px, 95vw)"
>
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
{/* ── Editor ─────────────────────────────────────────────────── */}
<Stack gap="sm">
<TextInput
ref={titleRef}
label="Article title"
placeholder="e.g. Obligations of the Client"
value={title}
onChange={(event) => setTitle(event.currentTarget.value)}
onFocus={() => (lastFocused.current = "title")}
required
/>
<Box>
<Text size="sm" fw={500} mb={4}>
Insert placeholder
</Text>
<Group gap={6} wrap="wrap">
{QUICK_PLACEHOLDERS.map(({ token, label, icon: Icon, hint }) => (
<Tooltip key={token} label={hint} withArrow>
<Button
variant="light"
color="edr-green"
size="compact-sm"
radius="md"
leftSection={<Icon size={13} />}
// Keep the field's focus/caret alive so insertion lands
// where the user was typing.
onMouseDown={(e) => e.preventDefault()}
onClick={() => insertAtCursor(token)}
>
{label}
</Button>
</Tooltip>
))}
<Menu shadow="md" width={300} position="bottom-start">
<Menu.Target>
<Button
variant="default"
size="compact-sm"
radius="md"
leftSection={<Plus size={13} />}
rightSection={<ChevronDown size={13} />}
onMouseDown={(e) => e.preventDefault()}
>
More
</Button>
</Menu.Target>
<Menu.Dropdown mah={340} style={{ overflowY: "auto" }}>
{MORE_PLACEHOLDER_GROUPS.map((group) => (
<Box key={group.label}>
<Menu.Label>{group.label}</Menu.Label>
{group.items.map(({ token, label, icon: Icon, hint }) => (
<Menu.Item
key={token}
leftSection={<Icon size={14} />}
onClick={() => insertAtCursor(token)}
>
<Text size="sm">{label}</Text>
<Text size="xs" c="dimmed" title={hint}>
{token}
</Text>
</Menu.Item>
))}
</Box>
))}
</Menu.Dropdown>
</Menu>
<Tooltip label="Start a new numbered clause" withArrow>
<Button
variant="default"
size="compact-sm"
radius="md"
leftSection={<ListOrdered size={13} />}
onMouseDown={(e) => e.preventDefault()}
onClick={() => insertLinePrefix("")}
>
New clause
</Button>
</Tooltip>
<Tooltip label="Nest a bullet under the previous clause" withArrow>
<Button
variant="default"
size="compact-sm"
radius="md"
leftSection={<ListPlus size={13} />}
onMouseDown={(e) => e.preventDefault()}
onClick={() => insertLinePrefix("- ")}
>
Bullet
</Button>
</Tooltip>
</Group>
</Box>
<Textarea
ref={bodyRef}
label="Article body"
description={BODY_HINT}
value={body}
onChange={(event) => setBody(event.currentTarget.value)}
onFocus={() => (lastFocused.current = "body")}
autosize
minRows={12}
maxRows={22}
styles={{
input: { fontFamily: "ui-monospace, monospace", fontSize: 13 },
}}
required
/>
{unknown.length > 0 && (
<Group gap={6} wrap="nowrap" align="flex-start">
<AlertTriangle size={14} className="mt-0.5 shrink-0 text-red-600" />
<Text size="xs" c="red.7">
Unknown placeholder{unknown.length > 1 ? "s" : ""}{" "}
{unknown.join(", ")} the generator won't fill{" "}
{unknown.length > 1 ? "these" : "this"}. Pick from the Insert
placeholder buttons instead.
</Text>
</Group>
)}
</Stack>
{/* ── Live preview ───────────────────────────────────────────── */}
<Paper withBorder radius="md" p="md" className="self-start lg:sticky lg:top-0">
<Group justify="space-between" mb="xs">
<Text fw={600} size="sm">
Live preview
</Text>
<Text size="xs" c="dimmed">
{clauseCount} clause{clauseCount !== 1 ? "s" : ""}
</Text>
</Group>
<ScrollArea.Autosize mah="60vh">
{title.trim() || clauseCount > 0 ? (
<Stack gap="xs">
{title.trim() && (
<Title order={5}>
<HighlightedText text={title} />
</Title>
)}
{parsed.paragraph && (
<Text size="sm">
<HighlightedText text={parsed.paragraph} />
</Text>
)}
{parsed.clauses.map((clause, i) => (
<Box key={i}>
<Text size="sm">
<Text component="span" fw={600} c="edr-green.7">
{i + 1}.{" "}
</Text>
<HighlightedText text={clause.text} />
</Text>
{clause.bullets.length > 0 && (
<Stack gap={2} mt={2} pl="lg">
{clause.bullets.map((bullet, j) => (
<Text key={j} size="sm" c="dimmed">
<HighlightedText text={bullet} />
</Text>
))}
</Stack>
)}
</Box>
))}
</Stack>
) : (
<Text size="sm" c="dimmed" ta="center" py="xl">
Start typing the article renders here exactly as it will
appear in the contract.
</Text>
)}
</ScrollArea.Autosize>
</Paper>
</div>
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={onClose}>
Cancel
</Button>
<Button
color="edr-green"
disabled={!canSave}
loading={saving}
onClick={() => onSave({ title: title.trim(), body: body.trim() })}
>
{initial.id ? "Save changes" : "Add article"}
</Button>
</Group>
</Modal>
);
}
interface DocumentDetailsModalProps {
opened: boolean;
onClose: () => void;

View File

@@ -6,14 +6,26 @@ import {
Badge,
Box,
Button,
CloseButton,
Group,
Modal,
Paper,
SegmentedControl,
Select,
Stack,
Text,
Textarea,
TextInput,
} from "@mantine/core";
import { Inbox, PackageSearch, RefreshCw, Search } from "lucide-react";
import { DateInput } from "@mantine/dates";
import {
ArrowUpDown,
FilterX,
Inbox,
PackageSearch,
RefreshCw,
Search,
} from "lucide-react";
import { DataTable, type ColumnDef } from "@edr/ui-common";
import type { Freight } from "@edr/types";
@@ -41,6 +53,17 @@ const fmtDate = (iso?: string | null) =>
}).format(new Date(iso))
: "—";
const fmtDateTime = (iso?: string | null) =>
iso
? new Intl.DateTimeFormat("en-GB", {
day: "2-digit",
month: "short",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
}).format(new Date(iso))
: "—";
function summarizeLines(lines: Freight.RequestedShipmentLines): string {
if (lines.containers?.length) {
return lines.containers
@@ -56,10 +79,46 @@ function summarizeLines(lines: Freight.RequestedShipmentLines): string {
return "—";
}
const STATUS_META: Record<
Freight.BookingRequestStatus,
{ label: string; color: string }
> = {
PENDING: { label: "Pending", color: "yellow" },
ACCEPTED: { label: "Accepted", color: "edr-green" },
REJECTED: { label: "Rejected", color: "red" },
CANCELLED: { label: "Cancelled", color: "gray" },
};
type StatusFilter = "ALL" | Freight.BookingRequestStatus;
type CargoFilter = "ALL" | "CONTAINER" | "BULK";
type SortKey =
| "submitted-desc"
| "submitted-asc"
| "preferred-asc"
| "preferred-desc"
| "reference";
const SORT_OPTIONS: Array<{ value: SortKey; label: string }> = [
{ value: "submitted-desc", label: "Newest first" },
{ value: "submitted-asc", label: "Oldest first" },
{ value: "preferred-asc", label: "Preferred date (soonest)" },
{ value: "preferred-desc", label: "Preferred date (latest)" },
{ value: "reference", label: "Reference AZ" },
];
const time = (iso?: string | null) => (iso ? new Date(iso).getTime() : 0);
export default function ShipmentRequestsPage() {
const navigate = useNavigate();
const queryClient = useQueryClient();
const [query, setQuery] = useState("");
const [status, setStatus] = useState<StatusFilter>("PENDING");
const [cargo, setCargo] = useState<CargoFilter>("ALL");
const [preferredFrom, setPreferredFrom] = useState<Date | null>(null);
const [preferredTo, setPreferredTo] = useState<Date | null>(null);
const [sort, setSort] = useState<SortKey>("submitted-desc");
const [rejectTarget, setRejectTarget] = useState<ShipmentListRow | null>(null);
const [rejectNote, setRejectNote] = useState("");
const [acceptTarget, setAcceptTarget] = useState<ShipmentListRow | null>(null);
@@ -80,26 +139,132 @@ export default function ShipmentRequestsPage() {
},
});
const allRows = useMemo<ShipmentListRow[]>(
() =>
(data ?? []).map((r) => {
const lines = r.requestedLines ?? {};
return {
id: r.id,
reference: r.reference || r.id.slice(0, 8),
contractId: r.contractId,
contractReference: r.contract?.reference ?? r.contractId,
scheduledDate: r.scheduledDate,
summary: summarizeLines(lines),
status: r.status,
createdBookingId: r.createdBookingId,
createdAt: r.createdAt,
customerName: r.contract?.company?.name ?? null,
freightKind: lines.containers?.length
? "CONTAINER"
: lines.bulk
? "BULK"
: r.contract?.freightType === "BULK"
? "BULK"
: "CONTAINER",
hazardous:
(lines.containers ?? []).some((c) => (c.hazardousQuantity ?? 0) > 0) ||
(lines.bulk?.hazardousQuantity ?? 0) > 0,
reefer: (lines.containers ?? []).some(
(c) => (c.reeferQuantity ?? 0) > 0,
),
};
}),
[data],
);
// Status counts always reflect the whole queue so the segmented control
// reads as a live overview, independent of the other filters.
const counts = useMemo(() => {
const c: Record<StatusFilter, number> = {
ALL: allRows.length,
PENDING: 0,
ACCEPTED: 0,
REJECTED: 0,
CANCELLED: 0,
};
allRows.forEach((r) => {
c[r.status] += 1;
});
return c;
}, [allRows]);
const rows = useMemo<ShipmentListRow[]>(() => {
const all = (data ?? []).map((r) => ({
id: r.id,
reference: r.reference || r.id.slice(0, 8),
contractId: r.contractId,
contractReference: r.contract?.reference ?? r.contractId,
scheduledDate: r.scheduledDate,
summary: summarizeLines(r.requestedLines ?? {}),
status: r.status,
createdBookingId: r.createdBookingId,
}));
let out = allRows;
if (status !== "ALL") out = out.filter((r) => r.status === status);
if (cargo !== "ALL") out = out.filter((r) => r.freightKind === cargo);
// Preferred-date range: rows without a preferred day drop out once a bound
// is set — a date filter that keeps dateless rows reads as broken.
if (preferredFrom || preferredTo) {
const from = preferredFrom ? preferredFrom.getTime() : -Infinity;
const to = preferredTo
? preferredTo.getTime() + 24 * 60 * 60 * 1000 - 1
: Infinity;
out = out.filter((r) => {
if (!r.scheduledDate) return false;
const t = time(r.scheduledDate);
return t >= from && t <= to;
});
}
const q = query.trim().toLowerCase();
if (!q) return all;
return all.filter(
(r) =>
r.reference.toLowerCase().includes(q) ||
r.contractReference.toLowerCase().includes(q) ||
r.summary.toLowerCase().includes(q),
);
}, [data, query]);
if (q) {
out = out.filter(
(r) =>
r.reference.toLowerCase().includes(q) ||
r.contractReference.toLowerCase().includes(q) ||
(r.customerName ?? "").toLowerCase().includes(q) ||
r.summary.toLowerCase().includes(q),
);
}
const sorted = [...out];
switch (sort) {
case "submitted-asc":
sorted.sort((a, b) => time(a.createdAt) - time(b.createdAt));
break;
case "preferred-asc":
// Requests without a preferred day sink to the bottom in both orders.
sorted.sort(
(a, b) =>
(a.scheduledDate ? time(a.scheduledDate) : Infinity) -
(b.scheduledDate ? time(b.scheduledDate) : Infinity),
);
break;
case "preferred-desc":
sorted.sort(
(a, b) =>
(b.scheduledDate ? time(b.scheduledDate) : -Infinity) -
(a.scheduledDate ? time(a.scheduledDate) : -Infinity),
);
break;
case "reference":
sorted.sort((a, b) => a.reference.localeCompare(b.reference));
break;
default:
// Newest submitted on top.
sorted.sort((a, b) => time(b.createdAt) - time(a.createdAt));
}
return sorted;
}, [allRows, status, cargo, preferredFrom, preferredTo, query, sort]);
const filtersActive =
query.trim() !== "" ||
status !== "PENDING" ||
cargo !== "ALL" ||
preferredFrom !== null ||
preferredTo !== null ||
sort !== "submitted-desc";
const clearFilters = () => {
setQuery("");
setStatus("PENDING");
setCargo("ALL");
setPreferredFrom(null);
setPreferredTo(null);
setSort("submitted-desc");
};
const columns = useMemo<ColumnDef<ShipmentListRow>[]>(
() => [
@@ -108,9 +273,14 @@ export default function ShipmentRequestsPage() {
header: "Request",
meta: cellMeta,
cell: ({ row }) => (
<Text size="sm" fw={700} c="dark.5">
{row.original.reference}
</Text>
<Box>
<Text size="sm" fw={700} c="dark.5">
{row.original.reference}
</Text>
<Text size="xs" c="dimmed" mt={2}>
Submitted {fmtDateTime(row.original.createdAt)}
</Text>
</Box>
),
},
{
@@ -118,9 +288,16 @@ export default function ShipmentRequestsPage() {
header: "Contract",
meta: cellMeta,
cell: ({ row }) => (
<Text size="sm" c="gray.7">
{row.original.contractReference}
</Text>
<Box>
<Text size="sm" c="gray.7">
{row.original.contractReference}
</Text>
{row.original.customerName ? (
<Text size="xs" c="dimmed" mt={2}>
{row.original.customerName}
</Text>
) : null}
</Box>
),
},
{
@@ -128,9 +305,21 @@ export default function ShipmentRequestsPage() {
header: "Requested",
meta: cellMeta,
cell: ({ row }) => (
<Badge variant="light" color="edr-green" radius="sm">
{row.original.summary}
</Badge>
<Group gap={6} wrap="wrap">
<Badge variant="light" color="edr-green" radius="sm">
{row.original.summary}
</Badge>
{row.original.hazardous ? (
<Badge variant="light" color="red" radius="sm">
Hazardous
</Badge>
) : null}
{row.original.reefer ? (
<Badge variant="light" color="blue" radius="sm">
Reefer
</Badge>
) : null}
</Group>
),
},
{
@@ -141,6 +330,19 @@ export default function ShipmentRequestsPage() {
<Text size="sm">{fmtDate(row.original.scheduledDate)}</Text>
),
},
{
id: "status",
header: "Status",
meta: cellMeta,
cell: ({ row }) => {
const meta = STATUS_META[row.original.status];
return (
<Badge variant="light" color={meta.color} radius="sm">
{meta.label}
</Badge>
);
},
},
{
id: "actions",
header: () => <span className={ruleEngineTable.headerCell}>Action</span>,
@@ -193,6 +395,8 @@ export default function ShipmentRequestsPage() {
[navigate],
);
const hasAnyRequests = allRows.length > 0;
return (
<PageContainer>
<Stack gap="lg">
@@ -206,7 +410,7 @@ export default function ShipmentRequestsPage() {
radius="sm"
leftSection={<PackageSearch size={13} />}
>
{rows.length} pending
{counts.PENDING} pending
</Badge>
}
action={
@@ -223,16 +427,108 @@ export default function ShipmentRequestsPage() {
}
/>
<TextInput
radius="md"
maw={360}
placeholder="Search request, contract, cargo…"
leftSection={<Search size={15} />}
value={query}
onChange={(e) => setQuery(e.currentTarget.value)}
/>
<Paper withBorder radius="lg" p="md" style={{ borderColor: "#E6ECF2" }}>
<Stack gap="sm">
<Group gap="sm" wrap="wrap">
<TextInput
radius="md"
style={{ flex: 1, minWidth: 220 }}
placeholder="Search request, contract, customer, cargo…"
leftSection={<Search size={15} />}
rightSection={
query ? (
<CloseButton
size="sm"
aria-label="Clear search"
onClick={() => setQuery("")}
/>
) : null
}
value={query}
onChange={(e) => setQuery(e.currentTarget.value)}
/>
<Select
radius="md"
w={150}
value={cargo}
onChange={(v) => setCargo((v as CargoFilter) ?? "ALL")}
data={[
{ value: "ALL", label: "All cargo" },
{ value: "CONTAINER", label: "Containers" },
{ value: "BULK", label: "Bulk" },
]}
allowDeselect={false}
aria-label="Cargo type"
/>
<DateInput
radius="md"
w={150}
placeholder="Preferred from"
value={preferredFrom}
onChange={(v) => setPreferredFrom(v ? new Date(v) : null)}
maxDate={preferredTo ?? undefined}
clearable
aria-label="Preferred date from"
/>
<DateInput
radius="md"
w={150}
placeholder="Preferred to"
value={preferredTo}
onChange={(v) => setPreferredTo(v ? new Date(v) : null)}
minDate={preferredFrom ?? undefined}
clearable
aria-label="Preferred date to"
/>
<Select
radius="md"
w={215}
leftSection={<ArrowUpDown size={14} />}
value={sort}
onChange={(v) => setSort((v as SortKey) ?? "submitted-desc")}
data={SORT_OPTIONS}
allowDeselect={false}
aria-label="Sort by"
/>
</Group>
{rows.length === 0 && !isLoading ? (
<Group justify="space-between" gap="sm" wrap="wrap">
<SegmentedControl
radius="md"
size="xs"
value={status}
onChange={(v) => setStatus(v as StatusFilter)}
data={[
{ value: "ALL", label: `All · ${counts.ALL}` },
{ value: "PENDING", label: `Pending · ${counts.PENDING}` },
{ value: "ACCEPTED", label: `Accepted · ${counts.ACCEPTED}` },
{ value: "REJECTED", label: `Rejected · ${counts.REJECTED}` },
{ value: "CANCELLED", label: `Cancelled · ${counts.CANCELLED}` },
]}
/>
<Group gap="sm">
<Text size="sm" c="dimmed">
{rows.length} of {allRows.length} request
{allRows.length === 1 ? "" : "s"}
</Text>
{filtersActive ? (
<Button
variant="subtle"
color="gray"
size="compact-sm"
radius="md"
leftSection={<FilterX size={14} />}
onClick={clearFilters}
>
Clear filters
</Button>
) : null}
</Group>
</Group>
</Stack>
</Paper>
{rows.length === 0 && !isLoading && !isError ? (
<Box
py={56}
style={{
@@ -242,9 +538,28 @@ export default function ShipmentRequestsPage() {
}}
>
<Inbox size={26} className="text-muted-foreground" />
<Text c="dimmed" mt="sm">
No pending shipment requests.
</Text>
{hasAnyRequests ? (
<>
<Text c="dimmed" mt="sm">
No requests match the current filters.
</Text>
<Button
variant="subtle"
color="gray"
size="compact-sm"
radius="md"
mt="xs"
leftSection={<FilterX size={14} />}
onClick={clearFilters}
>
Clear filters
</Button>
</>
) : (
<Text c="dimmed" mt="sm">
No shipment requests yet.
</Text>
)}
</Box>
) : (
<DataTable

View File

@@ -201,6 +201,11 @@ export interface BookingDetail {
latestChangeRequestNote?: string | null;
nextStep?: BookingNextStep | null;
paymentReceipt?: InAppPaymentReceipt;
/** Phased-clearance fields the ET/DJ queue rows surface (GENERAL customs bookings). */
clearanceCurrentPhase?: string | null;
roHoldReason?: string | null;
roAmendmentRequestedAt?: string | null;
preClearanceFinalizedAt?: string | null;
createdAt: string;
updatedAt: string;
// customer?: BookingNamedRef & { companyName?: string };