shipping line

This commit is contained in:
Marshal
2026-08-13 18:56:52 +00:00
parent 0e00a98ef3
commit b9ba830a09
48 changed files with 6766 additions and 639 deletions

View File

@@ -37,6 +37,7 @@ import DocumentClearanceListPage from "./pages/bookings/DocumentClearanceListPag
import CustomerDetailPage from "./pages/customers/CustomerDetailPage";
import CustomersPage from "./pages/customers/CustomersPage";
import ShippingLineCompaniesPage from "./pages/shipping-lines/ShippingLineCompaniesPage";
import ShippingLineCreditsPage from "./pages/shipping-lines/ShippingLineCreditsPage";
import InvoiceDetailPage from "./pages/invoices/InvoiceDetailPage";
import FinanceHubPage from "./pages/invoices/FinanceHubPage";
import MyProfilePage from "./pages/dashboard/MyProfilePage";
@@ -309,6 +310,16 @@ const App = () => {
</RequirePermission>
}
/>
<Route
path="shipping-line-credits"
element={
<RequirePermission
permission={FREIGHT_PERMS.shippingLineCredits.view}
>
<ShippingLineCreditsPage />
</RequirePermission>
}
/>
<Route
path="invoices"
element={

View File

@@ -1,5 +1,5 @@
import { Package } from "lucide-react";
import { SimpleGrid, Divider, Box, Table, Text } from "@mantine/core";
import { SimpleGrid, Divider, Box, Table, Text, Badge } from "@mantine/core";
import type { BookingDetail } from "@/types/booking";
import { cargoTonsAndItems } from "@/utils/cargoWeight";
@@ -16,6 +16,19 @@ export function BookingCargoCard({ booking }: BookingCargoCardProps) {
const containers = booking.bookingContainers ?? [];
const { tons, items } = cargoTonsAndItems(booking);
// Booking-level flags OR any container line carrying a count — the flag can
// lag the lines (per-line opt-ins), so either alone must light the tile.
const isHazardous =
booking.isHazardous ||
containers.some((c) => Number(c.hazardousQuantity ?? 0) > 0);
const isReefer =
booking.isReefer ||
containers.some((c) => Number(c.reeferQuantity ?? 0) > 0);
const showHandlingColumns = containers.some(
(c) =>
Number(c.hazardousQuantity ?? 0) > 0 || Number(c.reeferQuantity ?? 0) > 0,
);
return (
<SectionCard icon={Package} title="Cargo specifications" accent="orange">
<SimpleGrid cols={{ base: 1, sm: 3 }} spacing="sm">
@@ -27,11 +40,33 @@ export function BookingCargoCard({ booking }: BookingCargoCardProps) {
{items != null && <MetricTile label="Items" value={`${items}`} />}
<MetricTile
label="Hazardous"
value={booking.isHazardous ? "Yes" : "No"}
highlight={booking.isHazardous}
value={isHazardous ? "Yes" : "No"}
highlight={isHazardous}
/>
<MetricTile
label="Refrigerated"
value={isReefer ? "Yes" : "No"}
highlight={isReefer}
/>
</SimpleGrid>
{/* Handling that changes how the yard treats the shipment is flagged
loudly, not buried in the grid. */}
{(isHazardous || isReefer) && (
<Box mt="sm">
{isHazardous && (
<Badge color="red" variant="filled" radius="sm" mr={8}>
Hazardous cargo
</Badge>
)}
{isReefer && (
<Badge color="blue" variant="filled" radius="sm">
Refrigerated cargo
</Badge>
)}
</Box>
)}
{containers.length > 0 && (
<>
<Divider my="lg" color="var(--mantine-color-gray-2)" />
@@ -42,6 +77,8 @@ export function BookingCargoCard({ booking }: BookingCargoCardProps) {
<Table.Th>Container type</Table.Th>
<Table.Th>Qty</Table.Th>
<Table.Th>VGM / unit</Table.Th>
{showHandlingColumns && <Table.Th>Hazardous</Table.Th>}
{showHandlingColumns && <Table.Th>Reefer</Table.Th>}
</Table.Tr>
</Table.Thead>
<Table.Tbody>
@@ -54,6 +91,28 @@ export function BookingCargoCard({ booking }: BookingCargoCardProps) {
</Table.Td>
<Table.Td>{c.quantity}</Table.Td>
<Table.Td>{c.vgmPerUnitTons} t</Table.Td>
{showHandlingColumns && (
<Table.Td>
{Number(c.hazardousQuantity ?? 0) > 0 ? (
<Text fw={700} c="red" size="sm">
{c.hazardousQuantity}
</Text>
) : (
"—"
)}
</Table.Td>
)}
{showHandlingColumns && (
<Table.Td>
{Number(c.reeferQuantity ?? 0) > 0 ? (
<Text fw={700} c="blue" size="sm">
{c.reeferQuantity}
</Text>
) : (
"—"
)}
</Table.Td>
)}
</Table.Tr>
))}
</Table.Tbody>

View File

@@ -24,6 +24,7 @@ import {
Send,
Settings,
ShieldCheck,
HandCoins,
Ship,
SlidersHorizontal,
Train,
@@ -76,6 +77,12 @@ export const buildSidebarSections = (
icon: <Ship />,
permission: FREIGHT_PERMS.shippingLines.view,
},
{
label: "Shipping Line Credits",
href: "/dashboard/shipping-line-credits",
icon: <HandCoins />,
permission: FREIGHT_PERMS.shippingLineCredits.view,
},
{
label: "Contracts",
href: "/dashboard/contract-requests",

View File

@@ -0,0 +1,363 @@
import {
Badge,
Button,
Group,
Modal,
Stack,
Text,
Textarea,
TextInput,
} from "@mantine/core";
import { useMutation } from "@tanstack/react-query";
import { Ban, Check, HandCoins, X } from "lucide-react";
import { useState } from "react";
import { useAuth } from "@/auth/useAuth";
import { formatMoney } from "@/components/customers";
import { useToast } from "@/hooks/use-toast";
import { FREIGHT_PERMS, hasPermission } from "@/lib/permissions";
import { api } from "@/services/api";
import type {
CreditInvoiceActionType,
CreditInvoicePendingAction,
} from "@/types/shippingLineCredit";
/** The slice of an invoice row the actions need — both list pages have it. */
export interface CreditInvoiceActionTarget {
id: string;
invoiceNumber: string;
status: string;
currency: string;
totalAmount: string | number;
paidAmount: string | number;
balanceAmount: string | number;
}
/** Statuses an offline payment can still be recorded against. */
const MARK_PAID_STATUSES = new Set([
"ISSUED",
"PENDING",
"PAYMENT_PROCESSING",
"PARTIALLY_PAID",
"OVERDUE",
]);
const ACTION_LABEL: Record<CreditInvoiceActionType, string> = {
MARK_PAID: "Mark paid",
CANCEL: "Cancel invoice",
};
export interface CreditInvoiceActionsProps {
invoice: CreditInvoiceActionTarget;
pendingAction: CreditInvoicePendingAction | null;
}
/**
* Two-step actions for ONE shipping-line credit invoice, embeddable in any
* invoice list. Gated purely by permission: the request grants raise
* mark-paid / cancel, the approve/reject grants decide ANY pending request —
* the holder's own included. Renders only the buttons the signed-in user's
* grants allow; the API enforces the same gates server-side.
*/
export default function CreditInvoiceActions({
invoice,
pendingAction,
}: CreditInvoiceActionsProps) {
const { user } = useAuth();
const { toast } = useToast();
const canRequestPaid = hasPermission(
user,
FREIGHT_PERMS.shippingLineCredits.invoiceMarkPaid,
);
const canRequestCancel = hasPermission(
user,
FREIGHT_PERMS.shippingLineCredits.invoiceCancel,
);
const canApprove = hasPermission(
user,
FREIGHT_PERMS.shippingLineCredits.invoiceApprove,
);
const canReject = hasPermission(
user,
FREIGHT_PERMS.shippingLineCredits.invoiceReject,
);
const [requestAction, setRequestActionModal] =
useState<CreditInvoiceActionType | null>(null);
const [reason, setReason] = useState("");
const [paymentReference, setPaymentReference] = useState("");
const [decideApprove, setDecideApprove] = useState<boolean | null>(null);
const [decisionNote, setDecisionNote] = useState("");
const closeRequest = () => {
setRequestActionModal(null);
setReason("");
setPaymentReference("");
};
const closeDecide = () => {
setDecideApprove(null);
setDecisionNote("");
};
const { mutate: submitRequest, isPending: isRequesting } = useMutation(
api.shippingLineCredits.requestInvoiceAction.mutationOptions({
onSuccess: (_, variables) => {
closeRequest();
toast({
title: "Request submitted",
description: `${ACTION_LABEL[variables.action]} on ${invoice.invoiceNumber} now awaits a chief's approval.`,
});
},
onError: (err) =>
toast({
title: "Could not submit request",
description: err.message,
variant: "destructive",
}),
}),
);
const { mutate: submitDecision, isPending: isDeciding } = useMutation(
api.shippingLineCredits.decideInvoiceAction.mutationOptions({
onSuccess: (_, variables) => {
closeDecide();
toast({
title: variables.approve ? "Request approved" : "Request rejected",
description: variables.approve
? pendingAction?.action === "MARK_PAID"
? "The offline payment was recorded; the invoice and its credits are now paid."
: "The invoice was cancelled; its credits returned to the unbilled pool."
: "The request was rejected and nothing was changed.",
});
},
onError: (err) =>
toast({
title: "Could not decide request",
description: err.message,
variant: "destructive",
}),
}),
);
let body = null;
if (pendingAction) {
body = (
<Stack gap={6} py={4}>
<Badge variant="light" color="orange" title={pendingAction.reason}>
{ACTION_LABEL[pendingAction.action]} awaiting approval
</Badge>
{canApprove || canReject ? (
<Group gap={6} wrap="nowrap">
{canApprove ? (
<Button
size="compact-xs"
color="edr-green"
leftSection={<Check size={12} />}
onClick={() => setDecideApprove(true)}
>
Approve
</Button>
) : null}
{canReject ? (
<Button
size="compact-xs"
variant="outline"
color="red"
leftSection={<X size={12} />}
onClick={() => setDecideApprove(false)}
>
Reject
</Button>
) : null}
</Group>
) : null}
</Stack>
);
} else {
const showMarkPaid =
canRequestPaid && MARK_PAID_STATUSES.has(invoice.status);
const showCancel =
canRequestCancel &&
invoice.status !== "CANCELLED" &&
invoice.status !== "PAID" &&
invoice.status !== "REFUNDED" &&
Number(invoice.paidAmount) === 0;
body =
!showMarkPaid && !showCancel ? (
<Text size="sm" c="dimmed">
</Text>
) : (
<Group gap={6} wrap="nowrap">
{showMarkPaid ? (
<Button
size="compact-xs"
variant="light"
color="edr-green"
leftSection={<HandCoins size={12} />}
onClick={() => setRequestActionModal("MARK_PAID")}
>
Mark paid
</Button>
) : null}
{showCancel ? (
<Button
size="compact-xs"
variant="light"
color="red"
leftSection={<Ban size={12} />}
onClick={() => setRequestActionModal("CANCEL")}
>
Cancel
</Button>
) : null}
</Group>
);
}
return (
<>
{body}
{/* Maker: raise the request. */}
<Modal
opened={requestAction !== null}
onClose={closeRequest}
title={
requestAction
? `${ACTION_LABEL[requestAction]}${invoice.invoiceNumber}`
: ""
}
centered
>
<Stack gap="md">
<Text size="sm" c="dimmed">
{requestAction === "MARK_PAID"
? "Records a full offline settlement of the outstanding balance. Takes effect only after a chief approves."
: "Voids the invoice and returns its credits to the unbilled pool. Takes effect only after a chief approves."}
</Text>
{requestAction === "MARK_PAID" ? (
<TextInput
label="Payment reference"
description="Bank slip / transfer number, if any."
value={paymentReference}
onChange={(e) => setPaymentReference(e.currentTarget.value)}
/>
) : null}
<Textarea
label="Reason"
withAsterisk
minRows={2}
placeholder={
requestAction === "MARK_PAID"
? "Paid by bank transfer, slip #…"
: "Raised in error / rebilling with corrections…"
}
value={reason}
onChange={(e) => setReason(e.currentTarget.value)}
/>
<Group justify="flex-end" gap="sm">
<Button
variant="default"
onClick={closeRequest}
disabled={isRequesting}
>
Cancel
</Button>
<Button
loading={isRequesting}
disabled={reason.trim().length < 3}
onClick={() =>
requestAction &&
submitRequest({
invoiceId: invoice.id,
action: requestAction,
reason: reason.trim(),
paymentReference: paymentReference.trim() || undefined,
})
}
>
Submit for approval
</Button>
</Group>
</Stack>
</Modal>
{/* Checker: decide the request. */}
<Modal
opened={decideApprove !== null}
onClose={closeDecide}
title={
pendingAction
? `${decideApprove ? "Approve" : "Reject"}: ${ACTION_LABEL[pendingAction.action]}${invoice.invoiceNumber}`
: ""
}
centered
>
<Stack gap="md">
{pendingAction ? (
<Stack gap={4}>
<Text size="sm">
<Text component="span" c="dimmed">
Requested reason:{" "}
</Text>
{pendingAction.reason}
</Text>
{pendingAction.paymentReference ? (
<Text size="sm">
<Text component="span" c="dimmed">
Payment reference:{" "}
</Text>
{pendingAction.paymentReference}
</Text>
) : null}
</Stack>
) : null}
{decideApprove && pendingAction ? (
<Text size="sm" c="dimmed">
{pendingAction.action === "MARK_PAID"
? `Approving records ${formatMoney(
Number(invoice.balanceAmount ?? invoice.totalAmount),
invoice.currency,
)} as paid offline and settles the invoice's credits.`
: "Approving cancels the invoice and returns its credits to the unbilled pool."}
</Text>
) : null}
<Textarea
label={decideApprove ? "Note (optional)" : "Rejection note"}
withAsterisk={!decideApprove}
minRows={2}
value={decisionNote}
onChange={(e) => setDecisionNote(e.currentTarget.value)}
/>
<Group justify="flex-end" gap="sm">
<Button
variant="default"
onClick={closeDecide}
disabled={isDeciding}
>
Back
</Button>
<Button
color={decideApprove ? "edr-green" : "red"}
loading={isDeciding}
disabled={!decideApprove && !decisionNote.trim()}
onClick={() =>
pendingAction &&
decideApprove !== null &&
submitDecision({
approvalId: pendingAction.id,
approve: decideApprove,
note: decisionNote.trim() || undefined,
})
}
>
{decideApprove ? "Approve & execute" : "Reject request"}
</Button>
</Group>
</Stack>
</Modal>
</>
);
}

View File

@@ -36,6 +36,40 @@ export const QUERY_KEYS = {
["shipping-line-companies", "detail", id] as const,
},
SHIPPING_LINE_CREDITS: {
ROOT: ["shipping-line-credits"] as const,
invoices: (
page: number,
pageSize: number,
status?: string,
shippingLineId?: string,
) =>
[
"shipping-line-credits",
"invoices",
shippingLineId ?? "all",
page,
pageSize,
status ?? "all",
] as const,
summary: (shippingLineId?: string) =>
["shipping-line-credits", "summary", shippingLineId ?? "all"] as const,
list: (
page: number,
pageSize: number,
status?: string,
shippingLineId?: string,
) =>
[
"shipping-line-credits",
"list",
shippingLineId ?? "all",
page,
pageSize,
status ?? "all",
] as const,
},
CUSTOMERS: {
ROOT: ["customers"] as const,
stats: ["customers", "stats"] as const,

View File

@@ -88,6 +88,22 @@ export const URL_CONSTANTS = {
`/shipping-line-companies/${id}/resend-activation`,
},
/** Finance's view of what shipping lines owe (use now, pay later). */
SHIPPING_LINE_CREDITS: {
BASE: "/shipping-line-credits",
SUMMARY: "/shipping-line-credits/summary",
INVOICE: "/shipping-line-credits/invoice",
INVOICES: "/shipping-line-credits/invoices",
MARK_PAID_REQUEST: (invoiceId: string) =>
`/shipping-line-credits/invoices/${invoiceId}/mark-paid-request`,
CANCEL_REQUEST: (invoiceId: string) =>
`/shipping-line-credits/invoices/${invoiceId}/cancel-request`,
APPROVE_ACTION: (approvalId: string) =>
`/shipping-line-credits/invoice-actions/${approvalId}/approve`,
REJECT_ACTION: (approvalId: string) =>
`/shipping-line-credits/invoice-actions/${approvalId}/reject`,
},
COMPANIES: {
BASE: "/companies",
STATS: "/companies/stats",

View File

@@ -129,6 +129,15 @@ export const FREIGHT_PERMS = {
update: "edr_freight_app:shipping_lines:update",
resetPassword: "edr_freight_app:shipping_lines:reset-password",
},
shippingLineCredits: {
view: "edr_freight_app:shipping_line_credits:view",
invoice: "edr_freight_app:shipping_line_credits:invoice",
cancel: "edr_freight_app:shipping_line_credits:cancel",
invoiceMarkPaid: "edr_freight_app:shipping_line_credits:invoice_mark_paid",
invoiceCancel: "edr_freight_app:shipping_line_credits:invoice_cancel",
invoiceApprove: "edr_freight_app:shipping_line_credits:invoice_approve",
invoiceReject: "edr_freight_app:shipping_line_credits:invoice_reject",
},
payments: {
view: "edr_freight_app:payments:view",
},

View File

@@ -21,6 +21,7 @@ import {
formatMoney,
humanize,
} from "@/components/customers";
import CreditInvoiceActions from "@/components/shipping-lines/CreditInvoiceActions";
import { api } from "@/services/api";
import type { Invoice } from "@/types/invoice";
import {
@@ -58,6 +59,26 @@ export default function InvoicesPanel() {
const total = data?.total ?? 0;
const pageCount = Math.max(1, Math.ceil(total / pagination.pageSize));
// Shipping-line credit invoices carry makerchecker actions (mark paid /
// cancel). One batched lookup fetches the visible rows' pending requests.
const creditInvoiceIds = useMemo(
() =>
rows
.filter((inv) => inv.source === "shipping_line_credit")
.map((inv) => inv.id),
[rows],
);
const { data: pendingActions } = useQuery(
api.shippingLineCredits.pendingInvoiceActions.queryOptions({
input: { invoiceIds: creditInvoiceIds },
enabled: creditInvoiceIds.length > 0,
}),
);
const pendingByInvoice = useMemo(
() => new Map((pendingActions ?? []).map((p) => [p.invoiceId, p])),
[pendingActions],
);
const columns: ColumnDef<Invoice>[] = useMemo(
() => [
{
@@ -122,8 +143,30 @@ export default function InvoicesPanel() {
</Text>
),
},
{
id: "actions",
header: "Actions",
cell: ({ row }) => {
const inv = row.original;
// Only shipping-line credit invoices have manual makerchecker
// actions; every other source settles through its own flow.
if (inv.source !== "shipping_line_credit") {
return (
<Text size="sm" c="dimmed">
</Text>
);
}
return (
<CreditInvoiceActions
invoice={inv}
pendingAction={pendingByInvoice.get(inv.id) ?? null}
/>
);
},
},
],
[],
[pendingByInvoice],
);
return (

View File

@@ -0,0 +1,279 @@
import {
Badge,
Box,
Button,
Card,
Group,
Select,
Stack,
Text,
} from "@mantine/core";
import { useQuery } from "@tanstack/react-query";
import { Calendar, FilterX, RefreshCw, Ship } from "lucide-react";
import { useMemo, useState } from "react";
import { bookingTable } from "@/components/bookings/booking-ui.styles";
import { formatDate, formatMoney } from "@/components/customers";
import CreditInvoiceActions from "@/components/shipping-lines/CreditInvoiceActions";
import { api } from "@/services/api";
import type { CreditInvoice } from "@/types/shippingLineCredit";
import {
DataTable,
DataTableFooter,
usePagination,
type ColumnDef,
} from "@edr/ui-common";
const INVOICE_STATUS_META: Record<string, { label: string; color: string }> = {
DRAFT: { label: "Draft", color: "gray" },
ISSUED: { label: "Issued", color: "orange" },
PENDING: { label: "Pending", color: "orange" },
PAYMENT_PROCESSING: { label: "Processing", color: "blue" },
PARTIALLY_PAID: { label: "Partially paid", color: "yellow" },
PAID: { label: "Paid", color: "green" },
OVERDUE: { label: "Overdue", color: "red" },
CANCELLED: { label: "Cancelled", color: "gray" },
REFUNDED: { label: "Refunded", color: "blue" },
EXPIRED: { label: "Expired", color: "red" },
};
const STATUS_OPTIONS = Object.entries(INVOICE_STATUS_META).map(
([value, meta]) => ({ value, label: meta.label }),
);
/**
* Invoices minted from credit batches. The actions column is the shared
* makerchecker component (also embedded on the Finance hub's invoice list):
* finance requests mark-paid / cancel, a chief approves or rejects.
*/
export default function ShippingLineCreditInvoicesPanel() {
const { pagination, setPagination } = usePagination({ pageSize: 10 });
const [status, setStatus] = useState<string | null>(null);
const [shippingLineId, setShippingLineId] = useState<string | null>(null);
const { data: companies } = useQuery(
api.shippingLineCompanies.list.queryOptions({
input: { page: 1, limit: 100 },
}),
);
const lineOptions = useMemo(
() =>
(companies?.items ?? []).map((sl) => ({ value: sl.id, label: sl.name })),
[companies],
);
const { data, isLoading, isError, error, refetch, isFetching } = useQuery(
api.shippingLineCredits.listInvoices.queryOptions({
input: {
page: pagination.pageIndex + 1,
pageSize: pagination.pageSize,
status: status ?? undefined,
shippingLineId: shippingLineId ?? undefined,
},
}),
);
const rows = data?.items ?? [];
const total = data?.total ?? 0;
const pageCount = Math.max(1, Math.ceil(total / pagination.pageSize));
const activeFilterCount = (shippingLineId ? 1 : 0) + (status ? 1 : 0);
const resetPage = () =>
setPagination({ pageIndex: 0, pageSize: pagination.pageSize });
const columns: ColumnDef<CreditInvoice>[] = useMemo(
() => [
{
id: "invoice",
header: () => <span className={bookingTable.headerCell}>Invoice</span>,
cell: ({ row }) => {
const inv = row.original;
return (
<div className="flex items-center gap-3 py-1.5">
<div className={bookingTable.rowIcon}>
<Ship className="size-4" strokeWidth={1.75} />
</div>
<div className="min-w-0">
<p className="truncate font-mono text-sm font-semibold text-foreground">
{inv.invoiceNumber}
</p>
<p className="mt-0.5 truncate text-xs text-muted-foreground">
{inv.shippingLineName ?? "—"}
</p>
</div>
</div>
);
},
},
{
id: "issued",
header: () => <span className={bookingTable.headerCell}>Issued</span>,
cell: ({ row }) => (
<span className="inline-flex items-center gap-1.5 text-sm text-muted-foreground">
<Calendar className="size-3.5" />
{row.original.issuedAt ? formatDate(row.original.issuedAt) : "—"}
</span>
),
},
{
id: "due",
header: () => <span className={bookingTable.headerCell}>Due</span>,
cell: ({ row }) => (
<span className="text-sm text-muted-foreground">
{row.original.dueAt ? formatDate(row.original.dueAt) : "—"}
</span>
),
},
{
id: "amount",
header: () => <span className={bookingTable.headerCell}>Amount</span>,
cell: ({ row }) => (
<span className="text-sm font-semibold text-foreground">
{formatMoney(
Number(row.original.totalAmount),
row.original.currency,
)}
</span>
),
},
{
id: "balance",
header: () => <span className={bookingTable.headerCell}>Balance</span>,
cell: ({ row }) => (
<span className="text-sm text-muted-foreground">
{formatMoney(
Number(row.original.balanceAmount ?? row.original.totalAmount),
row.original.currency,
)}
</span>
),
},
{
id: "status",
header: () => <span className={bookingTable.headerCell}>Status</span>,
cell: ({ row }) => {
const meta = INVOICE_STATUS_META[row.original.status] ?? {
label: row.original.status,
color: "gray",
};
return (
<Badge variant="light" color={meta.color}>
{meta.label}
</Badge>
);
},
},
{
id: "actions",
header: () => <span className={bookingTable.headerCell}>Actions</span>,
cell: ({ row }) => (
<CreditInvoiceActions
invoice={row.original}
pendingAction={row.original.pendingAction}
/>
),
},
],
[],
);
return (
<Stack gap="lg">
<Card p={0}>
<Stack gap={0}>
<Box px="md" pt="md" pb="sm" w="100%">
<Group justify="space-between" gap="md" wrap="wrap">
<Group gap="sm" wrap="wrap">
<Select
placeholder="All shipping lines"
data={lineOptions}
value={shippingLineId}
onChange={(v) => {
setShippingLineId(v);
resetPage();
}}
clearable
searchable
radius="lg"
style={{ minWidth: 220 }}
/>
<Select
placeholder="All statuses"
data={STATUS_OPTIONS}
value={status}
onChange={(v) => {
setStatus(v);
resetPage();
}}
clearable
radius="lg"
style={{ minWidth: 160 }}
/>
{activeFilterCount > 0 ? (
<Button
variant="subtle"
color="gray"
radius="lg"
leftSection={<FilterX size={16} />}
onClick={() => {
setShippingLineId(null);
setStatus(null);
resetPage();
}}
>
Clear filters ({activeFilterCount})
</Button>
) : null}
</Group>
<Group gap="sm" wrap="nowrap">
<Text size="sm" c="dimmed">
{total} record{total !== 1 ? "s" : ""}
</Text>
<Button
variant="default"
size="compact-sm"
leftSection={<RefreshCw size={14} />}
loading={isFetching}
onClick={() => void refetch()}
>
Refresh
</Button>
</Group>
</Group>
</Box>
<Box style={{ overflowX: "auto" }} w="100%">
<DataTable
columns={columns}
data={rows}
status={isLoading ? "loading" : isError ? "error" : "success"}
emptyMessage="No credit invoices yet — generate one from the Credits tab."
error={
isError
? {
message: error?.message ?? "Failed to load invoices.",
onRetry: () => void refetch(),
}
: undefined
}
pagination={{
pageIndex: pagination.pageIndex,
pageSize: pagination.pageSize,
pageCount,
totalCount: total,
}}
tableOptions={{
state: { pagination },
onPaginationChange: setPagination,
manualPagination: true,
pageCount,
}}
containerClassName="border-0 shadow-none bg-transparent"
footer={DataTableFooter}
/>
</Box>
</Stack>
</Card>
</Stack>
);
}

View File

@@ -0,0 +1,65 @@
import { Stack, Tabs } from "@mantine/core";
import { HandCoins, Receipt } from "lucide-react";
import { useSearchParams } from "react-router-dom";
import { PageContainer, PageHeader } from "@/components/page";
import ShippingLineCreditInvoicesPanel from "./ShippingLineCreditInvoicesPanel";
import ShippingLineCreditsPanel from "./ShippingLineCreditsPanel";
/**
* Finance's view of what shipping lines owe. Two URL-linkable tabs (?tab=,
* FinanceHubPage convention): the credit ledger (select unbilled credits →
* generate an invoice) and the invoices minted from it (makerchecker
* mark-paid / cancel actions).
*/
export default function ShippingLineCreditsPage() {
const [searchParams, setSearchParams] = useSearchParams();
const activeTab =
searchParams.get("tab") === "invoices" ? "invoices" : "credits";
const handleTabChange = (value: string | null) => {
if (!value) return;
setSearchParams(
(prev) => {
const next = new URLSearchParams(prev);
next.set("tab", value);
return next;
},
{ replace: true },
);
};
return (
<PageContainer>
<Stack gap="lg">
<PageHeader
title="Shipping Line Credits"
subtitle={
activeTab === "invoices"
? "Invoices billed from credit batches. Manual mark-paid / cancel actions need a second approver."
: "What each line owes — outstanding totals and the full credit ledger."
}
/>
<Tabs value={activeTab} onChange={handleTabChange} keepMounted={false}>
<Tabs.List>
<Tabs.Tab value="credits" leftSection={<HandCoins size={16} />}>
Credits
</Tabs.Tab>
<Tabs.Tab value="invoices" leftSection={<Receipt size={16} />}>
Invoices
</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value="credits" pt="lg">
<ShippingLineCreditsPanel />
</Tabs.Panel>
<Tabs.Panel value="invoices" pt="lg">
<ShippingLineCreditInvoicesPanel />
</Tabs.Panel>
</Tabs>
</Stack>
</PageContainer>
);
}

View File

@@ -0,0 +1,553 @@
import {
Badge,
Box,
Button,
Card,
Checkbox,
Divider,
Group,
Modal,
NumberInput,
Select,
Stack,
Text,
} from "@mantine/core";
import { useMutation, useQuery } from "@tanstack/react-query";
import {
Calendar,
Clock,
FilterX,
HandCoins,
Receipt,
RefreshCw,
Ship,
} from "lucide-react";
import { useMemo, useState } from "react";
import { useAuth } from "@/auth/useAuth";
import { bookingTable } from "@/components/bookings/booking-ui.styles";
import { formatDate, formatMoney } from "@/components/customers";
import { KpiStrip } from "@/components/page";
import { useToast } from "@/hooks/use-toast";
import { FREIGHT_PERMS, hasPermission } from "@/lib/permissions";
import { api } from "@/services/api";
import type {
ShippingLineCredit,
ShippingLineCreditStatus,
} from "@/types/shippingLineCredit";
import {
DataTable,
DataTableFooter,
usePagination,
type ColumnDef,
} from "@edr/ui-common";
const STATUS_META: Record<
ShippingLineCreditStatus,
{ label: string; color: string }
> = {
UNBILLED: { label: "Unbilled", color: "orange" },
BILLED: { label: "Billed", color: "blue" },
PAID: { label: "Paid", color: "green" },
CANCELLED: { label: "Cancelled", color: "gray" },
};
const STATUS_OPTIONS = Object.entries(STATUS_META).map(([value, meta]) => ({
value,
label: meta.label,
}));
/**
* Every shipping line's credits in one list — finance's landing view, styled
* to match the booking-requests page. Summary cells total the current filter
* scope (all lines by default); the selects narrow both cells and ledger.
*/
export default function ShippingLineCreditsPanel() {
const { user } = useAuth();
const { toast } = useToast();
const [shippingLineId, setShippingLineId] = useState<string | null>(null);
const [status, setStatus] = useState<ShippingLineCreditStatus | null>(null);
const { pagination, setPagination } = usePagination({ pageSize: 10 });
const canInvoice = hasPermission(
user,
FREIGHT_PERMS.shippingLineCredits.invoice,
);
// Selection for batch invoicing, kept as id → credit so it survives page
// changes and can total itself. One invoice has one payer, so everything
// selected must belong to the same shipping line — enforced here so the
// API's rejection is never the first time staff hears about it.
const [selected, setSelected] = useState<Map<string, ShippingLineCredit>>(
new Map(),
);
const [invoiceOpen, setInvoiceOpen] = useState(false);
const [dueInDays, setDueInDays] = useState<number | "">("");
const selectedCredits = useMemo(() => [...selected.values()], [selected]);
const selectedLineId = selectedCredits[0]?.shippingLineCompanyId ?? null;
const selectedTotal = selectedCredits.reduce(
(sum, c) => sum + Number(c.amount),
0,
);
const toggleSelected = (credit: ShippingLineCredit) =>
setSelected((prev) => {
const next = new Map(prev);
if (next.has(credit.id)) next.delete(credit.id);
else next.set(credit.id, credit);
return next;
});
const clearSelection = () => setSelected(new Map());
// ponytail: first 100 lines in the picker; server-side search when a real
// deployment outgrows that.
const { data: companies } = useQuery(
api.shippingLineCompanies.list.queryOptions({
input: { page: 1, limit: 100 },
}),
);
const lineOptions = useMemo(
() =>
(companies?.items ?? []).map((sl) => ({
value: sl.id,
label: sl.scacCode ? `${sl.name} (${sl.scacCode})` : sl.name,
})),
[companies],
);
const {
data: summary,
isLoading: summaryLoading,
refetch: refetchSummary,
} = useQuery(
api.shippingLineCredits.summary.queryOptions({
input: { shippingLineId: shippingLineId ?? undefined },
}),
);
const {
data: ledger,
isLoading,
isError,
error,
refetch,
isFetching,
} = useQuery(
api.shippingLineCredits.list.queryOptions({
input: {
page: pagination.pageIndex + 1,
pageSize: pagination.pageSize,
status: status ?? undefined,
shippingLineId: shippingLineId ?? undefined,
},
}),
);
const rows = ledger?.items ?? [];
const total = ledger?.total ?? 0;
const pageCount = Math.max(1, Math.ceil(total / pagination.pageSize));
const activeFilterCount = (shippingLineId ? 1 : 0) + (status ? 1 : 0);
const resetPage = () =>
setPagination({ pageIndex: 0, pageSize: pagination.pageSize });
const clearFilters = () => {
setShippingLineId(null);
setStatus(null);
resetPage();
};
const handleRefresh = () => {
void refetch();
void refetchSummary();
};
const { mutate: generateInvoice, isPending: isInvoicing } = useMutation(
api.shippingLineCredits.generateInvoice.mutationOptions({
onSuccess: (invoice) => {
setInvoiceOpen(false);
clearSelection();
setDueInDays("");
toast({
title: `Invoice ${invoice.invoiceNumber} generated`,
description: `${formatMoney(Number(invoice.totalAmount), invoice.currency)} billed across ${selectedCredits.length} credit${selectedCredits.length === 1 ? "" : "s"}.`,
});
},
onError: (err) => {
toast({
title: "Could not generate invoice",
description: err.message,
variant: "destructive",
});
// A concurrent edit (someone else billed a selected credit) is the
// usual cause — resync so stale rows drop out of the list.
handleRefresh();
},
}),
);
const columns: ColumnDef<ShippingLineCredit>[] = useMemo(
() => [
...(canInvoice
? [
{
id: "select",
size: 40,
header: () => null,
cell: ({ row }: { row: { original: ShippingLineCredit } }) => {
const credit = row.original;
const selectable =
credit.status === "UNBILLED" &&
(selectedLineId === null ||
credit.shippingLineCompanyId === selectedLineId);
return (
<Checkbox
size="sm"
checked={selected.has(credit.id)}
disabled={!selectable}
title={
credit.status !== "UNBILLED"
? "Only unbilled credits can be invoiced"
: !selectable
? "One invoice has one payer — selection already holds another line's credits"
: undefined
}
onChange={() => toggleSelected(credit)}
aria-label="Select credit for invoicing"
/>
);
},
},
]
: []),
{
id: "shippingLine",
header: () => (
<span className={bookingTable.headerCell}>Shipping line</span>
),
cell: ({ row }) => {
const credit = row.original;
return (
<div className="flex items-center gap-3 py-1.5">
<div className={bookingTable.rowIcon}>
<Ship className="size-4" strokeWidth={1.75} />
</div>
<div className="min-w-0">
<p className="truncate font-medium text-foreground">
{credit.shippingLineCompany?.name ?? "—"}
</p>
<p className="mt-0.5 truncate font-mono text-xs text-muted-foreground">
{credit.booking?.reference ?? "—"}
</p>
</div>
</div>
);
},
},
{
id: "description",
header: () => (
<span className={bookingTable.headerCell}>Description</span>
),
cell: ({ row }) => (
<span className="block max-w-[16rem] truncate py-1 text-sm text-muted-foreground">
{row.original.description ?? "—"}
</span>
),
},
{
id: "amount",
header: () => <span className={bookingTable.headerCell}>Amount</span>,
cell: ({ row }) => (
<span className="text-sm font-semibold text-foreground">
{formatMoney(Number(row.original.amount), row.original.currency)}
</span>
),
},
{
id: "status",
header: () => <span className={bookingTable.headerCell}>Status</span>,
cell: ({ row }) => {
const meta = STATUS_META[row.original.status];
return (
<Badge variant="light" color={meta.color}>
{meta.label}
</Badge>
);
},
},
{
id: "invoice",
header: () => <span className={bookingTable.headerCell}>Invoice</span>,
cell: ({ row }) => {
const inv = row.original.invoice;
return inv ? (
<span className="truncate font-mono text-xs text-foreground">
{inv.invoiceNumber}
</span>
) : (
<span className="text-xs text-muted-foreground"></span>
);
},
},
{
id: "createdAt",
header: () => <span className={bookingTable.headerCell}>Recorded</span>,
cell: ({ row }) => (
<span className="inline-flex items-center gap-1.5 text-sm text-muted-foreground">
<Calendar className="size-3.5" />
{formatDate(row.original.createdAt)}
</span>
),
},
],
// Selection state drives the checkbox column's checked/disabled rendering.
// eslint-disable-next-line react-hooks/exhaustive-deps
[canInvoice, selected, selectedLineId],
);
return (
<Stack gap="lg">
<KpiStrip
loading={summaryLoading}
items={[
{
label: "Total outstanding",
value: summary
? formatMoney(summary.totalOutstanding, summary.currency)
: "—",
hint: "unbilled + billed",
icon: HandCoins,
color: "edr-green",
},
{
label: "Unbilled",
value: summary
? formatMoney(summary.unbilledAmount, summary.currency)
: "—",
hint: summary ? `${summary.unbilledCount} credits` : undefined,
icon: Clock,
color: "yellow",
},
{
label: "Billed",
value: summary
? formatMoney(summary.billedAmount, summary.currency)
: "—",
hint: summary ? `${summary.billedCount} on invoices` : undefined,
icon: Receipt,
color: "blue",
},
]}
/>
<Card p={0}>
<Stack gap={0}>
<Box px="md" pt="md" pb="sm" w="100%">
<Group justify="space-between" gap="md" wrap="wrap">
<Group gap="sm" wrap="wrap">
<Select
placeholder="All shipping lines"
data={lineOptions}
value={shippingLineId}
onChange={(v) => {
setShippingLineId(v);
resetPage();
}}
clearable
searchable
radius="lg"
style={{ minWidth: 220 }}
/>
<Select
placeholder="All statuses"
data={STATUS_OPTIONS}
value={status}
onChange={(v) => {
setStatus((v as ShippingLineCreditStatus | null) ?? null);
resetPage();
}}
clearable
radius="lg"
style={{ minWidth: 160 }}
/>
{activeFilterCount > 0 ? (
<Button
variant="subtle"
color="gray"
radius="lg"
leftSection={<FilterX size={16} />}
onClick={clearFilters}
>
Clear filters ({activeFilterCount})
</Button>
) : null}
</Group>
<Group gap="sm" wrap="nowrap">
<Text size="sm" c="dimmed">
{total} record{total !== 1 ? "s" : ""}
</Text>
<Button
variant="default"
size="compact-sm"
leftSection={<RefreshCw size={14} />}
loading={isFetching}
onClick={handleRefresh}
>
Refresh
</Button>
</Group>
</Group>
</Box>
{selectedCredits.length > 0 ? (
<>
<Divider />
<Group
px="md"
py="sm"
justify="space-between"
wrap="wrap"
bg="var(--mantine-color-edr-green-0)"
>
<Text size="sm" fw={600}>
{selectedCredits.length} credit
{selectedCredits.length === 1 ? "" : "s"} selected ·{" "}
{formatMoney(selectedTotal, selectedCredits[0].currency)}
{" — "}
{selectedCredits[0].shippingLineCompany?.name ?? ""}
</Text>
<Group gap="sm">
<Button
variant="subtle"
color="gray"
size="compact-sm"
onClick={clearSelection}
>
Clear selection
</Button>
<Button
size="compact-sm"
leftSection={<Receipt size={14} />}
onClick={() => setInvoiceOpen(true)}
>
Generate invoice
</Button>
</Group>
</Group>
</>
) : null}
<Box style={{ overflowX: "auto" }} w="100%">
<DataTable
columns={columns}
data={rows}
status={isLoading ? "loading" : isError ? "error" : "success"}
emptyMessage="No credits match this filter."
error={
isError
? {
message: error?.message ?? "Failed to load credits.",
onRetry: () => void refetch(),
}
: undefined
}
pagination={{
pageIndex: pagination.pageIndex,
pageSize: pagination.pageSize,
pageCount,
totalCount: total,
}}
tableOptions={{
state: { pagination },
onPaginationChange: setPagination,
manualPagination: true,
pageCount,
}}
containerClassName="border-0 shadow-none bg-transparent"
footer={DataTableFooter}
/>
</Box>
</Stack>
</Card>
<Modal
opened={invoiceOpen}
onClose={() => setInvoiceOpen(false)}
title="Generate invoice"
centered
>
<Stack gap="md">
<Text size="sm" c="dimmed">
One invoice for{" "}
<Text component="span" fw={600} c="edr-text">
{selectedCredits[0]?.shippingLineCompany?.name ?? "this line"}
</Text>{" "}
billing the selected credits. The line pays it at any CBE channel
there is no payment window.
</Text>
<Stack gap={6}>
{selectedCredits.map((credit) => (
<Group key={credit.id} justify="space-between" wrap="nowrap">
<Text size="sm" truncate>
{credit.booking?.reference ?? credit.description ?? credit.id}
</Text>
<Text size="sm" fw={500} style={{ whiteSpace: "nowrap" }}>
{formatMoney(Number(credit.amount), credit.currency)}
</Text>
</Group>
))}
<Divider my={4} />
<Group justify="space-between">
<Text size="sm" fw={700}>
Total
</Text>
<Text size="sm" fw={700}>
{formatMoney(
selectedTotal,
selectedCredits[0]?.currency ?? "ETB",
)}
</Text>
</Group>
</Stack>
<NumberInput
label="Due in days"
description="Optional — defaults to the standard invoice term."
placeholder="14"
min={1}
value={dueInDays}
onChange={(v) => setDueInDays(typeof v === "number" ? v : "")}
/>
<Group justify="flex-end" gap="sm">
<Button
variant="default"
onClick={() => setInvoiceOpen(false)}
disabled={isInvoicing}
>
Cancel
</Button>
<Button
loading={isInvoicing}
onClick={() =>
generateInvoice({
creditIds: selectedCredits.map((c) => c.id),
...(typeof dueInDays === "number"
? { dueInDays }
: {}),
})
}
>
Generate &amp; issue
</Button>
</Group>
</Stack>
</Modal>
</Stack>
);
}

View File

@@ -50,6 +50,14 @@ import type {
RegisterShippingLineCompanyResult,
ShippingLineCompany,
} from "@/types/shippingLineCompany";
import type {
CreditInvoicePendingAction,
GeneratedCreditInvoice,
OutstandingTotals,
PaginatedCreditInvoices,
PaginatedShippingLineCredits,
ShippingLineCreditStatus,
} from "@/types/shippingLineCredit";
import {
RuleEngineListResult,
RuleEngineRecord,
@@ -163,6 +171,7 @@ import { containerTypesService } from "./container-types.service";
import { containerService, type Container } from "./containerService";
import { customersService } from "./customers.service";
import { shippingLineCompaniesService } from "./shippingLineCompanies.service";
import { shippingLineCreditsService } from "./shippingLineCredits.service";
import { eimsService } from "./eims.service";
import type { EimsInvoiceStatusView, EimsVerifyResult } from "@/types/eims";
import { invoicesService } from "./invoices.service";
@@ -2836,6 +2845,123 @@ export const api = {
),
},
shippingLineCredits: {
summary: endpoint<{ shippingLineId?: string }, OutstandingTotals>(
"shippingLineCredits",
"summary",
({ shippingLineId }) => shippingLineCreditsService.summary(shippingLineId),
({ shippingLineId }) =>
QUERY_KEYS.SHIPPING_LINE_CREDITS.summary(shippingLineId),
),
list: endpoint<
{
page: number;
pageSize: number;
status?: ShippingLineCreditStatus;
shippingLineId?: string;
},
PaginatedShippingLineCredits
>(
"shippingLineCredits",
"list",
(filter) => shippingLineCreditsService.list(filter),
({ page, pageSize, status, shippingLineId }) =>
QUERY_KEYS.SHIPPING_LINE_CREDITS.list(
page,
pageSize,
status,
shippingLineId,
),
),
generateInvoice: endpoint<
{ creditIds: string[]; dueInDays?: number },
GeneratedCreditInvoice
>(
"shippingLineCredits",
"generateInvoice",
({ creditIds, dueInDays }) =>
shippingLineCreditsService.generateInvoice(creditIds, dueInDays),
undefined,
// Billing a batch changes ledger rows, the summary totals and (via the
// draft invoice) the invoices list.
() => [QUERY_KEYS.SHIPPING_LINE_CREDITS.ROOT, QUERY_KEYS.INVOICES.ROOT],
),
listInvoices: endpoint<
{
page: number;
pageSize: number;
status?: string;
shippingLineId?: string;
},
PaginatedCreditInvoices
>(
"shippingLineCredits",
"listInvoices",
(filter) => shippingLineCreditsService.listInvoices(filter),
({ page, pageSize, status, shippingLineId }) =>
QUERY_KEYS.SHIPPING_LINE_CREDITS.invoices(
page,
pageSize,
status,
shippingLineId,
),
),
pendingInvoiceActions: endpoint<
{ invoiceIds: string[] },
CreditInvoicePendingAction[]
>(
"shippingLineCredits",
"pendingInvoiceActions",
({ invoiceIds }) =>
shippingLineCreditsService.pendingInvoiceActions(invoiceIds),
({ invoiceIds }) =>
[
"shipping-line-credits",
"pending-actions",
[...invoiceIds].sort().join(","),
] as const,
),
requestInvoiceAction: endpoint<
{
invoiceId: string;
action: "MARK_PAID" | "CANCEL";
reason: string;
paymentReference?: string;
},
CreditInvoicePendingAction
>(
"shippingLineCredits",
"requestInvoiceAction",
({ invoiceId, action, reason, paymentReference }) =>
shippingLineCreditsService.requestInvoiceAction(
invoiceId,
action,
reason,
paymentReference,
),
undefined,
() => [QUERY_KEYS.SHIPPING_LINE_CREDITS.ROOT],
),
decideInvoiceAction: endpoint<
{ approvalId: string; approve: boolean; note?: string },
CreditInvoicePendingAction
>(
"shippingLineCredits",
"decideInvoiceAction",
({ approvalId, approve, note }) =>
shippingLineCreditsService.decideInvoiceAction(approvalId, approve, note),
undefined,
// Approving executes a billing action, so both surfaces move.
() => [QUERY_KEYS.SHIPPING_LINE_CREDITS.ROOT, QUERY_KEYS.INVOICES.ROOT],
),
},
customers: {
stats: endpoint<Record<string, never>, CompanyStats>(
"customers",

View File

@@ -0,0 +1,131 @@
import { api as apiClient } from "@/auth/http";
import { URL_CONSTANTS } from "@/constants/URLS";
import type {
CreditInvoicePendingAction,
GeneratedCreditInvoice,
OutstandingTotals,
PaginatedCreditInvoices,
PaginatedShippingLineCredits,
ShippingLineCreditStatus,
} from "@/types/shippingLineCredit";
export interface ShippingLineCreditListFilter {
page?: number;
pageSize?: number;
status?: ShippingLineCreditStatus;
/** Narrow to one line; omit for all lines. */
shippingLineId?: string;
}
export const shippingLineCreditsService = {
/** Outstanding totals — every line, or one line when an id is given. */
summary(shippingLineId?: string): Promise<OutstandingTotals> {
return apiClient
.get<OutstandingTotals>(URL_CONSTANTS.SHIPPING_LINE_CREDITS.SUMMARY, {
params: shippingLineId ? { shippingLineId } : {},
})
.then((r) => r.data);
},
/** The whole credit ledger, newest first, optionally filtered. */
list(
filter: ShippingLineCreditListFilter = {},
): Promise<PaginatedShippingLineCredits> {
const { page = 1, pageSize = 20, status, shippingLineId } = filter;
return apiClient
.get<PaginatedShippingLineCredits>(
URL_CONSTANTS.SHIPPING_LINE_CREDITS.BASE,
{
params: {
page,
pageSize,
...(status ? { status } : {}),
...(shippingLineId ? { shippingLineId } : {}),
},
},
)
.then((r) => r.data);
},
/**
* Bill a batch of unbilled credits as one invoice. The API enforces that all
* credits belong to one shipping line and share one currency.
*/
generateInvoice(
creditIds: string[],
dueInDays?: number,
): Promise<GeneratedCreditInvoice> {
return apiClient
.post<GeneratedCreditInvoice>(URL_CONSTANTS.SHIPPING_LINE_CREDITS.INVOICE, {
creditIds,
...(dueInDays ? { dueInDays } : {}),
})
.then((r) => r.data);
},
/** Credit invoices with any pending manual-action request attached. */
listInvoices(filter: {
page?: number;
pageSize?: number;
status?: string;
shippingLineId?: string;
} = {}): Promise<PaginatedCreditInvoices> {
const { page = 1, pageSize = 20, status, shippingLineId } = filter;
return apiClient
.get<PaginatedCreditInvoices>(URL_CONSTANTS.SHIPPING_LINE_CREDITS.INVOICES, {
params: {
page,
pageSize,
...(status ? { status } : {}),
...(shippingLineId ? { shippingLineId } : {}),
},
})
.then((r) => r.data);
},
/** Undecided manual-action requests for a batch of invoice ids. */
pendingInvoiceActions(
invoiceIds: string[],
): Promise<CreditInvoicePendingAction[]> {
if (!invoiceIds.length) return Promise.resolve([]);
return apiClient
.get<CreditInvoicePendingAction[]>(
`${URL_CONSTANTS.SHIPPING_LINE_CREDITS.BASE}/invoice-actions/pending`,
{ params: { invoiceIds: invoiceIds.join(",") } },
)
.then((r) => r.data);
},
/** Maker step: raise a mark-paid or cancel request on a credit invoice. */
requestInvoiceAction(
invoiceId: string,
action: "MARK_PAID" | "CANCEL",
reason: string,
paymentReference?: string,
): Promise<CreditInvoicePendingAction> {
const url =
action === "MARK_PAID"
? URL_CONSTANTS.SHIPPING_LINE_CREDITS.MARK_PAID_REQUEST(invoiceId)
: URL_CONSTANTS.SHIPPING_LINE_CREDITS.CANCEL_REQUEST(invoiceId);
return apiClient
.post<CreditInvoicePendingAction>(url, {
reason,
...(paymentReference ? { paymentReference } : {}),
})
.then((r) => r.data);
},
/** Decision step: approve (executes) or reject a pending request. */
decideInvoiceAction(
approvalId: string,
approve: boolean,
note?: string,
): Promise<CreditInvoicePendingAction> {
const url = approve
? URL_CONSTANTS.SHIPPING_LINE_CREDITS.APPROVE_ACTION(approvalId)
: URL_CONSTANTS.SHIPPING_LINE_CREDITS.REJECT_ACTION(approvalId);
return apiClient
.post<CreditInvoicePendingAction>(url, note ? { note } : {})
.then((r) => r.data);
},
};

View File

@@ -90,6 +90,9 @@ export interface BookingContainerLine {
containerNumber?: string | null;
quantity: number;
vgmPerUnitTons: number;
/** How many of this line are hazardous / refrigerated — 0 when none. */
hazardousQuantity?: number;
reeferQuantity?: number;
containerType?: {
id: string;
code?: string;
@@ -199,6 +202,7 @@ export interface BookingDetail {
/** Break-bulk (PER_ITEM) only: real total tons — cargoTotalWeightVgm then holds the item count. */
bulkTotalWeightTons?: number | null;
isHazardous: boolean;
isReefer?: boolean;
consolidationPartnerId?: string | null;
consolidationPartner?: BookingNamedRef & { reference?: string } | null;
priorityScore: number;

View File

@@ -0,0 +1,96 @@
/**
* The credit ledger for shipping lines — "use the service now, pay later".
* Mirrors `shipping-line-credits` API responses.
*/
export type ShippingLineCreditStatus =
| "UNBILLED"
| "BILLED"
| "PAID"
| "CANCELLED";
export interface ShippingLineCredit {
id: string;
shippingLineCompanyId: string;
bookingId: string;
/** Numeric column — serialized as a string by the API. */
amount: string;
currency: string;
status: ShippingLineCreditStatus;
description: string | null;
invoiceId: string | null;
billedAt: string | null;
paidAt: string | null;
cancelledAt: string | null;
cancellationReason: string | null;
createdAt: string;
booking?: { id: string; reference: string } | null;
invoice?: { id: string; invoiceNumber: string } | null;
shippingLineCompany?: { id: string; name: string } | null;
}
/** What one shipping line currently owes, split by billing stage. */
export interface OutstandingTotals {
unbilledAmount: number;
billedAmount: number;
totalOutstanding: number;
unbilledCount: number;
billedCount: number;
currency: string;
}
export interface PaginatedShippingLineCredits {
items: ShippingLineCredit[];
total: number;
page: number;
pageSize: number;
}
/** The invoice minted from a batch of unbilled credits (subset of fields). */
export interface GeneratedCreditInvoice {
id: string;
invoiceNumber: string;
totalAmount: string | number;
currency: string;
status: string;
dueDate: string | null;
}
export type CreditInvoiceActionType = "MARK_PAID" | "CANCEL";
export type CreditInvoiceActionStatus = "PENDING" | "APPROVED" | "REJECTED";
/** An undecided manual-action request attached to a credit invoice. */
export interface CreditInvoicePendingAction {
id: string;
invoiceId: string;
action: CreditInvoiceActionType;
status: CreditInvoiceActionStatus;
requestedBy: string;
reason: string;
paymentReference: string | null;
createdAt: string;
}
/** A credit invoice row in the staff list, enriched by the API. */
export interface CreditInvoice {
id: string;
invoiceNumber: string;
status: string;
currency: string;
totalAmount: string | number;
paidAmount: string | number;
balanceAmount: string | number;
issuedAt: string | null;
dueAt: string | null;
createdAt: string;
shippingLineCompanyId: string | null;
shippingLineName: string | null;
pendingAction: CreditInvoicePendingAction | null;
}
export interface PaginatedCreditInvoices {
items: CreditInvoice[];
total: number;
page: number;
pageSize: number;
}