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
375 lines
15 KiB
TypeScript
375 lines
15 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useMemo, useRef, useState } from "react";
|
|
import { exportErrorText, fetchAllForExport } from "@/app/lib/exportAll";
|
|
import { Download, Loader2 } from "lucide-react";
|
|
import type { ColumnDef } from "@tanstack/react-table";
|
|
import { Button } from "@/app/components/ui/button";
|
|
import { DateRangePicker } from "@/app/components/ui/date-range-picker";
|
|
import { Command, CommandGroup, CommandInput, CommandItem, CommandList } from "@/app/components/ui/command";
|
|
import { FilterField, FilterPanel, FilterSelect } from "@/app/components/ui/filter-panel";
|
|
import { Popover, PopoverAnchor, PopoverContent } from "@/app/components/ui/popover";
|
|
import { useListFilters } from "@/app/lib/hooks/useListFilters";
|
|
import { useTableSort } from "@/app/lib/hooks/useTableSort";
|
|
import { DataTable } from "@/app/components/ui/data-table";
|
|
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
|
import { getMovements, getSkuCatalog } from "@/app/lib/services/adminStock";
|
|
import { listAdminWarehouses } from "@/app/lib/services/adminWarehouses";
|
|
import type {
|
|
AdminWarehouse,
|
|
MovementHistoryRow,
|
|
MovementHistoryPage as MovementHistoryPageData,
|
|
SkuCatalogRow,
|
|
} from "@/app/lib/types";
|
|
import { formatDateTime } from "@/app/lib/format";
|
|
import { downloadXlsx, toXlsx } from "@/app/lib/xlsx";
|
|
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
|
|
// Movement History report — paged audit log of all inventory movements. The History tab of the
|
|
// Inventory page (merge-inventory-page). No side-effects on GET/prefetch — all data loading goes
|
|
// through useEffect.
|
|
|
|
// Known InventoryTrxnType enum codes from service-inventory. The backend does
|
|
// InventoryTrxnType.valueOf(value), so only these exact codes are valid —
|
|
// a free-text input with an invalid code (e.g. "STOCK_IN" for STI) silently
|
|
// returns an empty result. A <Select> makes an invalid code impossible.
|
|
export const TRXN_TYPES: readonly { readonly value: string; readonly labelCode: string }[] = [
|
|
{ value: "STI", labelCode: "BO_STOCK_IN" },
|
|
{ value: "TRF", labelCode: "InvActionTransfer" },
|
|
{ value: "AJI", labelCode: "StockMoveAdjustIn" },
|
|
{ value: "AJO", labelCode: "StockMoveAdjustOut" },
|
|
{ value: "SO", labelCode: "StockMoveTypeSalesOut" },
|
|
{ value: "DO", labelCode: "DoDeliveryOrder" },
|
|
{ value: "VDO", labelCode: "StockMoveTypeVdo" },
|
|
];
|
|
|
|
// Codes no live code writes any more: shown on old rows, not offered as a filter.
|
|
const LEGACY_TRXN_LABELS: Record<string, string> = { SR: "StockMoveReturn", SC: "StockMoveCount" };
|
|
|
|
const MOVEMENT_EXPORT_COLUMNS = [
|
|
{ key: "trxnDate", title: "Date" },
|
|
{ key: "warehouseName", title: "Warehouse" },
|
|
{ key: "skuLabel", title: "SKU" },
|
|
{ key: "trxnType", title: "Type" },
|
|
{ key: "quantityIn", title: "In" },
|
|
{ key: "quantityOut", title: "Out" },
|
|
{ key: "batchNumber", title: "Batch" },
|
|
{ key: "refNo", title: "Ref" },
|
|
{ key: "remark", title: "Remark" },
|
|
];
|
|
|
|
type MovementFilters = { warehouse: string; sku: string; type: string; from: string; to: string };
|
|
|
|
function useMovements(
|
|
filters: MovementFilters,
|
|
page: number,
|
|
reloadKey: number,
|
|
pageSize: number | null,
|
|
sortBy?: string,
|
|
sortDir?: "asc" | "desc",
|
|
) {
|
|
const [data, setData] = useState<MovementHistoryPageData | null>(null);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
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/sort-triggered fetch below, which is the actual synchronization.
|
|
setLoading(true);
|
|
setError(null);
|
|
getMovements({ ...movementParams(filters, page - 1, pageSize), sortBy, sortDir })
|
|
.then(result => {
|
|
if (!cancelled) setData(result);
|
|
})
|
|
.catch((err: unknown) => {
|
|
if (!cancelled)
|
|
setError(err instanceof Error ? err.message : "StockMoveLoadFailed");
|
|
})
|
|
.finally(() => {
|
|
if (!cancelled) setLoading(false);
|
|
});
|
|
return () => { cancelled = true; };
|
|
}, [filters, page, reloadKey, pageSize, sortBy, sortDir]);
|
|
|
|
return { data, loading, error, setError };
|
|
}
|
|
|
|
function movementParams(f: MovementFilters, page: number, size: number) {
|
|
return {
|
|
page,
|
|
size,
|
|
warehouseId: f.warehouse || undefined,
|
|
skuVariationId: f.sku || undefined,
|
|
trxnType: f.type || undefined,
|
|
dateFrom: f.from || undefined,
|
|
dateTo: f.to || undefined,
|
|
};
|
|
}
|
|
|
|
/** "BA-002 — Nursing Bra (Colour: Black)": variations of one SKU share code and name. */
|
|
function skuDisplayLabel(sku: SkuCatalogRow): string {
|
|
const base = `${sku.skuCode} — ${sku.skuName}`;
|
|
return sku.variation ? `${base} (${sku.variation})` : base;
|
|
}
|
|
|
|
type Parts = { name: string; code?: string };
|
|
|
|
/** Name on the first line, code on a muted second line. */
|
|
function TwoLine({ name, code }: Parts) {
|
|
return (
|
|
<div className="flex flex-col">
|
|
<span>{name}</span>
|
|
{code && <span className="text-xs text-muted-foreground">{code}</span>}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** Enrich a row with human-readable labels derived from the warehouse and SKU catalog lists. */
|
|
function enrichRow(
|
|
row: MovementHistoryRow,
|
|
warehouseMap: Map<string, AdminWarehouse>,
|
|
skuMap: Map<string, SkuCatalogRow>,
|
|
): Record<string, unknown> {
|
|
const wh = warehouseMap.get(row.warehouseId);
|
|
const warehouseName = wh ? `${wh.code} — ${wh.name}` : row.warehouseId;
|
|
const sku = skuMap.get(row.skuVariationId);
|
|
const skuLabel = sku ? skuDisplayLabel(sku) : row.skuVariationId;
|
|
return {
|
|
...row,
|
|
warehouseName,
|
|
skuLabel,
|
|
warehouseParts: wh ? { name: wh.name, code: wh.code } : { name: row.warehouseId },
|
|
skuParts: sku ? { name: sku.variation ? `${sku.skuName} (${sku.variation})` : sku.skuName, code: sku.skuCode } : { name: row.skuVariationId },
|
|
};
|
|
}
|
|
|
|
export interface MovementHistoryReportProps {
|
|
reloadKey: number;
|
|
}
|
|
|
|
const DEFAULTS: MovementFilters = { warehouse: "", sku: "", type: "", from: "", to: "" };
|
|
|
|
/** Searchable SKU filter: the loaded catalogue filtered client-side by code or name; value = skuVariationId. */
|
|
function SkuPicker({ options, value, onChange }: { options: SkuCatalogRow[]; value: string; onChange: (id: string) => void }) {
|
|
const t = useT();
|
|
const [open, setOpen] = useState(false);
|
|
const [query, setQuery] = useState("");
|
|
const selected = options.find(o => o.skuVariationId === value);
|
|
const term = query.trim().toLowerCase();
|
|
const matches = term
|
|
? options.filter(o => `${o.skuCode} ${o.skuName}`.toLowerCase().includes(term))
|
|
: options;
|
|
const pick = (id: string) => { onChange(id); setOpen(false); };
|
|
|
|
return (
|
|
<Popover open={open} onOpenChange={setOpen}>
|
|
<Command shouldFilter={false} label={t("StockMoveSkuFilterLabel")} className="overflow-visible bg-transparent">
|
|
<PopoverAnchor asChild>
|
|
<div className="flex h-9 w-full items-center sm:w-52 rounded-md border border-input bg-transparent shadow-sm transition-[color,box-shadow] focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50 dark:bg-input/30 [&_[data-slot=command-input-wrapper]]:h-full [&_[data-slot=command-input-wrapper]]:flex-1 [&_[data-slot=command-input-wrapper]]:border-b-0 [&_[data-slot=command-input]]:h-full [&_[data-slot=command-input]]:py-0 [&_[data-slot=command-input]]:outline-none">
|
|
<CommandInput
|
|
value={open ? query : selected ? skuDisplayLabel(selected) : value}
|
|
onValueChange={v => { setQuery(v); setOpen(true); }}
|
|
onFocus={() => { setQuery(""); setOpen(true); }}
|
|
placeholder={t("StockMoveAllSkus")}
|
|
/>
|
|
</div>
|
|
</PopoverAnchor>
|
|
<PopoverContent
|
|
className="w-[var(--radix-popover-trigger-width)] p-0"
|
|
align="start"
|
|
onOpenAutoFocus={e => e.preventDefault()}
|
|
>
|
|
<CommandList>
|
|
<CommandGroup>
|
|
{!term && <CommandItem value="__all__" onSelect={() => pick("")}>{t("StockMoveAllSkus")}</CommandItem>}
|
|
{matches.map(sku => (
|
|
<CommandItem key={sku.skuVariationId} value={sku.skuVariationId} onSelect={() => pick(sku.skuVariationId)}>
|
|
{skuDisplayLabel(sku)}
|
|
</CommandItem>
|
|
))}
|
|
{term && matches.length === 0 && (
|
|
<div className="px-3 py-6 text-center text-sm text-muted-foreground">{t("StockMoveNoSkuMatch")}</div>
|
|
)}
|
|
</CommandGroup>
|
|
</CommandList>
|
|
</PopoverContent>
|
|
</Command>
|
|
</Popover>
|
|
);
|
|
}
|
|
|
|
export function MovementHistoryReport({ reloadKey }: MovementHistoryReportProps) {
|
|
const t = useT();
|
|
// The View movements deep link is plain mv.* URL state (written by the Inventory page).
|
|
const { tableRef, pageSize } = useFitPageSize();
|
|
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS, { prefix: "mv." });
|
|
const { sorting, onSortingChange, sortBy, sortDir } = useTableSort("mv.");
|
|
const [exporting, setExporting] = useState(false);
|
|
const { data, loading, error, setError } = useMovements(filters, page, reloadKey, pageSize, sortBy, sortDir);
|
|
|
|
// Load all warehouses (inactive ones, e.g. closed events, still have history) for the filter select and label resolution.
|
|
const [warehouses, setWarehouses] = useState<AdminWarehouse[]>([]);
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
listAdminWarehouses()
|
|
.then(all => {
|
|
if (!cancelled) setWarehouses(all);
|
|
})
|
|
.catch(() => {
|
|
// Non-critical: filter renders without options.
|
|
});
|
|
return () => { cancelled = true; };
|
|
}, []);
|
|
|
|
// Load SKU catalog for the SKU label column and the SKU filter (skuCode — skuName).
|
|
const [skuCatalog, setSkuCatalog] = useState<SkuCatalogRow[]>([]);
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
getSkuCatalog()
|
|
.then(catalog => {
|
|
if (!cancelled) setSkuCatalog(catalog);
|
|
})
|
|
.catch(() => {
|
|
// Non-critical: SKU column falls back to raw skuVariationId.
|
|
});
|
|
return () => { cancelled = true; };
|
|
}, []);
|
|
|
|
const warehouseMap = useMemo(
|
|
() => new Map(warehouses.map(w => [String(w.id), w])),
|
|
[warehouses],
|
|
);
|
|
|
|
const skuMap = useMemo(
|
|
() => new Map(skuCatalog.map(s => [s.skuVariationId, s])),
|
|
[skuCatalog],
|
|
);
|
|
|
|
const mounted = useRef(true);
|
|
useEffect(() => () => { mounted.current = false; }, []);
|
|
|
|
const warehouseOptions = useMemo(() => warehouses.map(w => {
|
|
const label = `${w.code} — ${w.name}`;
|
|
return { value: String(w.id), label: w.status === "Y" ? label : t("RptSupplierInactive", { name: label }) };
|
|
}), [warehouses, t]);
|
|
|
|
const trxntypeOptions = useMemo(() => TRXN_TYPES.map(x => ({ value: x.value, label: t(x.labelCode) })), [t]);
|
|
|
|
const columns = useMemo<ColumnDef<Record<string, unknown>, unknown>[]>(
|
|
() => [
|
|
{
|
|
accessorKey: "trxnDate",
|
|
header: t("Date"),
|
|
cell: ({ getValue }) => <span className="tabular">{formatDateTime(getValue() as string | null)}</span>,
|
|
},
|
|
{ id: "warehouse", accessorKey: "warehouseName", header: t("Warehouse"), cell: ({ row }) => <TwoLine {...(row.original.warehouseParts as Parts)} /> },
|
|
{ id: "sku", accessorKey: "skuLabel", header: t("Sku"), cell: ({ row }) => <TwoLine {...(row.original.skuParts as Parts)} /> },
|
|
{
|
|
accessorKey: "trxnType",
|
|
header: t("Type"),
|
|
cell: ({ getValue }) => {
|
|
const code = getValue() as string;
|
|
const tt = TRXN_TYPES.find(x => x.value === code);
|
|
const label = tt ? t(tt.labelCode) : LEGACY_TRXN_LABELS[code] ? t(LEGACY_TRXN_LABELS[code]) : code;
|
|
return label;
|
|
},
|
|
},
|
|
{ accessorKey: "quantityIn", header: t("In"), meta: { numeric: true } },
|
|
{ accessorKey: "quantityOut", header: t("Out"), meta: { numeric: true } },
|
|
{ accessorKey: "batchNumber", header: t("StockMoveBatch") },
|
|
{ accessorKey: "refNo", header: t("StockMoveRef") },
|
|
{ accessorKey: "remark", header: t("Remark") },
|
|
],
|
|
[t],
|
|
);
|
|
|
|
const enrichedRows = useMemo(
|
|
() => (data?.content ?? []).map(row => enrichRow(row, warehouseMap, skuMap)),
|
|
[data?.content, warehouseMap, skuMap],
|
|
);
|
|
|
|
async function handleExport() {
|
|
setExporting(true);
|
|
setError(null);
|
|
try {
|
|
// portal-query-allowlist (F38): page through 500 rows at a time (mobile-api refuses size > 500); never a
|
|
// partial file.
|
|
const all = await fetchAllForExport(async (page0, size) => {
|
|
const p = await getMovements(movementParams(filters, page0, size));
|
|
return { rows: p.content, total: p.totalElements };
|
|
});
|
|
const enriched = all.map(row => enrichRow(row, warehouseMap, skuMap));
|
|
downloadXlsx(
|
|
"movement-history.xlsx",
|
|
await toXlsx(enriched, MOVEMENT_EXPORT_COLUMNS, "Movement history"),
|
|
);
|
|
} catch (err: unknown) {
|
|
setError(exportErrorText(err, t));
|
|
} finally {
|
|
if (mounted.current) setExporting(false);
|
|
}
|
|
}
|
|
|
|
const displayPage = page;
|
|
const totalElements = data?.totalElements ?? 0;
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
{error && <ErrorState message={t(error)} />}
|
|
|
|
<FilterPanel
|
|
activeCount={activeCount}
|
|
onClear={clear}
|
|
actions={
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
className="h-9"
|
|
onClick={handleExport}
|
|
disabled={exporting || totalElements === 0}
|
|
data-loading={exporting ? "true" : undefined}
|
|
>
|
|
{exporting ? (
|
|
<Loader2 aria-hidden="true" className="size-4 animate-spin" />
|
|
) : (
|
|
<Download aria-hidden="true" className="size-4" />
|
|
)}
|
|
{t("ExportXlsx")}
|
|
</Button>
|
|
}
|
|
>
|
|
<FilterField label={t("Warehouse")}>
|
|
<FilterSelect aria-label={t("CatWarehouseFilter")} className="w-full" allLabel={t("CatAllWarehouses")} options={warehouseOptions} value={filters.warehouse} onChange={warehouse => set({ warehouse })} />
|
|
</FilterField>
|
|
<FilterField label={t("Sku")}>
|
|
<SkuPicker options={skuCatalog} value={filters.sku} onChange={sku => set({ sku })} />
|
|
</FilterField>
|
|
<FilterField label={t("Type")}>
|
|
<FilterSelect aria-label={t("StockMoveTypeFilter")} className="w-full" allLabel={t("AllTypes")} options={trxntypeOptions} value={filters.type} onChange={type => set({ type })} />
|
|
</FilterField>
|
|
<FilterField label={t("Date")}>
|
|
<DateRangePicker fromLabel={t("CatDateFrom")} toLabel={t("CatDateTo")} value={{ from: filters.from, to: filters.to }} onChange={r => set({ from: r.from, to: r.to })} />
|
|
</FilterField>
|
|
</FilterPanel>
|
|
|
|
<DataTable
|
|
label={t("BO_MOVEMENT_HISTORY")}
|
|
columns={columns}
|
|
data={enrichedRows}
|
|
total={totalElements}
|
|
page={displayPage}
|
|
pageSize={pageSize ?? MIN_PAGE_SIZE}
|
|
onPageChange={setPage}
|
|
isLoading={loading}
|
|
tableRef={tableRef}
|
|
sorting={sorting}
|
|
onSortingChange={onSortingChange}
|
|
rowKey={row => String(row.id)}
|
|
empty={<EmptyState title={t("StockMoveEmpty")} />}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|