Files
co-lite/solvway-admin-portal/app/components/product-page/VariantsSection.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

521 lines
25 KiB
TypeScript

"use client";
import { useMemo, useState, type ChangeEvent, type ReactNode } from "react";
import { Plus } from "lucide-react";
import { Badge } from "@/app/components/ui/badge";
import { Button } from "@/app/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/app/components/ui/card";
import { Checkbox } from "@/app/components/ui/checkbox";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Segmented } from "@/app/components/ui/segmented";
import { Switch } from "@/app/components/ui/switch";
import { SkuDrawer } from "@/app/components/catalog-setup/SkuDrawer";
import { SkuPicker } from "@/app/components/catalog-setup/SkuPicker";
import { QianyiSkuPicker } from "@/app/components/products/QianyiSkuPicker";
import { FieldError } from "@/app/components/catalog-setup/FieldError";
import { BarcodeList } from "@/app/components/catalog-setup/BarcodeList";
import { StepTitle, type StepInfo } from "@/app/components/product-page/SetupStep";
import {
addOption,
MAX_OPTIONS,
OPTION_SEPARATOR,
parseOptionValues,
prefillFromQianyi,
removeOption,
setHasVariants,
setOptionValues,
withOptionLabels,
type PriceDraft,
type SkuDraft,
type SkuVariantDraft,
type SkuView,
} from "@/app/lib/catalogSetup";
import { checklistRows, variationsFromChecklist, missingShipping, ownedSku, syncOwnedVariations, syncPrices } from "@/app/lib/productPage";
import { getSku } from "@/app/lib/services/adminCatalogSetup";
import { uploadProductImage } from "@/app/lib/services/adminProduct";
import { fileToBase64 } from "@/app/lib/fileToBase64";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { CodeMatchNotice } from "./CodeMatchNotice";
import { LinkedSkuBanner } from "./LinkedSkuBanner";
import { OptionChips } from "./OptionChips";
import { PriceList } from "./PriceList";
import type { SectionProps } from "./ProductSetupPage";
// The Product page's Variants and Prices cards for a product that owns its SKU (simplify-product-setup): options
// as value chips, one row per variant, a table that switches between shipping and barcodes, then the Prices list in
// a card of its own (feedback 2026-10-28: variants and pricing in one card read as cluttered). Every edit goes
// through edit(): the SKU change and the matching Sales Item variations land in one onChange.
type View = "shipping" | "barcodes";
const VIEWS: { view: View; label: string }[] = [
{ view: "shipping", label: "PageViewShipping" },
{ view: "barcodes", label: "PageViewBarcodes" },
];
// Error keys by column set, so a set that is not on show can still flag its row.
const SET_ERRORS: Record<View, (path: string) => string[]> = {
shipping: (path) => ["weight", "lengthCm", "widthCm", "heightCm", "image"].map((f) => `${path}.${f}`),
barcodes: (path) => [`${path}.barcodes`, `${path}.qySku`],
};
const DIMENSIONS = [
{ key: "weight", label: "SkuWeightKg", aria: "SkuVariantNWeight", step: "0.001" },
{ key: "lengthCm", label: "SkuLengthCm", aria: "SkuVariantNLengthCm", step: "0.01" },
{ key: "widthCm", label: "SkuWidthCm", aria: "SkuVariantNWidthCm", step: "0.01" },
{ key: "heightCm", label: "SkuHeightCm", aria: "SkuVariantNHeightCm", step: "0.01" },
] as const;
type LinkProps = {
/** Set when the product sells SKUs it does not own: the Sell-column table replaces the owned one. */
linkedSkus?: SkuView[];
/** `replacing`: the SKU a banner's Change swapped out. */
onLink: (view: SkuView, replacing?: number) => void;
onReload: (view: SkuView) => void;
};
/** The Variants card: the step title, then the section's body. */
function VariantsCard({ step, children }: { step?: StepInfo; children: ReactNode }) {
const t = useT();
return (
<Card role="region" aria-labelledby="variants-title">
<CardHeader>
<CardTitle id="variants-title"><StepTitle step={step}>{t("SkuListVariants")}</StepTitle></CardTitle>
</CardHeader>
<CardContent className="space-y-4">{children}</CardContent>
</Card>
);
}
/** The Prices card, its own step after Variants (Bundle has the same card in BundleSection). */
export function PricesCard({ step, children }: { step?: StepInfo; children: ReactNode }) {
const t = useT();
return (
<Card id="setup-pricing" role="region" aria-labelledby="pricing-title" className="scroll-mt-48">
<CardHeader>
<CardTitle id="pricing-title"><StepTitle step={step}>{t("PageViewPrices")}</StepTitle></CardTitle>
<CardDescription>{t("SetupPricesHint")}</CardDescription>
</CardHeader>
<CardContent>{children}</CardContent>
</Card>
);
}
export function VariantsSection(props: SectionProps & LinkProps & { deferred: number[] }) {
return props.linkedSkus ? <LinkedVariants {...props} linkedSkus={props.linkedSkus} /> : <OwnedVariants {...props} />;
}
// A product selling SKUs it does not own: per SKU a banner and a Sell checklist (read-only stock fields; prices are in
// the Prices list). Ticking a variant adds its variation; the SKU itself is edited only in the drawer.
function LinkedVariants({ item, saved, prices, savedPrices, onChange, errors, saving, today, options, linkedSkus, onLink, onReload, step, pricingStep }: SectionProps & LinkProps & { linkedSkus: SkuView[] }) {
const t = useT();
// The id of the SKU whose banner opened the picker.
const [changing, setChanging] = useState<number | null>(null);
const [drawerSku, setDrawerSku] = useState<number | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const commitPrices = (rows: PriceDraft[]) => onChange({ prices: rows });
// The sold variations, named like the table rows.
const soldNames = new Map(linkedSkus.flatMap((sku) => checklistRows(sku, item, t).flatMap((r) => (r.variationKey ? [[r.variationKey, r.label || r.code] as const] : []))));
function setTicked(sku: SkuView, ticked: Set<number>) {
// Each SKU keeps its place; an unticked variation's price rows go, a ticked saved one gets its rows back.
const variations = linkedSkus.flatMap((s) =>
s.id === sku.id ? variationsFromChecklist(sku, item, ticked, saved) : item.variations.filter((v) => v.components[0]?.skuId === s.id),
);
onChange({ item: { ...item, variations }, prices: syncPrices(prices, savedPrices, item.variations, variations) });
}
return (
<div className="space-y-4">
<VariantsCard step={step}>
<FieldError message={errors["salesItem.variations"]} />
{loadError && <FieldError message={t(loadError)} />}
{changing != null && (
<div className="flex items-center gap-2">
<div className="flex-1">
<SkuPicker
disabled={saving}
onSelect={(row) =>
getSku(row.id)
.then((view) => {
const replacing = changing;
setChanging(null);
setLoadError(null);
onLink(view, replacing);
})
.catch((err: unknown) => setLoadError(err instanceof Error ? err.message : "SkuLoadFailed"))
}
/>
</div>
<Button type="button" variant="ghost" size="sm" onClick={() => setChanging(null)}>
{t("Cancel")}
</Button>
</div>
)}
{linkedSkus.map((sku) => {
const rows = checklistRows(sku, item, t);
const ticked = new Set(rows.filter((r) => r.variationKey != null).map((r) => r.skuVariationId));
const otherItems = [...new Set(sku.variations.flatMap((v) => v.usedBy))].filter((c) => c.toLowerCase() !== item.code.toLowerCase());
return (
<div key={sku.id} className="space-y-2">
<LinkedSkuBanner sku={sku} otherItems={otherItems} onEdit={() => setDrawerSku(sku.id)} onChange={() => setChanging(sku.id)} />
<div className="relative overflow-x-auto rounded-lg border">
<table className="w-full text-sm">
<thead>
<tr className="border-b text-left text-xs font-medium text-muted-foreground">
<th className="px-3 py-2">{t("PageSell")}</th>
<th className="px-3 py-2">{t("CatVariation")}</th>
<th className="px-3 py-2">{t("Code")}</th>
<th className="px-3 py-2 text-right">{t("SkuOnHand")}</th>
<th className="px-3 py-2">{t("PageViewShipping")}</th>
<th className="px-3 py-2">{t("Status")}</th>
</tr>
</thead>
<tbody className="divide-y">
{rows.map((row, i) => {
const v = sku.variations[i];
const on = ticked.has(row.skuVariationId);
return (
<tr key={row.skuVariationId} className="align-top">
<td className="px-3 py-3">
<Checkbox
aria-label={t("PageSellCode", { code: row.code })}
checked={on}
disabled={saving || row.locked}
onCheckedChange={(c) => {
const next = new Set(ticked);
if (c === true) next.add(row.skuVariationId);
else next.delete(row.skuVariationId);
setTicked(sku, next);
}}
/>
</td>
<td className="px-3 py-3">{row.label}</td>
<td className="px-3 py-2">
<Input aria-label={t("SkuVariantNCode", { n: i + 1 })} readOnly value={row.code} className="opacity-70" />
</td>
<td className="px-3 py-3 text-right tabular-nums">{v.onHand}</td>
<td className="px-3 py-3 text-muted-foreground">
{row.weight == null ? "—" : `${t("SkuWeightValueKg", { weight: row.weight })} · ${t("PageDimensionsCm", { length: v.lengthCm ?? "—", width: v.widthCm ?? "—", height: v.heightCm ?? "—" })}`}
</td>
<td className="space-y-1 px-3 py-3">
{row.isNew && !on && <Badge variant="outline">{t("SkuNewNotSold")}</Badge>}
{row.locked && <Badge variant="neutral">{t("SetupHasOrdersCantRemove")}</Badge>}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
})}
</VariantsCard>
<PricesCard step={pricingStep}>
<PriceList
prices={prices}
onChange={commitPrices}
variations={item.variations.map((v) => ({ key: v.key, name: soldNames.get(v.key) ?? (v.variantName || v.key) }))}
options={options}
errors={errors}
saving={saving}
today={today}
item={item}
onItem={(next) => onChange({ item: next })}
/>
</PricesCard>
<SkuDrawer
open={drawerSku != null}
skuId={drawerSku}
onOpenChange={(open) => !open && setDrawerSku(null)}
onSaved={(view) => {
setDrawerSku(null);
onReload(view);
}}
/>
</div>
);
}
function OwnedVariants({ item, prices, savedPrices, sku, onChange, errors, saving, today, options, deferred, onLink, step, pricingStep }: SectionProps & LinkProps & { deferred: number[] }) {
const t = useT();
const [view, setView] = useState<View>("shipping");
const [uploadError, setUploadError] = useState<string | null>(null);
const [linking, setLinking] = useState(false);
const [linkError, setLinkError] = useState<string | null>(null);
// A new SKU takes the product's code and name; the variations are kept in step with the variants.
const synced = useMemo(() => (sku ? syncOwnedVariations(item, ownedSku(sku, item)) : null), [item, sku]);
const commitPrices = (rows: PriceDraft[]) => onChange({ prices: rows, sku: synced?.sku, item: synced?.item });
if (!sku || !synced) return null;
const base = synced.sku;
const variations = synced.item.variations;
const hasOptions = base.optionNames.length > 0;
// Every saved variant stays: the backend refuses to remove a SKU variant any sales item (this one too) still uses.
const locked = new Set(base.variants.flatMap((v) => (v.id != null ? [v.id] : [])));
const sold = new Set(
variations.flatMap((v) => (v.removable === false && v.components[0]?.skuVariationId != null ? [v.components[0].skuVariationId] : [])),
);
const incomplete = new Set(missingShipping(base));
const axisValues = base.optionNames.map((_, a) => parseOptionValues(base.optionValues[a] ?? ""));
const rowName = (v: SkuVariantDraft) => v.options.filter((o) => o.trim()).join(OPTION_SEPARATOR) || t("SkuVariantDefault");
function edit(next: SkuDraft) {
const s = syncOwnedVariations(item, next);
onChange({ sku: s.sku, item: s.item, prices: syncPrices(prices, savedPrices, item.variations, s.item.variations) });
}
function patchVariant(i: number, next: Partial<SkuVariantDraft>) {
edit({ ...base, variants: base.variants.map((v, j) => (j === i ? { ...v, ...next } : v)) });
}
function setList(list: string[], index: number, value: string) {
return list.map((x, i) => (i === index ? value : x));
}
async function uploadImage(i: number, e: ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0];
e.target.value = "";
if (!file) return;
setUploadError(null);
try {
// SAME-REQUEST: the URL is saved with the next Save and the file is used at once (autocommit upload).
const res = await uploadProductImage({ fileName: file.name, fileType: file.type, base: await fileToBase64(file) });
patchVariant(i, { image: res.url });
} catch (err) {
setUploadError(err instanceof Error ? err.message : "SkuUploadVariantImageFailed");
}
}
return (
<div className="space-y-4">
<VariantsCard step={step}>
{item.id == null && (
<div className="space-y-2">
<CodeMatchNotice code={item.code} onUse={(view) => onLink(view)} />
<Button type="button" variant="link" size="sm" className="h-auto p-0" disabled={saving} onClick={() => setLinking((on) => !on)}>
{t("PageLinkExistingSku")}
</Button>
{linking && (
<SkuPicker
disabled={saving}
onSelect={(row) =>
getSku(row.id)
.then((view) => {
setLinkError(null);
onLink(view);
})
.catch((err: unknown) => setLinkError(err instanceof Error ? err.message : "SkuLoadFailed"))
}
/>
)}
{linkError && <FieldError message={t(linkError)} />}
</div>
)}
<div className="flex items-center gap-2">
<Switch
id="has-options"
checked={hasOptions}
disabled={saving || (hasOptions && base.variants.length > 1)}
onCheckedChange={(on) => edit(setHasVariants(base, on))}
/>
<Label htmlFor="has-options">{t("PageHasOptions")}</Label>
</div>
<FieldError message={errors["salesItem.variations"]} />
<FieldError message={errors["sku.variations"]} />
{hasOptions && (
<div className="space-y-3 rounded-md border p-3">
{base.optionNames.map((name, a) => (
<div key={a} className="grid gap-3 md:grid-cols-[1fr_2fr_auto]">
<div className="space-y-1.5">
<Label htmlFor={`option-name-${a}`}>{t("SkuOptionN", { n: a + 1 })}<span aria-hidden="true" className="text-destructive"> *</span></Label>
<Input
id={`option-name-${a}`}
aria-label={t("SkuOptionNName", { n: a + 1 })}
placeholder={t(`SkuOptionNamePlaceholder${a + 1}`)}
disabled={saving}
value={name}
aria-invalid={!!errors[`sku.optionNames[${a}]`]}
onChange={(e) => edit(withOptionLabels({ ...base, optionNames: setList(base.optionNames, a, e.target.value) }))}
/>
<FieldError message={errors[`sku.optionNames[${a}]`]} />
</div>
<div className="space-y-1.5">
<Label htmlFor={`option-values-${a}`}>{t("SkuOptionValues")}<span aria-hidden="true" className="text-destructive"> *</span></Label>
<OptionChips
id={`option-values-${a}`}
label={t("SkuOptionNValues", { n: a + 1 })}
placeholder={t(`SkuOptionValuesPlaceholder${a + 1}`)}
values={axisValues[a]}
disabled={saving}
onChange={(values) => edit(setOptionValues(base, a, values, locked))}
/>
</div>
<div className="flex items-end pb-0.5">
<Button
type="button"
variant="ghost"
size="sm"
disabled={saving || base.optionNames.length === 1}
onClick={() => edit(removeOption(base, a))}
>
{t("SkuRemoveOptionN", { n: a + 1 })}
</Button>
</div>
</div>
))}
<Button type="button" variant="outline" size="sm" disabled={saving || base.optionNames.length >= MAX_OPTIONS} onClick={() => edit(addOption(base))}>
<Plus aria-hidden="true" className="size-4" />
{t("SkuAddOption")}
</Button>
</div>
)}
{/* Which column set the table shows, as a segmented choice like Status (feedback 2026-10-28). A dot marks
a set with a problem, so an error in the set not on show is never hidden (feedback 2026-10-26); it is
visual only, as the row's "Check …" badge already says it in words. */}
<Segmented
label={t("SkuListVariants")}
value={view}
onChange={setView}
options={VIEWS.map(({ view: v, label }) => {
const flagged = base.variants.some((_, i) => {
const keys = SET_ERRORS[v](`sku.variations[${i}]`);
return Object.keys(errors).some((k) => errors[k] && keys.some((key) => k === key || k.startsWith(`${key}[`)));
});
return { value: v, label: t(label), lead: () => (flagged ? <span aria-hidden="true" className="size-2 rounded-full bg-destructive" /> : null) };
})}
/>
<div className="relative overflow-x-auto rounded-lg border">
<table className="w-full text-sm">
<thead>
<tr className="border-b text-left text-xs font-medium text-muted-foreground">
<th className="px-3 py-2">{t("CatVariation")}</th>
{/* Every one of these is required to save (validateSku); the * says so before Save does. */}
<th className="px-3 py-2">{t("Code")}<span aria-hidden="true" className="text-destructive"> *</span></th>
{view === "shipping" && DIMENSIONS.map(({ key, label }) => <th key={key} className="px-3 py-2">{t(label)}<span aria-hidden="true" className="text-destructive"> *</span></th>)}
{view === "shipping" && <th className="px-3 py-2">{t("CatImage")}</th>}
{view === "barcodes" && <th className="px-3 py-2">{t("PageViewBarcodes")}</th>}
<th className="px-3 py-2">{t("Status")}</th>
</tr>
</thead>
<tbody className="divide-y">
{base.variants.map((v, i) => {
const path = `sku.variations[${i}]`;
const n = i + 1;
const name = rowName(v);
const removedValue = v.id != null && locked.has(v.id) && v.options.some((o, a) => o.trim() && !axisValues[a]?.some((x) => x.toLowerCase() === o.trim().toLowerCase()));
return (
<tr key={v.rowKey ?? i} className="align-top">
<td className="px-3 py-2 pt-4">{name}</td>
<td className="min-w-[20ch] px-3 py-2">
<Input
aria-label={t("SkuVariantNCode", { n })}
readOnly
disabled={saving}
placeholder={t("SkuVariantCodePlaceholder")}
value={v.code}
aria-invalid={!!errors[`${path}.code`]}
className="opacity-70"
/>
<FieldError message={errors[`${path}.code`]} />
<FieldError message={errors[`${path}.options`]} />
</td>
{view === "shipping" &&
DIMENSIONS.map(({ key: field, aria, step }) => (
<td key={field} className="px-3 py-2">
<Input
aria-label={t(aria, { n })}
type="number"
step={step}
min="0"
disabled={saving}
value={v[field]}
aria-invalid={!!errors[`${path}.${field}`]}
onChange={(e) => patchVariant(i, { [field]: e.target.value })}
/>
<FieldError message={errors[`${path}.${field}`]} />
</td>
))}
{view === "shipping" && (
<td className="px-3 py-2">
<div className="flex items-center gap-2">
{v.image ? (
// eslint-disable-next-line @next/next/no-img-element -- remote drive thumbnail
<img src={v.image} alt={t("SkuVariantN", { n })} className="size-9 rounded object-cover" />
) : null}
<Input
aria-label={t("SkuVariantNImage", { n })}
type="file"
accept="image/png,image/jpeg,image/webp"
disabled={saving}
onChange={(e) => uploadImage(i, e)}
/>
</div>
</td>
)}
{view === "barcodes" && (
<td className="min-w-72 space-y-2 px-3 py-2">
<QianyiSkuPicker
value={v.qySku}
title={v.qyTitle}
status={v.qyStatus}
skuVariationId={v.id}
label={t("SetupQianyiFor", { code: v.code || name })}
disabled={saving}
onChange={(qySku, option) =>
qySku && option
? edit(prefillFromQianyi(base, i, option))
: patchVariant(i, { qySku, qyTitle: option?.title ?? null, qyStatus: qySku ? "OK" : undefined, qyTouched: true })
}
/>
<BarcodeList
n={n}
barcodes={v.barcodes ?? []}
path={path}
errors={errors}
disabled={saving}
onChange={(barcodes) => patchVariant(i, { barcodes, barcodesTouched: true })}
/>
</td>
)}
<td className="space-y-1 px-3 py-2 pt-3">
{incomplete.has(i) && <Badge variant="warning">{t("PageSizeMissing")}</Badge>}
{VIEWS.filter(({ view: h }) => h !== view && SET_ERRORS[h](path).some((p) => Object.keys(errors).some((e) => e === p || e.startsWith(`${p}.`) || e.startsWith(`${p}[`)))).map(({ view: h, label }) => (
<Badge key={h} variant="destructive">{t("PageCheckView", { view: t(label) })}</Badge>
))}
{removedValue && <Badge variant="neutral">{t(sold.has(v.id as number) ? "SetupHasOrdersCantRemove" : "PageSavedCantRemove")}</Badge>}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
{uploadError && <FieldError message={t(uploadError)} />}
{deferred.length > 0 && incomplete.size > 0 && (
<p role="status" className="text-sm text-warning">
{t("PageVariantsNotSaved", { names: [...incomplete].map((i) => rowName(base.variants[i])).join(", ") })}
</p>
)}
</VariantsCard>
<PricesCard step={pricingStep}>
<PriceList
prices={prices}
onChange={commitPrices}
variations={base.variants.map((v, i) => ({ key: variations[i]?.key ?? "", name: rowName(v) }))}
options={options}
errors={errors}
saving={saving}
today={today}
item={item}
onItem={(next) => onChange({ item: next })}
/>
</PricesCard>
</div>
);
}