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

272 lines
12 KiB
TypeScript

"use client";
import { useState } from "react";
import { Plus, X } from "lucide-react";
import { Button } from "@/app/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Switch } from "@/app/components/ui/switch";
import { FieldError } from "@/app/components/catalog-setup/FieldError";
import { SkuDrawer } from "@/app/components/catalog-setup/SkuDrawer";
import { SkuVariationPicker } from "@/app/components/catalog-setup/SkuVariationPicker";
import { QianyiSkuPicker } from "@/app/components/products/QianyiSkuPicker";
import { StepTitle } from "@/app/components/product-page/SetupStep";
import {
isDefaultVariant,
newVariationKey,
variantLabel,
type ComponentDraft,
type SalesVariationDraft,
type SkuVariantView,
type SkuView,
type SkuVariationOption,
} from "@/app/lib/catalogSetup";
import { getSku } from "@/app/lib/services/adminCatalogSetup";
import { setComponentQianyi, syncPrices } from "@/app/lib/productPage";
import type { Translate } from "@/app/lib/i18n/t";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { PriceList } from "./PriceList";
import { PricesCard } from "./VariantsSection";
import type { SectionProps } from "./ProductSetupPage";
// The Bundle page: What's in the box (SKU variant rows with qty and free qty), Price, and an optional split into
// named options, each with its own contents and price (simplify-product-setup). One page Save sends it all.
/** A component from a picked SKU variant, showing that variant's stored QianYi link (untouched, so not re-sent). */
export function componentFromOption(option: SkuVariationOption, t: Translate, stored?: SkuVariantView): ComponentDraft {
const variant = isDefaultVariant(option.variant, option.variantName) ? "" : ` · ${variantLabel(option.variant, option.variantName, t)}`;
return {
skuVariationId: option.skuVariationId,
skuVariationCode: option.code,
skuId: option.skuId,
label: `${option.code} — ${option.skuName}${variant}`,
qty: "1",
qtyFoc: "0",
qySku: stored?.qySku ?? undefined,
qyTitle: stored?.qyTitle ?? null,
qyStatus: stored?.qyStatus ?? undefined,
qyTouched: false,
};
}
export function emptyVariation(): SalesVariationDraft {
return { key: newVariationKey(), variant: "", variantName: "", removable: true, components: [] };
}
export function BundleSection({ item, prices, savedPrices, onChange, errors, saving, today, options, step, pricingStep }: SectionProps) {
const t = useT();
const variations = item.variations;
// On when the bundle already has several variations or a named one.
const [optionsOn, setOptionsOn] = useState(variations.length > 1 || variations.some((v) => !isDefaultVariant(v.variant, v.variantName)));
const [newSkuFor, setNewSkuFor] = useState<number | null>(null);
const [note, setNote] = useState<string | null>(null);
const commitPrices = (rows: typeof prices) => onChange({ prices: rows });
// The switch goes off only when one unsold-name variation is left to fold back into the plain bundle.
const canTurnOff = variations.length <= 1 && (variations[0]?.id == null || isDefaultVariant(variations[0].variant, variations[0].variantName));
function setVariations(next: SalesVariationDraft[]) {
onChange({ item: { ...item, variations: next }, prices: syncPrices(prices, savedPrices, variations, next) });
}
// Off folds the one option left back into the plain bundle: no name, and a fresh one if none is left.
function toggleOptions(on: boolean) {
if (!on) setVariations([{ ...(variations[0] ?? emptyVariation()), variant: "", variantName: "" }]);
setOptionsOn(on);
}
function patchVariation(index: number, next: Partial<SalesVariationDraft>) {
setVariations(variations.map((v, i) => (i === index ? { ...v, ...next } : v)));
}
function patchComponent(vi: number, ci: number, next: Partial<ComponentDraft>) {
patchVariation(vi, { components: variations[vi].components.map((c, j) => (j === ci ? { ...c, ...next } : c)) });
}
function addCreatedSku(view: SkuView) {
// A one-variant SKU goes straight in; a SKU with several variants is then picked variant by variant.
if (newSkuFor == null) return;
if (view.variations.length !== 1) {
setNote(t("PageStockItemCreatedPick", { code: view.code }));
return;
}
setNote(null);
const v = view.variations[0];
const option: SkuVariationOption = {
skuVariationId: v.id, code: v.code, skuId: view.id, skuCode: view.code, skuName: view.name, variant: v.variant, variantName: v.variantName,
};
patchVariation(newSkuFor, { components: [...variations[newSkuFor].components, componentFromOption(option, t, v)] });
}
async function addComponent(index: number, option: SkuVariationOption) {
// The variant search carries no QianYi link, so read it from the variant's SKU; without it, add unlinked.
// ponytail: an edit made during this one fetch is overwritten; queue the add if that ever bites.
let stored: SkuVariantView | undefined;
try {
stored = (await getSku(option.skuId))?.variations.find((sv) => sv.id === option.skuVariationId);
} catch {
stored = undefined;
}
patchVariation(index, { components: [...variations[index].components, componentFromOption(option, t, stored)] });
}
function contents(i: number) {
const variation = variations[i];
const path = `salesItem.variations[${i}]`;
return (
<div className="space-y-3">
<FieldError message={errors[path]} />
{/* With options off the card already shows errors["salesItem.variations"]: do not repeat the same text. */}
{(optionsOn || errors[`${path}.components`] !== errors["salesItem.variations"]) && <FieldError message={errors[`${path}.components`]} />}
{variation.components.map((c, j) => {
const cPath = `${path}.components[${j}]`;
const m = j + 1;
return (
<div key={`${c.skuVariationCode}-${j}`} data-testid="sales-component" className="grid items-end gap-2 sm:grid-cols-[2fr_80px_2fr_auto]">
<div className="min-w-0 space-y-1">
<span className="text-xs text-muted-foreground">{t("BundleSkuVariant")}</span>
<p className="truncate text-sm">{c.label || c.skuVariationCode}</p>
<FieldError message={errors[`${cPath}.skuVariationCode`]} />
</div>
<div className="space-y-1">
<Label htmlFor={`bundle-qty-${i}-${j}`}>{t("CatQty")}</Label>
<Input
id={`bundle-qty-${i}-${j}`}
aria-label={t("PageItemMQty", { m })}
type="number"
min="0"
disabled={saving}
value={c.qty}
onChange={(e) => patchComponent(i, j, { qty: e.target.value })}
/>
</div>
<div className="min-w-0">
{c.skuVariationId != null && (
<QianyiSkuPicker
label={t("SetupQianyiFor", { code: c.skuVariationCode })}
value={c.qySku}
title={c.qyTitle}
status={c.qyStatus}
skuVariationId={c.skuVariationId}
disabled={saving}
onChange={(qySku, option) => setVariations(setComponentQianyi({ ...item, variations }, c.skuVariationId as number, qySku, option?.title).variations)}
/>
)}
</div>
<Button
type="button"
variant="ghost"
size="sm"
aria-label={t("PageRemoveItemM", { m })}
onClick={() => patchVariation(i, { components: variation.components.filter((_, k) => k !== j) })}
disabled={saving}
>
<X aria-hidden="true" className="size-4" />
</Button>
<div className="sm:col-span-5">
<FieldError message={errors[cPath]} />
</div>
</div>
);
})}
<div className="flex flex-wrap items-center gap-2">
<div className="min-w-64 flex-1">
<SkuVariationPicker label={t("PageAddItem")} placeholder={t("BundleAddSkuVariantPlaceholder")} onSelect={(option) => addComponent(i, option)} disabled={saving} />
</div>
<Button type="button" variant="outline" size="sm" onClick={() => setNewSkuFor(i)} disabled={saving}>
<Plus aria-hidden="true" className="size-4" />
{t("PageNewStockItem")}
</Button>
</div>
</div>
);
}
const bundleName = item.name.trim() || item.code;
return (
<div className="space-y-4" data-testid="bundle-section">
<Card>
<CardHeader>
<CardTitle><StepTitle step={step}>{t("PageWhatsInBox")}</StepTitle></CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<FieldError message={errors["salesItem.variations"]} />
{note && <p role="status" className="text-sm text-muted-foreground">{note}</p>}
{!optionsOn && variations[0] && contents(0)}
<div className="flex items-center gap-2">
<Switch
id="bundle-options"
checked={optionsOn}
disabled={saving || (optionsOn && !canTurnOff)}
onCheckedChange={toggleOptions}
/>
<Label htmlFor="bundle-options">{t("PageBundleOptions")}</Label>
</div>
{optionsOn && (
<>
<ul className="space-y-3">
{variations.map((variation, i) => {
const n = i + 1;
return (
<li key={variation.key} role="group" aria-label={t("PageOptionN", { n })} data-testid="sales-variation" className="space-y-3 rounded-lg border p-3">
<div className="grid gap-2 sm:grid-cols-[1fr_1fr_auto]">
<Input
aria-label={t("PageOptionNType", { n })}
placeholder={t("BundleVariantPlaceholder")}
disabled={saving}
value={variation.variant}
onChange={(e) => patchVariation(i, { variant: e.target.value })}
/>
<Input
aria-label={t("PageOptionNName", { n })}
placeholder={t("BundleNamePlaceholder")}
disabled={saving}
value={variation.variantName}
onChange={(e) => patchVariation(i, { variantName: e.target.value })}
/>
<Button
type="button"
variant="ghost"
size="sm"
aria-label={t("PageRemoveOptionN", { n })}
onClick={() => setVariations(variations.filter((_, j) => j !== i))}
disabled={saving || variation.removable === false}
title={variation.removable === false ? t("SetupHasOrdersCantRemove") : undefined}
>
<X aria-hidden="true" className="size-4" />
</Button>
</div>
<FieldError message={errors[`salesItem.variations[${i}].variantName`]} />
{contents(i)}
</li>
);
})}
</ul>
<Button type="button" variant="outline" size="sm" onClick={() => setVariations([...variations, emptyVariation()])} disabled={saving}>
<Plus aria-hidden="true" className="size-4" />
{t("PageAddOption")}
</Button>
</>
)}
</CardContent>
</Card>
<PricesCard step={pricingStep}>
<PriceList
prices={prices}
onChange={commitPrices}
variations={variations.map((v, i) => ({ key: v.key, name: optionsOn ? v.variantName.trim() || t("PageOptionN", { n: i + 1 }) : bundleName }))}
options={options}
errors={errors}
saving={saving}
today={today}
item={item}
onItem={(next) => onChange({ item: next })}
/>
</PricesCard>
<SkuDrawer open={newSkuFor != null} skuId={null} onOpenChange={(open) => !open && setNewSkuFor(null)} onSaved={addCreatedSku} />
</div>
);
}