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
797 lines
31 KiB
TypeScript
797 lines
31 KiB
TypeScript
"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 <select> of ACTIVE (status="Y") warehouses.
|
|
// - Destination: a <select> 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<StockOnHandRow[]> {
|
|
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<AdminWarehouse[]>([]);
|
|
const [sourceWarehouseId, setSourceWarehouseId] = useState<string>("");
|
|
const [destWarehouseId, setDestWarehouseId] = useState<string>("");
|
|
const [warehousesLoading, setWarehousesLoading] = useState(true);
|
|
const [products, setProducts] = useState<ProductListRow[]>([]);
|
|
const [lines, setLines] = useState<TransferLine[]>([emptyLine()]);
|
|
const [remark, setRemark] = useState<string>("");
|
|
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<ImportedLine[] | null>(null);
|
|
const [importErrors, setImportErrors] = useState<string[]>([]);
|
|
const [onHand, setOnHand] = useState<Map<string, number>>(new Map());
|
|
const fileInputRef = useRef<HTMLInputElement>(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<string | null>(null);
|
|
const [successDocNo, setSuccessDocNo] = useState<string | null>(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<TransferLine>) {
|
|
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<HTMLInputElement>) {
|
|
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<ImportedLine>) {
|
|
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<unknown> — 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<string, unknown>).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 (
|
|
<form onSubmit={handleSubmit} noValidate className="space-y-6">
|
|
{/* Source warehouse select */}
|
|
<div className="space-y-1">
|
|
<Label className="text-xs text-muted-foreground">{t("StockXferSource")}</Label>
|
|
{warehousesLoading ? (
|
|
<Skeleton role="status" aria-label={t("UiLoading")} className="h-9 w-full" />
|
|
) : (
|
|
<Select
|
|
value={sourceWarehouseId}
|
|
onValueChange={val => {
|
|
setSourceWarehouseId(val);
|
|
requestSeq.current++;
|
|
downloadSeq.current++;
|
|
// The imported lines and their on-hand figures belong to the old source.
|
|
setImported(null);
|
|
setImportErrors([]);
|
|
setOnHand(new Map());
|
|
// Clear destination if it becomes the same as the new source.
|
|
if (destWarehouseId === val) setDestWarehouseId("");
|
|
}}
|
|
>
|
|
<SelectTrigger aria-label={t("StockXferSource")} className="w-[300px]">
|
|
<SelectValue placeholder={t("StockXferSelectSource")} />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
{activeWarehouses.map(w => (
|
|
<SelectItem key={w.id} value={String(w.id)}>
|
|
{w.code} — {w.name}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
)}
|
|
</div>
|
|
|
|
{/* Destination warehouse select — excludes chosen source */}
|
|
<div className="space-y-1">
|
|
<Label className="text-xs text-muted-foreground">{t("StockXferDest")}</Label>
|
|
{warehousesLoading ? (
|
|
<Skeleton role="status" aria-label={t("UiLoading")} className="h-9 w-full" />
|
|
) : (
|
|
<Select
|
|
value={destWarehouseId}
|
|
onValueChange={setDestWarehouseId}
|
|
>
|
|
<SelectTrigger aria-label={t("StockXferDest")} className="w-[300px]">
|
|
<SelectValue placeholder={t("StockXferSelectDest")} />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
{destWarehouses.map(w => (
|
|
<SelectItem key={w.id} value={String(w.id)}>
|
|
{w.code} — {w.name}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
)}
|
|
</div>
|
|
|
|
{/* Remark (optional) */}
|
|
<div className="space-y-1">
|
|
<Label htmlFor="transfer-remark" className="text-xs text-muted-foreground">
|
|
{t("Remark")}{" "}
|
|
<span className="font-normal text-muted-foreground">{t("StockOptional")}</span>
|
|
</Label>
|
|
<Input
|
|
id="transfer-remark"
|
|
type="text"
|
|
value={remark}
|
|
onChange={e => setRemark(e.target.value)}
|
|
placeholder={t("StockXferRemarkPlaceholder")}
|
|
className="w-[300px]"
|
|
/>
|
|
</div>
|
|
|
|
{/* Download template + Import actions — in-browser only, no file upload */}
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<Button type="button" variant="outline" size="sm" disabled={!sourceWarehouseId} onClick={handleDownloadTemplate}>
|
|
<Download aria-hidden className="mr-1 size-4" />
|
|
{t("CatDownloadTemplate")}
|
|
</Button>
|
|
{/* Hidden file input — triggered by the Import button */}
|
|
<input
|
|
ref={fileInputRef}
|
|
type="file"
|
|
accept=".xlsx"
|
|
aria-label={t("StockXferImportAria")}
|
|
className="sr-only"
|
|
onChange={handleImport}
|
|
/>
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
size="sm"
|
|
disabled={!sourceWarehouseId}
|
|
onClick={() => fileInputRef.current?.click()}
|
|
>
|
|
<Upload aria-hidden className="mr-1 size-4" />
|
|
{t("Import")}
|
|
</Button>
|
|
</div>
|
|
|
|
{importErrors.length > 0 && (
|
|
<div role="alert" className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive space-y-1">
|
|
<p className="font-medium">{t("StockInImportErrors")}</p>
|
|
<ul className="list-disc list-inside space-y-0.5">
|
|
{importErrors.map((err, i) => (
|
|
<li key={i}>{err}</li>
|
|
))}
|
|
</ul>
|
|
</div>
|
|
)}
|
|
|
|
{imported ? (
|
|
<Table aria-label={t("StockXferImportedLines")}>
|
|
<TableHeader>
|
|
<TableRow>
|
|
<TableHead>{t("SkuFieldCode")}</TableHead>
|
|
<TableHead>{t("SkuFieldName")}</TableHead>
|
|
<TableHead>{t("Quantity")}</TableHead>
|
|
<TableHead>{t("SkuOnHand")}</TableHead>
|
|
<TableHead>{t("Status")}</TableHead>
|
|
<TableHead>{t("StockBatchNumber")}</TableHead>
|
|
<TableHead>{t("StockExpiryDate")}</TableHead>
|
|
<TableHead><span className="sr-only">{t("StockRemoveLine")}</span></TableHead>
|
|
</TableRow>
|
|
</TableHeader>
|
|
<TableBody>
|
|
{imported.map(l => {
|
|
const short = shortfalls.get(l.skuVariationId);
|
|
return (
|
|
<TableRow key={l.key}>
|
|
<TableCell>{l.skuCode}</TableCell>
|
|
<TableCell className="max-w-[200px] whitespace-normal break-words">
|
|
<div>{l.skuName}</div>
|
|
{l.variation && <div className="text-xs text-muted-foreground">{l.variation}</div>}
|
|
</TableCell>
|
|
<TableCell>
|
|
<Input
|
|
type="number"
|
|
min={1}
|
|
value={l.quantityText}
|
|
onChange={e => patchImported(l.key, parseQuantityInput(e.target.value))}
|
|
aria-label={t("Quantity")}
|
|
aria-invalid={l.quantity < 1 || undefined}
|
|
className="w-[100px]"
|
|
/>
|
|
</TableCell>
|
|
<TableCell>{onHand.get(l.skuVariationId) ?? 0}</TableCell>
|
|
<TableCell className="text-destructive">
|
|
{short ? t("StockXferShortBy", { count: short }) : null}
|
|
</TableCell>
|
|
<TableCell>{l.batchNumber}</TableCell>
|
|
<TableCell>{l.expiryDate}</TableCell>
|
|
<TableCell>
|
|
<Button type="button" variant="ghost" size="sm" onClick={() => removeImported(l.key)} aria-label={t("StockRemoveLine")}>
|
|
<Trash2 aria-hidden className="size-4" />
|
|
</Button>
|
|
</TableCell>
|
|
</TableRow>
|
|
);
|
|
})}
|
|
</TableBody>
|
|
</Table>
|
|
) : (
|
|
<>
|
|
{/* Line editor */}
|
|
<div className="space-y-4">
|
|
{lines.map((line, idx) => (
|
|
<TransferLineEditor
|
|
key={line.key}
|
|
line={line}
|
|
lineNumber={idx + 1}
|
|
products={products}
|
|
onPickerOpenChange={open => 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
|
|
}
|
|
/>
|
|
))}
|
|
</div>
|
|
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => setLines(prev => [...prev, emptyLine()])}
|
|
>
|
|
<Plus aria-hidden className="mr-1 size-4" />
|
|
{t("StockAddLine")}
|
|
</Button>
|
|
</>
|
|
)}
|
|
|
|
{/* Feedback */}
|
|
{error && (
|
|
<div role="alert" className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
|
|
{t(error)}
|
|
</div>
|
|
)}
|
|
{successDocNo && (
|
|
<div role="status" className="rounded-md border border-positive/30 bg-positive/10 px-3 py-2 text-sm text-positive">
|
|
{t("StockXferSubmitted", { docNo: t(successDocNo) })}
|
|
</div>
|
|
)}
|
|
|
|
<Button
|
|
type="submit"
|
|
disabled={submitDisabled}
|
|
>
|
|
{submitting && <Loader2 aria-hidden className="mr-2 size-4 animate-spin" />}
|
|
{t("Submit")}
|
|
</Button>
|
|
</form>
|
|
);
|
|
}
|
|
|
|
// ─── 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 (
|
|
<div className="rounded-lg border p-4 space-y-3">
|
|
{/* Line header */}
|
|
<div className="flex items-center justify-between">
|
|
<span className="text-sm font-medium text-muted-foreground">{t("StockLine", { number: lineNumber })}</span>
|
|
{onRemove && (
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={onRemove}
|
|
aria-label={t("StockRemoveLine")}
|
|
>
|
|
<Trash2 aria-hidden className="size-4" />
|
|
</Button>
|
|
)}
|
|
</div>
|
|
|
|
{/* Product picker — Popover + Command pattern */}
|
|
<div className="space-y-1">
|
|
<Label className="text-xs text-muted-foreground">{t("StockProduct")}</Label>
|
|
<Popover open={line.pickerOpen} onOpenChange={onPickerOpenChange}>
|
|
<PopoverTrigger asChild>
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
role="combobox"
|
|
aria-expanded={line.pickerOpen}
|
|
aria-label={t("StockProduct")}
|
|
className="w-full justify-between font-normal"
|
|
>
|
|
<span className={cn("truncate", !line.productId && "text-muted-foreground")}>
|
|
{line.productLabel || t("StockSelectProduct")}
|
|
</span>
|
|
<ChevronsUpDown aria-hidden className="ml-2 size-4 shrink-0 opacity-50" />
|
|
</Button>
|
|
</PopoverTrigger>
|
|
<PopoverContent className="w-[360px] p-0" align="start">
|
|
<Command>
|
|
<CommandInput placeholder={t("StockSearchProducts")} />
|
|
<CommandList>
|
|
<CommandEmpty>{t("StockNoProductFound")}</CommandEmpty>
|
|
<CommandGroup>
|
|
{products.map(product => (
|
|
<CommandItem
|
|
key={product.id}
|
|
value={productPickerLabel(product)}
|
|
onSelect={() => onProductPick(product)}
|
|
>
|
|
<span>{product.productName}</span>{" "}
|
|
<span className="text-xs text-muted-foreground">{product.productCode}</span>
|
|
{line.productId === product.id && (
|
|
<Check aria-hidden className="ml-auto size-4" />
|
|
)}
|
|
</CommandItem>
|
|
))}
|
|
</CommandGroup>
|
|
</CommandList>
|
|
</Command>
|
|
</PopoverContent>
|
|
</Popover>
|
|
</div>
|
|
|
|
{/* Variation select — shown after a product is picked */}
|
|
{line.productId && (
|
|
<div className="space-y-1">
|
|
<Label htmlFor={variationSelectId} className="text-xs text-muted-foreground">
|
|
{t("CatVariation")}
|
|
</Label>
|
|
{line.variationsLoading ? (
|
|
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
|
<Loader2 aria-hidden className="size-4 animate-spin" />
|
|
{t("StockLoadingVariations")}
|
|
</div>
|
|
) : (
|
|
<Select
|
|
value={line.skuVariationId || undefined}
|
|
onValueChange={value => {
|
|
const opt = line.variations.find(o => o.skuVariationId === value);
|
|
onVariationChange(value, opt?.variationId ?? "");
|
|
}}
|
|
>
|
|
<SelectTrigger id={variationSelectId} aria-label={t("CatVariation")}>
|
|
<SelectValue placeholder={t("StockSelectVariation")} />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
{line.variations.map(opt => (
|
|
<SelectItem key={opt.skuVariationId} value={opt.skuVariationId}>
|
|
{opt.label}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{/* Quantity */}
|
|
<div className="space-y-1">
|
|
<Label htmlFor={qtyId} className="text-xs text-muted-foreground">
|
|
{t("Quantity")}
|
|
</Label>
|
|
<Input
|
|
id={qtyId}
|
|
type="number"
|
|
min={1}
|
|
value={line.quantityText}
|
|
onChange={e => onQuantityChange(e.target.value)}
|
|
aria-label={t("Quantity")}
|
|
aria-invalid={showQuantityError || undefined}
|
|
aria-describedby={showQuantityError ? qtyErrorId : undefined}
|
|
className="w-[120px]"
|
|
/>
|
|
{showQuantityError && (
|
|
<p id={qtyErrorId} className="text-xs text-destructive">
|
|
{t("StockQuantityRequired")}
|
|
</p>
|
|
)}
|
|
</div>
|
|
|
|
{/* Batch number (optional) */}
|
|
<div className="space-y-1">
|
|
<Label htmlFor={batchId} className="text-xs text-muted-foreground">
|
|
{t("StockBatchNumber")}{" "}
|
|
<span className="font-normal text-muted-foreground">{t("StockOptional")}</span>
|
|
</Label>
|
|
<Input
|
|
id={batchId}
|
|
type="text"
|
|
value={line.batchNumber}
|
|
onChange={e => onBatchNumberChange(e.target.value)}
|
|
placeholder={t("StockBatchPlaceholder")}
|
|
className="w-[240px]"
|
|
/>
|
|
</div>
|
|
|
|
{/* Expiry date (optional) — sent as ISO yyyy-MM-dd string */}
|
|
<div className="space-y-1">
|
|
<Label htmlFor={expiryId} className="text-xs text-muted-foreground">
|
|
{t("StockExpiryDate")}{" "}
|
|
<span className="font-normal text-muted-foreground">{t("StockOptional")}</span>
|
|
</Label>
|
|
<DatePicker
|
|
id={expiryId}
|
|
value={line.expiryDate}
|
|
onChange={onExpiryDateChange}
|
|
className="h-9 w-[180px]"
|
|
/>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|