"use client"; import { useEffect, useRef, useState } from "react"; import * as XLSX from "xlsx"; import { Check, ChevronsUpDown, Download, Loader2, Plus, Trash2, Upload } from "lucide-react"; import { Skeleton } from "@/app/components/ui/skeleton"; import { Button } from "@/app/components/ui/button"; import { DatePicker } from "@/app/components/ui/date-picker"; import { Input } from "@/app/components/ui/input"; import { Label } from "@/app/components/ui/label"; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from "@/app/components/ui/command"; import { Popover, PopoverContent, PopoverTrigger } from "@/app/components/ui/popover"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/app/components/ui/select"; import { transferStock, getProductVariations, getStockOnHand } from "@/app/lib/services/adminStock"; import { listAdminWarehouses } from "@/app/lib/services/adminWarehouses"; import { listProducts } from "@/app/lib/services/adminProduct"; import { productPickerLabel } from "@/app/lib/productPickerLabel"; import type { AdminWarehouse, ProductListRow, ProductVariationOption, StockOnHandRow, TransferPayload } from "@/app/lib/types"; import { cn } from "@/app/lib/utils"; import { parseQuantityInput } from "@/app/lib/inventory/quantityInput"; import { readSheetRows } from "@/app/lib/inventory/workbookRows"; import { buildTransferWorkbook, parseTransferWorkbook, transferShortfalls, type TransferImportLine, } from "@/app/lib/inventory/transferWorkbook"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import { insufficientStockMessage } from "./insufficientStock"; import type { StockFormProps } from "./StockInForm"; // Transfer form (openspec/changes/add-inventory-transfers-movement-history, I3 Task 7). // - Source: a of ACTIVE warehouses EXCLUDING the chosen source. // - Product picker: a search combobox (Popover + Command) loading products via listProducts(). // - Variation select: loaded after product pick via getProductVariations(productId). // - Multi-line: admin can add/remove lines. // - Submit: calls transferStock(payload), shows docNo on success, error message on failure. // Lines are retained on rejection so the admin can correct and resubmit. // No side-effects on mount/prefetch — all mutations go through the submit handler. // ─── types ─────────────────────────────────────────────────────────────────── interface TransferLine { /** Stable key for React list rendering — never changes after creation. */ key: number; productId: string; productLabel: string; pickerOpen: boolean; variations: ProductVariationOption[]; variationsLoading: boolean; skuVariationId: string; variationId: string; quantity: number; /** Raw text of the Quantity field, so it can be cleared and retyped. `quantity` is its parsed value (0 when empty). */ quantityText: string; batchNumber: string; expiryDate: string; } /** A line read from an imported workbook, shown in the review table instead of a line card. */ interface ImportedLine extends TransferImportLine { key: number; quantityText: string; } const ON_HAND_PAGE_SIZE = 200; /** * Every on-hand row of a warehouse, paging until the last page. * ponytail: the on-hand report re-runs the full SKU query on every page and slices it in memory, so each * download or import costs about N/200 full scans. Upgrade path: a server endpoint returning all rows * for one warehouse. */ async function fetchAllOnHand(warehouseId: string): Promise { const rows: StockOnHandRow[] = []; for (let page = 0; ; page++) { const res = await getStockOnHand({ warehouseId, page, size: ON_HAND_PAGE_SIZE }); rows.push(...res.content); if (res.number + 1 >= res.totalPages) return rows; } } let _nextKey = 0; function emptyLine(): TransferLine { return { key: _nextKey++, productId: "", productLabel: "", pickerOpen: false, variations: [], variationsLoading: false, skuVariationId: "", variationId: "", quantity: 1, quantityText: "1", batchNumber: "", expiryDate: "", }; } // ─── component ─────────────────────────────────────────────────────────────── export function TransferForm({ defaultWarehouseId, onSubmitted, onDirtyChange }: StockFormProps = {}) { const [activeWarehouses, setActiveWarehouses] = useState([]); const [sourceWarehouseId, setSourceWarehouseId] = useState(""); const [destWarehouseId, setDestWarehouseId] = useState(""); const [warehousesLoading, setWarehousesLoading] = useState(true); const [products, setProducts] = useState([]); const [lines, setLines] = useState([emptyLine()]); const [remark, setRemark] = useState(""); const [submitting, setSubmitting] = useState(false); // Set on the first Submit press so empty / zero quantities are reported on their lines. const [quantityAttempted, setQuantityAttempted] = useState(false); // Imported review table (null = manual line editor). onHand belongs to the source it was read for. const [imported, setImported] = useState(null); const [importErrors, setImportErrors] = useState([]); const [onHand, setOnHand] = useState>(new Map()); const fileInputRef = useRef(null); // Bumped by every import, download and source change: an async result from an older sequence is dropped. const requestSeq = useRef(0); // Download has its own counter (source change bumps it too) so it never cancels a running import. const downloadSeq = useRef(0); const t = useT(); const [error, setError] = useState(null); const [successDocNo, setSuccessDocNo] = useState(null); // Load warehouses on mount; filter to active (status="Y"). useEffect(() => { let cancelled = false; listAdminWarehouses() .then(warehouses => { if (cancelled) return; const active = warehouses.filter(w => w.status === "Y"); setActiveWarehouses(active); // Pre-select the Stock on Hand filter's warehouse when it is active. Runs once: the panel // mounts a fresh form each time. if (defaultWarehouseId && active.some(w => String(w.id) === defaultWarehouseId)) { setSourceWarehouseId(defaultWarehouseId); } setWarehousesLoading(false); }) .catch(() => { if (!cancelled) { setWarehousesLoading(false); setError("StockLoadWarehousesFailed"); } }); return () => { cancelled = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps -- mount-once: defaultWarehouseId only seeds the first pick. }, []); // Load a large product page on mount for the client-side product picker filter. useEffect(() => { let cancelled = false; listProducts({ page: 0, pageSize: 500 }) .then(result => { if (!cancelled) setProducts(result.items); }) .catch(() => { // Non-critical: picker is empty — admin can still try once the page reloads. }); return () => { cancelled = true; }; }, []); // Destination list excludes the currently-chosen source. const destWarehouses = sourceWarehouseId ? activeWarehouses.filter(w => String(w.id) !== sourceWarehouseId) : activeWarehouses; // Anything entered counts as unsaved work (the Inventory page asks before closing the panel). The // remark is kept after a submit for the next transfer, so from then on only lines count. const headerEntered = successDocNo === null && remark !== ""; const dirty = headerEntered || imported !== null || lines.some(l => l.productId !== "" || l.skuVariationId !== "" || l.quantityText !== "1" || l.batchNumber !== "" || l.expiryDate !== ""); useEffect(() => { onDirtyChange?.(dirty); }, [dirty, onDirtyChange]); // ─── line helpers ────────────────────────────────────────────────────────── function patchLine(key: number, patch: Partial) { setLines(prev => prev.map(l => (l.key === key ? { ...l, ...patch } : l))); } async function handleProductPick(lineKey: number, product: ProductListRow) { patchLine(lineKey, { productId: product.id, productLabel: productPickerLabel(product), pickerOpen: false, skuVariationId: "", variationId: "", variations: [], variationsLoading: true, }); try { const variations = await getProductVariations(product.id); patchLine(lineKey, { variations, variationsLoading: false }); } catch { patchLine(lineKey, { variationsLoading: false }); } } // ─── template + import (in-browser only, no file upload) ─────────────────── async function handleDownloadTemplate() { setError(null); const seq = ++downloadSeq.current; try { const rows = await fetchAllOnHand(sourceWarehouseId); if (seq !== downloadSeq.current) return; const bytes = buildTransferWorkbook(rows); // bytes is a Uint8Array (a valid BlobPart). Never read `.buffer`: see StockInForm. const blob = new Blob([bytes], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = "stock-transfer-template.xlsx"; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } catch { if (seq === downloadSeq.current) setError("StockInTemplateFailed"); } } async function handleImport(e: React.ChangeEvent) { const file = e.target.files?.[0]; if (!file) return; // Reset the input so the same file can be re-imported after corrections. e.target.value = ""; const seq = ++requestSeq.current; setError(null); setImportErrors([]); let rows: StockOnHandRow[]; try { rows = await fetchAllOnHand(sourceWarehouseId); } catch { if (seq === requestSeq.current) setError("StockOnHandLoadFailed"); return; } try { const buffer = await file.arrayBuffer(); // No cellDates (SheetJS shifts dates by a day east of UTC): readSheetRows decodes date cells. const wb = XLSX.read(new Uint8Array(buffer), { type: "array", cellNF: true }); const sheetName = wb.SheetNames.includes("Stock Transfer") ? "Stock Transfer" : wb.SheetNames[0]; const sheetRows = readSheetRows(wb.Sheets[sheetName], "Expiry (YYYY-MM-DD)"); const { lines: parsed, errors } = parseTransferWorkbook(sheetRows, t); // A newer import, or a source change, superseded this one while it was loading. if (seq !== requestSeq.current) return; if (parsed.length === 0 && errors.length === 0) { // Untouched template: keep whatever is on screen and say why nothing happened. setError("StockXferImportNoRows"); return; } setOnHand(new Map(rows.map(r => [String(r.skuVariationId), r.stockOnHand] as const))); setImportErrors(errors); setLines([emptyLine()]); setImported( parsed.length > 0 ? parsed.map(l => ({ ...l, key: _nextKey++, quantityText: String(l.quantity) })) : null, ); } catch { if (seq === requestSeq.current) setError("StockInReadFailed"); } } function patchImported(key: number, patch: Partial) { setImported(prev => prev && prev.map(l => (l.key === key ? { ...l, ...patch } : l))); } function removeImported(key: number) { setImported(prev => { const next = prev && prev.filter(l => l.key !== key); return next && next.length > 0 ? next : null; }); } // ─── submit ──────────────────────────────────────────────────────────────── async function handleSubmit(e: React.FormEvent) { e.preventDefault(); if (!sourceWarehouseId || !destWarehouseId) return; setError(null); setSuccessDocNo(null); setQuantityAttempted(true); if (imported ? imported.some(l => l.quantity < 1) : lines.some(l => l.quantity < 1)) return; setSubmitting(true); const payload: TransferPayload = { sourceWarehouseId, destWarehouseId, ...(remark.trim() ? { remark: remark.trim() } : {}), lines: imported ? imported.map(l => ({ skuVariationId: l.skuVariationId, quantity: l.quantity, ...(l.batchNumber ? { batchNumber: l.batchNumber } : {}), ...(l.expiryDate ? { expiryDate: l.expiryDate } : {}), })) : lines.map(l => ({ skuVariationId: l.skuVariationId, ...(l.variationId ? { variationId: l.variationId } : {}), quantity: l.quantity, ...(l.batchNumber ? { batchNumber: l.batchNumber } : {}), ...(l.expiryDate ? { expiryDate: l.expiryDate } : {}), })), }; try { const result = await transferStock(payload); // transferStock returns Promise — read documentNo defensively. // The backend returns the saved Inventory entity whose Jackson key is "documentNo" // (getDocumentNo()), not "docNo". Reading the wrong key always falls through to null. const docNo = result != null && typeof result === "object" && "documentNo" in result && result.documentNo != null ? String((result as Record).documentNo) : null; setSuccessDocNo(docNo ?? "StockSubmittedFallback"); // Reset to one empty line on success. setLines([emptyLine()]); setImported(null); setImportErrors([]); setQuantityAttempted(false); onSubmitted?.(); } catch (err: unknown) { // Keep lines on rejection so the admin can correct and resubmit. // An INSUFFICIENT_STOCK rejection names the line's product instead of the raw backend text. setError( insufficientStockMessage(err, insufficientLines, t) ?? (err instanceof Error ? err.message : "StockXferSubmitFailed"), ); } finally { setSubmitting(false); } } // ─── render ──────────────────────────────────────────────────────────────── // Submit is disabled unless: // 1. A source and a DISTINCT destination are chosen. // 2. At least one complete line (skuVariationId set) exists. const hasIncompleteLines = !imported && lines.some(l => !l.skuVariationId); const shortfalls = transferShortfalls(imported ?? [], onHand); const importBlocked = importErrors.length > 0 || (imported !== null && (shortfalls.size > 0 || imported.some(l => l.quantity < 1))); const insufficientLines = imported ? imported.map(l => ({ skuVariationId: l.skuVariationId, productLabel: `${l.skuCode} — ${l.skuName}`, variations: l.variation ? [{ skuVariationId: l.skuVariationId, variationId: "", label: l.variation }] : [], })) : lines; const submitDisabled = submitting || warehousesLoading || !sourceWarehouseId || !destWarehouseId || hasIncompleteLines || importBlocked; return (
{/* Source warehouse select */}
{warehousesLoading ? ( ) : ( )}
{/* Destination warehouse select — excludes chosen source */}
{warehousesLoading ? ( ) : ( )}
{/* Remark (optional) */}
setRemark(e.target.value)} placeholder={t("StockXferRemarkPlaceholder")} className="w-[300px]" />
{/* Download template + Import actions — in-browser only, no file upload */}
{/* Hidden file input — triggered by the Import button */}
{importErrors.length > 0 && (

{t("StockInImportErrors")}

    {importErrors.map((err, i) => (
  • {err}
  • ))}
)} {imported ? ( {t("SkuFieldCode")} {t("SkuFieldName")} {t("Quantity")} {t("SkuOnHand")} {t("Status")} {t("StockBatchNumber")} {t("StockExpiryDate")} {t("StockRemoveLine")} {imported.map(l => { const short = shortfalls.get(l.skuVariationId); return ( {l.skuCode}
{l.skuName}
{l.variation &&
{l.variation}
}
patchImported(l.key, parseQuantityInput(e.target.value))} aria-label={t("Quantity")} aria-invalid={l.quantity < 1 || undefined} className="w-[100px]" /> {onHand.get(l.skuVariationId) ?? 0} {short ? t("StockXferShortBy", { count: short }) : null} {l.batchNumber} {l.expiryDate}
); })}
) : ( <> {/* Line editor */}
{lines.map((line, idx) => ( patchLine(line.key, { pickerOpen: open })} onProductPick={product => handleProductPick(line.key, product)} onVariationChange={(skuVariationId, variationId) => patchLine(line.key, { skuVariationId, variationId }) } showQuantityError={quantityAttempted && line.quantity < 1} onQuantityChange={text => patchLine(line.key, parseQuantityInput(text))} onBatchNumberChange={v => patchLine(line.key, { batchNumber: v })} onExpiryDateChange={v => patchLine(line.key, { expiryDate: v })} onRemove={ lines.length > 1 ? () => setLines(prev => prev.filter(l => l.key !== line.key)) : undefined } /> ))}
)} {/* Feedback */} {error && (
{t(error)}
)} {successDocNo && (
{t("StockXferSubmitted", { docNo: t(successDocNo) })}
)}
); } // ─── TransferLineEditor ─────────────────────────────────────────────────────── interface TransferLineEditorProps { line: TransferLine; lineNumber: number; products: ProductListRow[]; onPickerOpenChange: (open: boolean) => void; onProductPick: (product: ProductListRow) => void; onVariationChange: (skuVariationId: string, variationId: string) => void; showQuantityError: boolean; onQuantityChange: (text: string) => void; onBatchNumberChange: (v: string) => void; onExpiryDateChange: (v: string) => void; onRemove?: () => void; } function TransferLineEditor({ line, lineNumber, products, onPickerOpenChange, onProductPick, onVariationChange, showQuantityError, onQuantityChange, onBatchNumberChange, onExpiryDateChange, onRemove, }: TransferLineEditorProps) { const variationSelectId = `tf-variation-${line.key}`; const t = useT(); const qtyId = `tf-qty-${line.key}`; const qtyErrorId = `tf-qty-error-${line.key}`; const batchId = `tf-batch-${line.key}`; const expiryId = `tf-expiry-${line.key}`; return (
{/* Line header */}
{t("StockLine", { number: lineNumber })} {onRemove && ( )}
{/* Product picker — Popover + Command pattern */}
{t("StockNoProductFound")} {products.map(product => ( onProductPick(product)} > {product.productName}{" "} {product.productCode} {line.productId === product.id && ( )} ))}
{/* Variation select — shown after a product is picked */} {line.productId && (
{line.variationsLoading ? (
{t("StockLoadingVariations")}
) : ( )}
)} {/* Quantity */}
onQuantityChange(e.target.value)} aria-label={t("Quantity")} aria-invalid={showQuantityError || undefined} aria-describedby={showQuantityError ? qtyErrorId : undefined} className="w-[120px]" /> {showQuantityError && (

{t("StockQuantityRequired")}

)}
{/* Batch number (optional) */}
onBatchNumberChange(e.target.value)} placeholder={t("StockBatchPlaceholder")} className="w-[240px]" />
{/* Expiry date (optional) — sent as ISO yyyy-MM-dd string */}
); }