mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-09-07 20:05:41 +00:00
resolve merge conflict
This commit is contained in:
@@ -118,6 +118,8 @@ import TrainDetailPage from "./pages/trains/TrainDetailPage";
|
||||
import TrainBuilderDetailPage from "./pages/trainBuilder/TrainBuilderDetailPage";
|
||||
import TrainBuilderListPage from "./pages/trainBuilder/TrainBuilderListPage";
|
||||
import ArrivalQueuePage from "./pages/warehouses/ArrivalQueuePage";
|
||||
import EDRLastMileReturnsPage from "./pages/warehouses/EDRLastMileReturnsPage";
|
||||
import ContainerReturnsPage from "./pages/warehouses/ContainerReturnsPage";
|
||||
import DispatchQueuePage from "./pages/warehouses/DispatchQueuePage";
|
||||
import ExportDjiboutiUnloadingQueuePage from "./pages/warehouses/ExportDjiboutiUnloadingQueuePage";
|
||||
import ExportWarehouseFlowPage from "./pages/warehouses/ExportWarehouseFlowPage";
|
||||
@@ -411,6 +413,18 @@ const buildSidebarSections = (demoItems: SidebarItem[]): SidebarSection[] => [
|
||||
icon: <Truck />,
|
||||
permission: FREIGHT_PERMS.warehouseInventory.view,
|
||||
},
|
||||
{
|
||||
label: "EDR Last Mile Returns",
|
||||
href: "/dashboard/edr-last-mile-returns",
|
||||
icon: <Container />,
|
||||
permission: FREIGHT_PERMS.warehouseInventory.view,
|
||||
},
|
||||
{
|
||||
label: "Container Returns",
|
||||
href: "/dashboard/container-returns",
|
||||
icon: <Container />,
|
||||
permission: FREIGHT_PERMS.warehouseInventory.view,
|
||||
},
|
||||
{
|
||||
label: "Dispatch Queue",
|
||||
href: "/dashboard/dispatch-queue",
|
||||
@@ -1060,6 +1074,8 @@ const App = () => {
|
||||
<Route path="intercity" element={<IntercityPage />} />
|
||||
<Route path="trucks-on-site" element={<TrucksOnSitePage />} />
|
||||
<Route path="import-trucks" element={<ImportTrucksPage />} />
|
||||
<Route path="edr-last-mile-returns" element={<EDRLastMileReturnsPage />} />
|
||||
<Route path="container-returns" element={<ContainerReturnsPage />} />
|
||||
<Route path="loaded-inventory" element={<LoadedInventoryPage />} />
|
||||
<Route path="dispatch-queue" element={<DispatchQueuePage />} />
|
||||
<Route
|
||||
|
||||
@@ -2,7 +2,6 @@ import {
|
||||
Alert,
|
||||
Anchor,
|
||||
Badge,
|
||||
Box,
|
||||
Button,
|
||||
Card,
|
||||
Group,
|
||||
@@ -27,11 +26,11 @@ import { useAuth } from "@/auth/useAuth";
|
||||
import { FREIGHT_PERMS, hasPermission } from "@/lib/permissions";
|
||||
import { fetchViewableFile } from "@/services/files.service";
|
||||
import { api } from "@/services/api";
|
||||
import type { Company, CompanyChangeRequest } from "@/types/customer";
|
||||
import type { Company } from "@/types/customer";
|
||||
import { formatDate, humanize } from "./format";
|
||||
|
||||
/** Friendly labels for the proposed-change snapshot keys (UpdateProfileDto). */
|
||||
const FIELD_LABELS: Record<string, string> = {
|
||||
export const FIELD_LABELS: Record<string, string> = {
|
||||
companyName: "Company name",
|
||||
companyEmail: "Company email",
|
||||
companyPhone: "Company phone",
|
||||
@@ -69,7 +68,7 @@ const FIELD_LABELS: Record<string, string> = {
|
||||
};
|
||||
|
||||
/** Best-effort current value on the live company for a proposed field key. */
|
||||
function currentValue(company: Company, key: string): string {
|
||||
export function currentValue(company: Company, key: string): string {
|
||||
const c = company as unknown as Record<string, unknown>;
|
||||
const attrs = (company.attributes ?? {}) as Record<string, unknown>;
|
||||
const map: Record<string, unknown> = {
|
||||
@@ -160,7 +159,7 @@ function FaydaIdentityDiff({
|
||||
);
|
||||
}
|
||||
|
||||
function DiffRow({
|
||||
export function DiffRow({
|
||||
label,
|
||||
from,
|
||||
to,
|
||||
@@ -201,8 +200,9 @@ function DiffRow({
|
||||
|
||||
/**
|
||||
* Backoffice review surface for a customer's staged profile edits. Shows the
|
||||
* pending change request as a proposed-vs-current diff with Approve / Reject
|
||||
* (with note) actions, plus a short history of past decisions.
|
||||
* pending change request as a proposed-vs-current diff with Approve / Reject /
|
||||
* Request changes actions. Past decisions live in the History tab's unified
|
||||
* timeline (see {@link CompanyTimeline}), not here.
|
||||
*/
|
||||
export function ChangeRequestReview({ company }: { company: Company }) {
|
||||
const { user } = useAuth();
|
||||
@@ -216,16 +216,21 @@ export function ChangeRequestReview({ company }: { company: Company }) {
|
||||
const reject = useMutation(
|
||||
api.customers.rejectChangeRequest.mutationOptions(),
|
||||
);
|
||||
const requestChanges = useMutation(
|
||||
api.customers.requestChangeRequestChanges.mutationOptions(),
|
||||
);
|
||||
|
||||
const { view, viewer } = useFileViewer();
|
||||
const [rejectId, setRejectId] = useState<string | null>(null);
|
||||
const [actionTarget, setActionTarget] = useState<{
|
||||
id: string;
|
||||
kind: "reject" | "request-changes";
|
||||
} | null>(null);
|
||||
const [note, setNote] = useState("");
|
||||
|
||||
const requests = query.data ?? [];
|
||||
const pending = requests.find((r) => r.status === "pending");
|
||||
const history = requests.filter((r) => r.status !== "pending").slice(0, 5);
|
||||
|
||||
if (!pending && history.length === 0) return null;
|
||||
if (!pending) return null;
|
||||
|
||||
const proposedKeys = pending
|
||||
? Object.keys(pending.snapshot ?? {}).filter((k) => k !== "faydaIdentity")
|
||||
@@ -237,13 +242,14 @@ export function ChangeRequestReview({ company }: { company: Company }) {
|
||||
const licenseChanges = pending?.licenseChanges ?? [];
|
||||
const documentChanges = pending?.documentChanges ?? [];
|
||||
|
||||
const confirmReject = () => {
|
||||
if (!rejectId) return;
|
||||
reject.mutate(
|
||||
{ id: rejectId, note: note.trim() },
|
||||
const confirmAction = () => {
|
||||
if (!actionTarget) return;
|
||||
const mutation = actionTarget.kind === "reject" ? reject : requestChanges;
|
||||
mutation.mutate(
|
||||
{ id: actionTarget.id, note: note.trim() },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setRejectId(null);
|
||||
setActionTarget(null);
|
||||
setNote("");
|
||||
},
|
||||
},
|
||||
@@ -270,6 +276,18 @@ export function ChangeRequestReview({ company }: { company: Company }) {
|
||||
</Text>
|
||||
</Group>
|
||||
|
||||
{pending.note && (
|
||||
<Alert
|
||||
color="yellow"
|
||||
variant="light"
|
||||
icon={<AlertTriangle size={16} />}
|
||||
>
|
||||
Changes were requested on an earlier round of this same
|
||||
submission: <strong>{pending.note}</strong> — check whether
|
||||
this resubmission actually addresses it before approving.
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{proposedKeys.length > 0 ? (
|
||||
<SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="lg">
|
||||
{proposedKeys.map((key) => (
|
||||
@@ -418,12 +436,22 @@ export function ChangeRequestReview({ company }: { company: Company }) {
|
||||
variant="light"
|
||||
color="red"
|
||||
onClick={() => {
|
||||
setRejectId(pending.id);
|
||||
setActionTarget({ id: pending.id, kind: "reject" });
|
||||
setNote("");
|
||||
}}
|
||||
>
|
||||
Reject
|
||||
</Button>
|
||||
<Button
|
||||
variant="light"
|
||||
color="yellow"
|
||||
onClick={() => {
|
||||
setActionTarget({ id: pending.id, kind: "request-changes" });
|
||||
setNote("");
|
||||
}}
|
||||
>
|
||||
Request changes
|
||||
</Button>
|
||||
<Button
|
||||
color="edr-green"
|
||||
loading={approve.isPending}
|
||||
@@ -437,51 +465,31 @@ export function ChangeRequestReview({ company }: { company: Company }) {
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{history.length > 0 && (
|
||||
<Card withBorder>
|
||||
<Stack gap="sm">
|
||||
<Text fw={600} c="edr-text">
|
||||
Review history
|
||||
</Text>
|
||||
{history.map((r: CompanyChangeRequest) => (
|
||||
<Group key={r.id} gap="sm" wrap="nowrap" align="flex-start">
|
||||
<Badge
|
||||
color={r.status === "approved" ? "edr-green" : "red"}
|
||||
variant="light"
|
||||
radius="md"
|
||||
tt="capitalize"
|
||||
>
|
||||
{r.status}
|
||||
</Badge>
|
||||
<Box style={{ flex: 1 }}>
|
||||
<Text size="sm" c="edr-text">
|
||||
{formatDate(r.reviewedAt ?? r.updatedAt)}
|
||||
</Text>
|
||||
{r.note && (
|
||||
<Text size="xs" c="dimmed">
|
||||
Note: {r.note}
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Group>
|
||||
))}
|
||||
</Stack>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
opened={rejectId !== null}
|
||||
onClose={() => setRejectId(null)}
|
||||
title="Reject changes"
|
||||
opened={actionTarget !== null}
|
||||
onClose={() => setActionTarget(null)}
|
||||
title={
|
||||
actionTarget?.kind === "reject" ? "Reject changes" : "Request changes"
|
||||
}
|
||||
centered
|
||||
radius="lg"
|
||||
>
|
||||
<Stack gap="md">
|
||||
<Alert color="red" variant="light" icon={<AlertTriangle size={18} />}>
|
||||
The customer will see this note and can amend and resubmit.
|
||||
<Alert
|
||||
color={actionTarget?.kind === "reject" ? "red" : "yellow"}
|
||||
variant="light"
|
||||
icon={<AlertTriangle size={18} />}
|
||||
>
|
||||
{actionTarget?.kind === "reject"
|
||||
? "The customer will see this note and can amend and resubmit."
|
||||
: "The customer will see this note and can keep editing this same request — no need to start over."}
|
||||
</Alert>
|
||||
<Textarea
|
||||
label="Reason for rejection"
|
||||
label={
|
||||
actionTarget?.kind === "reject"
|
||||
? "Reason for rejection"
|
||||
: "What needs to change"
|
||||
}
|
||||
placeholder="e.g. The company address doesn't match the trade license."
|
||||
autosize
|
||||
minRows={3}
|
||||
@@ -492,18 +500,20 @@ export function ChangeRequestReview({ company }: { company: Company }) {
|
||||
<Group justify="flex-end" gap="sm">
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={() => setRejectId(null)}
|
||||
disabled={reject.isPending}
|
||||
onClick={() => setActionTarget(null)}
|
||||
disabled={reject.isPending || requestChanges.isPending}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
color="red"
|
||||
loading={reject.isPending}
|
||||
color={actionTarget?.kind === "reject" ? "red" : "yellow"}
|
||||
loading={reject.isPending || requestChanges.isPending}
|
||||
disabled={note.trim().length === 0}
|
||||
onClick={confirmReject}
|
||||
onClick={confirmAction}
|
||||
>
|
||||
Reject changes
|
||||
{actionTarget?.kind === "reject"
|
||||
? "Reject changes"
|
||||
: "Request changes"}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
import { Alert, Anchor, Badge, Card, Group, SimpleGrid, Stack, Text } from "@mantine/core";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { FilePlus2, FileX2, History } from "lucide-react";
|
||||
import { useFileViewer } from "@edr/ui-common";
|
||||
|
||||
import { fetchViewableFile } from "@/services/files.service";
|
||||
import { api } from "@/services/api";
|
||||
import type {
|
||||
Company,
|
||||
CompanyChangeRequest,
|
||||
CompanyRevision,
|
||||
CompanyRevisionChange,
|
||||
DocumentChangeIntent,
|
||||
LicenseChangeIntent,
|
||||
} from "@/types/customer";
|
||||
import { DiffRow, FIELD_LABELS, currentValue } from "./ChangeRequestReview";
|
||||
import { formatDate, humanize } from "./format";
|
||||
|
||||
interface DocDiff {
|
||||
key: string;
|
||||
label: string;
|
||||
fromFile: { id: string; name: string } | null;
|
||||
toFile: { id: string; name: string } | null;
|
||||
}
|
||||
|
||||
interface FieldDiff {
|
||||
key: string;
|
||||
label: string;
|
||||
from: string;
|
||||
to: string;
|
||||
}
|
||||
|
||||
interface TimelineEntry {
|
||||
id: string;
|
||||
kind: "approved" | "rejected" | "changes_requested" | "revision";
|
||||
at: string;
|
||||
note?: string | null;
|
||||
summary?: string;
|
||||
fieldDiffs: FieldDiff[];
|
||||
docDiffs: DocDiff[];
|
||||
}
|
||||
|
||||
const KIND_BADGE: Record<TimelineEntry["kind"], { label: string; color: string }> = {
|
||||
approved: { label: "Approved", color: "edr-green" },
|
||||
rejected: { label: "Rejected", color: "red" },
|
||||
changes_requested: { label: "Changes requested", color: "yellow" },
|
||||
revision: { label: "Recorded", color: "blue" },
|
||||
};
|
||||
|
||||
/**
|
||||
* Pair adjacent remove-then-add intents into one before/after doc diff — a
|
||||
* "replace" is always staged as `[{op:'remove'}, {op:'add'}]` pushed together
|
||||
* (see `replaceProfileLicenseFile` and friends), and later merges only ever
|
||||
* append after that pair, so adjacency survives. A remove or add with no
|
||||
* adjacent partner stands alone.
|
||||
*/
|
||||
function pairIntents(
|
||||
intents: (LicenseChangeIntent | DocumentChangeIntent)[],
|
||||
labelFor: (intent: LicenseChangeIntent | DocumentChangeIntent) => string,
|
||||
): DocDiff[] {
|
||||
const diffs: DocDiff[] = [];
|
||||
let i = 0;
|
||||
while (i < intents.length) {
|
||||
const current = intents[i];
|
||||
const next = intents[i + 1];
|
||||
if (current.op === "remove" && next?.op === "add") {
|
||||
diffs.push({
|
||||
key: `${current.fileId}-${next.fileId}`,
|
||||
label: labelFor(next),
|
||||
fromFile: { id: current.fileId, name: current.fileName ?? "Document" },
|
||||
toFile: { id: next.fileId, name: next.fileName ?? "Document" },
|
||||
});
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
diffs.push({
|
||||
key: `${current.fileId}-${i}`,
|
||||
label: labelFor(current),
|
||||
fromFile:
|
||||
current.op === "remove"
|
||||
? { id: current.fileId, name: current.fileName ?? "Document" }
|
||||
: null,
|
||||
toFile:
|
||||
current.op === "add"
|
||||
? { id: current.fileId, name: current.fileName ?? "Document" }
|
||||
: null,
|
||||
});
|
||||
i += 1;
|
||||
}
|
||||
return diffs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Historical field diffs on a change request only ever recorded the proposed
|
||||
* ("to") value — there is no stored "before" snapshot — so `from` reads the
|
||||
* CURRENT company value. That's exact for the most recent entry; for an older
|
||||
* one it can drift if the field changed again since. A real limitation of the
|
||||
* data model, not something this view can reconstruct.
|
||||
*/
|
||||
function fromChangeRequest(
|
||||
r: CompanyChangeRequest,
|
||||
company: Company,
|
||||
): TimelineEntry {
|
||||
const proposedKeys = Object.keys(r.snapshot ?? {}).filter(
|
||||
(k) => k !== "faydaIdentity",
|
||||
);
|
||||
const fieldDiffs: FieldDiff[] = proposedKeys.map((key) => ({
|
||||
key,
|
||||
label: FIELD_LABELS[key] ?? humanize(key),
|
||||
from: currentValue(company, key),
|
||||
to:
|
||||
r.snapshot[key] === null || r.snapshot[key] === undefined || r.snapshot[key] === ""
|
||||
? "—"
|
||||
: String(r.snapshot[key]),
|
||||
}));
|
||||
|
||||
const docDiffs: DocDiff[] = [
|
||||
...pairIntents(r.licenseChanges, () => "Business license"),
|
||||
...pairIntents(r.documentChanges, (c) =>
|
||||
humanize((c as DocumentChangeIntent).code),
|
||||
),
|
||||
...r.documentFileIds.map((fileId, i) => ({
|
||||
key: fileId,
|
||||
label: "Document",
|
||||
fromFile: null,
|
||||
toFile: { id: fileId, name: `Document ${i + 1}` },
|
||||
})),
|
||||
];
|
||||
|
||||
return {
|
||||
id: r.id,
|
||||
kind: r.status as TimelineEntry["kind"],
|
||||
at: r.reviewedAt ?? r.updatedAt,
|
||||
note: r.note,
|
||||
fieldDiffs,
|
||||
docDiffs,
|
||||
};
|
||||
}
|
||||
|
||||
function fromRevision(rev: CompanyRevision): TimelineEntry {
|
||||
const isDocChange = (c: CompanyRevisionChange) => c.field.startsWith("document:");
|
||||
const fieldDiffs: FieldDiff[] = rev.changes
|
||||
.filter((c) => !isDocChange(c))
|
||||
.map((c) => ({ key: c.field, label: c.label, from: c.from ?? "—", to: c.to ?? "—" }));
|
||||
const docDiffs: DocDiff[] = rev.changes
|
||||
.filter(isDocChange)
|
||||
.map((c) => ({
|
||||
key: c.field,
|
||||
label: c.label,
|
||||
fromFile: c.fromFileId ? { id: c.fromFileId, name: c.from ?? "Document" } : null,
|
||||
toFile: c.toFileId ? { id: c.toFileId, name: c.to ?? "Document" } : null,
|
||||
}));
|
||||
|
||||
return {
|
||||
id: rev.id,
|
||||
kind: "revision",
|
||||
at: rev.createdAt,
|
||||
summary: rev.summary,
|
||||
fieldDiffs,
|
||||
docDiffs,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* One combined, chronological timeline of everything that's happened to a
|
||||
* company's record: onboarding-phase edits (no approval gate, from
|
||||
* `CompanyRevision`) and post-approval settings changes (reviewed via
|
||||
* `CompanyChangeRequest`) used to live in two separate, differently-shaped
|
||||
* lists — merged here into one sorted feed so "what changed and when" has a
|
||||
* single answer instead of two places to check.
|
||||
*/
|
||||
export function CompanyTimeline({ company }: { company: Company }) {
|
||||
const { view, viewer } = useFileViewer();
|
||||
const changeRequestsQuery = useQuery(
|
||||
api.customers.changeRequests.queryOptions({ input: { id: company.id } }),
|
||||
);
|
||||
const revisionsQuery = useQuery(
|
||||
api.customers.revisions.queryOptions({ input: { id: company.id } }),
|
||||
);
|
||||
|
||||
const entries: TimelineEntry[] = [
|
||||
...(changeRequestsQuery.data ?? [])
|
||||
.filter((r) => r.status !== "pending")
|
||||
.map((r) => fromChangeRequest(r, company)),
|
||||
...(revisionsQuery.data ?? []).map(fromRevision),
|
||||
].sort((a, b) => new Date(b.at).getTime() - new Date(a.at).getTime());
|
||||
|
||||
const openFile = (file: { id: string; name: string }) =>
|
||||
void fetchViewableFile(file.id, file.name).then(view);
|
||||
|
||||
if (entries.length === 0) {
|
||||
return (
|
||||
<Card withBorder>
|
||||
<Stack align="center" gap={6} py="xl">
|
||||
<History size={24} className="text-edr-muted" />
|
||||
<Text size="sm" c="dimmed">
|
||||
No changes recorded yet.
|
||||
</Text>
|
||||
</Stack>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack gap="md">
|
||||
{entries.map((entry) => {
|
||||
const badge = KIND_BADGE[entry.kind];
|
||||
return (
|
||||
<Card key={entry.id} withBorder>
|
||||
<Stack gap="sm">
|
||||
<Group justify="space-between" wrap="nowrap" align="flex-start">
|
||||
<Group gap="sm">
|
||||
<Badge color={badge.color} variant="light" radius="md">
|
||||
{badge.label}
|
||||
</Badge>
|
||||
{entry.summary && (
|
||||
<Text size="sm" c="edr-text" tt="capitalize">
|
||||
{entry.summary}
|
||||
</Text>
|
||||
)}
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed">
|
||||
{formatDate(entry.at)}
|
||||
</Text>
|
||||
</Group>
|
||||
|
||||
{entry.note && (
|
||||
<Alert color="yellow" variant="light">
|
||||
<Text size="sm">
|
||||
<strong>Note:</strong> {entry.note}
|
||||
</Text>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{entry.fieldDiffs.length > 0 && (
|
||||
<SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="lg">
|
||||
{entry.fieldDiffs.map((f) => (
|
||||
<DiffRow key={f.key} label={f.label} from={f.from} to={f.to} />
|
||||
))}
|
||||
</SimpleGrid>
|
||||
)}
|
||||
|
||||
{entry.docDiffs.length > 0 && (
|
||||
<Stack gap={8}>
|
||||
{entry.docDiffs.map((d) => (
|
||||
<Group key={d.key} gap={8} wrap="nowrap">
|
||||
<Text size="xs" fw={600} c="edr-muted" tt="uppercase">
|
||||
{d.label}
|
||||
</Text>
|
||||
{d.fromFile && (
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<FileX2 size={14} className="text-edr-muted" />
|
||||
<Anchor
|
||||
component="button"
|
||||
type="button"
|
||||
size="sm"
|
||||
td="line-through"
|
||||
onClick={() => openFile(d.fromFile!)}
|
||||
>
|
||||
{d.fromFile.name}
|
||||
</Anchor>
|
||||
</Group>
|
||||
)}
|
||||
{d.fromFile && d.toFile && (
|
||||
<Text size="sm" c="edr-muted">
|
||||
→
|
||||
</Text>
|
||||
)}
|
||||
{d.toFile && (
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<FilePlus2 size={14} className="text-edr-muted" />
|
||||
<Anchor
|
||||
component="button"
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={() => openFile(d.toFile!)}
|
||||
>
|
||||
{d.toFile.name}
|
||||
</Anchor>
|
||||
</Group>
|
||||
)}
|
||||
</Group>
|
||||
))}
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
{entry.fieldDiffs.length === 0 && entry.docDiffs.length === 0 && (
|
||||
<Text size="sm" c="dimmed">
|
||||
No details recorded for this entry.
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
{viewer}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -13,6 +13,7 @@ export {
|
||||
ChangeRequestReview,
|
||||
ChangeRequestPendingBadge,
|
||||
} from "./ChangeRequestReview";
|
||||
export { CompanyTimeline } from "./CompanyTimeline";
|
||||
export {
|
||||
RequestDocumentChangeModal,
|
||||
type RequestDocumentChangeModalProps,
|
||||
|
||||
@@ -4,7 +4,9 @@ import {
|
||||
WAREHOUSE_ZONE_TYPES,
|
||||
WAREHOUSE_STATUSES,
|
||||
INVENTORY_STATUSES,
|
||||
type ImportUnloadedItem,
|
||||
type Warehouse,
|
||||
type WarehouseInventoryItem,
|
||||
type WarehouseYard,
|
||||
} from '@/types/warehouse';
|
||||
|
||||
@@ -120,6 +122,44 @@ export const extractErrorMessage = (error: unknown, fallback = 'Something went w
|
||||
return Array.isArray(rawMessage) ? rawMessage.join(', ') : rawMessage ? String(rawMessage) : fallback;
|
||||
};
|
||||
|
||||
/**
|
||||
* An unloaded-queue row seen as the inventory item `ReleaseOrderModal` expects.
|
||||
* Both truck-arrival openers (last mile, import trucks) work off queue rows.
|
||||
*/
|
||||
export const toReleaseInventoryItem = (row: ImportUnloadedItem): WarehouseInventoryItem =>
|
||||
({
|
||||
id: row.id,
|
||||
bookingId: row.bookingId,
|
||||
quantity: 1,
|
||||
weight: Number(row.weight) || 0,
|
||||
grnNumber: row.grnNumber,
|
||||
status: row.currentStatus,
|
||||
arrivedAt: row.arrivalTime,
|
||||
unloadedAt: row.arrivalTime,
|
||||
inspectionStatus: row.inspectionStatus,
|
||||
releaseDate: row.releaseDate,
|
||||
releaseOrderReference: row.releaseOrderReference,
|
||||
handoverDocumentReference: row.handoverDocumentReference,
|
||||
handoverDocumentDate: row.handoverDocumentDate,
|
||||
deliveredAt: row.deliveredAt,
|
||||
// Carries the saved [Exit Inspection] block so truck-leaving prefills the
|
||||
// details captured at arrival (plate, driver, tare, gate-in).
|
||||
notes: row.notes,
|
||||
booking: row.bookingId
|
||||
? {
|
||||
id: row.bookingId,
|
||||
reference: row.bookingReference ?? row.bookingId,
|
||||
tradeDirection: 'IMPORT',
|
||||
lastMileDeliveryAddress: row.lastMileRequested ? row.pickupOption : null,
|
||||
customerTruckPlateNumber: row.customerTruckPlateNumber,
|
||||
customerTruckDriverName: row.customerTruckDriverName,
|
||||
customerTruckType: row.customerTruckType,
|
||||
customerTruckContainerNumber: row.customerTruckContainerNumber,
|
||||
customerTruckAssignedAt: row.customerTruckAssignedAt,
|
||||
}
|
||||
: null,
|
||||
}) as unknown as WarehouseInventoryItem;
|
||||
|
||||
/**
|
||||
* Error extractor for blob-download requests. When `responseType: 'blob'`, axios
|
||||
* delivers the JSON error body as a Blob, so `extractErrorMessage` can't read
|
||||
|
||||
@@ -42,6 +42,8 @@ export const QUERY_KEYS = {
|
||||
["customers", "detail", id, "reset-target"] as const,
|
||||
changeRequests: (id: string) =>
|
||||
["customers", "detail", id, "change-requests"] as const,
|
||||
revisions: (id: string) =>
|
||||
["customers", "detail", id, "revisions"] as const,
|
||||
},
|
||||
|
||||
INVOICES: {
|
||||
|
||||
@@ -78,10 +78,13 @@ export const URL_CONSTANTS = {
|
||||
`/companies/company-profiles/${profileId}/status`,
|
||||
CHANGE_REQUESTS: (companyId: string) =>
|
||||
`/companies/${companyId}/change-requests`,
|
||||
REVISIONS: (companyId: string) => `/companies/${companyId}/revisions`,
|
||||
CHANGE_REQUEST_APPROVE: (id: string) =>
|
||||
`/companies/change-requests/${id}/approve`,
|
||||
CHANGE_REQUEST_REJECT: (id: string) =>
|
||||
`/companies/change-requests/${id}/reject`,
|
||||
CHANGE_REQUEST_REQUEST_CHANGES: (id: string) =>
|
||||
`/companies/change-requests/${id}/request-changes`,
|
||||
DOCUMENT_REQUEST_CHANGE: (fileId: string) =>
|
||||
`/companies/documents/${fileId}/request-change`,
|
||||
BOOKINGS_CUSTOMER_VIEW: (id: string) =>
|
||||
@@ -132,6 +135,8 @@ export const URL_CONSTANTS = {
|
||||
CONTRACT_DOCUMENT: (id: string) => `/bookings/${id}/contract/document`,
|
||||
CONTRACT_SIGN: (id: string) => `/bookings/${id}/contract/sign`,
|
||||
CONTRACT_DOWNLOAD: (id: string) => `/bookings/${id}/contract`,
|
||||
CARRIAGE_ACCEPTANCE_SHEET: (id: string) =>
|
||||
`/bookings/${id}/carriage-acceptance-sheet`,
|
||||
SUMMARY: (id: string) => `/bookings/${id}/summary`,
|
||||
CUSTOMER_SIGN: (id: string) => `/bookings/${id}/customer/sign`,
|
||||
MARKETING_APPROVE: (id: string) => `/bookings/${id}/marketing/approve`,
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
|
||||
import toast from "react-hot-toast";
|
||||
import {
|
||||
ArrowLeft,
|
||||
FileSignature,
|
||||
FileText,
|
||||
FolderOpen,
|
||||
Layers,
|
||||
LayoutGrid,
|
||||
@@ -50,6 +52,7 @@ import {
|
||||
useBookingMutations,
|
||||
} from "@/hooks/bookings/useBookings";
|
||||
import { useScrollToHash } from "@/hooks/useScrollToHash";
|
||||
import { bookingsService } from "@/services/bookings.service";
|
||||
|
||||
export default function BookingRequestDetailPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
@@ -269,6 +272,33 @@ export default function BookingRequestDetailPage() {
|
||||
View / sign contract
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
fullWidth
|
||||
variant="default"
|
||||
leftSection={<FileText size={16} />}
|
||||
onClick={async () => {
|
||||
try {
|
||||
const blob =
|
||||
await bookingsService.downloadCarriageAcceptanceSheet(
|
||||
booking.id,
|
||||
);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `carriage-acceptance-${booking.reference}.pdf`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Carriage acceptance sheet is not available yet",
|
||||
);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Carriage acceptance sheet
|
||||
</Button>
|
||||
{booking.customsClearingEnabled && (
|
||||
<Button
|
||||
fullWidth
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
Download,
|
||||
Eye,
|
||||
FileText,
|
||||
History,
|
||||
Hourglass,
|
||||
IdCard,
|
||||
LayoutGrid,
|
||||
@@ -40,6 +41,7 @@ import {
|
||||
ChangeRequestPendingBadge,
|
||||
ChangeRequestReview,
|
||||
CompanyStatusBadge,
|
||||
CompanyTimeline,
|
||||
CompanyTypeBadge,
|
||||
InvoiceStatusBadge,
|
||||
PaymentStatusBadge,
|
||||
@@ -64,6 +66,7 @@ import {
|
||||
} from "@/services/files.service";
|
||||
import { api } from "@/services/api";
|
||||
import type {
|
||||
Company,
|
||||
CompanyProfile,
|
||||
CustomerBooking,
|
||||
CustomerDocument,
|
||||
@@ -78,6 +81,32 @@ import {
|
||||
type ColumnDef,
|
||||
} from "@edr/ui-common";
|
||||
|
||||
/** Plain-text summary of the company's eTrade-sourced record, downloaded client-side (eTrade returns data, not a document). */
|
||||
function downloadTinRecord(company: Company) {
|
||||
const lines = [
|
||||
`TIN: ${company.tin}`,
|
||||
`Company name: ${company.name}`,
|
||||
`Licence number: ${company.licenceNumber ?? ""}`,
|
||||
`Status: ${company.statusDescription ?? ""}`,
|
||||
`Date registered: ${company.dateRegistered ?? ""}`,
|
||||
`Renewed from: ${company.renewedFrom ?? ""}`,
|
||||
`Renewal date: ${company.renewalDate ?? ""}`,
|
||||
`Renewed to: ${company.renewedTo ?? ""}`,
|
||||
`Address: ${[company.region, company.zone, company.woreda, company.kebele, company.houseNo].filter(Boolean).join(", ")}`,
|
||||
];
|
||||
const blob = new Blob([lines.join("\n")], {
|
||||
type: "text/plain;charset=utf-8",
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `tin-${company.tin}.txt`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
}
|
||||
|
||||
function InfoField({ label, value }: { label: string; value?: string | null }) {
|
||||
return (
|
||||
<Stack gap={2}>
|
||||
@@ -689,6 +718,9 @@ export default function CustomerDetailPage() {
|
||||
<Tabs.Tab value="invoices" leftSection={<Receipt size={16} />}>
|
||||
Invoices
|
||||
</Tabs.Tab>
|
||||
<Tabs.Tab value="history" leftSection={<History size={16} />}>
|
||||
History
|
||||
</Tabs.Tab>
|
||||
</Tabs.List>
|
||||
|
||||
{/* OVERVIEW */}
|
||||
@@ -757,6 +789,18 @@ export default function CustomerDetailPage() {
|
||||
<InfoField label="TIN" value={company.tin} />
|
||||
<InfoField label="VAT number" value={company.vatNumber} />
|
||||
<InfoField label="FAN number" value={company.fanNumber} />
|
||||
<InfoField
|
||||
label="Submitted on"
|
||||
value={formatDate(company.createdAt)}
|
||||
/>
|
||||
<InfoField
|
||||
label="Approved on"
|
||||
value={
|
||||
company.approvedAt
|
||||
? formatDate(company.approvedAt)
|
||||
: "Not yet approved"
|
||||
}
|
||||
/>
|
||||
<InfoField
|
||||
label="Owner identity"
|
||||
value={
|
||||
@@ -800,18 +844,29 @@ export default function CustomerDetailPage() {
|
||||
|
||||
<Card>
|
||||
<Stack gap="lg">
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Text fw={600} c="edr-text">
|
||||
eTrade registration
|
||||
</Text>
|
||||
{hasEtradeRecord ? (
|
||||
<Badge size="sm" color="edr-green" variant="light">
|
||||
Verified with eTrade
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge size="sm" color="gray" variant="light">
|
||||
No eTrade record
|
||||
</Badge>
|
||||
<Group gap="xs" wrap="nowrap" justify="space-between">
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Text fw={600} c="edr-text">
|
||||
eTrade registration
|
||||
</Text>
|
||||
{hasEtradeRecord ? (
|
||||
<Badge size="sm" color="edr-green" variant="light">
|
||||
Verified with eTrade
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge size="sm" color="gray" variant="light">
|
||||
No eTrade record
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
{hasEtradeRecord && (
|
||||
<ActionIcon
|
||||
variant="default"
|
||||
aria-label="Download TIN record"
|
||||
onClick={() => downloadTinRecord(company)}
|
||||
>
|
||||
<Download size={16} />
|
||||
</ActionIcon>
|
||||
)}
|
||||
</Group>
|
||||
{hasEtradeRecord ? (
|
||||
@@ -1235,6 +1290,11 @@ export default function CustomerDetailPage() {
|
||||
</Box>
|
||||
</Box>
|
||||
</Tabs.Panel>
|
||||
|
||||
{/* HISTORY */}
|
||||
<Tabs.Panel value="history" pt="lg">
|
||||
<CompanyTimeline company={company} />
|
||||
</Tabs.Panel>
|
||||
</Tabs>
|
||||
|
||||
<RequestDocumentChangeModal
|
||||
|
||||
@@ -245,6 +245,16 @@ export default function CustomersPage() {
|
||||
</Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "approved",
|
||||
header: "Approved",
|
||||
meta: { headerClassName: "text-right", cellClassName: "text-right" },
|
||||
cell: ({ row }) => (
|
||||
<Text size="sm" c="dimmed">
|
||||
{row.original.approvedAt ? formatDate(row.original.approvedAt) : "—"}
|
||||
</Text>
|
||||
),
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
@@ -141,6 +141,7 @@ export const vehiclesConfig: FleetResourceConfig = {
|
||||
required: true,
|
||||
description: "Pre-filled from the truck type — override only for a one-off",
|
||||
},
|
||||
{ name: "pricePerKm", label: "Price per KM (ETB)", type: "number", description: "Haulage rate charged per kilometre" },
|
||||
{ name: "status", label: "Status", type: "select", required: true, options: VEHICLE_STATUS_OPTIONS },
|
||||
{ name: "availability", label: "Availability", type: "select", required: true, options: VEHICLE_AVAILABILITY_OPTIONS },
|
||||
{ name: "description", label: "Description", type: "textarea" },
|
||||
@@ -157,6 +158,7 @@ export const vehiclesConfig: FleetResourceConfig = {
|
||||
year: new Date().getFullYear(),
|
||||
fuelType: "DIESEL",
|
||||
capacity: 0,
|
||||
pricePerKm: 0,
|
||||
status: "ACTIVE",
|
||||
availability: "FREE",
|
||||
description: "",
|
||||
|
||||
@@ -57,6 +57,7 @@ import {
|
||||
import { vehiclesService } from "@/services/vehicles.service";
|
||||
import { driversService, type Driver } from "@/services/drivers.service";
|
||||
import { ReleaseOrderModal, type ReleaseOrderTruckPrefill } from "@/components/warehouses/ReleaseOrderModal";
|
||||
import { toReleaseInventoryItem } from "@/components/warehouses/options";
|
||||
import { EdrTruckExitPapersModal } from "./EdrTruckExitPapersModal";
|
||||
import { TruckDetentionModal } from "@/components/operations/TruckDetentionModal";
|
||||
import { ProofOfDeliveryModal } from "@/components/operations/ProofOfDeliveryModal";
|
||||
@@ -299,40 +300,6 @@ const requestedDate = (r: LastMileRecord) => {
|
||||
const serviceTypeName = (r: LastMileRecord) =>
|
||||
r.booking?.serviceType?.label ?? r.booking?.serviceType?.name ?? "—";
|
||||
|
||||
const toReleaseInventoryItem = (row: ImportUnloadedItem): WarehouseInventoryItem =>
|
||||
({
|
||||
id: row.id,
|
||||
bookingId: row.bookingId,
|
||||
quantity: 1,
|
||||
weight: Number(row.weight) || 0,
|
||||
grnNumber: row.grnNumber,
|
||||
status: row.currentStatus,
|
||||
arrivedAt: row.arrivalTime,
|
||||
unloadedAt: row.arrivalTime,
|
||||
inspectionStatus: row.inspectionStatus,
|
||||
releaseDate: row.releaseDate,
|
||||
releaseOrderReference: row.releaseOrderReference,
|
||||
handoverDocumentReference: row.handoverDocumentReference,
|
||||
handoverDocumentDate: row.handoverDocumentDate,
|
||||
deliveredAt: row.deliveredAt,
|
||||
// Carries the saved [Exit Inspection] block so truck-leaving prefills the
|
||||
// details captured at arrival (plate, driver, tare, gate-in).
|
||||
notes: row.notes,
|
||||
booking: row.bookingId
|
||||
? {
|
||||
id: row.bookingId,
|
||||
reference: row.bookingReference ?? row.bookingId,
|
||||
tradeDirection: "IMPORT",
|
||||
lastMileDeliveryAddress: row.lastMileRequested ? row.pickupOption : null,
|
||||
customerTruckPlateNumber: row.customerTruckPlateNumber,
|
||||
customerTruckDriverName: row.customerTruckDriverName,
|
||||
customerTruckType: row.customerTruckType,
|
||||
customerTruckContainerNumber: row.customerTruckContainerNumber,
|
||||
customerTruckAssignedAt: row.customerTruckAssignedAt,
|
||||
}
|
||||
: null,
|
||||
}) as unknown as WarehouseInventoryItem;
|
||||
|
||||
const releasePrefillFromLastMile = (
|
||||
record: LastMileRecord,
|
||||
row?: ImportUnloadedItem | null,
|
||||
|
||||
@@ -68,6 +68,7 @@ const METHOD_OPTIONS: { value: PaymentMethod; label: string }[] = [
|
||||
{ value: "card", label: "Card" },
|
||||
{ value: "dmoney", label: "D-Money" },
|
||||
{ value: "cac-bank", label: "CAC Bank" },
|
||||
{ value: "cbe-bill", label: "CBE Bill" },
|
||||
];
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
|
||||
@@ -0,0 +1,741 @@
|
||||
import { Fragment, useMemo, useState, useEffect } from "react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
ActionIcon,
|
||||
Alert,
|
||||
Badge,
|
||||
Button,
|
||||
Group,
|
||||
Loader,
|
||||
Modal,
|
||||
SegmentedControl,
|
||||
Stack,
|
||||
Table,
|
||||
Text,
|
||||
TextInput,
|
||||
Textarea,
|
||||
Select,
|
||||
Checkbox,
|
||||
} from "@mantine/core";
|
||||
import { ChevronDown, ChevronRight } from "lucide-react";
|
||||
|
||||
import { PageContainer, PageHeader } from "@/components/page";
|
||||
import RuleEngineListFooter from "@/components/ruleEngine/RuleEngineListFooter";
|
||||
import { useListControls } from "@/hooks/useListControls";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { useWarehouseYards, useWarehouseZones } from "@/hooks/useWarehouses";
|
||||
import { api } from "@/services/api";
|
||||
import { warehouseService } from "@/services/warehouse.service";
|
||||
import { importOperationsService } from "@/services/importOperations.service";
|
||||
|
||||
type ReturnType = "all" | "edr" | "customer";
|
||||
|
||||
interface ContainerReturnRow {
|
||||
key: string;
|
||||
containerNumber: string;
|
||||
size: string | null;
|
||||
type: string | null;
|
||||
bookingRef: string;
|
||||
bookingId: string;
|
||||
customerId: string | null;
|
||||
companyName: string | null;
|
||||
returnType: "EDR" | "CUSTOMER";
|
||||
plate: string | null;
|
||||
isReturn: boolean;
|
||||
}
|
||||
|
||||
interface BookingReturnGroup {
|
||||
bookingId: string;
|
||||
bookingRef: string;
|
||||
companyName: string | null;
|
||||
customerId: string | null;
|
||||
returnType: "EDR" | "CUSTOMER";
|
||||
containers: ContainerReturnRow[];
|
||||
}
|
||||
|
||||
export default function ContainerReturnsPage() {
|
||||
const { toast } = useToast();
|
||||
const qc = useQueryClient();
|
||||
const [expanded, setExpanded] = useState<string | null>(null);
|
||||
const [filterType, setFilterType] = useState<ReturnType>("all");
|
||||
const [returnModalOpen, setReturnModalOpen] = useState(false);
|
||||
const [standaloneModalOpen, setStandaloneModalOpen] = useState(false);
|
||||
const [activeKey, setActiveKey] = useState<string | null>(null);
|
||||
|
||||
const { data: unloadedQueue = [], isLoading: queueLoading } = useQuery({
|
||||
queryKey: ["import-unloaded-queue"],
|
||||
queryFn: async () => {
|
||||
const response = await api.warehouses.importUnloadedQueue.call();
|
||||
return response ?? [];
|
||||
},
|
||||
});
|
||||
|
||||
const { data: returnedContainers = [] } = useQuery({
|
||||
queryKey: ["empty-container-returns"],
|
||||
queryFn: async () => {
|
||||
return await importOperationsService.listEmptyReturns().catch(() => []);
|
||||
},
|
||||
});
|
||||
|
||||
const bookingIds = unloadedQueue.map((item) => item.bookingId).filter(Boolean) as string[];
|
||||
const containerReturnsQuery = useQuery({
|
||||
queryKey: ["container-returns", bookingIds],
|
||||
queryFn: async () => {
|
||||
const groups = new Map<string, BookingReturnGroup>();
|
||||
|
||||
for (const item of unloadedQueue) {
|
||||
if (!item.bookingId) continue;
|
||||
|
||||
// EDR last-mile returns: same EDR truck that delivered will return with empty containers
|
||||
const edrTrucks = await warehouseService.getLastMileTrucks(item.bookingId).catch(() => []);
|
||||
if (edrTrucks.length > 0) {
|
||||
const inventory = await api.warehouses.listInventory
|
||||
.call({ filter: { bookingId: item.bookingId } })
|
||||
.catch(() => []);
|
||||
|
||||
const returnContainers: ContainerReturnRow[] = inventory
|
||||
.filter((inv: any) => inv.isReturn)
|
||||
.map((inv: any) => ({
|
||||
key: inv.id,
|
||||
containerNumber: inv.containerNumber || "—",
|
||||
size: inv.containerSize || null,
|
||||
type: inv.containerType || null,
|
||||
bookingRef: (item.bookingReference ?? item.bookingId) || "",
|
||||
bookingId: item.bookingId || "",
|
||||
customerId: item.customerId || null,
|
||||
companyName: item.customerName ?? null,
|
||||
returnType: "EDR" as const,
|
||||
plate: edrTrucks[0]?.truckPlateNumber || null,
|
||||
isReturn: true,
|
||||
}));
|
||||
|
||||
if (returnContainers.length > 0) {
|
||||
const key = `edr-${item.bookingId}`;
|
||||
groups.set(key, {
|
||||
bookingId: item.bookingId,
|
||||
bookingRef: item.bookingReference ?? item.bookingId,
|
||||
companyName: item.customerName ?? null,
|
||||
customerId: item.customerId || null,
|
||||
returnType: "EDR",
|
||||
containers: returnContainers,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Customer self-haul last-mile returns: same customer truck that delivered will return with empty containers
|
||||
const customerTrucks = await warehouseService.getCustomerTrucks(item.bookingId).catch(() => []);
|
||||
if (customerTrucks.length > 0) {
|
||||
const inventory = await api.warehouses.listInventory
|
||||
.call({ filter: { bookingId: item.bookingId } })
|
||||
.catch(() => []);
|
||||
|
||||
const returnContainers: ContainerReturnRow[] = inventory
|
||||
.filter((inv: any) => inv.isReturn)
|
||||
.map((inv: any) => ({
|
||||
key: inv.id,
|
||||
containerNumber: inv.containerNumber || "—",
|
||||
size: inv.containerSize || null,
|
||||
type: inv.containerType || null,
|
||||
bookingRef: (item.bookingReference ?? item.bookingId) || "",
|
||||
bookingId: item.bookingId || "",
|
||||
customerId: item.customerId || null,
|
||||
companyName: item.customerName ?? null,
|
||||
returnType: "CUSTOMER" as const,
|
||||
plate: customerTrucks[0]?.plateNumber || null,
|
||||
isReturn: true,
|
||||
}));
|
||||
|
||||
if (returnContainers.length > 0) {
|
||||
const key = `customer-${item.bookingId}`;
|
||||
groups.set(key, {
|
||||
bookingId: item.bookingId,
|
||||
bookingRef: item.bookingReference ?? item.bookingId,
|
||||
companyName: item.customerName ?? null,
|
||||
customerId: item.customerId || null,
|
||||
returnType: "CUSTOMER",
|
||||
containers: returnContainers,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(groups.values());
|
||||
},
|
||||
enabled: bookingIds.length > 0 && !queueLoading,
|
||||
});
|
||||
|
||||
const allGroups = useMemo(() => containerReturnsQuery.data ?? [], [containerReturnsQuery.data]);
|
||||
const filteredGroups = useMemo(() => {
|
||||
if (filterType === "all") return allGroups;
|
||||
if (filterType === "edr") return allGroups.filter((g) => g.returnType === "EDR");
|
||||
if (filterType === "customer") return allGroups.filter((g) => g.returnType === "CUSTOMER");
|
||||
return allGroups;
|
||||
}, [allGroups, filterType]);
|
||||
|
||||
const controls = useListControls(filteredGroups, {
|
||||
searchKeys: ["bookingRef", "companyName"],
|
||||
});
|
||||
|
||||
const createReturnsMutation = useMutation({
|
||||
mutationFn: async (payload: {
|
||||
trucks: Array<{
|
||||
bookingId: string;
|
||||
customerId: string | null;
|
||||
returnType: "EDR" | "CUSTOMER";
|
||||
containers: Array<{
|
||||
containerNumber: string;
|
||||
returnDate: string;
|
||||
warehouse: string;
|
||||
condition?: string;
|
||||
handoverNote?: string;
|
||||
}>;
|
||||
}>;
|
||||
}) => {
|
||||
const results = [];
|
||||
for (const truck of payload.trucks) {
|
||||
for (const container of truck.containers) {
|
||||
const result = await importOperationsService.createEmptyReturn({
|
||||
containerNumber: container.containerNumber,
|
||||
returnDate: new Date(container.returnDate).toISOString(),
|
||||
bookingId: truck.bookingId,
|
||||
customerId: truck.customerId ?? undefined,
|
||||
facility: container.warehouse,
|
||||
condition: container.condition,
|
||||
handoverNote: container.handoverNote,
|
||||
});
|
||||
results.push(result);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast({ title: "Container returns recorded" });
|
||||
qc.invalidateQueries({ queryKey: ["container-returns", bookingIds] });
|
||||
setReturnModalOpen(false);
|
||||
setActiveKey(null);
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Failed to record returns",
|
||||
description: error?.response?.data?.message || error?.message,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const activeGroup = activeKey ? (filteredGroups.find((g) => `${g.returnType.toLowerCase()}-${g.bookingId}` === activeKey) ?? null) : null;
|
||||
|
||||
if (queueLoading || containerReturnsQuery.isLoading) {
|
||||
return (
|
||||
<PageContainer>
|
||||
<Group justify="center" py="lg">
|
||||
<Loader size="sm" />
|
||||
</Group>
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<PageContainer>
|
||||
<PageHeader
|
||||
title="Container Returns"
|
||||
subtitle="Empty containers returned by last-mile trucks (EDR or customer self-haul)"
|
||||
/>
|
||||
|
||||
<Group mb="lg" justify="space-between">
|
||||
<SegmentedControl
|
||||
value={filterType}
|
||||
onChange={(val) => setFilterType(val as ReturnType)}
|
||||
data={[
|
||||
{ label: "All", value: "all" },
|
||||
{ label: "EDR Last Mile", value: "edr" },
|
||||
{ label: "Customer Self-Haul", value: "customer" },
|
||||
]}
|
||||
/>
|
||||
<Button onClick={() => setStandaloneModalOpen(true)}>
|
||||
Record Return
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
{returnedContainers.length > 0 && (
|
||||
<>
|
||||
<Text fw={600} mb="xs">Returned Containers</Text>
|
||||
<Table.ScrollContainer minWidth={1000} mb="lg">
|
||||
<Table striped highlightOnHover verticalSpacing="xs">
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th>Container Number</Table.Th>
|
||||
<Table.Th>Booking Ref</Table.Th>
|
||||
<Table.Th>Returned Date</Table.Th>
|
||||
<Table.Th>Facility</Table.Th>
|
||||
<Table.Th>Yard</Table.Th>
|
||||
<Table.Th>Condition</Table.Th>
|
||||
<Table.Th>Status</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{returnedContainers.map((ret: any) => (
|
||||
<Table.Tr key={ret.id}>
|
||||
<Table.Td>{ret.containerNumber}</Table.Td>
|
||||
<Table.Td>{ret.bookingId ? "Associated" : "—"}</Table.Td>
|
||||
<Table.Td>{ret.returnDate ? new Date(ret.returnDate).toLocaleDateString() : "—"}</Table.Td>
|
||||
<Table.Td>{ret.facility || "—"}</Table.Td>
|
||||
<Table.Td>{ret.yard || "—"}</Table.Td>
|
||||
<Table.Td>{ret.condition || "—"}</Table.Td>
|
||||
<Table.Td>
|
||||
<Badge size="sm">{ret.status}</Badge>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
))}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</Table.ScrollContainer>
|
||||
</>
|
||||
)}
|
||||
|
||||
{filteredGroups.length === 0 ? (
|
||||
<Alert color="gray">No {filterType !== "all" ? filterType : ""} container returns found.</Alert>
|
||||
) : (
|
||||
<>
|
||||
<Table.ScrollContainer minWidth={1000}>
|
||||
<Table highlightOnHover verticalSpacing="xs">
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th w={40} />
|
||||
<Table.Th>Booking Ref</Table.Th>
|
||||
<Table.Th>Company</Table.Th>
|
||||
<Table.Th>Return Type</Table.Th>
|
||||
<Table.Th>Containers</Table.Th>
|
||||
<Table.Th ta="right">Actions</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{controls.pagedRows.map((group) => {
|
||||
const groupKey = `${group.returnType.toLowerCase()}-${group.bookingId}`;
|
||||
const isOpen = expanded === groupKey;
|
||||
return (
|
||||
<Fragment key={groupKey}>
|
||||
<Table.Tr>
|
||||
<Table.Td>
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
color="gray"
|
||||
onClick={() => setExpanded(isOpen ? null : groupKey)}
|
||||
>
|
||||
{isOpen ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
|
||||
</ActionIcon>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text fw={600}>{group.bookingRef}</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>{group.companyName ?? "—"}</Table.Td>
|
||||
<Table.Td>
|
||||
<Badge color={group.returnType === "EDR" ? "edr-green" : "blue"}>
|
||||
{group.returnType === "EDR" ? "EDR Last Mile" : "Customer Self-Haul"}
|
||||
</Badge>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Badge>{group.containers.length} container{group.containers.length !== 1 ? "s" : ""}</Badge>
|
||||
</Table.Td>
|
||||
<Table.Td ta="right">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="light"
|
||||
onClick={() => {
|
||||
setActiveKey(groupKey);
|
||||
setReturnModalOpen(true);
|
||||
}}
|
||||
>
|
||||
Record Return
|
||||
</Button>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
{isOpen && (
|
||||
<Table.Tr>
|
||||
<Table.Td colSpan={6}>
|
||||
<Table striped>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th>Container</Table.Th>
|
||||
<Table.Th>Size</Table.Th>
|
||||
<Table.Th>Type</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{group.containers.map((container) => (
|
||||
<Table.Tr key={container.key}>
|
||||
<Table.Td>{container.containerNumber}</Table.Td>
|
||||
<Table.Td>{container.size ?? "—"}</Table.Td>
|
||||
<Table.Td>{container.type ?? "—"}</Table.Td>
|
||||
</Table.Tr>
|
||||
))}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</Table.ScrollContainer>
|
||||
<RuleEngineListFooter
|
||||
pagination={controls.pagination}
|
||||
pageCount={controls.pageCount}
|
||||
totalCount={controls.totalCount}
|
||||
itemLabel="bookings"
|
||||
onPaginationChange={controls.setPagination}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<ContainerReturnModal
|
||||
opened={returnModalOpen}
|
||||
onClose={() => setReturnModalOpen(false)}
|
||||
group={activeGroup}
|
||||
onSubmit={(payload) => createReturnsMutation.mutate(payload)}
|
||||
loading={createReturnsMutation.isPending}
|
||||
/>
|
||||
|
||||
<StandaloneReturnModal
|
||||
opened={standaloneModalOpen}
|
||||
onClose={() => setStandaloneModalOpen(false)}
|
||||
onSubmit={(payload) => createReturnsMutation.mutate(payload)}
|
||||
loading={createReturnsMutation.isPending}
|
||||
/>
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
interface ContainerReturnModalProps {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
group: BookingReturnGroup | null;
|
||||
onSubmit: (payload: any) => void;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
function ContainerReturnModal({ opened, onClose, group, onSubmit, loading }: ContainerReturnModalProps) {
|
||||
const [selectedContainers, setSelectedContainers] = useState<string[]>([]);
|
||||
const [returnDate, setReturnDate] = useState<string>(new Date().toISOString().split("T")[0]);
|
||||
const [warehouse, setWarehouse] = useState<string | null>(null);
|
||||
const [condition, setCondition] = useState<string>("");
|
||||
const [handoverNote, setHandoverNote] = useState<string>("");
|
||||
|
||||
const { data: warehousesResponse } = useQuery({
|
||||
queryKey: ["warehouses-list"],
|
||||
queryFn: async () => {
|
||||
return await warehouseService.list({});
|
||||
},
|
||||
});
|
||||
|
||||
const warehouses = (warehousesResponse as any)?.data ?? warehousesResponse ?? [];
|
||||
const warehouseOptions = Array.isArray(warehouses)
|
||||
? warehouses.map((wh: any) => ({
|
||||
value: wh.id,
|
||||
label: `${wh.name} ${wh.code ? `(${wh.code})` : ""}`,
|
||||
}))
|
||||
: [];
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!group || !selectedContainers.length || !warehouse) return;
|
||||
|
||||
const selectedWarehouse = Array.isArray(warehouses) ? warehouses.find((wh: any) => wh.id === warehouse) : null;
|
||||
|
||||
const containers = group.containers
|
||||
.filter((c) => selectedContainers.includes(c.key))
|
||||
.map((c) => ({
|
||||
containerNumber: c.containerNumber,
|
||||
returnDate,
|
||||
warehouse: selectedWarehouse?.name || warehouse,
|
||||
condition: condition || undefined,
|
||||
handoverNote: handoverNote || undefined,
|
||||
}));
|
||||
|
||||
onSubmit({
|
||||
trucks: [
|
||||
{
|
||||
bookingId: group.bookingId,
|
||||
customerId: group.customerId,
|
||||
returnType: group.returnType,
|
||||
containers,
|
||||
},
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal opened={opened} onClose={onClose} title="Record Container Return" size="lg">
|
||||
{group && (
|
||||
<Stack gap="md">
|
||||
<Group>
|
||||
<Text fw={600}>{group.bookingRef}</Text>
|
||||
<Badge color={group.returnType === "EDR" ? "edr-green" : "blue"}>
|
||||
{group.returnType === "EDR" ? "EDR Last Mile" : "Customer Self-Haul"}
|
||||
</Badge>
|
||||
</Group>
|
||||
|
||||
<div>
|
||||
<Text size="sm" fw={600} mb="xs">
|
||||
Select containers to return:
|
||||
</Text>
|
||||
<Stack gap="xs">
|
||||
{group.containers.map((container) => (
|
||||
<Checkbox
|
||||
key={container.key}
|
||||
label={`${container.containerNumber} (${container.size || "bulk"})`}
|
||||
checked={selectedContainers.includes(container.key)}
|
||||
onChange={(e) => {
|
||||
if (e.currentTarget.checked) {
|
||||
setSelectedContainers([...selectedContainers, container.key]);
|
||||
} else {
|
||||
setSelectedContainers(selectedContainers.filter((c) => c !== container.key));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
</div>
|
||||
|
||||
<Select
|
||||
label="Return Warehouse"
|
||||
placeholder="Select warehouse for container return"
|
||||
value={warehouse}
|
||||
onChange={setWarehouse}
|
||||
data={warehouseOptions}
|
||||
required
|
||||
searchable
|
||||
/>
|
||||
|
||||
<input
|
||||
type="date"
|
||||
value={returnDate}
|
||||
onChange={(e) => setReturnDate(e.target.value)}
|
||||
style={{ padding: "8px", borderRadius: "4px", border: "1px solid #ccc" }}
|
||||
required
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label="Condition"
|
||||
placeholder="Damage, residue, or cleanliness notes"
|
||||
value={condition}
|
||||
onChange={(e) => setCondition(e.currentTarget.value)}
|
||||
rows={3}
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label="Handover Note"
|
||||
placeholder="Consignee, trucker, or authorization notes"
|
||||
value={handoverNote}
|
||||
onChange={(e) => setHandoverNote(e.currentTarget.value)}
|
||||
rows={3}
|
||||
/>
|
||||
|
||||
<Group justify="flex-end" gap="sm">
|
||||
<Button variant="default" onClick={onClose} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={!selectedContainers.length || !warehouse}
|
||||
loading={loading}
|
||||
>
|
||||
Record Return ({selectedContainers.length})
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
interface StandaloneReturnModalProps {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
onSubmit: (payload: any) => void;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
function StandaloneReturnModal({ opened, onClose, onSubmit, loading }: StandaloneReturnModalProps) {
|
||||
const [containerNumber, setContainerNumber] = useState<string>("");
|
||||
const [returnedBy, setReturnedBy] = useState<"EDR" | "CUSTOMER" | null>(null);
|
||||
const [returnDate, setReturnDate] = useState<string>(new Date().toISOString().split("T")[0]);
|
||||
const [warehouse, setWarehouse] = useState<string | null>(null);
|
||||
const [yardId, setYardId] = useState<string | null>(null);
|
||||
const [zoneId, setZoneId] = useState<string | null>(null);
|
||||
const [condition, setCondition] = useState<string>("");
|
||||
const [handoverNote, setHandoverNote] = useState<string>("");
|
||||
|
||||
const { data: warehousesResponse } = useQuery({
|
||||
queryKey: ["warehouses-list"],
|
||||
queryFn: async () => {
|
||||
return await warehouseService.list({});
|
||||
},
|
||||
});
|
||||
|
||||
const warehouses = (warehousesResponse as any)?.data ?? warehousesResponse ?? [];
|
||||
|
||||
const { data: yards } = useWarehouseYards(warehouse ?? undefined);
|
||||
const { data: zones } = useWarehouseZones(yardId ?? undefined);
|
||||
|
||||
useEffect(() => {
|
||||
setYardId(null);
|
||||
setZoneId(null);
|
||||
}, [warehouse]);
|
||||
|
||||
useEffect(() => {
|
||||
setZoneId(null);
|
||||
}, [yardId]);
|
||||
|
||||
const warehouseOptions = Array.isArray(warehouses)
|
||||
? warehouses.map((wh: any) => ({
|
||||
value: wh.id,
|
||||
label: `${wh.name} ${wh.code ? `(${wh.code})` : ""}`,
|
||||
}))
|
||||
: [];
|
||||
|
||||
const yardOptions = (yards ?? [])
|
||||
.filter((y) => y.status === "ACTIVE")
|
||||
.map((y) => ({ value: y.id, label: `${y.name} (${y.code})` }));
|
||||
|
||||
const zoneOptions = (zones ?? [])
|
||||
.filter((z) => z.status === "ACTIVE")
|
||||
.map((z) => ({ value: z.id, label: `${z.name} (${z.code})` }));
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!containerNumber || !warehouse || !returnedBy) return;
|
||||
|
||||
const selectedWarehouse = Array.isArray(warehouses) ? warehouses.find((wh: any) => wh.id === warehouse) : null;
|
||||
const selectedYard = yards?.find((y) => y.id === yardId);
|
||||
const selectedZone = zones?.find((z) => z.id === zoneId);
|
||||
|
||||
onSubmit({
|
||||
trucks: [
|
||||
{
|
||||
bookingId: null,
|
||||
customerId: null,
|
||||
returnType: returnedBy,
|
||||
containers: [
|
||||
{
|
||||
containerNumber,
|
||||
returnDate,
|
||||
warehouse: selectedWarehouse?.name || warehouse,
|
||||
yard: selectedYard?.name,
|
||||
zone: selectedZone?.name,
|
||||
condition: condition || undefined,
|
||||
handoverNote: handoverNote || undefined,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
setContainerNumber("");
|
||||
setReturnedBy(null);
|
||||
setReturnDate(new Date().toISOString().split("T")[0]);
|
||||
setWarehouse(null);
|
||||
setYardId(null);
|
||||
setZoneId(null);
|
||||
setCondition("");
|
||||
setHandoverNote("");
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal opened={opened} onClose={onClose} title="Record Container Return (Standalone)" size="lg">
|
||||
<Stack gap="md">
|
||||
<Text size="sm" c="dimmed">
|
||||
Record container return without booking association
|
||||
</Text>
|
||||
|
||||
<TextInput
|
||||
label="Container Number"
|
||||
placeholder="e.g., TEMU1234567"
|
||||
value={containerNumber}
|
||||
onChange={(e) => setContainerNumber(e.currentTarget.value)}
|
||||
required
|
||||
/>
|
||||
|
||||
<Select
|
||||
label="Returned By"
|
||||
placeholder="Select truck type"
|
||||
value={returnedBy}
|
||||
onChange={(val) => setReturnedBy(val as "EDR" | "CUSTOMER" | null)}
|
||||
data={[
|
||||
{ value: "EDR", label: "EDR Truck" },
|
||||
{ value: "CUSTOMER", label: "Customer Truck" },
|
||||
]}
|
||||
required
|
||||
/>
|
||||
|
||||
<Select
|
||||
label="Return Warehouse"
|
||||
placeholder="Select warehouse for container return"
|
||||
value={warehouse}
|
||||
onChange={setWarehouse}
|
||||
data={warehouseOptions}
|
||||
required
|
||||
searchable
|
||||
/>
|
||||
|
||||
<Select
|
||||
label="Yard"
|
||||
placeholder={warehouse ? "Select yard" : "Select warehouse first"}
|
||||
value={yardId}
|
||||
onChange={setYardId}
|
||||
data={yardOptions}
|
||||
disabled={!warehouse}
|
||||
searchable
|
||||
/>
|
||||
|
||||
<Select
|
||||
label="Zone"
|
||||
placeholder={yardId ? "Select zone" : "Select yard first"}
|
||||
value={zoneId}
|
||||
onChange={setZoneId}
|
||||
data={zoneOptions}
|
||||
disabled={!yardId}
|
||||
searchable
|
||||
/>
|
||||
|
||||
<input
|
||||
type="date"
|
||||
value={returnDate}
|
||||
onChange={(e) => setReturnDate(e.target.value)}
|
||||
style={{ padding: "8px", borderRadius: "4px", border: "1px solid #ccc" }}
|
||||
required
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label="Condition"
|
||||
placeholder="Damage, residue, or cleanliness notes"
|
||||
value={condition}
|
||||
onChange={(e) => setCondition(e.currentTarget.value)}
|
||||
rows={3}
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label="Handover Note"
|
||||
placeholder="Consignee, trucker, or authorization notes"
|
||||
value={handoverNote}
|
||||
onChange={(e) => setHandoverNote(e.currentTarget.value)}
|
||||
rows={3}
|
||||
/>
|
||||
|
||||
<Group justify="flex-end" gap="sm">
|
||||
<Button variant="default" onClick={onClose} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={!containerNumber || !returnedBy || !warehouse}
|
||||
loading={loading}
|
||||
>
|
||||
Record Return
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
import { Fragment, useMemo, useState } from "react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
ActionIcon,
|
||||
Alert,
|
||||
Badge,
|
||||
Button,
|
||||
Group,
|
||||
Loader,
|
||||
Modal,
|
||||
Stack,
|
||||
Table,
|
||||
Text,
|
||||
TextInput,
|
||||
Textarea,
|
||||
Select,
|
||||
Checkbox,
|
||||
} from "@mantine/core";
|
||||
import { ChevronDown, ChevronRight } from "lucide-react";
|
||||
|
||||
import { PageContainer, PageHeader } from "@/components/page";
|
||||
import RuleEngineListFooter from "@/components/ruleEngine/RuleEngineListFooter";
|
||||
import { useListControls } from "@/hooks/useListControls";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { api } from "@/services/api";
|
||||
import { warehouseService } from "@/services/warehouse.service";
|
||||
import { importOperationsService } from "@/services/importOperations.service";
|
||||
|
||||
interface ReturnContainer {
|
||||
containerNumber: string;
|
||||
size: string | null;
|
||||
type: string | null;
|
||||
selected: boolean;
|
||||
}
|
||||
|
||||
interface TruckReturn {
|
||||
key: string;
|
||||
plate: string;
|
||||
companyName: string | null;
|
||||
bookingRef: string;
|
||||
bookingId: string;
|
||||
customerId: string | null;
|
||||
containers: ReturnContainer[];
|
||||
}
|
||||
|
||||
|
||||
export default function EDRLastMileReturnsPage() {
|
||||
const { toast } = useToast();
|
||||
const qc = useQueryClient();
|
||||
const [expanded, setExpanded] = useState<string | null>(null);
|
||||
const [returnModalOpen, setReturnModalOpen] = useState(false);
|
||||
const [activeKey, setActiveKey] = useState<string | null>(null);
|
||||
|
||||
const { data: unloadedQueue = [], isLoading: queueLoading } = useQuery({
|
||||
queryKey: ["import-unloaded-queue"],
|
||||
queryFn: async () => {
|
||||
const response = await api.warehouses.importUnloadedQueue.call();
|
||||
return response ?? [];
|
||||
},
|
||||
});
|
||||
|
||||
const bookingIds = unloadedQueue.map((item) => item.bookingId).filter(Boolean) as string[];
|
||||
const truckReturnsQuery = useQuery({
|
||||
queryKey: ["edr-last-mile-returns", bookingIds],
|
||||
queryFn: async () => {
|
||||
const grouped = new Map<string, TruckReturn>();
|
||||
|
||||
for (const item of unloadedQueue) {
|
||||
if (!item.bookingId) continue;
|
||||
|
||||
const edrTrucks = await warehouseService.getLastMileTrucks(item.bookingId).catch(() => []);
|
||||
for (const truck of edrTrucks) {
|
||||
const inventory = await api.warehouses.listInventory.call({ filter: { bookingId: item.bookingId } }).catch(() => []);
|
||||
|
||||
const returnContainers = inventory
|
||||
.filter((inv: any) => inv.isReturn)
|
||||
.map((inv: any) => ({
|
||||
containerNumber: inv.containerNumber || "—",
|
||||
size: inv.containerSize || null,
|
||||
type: inv.containerType || null,
|
||||
selected: false,
|
||||
}));
|
||||
|
||||
if (returnContainers.length > 0) {
|
||||
const key = `${item.bookingId}-${truck.vehicleId}`;
|
||||
grouped.set(key, {
|
||||
key,
|
||||
plate: [truck.truckPlateNumber, truck.trailerPlateNumber].filter(Boolean).join(" + ") || "—",
|
||||
companyName: item.customerName ?? null,
|
||||
bookingRef: item.bookingReference ?? item.bookingId,
|
||||
bookingId: item.bookingId,
|
||||
customerId: item.customerId || null,
|
||||
containers: returnContainers,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(grouped.values());
|
||||
},
|
||||
enabled: bookingIds.length > 0 && !queueLoading,
|
||||
});
|
||||
|
||||
const trucksWithReturns = useMemo(() => truckReturnsQuery.data ?? [], [truckReturnsQuery.data]);
|
||||
const controls = useListControls(trucksWithReturns, {
|
||||
searchKeys: ["plate", "companyName", "bookingRef"],
|
||||
});
|
||||
|
||||
const createReturnsMutation = useMutation({
|
||||
mutationFn: async (payload: { trucks: Array<{ bookingId: string; customerId: string | null; containers: Array<{ containerNumber: string; returnDate: string; facility: string; yard?: string; zone?: string; condition?: string; handoverNote?: string }> }> }) => {
|
||||
const results = [];
|
||||
for (const truck of payload.trucks) {
|
||||
for (const container of truck.containers) {
|
||||
const result = await importOperationsService.createEmptyReturn({
|
||||
containerNumber: container.containerNumber,
|
||||
returnDate: new Date(container.returnDate).toISOString(),
|
||||
bookingId: truck.bookingId,
|
||||
customerId: truck.customerId ?? undefined,
|
||||
facility: container.facility,
|
||||
yard: container.yard,
|
||||
zone: container.zone,
|
||||
condition: container.condition,
|
||||
handoverNote: container.handoverNote,
|
||||
});
|
||||
results.push(result);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast({ title: "Empty container returns recorded" });
|
||||
qc.invalidateQueries({ queryKey: ["edr-last-mile-returns", bookingIds] });
|
||||
setReturnModalOpen(false);
|
||||
setActiveKey(null);
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Failed to record returns",
|
||||
description: error?.response?.data?.message || error?.message,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const activeTruck = activeKey ? trucksWithReturns.find(t => t.key === activeKey) ?? null : null;
|
||||
|
||||
if (queueLoading || truckReturnsQuery.isLoading) {
|
||||
return (
|
||||
<PageContainer>
|
||||
<Group justify="center" py="lg">
|
||||
<Loader size="sm" />
|
||||
</Group>
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<PageContainer>
|
||||
<PageHeader
|
||||
title="EDR Last Mile Returns"
|
||||
subtitle="Empty containers returned by EDR-haulage trucks — single or bulk processing"
|
||||
/>
|
||||
|
||||
{trucksWithReturns.length === 0 ? (
|
||||
<Alert color="gray">No EDR trucks with return containers found.</Alert>
|
||||
) : (
|
||||
<>
|
||||
<Table.ScrollContainer minWidth={1000}>
|
||||
<Table highlightOnHover verticalSpacing="xs">
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th w={40} />
|
||||
<Table.Th>Plate</Table.Th>
|
||||
<Table.Th>Company</Table.Th>
|
||||
<Table.Th>Booking Ref</Table.Th>
|
||||
<Table.Th>Return Containers</Table.Th>
|
||||
<Table.Th ta="right">Actions</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{controls.pagedRows.map((truck) => {
|
||||
const isOpen = expanded === truck.key;
|
||||
return (
|
||||
<Fragment key={truck.key}>
|
||||
<Table.Tr>
|
||||
<Table.Td>
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
color="gray"
|
||||
onClick={() => setExpanded(isOpen ? null : truck.key)}
|
||||
>
|
||||
{isOpen ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
|
||||
</ActionIcon>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text fw={600}>{truck.plate}</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>{truck.companyName ?? "—"}</Table.Td>
|
||||
<Table.Td>{truck.bookingRef}</Table.Td>
|
||||
<Table.Td>
|
||||
<Badge>{truck.containers.length} container{truck.containers.length !== 1 ? "s" : ""}</Badge>
|
||||
</Table.Td>
|
||||
<Table.Td ta="right">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="light"
|
||||
onClick={() => {
|
||||
setActiveKey(truck.key);
|
||||
setReturnModalOpen(true);
|
||||
}}
|
||||
>
|
||||
Process Returns
|
||||
</Button>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
{isOpen && (
|
||||
<Table.Tr>
|
||||
<Table.Td colSpan={6}>
|
||||
<Table striped>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th w={40}>
|
||||
<Checkbox disabled />
|
||||
</Table.Th>
|
||||
<Table.Th>Container</Table.Th>
|
||||
<Table.Th>Size</Table.Th>
|
||||
<Table.Th>Type</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{truck.containers.map((container, idx) => (
|
||||
<Table.Tr key={idx}>
|
||||
<Table.Td>
|
||||
<Checkbox checked={container.selected} />
|
||||
</Table.Td>
|
||||
<Table.Td>{container.containerNumber}</Table.Td>
|
||||
<Table.Td>{container.size ?? "—"}</Table.Td>
|
||||
<Table.Td>{container.type ?? "—"}</Table.Td>
|
||||
</Table.Tr>
|
||||
))}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</Table.ScrollContainer>
|
||||
<RuleEngineListFooter
|
||||
pagination={controls.pagination}
|
||||
pageCount={controls.pageCount}
|
||||
totalCount={controls.totalCount}
|
||||
itemLabel="trucks"
|
||||
onPaginationChange={controls.setPagination}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<EmptyContainerReturnModal
|
||||
opened={returnModalOpen}
|
||||
onClose={() => setReturnModalOpen(false)}
|
||||
truck={activeTruck}
|
||||
onSubmit={(payload) => createReturnsMutation.mutate(payload)}
|
||||
loading={createReturnsMutation.isPending}
|
||||
/>
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
interface EmptyContainerReturnModalProps {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
truck: TruckReturn | null;
|
||||
onSubmit: (payload: any) => void;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
function EmptyContainerReturnModal({ opened, onClose, truck, onSubmit, loading }: EmptyContainerReturnModalProps) {
|
||||
const [selectedContainers, setSelectedContainers] = useState<string[]>([]);
|
||||
const [returnDate, setReturnDate] = useState<string>(new Date().toISOString().split("T")[0]);
|
||||
const [warehouse, setWarehouse] = useState<string | null>(null);
|
||||
const [condition, setCondition] = useState<string>("");
|
||||
const [handoverNote, setHandoverNote] = useState<string>("");
|
||||
|
||||
const { data: warehousesResponse } = useQuery({
|
||||
queryKey: ["warehouses-list"],
|
||||
queryFn: async () => {
|
||||
return await warehouseService.list({});
|
||||
},
|
||||
});
|
||||
|
||||
const warehouses = (warehousesResponse as any)?.data ?? warehousesResponse ?? [];
|
||||
const warehouseOptions = Array.isArray(warehouses) ? warehouses.map((wh: any) => ({
|
||||
value: wh.id,
|
||||
label: `${wh.name} ${wh.code ? `(${wh.code})` : ""}`,
|
||||
})) : [];
|
||||
|
||||
const selectedWarehouse = warehouse && Array.isArray(warehouses) ? warehouses.find((wh: any) => wh.id === warehouse) : null;
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!truck || !selectedContainers.length || !warehouse) return;
|
||||
|
||||
const containers = truck.containers
|
||||
.filter((c) => selectedContainers.includes(c.containerNumber))
|
||||
.map((c) => ({
|
||||
containerNumber: c.containerNumber,
|
||||
returnDate,
|
||||
facility: selectedWarehouse?.name || warehouse,
|
||||
yard: selectedWarehouse?.code || undefined,
|
||||
zone: undefined,
|
||||
condition: condition || undefined,
|
||||
handoverNote: handoverNote || undefined,
|
||||
}));
|
||||
|
||||
onSubmit({
|
||||
trucks: [{
|
||||
bookingId: truck.bookingId,
|
||||
customerId: truck.customerId,
|
||||
containers,
|
||||
}],
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal opened={opened} onClose={onClose} title="Process Empty Container Returns" size="lg">
|
||||
{truck && (
|
||||
<Stack gap="md">
|
||||
<Group>
|
||||
<Text fw={600}>{truck.plate}</Text>
|
||||
<Text size="sm" c="dimmed">{truck.bookingRef}</Text>
|
||||
</Group>
|
||||
|
||||
<div>
|
||||
<Text size="sm" fw={600} mb="xs">Select containers to return:</Text>
|
||||
<Stack gap="xs">
|
||||
{truck.containers.map((container) => (
|
||||
<Checkbox
|
||||
key={container.containerNumber}
|
||||
label={`${container.containerNumber} (${container.size || "bulk"})`}
|
||||
checked={selectedContainers.includes(container.containerNumber)}
|
||||
onChange={(e) => {
|
||||
if (e.currentTarget.checked) {
|
||||
setSelectedContainers([...selectedContainers, container.containerNumber]);
|
||||
} else {
|
||||
setSelectedContainers(selectedContainers.filter(c => c !== container.containerNumber));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
</div>
|
||||
|
||||
<Select
|
||||
label="Return Warehouse"
|
||||
placeholder="Select warehouse for container return"
|
||||
value={warehouse}
|
||||
onChange={setWarehouse}
|
||||
data={warehouseOptions}
|
||||
required
|
||||
searchable
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
label="Return Date"
|
||||
type="date"
|
||||
value={returnDate}
|
||||
onChange={(e) => setReturnDate(e.currentTarget.value)}
|
||||
required
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label="Condition"
|
||||
placeholder="Damage, residue, or cleanliness notes"
|
||||
value={condition}
|
||||
onChange={(e) => setCondition(e.currentTarget.value)}
|
||||
rows={3}
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label="Handover Note"
|
||||
placeholder="Consignee, trucker, or authorization notes"
|
||||
value={handoverNote}
|
||||
onChange={(e) => setHandoverNote(e.currentTarget.value)}
|
||||
rows={3}
|
||||
/>
|
||||
|
||||
<Group justify="flex-end" gap="sm">
|
||||
<Button variant="default" onClick={onClose} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={!selectedContainers.length || !warehouse}
|
||||
loading={loading}
|
||||
>
|
||||
{selectedContainers.length > 1 ? "Bulk" : "Single"} Return ({selectedContainers.length})
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Fragment, useMemo, useState } from "react";
|
||||
import { useQueries, useQuery } from "@tanstack/react-query";
|
||||
import { useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
ActionIcon,
|
||||
Alert,
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
FileText,
|
||||
MoreHorizontal,
|
||||
Receipt,
|
||||
Truck,
|
||||
} from "lucide-react";
|
||||
import type { Freight } from "@edr/types";
|
||||
|
||||
@@ -27,14 +28,22 @@ import RuleEngineListFooter from "@/components/ruleEngine/RuleEngineListFooter";
|
||||
import { InspectionReportModal } from "@/components/warehouses/InspectionReportModal";
|
||||
import { TruckDetentionModal } from "@/components/operations/TruckDetentionModal";
|
||||
import { WarehouseGateTimesModal } from "@/components/operations/WarehouseGateTimesModal";
|
||||
import { extractDownloadErrorMessage, formatNumber } from "@/components/warehouses/options";
|
||||
import {
|
||||
ReleaseOrderModal,
|
||||
type ReleaseOrderTruckPrefill,
|
||||
} from "@/components/warehouses/ReleaseOrderModal";
|
||||
import {
|
||||
extractDownloadErrorMessage,
|
||||
formatNumber,
|
||||
toReleaseInventoryItem,
|
||||
} from "@/components/warehouses/options";
|
||||
import { openPdfBlob } from "@/components/warehouses/pdf";
|
||||
import { useListControls } from "@/hooks/useListControls";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { api } from "@/services/api";
|
||||
import { lastMileService } from "@/services/last-mile.service";
|
||||
import { warehouseService, type LastMileArrivalTruck } from "@/services/warehouse.service";
|
||||
import type { ImportUnloadedItem } from "@/types/warehouse";
|
||||
import type { ImportUnloadedItem, WarehouseInventoryItem } from "@/types/warehouse";
|
||||
|
||||
/**
|
||||
* Import trucks — the unloaded queue seen truck-first instead of item-first.
|
||||
@@ -53,6 +62,20 @@ import type { ImportUnloadedItem } from "@/types/warehouse";
|
||||
|
||||
const COLS = 11;
|
||||
|
||||
/** Truck columns — the table head, and repeated inside each expanded booking. */
|
||||
const TRUCK_COLUMNS = [
|
||||
"Plate",
|
||||
"Type",
|
||||
"Containers",
|
||||
"Truck Arrival",
|
||||
"Truck Leaving",
|
||||
"Weight",
|
||||
"Demurrage",
|
||||
"Storage",
|
||||
"Detention",
|
||||
"Actions",
|
||||
] as const;
|
||||
|
||||
const money = (amount: number, currency: string) =>
|
||||
`${Number(amount).toLocaleString(undefined, { maximumFractionDigits: 2 })} ${currency === "ETB" ? "ETB" : currency}`;
|
||||
|
||||
@@ -109,6 +132,8 @@ interface TruckRow {
|
||||
vehicleId: string | null;
|
||||
arrivedAt: string | null;
|
||||
departedAt: string | null;
|
||||
/** Identity handed to the release modal so it opens on THIS truck. */
|
||||
prefill: ReleaseOrderTruckPrefill;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -117,10 +142,17 @@ interface TruckRow {
|
||||
*/
|
||||
function TruckRows({ group }: { group: BookingGroup }) {
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [inspectId, setInspectId] = useState<string | null>(null);
|
||||
const [detentionOpen, setDetentionOpen] = useState(false);
|
||||
const [gateTimesOpen, setGateTimesOpen] = useState(false);
|
||||
// The truck whose arrival/exit weighing is open — kept in state so the prefill
|
||||
// object stays referentially stable while the modal is up.
|
||||
const [release, setRelease] = useState<{
|
||||
item: WarehouseInventoryItem;
|
||||
prefill: ReleaseOrderTruckPrefill;
|
||||
} | null>(null);
|
||||
|
||||
const edrQuery = useQuery({
|
||||
queryKey: ["booking-edr-trucks", group.bookingId],
|
||||
@@ -194,6 +226,15 @@ function TruckRows({ group }: { group: BookingGroup }) {
|
||||
vehicleId: t.vehicleId,
|
||||
arrivedAt: t.arrivedAt,
|
||||
departedAt: t.departedAt,
|
||||
prefill: {
|
||||
truckPlateNumber: t.truckPlateNumber,
|
||||
trailerPlateNumber: t.trailerPlateNumber,
|
||||
driverName: t.driverName,
|
||||
driverLicense: t.driverLicense,
|
||||
driverPhone: t.driverPhone,
|
||||
truckType: t.truckType,
|
||||
containerNumber: t.containerNumber,
|
||||
},
|
||||
...costsFor(containers),
|
||||
};
|
||||
};
|
||||
@@ -208,11 +249,39 @@ function TruckRows({ group }: { group: BookingGroup }) {
|
||||
vehicleId: null,
|
||||
arrivedAt: t.arrivedAt ?? null,
|
||||
departedAt: t.departedAt ?? null,
|
||||
prefill: {
|
||||
truckPlateNumber: t.plateNumber,
|
||||
driverName: t.driverName,
|
||||
truckType: t.truckType,
|
||||
containerNumber: containers.join(", "),
|
||||
},
|
||||
...costsFor(containers),
|
||||
};
|
||||
};
|
||||
const trucks: TruckRow[] = isEdr ? edrTrucks.map(fromEdr) : customerTrucks.map(fromCustomer);
|
||||
|
||||
/**
|
||||
* Arrival and leaving are one form per truck: the modal picks the step from
|
||||
* that plate's own saved weighing block, so both menu items open it the same
|
||||
* way. The booking-level opener (inventory workbench) stays as it was.
|
||||
*/
|
||||
const openRelease = (t: TruckRow) => {
|
||||
const row = group.rows.find((r) => r.id === t.inventoryIds[0]) ?? group.rows[0];
|
||||
if (!row) return;
|
||||
setRelease({ item: toReleaseInventoryItem(row), prefill: t.prefill });
|
||||
};
|
||||
|
||||
const closeRelease = () => {
|
||||
setRelease(null);
|
||||
void queryClient.invalidateQueries({ queryKey: ["booking-edr-trucks", group.bookingId] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["booking-customer-trucks", group.bookingId] });
|
||||
// The saved weighing block lives in the inventory row's notes — refetch the
|
||||
// queue or the next open would still show the truck as never arrived.
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: api.warehouses.importUnloadedQueue.queryOptions({}).queryKey,
|
||||
});
|
||||
};
|
||||
|
||||
const openDocument = async (
|
||||
kind: "release" | "handover",
|
||||
inventoryId: string,
|
||||
@@ -267,6 +336,18 @@ function TruckRows({ group }: { group: BookingGroup }) {
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* The booking row sits between the head and these trucks, so repeat the
|
||||
column labels — otherwise an expanded booking reads as unlabelled. */}
|
||||
<Table.Tr bg="var(--mantine-color-gray-1)">
|
||||
<Table.Td />
|
||||
{TRUCK_COLUMNS.map((label) => (
|
||||
<Table.Td key={label} ta={label === "Actions" ? "right" : undefined}>
|
||||
<Text size="xs" fw={700} c="dimmed">
|
||||
{label}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
))}
|
||||
</Table.Tr>
|
||||
{trucks.map((t, idx) => {
|
||||
const detention = t.vehicleId ? detentionByVehicle.get(t.vehicleId) : undefined;
|
||||
const primaryId = t.inventoryIds[0] ?? null;
|
||||
@@ -337,6 +418,21 @@ function TruckRows({ group }: { group: BookingGroup }) {
|
||||
</ActionIcon>
|
||||
</Menu.Target>
|
||||
<Menu.Dropdown>
|
||||
<Menu.Item
|
||||
leftSection={<Truck size={14} />}
|
||||
disabled={!primaryId}
|
||||
onClick={() => openRelease(t)}
|
||||
>
|
||||
Truck Arrival
|
||||
</Menu.Item>
|
||||
<Menu.Item
|
||||
leftSection={<Truck size={14} />}
|
||||
disabled={!primaryId}
|
||||
onClick={() => openRelease(t)}
|
||||
>
|
||||
Truck Leaving
|
||||
</Menu.Item>
|
||||
<Menu.Divider />
|
||||
<Menu.Item
|
||||
leftSection={<FileText size={14} />}
|
||||
disabled={!primaryId}
|
||||
@@ -388,6 +484,12 @@ function TruckRows({ group }: { group: BookingGroup }) {
|
||||
onClose={() => setInspectId(null)}
|
||||
inventoryId={inspectId}
|
||||
/>
|
||||
<ReleaseOrderModal
|
||||
opened={Boolean(release)}
|
||||
onClose={closeRelease}
|
||||
item={release?.item ?? null}
|
||||
truckPrefill={release?.prefill ?? null}
|
||||
/>
|
||||
{isEdr && (
|
||||
<>
|
||||
<TruckDetentionModal
|
||||
@@ -459,16 +561,11 @@ export default function ImportTrucksPage() {
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th w={40} />
|
||||
<Table.Th>Plate</Table.Th>
|
||||
<Table.Th>Type</Table.Th>
|
||||
<Table.Th>Containers</Table.Th>
|
||||
<Table.Th>Truck Arrival</Table.Th>
|
||||
<Table.Th>Truck Leaving</Table.Th>
|
||||
<Table.Th>Weight</Table.Th>
|
||||
<Table.Th>Demurrage</Table.Th>
|
||||
<Table.Th>Storage</Table.Th>
|
||||
<Table.Th>Detention</Table.Th>
|
||||
<Table.Th ta="right">Actions</Table.Th>
|
||||
{TRUCK_COLUMNS.map((label) => (
|
||||
<Table.Th key={label} ta={label === "Actions" ? "right" : undefined}>
|
||||
{label}
|
||||
</Table.Th>
|
||||
))}
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
|
||||
@@ -150,8 +150,9 @@ function AllocationRules() {
|
||||
.filter((yard) => yard.code)
|
||||
.map((yard) => ({
|
||||
value: yard.code,
|
||||
label: `${yard.code} - ${yard.name}${yard.warehouse?.code ? ` (${yard.warehouse.code})` : ''}`,
|
||||
label: `${yard.name} (${yard.code})${yard.warehouse?.code ? ` — ${yard.warehouse.code}` : ''}`,
|
||||
}));
|
||||
const yardNameByCode = Object.fromEntries(yards.map((yard) => [yard.code, yard.name]));
|
||||
|
||||
const resetForm = () => {
|
||||
setEditingId(null);
|
||||
@@ -223,7 +224,11 @@ function AllocationRules() {
|
||||
{
|
||||
id: 'targetYard',
|
||||
header: 'Target yard',
|
||||
cell: ({ row }) => <Badge variant="light">{row.original.targetYardCode}</Badge>,
|
||||
cell: ({ row }) => (
|
||||
<Badge variant="light">
|
||||
{yardNameByCode[row.original.targetYardCode] ?? row.original.targetYardCode}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'active',
|
||||
@@ -307,7 +312,8 @@ function AllocationRules() {
|
||||
{anyLabel(form.freightType, 'freight type').toLowerCase()} booking
|
||||
{form.cargoTypeCode.trim() ? ` with cargo code ${form.cargoTypeCode.trim()}` : ''}
|
||||
{form.containerStatus.trim() ? ` and container status ${form.containerStatus.trim()}` : ''}{' '}
|
||||
is received, <b>send it to</b> {form.targetYardCode || 'a selected target yard'}.
|
||||
is received, <b>send it to</b>{' '}
|
||||
{(form.targetYardCode && yardNameByCode[form.targetYardCode]) || form.targetYardCode || 'a selected target yard'}.
|
||||
</Text>
|
||||
</Stack>
|
||||
</Card>
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
CompanyChangeRequest,
|
||||
CompanyListFilter,
|
||||
CompanyProfile,
|
||||
CompanyRevision,
|
||||
CompanyStats,
|
||||
CustomerBooking,
|
||||
CustomerDocument,
|
||||
@@ -2778,6 +2779,13 @@ export const api = {
|
||||
({ id }) => QUERY_KEYS.CUSTOMERS.changeRequests(id),
|
||||
),
|
||||
|
||||
revisions: endpoint<{ id: string }, CompanyRevision[]>(
|
||||
"customers",
|
||||
"revisions",
|
||||
({ id }) => customersService.revisions(id),
|
||||
({ id }) => QUERY_KEYS.CUSTOMERS.revisions(id),
|
||||
),
|
||||
|
||||
approveChangeRequest: endpoint<{ id: string }, CompanyChangeRequest>(
|
||||
"customers",
|
||||
"approveChangeRequest",
|
||||
@@ -2802,6 +2810,21 @@ export const api = {
|
||||
],
|
||||
),
|
||||
|
||||
requestChangeRequestChanges: endpoint<
|
||||
{ id: string; note: string },
|
||||
CompanyChangeRequest
|
||||
>(
|
||||
"customers",
|
||||
"requestChangeRequestChanges",
|
||||
({ id, note }) => customersService.requestChangeRequestChanges(id, note),
|
||||
undefined,
|
||||
(_input, data) => [
|
||||
QUERY_KEYS.CUSTOMERS.changeRequests(data.companyId),
|
||||
QUERY_KEYS.CUSTOMERS.byId(data.companyId),
|
||||
QUERY_KEYS.CUSTOMERS.ROOT,
|
||||
],
|
||||
),
|
||||
|
||||
/**
|
||||
* Ask the customer to correct one document. Invalidates the documents list
|
||||
* and the company itself, since an open request blocks role approval.
|
||||
|
||||
@@ -455,6 +455,13 @@ export const bookingsService = {
|
||||
return (unwrap(response.data) ?? []) as BookingDetail[];
|
||||
},
|
||||
|
||||
downloadCarriageAcceptanceSheet: async (id: string): Promise<Blob> => {
|
||||
const response = await client.get(B.CARRIAGE_ACCEPTANCE_SHEET(id), {
|
||||
responseType: "blob",
|
||||
});
|
||||
return ensurePdfBlob(response.data as Blob);
|
||||
},
|
||||
|
||||
getDjClearanceQueue: async (): Promise<BookingDetail[]> => {
|
||||
const response = await client.get(B.CLEARANCE_DJ_QUEUE);
|
||||
return (unwrap(response.data) ?? []) as BookingDetail[];
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
CompanyChangeRequest,
|
||||
CompanyListFilter,
|
||||
CompanyProfile,
|
||||
CompanyRevision,
|
||||
CompanyStats,
|
||||
CustomerBooking,
|
||||
CustomerDocument,
|
||||
@@ -146,6 +147,13 @@ export const customersService = {
|
||||
.then((r) => r.data);
|
||||
},
|
||||
|
||||
/** Onboarding-phase edit history for a company (version history), newest first. */
|
||||
revisions(companyId: string): Promise<CompanyRevision[]> {
|
||||
return apiClient
|
||||
.get<CompanyRevision[]>(URL_CONSTANTS.COMPANIES.REVISIONS(companyId))
|
||||
.then((r) => r.data);
|
||||
},
|
||||
|
||||
/** Approve a pending change request — applies the proposed changes. */
|
||||
approveChangeRequest(id: string): Promise<CompanyChangeRequest> {
|
||||
return apiClient
|
||||
@@ -165,6 +173,19 @@ export const customersService = {
|
||||
.then((r) => r.data);
|
||||
},
|
||||
|
||||
/** Ask for specific changes without rejecting — the request stays open for the customer's next edit to append to. */
|
||||
requestChangeRequestChanges(
|
||||
id: string,
|
||||
note: string,
|
||||
): Promise<CompanyChangeRequest> {
|
||||
return apiClient
|
||||
.post<CompanyChangeRequest>(
|
||||
URL_CONSTANTS.COMPANIES.CHANGE_REQUEST_REQUEST_CHANGES(id),
|
||||
{ note },
|
||||
)
|
||||
.then((r) => r.data);
|
||||
},
|
||||
|
||||
/**
|
||||
* Ask the customer to correct one uploaded document. Narrower than rejecting
|
||||
* the whole role: the customer keeps their other documents and only re-uploads
|
||||
|
||||
@@ -19,7 +19,8 @@ export type PaymentMethod =
|
||||
| "waafi"
|
||||
| "card"
|
||||
| "dmoney"
|
||||
| "cac-bank";
|
||||
| "cac-bank"
|
||||
| "cbe-bill";
|
||||
|
||||
export interface PaymentRow {
|
||||
id: string;
|
||||
|
||||
@@ -69,7 +69,11 @@ export interface CompanyProfile {
|
||||
}
|
||||
|
||||
/** Lifecycle of a staged customer profile-edit review. */
|
||||
export type ChangeRequestStatus = "pending" | "approved" | "rejected";
|
||||
export type ChangeRequestStatus =
|
||||
| "pending"
|
||||
| "approved"
|
||||
| "rejected"
|
||||
| "changes_requested";
|
||||
|
||||
/** A staged business-license add/remove on one profile, awaiting review. */
|
||||
export interface LicenseChangeIntent {
|
||||
@@ -110,6 +114,33 @@ export interface CompanyChangeRequest {
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One field/document change recorded on a company revision. A document change
|
||||
* carries `fromFileId`/`toFileId` alongside the display names, so the
|
||||
* previous and current file can both be opened, not just named.
|
||||
*/
|
||||
export interface CompanyRevisionChange {
|
||||
field: string;
|
||||
label: string;
|
||||
from: string | null;
|
||||
to: string | null;
|
||||
fromFileId?: string | null;
|
||||
toFileId?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Onboarding-phase edit history — records what changed on a company record
|
||||
* before it reached Active, the write path that has no approval gate.
|
||||
*/
|
||||
export interface CompanyRevision {
|
||||
id: string;
|
||||
companyId: string;
|
||||
actorId: string | null;
|
||||
summary: string;
|
||||
changes: CompanyRevisionChange[];
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
/** The channel a customer's password-reset link is delivered over. */
|
||||
export type ResetChannel = "email" | "phone";
|
||||
|
||||
@@ -215,6 +246,7 @@ export interface Company {
|
||||
onboardingCompleted?: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
approvedAt?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -883,6 +883,9 @@ export function AppLayout({
|
||||
<AppShell.Main
|
||||
style={{
|
||||
backgroundColor: "##f8fafc",
|
||||
// Extra bottom clearance so the fixed support-chat FAB never
|
||||
// overlaps page content, even at the bottom of a scrolled page.
|
||||
paddingBottom: 112,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -28,6 +28,31 @@ interface ETradeInfoProps {
|
||||
|
||||
const isValidTin = (tin: string) => tin.length === 10;
|
||||
|
||||
/** Plain-text summary of the fetched eTrade record, downloaded client-side (eTrade returns data, not a document). */
|
||||
function downloadTinRecord(tin: string, data: CompanyRegistrationData) {
|
||||
const lines = [
|
||||
`TIN: ${tin}`,
|
||||
`Company name: ${data.companyName}`,
|
||||
`Licence number: ${data.licenceNumber}`,
|
||||
`Status: ${data.statusDescription}`,
|
||||
`Date registered: ${data.dateRegistered}`,
|
||||
`Renewed from: ${data.renewedFrom}`,
|
||||
`Renewal date: ${data.renewalDate}`,
|
||||
`Renewed to: ${data.renewedTo}`,
|
||||
`Address: ${[data.region, data.zone, data.woreda, data.kebele, data.houseNo].filter(Boolean).join(", ")}`,
|
||||
`Manager: ${data.managerName}`,
|
||||
];
|
||||
const blob = new Blob([lines.join("\n")], { type: "text/plain;charset=utf-8" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `tin-${tin}.txt`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
}
|
||||
|
||||
export default function ETradeInfo({
|
||||
tin,
|
||||
register,
|
||||
@@ -123,6 +148,17 @@ export default function ETradeInfo({
|
||||
{isLoading ? "Getting..." : "Get Data"}
|
||||
</Button>
|
||||
)}
|
||||
{status === "verified" && mutation.data && !mutation.data.tinTaken && (
|
||||
<Button
|
||||
variant="light"
|
||||
color="edr-green"
|
||||
onClick={() => downloadTinRecord(tin, mutation.data!)}
|
||||
leftSection={<Download size={16} />}
|
||||
mt="24px"
|
||||
>
|
||||
Download
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
|
||||
{notFound && (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Link } from "react-router-dom";
|
||||
import { AlertTriangle, ArrowRight, Clock } from "lucide-react";
|
||||
import { AlertTriangle, ArrowRight, CheckCircle2, Clock } from "lucide-react";
|
||||
import { api } from "@/services/api";
|
||||
import useAuth from "@/hooks/useAuth";
|
||||
import type { OnboardingRequirements } from "@/services/companies.service";
|
||||
@@ -150,18 +150,46 @@ export default function OnboardingResumeBanner({
|
||||
|
||||
/**
|
||||
* Post-onboarding review banner. Surfaces (in priority order):
|
||||
* 0. The account is suspended/blacklisted — hard lock.
|
||||
* 1. A pending profile-edit review — the whole account is locked until an admin
|
||||
* approves the submitted changes.
|
||||
* 2. A rejected profile-edit review — links to Settings to amend & resubmit.
|
||||
* 3. Per-operational-profile approval — bookings unlock as each role clears.
|
||||
* 2. Backoffice requested changes — soft: same edit-and-resubmit call to
|
||||
* action as a rejection, but the edit appends to the same request.
|
||||
* 3. A rejected profile-edit review — links to Settings to amend & resubmit
|
||||
* (starts a fresh request).
|
||||
* 4/5. Company- and per-operational-profile approval — bookings unlock as
|
||||
* each role clears.
|
||||
* Self-hides when there's nothing outstanding.
|
||||
*/
|
||||
export function AccountReviewBanner() {
|
||||
const { company, reviewStatus, reviewNote } = useAuth();
|
||||
const { company, companyStatus, reviewStatus, reviewNote } = useAuth();
|
||||
const profiles = company?.company?.companyProfiles ?? [];
|
||||
const pending = profiles.filter((p) => p.status === "pending");
|
||||
const approved = profiles.filter((p) => p.status === "active");
|
||||
|
||||
// 0. Account suspended/blacklisted — the hardest lock, takes priority over
|
||||
// everything else since nothing below matters if the account is shut down.
|
||||
if (companyStatus === "suspended" || companyStatus === "blacklisted") {
|
||||
return (
|
||||
<div className="border-b border-red-200 bg-red-50 px-6 py-3">
|
||||
<div className="mx-auto flex max-w-6xl items-center gap-3">
|
||||
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-red-100 text-red-700">
|
||||
<AlertTriangle size={18} />
|
||||
</span>
|
||||
<span className="flex flex-col gap-0.5">
|
||||
<span className="text-sm font-semibold text-red-900">
|
||||
Your account has been suspended
|
||||
</span>
|
||||
<span className="text-xs text-red-800">
|
||||
Contact EDR support to resolve this before you can continue
|
||||
working.
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 1. Profile-edit review pending — the account-wide lock.
|
||||
if (reviewStatus === "pending") {
|
||||
return (
|
||||
@@ -184,7 +212,41 @@ export function AccountReviewBanner() {
|
||||
);
|
||||
}
|
||||
|
||||
// 2. Profile-edit review rejected — prompt to fix & resubmit.
|
||||
// 2. Backoffice asked for specific changes — soft: same edit-and-resubmit
|
||||
// call to action as a rejection, but the copy stays collaborative since
|
||||
// the edit appends to this same request instead of starting over.
|
||||
if (reviewStatus === "changes_requested") {
|
||||
return (
|
||||
<div className="border-b border-amber-200 bg-amber-50 px-6 py-3">
|
||||
<div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-amber-100 text-amber-700">
|
||||
<AlertTriangle size={18} />
|
||||
</span>
|
||||
<span className="flex flex-col gap-0.5">
|
||||
<span className="text-sm font-semibold text-amber-900">
|
||||
Changes requested on your submission
|
||||
</span>
|
||||
<span className="text-xs text-amber-800">
|
||||
{reviewNote
|
||||
? `Reviewer note: ${reviewNote}`
|
||||
: "Please update the requested details and resubmit for review."}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<Link
|
||||
to="/settings"
|
||||
className="inline-flex items-center gap-2 rounded-lg bg-amber-600 px-4 py-2 text-sm font-semibold text-white shadow-sm transition-transform hover:scale-[1.02]"
|
||||
>
|
||||
Review & resubmit
|
||||
<ArrowRight size={16} />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Profile-edit review rejected — prompt to fix & resubmit.
|
||||
if (reviewStatus === "rejected") {
|
||||
return (
|
||||
<div className="border-b border-red-200 bg-red-50 px-6 py-3">
|
||||
@@ -216,8 +278,45 @@ export function AccountReviewBanner() {
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Per-operational-profile approval (existing behaviour).
|
||||
if (profiles.length === 0 || pending.length === 0) return null;
|
||||
// 4. Company approved and awaiting its first operational profile — nothing
|
||||
// profile-specific to report yet, but the account itself is pending.
|
||||
if (profiles.length === 0) {
|
||||
if (companyStatus === "pending") {
|
||||
return (
|
||||
<div className="border-b border-amber-200 bg-amber-50 px-6 py-3">
|
||||
<div className="mx-auto flex max-w-6xl items-center gap-3">
|
||||
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-amber-100 text-amber-700">
|
||||
<Clock size={18} />
|
||||
</span>
|
||||
<span className="text-sm font-semibold text-amber-900">
|
||||
Your account is pending approval
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// 5. Per-operational-profile approval (existing behaviour).
|
||||
if (pending.length === 0) {
|
||||
// Nothing outstanding — a quiet confirmation that the account is live.
|
||||
if (companyStatus === "active") {
|
||||
return (
|
||||
<div className="border-b border-emerald-200 bg-emerald-50 px-6 py-3">
|
||||
<div className="mx-auto flex max-w-6xl items-center gap-3">
|
||||
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-emerald-100 text-emerald-700">
|
||||
<CheckCircle2 size={18} />
|
||||
</span>
|
||||
<span className="text-sm font-semibold text-emerald-900">
|
||||
Your account is approved
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const pendingLabel = pending
|
||||
.map((p) => p.type.replace(/_/g, " "))
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
Text,
|
||||
Title,
|
||||
} from "@mantine/core";
|
||||
import { useMediaQuery } from "@mantine/hooks";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
ArrowRight,
|
||||
@@ -127,6 +128,7 @@ export default function OnboardingWizardDialog({
|
||||
}: OnboardingWizardDialogProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { user, company, onboardingStep, onboardingCompleted } = useAuth();
|
||||
const isMobile = useMediaQuery("(max-width: 48em)");
|
||||
|
||||
const existingProfiles = company?.company?.companyProfiles ?? [];
|
||||
const companyAlreadyStarted = Boolean(company?.company?.id);
|
||||
@@ -409,7 +411,9 @@ export default function OnboardingWizardDialog({
|
||||
ceiling = Math.min(ceiling, FORM_STEPS.indexOf("documents"));
|
||||
if (poaIncomplete) ceiling = Math.min(ceiling, FORM_STEPS.indexOf("poa"));
|
||||
const effectiveResumeStep: FormStep =
|
||||
FORM_STEPS[Math.min(Math.max(FORM_STEPS.indexOf(resumeFormStep), 0), ceiling)];
|
||||
FORM_STEPS[
|
||||
Math.min(Math.max(FORM_STEPS.indexOf(resumeFormStep), 0), ceiling)
|
||||
];
|
||||
|
||||
const formProps = {
|
||||
documentSettingCode: resolvedDocumentSettingCode,
|
||||
@@ -450,9 +454,10 @@ export default function OnboardingWizardDialog({
|
||||
withCloseButton={!completed}
|
||||
closeOnClickOutside={false}
|
||||
closeOnEscape={!completed}
|
||||
fullScreen={isMobile}
|
||||
size={1440}
|
||||
radius="lg"
|
||||
padding="xl"
|
||||
padding={isMobile ? "md" : "xl"}
|
||||
centered
|
||||
keepMounted
|
||||
scrollAreaComponent={ScrollArea.Autosize}
|
||||
@@ -464,6 +469,9 @@ export default function OnboardingWizardDialog({
|
||||
title: {
|
||||
flex: 1,
|
||||
},
|
||||
body: isMobile
|
||||
? { paddingBottom: "calc(100px + env(safe-area-inset-bottom))" }
|
||||
: undefined,
|
||||
}}
|
||||
title={
|
||||
completed ? null : (
|
||||
|
||||
@@ -130,6 +130,8 @@ export const URL_CONSTANTS = {
|
||||
CANCEL: (id: string | number) => `/api/bookings/${id}/cancel`,
|
||||
CONFIRM: (id: string | number) => `/api/bookings/${id}/confirm`,
|
||||
CUSTOMER_TRUCKS: (id: string) => `/api/bookings/${id}/customer-trucks`,
|
||||
CUSTOMER_TRUCKS_BULK: (id: string) =>
|
||||
`/api/bookings/${id}/customer-trucks/bulk`,
|
||||
CUSTOMER_TRUCK: (id: string, assignmentId: string) =>
|
||||
`/api/bookings/${id}/customer-trucks/${assignmentId}`,
|
||||
},
|
||||
@@ -201,6 +203,8 @@ export const URL_CONSTANTS = {
|
||||
MY_INVOICE_DOCUMENT: (id: string) => `/api/billing/my-invoices/${id}/document`,
|
||||
MY_INVOICE_RECEIPT: (id: string) => `/api/billing/my-invoices/${id}/receipt`,
|
||||
PAY_INVOICE: (id: string) => `/api/billing/my-invoices/${id}/pay`,
|
||||
CONFIRM_INVOICE_OTP: (id: string) =>
|
||||
`/api/billing/my-invoices/${id}/confirm`,
|
||||
},
|
||||
|
||||
WAREHOUSE_INVOICES: {
|
||||
|
||||
@@ -41,7 +41,7 @@ export function SupportWidget() {
|
||||
if (!isAuthenticated) return null;
|
||||
|
||||
return (
|
||||
<Affix position={{ bottom: 24, right: 24 }} zIndex={300}>
|
||||
<Affix position={{ bottom: 24, right: 24 }} zIndex={300} className="group">
|
||||
<Transition mounted={open} transition="pop-bottom-right" duration={200}>
|
||||
{(styles) => (
|
||||
<div style={styles} className="mb-3">
|
||||
@@ -53,40 +53,44 @@ export function SupportWidget() {
|
||||
<Transition mounted={!open} transition="pop" duration={150}>
|
||||
{(styles) => (
|
||||
<div style={styles} className="flex justify-end">
|
||||
<Indicator
|
||||
label={unread > 9 ? "9+" : unread}
|
||||
size={20}
|
||||
offset={8}
|
||||
color="red"
|
||||
disabled={unread === 0}
|
||||
processing
|
||||
withBorder
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Open support chat"
|
||||
onClick={() => setOpen(true)}
|
||||
className="group relative flex cursor-pointer items-center gap-2.5 rounded-full bg-linear-135 from-edr-primary-dark to-edr-primary py-2 pr-2 pl-2 text-white shadow-[0_10px_28px_rgba(13,92,44,0.4)] transition-transform duration-150 hover:-translate-y-0.5 focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-edr-primary active:translate-y-0 motion-reduce:transition-none motion-reduce:hover:translate-y-0 sm:pr-5"
|
||||
{/* Icon+label stay recognizable at rest, just tucked down a bit;
|
||||
lifts fully into place on hover/focus. */}
|
||||
<div className="translate-y-[60%] transition-transform duration-300 ease-out group-hover:translate-y-0 focus-within:translate-y-0 motion-reduce:translate-y-0">
|
||||
<Indicator
|
||||
label={unread > 9 ? "9+" : unread}
|
||||
size={20}
|
||||
offset={8}
|
||||
color="red"
|
||||
disabled={unread === 0}
|
||||
processing
|
||||
withBorder
|
||||
>
|
||||
{/* Faint breathing ring; the unread badge already pulses, so stand down then. */}
|
||||
{unread === 0 && (
|
||||
<span className="pointer-events-none absolute -inset-1 animate-pulse rounded-full ring-2 ring-edr-primary/50 motion-reduce:animate-none" />
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Open support chat"
|
||||
onClick={() => setOpen(true)}
|
||||
className="group relative flex cursor-pointer items-center gap-2.5 rounded-full bg-linear-135 from-edr-primary-dark to-edr-primary py-2 pr-2 pl-2 text-white shadow-[0_10px_28px_rgba(13,92,44,0.4)] transition-transform duration-150 hover:-translate-y-0.5 focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-edr-primary active:translate-y-0 motion-reduce:transition-none motion-reduce:hover:translate-y-0 sm:pr-5"
|
||||
>
|
||||
{/* Faint breathing ring; the unread badge already pulses, so stand down then. */}
|
||||
{unread === 0 && (
|
||||
<span className="pointer-events-none absolute -inset-1 animate-pulse rounded-full ring-2 ring-edr-primary/50 motion-reduce:animate-none" />
|
||||
)}
|
||||
|
||||
<span className="relative grid size-[42px] shrink-0 place-items-center rounded-full bg-white/20">
|
||||
<Headset size={22} />
|
||||
</span>
|
||||
<span className="relative grid size-[42px] shrink-0 place-items-center rounded-full bg-white/20">
|
||||
<Headset size={22} />
|
||||
</span>
|
||||
|
||||
<span className="relative hidden text-left leading-tight sm:block">
|
||||
<span className="block text-sm font-semibold whitespace-nowrap">
|
||||
👋 Need help?
|
||||
<span className="relative hidden text-left leading-tight sm:block">
|
||||
<span className="block text-sm font-semibold whitespace-nowrap">
|
||||
👋 Need help?
|
||||
</span>
|
||||
<span className="block text-[11px] whitespace-nowrap opacity-85">
|
||||
Chat with our team
|
||||
</span>
|
||||
</span>
|
||||
<span className="block text-[11px] whitespace-nowrap opacity-85">
|
||||
Chat with our team
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</Indicator>
|
||||
</button>
|
||||
</Indicator>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Transition>
|
||||
|
||||
115
apps/edr-freight-web/portal/src/hooks/useInvoicePayment.ts
Normal file
115
apps/edr-freight-web/portal/src/hooks/useInvoicePayment.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import type { AxiosError } from "axios";
|
||||
import { useState } from "react";
|
||||
|
||||
import { invoicesService } from "@/services/invoices.service";
|
||||
import {
|
||||
paymentsService,
|
||||
type InitiateResponse,
|
||||
type PaymentMethod,
|
||||
} from "@/services/payments.service";
|
||||
|
||||
/** How the invoice is charged — overridable for warehouse fee invoices. */
|
||||
type InitiateFn = (
|
||||
invoiceId: string,
|
||||
method: PaymentMethod,
|
||||
payerAccount?: string,
|
||||
) => Promise<InitiateResponse>;
|
||||
|
||||
const payViaBilling: InitiateFn = (invoiceId, method, payerAccount) =>
|
||||
invoicesService.pay(invoiceId, { method, platform: "web", payerAccount });
|
||||
|
||||
/** The server's message (`{ message }` / `{ message: [] }`), or a fallback. */
|
||||
function apiMessage(err: unknown, fallback: string): string {
|
||||
const message = (err as AxiosError<{ message?: string | string[] }>)?.response
|
||||
?.data?.message;
|
||||
const first = Array.isArray(message) ? message[0] : message;
|
||||
return first || fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* One payment flow for every "pay this invoice" entry point: initiate, then
|
||||
* either redirect to the provider or — for CAC Bank, an OTP debit with no
|
||||
* redirect — collect the SMS'd code and confirm it in-app. Pass `initiate` to
|
||||
* charge through a different endpoint (warehouse fee invoices); OTP
|
||||
* confirmation always goes through billing, which owns the intent either way.
|
||||
*/
|
||||
export function useInvoicePayment(initiate: InitiateFn = payViaBilling) {
|
||||
const [otpInvoiceId, setOtpInvoiceId] = useState<string | null>(null);
|
||||
const [otpMessage, setOtpMessage] = useState<string | undefined>();
|
||||
|
||||
const payMutation = useMutation({
|
||||
mutationFn: (vars: {
|
||||
invoiceId: string;
|
||||
method: PaymentMethod;
|
||||
payerAccount?: string;
|
||||
}) => initiate(vars.invoiceId, vars.method, vars.payerAccount),
|
||||
onSuccess: (data, vars) => {
|
||||
if (data?.clientAction?.type === "COLLECT_OTP") {
|
||||
setOtpMessage(
|
||||
data.clientAction.message ?? "Enter the OTP sent to your phone",
|
||||
);
|
||||
setOtpInvoiceId(vars.invoiceId);
|
||||
return;
|
||||
}
|
||||
window.location.href =
|
||||
data?.clientAction?.type === "REDIRECT" && data.clientAction.url
|
||||
? data.clientAction.url
|
||||
: paymentsService.checkoutUrlForInvoice({
|
||||
invoiceId: vars.invoiceId,
|
||||
method: vars.method,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const otpMutation = useMutation({
|
||||
mutationFn: (otp: string) =>
|
||||
invoicesService.confirmOtp(otpInvoiceId as string, otp),
|
||||
// Settled — reload so the invoice/booking re-reads its now-paid state.
|
||||
onSuccess: () => {
|
||||
setOtpInvoiceId(null);
|
||||
window.location.reload();
|
||||
},
|
||||
});
|
||||
|
||||
const reset = () => {
|
||||
payMutation.reset();
|
||||
otpMutation.reset();
|
||||
setOtpInvoiceId(null);
|
||||
};
|
||||
|
||||
return {
|
||||
processing: payMutation.isPending,
|
||||
error: payMutation.isError
|
||||
? apiMessage(
|
||||
payMutation.error,
|
||||
payMutation.error instanceof Error
|
||||
? payMutation.error.message
|
||||
: "Could not start payment. Please try again.",
|
||||
)
|
||||
: null,
|
||||
pay: (invoiceId: string, method: PaymentMethod, payerAccount?: string) =>
|
||||
payMutation.mutate({ invoiceId, method, payerAccount }),
|
||||
reset,
|
||||
/** Drives the modal's OTP step; `open` only for CAC Bank. */
|
||||
otp: {
|
||||
open: otpInvoiceId !== null,
|
||||
message: otpMessage,
|
||||
submitting: otpMutation.isPending,
|
||||
// A wrong/expired OTP is a 400 — keep the step open so the payer retries.
|
||||
error: otpMutation.isError
|
||||
? apiMessage(
|
||||
otpMutation.error,
|
||||
"Invalid or expired OTP. Please try again.",
|
||||
)
|
||||
: null,
|
||||
submit: (otp: string) => otpMutation.mutate(otp),
|
||||
cancel: () => {
|
||||
otpMutation.reset();
|
||||
setOtpInvoiceId(null);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type InvoicePaymentFlow = ReturnType<typeof useInvoicePayment>;
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Badge, Box, Button, Group, Stack, Text } from "@mantine/core";
|
||||
import {
|
||||
AlertTriangle,
|
||||
@@ -10,9 +10,8 @@ import {
|
||||
PackagePlus,
|
||||
} from "lucide-react";
|
||||
|
||||
import { api } from "@/services/api";
|
||||
import { ModalSafeWrapper } from "@/components/customer-actions/ModalSafeWrapper";
|
||||
import { paymentsService, type PaymentMethod } from "@/services/payments.service";
|
||||
import { useInvoicePayment } from "@/hooks/useInvoicePayment";
|
||||
import { invoicesService } from "@/services/invoices.service";
|
||||
import { isPayable } from "@/pages/billing/invoice-ui";
|
||||
import { PaymentMethodModal } from "@/pages/bookings/BookingDetailPage/components/PaymentMethodModal";
|
||||
@@ -60,29 +59,7 @@ export function ActionNeededSection({ items: base }: ActionNeededSectionProps) {
|
||||
isPayable(inv.status),
|
||||
)?.id;
|
||||
|
||||
const payMutation = useMutation({
|
||||
mutationFn: (method: PaymentMethod) => {
|
||||
if (!payableInvoiceId) {
|
||||
throw new Error(
|
||||
"No payable invoice found for this booking yet. Please refresh or contact support.",
|
||||
);
|
||||
}
|
||||
return api.invoices.pay.call({
|
||||
id: payableInvoiceId,
|
||||
payload: { method, platform: "web" },
|
||||
});
|
||||
},
|
||||
onSuccess: (data, method) => {
|
||||
const url =
|
||||
data?.clientAction?.type === "REDIRECT" && data.clientAction.url
|
||||
? data.clientAction.url
|
||||
: paymentsService.checkoutUrlForInvoice({
|
||||
invoiceId: payableInvoiceId!,
|
||||
method,
|
||||
});
|
||||
window.location.href = url;
|
||||
},
|
||||
});
|
||||
const pay = useInvoicePayment();
|
||||
|
||||
if (items.length === 0) return null;
|
||||
|
||||
@@ -189,21 +166,24 @@ export function ActionNeededSection({ items: base }: ActionNeededSectionProps) {
|
||||
<PaymentMethodModal
|
||||
opened={payItem !== null}
|
||||
onClose={() => {
|
||||
if (!payMutation.isPending) {
|
||||
if (!pay.processing) {
|
||||
setPayItem(null);
|
||||
payMutation.reset();
|
||||
pay.reset();
|
||||
}
|
||||
}}
|
||||
currency={undefined}
|
||||
processing={payMutation.isPending}
|
||||
processing={pay.processing}
|
||||
error={
|
||||
payMutation.isError
|
||||
? payMutation.error instanceof Error
|
||||
? payMutation.error.message
|
||||
: "Could not start payment. Please try again."
|
||||
: null
|
||||
pay.error ??
|
||||
(payItemInvoices.length > 0 && !payableInvoiceId
|
||||
? "No payable invoice found for this booking yet. Please refresh or contact support."
|
||||
: null)
|
||||
}
|
||||
otp={pay.otp}
|
||||
onConfirm={(method, payerAccount) =>
|
||||
payableInvoiceId &&
|
||||
pay.pay(payableInvoiceId, method, payerAccount)
|
||||
}
|
||||
onConfirm={(method) => payMutation.mutate(method)}
|
||||
/>
|
||||
</ModalSafeWrapper>
|
||||
</Card>
|
||||
|
||||
@@ -287,9 +287,31 @@ export default function SettingsPage() {
|
||||
icon={<Clock size={18} />}
|
||||
title="Changes submitted for review"
|
||||
>
|
||||
Your recent changes are awaiting administrator approval. Editing is
|
||||
disabled until the review is complete — you'll be notified once it's
|
||||
approved or if any changes are requested.
|
||||
Your recent changes are awaiting administrator approval. Company
|
||||
details and documents can't be edited until the review is complete —
|
||||
you'll be notified once it's approved or if any changes are
|
||||
requested. Your contact person, general manager and Power of
|
||||
Attorney stay editable.
|
||||
</Alert>
|
||||
)}
|
||||
{reviewStatus === "changes_requested" && (
|
||||
<Alert
|
||||
color="yellow"
|
||||
variant="light"
|
||||
icon={<AlertTriangle size={18} />}
|
||||
title="Changes requested on your submission"
|
||||
>
|
||||
<Stack gap={4}>
|
||||
{profile.reviewNote && (
|
||||
<Text size="sm">
|
||||
<strong>Reviewer note:</strong> {profile.reviewNote}
|
||||
</Text>
|
||||
)}
|
||||
<Text size="sm">
|
||||
Please update the requested details below and save again to
|
||||
resubmit for review.
|
||||
</Text>
|
||||
</Stack>
|
||||
</Alert>
|
||||
)}
|
||||
{reviewStatus === "rejected" && (
|
||||
@@ -358,9 +380,17 @@ export default function SettingsPage() {
|
||||
)}
|
||||
</Tabs.Panel>
|
||||
|
||||
{/* While a change request is pending, every panel's inputs + submit
|
||||
buttons are disabled via the native fieldset; tab switching stays
|
||||
enabled so the customer can still review what they submitted. */}
|
||||
{/* While a change request is pending, the reviewed panels' inputs +
|
||||
submit buttons are disabled via the native fieldset; tab switching
|
||||
stays enabled so the customer can still review what they
|
||||
submitted.
|
||||
|
||||
Personnel panels below (contact person, general manager, Power of
|
||||
Attorney) are deliberately outside the lock: the API applies those
|
||||
edits live rather than staging them, so locking them here would
|
||||
re-impose the approval wait the API no longer does. The PoA's
|
||||
delegation letter is still reviewed — that lock lives on the file
|
||||
itself, not the panel. */}
|
||||
<Tabs.Panel value="company">
|
||||
<Fieldset disabled={locked} variant="unstyled" p={0}>
|
||||
<TabCompanyProfile mode="edit" profile={profile} user={user ?? undefined} />
|
||||
@@ -368,19 +398,13 @@ export default function SettingsPage() {
|
||||
<OperationalServicesCard profile={profile} />
|
||||
</Tabs.Panel>
|
||||
<Tabs.Panel value="contact">
|
||||
<Fieldset disabled={locked} variant="unstyled" p={0}>
|
||||
<TabContactPerson profile={profile} mode="edit" />
|
||||
</Fieldset>
|
||||
<TabContactPerson profile={profile} mode="edit" />
|
||||
</Tabs.Panel>
|
||||
<Tabs.Panel value="gm">
|
||||
<Fieldset disabled={locked} variant="unstyled" p={0}>
|
||||
<TabGeneralManager profile={profile} mode="edit" />
|
||||
</Fieldset>
|
||||
<TabGeneralManager profile={profile} mode="edit" />
|
||||
</Tabs.Panel>
|
||||
<Tabs.Panel value="poa">
|
||||
<Fieldset disabled={locked} variant="unstyled" p={0}>
|
||||
<TabPowerOfAttorney profile={profile} mode="edit" />
|
||||
</Fieldset>
|
||||
<TabPowerOfAttorney profile={profile} mode="edit" />
|
||||
</Tabs.Panel>
|
||||
<Tabs.Panel value="documents">
|
||||
<Fieldset disabled={locked} variant="unstyled" p={0}>
|
||||
|
||||
@@ -33,7 +33,6 @@ import {
|
||||
buildOnboardingSchema,
|
||||
type CompanyStep,
|
||||
type FormData,
|
||||
hasPoaDetails,
|
||||
POA_DELEGATION_FILE_KEY,
|
||||
stepFields,
|
||||
} from "./companyProfileForm/schema";
|
||||
@@ -191,11 +190,7 @@ export default function CompanyProfileForm({
|
||||
formState: { errors },
|
||||
} = useForm<FormData>({
|
||||
resolver: zodResolver(
|
||||
buildOnboardingSchema(
|
||||
requirePoa,
|
||||
verifiedIdentity,
|
||||
identity?.passportRequired === true,
|
||||
),
|
||||
buildOnboardingSchema(identity?.passportRequired === true),
|
||||
),
|
||||
defaultValues: {
|
||||
companyName: "",
|
||||
@@ -321,7 +316,6 @@ export default function CompanyProfileForm({
|
||||
// them and re-enables editing.
|
||||
const [gmSameAsOwner, setGmSameAsOwner] = useState(false);
|
||||
const [contactSameAsGm, setContactSameAsGm] = useState(false);
|
||||
const [poaSameAsContact, setPoaSameAsContact] = useState(false);
|
||||
|
||||
// General Manager source. The company step's email/phone are seeded from
|
||||
// eTrade (and the account email) but stay editable, so the link reads the
|
||||
@@ -367,9 +361,6 @@ export default function CompanyProfileForm({
|
||||
const gmName = watch("generalManagerName");
|
||||
const gmEmail = watch("generalManagerEmail");
|
||||
const gmPhone = watch("generalManagerPhone");
|
||||
const contactName = watch("contactPersonName");
|
||||
const contactEmail = watch("contactPersonEmail");
|
||||
const contactPhone = watch("contactPersonPhone");
|
||||
|
||||
// While linked, mirror the source values into the (disabled) target fields so
|
||||
// the copy stays current even if the user goes back and edits the source.
|
||||
@@ -381,26 +372,6 @@ export default function CompanyProfileForm({
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [contactSameAsGm, gmName, gmEmail, gmPhone]);
|
||||
|
||||
// The contact-person step has no address of its own, so the linked PoA takes
|
||||
// the company's composed address. poaLocation (the city) stays typed on the
|
||||
// PoA step — the company step no longer has a location field to mirror.
|
||||
const companyAddress = watch("companyAddress");
|
||||
|
||||
useEffect(() => {
|
||||
if (!poaSameAsContact) return;
|
||||
setValue("poaName", contactName ?? "");
|
||||
setValue("poaEmail", contactEmail ?? "");
|
||||
setValue("poaPhone", contactPhone ?? "");
|
||||
setValue("poaAddress", companyAddress ?? "");
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [
|
||||
poaSameAsContact,
|
||||
contactName,
|
||||
contactEmail,
|
||||
contactPhone,
|
||||
companyAddress,
|
||||
]);
|
||||
|
||||
const toggleContactSameAsGm = (checked: boolean) => {
|
||||
setContactSameAsGm(checked);
|
||||
// Checked → the mirror effect fills the fields; unchecked → reset them.
|
||||
@@ -411,17 +382,6 @@ export default function CompanyProfileForm({
|
||||
}
|
||||
};
|
||||
|
||||
const togglePoaSameAsContact = (checked: boolean) => {
|
||||
setPoaSameAsContact(checked);
|
||||
if (!checked) {
|
||||
setValue("poaName", "");
|
||||
setValue("poaEmail", "");
|
||||
setValue("poaPhone", "");
|
||||
setValue("poaLocation", "");
|
||||
setValue("poaAddress", "");
|
||||
}
|
||||
};
|
||||
|
||||
// The DARS delegation paper ships in the same nationality document set as the
|
||||
// rest (the API guarantees it is there), but belongs on the PoA step next to
|
||||
// the details it evidences — so it's split out here and the Documents step
|
||||
@@ -551,7 +511,9 @@ export default function CompanyProfileForm({
|
||||
// for a freight forwarder, whose PoA itself is mandatory. The API enforces
|
||||
// the same rule on save, so skipping it here only costs the customer a
|
||||
// round-trip.
|
||||
const poaProvided = hasPoaDetails(watch());
|
||||
// A PoA exists exactly when one has been verified — the details are the
|
||||
// verification's output, so there is nothing else that could stand for one.
|
||||
const poaProvided = identity?.poa.verified ?? false;
|
||||
const delegationRequired = requirePoa || poaProvided;
|
||||
const delegationPresent =
|
||||
(uploadedDocumentKeys ?? []).includes(POA_DELEGATION_FILE_KEY) ||
|
||||
@@ -638,12 +600,7 @@ export default function CompanyProfileForm({
|
||||
setSaveError("Verify the company owner's identity with Fayda before continuing.");
|
||||
return;
|
||||
}
|
||||
if (
|
||||
step === "poa" &&
|
||||
verifiedIdentity &&
|
||||
requirePoa &&
|
||||
!identity?.poa.verified
|
||||
) {
|
||||
if (step === "poa" && requirePoa && !identity?.poa.verified) {
|
||||
setSaveError(
|
||||
"Freight forwarders act on other companies' behalf, so the Power of Attorney's identity must be verified with Fayda.",
|
||||
);
|
||||
@@ -876,71 +833,27 @@ export default function CompanyProfileForm({
|
||||
? "As a freight forwarder you act on other companies' behalf, so Power of Attorney details and the DARS delegation paper are required."
|
||||
: "Power of Attorney details are optional. Fill them in if you have them, or skip to continue. If you do enter a representative, upload the delegation paper authenticated by DARS."}
|
||||
</Text>
|
||||
{/* A representative acts for the company inside Ethiopia
|
||||
whoever owns it, so the PoA is proven with Fayda regardless of
|
||||
nationality — their name, email, phone and address all come
|
||||
from the verification and are never typed here. */}
|
||||
{identity && (
|
||||
<FaydaVerifyPanel
|
||||
subject="poa"
|
||||
title="Power of Attorney"
|
||||
state={identity.poa}
|
||||
required={identity.faydaRequired}
|
||||
required={requirePoa}
|
||||
onVerified={() => onIdentityChange?.()}
|
||||
/>
|
||||
)}
|
||||
{!verifiedIdentity && watch("contactPersonName") && (
|
||||
<LinkCheckboxCard
|
||||
checked={poaSameAsContact}
|
||||
onToggle={togglePoaSameAsContact}
|
||||
title="Same as contact person"
|
||||
description="Reuse the contact person's name, email and phone, plus the company's location and address. Uncheck to enter different details."
|
||||
/>
|
||||
)}
|
||||
{!verifiedIdentity && (
|
||||
<>
|
||||
<TextInput
|
||||
label="PoA Name"
|
||||
placeholder="Authorized Representative Name"
|
||||
error={errors.poaName?.message}
|
||||
{...register("poaName")}
|
||||
/>
|
||||
<SimpleGrid cols={2} spacing="md">
|
||||
<TextInput
|
||||
label="PoA Email"
|
||||
type="email"
|
||||
placeholder="poa@company.com"
|
||||
error={errors.poaEmail?.message}
|
||||
{...register("poaEmail")}
|
||||
/>
|
||||
<ControlledPhoneField
|
||||
control={control}
|
||||
name="poaPhone"
|
||||
label="PoA Phone"
|
||||
/>
|
||||
</SimpleGrid>
|
||||
<SimpleGrid cols={2} spacing="md">
|
||||
<TextInput
|
||||
label="PoA Location"
|
||||
placeholder="City, Country"
|
||||
error={errors.poaLocation?.message}
|
||||
{...register("poaLocation")}
|
||||
/>
|
||||
<TextInput
|
||||
label="PoA Address"
|
||||
placeholder="Full Address"
|
||||
error={errors.poaAddress?.message}
|
||||
{...register("poaAddress")}
|
||||
/>
|
||||
</SimpleGrid>
|
||||
</>
|
||||
)}
|
||||
{/* The city is the one field the Fayda address claim does not
|
||||
reliably decompose into, so it stays typed either way. */}
|
||||
{verifiedIdentity && (
|
||||
<TextInput
|
||||
label="PoA Location"
|
||||
placeholder="City, Country"
|
||||
error={errors.poaLocation?.message}
|
||||
{...register("poaLocation")}
|
||||
/>
|
||||
)}
|
||||
reliably decompose into, so it stays typed. */}
|
||||
<TextInput
|
||||
label="PoA Location"
|
||||
placeholder="City, Country"
|
||||
error={errors.poaLocation?.message}
|
||||
{...register("poaLocation")}
|
||||
/>
|
||||
|
||||
{poaDocumentSetting && (
|
||||
<>
|
||||
|
||||
@@ -37,10 +37,8 @@ export function buildPayload(
|
||||
generalManagerName: data.generalManagerName,
|
||||
generalManagerEmail: data.generalManagerEmail,
|
||||
generalManagerPhone: data.generalManagerPhone,
|
||||
poaName: data.poaName || undefined,
|
||||
poaPhone: data.poaPhone || undefined,
|
||||
poaAddress: data.poaAddress || undefined,
|
||||
poaEmail: data.poaEmail || undefined,
|
||||
// The representative's own details are written by their Fayda
|
||||
// verification, so the city is all the form has to send.
|
||||
poaLocation: data.poaLocation || undefined,
|
||||
},
|
||||
};
|
||||
@@ -88,13 +86,7 @@ export function stepPayload(
|
||||
contactPersonPhone: d.contactPersonPhone,
|
||||
};
|
||||
case "poa":
|
||||
return {
|
||||
poaName: d.poaName || undefined,
|
||||
poaPhone: d.poaPhone || undefined,
|
||||
poaEmail: d.poaEmail || undefined,
|
||||
poaLocation: d.poaLocation || undefined,
|
||||
poaAddress: d.poaAddress || undefined,
|
||||
};
|
||||
return { poaLocation: d.poaLocation || undefined };
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -92,58 +92,28 @@ export type FormData = z.infer<typeof onboardingSchema>;
|
||||
/** fileKey of the delegation letter uploaded on the Power of Attorney step. */
|
||||
export const POA_DELEGATION_FILE_KEY = "poa_delegation_letter";
|
||||
|
||||
export const POA_FIELDS = [
|
||||
"poaName",
|
||||
"poaPhone",
|
||||
"poaEmail",
|
||||
"poaLocation",
|
||||
"poaAddress",
|
||||
] as const satisfies readonly (keyof FormData)[];
|
||||
|
||||
/** True once the customer has entered any Power of Attorney detail. */
|
||||
export const hasPoaDetails = (d: Partial<FormData>) =>
|
||||
POA_FIELDS.some((f) => d[f]?.trim());
|
||||
|
||||
/**
|
||||
* A freight forwarder acts on other companies' behalf, so its PoA is mandatory
|
||||
* rather than optional. Everyone else keeps the optional PoA — but once they
|
||||
* start filling it in, the identifying fields have to be complete (the
|
||||
* delegation-letter upload is enforced alongside this, in CompanyProfileForm,
|
||||
* since files live outside the form state).
|
||||
* The PoA's identifying fields are never typed — they come from the Fayda
|
||||
* verification, whatever the company's nationality — so nothing here requires
|
||||
* them. A freight forwarder's mandatory PoA is gated on the verification
|
||||
* itself, and its delegation letter alongside it, both in CompanyProfileForm
|
||||
* (files live outside form state).
|
||||
*
|
||||
* That leaves the owner's passport number as the only conditional field.
|
||||
*/
|
||||
export function buildOnboardingSchema(
|
||||
requirePoa: boolean,
|
||||
/**
|
||||
* True when the PoA's identity fields come from a Fayda verification rather
|
||||
* than the form (Ethiopian companies). Requiring them here would fail
|
||||
* validation against inputs the step no longer renders — the verification
|
||||
* itself is what the step gates on instead.
|
||||
*/
|
||||
faydaOwnedPoa = false,
|
||||
/** True for a foreign company: the owner's passport number is mandatory. */
|
||||
passportRequired = false,
|
||||
) {
|
||||
const poaRequired = requirePoa && !faydaOwnedPoa;
|
||||
if (!poaRequired && !passportRequired) return onboardingSchema;
|
||||
if (!passportRequired) return onboardingSchema;
|
||||
return onboardingSchema.superRefine((d, ctx) => {
|
||||
const required: [keyof FormData, string][] = [];
|
||||
if (poaRequired) {
|
||||
required.push(
|
||||
["poaName", "PoA name is required for freight forwarders"],
|
||||
["poaEmail", "PoA email is required for freight forwarders"],
|
||||
["poaPhone", "PoA phone is required for freight forwarders"],
|
||||
);
|
||||
}
|
||||
if (passportRequired) {
|
||||
required.push([
|
||||
"ownerPassportNumber",
|
||||
"The owner's passport number is required",
|
||||
]);
|
||||
}
|
||||
for (const [path, message] of required) {
|
||||
if (!d[path]?.trim()) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, path: [path], message });
|
||||
}
|
||||
if (!d.ownerPassportNumber?.trim()) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["ownerPassportNumber"],
|
||||
message: "The owner's passport number is required",
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -180,7 +150,7 @@ export const stepFields: Record<CompanyStep, (keyof FormData)[]> = {
|
||||
"contactPersonEmail",
|
||||
"contactPersonPhone",
|
||||
],
|
||||
poa: [...POA_FIELDS],
|
||||
poa: ["poaLocation"],
|
||||
documents: [],
|
||||
additional: [],
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
Alert,
|
||||
Box,
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
Divider,
|
||||
Group,
|
||||
Loader,
|
||||
Modal,
|
||||
Paper,
|
||||
SimpleGrid,
|
||||
Stack,
|
||||
@@ -27,10 +28,7 @@ import toast from "react-hot-toast";
|
||||
|
||||
import { api } from "@/services/api";
|
||||
import { invoicesService } from "@/services/invoices.service";
|
||||
import {
|
||||
paymentsService,
|
||||
type PaymentMethod,
|
||||
} from "@/services/payments.service";
|
||||
import { useInvoicePayment } from "@/hooks/useInvoicePayment";
|
||||
import { warehouseInvoicesService } from "@/services/warehouse-invoices.service";
|
||||
import { PaymentMethodModal } from "@/pages/bookings/BookingDetailPage/components/PaymentMethodModal";
|
||||
import { saveBlob } from "@/utils/download";
|
||||
@@ -72,21 +70,17 @@ export default function InvoiceDetailPage() {
|
||||
} = useQuery(api.invoices.get.queryOptions({ input: { id } }));
|
||||
|
||||
const [payModalOpen, setPayModalOpen] = useState(false);
|
||||
// CBE bill payment: the bill reference to pay at any CBE channel (no redirect).
|
||||
const [billAction, setBillAction] = useState<{
|
||||
billReference?: string;
|
||||
instructions?: string;
|
||||
expiresAt?: string;
|
||||
} | null>(null);
|
||||
|
||||
// Ownership-checked: POST /billing/my-invoices/:id/pay only ever charges
|
||||
// one of the signed-in customer's own invoices (unlike the admin-facing
|
||||
// /payments/initiate, which takes any invoiceId with no ownership check).
|
||||
const payMutation = useMutation({
|
||||
mutationFn: (method: PaymentMethod) =>
|
||||
api.invoices.pay.call({ id, payload: { method, platform: "web" } }),
|
||||
onSuccess: (data, method) => {
|
||||
const redirectUrl =
|
||||
data?.clientAction?.type === "REDIRECT" && data.clientAction.url
|
||||
? data.clientAction.url
|
||||
: paymentsService.checkoutUrlForInvoice({ invoiceId: id, method });
|
||||
window.location.href = redirectUrl;
|
||||
},
|
||||
});
|
||||
const pay = useInvoicePayment();
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -249,7 +243,7 @@ export default function InvoiceDetailPage() {
|
||||
radius="md"
|
||||
size="md"
|
||||
leftSection={<CreditCard size={16} />}
|
||||
loading={payMutation.isPending}
|
||||
loading={pay.processing}
|
||||
onClick={handlePay}
|
||||
styles={{
|
||||
root: { fontWeight: 600, height: 42, paddingInline: 18 },
|
||||
@@ -376,23 +370,76 @@ export default function InvoiceDetailPage() {
|
||||
<PaymentMethodModal
|
||||
opened={payModalOpen}
|
||||
onClose={() => {
|
||||
if (!payMutation.isPending) {
|
||||
if (!pay.processing) {
|
||||
setPayModalOpen(false);
|
||||
payMutation.reset();
|
||||
pay.reset();
|
||||
}
|
||||
}}
|
||||
amountLabel={formatCurrency(amountDue, invoice.currency)}
|
||||
currency={invoice.currency}
|
||||
processing={payMutation.isPending}
|
||||
error={
|
||||
payMutation.isError
|
||||
? payMutation.error instanceof Error
|
||||
? payMutation.error.message
|
||||
: "Could not start payment. Please try again."
|
||||
: null
|
||||
processing={pay.processing}
|
||||
error={pay.error}
|
||||
otp={pay.otp}
|
||||
onConfirm={(method, payerAccount) =>
|
||||
pay.pay(id, method, payerAccount)
|
||||
}
|
||||
onConfirm={(method) => payMutation.mutate(method)}
|
||||
/>
|
||||
|
||||
{/* CBE bill payment — show the bill number; settlement arrives via CBE, not the browser */}
|
||||
<Modal
|
||||
opened={!!billAction}
|
||||
onClose={() => setBillAction(null)}
|
||||
centered
|
||||
radius={18}
|
||||
size={440}
|
||||
title={<Text fw={800}>Pay at CBE</Text>}
|
||||
>
|
||||
<Stack gap="sm">
|
||||
<Text fz="sm" c={MUTED}>
|
||||
{billAction?.instructions ??
|
||||
"Pay this bill at any CBE branch, the CBE Birr app, mobile banking or USSD."}
|
||||
</Text>
|
||||
<Group
|
||||
justify="space-between"
|
||||
px={16}
|
||||
py={13}
|
||||
style={{ borderRadius: 12, border: `1px solid ${BORDER}` }}
|
||||
>
|
||||
<Text ff="monospace" fz={24} fw={800} c={INK} style={{ letterSpacing: 3 }}>
|
||||
{billAction?.billReference}
|
||||
</Text>
|
||||
<Button
|
||||
variant="light"
|
||||
size="xs"
|
||||
onClick={() => {
|
||||
if (billAction?.billReference) {
|
||||
navigator.clipboard?.writeText(billAction.billReference);
|
||||
toast.success("Bill number copied");
|
||||
}
|
||||
}}
|
||||
>
|
||||
Copy
|
||||
</Button>
|
||||
</Group>
|
||||
<Text fz="sm" c={MUTED}>
|
||||
Amount due:{" "}
|
||||
<Text span fw={700} c={INK}>
|
||||
{formatCurrency(amountDue, invoice.currency)}
|
||||
</Text>
|
||||
</Text>
|
||||
{billAction?.expiresAt && (
|
||||
<Text fz="sm" c={MUTED}>
|
||||
Pay before:{" "}
|
||||
<Text span fw={700} c={INK}>
|
||||
{fmtDate(billAction.expiresAt)}
|
||||
</Text>
|
||||
</Text>
|
||||
)}
|
||||
<Text fz="xs" c={MUTED}>
|
||||
The invoice updates automatically once CBE confirms your payment.
|
||||
</Text>
|
||||
</Stack>
|
||||
</Modal>
|
||||
</Stack>
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -4,11 +4,7 @@ import { Clock, CreditCard, FileText, LayoutGrid, Truck } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { api } from "@/services/api";
|
||||
import { useFileViewer } from "@/hooks/useFileViewer";
|
||||
import { invoicesService } from "@/services/invoices.service";
|
||||
import { paymentsService, type PaymentMethod } from "@/services/payments.service";
|
||||
import { isPayable } from "@/pages/billing/invoice-ui";
|
||||
import type { Freight } from "@edr/types";
|
||||
|
||||
import { ApproveDeliveryButton } from "../delivery/ApproveDeliveryButton";
|
||||
@@ -41,6 +37,7 @@ import { StatusHero } from "./components/StatusHero";
|
||||
import { SupportCard } from "./components/SupportCard";
|
||||
import { fmtDate, isNegative, priceTotal } from "./utils";
|
||||
import { useScrollToHash } from "@/hooks/useScrollToHash";
|
||||
import { useBookingPayment } from "@/pages/bookings/payments/useBookingPayment";
|
||||
|
||||
export function ReadonlyBookingView({
|
||||
booking,
|
||||
@@ -53,7 +50,6 @@ export function ReadonlyBookingView({
|
||||
// Deep-link support: e.g. /bookings/:id#warehouse-payments from an invoice.
|
||||
useScrollToHash();
|
||||
const status = booking.status as string;
|
||||
const [payModalOpen, setPayModalOpen] = useState(false);
|
||||
const { viewer } = useFileViewer();
|
||||
|
||||
// Re-book opens the New Shipment Booking form for the same contract, not the
|
||||
@@ -63,44 +59,11 @@ export function ReadonlyBookingView({
|
||||
: "/contracts/new";
|
||||
const onRebook = () => navigate(rebookTo);
|
||||
|
||||
// Billing is invoice-centric — resolve the booking's currently payable
|
||||
// invoice (same query/key BookingPaymentPanel uses, so this shares its
|
||||
// cache) and pay it through the ownership-checked portal route.
|
||||
const { data: bookingInvoices = [] } = useQuery({
|
||||
queryKey: ["booking-invoices", booking.id],
|
||||
queryFn: () => invoicesService.listForSource("booking", booking.id),
|
||||
});
|
||||
const payableInvoiceId = bookingInvoices.find((inv) =>
|
||||
isPayable(inv.status),
|
||||
)?.id;
|
||||
|
||||
// POST /billing/my-invoices/:id/pay creates the intent and returns the
|
||||
// provider's redirect URL (clientAction.url). Send the browser straight
|
||||
// there; fall back to the public /payments/checkout page if no redirect
|
||||
// URL came back.
|
||||
const payMutation = useMutation({
|
||||
mutationFn: (method: PaymentMethod) => {
|
||||
if (!payableInvoiceId) {
|
||||
throw new Error(
|
||||
"No payable invoice found for this booking yet. Please refresh or contact support.",
|
||||
);
|
||||
}
|
||||
return api.invoices.pay.call({
|
||||
id: payableInvoiceId,
|
||||
payload: { method, platform: "web" },
|
||||
});
|
||||
},
|
||||
onSuccess: (data, method) => {
|
||||
const redirectUrl =
|
||||
data?.clientAction?.type === "REDIRECT" && data.clientAction.url
|
||||
? data.clientAction.url
|
||||
: paymentsService.checkoutUrlForInvoice({
|
||||
invoiceId: payableInvoiceId!,
|
||||
method,
|
||||
});
|
||||
window.location.href = redirectUrl;
|
||||
},
|
||||
});
|
||||
// Billing is invoice-centric — the shared hook resolves the booking's
|
||||
// currently payable invoice (same query/key BookingPaymentPanel uses, so it
|
||||
// shares that cache), charges it through the ownership-checked portal route,
|
||||
// and handles redirect vs CAC Bank OTP.
|
||||
const pay = useBookingPayment(booking.id);
|
||||
|
||||
const pricing = booking.pricingBreakdown;
|
||||
// A general contract is paid once it's FULLY_EXECUTED (signed) — it never
|
||||
@@ -171,7 +134,7 @@ export function ReadonlyBookingView({
|
||||
green
|
||||
icon={<CreditCard size={16} />}
|
||||
label="Pay now"
|
||||
onClick={() => setPayModalOpen(true)}
|
||||
onClick={pay.open}
|
||||
/>
|
||||
)}
|
||||
</Group>
|
||||
@@ -276,8 +239,8 @@ export function ReadonlyBookingView({
|
||||
<BookingPaymentPanel
|
||||
booking={booking}
|
||||
pricing={pricing}
|
||||
onPay={() => setPayModalOpen(true)}
|
||||
paying={payMutation.isPending}
|
||||
onPay={pay.open}
|
||||
paying={pay.processing}
|
||||
showCountdown={showCountdown}
|
||||
/>
|
||||
<ScheduleCard
|
||||
@@ -327,24 +290,14 @@ export function ReadonlyBookingView({
|
||||
</Tabs>
|
||||
|
||||
<PaymentMethodModal
|
||||
opened={payModalOpen}
|
||||
onClose={() => {
|
||||
if (!payMutation.isPending) {
|
||||
setPayModalOpen(false);
|
||||
payMutation.reset();
|
||||
}
|
||||
}}
|
||||
opened={pay.modalOpen}
|
||||
onClose={pay.close}
|
||||
amountLabel={pricing ? priceTotal(pricing) : undefined}
|
||||
currency={pricing?.currency ?? booking.paymentCurrency}
|
||||
processing={payMutation.isPending}
|
||||
error={
|
||||
payMutation.isError
|
||||
? payMutation.error instanceof Error
|
||||
? payMutation.error.message
|
||||
: "Could not start payment. Please try again."
|
||||
: null
|
||||
}
|
||||
onConfirm={(method) => payMutation.mutate(method)}
|
||||
processing={pay.processing}
|
||||
error={pay.error}
|
||||
otp={pay.otp}
|
||||
onConfirm={pay.confirm}
|
||||
/>
|
||||
{viewer}
|
||||
</PageShell>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Upload, Download, AlertCircle, CheckCircle, AlertTriangle } from "lucid
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
|
||||
import { client } from "@/utils/api";
|
||||
import { URL_CONSTANTS } from "@/constants/URLS";
|
||||
import { generateTruckAssignmentTemplate, parseTruckAssignmentFile } from "@/utils/truck-assignment-template";
|
||||
|
||||
interface BulkTruckUploadModalProps {
|
||||
@@ -32,7 +33,7 @@ export function BulkTruckUploadModal({
|
||||
|
||||
const uploadMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const { data } = await client.post(`/bookings/${bookingId}/customer-trucks/bulk`, {
|
||||
const { data } = await client.post(URL_CONSTANTS.BOOKINGS.CUSTOMER_TRUCKS_BULK(bookingId), {
|
||||
trucks: parsed,
|
||||
});
|
||||
return data;
|
||||
|
||||
@@ -1,20 +1,32 @@
|
||||
import { Box, Button, Group, Image, Modal, Stack, Text } from "@mantine/core";
|
||||
import { Check, ShieldCheck } from "lucide-react";
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
Group,
|
||||
Image,
|
||||
Modal,
|
||||
PinInput,
|
||||
Stack,
|
||||
Text,
|
||||
TextInput,
|
||||
} from "@mantine/core";
|
||||
import { Check, Landmark, ShieldCheck } from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import type { InvoicePaymentFlow } from "@/hooks/useInvoicePayment";
|
||||
import type { PaymentMethod } from "@/services/payments.service";
|
||||
|
||||
interface ProviderOption {
|
||||
method: PaymentMethod;
|
||||
label: string;
|
||||
description: string;
|
||||
logo: string;
|
||||
/** Logo asset; falls back to a bank glyph when the provider has none. */
|
||||
logo?: string;
|
||||
/** Currencies this provider settles in. */
|
||||
currencies: string[];
|
||||
accent: string;
|
||||
}
|
||||
|
||||
// Only Telebirr and Waafi are enabled for now.
|
||||
// Only Telebirr, Waafi and CBE bill payment are enabled for now.
|
||||
const PROVIDERS: ProviderOption[] = [
|
||||
{
|
||||
method: "TELEBIRR",
|
||||
@@ -32,8 +44,26 @@ const PROVIDERS: ProviderOption[] = [
|
||||
currencies: ["USD"],
|
||||
accent: "#2E5B96",
|
||||
},
|
||||
{
|
||||
method: "CAC_BANK",
|
||||
label: "CAC Bank",
|
||||
description: "Djibouti bank debit · confirmed by SMS OTP",
|
||||
currencies: ["USD"],
|
||||
accent: "#8A5A17",
|
||||
},
|
||||
{
|
||||
method: "CBE_BILL",
|
||||
label: "CBE bill payment",
|
||||
description: "Pay at any CBE branch, app or USSD · ETB",
|
||||
logo: "/assets/edr-logo.png",
|
||||
currencies: ["ETB"],
|
||||
accent: "#5B2D8C",
|
||||
},
|
||||
];
|
||||
|
||||
/** Providers that debit against an SMS OTP instead of redirecting to a page. */
|
||||
const isOtpMethod = (method: PaymentMethod) => method === "CAC_BANK";
|
||||
|
||||
/**
|
||||
* Pick the provider that settles in the booking's currency. USD → Waafi,
|
||||
* ETB → Telebirr. Falls back to the first provider when unknown.
|
||||
@@ -91,13 +121,27 @@ function ProviderRow({
|
||||
backgroundColor: "#fff",
|
||||
}}
|
||||
>
|
||||
<Image
|
||||
src={option.logo}
|
||||
alt={`${option.label} logo`}
|
||||
w={52}
|
||||
h={52}
|
||||
fit="cover"
|
||||
/>
|
||||
{option.logo ? (
|
||||
<Image
|
||||
src={option.logo}
|
||||
alt={`${option.label} logo`}
|
||||
w={52}
|
||||
h={52}
|
||||
fit="cover"
|
||||
/>
|
||||
) : (
|
||||
<Box
|
||||
style={{
|
||||
width: 52,
|
||||
height: 52,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
<Landmark size={24} color={option.accent} />
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
<Box style={{ flex: 1, minWidth: 0 }}>
|
||||
<Text fz="15px" fw={800} c="#10202F" tt="capitalize">
|
||||
@@ -135,6 +179,7 @@ export function PaymentMethodModal({
|
||||
onConfirm,
|
||||
processing,
|
||||
error,
|
||||
otp,
|
||||
}: {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
@@ -142,12 +187,19 @@ export function PaymentMethodModal({
|
||||
amountLabel?: string;
|
||||
/** Booking payment currency — drives which provider is shown (USD → Waafi, ETB → Telebirr). */
|
||||
currency?: string | null;
|
||||
onConfirm: (method: PaymentMethod) => void;
|
||||
onConfirm: (method: PaymentMethod, payerAccount?: string) => void;
|
||||
processing?: boolean;
|
||||
error?: string | null;
|
||||
/** CAC Bank OTP step, from `useInvoicePayment`. Omit to disable OTP providers. */
|
||||
otp?: InvoicePaymentFlow["otp"];
|
||||
}) {
|
||||
const providers = useMemo(() => providersForCurrency(currency), [currency]);
|
||||
const providers = useMemo(
|
||||
() => providersForCurrency(currency).filter((p) => otp || !isOtpMethod(p.method)),
|
||||
[currency, otp],
|
||||
);
|
||||
const [method, setMethod] = useState<PaymentMethod>(providers[0].method);
|
||||
const [mobile, setMobile] = useState("");
|
||||
const [code, setCode] = useState("");
|
||||
|
||||
// Keep the selection valid when the currency (and therefore provider list) changes.
|
||||
useEffect(() => {
|
||||
@@ -156,6 +208,89 @@ export function PaymentMethodModal({
|
||||
}
|
||||
}, [providers, method]);
|
||||
|
||||
// A fresh OTP round always starts empty.
|
||||
useEffect(() => {
|
||||
if (otp?.open) setCode("");
|
||||
}, [otp?.open]);
|
||||
|
||||
// CAC Bank debits the account behind this number and SMSes the OTP to it.
|
||||
const needsMobile = isOtpMethod(method);
|
||||
const canSubmit = !needsMobile || mobile.trim().length > 0;
|
||||
|
||||
if (otp?.open) {
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={otp.cancel}
|
||||
centered
|
||||
radius={18}
|
||||
size={420}
|
||||
padding={0}
|
||||
withCloseButton={false}
|
||||
// A stray click must not drop the payer out of a live OTP window —
|
||||
// Cancel is the only way back.
|
||||
closeOnClickOutside={false}
|
||||
overlayProps={{ backgroundOpacity: 0.45, blur: 3 }}
|
||||
>
|
||||
<Box px={24} py={24}>
|
||||
<Text fw={800} fz="18px" c="#10202F">
|
||||
Enter OTP
|
||||
</Text>
|
||||
<Text mt={4} fz="13px" c="#7A8794">
|
||||
{otp.message}
|
||||
</Text>
|
||||
|
||||
<Box mt={18}>
|
||||
<PinInput
|
||||
length={6}
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
oneTimeCode
|
||||
value={code}
|
||||
onChange={setCode}
|
||||
onComplete={(value) => otp.submit(value)}
|
||||
aria-label="One-time password"
|
||||
/>
|
||||
</Box>
|
||||
|
||||
{otp.error && (
|
||||
<Text mt={10} fz="12.5px" c="#C0392B" fw={600}>
|
||||
{otp.error}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
<Group gap={10} wrap="nowrap" mt={20}>
|
||||
<Button
|
||||
variant="default"
|
||||
radius={12}
|
||||
onClick={otp.cancel}
|
||||
disabled={otp.submitting}
|
||||
styles={{
|
||||
root: { height: 46, flex: "0 0 38%" },
|
||||
label: { fontSize: 14, fontWeight: 700, color: "#475569" },
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
radius={12}
|
||||
color="edr-green"
|
||||
loading={otp.submitting}
|
||||
disabled={otp.submitting || code.trim().length === 0}
|
||||
onClick={() => otp.submit(code.trim())}
|
||||
styles={{
|
||||
root: { height: 46, flex: 1 },
|
||||
label: { fontSize: 14, fontWeight: 800 },
|
||||
}}
|
||||
>
|
||||
Confirm payment
|
||||
</Button>
|
||||
</Group>
|
||||
</Box>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
@@ -215,6 +350,22 @@ export function PaymentMethodModal({
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
|
||||
{needsMobile && (
|
||||
<TextInput
|
||||
mt={12}
|
||||
label="Mobile number"
|
||||
description="CAC Bank sends a one-time password to this number to authorise the debit."
|
||||
placeholder="77xxxxxx"
|
||||
value={mobile}
|
||||
onChange={(e) => setMobile(e.currentTarget.value)}
|
||||
disabled={processing}
|
||||
styles={{
|
||||
label: { fontSize: 12.5, fontWeight: 700, color: "#10202F" },
|
||||
description: { fontSize: 11.5 },
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* Footer */}
|
||||
@@ -228,7 +379,9 @@ export function PaymentMethodModal({
|
||||
<Group gap={6} align="center" justify="center" mb={12}>
|
||||
<ShieldCheck size={14} color="#0A8A5F" />
|
||||
<Text fz="11.5px" c="#7A8794">
|
||||
Secured · you'll be redirected to your provider to pay
|
||||
{needsMobile
|
||||
? "Secured · you'll confirm with the OTP sent to your phone"
|
||||
: "Secured · you'll be redirected to your provider to pay"}
|
||||
</Text>
|
||||
</Group>
|
||||
|
||||
@@ -248,15 +401,21 @@ export function PaymentMethodModal({
|
||||
<Button
|
||||
radius={12}
|
||||
color="edr-green"
|
||||
disabled={processing}
|
||||
disabled={processing || !canSubmit}
|
||||
loading={processing}
|
||||
onClick={() => onConfirm(method)}
|
||||
onClick={() =>
|
||||
onConfirm(method, needsMobile ? mobile.trim() : undefined)
|
||||
}
|
||||
styles={{
|
||||
root: { height: 48, flex: 1 },
|
||||
label: { fontSize: 14, fontWeight: 800 },
|
||||
}}
|
||||
>
|
||||
{processing ? "Redirecting…" : "Continue to payment"}
|
||||
{processing
|
||||
? needsMobile
|
||||
? "Sending OTP…"
|
||||
: "Redirecting…"
|
||||
: "Continue to payment"}
|
||||
</Button>
|
||||
</Group>
|
||||
</Box>
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { ActionIcon, Box, Button, Group, Stack, Text } from "@mantine/core";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { CreditCard, Download, FileText, Receipt } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
import { paymentsService, type PaymentMethod } from "@/services/payments.service";
|
||||
import { useInvoicePayment } from "@/hooks/useInvoicePayment";
|
||||
import {
|
||||
warehouseInvoicesService,
|
||||
type PortalWarehouseInvoice,
|
||||
@@ -67,36 +67,20 @@ export function WarehousePaymentsSection({ bookingId }: { bookingId: string }) {
|
||||
|
||||
const [payInvoice, setPayInvoice] = useState<PortalWarehouseInvoice | null>(null);
|
||||
|
||||
const payMutation = useMutation({
|
||||
mutationFn: (method: PaymentMethod) => {
|
||||
if (!payInvoice) throw new Error("No invoice selected for payment.");
|
||||
return warehouseInvoicesService.payOnline(payInvoice.id, {
|
||||
method,
|
||||
platform: "web",
|
||||
});
|
||||
},
|
||||
onSuccess: (data, method) => {
|
||||
if (!payInvoice) return;
|
||||
// Redirect to the provider (or the fallback checkout page) — same as the
|
||||
// booking "Pay now" flow, so behaviour is identical everywhere.
|
||||
const redirectUrl =
|
||||
data?.clientAction?.type === "REDIRECT" && data.clientAction.url
|
||||
? data.clientAction.url
|
||||
: paymentsService.checkoutUrlForInvoice({ invoiceId: payInvoice.id, method });
|
||||
window.location.href = redirectUrl;
|
||||
},
|
||||
});
|
||||
|
||||
const payError = payMutation.isError
|
||||
? payMutation.error instanceof Error
|
||||
? payMutation.error.message
|
||||
: "Could not start payment. Please try again."
|
||||
: null;
|
||||
// Warehouse fees are charged through the warehouse route, but they are the
|
||||
// same central invoices — so redirect vs CAC Bank OTP is the shared flow.
|
||||
const pay = useInvoicePayment((invoiceId, method, payerAccount) =>
|
||||
warehouseInvoicesService.payOnline(invoiceId, {
|
||||
method,
|
||||
platform: "web",
|
||||
payerAccount,
|
||||
}),
|
||||
);
|
||||
|
||||
const closePayModal = () => {
|
||||
if (!payMutation.isPending) {
|
||||
if (!pay.processing) {
|
||||
setPayInvoice(null);
|
||||
payMutation.reset();
|
||||
pay.reset();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -253,9 +237,12 @@ export function WarehousePaymentsSection({ bookingId }: { bookingId: string }) {
|
||||
payInvoice ? money(payInvoice.balanceAmount, payInvoice.currency) : undefined
|
||||
}
|
||||
currency={payInvoice?.currency}
|
||||
onConfirm={(method) => payMutation.mutate(method)}
|
||||
processing={payMutation.isPending}
|
||||
error={payError}
|
||||
onConfirm={(method, payerAccount) =>
|
||||
payInvoice && pay.pay(payInvoice.id, method, payerAccount)
|
||||
}
|
||||
processing={pay.processing}
|
||||
error={pay.error}
|
||||
otp={pay.otp}
|
||||
/>
|
||||
</SectionCard>
|
||||
);
|
||||
|
||||
@@ -55,6 +55,7 @@ export function PayNowButton({
|
||||
currency={pricing?.currency ?? booking.paymentCurrency}
|
||||
processing={pay.processing}
|
||||
error={pay.error}
|
||||
otp={pay.otp}
|
||||
onConfirm={pay.confirm}
|
||||
/>
|
||||
</ModalSafeWrapper>
|
||||
|
||||
@@ -1,23 +1,22 @@
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
|
||||
import { api } from "@/services/api";
|
||||
import {
|
||||
paymentsService,
|
||||
type PaymentMethod,
|
||||
} from "@/services/payments.service";
|
||||
import { useInvoicePayment } from "@/hooks/useInvoicePayment";
|
||||
import { type PaymentMethod } from "@/services/payments.service";
|
||||
import { invoicesService } from "@/services/invoices.service";
|
||||
import { isPayable } from "@/pages/billing/invoice-ui";
|
||||
|
||||
/**
|
||||
* Shared payment flow for a single booking: opens the method modal, fires
|
||||
* POST /billing/my-invoices/:id/pay for the booking's currently payable
|
||||
* invoice, and redirects the browser to the provider (or the fallback
|
||||
* checkout page). Reused by the booking detail page, the booking list, and
|
||||
* the home page so "Pay now" behaves identically everywhere.
|
||||
* invoice, and redirects the browser to the provider (or, for CAC Bank, an
|
||||
* OTP debit with no redirect, collects the SMS'd code in the modal). Reused by
|
||||
* the booking detail page, the booking list, and the home page so "Pay now"
|
||||
* behaves identically everywhere.
|
||||
*/
|
||||
export function useBookingPayment(bookingId: string) {
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [noInvoice, setNoInvoice] = useState(false);
|
||||
|
||||
const { data: invoices = [] } = useQuery({
|
||||
queryKey: ["booking-invoices", bookingId],
|
||||
@@ -25,51 +24,34 @@ export function useBookingPayment(bookingId: string) {
|
||||
});
|
||||
const payableInvoiceId = invoices.find((inv) => isPayable(inv.status))?.id;
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: (method: PaymentMethod) => {
|
||||
if (!payableInvoiceId) {
|
||||
throw new Error(
|
||||
"No payable invoice found for this booking yet. Please refresh or contact support.",
|
||||
);
|
||||
}
|
||||
return api.invoices.pay.call({
|
||||
id: payableInvoiceId,
|
||||
payload: { method, platform: "web" },
|
||||
});
|
||||
},
|
||||
onSuccess: (data, method) => {
|
||||
const redirectUrl =
|
||||
data?.clientAction?.type === "REDIRECT" && data.clientAction.url
|
||||
? data.clientAction.url
|
||||
: paymentsService.checkoutUrlForInvoice({
|
||||
invoiceId: payableInvoiceId!,
|
||||
method,
|
||||
});
|
||||
window.location.href = redirectUrl;
|
||||
},
|
||||
});
|
||||
const flow = useInvoicePayment();
|
||||
|
||||
const open = () => setModalOpen(true);
|
||||
|
||||
const close = () => {
|
||||
if (!mutation.isPending) {
|
||||
if (!flow.processing) {
|
||||
setModalOpen(false);
|
||||
mutation.reset();
|
||||
setNoInvoice(false);
|
||||
flow.reset();
|
||||
}
|
||||
};
|
||||
|
||||
const error = mutation.isError
|
||||
? mutation.error instanceof Error
|
||||
? mutation.error.message
|
||||
: "Could not start payment. Please try again."
|
||||
: null;
|
||||
|
||||
return {
|
||||
modalOpen,
|
||||
open,
|
||||
close,
|
||||
processing: mutation.isPending,
|
||||
error,
|
||||
confirm: (method: PaymentMethod) => mutation.mutate(method),
|
||||
processing: flow.processing,
|
||||
error: noInvoice
|
||||
? "No payable invoice found for this booking yet. Please refresh or contact support."
|
||||
: flow.error,
|
||||
otp: flow.otp,
|
||||
confirm: (method: PaymentMethod, payerAccount?: string) => {
|
||||
if (!payableInvoiceId) {
|
||||
setNoInvoice(true);
|
||||
return;
|
||||
}
|
||||
setNoInvoice(false);
|
||||
flow.pay(payableInvoiceId, method, payerAccount);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -39,20 +39,15 @@ import {
|
||||
type LicenseFile,
|
||||
type LicenseFileStatus,
|
||||
} from "@/services/companies.service";
|
||||
import { ControlledPhoneField, isValidPhone } from "@/components/PhoneField";
|
||||
import FaydaVerifyPanel from "@/components/FaydaVerifyPanel";
|
||||
import { verifaydaService } from "@/services/verifayda.service";
|
||||
import type { ProfileResponse } from "@/types/profile";
|
||||
|
||||
// The representative's name, email, phone and address all come from their
|
||||
// Fayda verification — a PoA is always an Ethiopian holding one — so the city
|
||||
// is the only detail this form owns.
|
||||
const schema = z.object({
|
||||
poaName: z.string().optional(),
|
||||
poaEmail: z.string().optional(),
|
||||
poaPhone: z
|
||||
.string()
|
||||
.optional()
|
||||
.refine((v) => !v || isValidPhone(v), "Enter a valid phone number"),
|
||||
poaLocation: z.string().optional(),
|
||||
poaAddress: z.string().optional(),
|
||||
});
|
||||
|
||||
type FormData = z.infer<typeof schema>;
|
||||
@@ -98,22 +93,15 @@ export default function TabPowerOfAttorney({
|
||||
const { view, viewer } = useFileViewer();
|
||||
const uploadInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const defaultValues = useMemo((): FormData => {
|
||||
return {
|
||||
poaName: profile.poaName ?? "",
|
||||
poaEmail: profile.poaEmail ?? "",
|
||||
poaPhone: profile.poaPhone ?? "",
|
||||
poaLocation: profile.poaLocation ?? "",
|
||||
poaAddress: profile.poaAddress ?? "",
|
||||
};
|
||||
}, [profile]);
|
||||
const defaultValues = useMemo(
|
||||
(): FormData => ({ poaLocation: profile.poaLocation ?? "" }),
|
||||
[profile],
|
||||
);
|
||||
|
||||
const {
|
||||
register,
|
||||
control,
|
||||
handleSubmit,
|
||||
reset,
|
||||
watch,
|
||||
formState: { errors, isDirty },
|
||||
} = useForm<FormData>({
|
||||
resolver: zodResolver(schema),
|
||||
@@ -123,10 +111,10 @@ export default function TabPowerOfAttorney({
|
||||
const letterQuery = useQuery(api.companies.poaDelegation.queryOptions({}));
|
||||
const letters = useMemo(() => letterQuery.data ?? [], [letterQuery.data]);
|
||||
|
||||
// The letter is staged locally, not uploaded on pick. Uploading immediately
|
||||
// would open a change request, which locks the whole settings page (see
|
||||
// SettingsPage's `locked` fieldset) before the text fields could be saved.
|
||||
// Save submits the file and the fields together, into one change request.
|
||||
// The letter is staged locally, not uploaded on pick: the paper is the one
|
||||
// thing here that still goes to a reviewer, so picking it must not open a
|
||||
// change request before the customer has committed to the save. Save submits
|
||||
// the file and the fields together.
|
||||
const [pickedFile, setPickedFile] = useState<File | null>(null);
|
||||
const [removeIds, setRemoveIds] = useState<string[]>([]);
|
||||
const [saveBlocked, setSaveBlocked] = useState(false);
|
||||
@@ -142,22 +130,12 @@ export default function TabPowerOfAttorney({
|
||||
const requirePoa = profile.companyProfiles.some(
|
||||
(p) => p.type === "freight_forwarder",
|
||||
);
|
||||
// An Ethiopian company does not type its representative's details — they
|
||||
// come from the Fayda verification. A foreign company keeps the typed form:
|
||||
// its representative may hold no Fayda ID.
|
||||
// No company types its representative's details — they come from the Fayda
|
||||
// verification whatever the nationality, since a representative acts for the
|
||||
// company inside Ethiopia either way. A PoA therefore exists exactly when one
|
||||
// has been verified.
|
||||
const identity = profile.identity;
|
||||
const verifiedIdentity = identity?.faydaRequired === true;
|
||||
|
||||
const poaValues = watch([
|
||||
"poaName",
|
||||
"poaEmail",
|
||||
"poaPhone",
|
||||
"poaLocation",
|
||||
"poaAddress",
|
||||
]);
|
||||
const poaProvided = verifiedIdentity
|
||||
? (identity?.poa.verified ?? false)
|
||||
: poaValues.some((v) => v?.trim());
|
||||
const poaProvided = identity?.poa.verified ?? false;
|
||||
const letterRequired = requirePoa || poaProvided;
|
||||
const letterMissing = letterRequired && !hasLetterAfterSave;
|
||||
|
||||
@@ -166,16 +144,8 @@ export default function TabPowerOfAttorney({
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (data: FormData) => {
|
||||
// Every identity field except the city is written by the verification, so
|
||||
// an Ethiopian company only ever saves the paper and the location here.
|
||||
const fields = verifiedIdentity
|
||||
? { poaLocation: data.poaLocation || undefined }
|
||||
: {
|
||||
poaName: data.poaName || undefined,
|
||||
poaPhone: data.poaPhone || undefined,
|
||||
poaEmail: data.poaEmail || undefined,
|
||||
poaLocation: data.poaLocation || undefined,
|
||||
poaAddress: data.poaAddress || undefined,
|
||||
};
|
||||
// only the paper and the location are ever saved here.
|
||||
const fields = { poaLocation: data.poaLocation || undefined };
|
||||
// A fresh upload already stages the removal of every paper on file, so
|
||||
// the explicit removals only need applying when no replacement was
|
||||
// picked. Saving the details after it means the API sees the new paper.
|
||||
@@ -281,12 +251,8 @@ export default function TabPowerOfAttorney({
|
||||
subject="poa"
|
||||
title="Power of Attorney"
|
||||
state={identity.poa}
|
||||
required={identity.faydaRequired}
|
||||
required={requirePoa}
|
||||
disabled={mutation.isPending}
|
||||
pendingReview={Boolean(
|
||||
(profile.pendingChanges as { faydaIdentity?: Record<string, unknown> } | null)
|
||||
?.faydaIdentity?.poaFaydaSub,
|
||||
)}
|
||||
onVerified={() => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: api.companies.getProfile.queryKey(),
|
||||
@@ -300,39 +266,9 @@ export default function TabPowerOfAttorney({
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<Stack gap="md">
|
||||
{/* Name, email, phone and address are written by the Fayda
|
||||
verification for an Ethiopian company, so only the city — which
|
||||
the address claim does not reliably decompose into — is typed. */}
|
||||
{!verifiedIdentity && (
|
||||
<>
|
||||
<TextInput
|
||||
label="PoA Full Name"
|
||||
placeholder="Authorized Representative Name"
|
||||
error={errors.poaName?.message}
|
||||
{...register("poaName")}
|
||||
/>
|
||||
|
||||
<Grid>
|
||||
<Grid.Col span={6}>
|
||||
<TextInput
|
||||
label="PoA Email"
|
||||
type="email"
|
||||
placeholder="poa@company.com"
|
||||
error={errors.poaEmail?.message}
|
||||
{...register("poaEmail")}
|
||||
/>
|
||||
</Grid.Col>
|
||||
<Grid.Col span={6}>
|
||||
<ControlledPhoneField
|
||||
control={control}
|
||||
name="poaPhone"
|
||||
label="PoA Phone"
|
||||
/>
|
||||
</Grid.Col>
|
||||
</Grid>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Name, email, phone and address are all written by the Fayda
|
||||
verification, so only the city — which the address claim does
|
||||
not reliably decompose into — is typed. */}
|
||||
<Grid>
|
||||
<Grid.Col span={6}>
|
||||
<TextInput
|
||||
@@ -342,16 +278,6 @@ export default function TabPowerOfAttorney({
|
||||
{...register("poaLocation")}
|
||||
/>
|
||||
</Grid.Col>
|
||||
{!verifiedIdentity && (
|
||||
<Grid.Col span={6}>
|
||||
<TextInput
|
||||
label="PoA Address"
|
||||
placeholder="Full Address"
|
||||
error={errors.poaAddress?.message}
|
||||
{...register("poaAddress")}
|
||||
/>
|
||||
</Grid.Col>
|
||||
)}
|
||||
</Grid>
|
||||
</Stack>
|
||||
|
||||
@@ -480,7 +406,10 @@ export default function TabPowerOfAttorney({
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
{profile.reviewStatus === "pending" && (
|
||||
{/* Keyed on the paper's own staged status, not the company's
|
||||
review state: the details on this tab now apply live, so a
|
||||
pending review is just as likely to be about something else. */}
|
||||
{letters.some((f) => f.status !== "live") && (
|
||||
<Group gap={6} c="edr-amber-text">
|
||||
<Clock size={13} />
|
||||
<Text size="xs" fw={500}>
|
||||
@@ -527,7 +456,6 @@ export default function TabPowerOfAttorney({
|
||||
</Group>
|
||||
<Group gap="md">
|
||||
{mode === "edit" &&
|
||||
verifiedIdentity &&
|
||||
identity?.poa.verified &&
|
||||
!requirePoa && (
|
||||
<Button
|
||||
|
||||
@@ -94,10 +94,12 @@ export interface CompanyInfoResponse {
|
||||
company: CompanyResponse;
|
||||
/**
|
||||
* Open profile-edit review, if any. `pending` locks the settings page + new
|
||||
* contract/booking creation; `rejected` surfaces the note for reapply.
|
||||
* contract/booking creation; `rejected`/`changes_requested` both surface the
|
||||
* note for reapply — `changes_requested` just means the edit appends to the
|
||||
* same request instead of starting a fresh one.
|
||||
*/
|
||||
review?: {
|
||||
status: "pending" | "rejected";
|
||||
status: "pending" | "rejected" | "changes_requested";
|
||||
note: string | null;
|
||||
} | null;
|
||||
}
|
||||
@@ -106,7 +108,7 @@ export interface CompanyInfoResponse {
|
||||
export interface ChangeRequestResponse {
|
||||
id: string;
|
||||
companyId: string;
|
||||
status: "pending" | "approved" | "rejected";
|
||||
status: "pending" | "approved" | "rejected" | "changes_requested";
|
||||
snapshot: Record<string, any>;
|
||||
documentFileIds: string[];
|
||||
note: string | null;
|
||||
|
||||
@@ -73,4 +73,10 @@ export const invoicesService = {
|
||||
});
|
||||
return data.data ?? data;
|
||||
},
|
||||
|
||||
/** Submit the CAC Bank OTP for an invoice whose intent is awaiting confirmation. */
|
||||
confirmOtp: async (id: string, otp: string): Promise<InitiateResponse> => {
|
||||
const { data } = await client.post(B.CONFIRM_INVOICE_OTP(id), { otp });
|
||||
return data.data ?? data;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -12,7 +12,8 @@ export type PaymentMethod =
|
||||
| "WAAFI"
|
||||
| "CARD"
|
||||
| "DMONEY"
|
||||
| "CAC_BANK";
|
||||
| "CAC_BANK"
|
||||
| "CBE_BILL";
|
||||
|
||||
export type PaymentPlatform = "web" | "mobile";
|
||||
|
||||
@@ -26,13 +27,17 @@ export interface InitiatePaymentPayload {
|
||||
}
|
||||
|
||||
export interface ClientAction {
|
||||
type: "REDIRECT" | "LAUNCH_APP" | "COLLECT_OTP";
|
||||
type: "REDIRECT" | "LAUNCH_APP" | "COLLECT_OTP" | "SHOW_BILL_REFERENCE";
|
||||
url?: string;
|
||||
appId?: string;
|
||||
receiveCode?: string;
|
||||
shortCode?: string;
|
||||
providerOrderId?: string;
|
||||
message?: string;
|
||||
/** SHOW_BILL_REFERENCE (CBE bill payment) */
|
||||
billReference?: string;
|
||||
instructions?: string;
|
||||
expiresAt?: string;
|
||||
}
|
||||
|
||||
export interface InitiateResponse {
|
||||
|
||||
@@ -51,10 +51,12 @@ export interface ProfileResponse {
|
||||
profileId: string;
|
||||
/**
|
||||
* Open profile-edit review. `pending` → the settings page is read-only until an
|
||||
* admin decides; `rejected` → the note explains why and the forms prefill the
|
||||
* declined values so the customer can amend & resubmit.
|
||||
* admin decides; `rejected`/`changes_requested` → the note explains why and
|
||||
* the forms prefill the declined values so the customer can amend & resubmit
|
||||
* (`changes_requested` appends that edit to this same request instead of
|
||||
* starting a fresh one).
|
||||
*/
|
||||
reviewStatus?: "pending" | "rejected" | null;
|
||||
reviewStatus?: "pending" | "rejected" | "changes_requested" | null;
|
||||
reviewNote?: string | null;
|
||||
pendingChanges?: Record<string, any> | null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user