Files
co-lite/solvway-admin-portal/app/components/inventory/StockOnHandReport.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
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
2026-11-26 15:55:45 +08:00

253 lines
9.3 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 { DataTable } from "@/app/components/ui/data-table";
import { FilterField, FilterPanel, FilterSearch, FilterSelect } from "@/app/components/ui/filter-panel";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { useListFilters } from "@/app/lib/hooks/useListFilters";
import { getStockOnHand } from "@/app/lib/services/adminStock";
import { listAdminWarehouses } from "@/app/lib/services/adminWarehouses";
import type { AdminWarehouse, StockOnHandRow, StockOnHandPage as StockOnHandPageData } from "@/app/lib/types";
import { downloadXlsx, toXlsx } from "@/app/lib/xlsx";
import { useTableSort } from "@/app/lib/hooks/useTableSort";
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
import { useT } from "@/app/lib/i18n/MessagesProvider";
// Stock on Hand report — paged table of current inventory levels per SKU. The Stock on Hand tab of
// the Inventory page (merge-inventory-page), which owns the warehouse filter so the stock forms can
// pre-fill it. No side-effects on GET/prefetch — all data loading goes through useEffect.
const DEFAULTS = { q: "", warehouse: "" };
const SOH_EXPORT_COLUMNS = [
{ key: "skuCode", title: "SKU code" },
{ key: "skuName", title: "SKU name" },
{ key: "stockOnHand", title: "Stock on hand" },
{ key: "committedQty", title: "Committed" },
{ key: "availableQty", title: "Available" },
{ key: "outQty", title: "Out qty" },
];
type SortArgs = { sortBy?: string; sortDir?: string };
function useStockOnHand(filters: typeof DEFAULTS, page: number, reloadKey: number, pageSize: number | null, sort: SortArgs) {
const [data, setData] = useState<StockOnHandPageData | 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);
getStockOnHand({
page: page - 1,
size: pageSize,
warehouseId: filters.warehouse || undefined,
q: filters.q || undefined,
...sort,
})
.then(result => {
if (!cancelled) setData(result);
})
.catch((err: unknown) => {
if (!cancelled)
setError(err instanceof Error ? err.message : "StockOnHandLoadFailed");
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [filters, page, reloadKey, pageSize, sort]);
return { data, loading, error, setError };
}
export interface StockOnHandReportProps {
/** Told the warehouse filter (URL state) so the Inventory page can pre-fill the stock forms. */
onWarehouseChange: (id: string | undefined) => void;
/** Called with the row's skuVariationId (several rows can share a SKU code). */
onViewMovements: (skuVariationId: string) => void;
reloadKey: number;
}
export function StockOnHandReport({ onWarehouseChange, onViewMovements, reloadKey }: StockOnHandReportProps) {
const t = useT();
const { tableRef, pageSize } = useFitPageSize();
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS, { prefix: "soh." });
const { sorting, onSortingChange, sortBy, sortDir } = useTableSort("soh.");
const sort = useMemo(() => (sortBy ? { sortBy, sortDir } : {}), [sortBy, sortDir]);
const [exporting, setExporting] = useState(false);
const { data, loading, error, setError } = useStockOnHand(filters, page, reloadKey, pageSize, sort);
useEffect(() => { onWarehouseChange(filters.warehouse || undefined); }, [filters.warehouse, onWarehouseChange]);
// Load active warehouses for the warehouse filter select.
const [warehouses, setWarehouses] = useState<AdminWarehouse[]>([]);
useEffect(() => {
let cancelled = false;
listAdminWarehouses()
.then(all => {
if (!cancelled) setWarehouses(all.filter(w => w.status === "Y"));
})
.catch(() => {
// Non-critical: filter renders without options.
});
return () => { cancelled = true; };
}, []);
const mounted = useRef(true);
useEffect(() => () => { mounted.current = false; }, []);
const warehouseOptions = useMemo(() => warehouses.map(w => ({ value: String(w.id), label: `${w.code} — ${w.name}` })), [warehouses]);
const columns = useMemo<ColumnDef<StockOnHandRow, unknown>[]>(
() => [
{ accessorKey: "skuCode", header: t("SkuFieldCode") },
{
accessorKey: "skuName",
header: t("SkuFieldName"),
// Several variations share a SKU name, so show the variation under it.
cell: ({ row }) => (
<div>
<div>{row.original.skuName}</div>
{row.original.variation && (
<div className="text-xs text-muted-foreground">{row.original.variation}</div>
)}
</div>
),
},
{
accessorKey: "stockOnHand",
header: t("BO_STOCK_ON_HAND"),
meta: { numeric: true },
},
{
accessorKey: "committedQty",
header: t("StockOnHandCommitted"),
meta: { numeric: true },
},
{
accessorKey: "availableQty",
header: t("StockOnHandAvailable"),
meta: { numeric: true },
cell: ({ getValue }) => {
const qty = getValue() as number;
return <span className={qty < 0 ? "text-negative" : undefined}>{qty}</span>;
},
},
{
accessorKey: "outQty",
header: t("StockOnHandOutQty"),
meta: { numeric: true },
},
{
id: "actions",
enableSorting: false,
header: "",
cell: ({ row }) => (
<Button
variant="link"
size="sm"
className="h-auto p-0 whitespace-nowrap"
aria-label={t("StockOnHandViewMovementsAria", { item: `${row.original.skuCode}${row.original.variation ? ` ${row.original.variation}` : ""}` })}
onClick={() => onViewMovements(row.original.skuVariationId)}
>
{t("StockOnHandMovements")}
</Button>
),
},
],
[t, onViewMovements],
);
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 getStockOnHand({
page: page0,
size,
warehouseId: filters.warehouse || undefined,
q: filters.q || undefined,
...sort,
});
return { rows: p.content, total: p.totalElements };
});
downloadXlsx(
"stock-on-hand.xlsx",
await toXlsx(all as unknown as Record<string, unknown>[], SOH_EXPORT_COLUMNS, "Stock on hand"),
);
} 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("SkuCodeOrNamePlaceholder")}>
<FilterSearch aria-label={t("SkuCodeOrNamePlaceholder")} className="w-full" placeholder={t("SkuCodeOrNamePlaceholder")} value={filters.q} onChange={q => set({ q })} />
</FilterField>
<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>
</FilterPanel>
<DataTable
label={t("BO_STOCK_ON_HAND")}
columns={columns}
data={data?.content ?? []}
total={totalElements}
page={displayPage}
pageSize={pageSize ?? MIN_PAGE_SIZE}
onPageChange={setPage}
isLoading={loading}
sorting={sorting}
onSortingChange={onSortingChange}
tableRef={tableRef}
// Keyed by variation: SKU codes repeat across variations, and duplicate React keys left stale
// rows on screen after a reload (fix-stock-on-hand-row-identity).
rowKey={row => row.skuVariationId}
empty={<EmptyState title={t("StockOnHandEmpty")} />}
/>
</div>
);
}