Files
co-lite/solvway-admin-portal/app/components/inventory/StockInForm.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

629 lines
24 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"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 { postStockIn, getProductVariations, getSkuCatalog } 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 { buildStockInWorkbook, parseStockInWorkbook } from "@/app/lib/inventory/stockInWorkbook";
import { readSheetRows } from "@/app/lib/inventory/workbookRows";
import type { AdminWarehouse, ProductListRow, ProductVariationOption, StockInPayload } from "@/app/lib/types";
import { cn } from "@/app/lib/utils";
import { parseQuantityInput } from "@/app/lib/inventory/quantityInput";
import { useT } from "@/app/lib/i18n/MessagesProvider";
// Stock-in form (openspec/changes/add-inventory-stock-in, I2 Task 5; enhanced I2.1 Task 8A).
// - Destination: a <select> of ACTIVE (status="Y") warehouses from listAdminWarehouses(), defaulting
// to the type-M (Master Store). Admin can change destination before submitting.
// - 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 postStockIn(payload), shows documentNo on success, error message on failure.
// No side-effects on mount/prefetch — all mutations go through the submit handler.
// ─── types ───────────────────────────────────────────────────────────────────
interface StockInLine {
/** 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;
}
let _nextKey = 0;
function emptyLine(): StockInLine {
return {
key: _nextKey++,
productId: "",
productLabel: "",
pickerOpen: false,
variations: [],
variationsLoading: false,
skuVariationId: "",
variationId: "",
quantity: 1,
quantityText: "1",
batchNumber: "",
expiryDate: "",
};
}
// ─── component ───────────────────────────────────────────────────────────────
/** Optional hooks for the Inventory page's side panel (merge-inventory-page). */
export interface StockFormProps {
/** Warehouse to pre-select, if it is active (the Stock on Hand filter). */
defaultWarehouseId?: string;
onSubmitted?: () => void;
onDirtyChange?: (dirty: boolean) => void;
}
export function StockInForm({ defaultWarehouseId, onSubmitted, onDirtyChange }: StockFormProps = {}) {
const t = useT();
const [activeWarehouses, setActiveWarehouses] = useState<AdminWarehouse[]>([]);
const [selectedWarehouseId, setSelectedWarehouseId] = useState<string>("");
const [warehousesLoading, setWarehousesLoading] = useState(true);
const [products, setProducts] = useState<ProductListRow[]>([]);
const [lines, setLines] = useState<StockInLine[]>([emptyLine()]);
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);
const [error, setError] = useState<string | null>(null);
const [successDocNo, setSuccessDocNo] = useState<string | null>(null);
/** Import-specific parse errors — shown separately from general submit errors. */
const [importErrors, setImportErrors] = useState<string[]>([]);
const fileInputRef = useRef<HTMLInputElement>(null);
// Load warehouses on mount; filter to active (status="Y") and default to defaultWarehouseId when it
// is active, else the type-M Master Store. Runs once: the panel mounts a fresh form each time.
useEffect(() => {
let cancelled = false;
listAdminWarehouses()
.then(warehouses => {
if (cancelled) return;
const active = warehouses.filter(w => w.status === "Y");
setActiveWarehouses(active);
const preset = defaultWarehouseId ? active.find(w => String(w.id) === defaultWarehouseId) : undefined;
const initial = preset ?? active.find(w => w.type === "M");
if (initial) setSelectedWarehouseId(String(initial.id));
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.
// Mirrors the products-page pattern in app/lib/services/adminProduct.ts.
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;
};
}, []);
// Anything entered counts as unsaved work (the Inventory page asks before closing the panel).
const dirty = 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<StockInLine>) {
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 });
}
}
// ─── download template ─────────────────────────────────────────────────────
/** Download a pre-filled .xlsx template built from the full SKU catalog.
* All logic is in-browser — no file upload, no drive-service call. */
async function handleDownloadTemplate() {
setError(null);
try {
const catalog = await getSkuCatalog();
const bytes = buildStockInWorkbook(catalog);
// bytes is a Uint8Array (a valid BlobPart). Do NOT read `.buffer` — SheetJS's
// type:"array" may itself return an ArrayBuffer, whose `.buffer` is undefined
// and produced a 9-byte "undefined" download.
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-in-template.xlsx";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch {
setError("StockInTemplateFailed");
}
}
// ─── import ────────────────────────────────────────────────────────────────
/** Parse an uploaded .xlsx in the browser and populate the line editor for review.
* No file is uploaded to any server — the drive-service lifecycle is not involved. */
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 = "";
setError(null);
setImportErrors([]);
try {
const buffer = await file.arrayBuffer();
// Fix 1: pass Uint8Array — type:"array" expects a typed array, not a raw ArrayBuffer.
const wb = XLSX.read(new Uint8Array(buffer), { type: "array", cellNF: true });
const sheetName = wb.SheetNames.includes("Stock In") ? "Stock In" : wb.SheetNames[0];
const sheet = wb.Sheets[sheetName];
const rows = readSheetRows(sheet, "Expiry (YYYY-MM-DD)");
const { lines: parsedLines, errors: parseErrors } = parseStockInWorkbook(rows, t);
if (parseErrors.length > 0) {
setImportErrors(parseErrors);
}
// Fix 2: always replace the line editor with the parsed result so stale
// manually-entered lines are never left behind after an import.
// Fix 3: build a Map for O(N+M) label derivation instead of O(M×N) rows.find.
const rowBySkuVariationId = new Map<string, Record<string, unknown>>(
rows.map(r => [String(r["skuVariationId"]), r]),
);
setLines(
parsedLines.length > 0
? parsedLines.map(l => {
const sourceRow = rowBySkuVariationId.get(l.skuVariationId);
const label = sourceRow
? [sourceRow["SKU Code"], sourceRow["SKU Name"], sourceRow["Variation"]]
.filter(Boolean)
.join(" — ")
: l.skuVariationId;
return {
...emptyLine(),
skuVariationId: l.skuVariationId,
productLabel: label,
...parseQuantityInput(String(l.quantity)),
batchNumber: l.batchNumber ?? "",
expiryDate: l.expiryDate ?? "",
};
})
: [emptyLine()],
);
} catch {
setError("StockInReadFailed");
}
}
// ─── submit ────────────────────────────────────────────────────────────────
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!selectedWarehouseId) return;
setError(null);
setSuccessDocNo(null);
setQuantityAttempted(true);
if (lines.some(l => l.quantity < 1)) return;
setSubmitting(true);
const payload: StockInPayload = {
warehouseId: selectedWarehouseId,
lines: 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 postStockIn(payload);
// postStockIn returns Promise<unknown> — read documentNo defensively.
const docNo =
result != null &&
typeof result === "object" &&
"documentNo" in result &&
result.documentNo != null
? String((result as Record<string, unknown>).documentNo)
: null;
setSuccessDocNo(docNo ?? "StockSubmittedFallback");
// Clear the form on success.
setLines([emptyLine()]);
setQuantityAttempted(false);
onSubmitted?.();
} catch (err: unknown) {
setError(err instanceof Error ? err.message : "StockInSubmitFailed");
} finally {
setSubmitting(false);
}
}
// ─── render ────────────────────────────────────────────────────────────────
// Disable Submit when any line has no skuVariationId — covers both:
// (a) product picked but variation not chosen yet, and
// (b) empty line (no product, no variation).
const hasIncompleteLines = lines.some(l => !l.skuVariationId);
return (
<form onSubmit={handleSubmit} noValidate className="space-y-6">
{/* Destination — select from active warehouses, defaults to type-M Master Store */}
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">{t("StockInDestination")}</Label>
{warehousesLoading ? (
<Skeleton role="status" aria-label={t("UiLoading")} className="h-9 w-full" />
) : (
<Select value={selectedWarehouseId} onValueChange={setSelectedWarehouseId}>
<SelectTrigger aria-label={t("StockInDestination")} className="w-[300px]">
<SelectValue placeholder={t("StockSelectWarehouse")} />
</SelectTrigger>
<SelectContent>
{activeWarehouses.map(w => (
<SelectItem key={w.id} value={String(w.id)}>
{w.code} — {w.name}
</SelectItem>
))}
</SelectContent>
</Select>
)}
</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"
onClick={handleDownloadTemplate}
>
<Download aria-hidden className="mr-1 size-4" />
{t("CatDownloadTemplate")}
</Button>
{/* Hidden file input — triggered by the Import button */}
<input
ref={fileInputRef}
id="stock-in-import"
type="file"
accept=".xlsx"
aria-label={t("StockInImportAria")}
className="sr-only"
onChange={handleImport}
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
>
<Upload aria-hidden className="mr-1 size-4" />
{t("Import")}
</Button>
</div>
{/* Line editor */}
<div className="space-y-4">
{lines.map((line, idx) => (
<StockInLineEditor
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 */}
{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>
)}
{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("StockInSubmitted", { docNo: t(successDocNo) })}
</div>
)}
<Button
type="submit"
disabled={submitting || warehousesLoading || !selectedWarehouseId || hasIncompleteLines}
>
{submitting && <Loader2 aria-hidden className="mr-2 size-4 animate-spin" />}
{t("Submit")}
</Button>
</form>
);
}
// ─── StockInLineEditor ───────────────────────────────────────────────────────
interface StockInLineEditorProps {
line: StockInLine;
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 StockInLineEditor({
line,
lineNumber,
products,
onPickerOpenChange,
onProductPick,
onVariationChange,
showQuantityError,
onQuantityChange,
onBatchNumberChange,
onExpiryDateChange,
onRemove,
}: StockInLineEditorProps) {
const variationSelectId = `variation-${line.key}`;
const t = useT();
const qtyId = `qty-${line.key}`;
const qtyErrorId = `qty-error-${line.key}`;
const batchId = `batch-${line.key}`;
const expiryId = `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 (mirrors MemberCombobox in reports/page.tsx) */}
<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>
);
}