Files
co-lite/solvway-admin-portal/app/catalog-setup/page.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

495 lines
18 KiB
TypeScript

"use client";
import { useCallback, useEffect, useMemo, useRef, useState, type FormEvent } from "react";
import { Pencil, Plus } from "lucide-react";
import type { SortingState } from "@tanstack/react-table";
import { SortableHead, sortRows } from "@/app/components/ui/sortable-head";
import { Badge } from "@/app/components/ui/badge";
import { Button } from "@/app/components/ui/button";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/app/components/ui/dialog";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/app/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/app/components/ui/tabs";
import { PageHeader } from "@/app/components/ui/page-header";
import { RowActions } from "@/app/components/ui/row-actions";
import { EmptyState, ErrorState, TableSkeleton } from "@/app/components/ui/states";
import { FilterPanel, FilterField, FilterSearch } from "@/app/components/ui/filter-panel";
import { RequireModule } from "@/app/lib/RequireModule";
import { matchesCodeOrName } from "@/app/lib/codeOrNameSearch";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import {
CATALOG_TABLES,
type CatalogColumn,
type CatalogTableSpec,
} from "@/app/lib/catalogTables";
import {
createCatalogRow,
listCatalogRows,
toggleCatalogRowStatus,
updateCatalogRow,
uploadCatalogImage,
} from "@/app/lib/services/adminCatalog";
import type { CatalogRow, CatalogRowPayload } from "@/app/lib/types";
// Allowed image types and size limit (mirrors app/bulletins/page.tsx).
const ALLOWED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
const MAX_IMAGE_BYTES = 2 * 1024 * 1024; // 2 MB
function fileToBase64(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve((reader.result as string).split(",")[1]);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
}
// `/catalog-setup` catalogue-list management (add-admin-catalog-setup, spec
// "admin-portal-catalog-ui"): one generic surface over the three maintained product-catalog
// lists (brand, category, priceType). Mirrors app/reference/page.tsx's
// table-picker + registry-driven grid + add/edit dialog pattern. All three lists key off the same
// wire field, CatalogRow.code (mobile-api carries every list's stable key there — for
// category/priceType it doubles as the display value); only the column LABEL differs per list.
// The dialog's read-only-on-edit field is still derived from CatalogTableSpec.keyField rather than
// hardcoded, mirroring the reference page. Status is never a dialog field — it renders as a Badge in the grid and
// changes only through the inline Activate/Deactivate action (POST toggle-status), never a
// hard delete. Wrapped in RequireModule against the seeded BO_CATALOG_SETUP module (id
// 41900000, under the BO_CATALOG group). GETs are pure reads — no side effects on prefetch, and
// the toggle is always a POST, never wired to a GET.
// Collection was removed (openspec/changes/bundle-by-sku-drop-collection) — Category is
// sufficient; it had no product relationship and 0 rows.
interface DialogState {
mode: "add" | "edit";
id?: string;
values: Record<string, string>;
}
function valueFor(row: CatalogRow, field: string): string {
const v = (row as unknown as Record<string, unknown>)[field];
return v == null ? "" : String(v);
}
function emptyValues(spec: CatalogTableSpec): Record<string, string> {
const values: Record<string, string> = {};
for (const col of spec.columns) values[col.field] = "";
if (spec.hasImage) values.imageUrl = "";
return values;
}
function valuesForRow(spec: CatalogTableSpec, row: CatalogRow): Record<string, string> {
const values: Record<string, string> = {};
for (const col of spec.columns) values[col.field] = valueFor(row, col.field);
if (spec.hasImage) values.imageUrl = row.imageUrl ?? "";
return values;
}
function rowKey(spec: CatalogTableSpec, row: CatalogRow): string {
return row.id ?? valueFor(row, spec.keyField);
}
function CatalogFormDialog({
spec,
mode,
id,
initial,
onClose,
onSaved,
}: {
spec: CatalogTableSpec;
mode: "add" | "edit";
id?: string;
initial: Record<string, string>;
onClose: () => void;
onSaved: () => void;
}) {
const [values, setValues] = useState<Record<string, string>>(initial);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [imageError, setImageError] = useState<string | null>(null);
const [imageFile, setImageFile] = useState<File | null>(null);
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
const previewRef = useRef<string | null>(null);
const isEdit = mode === "edit";
const t = useT();
function setField(field: string, value: string) {
setValues((prev) => ({ ...prev, [field]: value }));
}
// Revoke previous object URL on cleanup / new selection.
useEffect(() => {
return () => {
if (previewRef.current) {
URL.revokeObjectURL(previewRef.current);
previewRef.current = null;
}
};
}, []);
function handleImagePick(file: File | undefined) {
// Revoke old blob.
if (previewRef.current) {
URL.revokeObjectURL(previewRef.current);
previewRef.current = null;
}
setPreviewUrl(null);
setImageFile(null);
setImageError(null);
if (!file) return;
if (!ALLOWED_IMAGE_TYPES.includes(file.type)) {
setImageError("CatImageTypeNotAllowed");
return;
}
if (file.size > MAX_IMAGE_BYTES) {
setImageError("CatImageTooLarge");
return;
}
const url = URL.createObjectURL(file);
previewRef.current = url;
setPreviewUrl(url);
setImageFile(file);
}
function removeImage() {
if (previewRef.current) {
URL.revokeObjectURL(previewRef.current);
previewRef.current = null;
}
setPreviewUrl(null);
setImageFile(null);
setImageError(null);
setField("imageUrl", "");
}
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setSaving(true);
setError(null);
setImageError(null);
try {
// Every editable field is always sent (trimmed); a blank optional one (supplier contact fields) clears it.
// Status is never among them.
const payload: CatalogRowPayload = {};
for (const col of spec.columns.filter((c) => c.editable)) {
(payload as Record<string, string>)[col.field] = (values[col.field] ?? "").trim();
}
if (spec.hasImage) {
let imageUrl = values.imageUrl ?? "";
if (imageFile) {
const base = await fileToBase64(imageFile);
try {
imageUrl = (await uploadCatalogImage(spec.key, {
fileName: imageFile.name,
fileType: imageFile.type,
base,
})).url;
// Keep the uploaded URL: if the save below fails, a retry reuses it rather than
// uploading (and auto-committing) the same file again.
setField("imageUrl", imageUrl);
setImageFile(null);
} catch (err) {
// An upload failure BLOCKS the save — never persist a row pointing at a missing image.
setError(err instanceof Error ? t("CatImageUploadFailedReason", { message: t(err.message) }) : t("CatImageUploadFailed"));
return;
}
}
payload.imageUrl = imageUrl;
}
if (isEdit && id != null) {
await updateCatalogRow(spec.key, id, payload);
} else {
await createCatalogRow(spec.key, payload);
}
onSaved();
onClose();
} catch (err) {
// A duplicate-key 409 / validation 422 surfaces here as the downstream message —
// reported inline, never a silent no-op and never a phantom success in the grid.
setError(err instanceof Error ? err.message : "CatSaveRowFailed");
} finally {
setSaving(false);
}
}
function renderField(col: CatalogColumn) {
const fieldId = `cat-${col.field}`;
const readOnly = col.field === spec.keyField && isEdit;
return (
<Input
key={col.field}
id={fieldId}
required={col.required}
readOnly={readOnly}
disabled={saving}
value={values[col.field] ?? ""}
onChange={(e) => setField(col.field, e.target.value)}
className={readOnly ? "opacity-70" : undefined}
/>
);
}
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>
{isEdit ? t("CatEditRowTitle", { noun: t(spec.noun) }) : t("CatAddRowTitle", { noun: t(spec.noun) })}
</DialogTitle>
</DialogHeader>
{error && <ErrorState message={t(error)} />}
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
{spec.columns.filter((c) => c.editable).map((col) => (
<div key={col.field} className="space-y-1.5">
<Label htmlFor={`cat-${col.field}`}>{t(col.label)}</Label>
{renderField(col)}
{col.field === spec.keyField && isEdit && (
<p className="text-xs text-muted-foreground">
{t("CatKeyImmutableNote", { label: t(col.label) })}
</p>
)}
</div>
))}
{spec.hasImage && (
<div className="space-y-1.5">
<Label htmlFor="cat-image">{t("CatImage")}</Label>
{(previewUrl ?? values.imageUrl) ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={previewUrl ?? values.imageUrl} alt={t("CatImagePreviewAlt")}
className="max-h-32 w-full rounded border object-contain" />
) : (
<p className="text-sm text-muted-foreground">{t("CatNoImageSelected")}</p>
)}
<Input id="cat-image" type="file" accept="image/png,image/jpeg,image/webp,image/gif"
disabled={saving}
onChange={(e) => { handleImagePick(e.target.files?.[0]); e.target.value = ""; }} />
{(previewUrl ?? values.imageUrl) && (
<Button type="button" variant="outline" size="sm" onClick={removeImage} disabled={saving}>
{t("CatRemoveImage")}
</Button>
)}
{imageError && <p className="text-sm text-destructive">{t(imageError)}</p>}
</div>
)}
<DialogFooter>
<Button type="submit" disabled={saving}>
{t("Save")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
function CatalogSetupPageContent() {
const t = useT();
const [listKey, setListKey] = useState(CATALOG_TABLES[0].key);
const spec = useMemo(
() => CATALOG_TABLES.find((t) => t.key === listKey) ?? CATALOG_TABLES[0],
[listKey],
);
const [rows, setRows] = useState<CatalogRow[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
const [dialog, setDialog] = useState<DialogState | null>(null);
const [search, setSearch] = useState("");
const shownRows = useMemo(() => rows.filter((row) => matchesCodeOrName(row, search)), [rows, search]);
const [sorting, setSorting] = useState<SortingState>([]);
const sortedRows = useMemo(
() => sortRows(shownRows, sorting, Object.fromEntries(spec.columns.map((c) => [c.field, (r: CatalogRow) => valueFor(r, c.field)]))),
[shownRows, sorting, spec.columns],
);
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
useEffect(() => {
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error ahead of the listKey-triggered fetch below, which is the actual synchronization.
setLoading(true);
setError(null);
listCatalogRows(listKey)
.then((result) => {
if (!cancelled) setRows(result);
})
.catch((err: unknown) => {
if (!cancelled) setError(err instanceof Error ? err.message : "CatLoadRowsFailed");
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [listKey, reloadKey]);
function openAdd() {
setDialog({ mode: "add", values: emptyValues(spec) });
}
function openEdit(row: CatalogRow) {
setDialog({ mode: "edit", id: row.id, values: valuesForRow(spec, row) });
}
async function toggleStatus(row: CatalogRow) {
if (row.id == null) return;
setError(null);
try {
await toggleCatalogRowStatus(spec.key, row.id);
refetch();
} catch (err) {
setError(err instanceof Error ? err.message : "CatUpdateStatusFailed");
}
}
return (
<Tabs
className="block"
value={listKey}
onValueChange={(key) => {
setListKey(key as typeof listKey);
setSearch("");
setSorting([]);
setDialog(null); // a dialog from another list is never kept open
}}
>
<PageHeader
title={t("BO_CATALOG_SETUP")}
actions={
<Button onClick={openAdd}>
<Plus aria-hidden="true" className="size-4" />
{t("CatAddRow")}
</Button>
}
>
<TabsList aria-label={t("CatListTabsLabel")}>
{CATALOG_TABLES.map((table) => (
<TabsTrigger key={table.key} value={table.key}>{t(table.label)}</TabsTrigger>
))}
</TabsList>
</PageHeader>
<TabsContent value={listKey}>
<FilterPanel className="mb-4" activeCount={search.trim() ? 1 : 0} onClear={() => setSearch("")}>
<FilterField label={t("CatCodeOrName")}>
<FilterSearch aria-label={t("CatCodeOrName")} placeholder={t("CatCodeOrName")} value={search} onChange={setSearch} />
</FilterField>
</FilterPanel>
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
{/* A failed fetch must not leave the previous list's rows on screen: the grid is gated
on !error, so switching lists with the new fetch failing shows only the error banner
— never stale rows under the new list's headers. */}
{error ? null : loading ? (
<TableSkeleton columns={spec.columns.length + 1 + (spec.hasImage ? 1 : 0)} />
) : rows.length === 0 ? (
<EmptyState title={t("CatNoRowsYet", { noun: t(spec.noun) })} />
) : shownRows.length === 0 ? (
<EmptyState title={t("CatNoRowsMatch")} />
) : (
<div className="overflow-hidden rounded-table border bg-card">
<Table>
<TableHeader>
<TableRow>
{spec.hasImage && <TableHead className="w-16">{t("CatImage")}</TableHead>}
{spec.columns.map((col) => (
<SortableHead key={col.field} label={t(col.label)} sortKey={col.field} sorting={sorting} onSortingChange={setSorting} />
))}
<TableHead className="w-24 text-right">{t("CatActions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{sortedRows.map((row) => {
const key = valueFor(row, spec.keyField);
const isActive = row.status === "Y";
return (
<TableRow key={rowKey(spec, row)}>
{spec.hasImage && (
<TableCell>
{row.imageUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={row.imageUrl} alt={t("CatRowLogoAlt", { key })} className="h-10 w-10 rounded border object-contain" />
) : (
<span className="text-xs text-muted-foreground">{t("CatNoImage")}</span>
)}
</TableCell>
)}
{spec.columns.map((col) =>
col.badge ? (
<TableCell key={col.field}>
<Badge variant={isActive ? "positive" : "neutral"}>
{isActive ? t("CatActive") : t("CatInactive")}
</Badge>
</TableCell>
) : (
<TableCell key={col.field}>{valueFor(row, col.field) || "—"}</TableCell>
),
)}
<TableCell>
<RowActions
label={key}
items={[{ label: isActive ? t("CatDeactivate") : t("CatActivate"), destructive: isActive, onSelect: () => toggleStatus(row) }]}
>
<Button
variant="ghost"
size="sm"
aria-label={t("CatEditRowAria", { key })}
onClick={() => openEdit(row)}
className="h-8 px-2"
>
<Pencil aria-hidden="true" className="size-3.5" />
</Button>
</RowActions>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
)}
{dialog && (
<CatalogFormDialog
spec={spec}
mode={dialog.mode}
id={dialog.id}
initial={dialog.values}
onClose={() => setDialog(null)}
onSaved={refetch}
/>
)}
</TabsContent>
</Tabs>
);
}
export default function CatalogSetupPage() {
return (
<RequireModule pathname="/catalog-setup">
<CatalogSetupPageContent />
</RequireModule>
);
}