Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
411 lines
16 KiB
TypeScript
411 lines
16 KiB
TypeScript
"use client";
|
|
|
|
import { downloadBlob } from "@/app/lib/downloadDoPdf";
|
|
import { useEffect, useMemo, useState } from "react";
|
|
import { DataTable } from "@/app/components/ui/data-table";
|
|
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
|
import { Badge } from "@/app/components/ui/badge";
|
|
import { Button } from "@/app/components/ui/button";
|
|
import { FilterField, FilterPanel, FilterSearch, FilterSelect } from "@/app/components/ui/filter-panel";
|
|
import { useListFilters } from "@/app/lib/hooks/useListFilters";
|
|
import { useTableSort } from "@/app/lib/hooks/useTableSort";
|
|
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
|
|
import { listToIssue, type ToIssueRow, type IssueResult } from "@/app/lib/services/adminDeliveryOrders";
|
|
import { listAdminWarehouses } from "@/app/lib/services/adminWarehouses";
|
|
import type { AdminWarehouse } from "@/app/lib/types";
|
|
import { malaysiaToday } from "@/app/lib/malaysiaPeriod";
|
|
import { formatDateTime } from "@/app/lib/format";
|
|
import { MemberCell } from "@/app/components/members/MemberCell";
|
|
import { OverdueChip } from "./FulfilmentHealthStrip";
|
|
import { SelectionBar } from "./SelectionBar";
|
|
import { IssueDrawer } from "./IssueDrawer";
|
|
import { BulkIssueDialog } from "./BulkIssueDialog";
|
|
import { printDeliveryOrders } from "@/app/lib/services/adminFulfilment";
|
|
import { useListingExport } from "@/app/lib/useListingExport";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
import { DELIVERY_STATUS_VARIANT } from "./deliveryStatus";
|
|
import { FULFILMENT_TONE } from "@/app/lib/services/adminWebOrders";
|
|
import { Checkbox } from "@/app/components/ui/checkbox";
|
|
|
|
// Module-level so useListFilters sees a stable defaults object.
|
|
const TI_DEFAULTS = { warehouseId: "", pickupOption: "", documentNo: "", buyerCode: "", deliveryOrderStatus: "", overdue: "" };
|
|
|
|
// One call shared by the table fetch and the export, so they cannot drift.
|
|
function fetchToIssue(filters: Record<string, string>, page0: number, size: number, sortBy?: string, sortDir = "asc") {
|
|
const query = onlyNonEmpty(filters);
|
|
return sortBy ? listToIssue(query, page0, size, { sortBy, sortDir }) : listToIssue(query, page0, size);
|
|
}
|
|
|
|
function onlyNonEmpty(obj: Record<string, string>): Record<string, string> {
|
|
const result: Record<string, string> = {};
|
|
for (const [k, v] of Object.entries(obj)) {
|
|
if (v) result[k] = v;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
/** "To issue" tab — list of paid orders waiting to be issued, with a per-row Issue drawer. */
|
|
export function ToIssueTab() {
|
|
const t = useT();
|
|
const { filters, page, set, setPage, clear, activeCount } = useListFilters(TI_DEFAULTS, { prefix: "ti." });
|
|
const { sorting, onSortingChange, sortBy, sortDir } = useTableSort("ti.");
|
|
const [reloadKey, setReloadKey] = useState(0);
|
|
const [rows, setRows] = useState<ToIssueRow[]>([]);
|
|
const [total, setTotal] = useState(0);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const { tableRef, pageSize } = useFitPageSize();
|
|
|
|
// ── Data load ──
|
|
useEffect(() => {
|
|
if (pageSize == null) return;
|
|
let cancelled = false;
|
|
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error ahead of the filters/page/reloadKey-triggered fetch below, which is the actual synchronization.
|
|
setLoading(true);
|
|
setError(null);
|
|
fetchToIssue(filters, page - 1, pageSize, sortBy, sortDir)
|
|
.then(r => {
|
|
if (!cancelled) {
|
|
setRows(r.content);
|
|
setTotal(r.totalElements);
|
|
}
|
|
})
|
|
.catch(err => {
|
|
if (!cancelled) setError(err instanceof Error ? err.message : String(err));
|
|
})
|
|
.finally(() => {
|
|
if (!cancelled) setLoading(false);
|
|
});
|
|
return () => { cancelled = true; };
|
|
}, [filters, page, pageSize, reloadKey, sortBy, sortDir]);
|
|
|
|
// ── Warehouse list ──
|
|
const [warehouses, setWarehouses] = useState<AdminWarehouse[]>([]);
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
listAdminWarehouses()
|
|
.then(w => { if (!cancelled) setWarehouses(w); })
|
|
.catch(() => {});
|
|
return () => { cancelled = true; };
|
|
}, []);
|
|
|
|
const warehouseById = useMemo(
|
|
() => new Map(warehouses.map(w => [String(w.id), w])),
|
|
[warehouses],
|
|
);
|
|
|
|
// ── Open state for the Issue drawer ──
|
|
const [open, setOpen] = useState<{ uuid: string; documentNo: string } | null>(null);
|
|
const [notice, setNotice] = useState("");
|
|
|
|
// ── Bulk selection state ──
|
|
// Ticks belong to the page on screen: a page, filter or reload change clears them.
|
|
const selectionKey = JSON.stringify([page, filters, reloadKey, sortBy, sortDir]);
|
|
const [selection, setSelection] = useState<{ key: string; uuids: Set<string> }>({ key: "", uuids: new Set() });
|
|
const selected = useMemo(() => (selection.key === selectionKey ? selection.uuids : new Set<string>()), [selection, selectionKey]);
|
|
// Frozen when the dialog opens, so a re-render cannot reload its plans mid-run.
|
|
const [bulkOrders, setBulkOrders] = useState<{ uuid: string; documentNo: string; transactionDateTime: string }[] | null>(null);
|
|
const [slipUuids, setSlipUuids] = useState<string[]>([]);
|
|
const [slipError, setSlipError] = useState<string | null>(null);
|
|
|
|
function handleIssued(result: IssueResult) {
|
|
setNotice(t("FulIssuedToast", { doNumbers: result.deliveryOrderNumbers.join(", "), left: result.outstandingUnits }));
|
|
setOpen(null);
|
|
setReloadKey(k => k + 1);
|
|
setSlipUuids(result.deliveryOrderUuids);
|
|
}
|
|
|
|
// ── Warehouse picker options (all warehouses) ──
|
|
const warehouseOptions = useMemo(
|
|
() => warehouses.map(w => ({ value: String(w.id), label: `${w.code} — ${w.name}` })),
|
|
[warehouses],
|
|
);
|
|
|
|
// Fulfilment filter options
|
|
const fulfilmentOptions = [
|
|
{ value: "false", label: t("Delivery") },
|
|
{ value: "true", label: t("Pickup") },
|
|
];
|
|
|
|
// Status filter options
|
|
const statusOptions = [
|
|
{ value: "PE", label: t("FulAwaitingIssue") },
|
|
{ value: "PA", label: t("FulPartlyIssued") },
|
|
];
|
|
|
|
const selectedRows = useMemo(() => rows.filter(r => selected.has(r.uuid)), [rows, selected]);
|
|
|
|
|
|
async function handlePrintSlip() {
|
|
setSlipError(null);
|
|
try {
|
|
const result = await printDeliveryOrders({ uuids: slipUuids });
|
|
downloadBlob(result.pdf, "packing-slip.pdf");
|
|
} catch (err) {
|
|
setSlipError(err instanceof Error ? err.message : t("FulPrintFailed"));
|
|
}
|
|
}
|
|
|
|
const listingExport = useListingExport<ToIssueRow>(
|
|
"delivery-orders-to-issue", t("FulChipToIssue"), total,
|
|
async (page0, size) => {
|
|
const r = await fetchToIssue(filters, page0, size, sortBy, sortDir);
|
|
return { rows: r.content ?? [], total: r.totalElements ?? 0 };
|
|
},
|
|
[
|
|
{ key: "invoice", title: t("FulColInvoice") },
|
|
{ key: "memberCode", title: t("MemberCode") },
|
|
{ key: "memberName", title: t("MemberName") },
|
|
{ key: "paidOn", title: t("FulColPaidOn") },
|
|
{ key: "fulfilment", title: t("FulColFulfilment") },
|
|
{ key: "warehouse", title: t("FulColWarehouse") },
|
|
{ key: "items", title: t("FulColItems") },
|
|
{ key: "status", title: t("FulColStatus") },
|
|
],
|
|
r => {
|
|
const w = warehouseById.get(r.warehouseId);
|
|
return {
|
|
invoice: r.documentNo,
|
|
memberCode: r.buyerCode ?? "",
|
|
memberName: r.buyer?.buyerName ?? "",
|
|
paidOn: formatDateTime(r.transactionDateTime),
|
|
fulfilment: r.pickupOption ? t("Pickup") : t("Delivery"),
|
|
warehouse: w ? `${w.code} — ${w.name}` : r.warehouseId,
|
|
items: t("FulItemsToIssue", { outstanding: r.orderedUnits - r.issuedUnits, ordered: r.orderedUnits }),
|
|
status: r.deliveryOrderStatus === "PE" ? t("FulAwaitingIssue") : r.deliveryOrderStatus === "PA" ? t("FulPartlyIssued") : r.deliveryOrderStatus,
|
|
};
|
|
},
|
|
);
|
|
|
|
// ── Columns (with checkbox as first column) ──
|
|
const columns = useMemo(() => [
|
|
{
|
|
id: "select",
|
|
enableSorting: false,
|
|
header: () => null,
|
|
cell: ({ row }: { row: { original: ToIssueRow } }) => (
|
|
<Checkbox
|
|
aria-label={t("FulSelectRow", { ref: row.original.documentNo })}
|
|
checked={selected.has(row.original.uuid)}
|
|
onCheckedChange={() => {
|
|
const next = new Set(selected);
|
|
if (!next.delete(row.original.uuid)) next.add(row.original.uuid);
|
|
setSelection({ key: selectionKey, uuids: next });
|
|
}}
|
|
/>
|
|
),
|
|
},
|
|
{ accessorKey: "documentNo", header: t("FulColInvoice") },
|
|
{
|
|
id: "member",
|
|
accessorFn: (r: ToIssueRow) => r.buyerCode,
|
|
header: t("FulColMember"),
|
|
cell: ({ row }: { row: { original: ToIssueRow } }) => (
|
|
<MemberCell code={row.original.buyerCode} name={row.original.buyer?.buyerName} />
|
|
),
|
|
},
|
|
{
|
|
id: "paidOn",
|
|
accessorFn: (r: ToIssueRow) => r.transactionDateTime,
|
|
header: t("FulColPaidOn"),
|
|
cell: ({ row }: { row: { original: ToIssueRow } }) => {
|
|
const dt = row.original.transactionDateTime;
|
|
// Both dates are Malaysia calendar days; parse as UTC midnight so the difference is whole days.
|
|
const days = Math.max(0, Math.round(
|
|
(Date.parse(`${malaysiaToday()}T00:00:00Z`) - Date.parse(`${dt.slice(0, 10)}T00:00:00Z`)) / 86400000));
|
|
// Waiting to issue is overdue after more than 1 day (fulfilment-health spec), so the age chip
|
|
// turns negative on the same rule the health strip counts, with a word, not colour alone.
|
|
const overdue = days > 1;
|
|
return (
|
|
<span className="inline-flex flex-wrap items-center gap-2">
|
|
<span className="tabular">{formatDateTime(dt)}</span>
|
|
<Badge variant={overdue ? "negative" : "neutral"} className="gap-1">
|
|
<span className="tabular">{t("FulAgeDays", { days })}</span>
|
|
{overdue && <span>· {t("FulHealthOverdue")}</span>}
|
|
</Badge>
|
|
</span>
|
|
);
|
|
},
|
|
},
|
|
{
|
|
id: "fulfilment",
|
|
accessorFn: (r: ToIssueRow) => !!r.pickupOption,
|
|
header: t("FulColFulfilment"),
|
|
cell: ({ row }: { row: { original: ToIssueRow } }) => (
|
|
<Badge variant={FULFILMENT_TONE[row.original.pickupOption ? "PICKUP" : "DELIVERY"]}>
|
|
{row.original.pickupOption ? t("Pickup") : t("Delivery")}
|
|
</Badge>
|
|
),
|
|
},
|
|
{
|
|
id: "warehouse",
|
|
accessorFn: (r: ToIssueRow) => r.warehouseId,
|
|
header: t("FulColWarehouse"),
|
|
cell: ({ row }: { row: { original: ToIssueRow } }) => {
|
|
const w = warehouseById.get(row.original.warehouseId);
|
|
return w ? `${w.code} — ${w.name}` : row.original.warehouseId;
|
|
},
|
|
},
|
|
{
|
|
id: "items",
|
|
accessorFn: (r: ToIssueRow) => r.orderedUnits - r.issuedUnits,
|
|
header: t("FulColItems"),
|
|
cell: ({ row }: { row: { original: ToIssueRow } }) => {
|
|
const { orderedUnits, issuedUnits } = row.original;
|
|
const issued = orderedUnits > 0 ? Math.min(1, issuedUnits / orderedUnits) : 0;
|
|
return (
|
|
<span className="flex min-w-32 flex-col gap-1">
|
|
<span>{t("FulItemsToIssue", { outstanding: orderedUnits - issuedUnits, ordered: orderedUnits })}</span>
|
|
{/* Share already issued; the sentence above is the content. */}
|
|
<span aria-hidden="true" className="h-1.5 w-full overflow-hidden rounded-full bg-muted">
|
|
<span className="block h-full rounded-full bg-contrast" style={{ width: `${issued * 100}%` }} />
|
|
</span>
|
|
</span>
|
|
);
|
|
},
|
|
},
|
|
{
|
|
id: "status",
|
|
accessorFn: (r: ToIssueRow) => r.deliveryOrderStatus,
|
|
header: t("FulColStatus"),
|
|
cell: ({ row }: { row: { original: ToIssueRow } }) => {
|
|
const status = row.original.deliveryOrderStatus;
|
|
const label = status === "PE" ? t("FulAwaitingIssue") : status === "PA" ? t("FulPartlyIssued") : status;
|
|
return (
|
|
<Badge variant={DELIVERY_STATUS_VARIANT[status] ?? "neutral"}>{label}</Badge>
|
|
);
|
|
},
|
|
},
|
|
{
|
|
id: "action",
|
|
enableSorting: false,
|
|
header: () => <span className="sr-only" />,
|
|
cell: ({ row }: { row: { original: ToIssueRow } }) => (
|
|
<Button
|
|
size="sm"
|
|
onClick={() => { setNotice(""); setOpen({ uuid: row.original.uuid, documentNo: row.original.documentNo }); }}
|
|
>
|
|
{t("FulIssue")}
|
|
</Button>
|
|
),
|
|
},
|
|
], [t, warehouseById, selected, selectionKey]);
|
|
|
|
return (
|
|
<div>
|
|
{slipUuids.length > 0 && (
|
|
<div className="mb-4">
|
|
<Button variant="outline" size="sm" onClick={handlePrintSlip}>{t("FulPrintPackingSlip")}</Button>
|
|
</div>
|
|
)}
|
|
{slipError && <ErrorState message={slipError} className="mb-4" />}
|
|
{listingExport.errorLine}
|
|
|
|
<OverdueChip overdue={filters.overdue} onClear={() => set({ overdue: "" })} />
|
|
<FilterPanel activeCount={activeCount} onClear={clear} actions={listingExport.button} className="mb-4">
|
|
<FilterField label={t("FulWarehouse")}>
|
|
<FilterSelect
|
|
className="w-full"
|
|
aria-label={t("FulWarehouseFilter")}
|
|
allLabel={t("FulAllWarehouses")}
|
|
options={warehouseOptions}
|
|
value={filters.warehouseId}
|
|
onChange={warehouseId => set({ warehouseId })}
|
|
/>
|
|
</FilterField>
|
|
<FilterField label={t("FulFulfilment")}>
|
|
<FilterSelect
|
|
className="w-full"
|
|
aria-label={t("FulFulfilment")}
|
|
allLabel={t("FulChipAll")}
|
|
options={fulfilmentOptions}
|
|
value={filters.pickupOption}
|
|
onChange={pickupOption => set({ pickupOption })}
|
|
/>
|
|
</FilterField>
|
|
<FilterField label={t("FulInvoiceNo")}>
|
|
<FilterSearch
|
|
className="w-full"
|
|
aria-label={t("FulInvoiceNo")}
|
|
placeholder={t("FulInvoiceNo")}
|
|
value={filters.documentNo}
|
|
onChange={documentNo => set({ documentNo })}
|
|
/>
|
|
</FilterField>
|
|
<FilterField label={t("FulMemberCode")}>
|
|
<FilterSearch
|
|
className="w-full"
|
|
aria-label={t("FulMemberCode")}
|
|
placeholder={t("FulMemberCode")}
|
|
value={filters.buyerCode}
|
|
onChange={buyerCode => set({ buyerCode })}
|
|
/>
|
|
</FilterField>
|
|
<FilterField label={t("FulIssueStatus")}>
|
|
<FilterSelect
|
|
className="w-full"
|
|
aria-label={t("FulIssueStatus")}
|
|
allLabel={t("AllStatuses")}
|
|
options={statusOptions}
|
|
value={filters.deliveryOrderStatus}
|
|
onChange={deliveryOrderStatus => set({ deliveryOrderStatus })}
|
|
/>
|
|
</FilterField>
|
|
</FilterPanel>
|
|
|
|
{/* Success notice */}
|
|
{notice && (
|
|
<p role="status" className="mb-4 text-sm">{notice}</p>
|
|
)}
|
|
|
|
{error && <ErrorState message={error} className="mb-4" />}
|
|
|
|
{/* Feedback 2026-10-26: a selection bar that appears once rows are ticked, instead of a
|
|
permanently disabled "Issue selected" on its own row. */}
|
|
{selectedRows.length > 0 && (
|
|
<SelectionBar count={t("FulSelectedCount", { count: selectedRows.length })}>
|
|
<Button variant="outline" size="sm" onClick={() => setSelection({ key: selectionKey, uuids: new Set() })}>
|
|
{t("FulClearSelection")}
|
|
</Button>
|
|
<Button size="sm" onClick={() => setBulkOrders(selectedRows.map(r => ({ uuid: r.uuid, documentNo: r.documentNo, transactionDateTime: r.transactionDateTime })))}>
|
|
{t("FulIssueSelected")}
|
|
</Button>
|
|
</SelectionBar>
|
|
)}
|
|
<DataTable
|
|
label={t("FulChipToIssue")}
|
|
columns={columns}
|
|
data={rows}
|
|
total={total}
|
|
page={page}
|
|
pageSize={pageSize ?? MIN_PAGE_SIZE}
|
|
onPageChange={setPage}
|
|
isLoading={loading}
|
|
sorting={sorting}
|
|
onSortingChange={onSortingChange}
|
|
rowKey={r => r.uuid}
|
|
empty={<EmptyState title={t("FulToIssueEmpty")} />}
|
|
tableRef={tableRef}
|
|
/>
|
|
|
|
<IssueDrawer
|
|
orderUuid={open?.uuid ?? null}
|
|
invoice={open?.documentNo ?? ""}
|
|
onClose={() => setOpen(null)}
|
|
onIssued={handleIssued}
|
|
/>
|
|
|
|
{bulkOrders && (
|
|
<BulkIssueDialog
|
|
orders={bulkOrders}
|
|
onClose={(uuids) => {
|
|
setBulkOrders(null);
|
|
setReloadKey(k => k + 1);
|
|
if (uuids.length) setSlipUuids(uuids);
|
|
}}
|
|
/>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|