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

603 lines
23 KiB
TypeScript

"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { Check, ChevronsUpDown, Loader2, Plus, Trash2 } 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 { adjustStock, getProductVariations } 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,
AdjustmentReason,
ProductListRow,
ProductVariationOption,
} from "@/app/lib/types";
import { cn } from "@/app/lib/utils";
import { parseQuantityInput } from "@/app/lib/inventory/quantityInput";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { insufficientStockMessage } from "./insufficientStock";
import type { StockFormProps } from "./StockInForm";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { INVENTORY_MODULES } from "@/app/lib/inventoryModules";
// Adjustment form (openspec/changes/add-inventory-adjustments, I4 Task 6).
// - One warehouse <select> (active warehouses only).
// - Increase / Decrease direction toggle (sends "IN" or "OUT" to the backend).
// - A required reason <select> with six exact backend-validated strings plus an optional note.
// - Multi-line SKU editor (product picker + variation + qty + optional batch/expiry).
// - Submit disabled until: a warehouse, a direction, a reason, and >=1 complete line.
// - On success: show the documentNo (AJI.../AJO...) and reset lines.
// - On 4xx: display the error message; keep lines so the admin can correct and resubmit.
// No side-effects on mount/prefetch — all mutations go through the submit handler.
// ─── reason constants ─────────────────────────────────────────────────────────
// The six exact reason strings the backend validates (case-sensitive).
// Values are submitted verbatim; labels may be friendlier.
const ADJUSTMENT_REASONS: { value: AdjustmentReason; labelCode: string }[] = [
{ value: "Damage", labelCode: "StockAdjReasonDamage" },
{ value: "Expiry", labelCode: "StockAdjReasonExpiry" },
{ value: "Return-to-shelf", labelCode: "StockAdjReasonReturnToShelf" },
{ value: "Cancelled-DO", labelCode: "StockAdjReasonCancelledDo" },
{ value: "Transfer-gap", labelCode: "StockAdjReasonTransferGap" },
{ value: "Count-correction", labelCode: "StockAdjReasonCountCorrection" },
];
// ─── types ───────────────────────────────────────────────────────────────────
interface AdjustmentLine {
/** 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(): AdjustmentLine {
return {
key: _nextKey++,
productId: "",
productLabel: "",
pickerOpen: false,
variations: [],
variationsLoading: false,
skuVariationId: "",
variationId: "",
quantity: 1,
quantityText: "1",
batchNumber: "",
expiryDate: "",
};
}
// ─── component ───────────────────────────────────────────────────────────────
export function AdjustmentForm({ defaultWarehouseId, onSubmitted, onDirtyChange }: StockFormProps = {}) {
const [activeWarehouses, setActiveWarehouses] = useState<AdminWarehouse[]>([]);
const [warehouseId, setWarehouseId] = useState<string>("");
const [warehousesLoading, setWarehousesLoading] = useState(true);
const [direction, setDirection] = useState<"IN" | "OUT">("IN");
const [reason, setReason] = useState<AdjustmentReason | "">("");
const [note, setNote] = useState<string>("");
const [products, setProducts] = useState<ProductListRow[]>([]);
const [lines, setLines] = useState<AdjustmentLine[]>([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 t = useT();
const [error, setError] = useState<string | null>(null);
const [successDocNo, setSuccessDocNo] = useState<string | null>(null);
const canSeeHistory = useAdminAuth().hasModule(INVENTORY_MODULES.history);
// 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)) {
setWarehouseId(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 retry once the page reloads.
});
return () => { cancelled = true; };
}, []);
// Anything entered counts as unsaved work (the Inventory page asks before closing the panel). The
// reason and note are kept after a submit for the next adjustment, so from then on only lines count.
const headerEntered = successDocNo === null && (reason !== "" || note !== "");
const dirty = headerEntered || 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<AdjustmentLine>) {
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 });
}
}
// ─── submit ────────────────────────────────────────────────────────────────
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!warehouseId || !reason) return;
setError(null);
setSuccessDocNo(null);
setQuantityAttempted(true);
if (lines.some(l => l.quantity < 1)) return;
setSubmitting(true);
try {
const result = await adjustStock({
warehouseId,
direction,
reason: reason as AdjustmentReason,
...(note.trim() ? { note: note.trim() } : {}),
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 } : {}),
})),
});
// 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()]);
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, lines, t) ??
(err instanceof Error ? err.message : "StockAdjSubmitFailed"),
);
} finally {
setSubmitting(false);
}
}
// ─── render ────────────────────────────────────────────────────────────────
// Submit is disabled unless:
// 1. A warehouse is chosen.
// 2. A reason is selected.
// 3. At least one complete line (skuVariationId set) exists.
const hasIncompleteLines = lines.some(l => !l.skuVariationId);
const submitDisabled =
submitting ||
warehousesLoading ||
!warehouseId ||
!reason ||
hasIncompleteLines;
return (
<form onSubmit={handleSubmit} noValidate className="space-y-6">
{/* Warehouse select */}
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">{t("Warehouse")}</Label>
{warehousesLoading ? (
<Skeleton role="status" aria-label={t("UiLoading")} className="h-9 w-full" />
) : (
<Select value={warehouseId} onValueChange={setWarehouseId}>
<SelectTrigger aria-label={t("Warehouse")} 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>
{/* Direction toggle: Increase (IN) / Decrease (OUT) */}
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">{t("StockAdjDirection")}</Label>
<div className="flex gap-2" role="group" aria-label={t("StockAdjDirection")}>
<Button
type="button"
variant={direction === "IN" ? "default" : "outline"}
size="sm"
onClick={() => setDirection("IN")}
aria-pressed={direction === "IN"}
>
{t("StockAdjIncrease")}
</Button>
<Button
type="button"
variant={direction === "OUT" ? "default" : "outline"}
size="sm"
onClick={() => setDirection("OUT")}
aria-pressed={direction === "OUT"}>
{t("StockAdjDecrease")}
</Button>
</div>
</div>
{/* Reason select — required */}
<div className="space-y-1">
<Label htmlFor="adjustment-reason" className="text-xs text-muted-foreground">
{t("StockAdjReason")} <span className="text-destructive">*</span>
</Label>
<Select
value={reason}
onValueChange={v => setReason(v as AdjustmentReason)}
>
<SelectTrigger id="adjustment-reason" aria-label={t("StockAdjReason")} className="w-[300px]">
<SelectValue placeholder={t("StockAdjSelectReason")} />
</SelectTrigger>
<SelectContent>
{ADJUSTMENT_REASONS.map(r => (
<SelectItem key={r.value} value={r.value}>
{t(r.labelCode)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Note (optional free-text) */}
<div className="space-y-1">
<Label htmlFor="adjustment-note" className="text-xs text-muted-foreground">
{t("StockAdjNote")}{" "}
<span className="font-normal text-muted-foreground">{t("StockOptional")}</span>
</Label>
<Input
id="adjustment-note"
type="text"
value={note}
onChange={e => setNote(e.target.value)}
placeholder={t("StockAdjNotePlaceholder")}
className="w-[300px]"
/>
</div>
{/* Line editor */}
<div className="space-y-4">
{lines.map((line, idx) => (
<AdjustmentLineEditor
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("StockAdjSubmitted", { docNo: t(successDocNo) })}
</div>
)}
<Button type="submit" disabled={submitDisabled}>
{submitting && <Loader2 aria-hidden className="mr-2 size-4 animate-spin" />}
{t("Submit")}
</Button>
{/* Link to the History tab for past adjustments (AJI/AJO entries), for users who can see it.
Keeps action=adjust so the panel, and any lines entered, stay open while the tab behind it
switches; replace, like the page's own URL updates. */}
{canSeeHistory && (
<p className="text-xs text-muted-foreground">
{t("StockAdjHistoryBefore")}{" "}
<Link href="/inventory?tab=history&action=adjust" replace className="underline underline-offset-2">
{t("InvTabHistory")}
</Link>{" "}
{t("StockAdjHistoryAfter")}
</p>
)}
</form>
);
}
// ─── AdjustmentLineEditor ─────────────────────────────────────────────────────
interface AdjustmentLineEditorProps {
line: AdjustmentLine;
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 AdjustmentLineEditor({
line,
lineNumber,
products,
onPickerOpenChange,
onProductPick,
onVariationChange,
showQuantityError,
onQuantityChange,
onBatchNumberChange,
onExpiryDateChange,
onRemove,
}: AdjustmentLineEditorProps) {
const variationSelectId = `adj-variation-${line.key}`;
const t = useT();
const qtyId = `adj-qty-${line.key}`;
const qtyErrorId = `adj-qty-error-${line.key}`;
const batchId = `adj-batch-${line.key}`;
const expiryId = `adj-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>
);
}