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
297 lines
13 KiB
TypeScript
297 lines
13 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
import type { SortingState } from "@tanstack/react-table";
|
|
import Link from "next/link";
|
|
import { Badge } from "@/app/components/ui/badge";
|
|
import { Button } from "@/app/components/ui/button";
|
|
import { Input } from "@/app/components/ui/input";
|
|
import { PageHeader } from "@/app/components/ui/page-header";
|
|
import { ErrorState, TableSkeleton } from "@/app/components/ui/states";
|
|
import { SortableHead, sortRows } from "@/app/components/ui/sortable-head";
|
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
|
|
import { SkuVariationPicker } from "@/app/components/catalog-setup/SkuVariationPicker";
|
|
import { findSkuVariationsByCode } from "@/app/lib/services/adminCatalogSetup";
|
|
import { useScanKeyCapture } from "@/app/lib/useScanKeyCapture";
|
|
import type { SkuVariationOption } from "@/app/lib/catalogSetup";
|
|
import { EventCloseOutDialog } from "@/app/components/events/EventCloseOutDialog";
|
|
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
|
import { INVENTORY_MODULES } from "@/app/lib/inventoryModules";
|
|
import { getEvent } from "@/app/lib/services/adminEvents";
|
|
import { saveStockCountEntries, getStockCount, stockCountAction, getEventCloseOut } from "@/app/lib/services/adminStockCounts";
|
|
import { STOCK_COUNT_STATUS_LABEL, STOCK_COUNT_STATUS_TONE } from "@/app/lib/stockCountStatus";
|
|
import type { StockCount, StockCountAction, StockCountEntry, StockCountLine, AdminEvent, EventCloseOutState } from "@/app/lib/types";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
|
|
// One stock count (add-stock-count-event-closeout). While OPEN the count is blind: the server sends
|
|
// no expected quantities, so the counter only enters what is on the shelf. Submitting reveals the
|
|
// variance; a different user with BO_STOCK_COUNT_APPROVE approves it, which posts Count-correction
|
|
// adjustments. Approved event counts point to close-out, where the return warehouse is chosen.
|
|
// The server enforces every rule (including submitter != approver); this page only decides what to show.
|
|
|
|
const message = (e: unknown) => (e instanceof Error ? e.message : String(e));
|
|
const signed = (n: number) => (n > 0 ? `+${n}` : String(n));
|
|
|
|
// Scan box: shown only on an editable count, so the key capture is active only then. `onScan`
|
|
// resolves to a message to show, or null.
|
|
function ScanBox({ onScan }: { onScan: (code: string) => Promise<string | null> }) {
|
|
const t = useT();
|
|
const ref = useRef<HTMLInputElement>(null);
|
|
const [value, setValue] = useState("");
|
|
const [note, setNote] = useState<string | null>(null);
|
|
useScanKeyCapture(key => {
|
|
setValue(v => v + key);
|
|
ref.current?.focus();
|
|
});
|
|
const submit = async () => {
|
|
const code = value.trim();
|
|
if (!code) return;
|
|
setValue("");
|
|
setNote(null);
|
|
setNote(await onScan(code));
|
|
};
|
|
return (
|
|
<div className="max-w-sm space-y-1">
|
|
<Input
|
|
ref={ref}
|
|
aria-label={t("StockCountScanLabel")}
|
|
placeholder={t("StockCountScanLabel")}
|
|
value={value}
|
|
onChange={e => setValue(e.target.value)}
|
|
onKeyDown={e => {
|
|
if (e.key === "Enter") {
|
|
e.preventDefault();
|
|
submit();
|
|
}
|
|
}}
|
|
/>
|
|
{note && <p className="text-sm text-muted-foreground">{note}</p>}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function StockCountDetail({ id }: { id: string }) {
|
|
const t = useT();
|
|
const { hasModule } = useAdminAuth();
|
|
const [count, setCount] = useState<StockCount | null>(null);
|
|
const [lines, setLines] = useState<StockCountLine[]>([]);
|
|
const [drafts, setDrafts] = useState<Record<string, string>>({});
|
|
const [loadError, setLoadError] = useState<string | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [busy, setBusy] = useState(false);
|
|
const canEvents = hasModule("BO_EVENTS");
|
|
const [closeOut, setCloseOut] = useState<EventCloseOutState | null>(null);
|
|
const [closeEvent, setCloseEvent] = useState<AdminEvent | null>(null);
|
|
const [eventClosed, setEventClosed] = useState(false);
|
|
const [sorting, setSorting] = useState<SortingState>([]);
|
|
const sortedLines = useMemo(
|
|
() => sortRows(lines, sorting, {
|
|
sku: l => l.skuCode ?? l.skuVariationId,
|
|
variant: l => l.variantName,
|
|
expected: l => l.expectedQty,
|
|
counted: l => l.countedQty,
|
|
variance: l => l.variance,
|
|
}),
|
|
[lines, sorting],
|
|
);
|
|
|
|
const show = useCallback((c: StockCount) => {
|
|
setCount(c);
|
|
setLines(c.lines);
|
|
setDrafts(Object.fromEntries(c.lines.map(l => [l.skuVariationId, l.countedQty === null ? "" : String(l.countedQty)])));
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
getStockCount(id).then(show).catch(e => setLoadError(message(e)));
|
|
}, [id, show]);
|
|
|
|
useEffect(() => {
|
|
if (count?.status === "APPROVED" && count.eventId !== null && canEvents) {
|
|
getEventCloseOut(String(count.eventId)).then(setCloseOut).catch(() => setCloseOut(null));
|
|
}
|
|
}, [count?.status, count?.eventId, canEvents]);
|
|
|
|
const entries = (): StockCountEntry[] =>
|
|
lines.map(l => ({
|
|
skuVariationId: l.skuVariationId,
|
|
variationId: l.variationId,
|
|
countedQty: drafts[l.skuVariationId] === "" || drafts[l.skuVariationId] === undefined ? null : Number(drafts[l.skuVariationId]),
|
|
}));
|
|
|
|
const run = async (work: () => Promise<StockCount>) => {
|
|
setBusy(true);
|
|
setError(null);
|
|
try {
|
|
show(await work());
|
|
} catch (e) {
|
|
setError(message(e));
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
const save = () => run(() => saveStockCountEntries(id, entries()));
|
|
const submit = () => {
|
|
if (entries().some(e => e.countedQty === null)) {
|
|
setError("StockCountEnterAll");
|
|
return;
|
|
}
|
|
return run(async () => {
|
|
await saveStockCountEntries(id, entries());
|
|
return stockCountAction(id, "submit");
|
|
});
|
|
};
|
|
const addLine = (o: SkuVariationOption) => {
|
|
const skuVariationId = String(o.skuVariationId);
|
|
setLines(ls => ls.some(l => l.skuVariationId === skuVariationId) ? ls : [...ls, {
|
|
skuVariationId, variationId: null, skuCode: o.code, variantName: o.variantName,
|
|
expectedQty: null, countedQty: null, variance: null,
|
|
}]);
|
|
};
|
|
const scan = async (code: string) => {
|
|
setError(null);
|
|
try {
|
|
const matches = await findSkuVariationsByCode(code);
|
|
if (matches.length === 0) return t("StockCountScanNoMatch", { code });
|
|
if (matches.length > 1) return t("StockCountScanMany", { code });
|
|
const id = String(matches[0].skuVariationId);
|
|
addLine(matches[0]);
|
|
setDrafts(d => ({ ...d, [id]: String((Number(d[id]) || 0) + 1) }));
|
|
} catch (e) {
|
|
setError(message(e));
|
|
}
|
|
return null;
|
|
};
|
|
const act = (action: StockCountAction) => run(() => stockCountAction(id, action));
|
|
|
|
if (loadError) return <ErrorState message={loadError} />;
|
|
if (!count) return <TableSkeleton columns={5} />;
|
|
|
|
const open = count.status === "OPEN";
|
|
const canCount = hasModule(INVENTORY_MODULES.count);
|
|
const canApprove = hasModule(INVENTORY_MODULES.countApprove);
|
|
const openCloseOut = () => getEvent(String(count.eventId)).then(setCloseEvent).catch(e => setError(message(e)));
|
|
const differing = lines.filter(l => (l.variance ?? 0) !== 0).length;
|
|
|
|
const actions = [
|
|
open && canCount && <Button key="save" variant="outline" disabled={busy} onClick={save}>{t("Save")}</Button>,
|
|
open && canCount && <Button key="submit" disabled={busy} onClick={submit}>{t("StockCountSubmit")}</Button>,
|
|
count.status === "SUBMITTED" && canApprove && (
|
|
<Button key="reopen" variant="outline" disabled={busy} onClick={() => act("reopen")}>{t("StockCountSendBack")}</Button>
|
|
),
|
|
count.status === "SUBMITTED" && canApprove && (
|
|
<Button key="approve" disabled={busy} onClick={() => act("approve")}>{t("StockCountApprove")}</Button>
|
|
),
|
|
(open || count.status === "SUBMITTED") && canCount && (
|
|
<Button key="cancel" variant="outline" disabled={busy} onClick={() => act("cancel")}>{t("StockCountCancel")}</Button>
|
|
),
|
|
].filter(Boolean);
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
<PageHeader title={t("StockCountTitle", { id: count.id })} actions={actions} />
|
|
<div className="flex flex-wrap items-center gap-3 text-sm">
|
|
<Badge variant={STOCK_COUNT_STATUS_TONE[count.status]}>{t(STOCK_COUNT_STATUS_LABEL[count.status])}</Badge>
|
|
<span>{count.warehouseCode} — {count.warehouseName}</span>
|
|
{count.eventId !== null && (
|
|
<Link className="underline underline-offset-4" href="/events">{t("StockCountBackToEvents")}</Link>
|
|
)}
|
|
</div>
|
|
|
|
{open && (
|
|
<p className="text-sm text-muted-foreground">
|
|
{t("StockCountBlindNotice")}
|
|
</p>
|
|
)}
|
|
{count.status === "SUBMITTED" && (
|
|
<p className="text-sm">{differing === 0 ? t("StockCountNoDifferences") : differing === 1 ? t("StockCountLineDiffers", { count: differing }) : t("StockCountLinesDiffer", { count: differing })}</p>
|
|
)}
|
|
{count.status === "APPROVED" && (
|
|
<p className="text-sm">{count.adjustmentRef ? t("StockCountAdjustmentsPosted", { ref: count.adjustmentRef }) : t("StockCountNoVariance")}</p>
|
|
)}
|
|
{count.status === "APPROVED" && count.eventId !== null && !canEvents && (
|
|
<p className="text-sm text-muted-foreground">
|
|
{t("StockCountLeftoverHint")}
|
|
</p>
|
|
)}
|
|
{eventClosed && <p className="text-sm">{t("StockCountEventClosed")}</p>}
|
|
{!eventClosed && closeOut?.phase === "READY_TO_CLOSE" && (
|
|
<div className="space-y-2 rounded-xl border bg-card p-4 text-sm">
|
|
<p>{t("StockCountReadyToClose")}</p>
|
|
<Button disabled={busy} onClick={openCloseOut}>{t("StockCountChooseReturn")}</Button>
|
|
</div>
|
|
)}
|
|
{error && <ErrorState message={t(error)} />}
|
|
|
|
<div className="overflow-hidden rounded-table border bg-card">
|
|
<Table aria-label={t("StockCountLinesLabel")}>
|
|
<TableHeader>
|
|
<TableRow>
|
|
<SortableHead label={t("Sku")} sortKey="sku" sorting={sorting} onSortingChange={setSorting} />
|
|
<SortableHead label={t("StockCountVariant")} sortKey="variant" sorting={sorting} onSortingChange={setSorting} />
|
|
{!open && <SortableHead className="text-right" label={t("StockCountExpected")} sortKey="expected" sorting={sorting} onSortingChange={setSorting} />}
|
|
<SortableHead className="text-right" label={t("StockCountCounted")} sortKey="counted" sorting={sorting} onSortingChange={setSorting} />
|
|
{!open && <SortableHead className="text-right" label={t("StockCountVariance")} sortKey="variance" sorting={sorting} onSortingChange={setSorting} />}
|
|
</TableRow>
|
|
</TableHeader>
|
|
<TableBody>
|
|
{sortedLines.map(l => (
|
|
<TableRow key={l.skuVariationId}>
|
|
<TableCell>{l.skuCode ?? l.skuVariationId}</TableCell>
|
|
<TableCell>{l.variantName ?? ""}</TableCell>
|
|
{!open && <TableCell className="tabular text-right">{l.expectedQty}</TableCell>}
|
|
<TableCell className="text-right">
|
|
{open && canCount ? (
|
|
<Input
|
|
type="number"
|
|
min={0}
|
|
inputMode="numeric"
|
|
className="ml-auto w-24 text-right"
|
|
aria-label={t("StockCountCountedAria", { sku: l.skuCode ?? l.skuVariationId })}
|
|
value={drafts[l.skuVariationId] ?? ""}
|
|
onChange={e => setDrafts(d => ({ ...d, [l.skuVariationId]: e.target.value }))}
|
|
/>
|
|
) : (
|
|
<span className="tabular">{l.countedQty ?? "—"}</span>
|
|
)}
|
|
</TableCell>
|
|
{!open && (
|
|
<TableCell className={`tabular text-right ${(l.variance ?? 0) !== 0 ? "font-medium text-destructive" : ""}`}>
|
|
{l.variance === null ? "—" : signed(l.variance)}
|
|
</TableCell>
|
|
)}
|
|
</TableRow>
|
|
))}
|
|
</TableBody>
|
|
</Table>
|
|
</div>
|
|
|
|
{open && canCount && <ScanBox onScan={scan} />}
|
|
|
|
{open && canCount && (
|
|
<div className="max-w-sm">
|
|
<SkuVariationPicker
|
|
label={t("StockCountAddSku")}
|
|
placeholder={t("StockCountAddSkuPlaceholder")}
|
|
onSelect={o => {
|
|
addLine(o);
|
|
setDrafts(d => String(o.skuVariationId) in d ? d : { ...d, [String(o.skuVariationId)]: "" });
|
|
}}
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{closeEvent && (
|
|
<EventCloseOutDialog
|
|
event={closeEvent}
|
|
onClose={() => setCloseEvent(null)}
|
|
onClosed={() => {
|
|
setCloseEvent(null);
|
|
setEventClosed(true);
|
|
}}
|
|
/>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|