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

588 lines
25 KiB
TypeScript

"use client";
import { useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { ArrowDown, ArrowUp, Plus, Trash2, X } from "lucide-react";
import { Badge } from "@/app/components/ui/badge";
import { Button } from "@/app/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/app/components/ui/radio-group";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
import { ErrorState } from "@/app/components/ui/states";
import { Textarea } from "@/app/components/ui/textarea";
import { FieldError } from "@/app/components/catalog-setup/FieldError";
import { ProductSearchCombobox } from "@/app/components/products/ProductSearchCombobox";
import { parseServerError, type FieldErrors } from "@/app/lib/catalogSetup";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import {
RULE_FIELD_LABELS,
SORT_LABELS,
collectionBody,
collectionFromView,
emptyCollection,
moveProduct,
previewBody,
validateCollection,
withTitle,
withType,
type CollectionDraft,
type CollectionPreview,
type CollectionSort,
type RuleField,
} from "@/app/lib/collections";
import { displayLocaleName } from "@/app/lib/messageContent";
import {
deleteCollection,
getCollection,
previewCollection,
saveCollection,
uploadCollectionImage,
} from "@/app/lib/services/adminCollections";
import { getProductOptions, listProductTags } from "@/app/lib/services/adminProduct";
import type { CatalogRow } from "@/app/lib/types";
// The collection form (add-storefront-collections): Manual (hand-picked, ordered products) or
// Automatic (conditions on brand, category or tag). The type is chosen once, at creation.
// The image is a SAME-REQUEST upload: it is sent only on save, just before the save call.
const PREVIEW_DELAY_MS = 300;
/** Error paths the form renders under a field; any other server path becomes the summary. */
const SHOWN_ERROR_SLOT = /^(title|slug|description|imageUrl|metaDescription|sort|rules|productIds|rules\[\d+\]\.(value|field))$/;
const MANUAL_SORTS: CollectionSort[] = ["MANUAL", "PRICE_ASC", "PRICE_DESC", "NEWEST", "NAME"];
const AUTOMATIC_SORTS: CollectionSort[] = ["NEWEST", "PRICE_ASC", "PRICE_DESC", "NAME"];
function readDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
}
export function CollectionForm({ collectionId }: { collectionId?: number }) {
const t = useT();
const router = useRouter();
const [draft, setDraft] = useState<CollectionDraft>(() => emptyCollection("MANUAL"));
const [loading, setLoading] = useState(collectionId != null);
const [loadError, setLoadError] = useState<string | null>(null);
const [errors, setErrors] = useState<FieldErrors>({});
const [summary, setSummary] = useState<string | null>(null);
// A new collection's save moves to its edit URL with ?saved=1, which remounts the form.
const savedParam = useSearchParams()?.get("saved") === "1";
const [notice, setNotice] = useState<string | null>(savedParam ? "CollSaved" : null);
const [saving, setSaving] = useState(false);
const [imageFile, setImageFile] = useState<File | null>(null);
const [imagePreview, setImagePreview] = useState("");
const [brands, setBrands] = useState<CatalogRow[]>([]);
const [categories, setCategories] = useState<CatalogRow[]>([]);
const [tags, setTags] = useState<string[]>([]);
const [preview, setPreview] = useState<CollectionPreview | null>(null);
const [confirmDelete, setConfirmDelete] = useState(false);
useEffect(() => {
let cancelled = false;
getProductOptions()
.then((opts) => {
if (cancelled) return;
setBrands(opts.brands);
setCategories(opts.categories);
})
.catch(() => {});
listProductTags()
.then((found) => {
if (!cancelled) setTags(found);
})
.catch(() => {});
return () => {
cancelled = true;
};
}, []);
useEffect(() => {
if (collectionId == null) return;
let cancelled = false;
getCollection(collectionId)
.then((view) => {
if (!cancelled) setDraft(collectionFromView(view));
})
.catch((err: unknown) => {
if (!cancelled) setLoadError(err instanceof Error ? err.message : "CollLoadFailed");
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [collectionId]);
const previewKey = JSON.stringify(previewBody({ ...draft, title: "", slug: "", description: "", metaDescription: "", imageUrl: "" }));
useEffect(() => {
if (loading) return;
let cancelled = false;
const timer = setTimeout(() => {
previewCollection(JSON.parse(previewKey))
.then((result) => {
if (!cancelled) setPreview(result);
})
.catch(() => {
if (!cancelled) setPreview(null);
});
}, PREVIEW_DELAY_MS);
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [previewKey, loading]);
function patch(next: Partial<CollectionDraft>) {
setDraft((d) => ({ ...d, ...next }));
}
function setRule(index: number, next: { field?: RuleField; value?: string }) {
setDraft((d) => ({
...d,
rules: d.rules.map((rule, i) =>
i !== index ? rule : next.field && next.field !== rule.field ? { field: next.field, value: "" } : { ...rule, ...next },
),
}));
}
async function chooseImage(file: File | undefined) {
if (!file) return;
setImageFile(file);
setImagePreview(await readDataUrl(file));
}
async function save() {
setSummary(null);
setNotice(null);
const clientErrors = validateCollection(draft, t);
setErrors(clientErrors);
if (Object.keys(clientErrors).length > 0) return;
setSaving(true);
try {
let imageUrl = draft.imageUrl;
if (imageFile) {
const base = (await readDataUrl(imageFile)).split(",")[1];
imageUrl = (await uploadCollectionImage({ fileName: imageFile.name, fileType: imageFile.type, base })).url;
// Keep the uploaded URL, so a retry after a failed save never uploads the image again.
setImageFile(null);
setImagePreview("");
patch({ imageUrl });
}
const view = await saveCollection(collectionBody({ ...draft, imageUrl }));
setDraft(collectionFromView(view));
setImageFile(null);
setImagePreview("");
setNotice("CollSaved");
if (draft.id == null) router.replace(`/collections/${view.id}?saved=1`);
} catch (err) {
const message = err instanceof Error ? err.message : "CollSaveFailed";
const { path, message: fieldMessage } = parseServerError(message);
const slot = path?.startsWith("productIds[") ? "productIds" : path;
if (slot && SHOWN_ERROR_SLOT.test(slot)) setErrors({ [slot]: fieldMessage });
else setSummary(message);
} finally {
setSaving(false);
}
}
async function remove() {
if (draft.id == null) return;
setSummary(null);
try {
await deleteCollection(draft.id);
router.push("/collections");
} catch (err) {
setSummary(err instanceof Error ? err.message : "CollDeleteFailed");
}
}
if (loadError) return <ErrorState message={t(loadError)} />;
if (loading) return null;
const automatic = draft.type === "AUTOMATIC";
const sorts = automatic ? AUTOMATIC_SORTS : MANUAL_SORTS;
const shownImage = imagePreview || draft.imageUrl;
return (
<div className="space-y-4">
{summary && <ErrorState message={t(summary)} />}
{notice && (
<p role="status" className="text-sm text-positive">
{t(notice)}
</p>
)}
<div className="grid gap-4 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
<div className="space-y-4">
<Card>
<CardHeader>
<CardTitle>{t("CollCardCollection")}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-1.5">
<Label htmlFor="collection-title">
{t("Title")} <span aria-hidden="true" className="text-destructive">*</span>
</Label>
<Input
id="collection-title"
value={draft.title}
aria-invalid={!!errors.title}
disabled={saving}
onChange={(e) => setDraft((d) => withTitle(d, e.target.value))}
/>
<FieldError message={errors.title} />
</div>
<div className="space-y-1.5">
<Label htmlFor="collection-slug">
{t("CollSlug")} <span aria-hidden="true" className="text-destructive">*</span>
</Label>
<div className="flex items-center gap-1 text-sm text-muted-foreground">
<span>{"/collections/"}</span>
<Input
id="collection-slug"
value={draft.slug}
aria-invalid={!!errors.slug}
disabled={saving}
onChange={(e) => patch({ slug: e.target.value, slugTouched: true })}
/>
</div>
<FieldError message={errors.slug} />
</div>
<div className="space-y-1.5">
<Label htmlFor="collection-description">{t("Description")}</Label>
<Textarea
id="collection-description"
rows={3}
value={draft.description}
aria-invalid={!!errors.description}
disabled={saving}
onChange={(e) => patch({ description: e.target.value })}
/>
<FieldError message={errors.description} />
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>{t("CollectionsColProducts")}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{draft.id == null ? (
<RadioGroup
aria-label={t("CollTypeAria")}
value={draft.type}
onValueChange={(v) => setDraft((d) => withType(d.rules.length === 0 && v === "AUTOMATIC" ? { ...d, rules: emptyCollection("AUTOMATIC").rules } : d, v as CollectionDraft["type"]))}
className="gap-3"
>
<div className="flex items-start gap-2">
<RadioGroupItem value="MANUAL" id="collection-type-manual" />
<Label htmlFor="collection-type-manual" className="font-normal">
{t("CollTypeManualOption")}
</Label>
</div>
<div className="flex items-start gap-2">
<RadioGroupItem value="AUTOMATIC" id="collection-type-automatic" />
<Label htmlFor="collection-type-automatic" className="font-normal">
{t("CollTypeAutomaticOption")}
</Label>
</div>
</RadioGroup>
) : (
<p className="text-sm text-muted-foreground">
{t("CollTypeFixed", { type: t(automatic ? "CollTypeAutomatic" : "CollTypeManual") })}
</p>
)}
{automatic ? (
<div className="space-y-3">
<RadioGroup
aria-label={t("CollMatchAria")}
value={draft.match}
onValueChange={(v) => patch({ match: v as CollectionDraft["match"] })}
className="flex flex-wrap gap-4"
>
<div className="flex items-center gap-2">
<RadioGroupItem value="ALL" id="collection-match-all" />
<Label htmlFor="collection-match-all" className="font-normal">
{t("CollMatchAll")}
</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value="ANY" id="collection-match-any" />
<Label htmlFor="collection-match-any" className="font-normal">
{t("CollMatchAny")}
</Label>
</div>
</RadioGroup>
{draft.rules.map((rule, i) => (
<div key={i} className="space-y-1">
<div className="flex flex-wrap items-center gap-2">
<Select value={rule.field} onValueChange={(v) => setRule(i, { field: v as RuleField })} disabled={saving}>
<SelectTrigger aria-label={t("CollConditionFieldAria", { n: i + 1 })} className="w-36">
<SelectValue />
</SelectTrigger>
<SelectContent>
{(Object.keys(RULE_FIELD_LABELS) as RuleField[]).map((field) => (
<SelectItem key={field} value={field}>
{t(RULE_FIELD_LABELS[field])}
</SelectItem>
))}
</SelectContent>
</Select>
<span className="text-sm text-muted-foreground">{t("CollConditionIs")}</span>
{rule.field === "TAG" ? (
<>
<Input
aria-label={t("CollConditionValueAria", { n: i + 1 })}
list="collection-tag-suggestions"
className="w-56"
value={rule.value}
aria-invalid={!!errors[`rules[${i}].value`]}
disabled={saving}
onChange={(e) => setRule(i, { value: e.target.value })}
/>
</>
) : (
<Select value={rule.value} onValueChange={(v) => setRule(i, { value: v })} disabled={saving}>
<SelectTrigger
aria-label={t("CollConditionValueAria", { n: i + 1 })}
aria-invalid={!!errors[`rules[${i}].value`]}
className="w-56"
>
<SelectValue placeholder={rule.field === "BRAND" ? t("ProdPanelSelectBrand") : t("ProdPanelSelectCategory")} />
</SelectTrigger>
<SelectContent>
{(rule.field === "BRAND" ? brands : categories).map((row) => (
<SelectItem key={row.id} value={String(row.id)}>
{row.code}
</SelectItem>
))}
</SelectContent>
</Select>
)}
<Button
type="button"
variant="ghost"
size="sm"
aria-label={t("CollRemoveConditionAria", { n: i + 1 })}
disabled={saving}
onClick={() => patch({ rules: draft.rules.filter((_, j) => j !== i) })}
>
<X aria-hidden="true" className="size-4" />
</Button>
</div>
<FieldError message={errors[`rules[${i}].value`] ?? errors[`rules[${i}].field`]} />
</div>
))}
<datalist id="collection-tag-suggestions">
{tags.map((tag) => (
<option key={tag} value={tag} />
))}
</datalist>
<Button
type="button"
variant="outline"
size="sm"
disabled={saving}
onClick={() => patch({ rules: [...draft.rules, { field: "TAG", value: "" }] })}
>
<Plus aria-hidden="true" className="size-4" />
{t("CollAddCondition")}
</Button>
<FieldError message={errors.rules} />
</div>
) : (
<div className="space-y-3">
<ProductSearchCombobox
aria-label={t("CollAddProductsAria")}
placeholder={t("CollSearchProductsToAdd")}
disabled={saving}
onSelect={(row) => {
const id = Number(row.id);
if (draft.products.some((p) => p.id === id)) return;
patch({
products: [
...draft.products,
{ id, code: row.productCode, name: displayLocaleName(row.productName), status: row.productStatus },
],
});
}}
/>
{draft.products.length > 0 && (
<ol aria-label={t("CollProductsListAria")} className="divide-y rounded-lg border">
{draft.products.map((p, i) => (
<li key={p.id} className="flex items-center gap-2 px-3 py-2 text-sm">
<span className="w-6 text-muted-foreground tabular">{i + 1}</span>
<span className="min-w-0 flex-1">
{p.name} <span className="text-muted-foreground">({p.code})</span>
{p.status && p.status !== "Y" && (
<Badge variant="neutral" className="ml-2">
{t("CollInactiveHidden")}
</Badge>
)}
</span>
<Button type="button" variant="ghost" size="sm" aria-label={t("CollMoveUpAria", { code: p.code })} disabled={saving || i === 0}
onClick={() => patch({ products: moveProduct(draft.products, i, -1) })}>
<ArrowUp aria-hidden="true" className="size-4" />
</Button>
<Button type="button" variant="ghost" size="sm" aria-label={t("CollMoveDownAria", { code: p.code })} disabled={saving || i === draft.products.length - 1}
onClick={() => patch({ products: moveProduct(draft.products, i, 1) })}>
<ArrowDown aria-hidden="true" className="size-4" />
</Button>
<Button type="button" variant="ghost" size="sm" aria-label={t("CollRemoveProductAria", { code: p.code })} disabled={saving}
onClick={() => patch({ products: draft.products.filter((x) => x.id !== p.id) })}>
<X aria-hidden="true" className="size-4" />
</Button>
</li>
))}
</ol>
)}
<FieldError message={errors.productIds} />
</div>
)}
<div className="rounded-lg bg-muted/50 px-3 py-2 text-sm" aria-live="polite">
{preview ? (
<>
<p className="font-medium">
{t(preview.count === 1 ? "CollMatchesOne" : "CollMatchesMany", { count: preview.count })}
</p>
{preview.names.length > 0 && (
<ul className="mt-1 list-disc pl-5 text-muted-foreground">
{preview.names.map((name, i) => (
<li key={`${name}-${i}`}>{name}</li>
))}
</ul>
)}
<p className="mt-1 text-xs text-muted-foreground">{t("CollPreviewNote")}</p>
</>
) : (
<p className="text-muted-foreground">{t("CollPreviewUnavailable")}</p>
)}
</div>
</CardContent>
</Card>
</div>
<div className="space-y-4">
<Card>
<CardHeader>
<CardTitle>{t("CollCardPublishing")}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-1.5">
<Label htmlFor="collection-status">{t("Status")}</Label>
<Select value={draft.status} onValueChange={(v) => patch({ status: v as "Y" | "N" })} disabled={saving}>
<SelectTrigger id="collection-status" aria-label={t("Status")} className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="Y">{t("CatActive")}</SelectItem>
<SelectItem value="N">{t("CatInactive")}</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor="collection-sort">{t("CollSort")}</Label>
<Select value={draft.sort} onValueChange={(v) => patch({ sort: v as CollectionSort })} disabled={saving}>
<SelectTrigger id="collection-sort" aria-label={t("CollSortAria")} aria-invalid={!!errors.sort} className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{sorts.map((sort) => (
<SelectItem key={sort} value={sort}>
{t(SORT_LABELS[sort])}
</SelectItem>
))}
</SelectContent>
</Select>
<FieldError message={errors.sort} />
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>{t("CatImage")}</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{shownImage && (
// eslint-disable-next-line @next/next/no-img-element -- a local preview or a drive URL, not a static asset.
<img src={shownImage} alt="" className="max-h-40 w-full rounded-lg object-cover" />
)}
<Input
type="file"
accept="image/png,image/jpeg,image/webp,image/gif"
aria-label={t("CollImageAria")}
disabled={saving}
onChange={(e) => void chooseImage(e.target.files?.[0])}
/>
{shownImage && (
<Button type="button" variant="outline" size="sm" disabled={saving}
onClick={() => {
setImageFile(null);
setImagePreview("");
patch({ imageUrl: "" });
}}>
{t("CatRemoveImage")}
</Button>
)}
<FieldError message={errors.imageUrl} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>{t("CollCardSeo")}</CardTitle>
</CardHeader>
<CardContent className="space-y-1.5">
<Label htmlFor="collection-meta">{t("CollMetaDescription")}</Label>
<Textarea
id="collection-meta"
rows={3}
value={draft.metaDescription}
aria-invalid={!!errors.metaDescription}
disabled={saving}
onChange={(e) => patch({ metaDescription: e.target.value })}
/>
<p className="text-xs text-muted-foreground tabular">{draft.metaDescription.trim().length} / 160</p>
<FieldError message={errors.metaDescription} />
</CardContent>
</Card>
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-2">
{draft.id != null ? (
<Button type="button" variant="destructive-outline" disabled={saving} onClick={() => setConfirmDelete(true)}>
<Trash2 aria-hidden="true" className="size-4" />
{t("CollDelete")}
</Button>
) : (
<span />
)}
<Button type="button" disabled={saving} onClick={() => void save()}>
{saving ? t("Saving") : t("CollSave")}
</Button>
</div>
<ConfirmDialog
open={confirmDelete}
onOpenChange={setConfirmDelete}
title={t("CollDeleteConfirmTitle")}
description={t("CollDeleteConfirmBody")}
confirmLabel={t("Delete")}
onConfirm={() => void remove()}
/>
</div>
);
}