Files
co-lite/solvway-admin-portal/app/lib/catalogSetup.ts
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

937 lines
36 KiB
TypeScript

import type { Translate } from "@/app/lib/i18n/t";
import type { ImageRowState } from "@/app/components/products/panels/types";
import type { ProductGroupComponent, QianyiLinkStatus, QianyiSkuOption } from "@/app/lib/types";
import type { PriceMarket } from "@/app/lib/productPage";
// The catalogue setup page model (restructure-catalogue-setup): the inventory CatalogSetupResponse
// wire shapes (mobile-api passes them through untouched), the drafts the three sections edit, the
// request parts each Save sends, and client checks that use the backend's field paths so a server
// 409/422 lands on the same field as a client error.
export type Status = "Y" | "N";
interface QianyiLinkView {
qySku?: string | null;
qyTitle?: string | null;
qyBarcode?: string | null;
qyStatus?: QianyiLinkStatus | null;
qyLinkSource?: "MANUAL" | "AUTO" | null;
}
export interface BarcodeView {
id: number;
barcode: string;
batchNumber?: string | null;
expiryDate?: string | null;
status: Status;
source: "MANUAL" | "QIANYI";
}
export interface SkuVariantView extends QianyiLinkView {
id: number;
code: string;
variant: string;
variantName: string;
options?: string[];
weight: number | null;
lengthCm?: number | null;
widthCm?: number | null;
heightCm?: number | null;
image?: string | null;
usedBy: string[];
onHand: number;
barcodes?: BarcodeView[];
}
export interface SkuView {
id: number;
code: string;
name: string;
status: Status;
supplierId?: number | null;
optionNames?: string[];
variations: SkuVariantView[];
}
export interface ComponentView extends QianyiLinkView {
skuVariationId: number;
skuVariationCode: string;
skuId: number;
skuCode: string;
skuName: string;
variant: string;
variantName: string;
qty: number;
qtyFoc: number;
}
export interface PricingView {
id: number;
variationId: number;
currency: string;
priceType: string;
country?: string | null;
region?: string | null;
price: number;
status: Status;
effectiveFrom?: string | null;
effectiveTo?: string | null;
}
export interface SalesVariationView {
id: number;
variant: string;
variantName: string;
/** False when the variation has stock or order history (it cannot be removed). */
removable?: boolean;
components: ComponentView[];
pricing: PricingView[];
}
export type Fulfilment = "ANY" | "PICKUP_ONLY" | "DELIVERY_ONLY";
export interface SalesItemView {
id: number;
code: string;
name: string;
brand: string;
category: string;
status: Status;
productType: string;
groupPickCount?: number | null;
groupComponentProductIds: number[];
/** The same components with code and name; absent from an older backend. */
groupComponents?: { id: number; code?: string | null; name?: string | null }[];
images: { url: string; sortOrder: number; primary: boolean }[];
shortDesc?: string | null;
longDesc?: string | null;
yellowLabel: boolean;
allowOversell: boolean;
fulfilment?: Fulfilment;
compareAtPrice?: number | null;
effectiveDate?: string | null;
tags?: string[];
variations: SalesVariationView[];
}
export interface CatalogSetupResponse {
sku?: SkuView | null;
salesItem?: SalesItemView | null;
}
export interface SkuListItem {
id: number;
code: string;
name: string;
status: Status;
variantCount: number;
linkedCount?: number;
autoLinkedCount?: number;
}
export interface SkuListPage {
content: SkuListItem[];
totalElements: number;
}
export interface SkuVariationOption {
skuVariationId: number;
code: string;
skuId: number;
skuCode: string;
skuName: string;
variant: string;
variantName: string;
}
/** A QianYi link being edited. Only a touched link is sent, so an untouched one stays as stored. */
export interface QianyiDraft {
qySku?: string;
qyTitle?: string | null;
qyStatus?: QianyiLinkStatus;
qyTouched: boolean;
}
export interface BarcodeDraft {
id?: number;
barcode: string;
batchNumber: string;
expiryDate: string;
status: Status;
source: "MANUAL" | "QIANYI";
}
export interface SkuVariantDraft extends QianyiDraft {
/** Client-only id that ties an unsaved variant to its Sales Item variation; never sent. */
rowKey?: string;
id?: number;
code: string;
variant: string;
variantName: string;
/** One value per SKU option name (add-sku-option-axes); empty for the default variant. */
options: string[];
weight: string;
lengthCm: string;
widthCm: string;
heightCm: string;
image: string;
usedBy: string[];
/** From the loaded SKU; null for an unsaved variant. */
onHand: number | null;
/** The value each field was last filled with from QianYi (shown as a note; never saved). A field
* still holding that value is QianYi's, so a later pick may replace it. */
qyFilled?: QianyiFilled;
/** From the loaded SKU; null for an unsaved variant. */
qyLinkSource?: "MANUAL" | "AUTO" | null;
barcodes?: BarcodeDraft[];
barcodesTouched?: boolean;
}
export type QianyiFilled = Partial<Record<"code" | "weight" | "variant" | "lengthCm" | "widthCm" | "heightCm", string>>;
export interface SkuDraft {
id?: number;
code: string;
name: string;
status: Status;
supplierId: number | null;
/** Up to three option names; empty = the SKU has no variants (one default variant). */
optionNames: string[];
/** Per option, the comma-separated values the generator combines (editor-only, never saved). */
optionValues: string[];
variants: SkuVariantDraft[];
}
export interface ComponentDraft extends QianyiDraft {
/** Known once the variant is saved (picked from search or loaded); a variant from the unsaved SKU
* section has only its code. */
skuVariationId?: number;
skuVariationCode: string;
/** The SKU this variant belongs to, when known (loaded or picked). */
skuId?: number;
label: string;
qty: string;
qtyFoc: string;
}
export interface SalesVariationDraft {
id?: number;
/** savedVariationKey(id) for a saved variation, newVariationKey() for a new one. */
key: string;
variant: string;
variantName: string;
/** False when saved with stock or order history; undefined or true = may be removed. */
removable?: boolean;
components: ComponentDraft[];
}
export interface SalesItemDraft {
id?: number;
code: string;
name: string;
brand: string;
category: string;
status: Status;
isGroup: boolean;
groupPickCount: number;
groupComponents: ProductGroupComponent[];
images: ImageRowState[];
shortDesc: string;
longDesc: string;
yellowLabel: boolean;
allowOversell: boolean;
fulfilment: Fulfilment;
compareAtPrice: string;
tags: string[];
variations: SalesVariationDraft[];
}
export interface PriceDraft {
id?: number;
variationKey: string;
currency: string;
priceType: string;
country: string;
region: string;
price: string;
status: Status;
effectiveFrom: string;
effectiveTo: string;
/** The stored bounds as loaded, re-sent unchanged while the date picker still shows their day. */
loadedFrom?: string;
loadedTo?: string;
/** Client-only: set by Add a later price, so the row must start after today; never sent. */
later?: boolean;
}
/** Field path (as the backend reports it, e.g. "sku.variations[2].code") -> message. */
export type FieldErrors = Record<string, string>;
const DEFAULT = "DEFAULT";
let keySeq = 0;
export function newVariationKey(): string {
keySeq += 1;
return `new-${Date.now().toString(36)}-${keySeq}`;
}
export function savedVariationKey(id: number): string {
return `v${id}`;
}
export function isDefaultVariant(variant: string, variantName: string): boolean {
return (!variant.trim() && !variantName.trim()) || variant.trim() === DEFAULT;
}
/** A variant code is built from letters and numbers, so a value without one gives no code. */
export function hasLetterOrNumber(value: string): boolean {
return /[\p{L}\p{N}]/u.test(value);
}
export function suggestVariantCode(skuCode: string, variant: string, variantName: string): string {
const base = skuCode.trim();
if (isDefaultVariant(variant, variantName)) return base;
const tail = variantName.trim().toUpperCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "");
// A variant with options but no value yet gets no suggestion: never the bare SKU code, which is the
// default variant's code.
return tail ? `${base}-${tail}` : "";
}
export const OPTION_SEPARATOR = " / ";
export const MAX_OPTIONS = 3;
function optionKey(values: string[]): string {
return values.map((v) => v.trim().toLowerCase()).join("\u0000");
}
/** Recomputes each variant's composed label ("Colour / Size", "Red / L") from the option names and its values. */
export function withOptionLabels(sku: SkuDraft): SkuDraft {
const names = sku.optionNames.map((n) => n.trim());
const variant = names.join(OPTION_SEPARATOR);
return {
...sku,
variants: sku.variants.map((v) => {
const variantName = names.map((_, i) => (v.options[i] ?? "").trim()).join(OPTION_SEPARATOR);
return v.variant === variant && v.variantName === variantName ? v : { ...v, variant, variantName };
}),
};
}
/** The "This SKU has variants" switch: on adds one empty option; off only while one variant is left. */
export function setHasVariants(sku: SkuDraft, on: boolean): SkuDraft {
if (on === sku.optionNames.length > 0) return sku;
if (on) {
return withOptionLabels({ ...sku, optionNames: [""], optionValues: [""], variants: sku.variants.map((v) => ({ ...v, options: [""] })) });
}
if (sku.variants.length !== 1) return sku;
return withOptionLabels({ ...sku, optionNames: [], optionValues: [], variants: sku.variants.map((v) => ({ ...v, options: [] })) });
}
export function addOption(sku: SkuDraft): SkuDraft {
if (sku.optionNames.length === 0 || sku.optionNames.length >= MAX_OPTIONS) return sku;
return withOptionLabels({
...sku,
optionNames: [...sku.optionNames, ""],
optionValues: [...sku.optionValues, ""],
variants: sku.variants.map((v) => ({ ...v, options: [...v.options, ""] })),
});
}
/** Drops one option everywhere; the last option is removed only by switching variants off. */
export function removeOption(sku: SkuDraft, index: number): SkuDraft {
if (sku.optionNames.length <= 1) return sku;
const drop = <T,>(list: T[]) => list.filter((_, i) => i !== index);
return withOptionLabels({
...sku,
optionNames: drop(sku.optionNames),
optionValues: drop(sku.optionValues),
variants: sku.variants.map((v) => ({ ...v, options: drop(v.options) })),
});
}
/** Comma-separated values, trimmed, blanks and repeats (ignoring case) dropped. */
export function parseOptionValues(text: string): string[] {
const seen = new Set<string>();
const out: string[] = [];
for (const raw of text.split(",")) {
const value = raw.trim();
if (value && !seen.has(value.toLowerCase())) {
seen.add(value.toLowerCase());
out.push(value);
}
}
return out;
}
/**
* "Generate variants": every combination of the option values not yet present (ignoring case). A row with a
* blank value takes the first missing combination that matches the values it has, so a weight typed before
* turning variants on or adding an option is kept; the rest are appended. Never removes a row. New and filled
* unsaved rows get the suggested code.
*/
export function generateVariants(sku: SkuDraft): SkuDraft {
const lists = sku.optionNames.map((_, i) => parseOptionValues(sku.optionValues[i] ?? ""));
if (lists.length === 0 || lists.some((l) => l.length === 0)) return sku;
let combos: string[][] = [[]];
for (const list of lists) combos = combos.flatMap((c) => list.map((v) => [...c, v]));
const existing = new Set(sku.variants.map((v) => optionKey(v.options)));
const missing = combos.filter((c) => !existing.has(optionKey(c)));
const fits = (v: SkuVariantDraft, combo: string[]) =>
combo.every((value, i) => !(v.options[i] ?? "").trim() || value.toLowerCase() === v.options[i].trim().toLowerCase());
const filled = sku.variants.map((v) => {
if (v.options.every((o) => o.trim())) return v;
const index = missing.findIndex((combo) => fits(v, combo));
return index < 0 ? v : { ...v, options: missing.splice(index, 1)[0] };
});
const labelled = withOptionLabels({ ...sku, variants: [...filled, ...missing.map((options) => ({ ...emptySkuVariant(), options }))] });
// An unsaved row's code is still automatic while blank, the SKU code, or the suggestion for its old values.
const auto = (v: SkuVariantDraft, before?: SkuVariantDraft) =>
!v.code.trim() || v.code === sku.code || (before != null && v.code === suggestVariantCode(sku.code, before.variant, before.variantName));
return {
...labelled,
variants: labelled.variants.map((v, i) =>
v.id == null && sku.code.trim() && auto(v, sku.variants[i]) ? { ...v, code: suggestVariantCode(sku.code, v.variant, v.variantName) } : v,
),
};
}
/**
* Option value chips (simplify-product-setup): sets option `axis` to `values`, removes the rows whose value on
* that axis was taken away (ignoring case) unless their id is in `locked`, then adds the missing combinations.
* Never leaves the SKU without a row.
*/
export function setOptionValues(sku: SkuDraft, axis: number, values: string[], locked: ReadonlySet<number>): SkuDraft {
const optionValues = sku.optionValues.map((v, i) => (i === axis ? values.join(", ") : v));
const keep = new Set(values.map((v) => v.trim().toLowerCase()).filter(Boolean));
// No values left: the option is blank on every row that is not sold, and every row stays.
if (keep.size === 0) {
const blanked = sku.variants.map((v) =>
v.id != null && locked.has(v.id) ? v : { ...v, options: sku.optionNames.map((_, i) => (i === axis ? "" : (v.options[i] ?? ""))) },
);
return withOptionLabels({ ...sku, optionValues, variants: blanked });
}
const variants = sku.variants
.filter((v) => {
const value = (v.options[axis] ?? "").trim().toLowerCase();
return (v.id != null && locked.has(v.id)) || !value || keep.has(value);
})
.map((v) => ({ ...v, options: sku.optionNames.map((_, i) => v.options[i] ?? "") }));
if (variants.length === 0) variants.push({ ...emptySkuVariant(), options: sku.optionNames.map(() => "") });
return generateVariants(withOptionLabels({ ...sku, optionValues, variants }));
}
/**
* Links the variant at `index` to the picked QianYi SKU and fills its empty fields from it
* (prefill-variant-from-qianyi, add-sku-option-axes): the code while unsaved on a SKU with options (on a
* new SKU without options, the blank SKU code instead), the weight and dimensions, and the values of options named
* Colour/Color and Size. A field is filled only while it is empty or still holds what an earlier QianYi
* pick put there, so re-picking replaces a wrong pick but never what the admin typed. A SKU without
* options is never given options.
*/
export function prefillFromQianyi(sku: SkuDraft, index: number, option: QianyiSkuOption): SkuDraft {
let skuCode = sku.code;
const variants = sku.variants.map((v, i) => {
if (i !== index) return v;
const earlier = v.qyFilled ?? {};
const next: SkuVariantDraft = { ...v, qySku: option.sku, qyTitle: option.title ?? null, qyStatus: "OK", qyTouched: true };
const filled: QianyiFilled = {};
const codeIsFree =
!v.code.trim() || v.code === earlier.code || v.code === suggestVariantCode(sku.code, v.variant, v.variantName);
if (sku.optionNames.length === 0) {
// The default variant's code is the SKU code: a new SKU without a code takes the QianYi code.
if (sku.id == null && (!sku.code.trim() || sku.code === earlier.code)) {
skuCode = option.sku;
filled.code = option.sku;
}
} else if (v.id == null && codeIsFree) {
next.code = option.sku;
filled.code = option.sku;
}
if (!v.weight.trim() || v.weight === earlier.weight) {
next.weight = option.weightKg != null ? String(option.weightKg) : "";
if (option.weightKg != null) filled.weight = next.weight;
}
const dimFields = ["lengthCm" as const, "widthCm" as const, "heightCm" as const];
const dimValues = [option.lengthCm, option.widthCm, option.heightCm];
dimFields.forEach((key, i) => {
if (!v[key].trim() || v[key] === earlier[key]) {
const dimVal = dimValues[i] != null ? String(dimValues[i]) : "";
next[key] = dimVal;
if (dimValues[i] != null) filled[key] = dimVal;
}
});
if (sku.optionNames.length > 0) {
const earlierValues = (earlier.variant ?? "").split("\n");
let fromQianyi = false;
next.options = sku.optionNames.map((name, a) => {
const current = v.options[a] ?? "";
const key = name.trim().toLowerCase();
const raw = key === "colour" || key === "color" ? option.color : key === "size" ? option.size : undefined;
const qy = raw != null && !hasLetterOrNumber(raw) ? null : raw;
if (qy === undefined || (current.trim() && current !== earlierValues[a])) return current;
if (qy) fromQianyi = true;
return qy ?? "";
});
if (fromQianyi) filled.variant = next.options.join("\n");
}
next.qyFilled = filled;
return next;
});
return withOptionLabels({ ...sku, code: skuCode, variants });
}
export function variantLabel(variant: string, variantName: string, t: Translate): string {
return isDefaultVariant(variant, variantName) ? t("SkuVariantDefault") : variantName.trim();
}
export function emptySkuVariant(): SkuVariantDraft {
return { code: "", variant: "", variantName: "", options: [], weight: "", lengthCm: "", widthCm: "", heightCm: "", image: "", usedBy: [], onHand: null, qyTouched: false, barcodes: [], barcodesTouched: false };
}
export function emptySku(): SkuDraft {
return { code: "", name: "", status: "Y", supplierId: null, optionNames: [], optionValues: [], variants: [emptySkuVariant()] };
}
export function emptySalesItem(): SalesItemDraft {
return {
code: "",
name: "",
brand: "",
category: "",
// A new product is an Inactive draft until it is priced (redesign-product-setup-stepper).
status: "N",
isGroup: false,
groupPickCount: 1,
groupComponents: [],
images: [],
shortDesc: "",
longDesc: "",
yellowLabel: false,
allowOversell: false,
fulfilment: "ANY",
compareAtPrice: "",
tags: [],
variations: [],
};
}
export function emptyPrice(variationKey: string, market?: PriceMarket): PriceDraft {
return {
variationKey,
currency: market?.currency ?? "MYR",
priceType: "",
country: market?.id ?? "",
region: "",
price: "",
status: "Y",
effectiveFrom: "",
effectiveTo: "",
};
}
function blankDefault(value: string | null | undefined): string {
return value == null || value === DEFAULT ? "" : value;
}
function componentLabel(code: string, skuName: string, variant: string, variantName: string): string {
const name = isDefaultVariant(variant, variantName) ? skuName : `${skuName} · ${variantName.trim()}`;
return name ? `${code} — ${name}` : code;
}
export function skuFromView(view: SkuView): SkuDraft {
return {
id: view.id,
code: view.code,
name: view.name ?? "",
status: view.status,
supplierId: view.supplierId ?? null,
optionNames: view.optionNames ?? [],
optionValues: (view.optionNames ?? []).map((_, i) =>
parseOptionValues(view.variations.map((v) => v.options?.[i] ?? "").join(",")).join(", "),
),
variants: view.variations.map((v) => ({
id: v.id,
code: v.code ?? "",
variant: blankDefault(v.variant),
variantName: blankDefault(v.variantName),
options: v.options ?? [],
weight: v.weight == null ? "" : String(v.weight),
lengthCm: v.lengthCm == null ? "" : String(v.lengthCm),
widthCm: v.widthCm == null ? "" : String(v.widthCm),
heightCm: v.heightCm == null ? "" : String(v.heightCm),
image: v.image ?? "",
usedBy: v.usedBy ?? [],
onHand: v.onHand ?? null,
qySku: v.qySku ?? undefined,
qyTitle: v.qyTitle ?? null,
qyStatus: v.qyStatus ?? undefined,
qyLinkSource: v.qyLinkSource ?? null,
qyTouched: false,
barcodes: (v.barcodes ?? []).map(b => ({ id: b.id, barcode: b.barcode, batchNumber: b.batchNumber ?? "", expiryDate: b.expiryDate ?? "", status: b.status, source: b.source })),
barcodesTouched: false,
})),
};
}
export function salesItemFromView(view: SalesItemView): { salesItem: SalesItemDraft; prices: PriceDraft[] } {
const prices: PriceDraft[] = [];
const skuIds = new Set<number>();
const variations = view.variations.map((v) => {
const key = savedVariationKey(v.id);
for (const p of v.pricing) {
prices.push({
id: p.id,
variationKey: key,
currency: p.currency,
priceType: p.priceType,
country: p.country ?? "",
region: p.region ?? "",
price: String(p.price),
status: p.status,
effectiveFrom: (p.effectiveFrom ?? "").slice(0, 10),
effectiveTo: (p.effectiveTo ?? "").slice(0, 10),
loadedFrom: p.effectiveFrom ?? undefined,
loadedTo: p.effectiveTo ?? undefined,
});
}
for (const c of v.components) {
skuIds.add(c.skuId);
}
return {
id: v.id,
key,
variant: blankDefault(v.variant),
variantName: blankDefault(v.variantName),
removable: v.removable ?? true,
components: v.components.map((c) => ({
skuVariationId: c.skuVariationId,
skuVariationCode: c.skuVariationCode,
skuId: c.skuId,
label: componentLabel(c.skuVariationCode, c.skuName, c.variant, c.variantName),
qty: String(c.qty),
qtyFoc: String(c.qtyFoc),
qySku: c.qySku ?? undefined,
qyTitle: c.qyTitle ?? null,
qyStatus: c.qyStatus ?? undefined,
qyTouched: false,
})),
};
});
return {
salesItem: {
id: view.id,
code: view.code,
name: view.name ?? "",
brand: view.brand ?? "",
category: view.category ?? "",
status: view.status,
isGroup: view.productType === "GROUP",
groupPickCount: view.groupPickCount ?? 1,
groupComponents: view.groupComponentProductIds.map((id) => {
const named = view.groupComponents?.find((c) => c.id === id);
return named?.name ? { componentProductId: String(id), label: named.code ? `${named.name} (${named.code})` : named.name } : { componentProductId: String(id) };
}),
images: view.images.map((i) => ({ url: i.url, sortOrder: i.sortOrder })),
shortDesc: view.shortDesc ?? "",
longDesc: view.longDesc ?? "",
yellowLabel: view.yellowLabel,
allowOversell: view.allowOversell,
fulfilment: view.fulfilment ?? "ANY",
compareAtPrice: view.compareAtPrice == null ? "" : String(view.compareAtPrice),
tags: view.tags ?? [],
variations,
},
prices,
};
}
function num(value: string | undefined | null): number | null {
const t = value == null ? "" : value.trim();
return t === "" ? null : Number(t);
}
function qianyi(d: QianyiDraft): { qySku?: string } {
return d.qyTouched ? { qySku: d.qySku ?? "" } : {};
}
function omitUndefined<T extends object>(value: T): T {
return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as T;
}
/** A touched list goes out whole (an emptied one as [] removes them); untouched stays as stored. */
function barcodesPart(v: SkuVariantDraft) {
if (!v.barcodesTouched) return {};
return {
barcodes: (v.barcodes ?? []).map((b) =>
omitUndefined({ id: b.id, barcode: b.barcode.trim(), batchNumber: b.batchNumber.trim() || null, expiryDate: b.expiryDate || null, status: b.status }),
),
};
}
export function skuPart(d: SkuDraft) {
return omitUndefined({
id: d.id,
code: d.id ? undefined : d.code.trim(),
name: d.name.trim(),
status: d.status,
supplierId: d.supplierId ?? null,
optionNames: d.optionNames.map((n) => n.trim()),
variations: d.variants.map((v) =>
omitUndefined({
id: v.id,
code: v.id ? undefined : v.code.trim() || undefined,
variant: v.variant.trim(),
variantName: v.variantName.trim(),
options: d.optionNames.length > 0 ? v.options.map((o) => o.trim()) : [],
weight: num(v.weight),
lengthCm: num(v.lengthCm),
widthCm: num(v.widthCm),
heightCm: num(v.heightCm),
image: v.image || undefined,
...qianyi(v),
...barcodesPart(v),
}),
),
});
}
export function salesItemPart(d: SalesItemDraft) {
return omitUndefined({
id: d.id,
code: d.id ? undefined : d.code.trim(),
name: d.name.trim(),
brand: d.brand,
category: d.category,
status: d.status,
productType: d.isGroup ? "GROUP" : "STANDARD",
groupPickCount: d.isGroup ? d.groupPickCount : undefined,
groupComponentProductIds: d.isGroup ? d.groupComponents.map((c) => Number(c.componentProductId)) : [],
images: d.images.map((i) => ({ url: i.url, sortOrder: i.sortOrder })),
shortDesc: d.shortDesc.trim() || undefined,
longDesc: d.longDesc || undefined,
yellowLabel: d.yellowLabel,
allowOversell: d.allowOversell,
fulfilment: d.isGroup ? "ANY" : d.fulfilment,
compareAtPrice: num(d.compareAtPrice),
tags: d.tags,
variations: d.isGroup
? []
: d.variations.map((v) =>
omitUndefined({
id: v.id,
key: v.key,
variant: v.variant.trim(),
variantName: v.variantName.trim(),
components: v.components.map((c) => ({
skuVariationCode: c.skuVariationCode.trim(),
qty: Number(c.qty || 0),
qtyFoc: Number(c.qtyFoc || 0),
...qianyi(c),
})),
}),
),
});
}
export function pricingPart(prices: PriceDraft[], salesItem: SalesItemDraft) {
const idByKey = new Map<string, number>();
for (const v of salesItem.variations) {
if (v.id != null) idByKey.set(v.key, v.id);
}
// The pricing part is the item's complete price list: a row of a variation this save removes would be
// rejected by the backend, and goes with its variation anyway (redesign-product-setup-stepper).
const kept = new Set(salesItem.variations.map((v) => v.key));
return omitUndefined({
salesItemId: salesItem.id,
rows: prices.filter((p) => kept.has(p.variationKey)).map((p) => {
const variationId = idByKey.get(p.variationKey);
return omitUndefined({
id: p.id,
variationId,
variationRef: variationId == null ? p.variationKey : undefined,
currency: p.currency,
priceType: p.priceType,
country: p.country || undefined,
region: p.region || undefined,
price: num(p.price),
status: p.status,
// A picked date covers the whole day: from its first second to its last. A loaded bound
// whose day is unchanged keeps its stored time (legacy rows carry times like 08:03).
effectiveFrom: wireBound(p.effectiveFrom, p.loadedFrom, "T00:00:00"),
effectiveTo: wireBound(p.effectiveTo, p.loadedTo, "T23:59:59"),
});
}),
});
}
function wireBound(picked: string, loaded: string | undefined, time: string): string | undefined {
if (!picked) return undefined;
if (loaded && loaded.slice(0, 10) === picked) return loaded;
return picked.length === 10 ? `${picked}${time}` : picked;
}
export function validateSku(d: SkuDraft, t: Translate): FieldErrors {
const errors: FieldErrors = {};
if (!d.id && !d.code.trim()) errors["sku.code"] = t("SkuErrCodeRequired");
if (!d.name.trim()) errors["sku.name"] = t("SkuErrNameRequired");
if (d.variants.length === 0) errors["sku.variations"] = t("SkuErrAddVariant");
const names = new Set<string>();
d.optionNames.forEach((name, i) => {
const key = name.trim().toLowerCase();
if (!key) errors[`sku.optionNames[${i}]`] = t("SkuErrOptionNameRequired");
else if (names.has(key)) errors[`sku.optionNames[${i}]`] = t("SkuErrOptionNameRepeated");
names.add(key);
});
const combinations = new Set<string>();
const codes = new Set<string>();
d.variants.forEach((v, i) => {
const path = `sku.variations[${i}]`;
const isDefault = d.optionNames.length === 0;
if (!isDefault) {
const values = d.optionNames.map((_, a) => v.options[a] ?? "");
if (values.some((o) => !o.trim())) errors[`${path}.options`] = t("SkuErrOptionValueRequired");
else if (combinations.has(optionKey(values))) errors[`${path}.options`] = t("SkuErrCombinationRepeated");
combinations.add(optionKey(values));
}
const code = v.code.trim() || (isDefault ? d.code.trim() : "");
if (!code) errors[`${path}.code`] = t("SkuErrVariantCodeRequired");
else if (codes.has(code)) errors[`${path}.code`] = t("SkuErrVariantCodeRepeated");
else codes.add(code);
if (!v.weight.trim() || !(Number(v.weight) > 0)) errors[`${path}.weight`] = t("SkuErrWeightPositive");
if (!v.lengthCm.trim() || !(Number(v.lengthCm) > 0)) errors[`${path}.lengthCm`] = t("SkuErrLengthPositive");
if (!v.widthCm.trim() || !(Number(v.widthCm) > 0)) errors[`${path}.widthCm`] = t("SkuErrWidthPositive");
if (!v.heightCm.trim() || !(Number(v.heightCm) > 0)) errors[`${path}.heightCm`] = t("SkuErrHeightPositive");
});
// Barcodes are unique across the whole catalogue; the server checks other SKUs, this checks the draft.
const barcodes = new Set<string>();
d.variants.forEach((v, i) => {
(v.barcodes ?? []).forEach((b, j) => {
const path = `sku.variations[${i}].barcodes[${j}]`;
const text = b.barcode.trim();
if (!/^[\x21-\x7E]{4,64}$/.test(text)) errors[`${path}.barcode`] = t("SkuErrBarcodeFormat");
else if (barcodes.has(text.toLowerCase())) errors[`${path}.barcode`] = t("SkuErrBarcodeRepeated", { barcode: text });
barcodes.add(text.toLowerCase()); // the database's unique key ignores case
if (b.batchNumber.trim().length > 64) errors[`${path}.batchNumber`] = t("SkuErrBatchTooLong");
});
});
return errors;
}
/** `product.product_desc` is a MySQL TEXT column: 65,535 bytes. */
export const DESCRIPTION_MAX_BYTES = 65535;
export function validateSalesItem(d: SalesItemDraft, t: Translate): FieldErrors {
const errors: FieldErrors = {};
if (!d.id && !d.code.trim()) errors["salesItem.code"] = t("SalesItemErrCodeRequired");
if (!d.name.trim()) errors["salesItem.name"] = t("SalesItemErrNameRequired");
if (!d.brand) errors["salesItem.brand"] = t("SalesItemErrBrandRequired");
if (!d.category) errors["salesItem.category"] = t("SalesItemErrCategoryRequired");
// Only activation needs an image (SalesItemSetupService); an Inactive draft saves without one.
if (d.status === "Y" && d.images.length === 0) errors["salesItem.images"] = t("SalesItemErrImageRequired");
if (new TextEncoder().encode(d.longDesc).length > DESCRIPTION_MAX_BYTES) {
errors["salesItem.longDesc"] = t("SalesItemErrDescTooLong");
}
if (d.isGroup) {
// An Inactive Group draft may have no components yet; an Active one may not.
if (d.groupComponents.length === 0) {
if (d.status === "Y") errors["salesItem.groupComponentProductIds"] = t("SalesItemErrGroupComponentRequired");
}
else if (d.groupPickCount < 1 || d.groupPickCount > d.groupComponents.length) {
errors["salesItem.groupPickCount"] = t("SalesItemErrPickCountRange");
}
return errors;
}
// An Inactive draft (product setup step 1) may have no variations yet (redesign-product-setup-stepper).
if (d.variations.length === 0 && d.status === "Y") errors["salesItem.variations"] = t("SalesItemErrVariationRequired");
const names = new Set<string>();
d.variations.forEach((v, i) => {
const path = `salesItem.variations[${i}]`;
const isDefault = isDefaultVariant(v.variant, v.variantName);
if (!isDefault && (!v.variant.trim() || !v.variantName.trim())) {
errors[`${path}.variantName`] = t("BundleVariantAndNameRequired");
}
const key = `${v.variant.trim()}\n${v.variantName.trim()}`;
if (names.has(key)) errors[path] = t("SalesItemErrVariationRepeated", { name: variantLabel(v.variant, v.variantName, t) });
names.add(key);
if (v.components.length === 0) errors[`${path}.components`] = t("BundleErrComponentRequired");
const seen = new Set<string>();
v.components.forEach((c, j) => {
const cPath = `${path}.components[${j}]`;
const code = c.skuVariationCode.trim();
const qty = Number(c.qty || 0);
const foc = Number(c.qtyFoc || 0);
if (!code) errors[`${cPath}.skuVariationCode`] = t("BundleErrPickSkuVariant");
else if (seen.has(code)) errors[`${cPath}.skuVariationCode`] = t("BundleErrSkuVariantTwice");
seen.add(code);
if (!Number.isInteger(qty) || !Number.isInteger(foc)) errors[cPath] = t("BundleErrQtyWhole");
else if (qty < 0 || foc < 0) errors[cPath] = t("BundleErrQtyNegative");
else if (qty + foc <= 0) errors[cPath] = t("BundleErrQtyPositive");
});
});
return errors;
}
function toMillis(value: string, ifBlank: number): number {
const t = value.trim();
if (!t) return ifBlank;
return new Date(t.length === 10 ? `${t}T00:00:00` : t).getTime();
}
/**
* Indexes of active rows that overlap an earlier active row with the same key (backend rule). `country` is the
* default country: a stored empty country is the same market, so it is keyed as that country.
*/
export function findPriceOverlaps(prices: PriceDraft[], country = ""): number[] {
const out: number[] = [];
const key = (p: PriceDraft) =>
[p.variationKey, p.priceType.trim(), p.currency.trim(), p.country.trim() || country, p.region.trim()].join("|");
prices.forEach((later, i) => {
if (later.status !== "Y") return;
const laterFrom = toMillis(later.effectiveFrom, -Infinity);
const laterTo = toMillis(later.effectiveTo, Infinity);
const clash = prices.slice(0, i).some((earlier) => {
if (earlier.status !== "Y" || key(earlier) !== key(later)) return false;
const earlierFrom = toMillis(earlier.effectiveFrom, -Infinity);
const earlierTo = toMillis(earlier.effectiveTo, Infinity);
return !(earlierTo < laterFrom || laterTo < earlierFrom);
});
if (clash) out.push(i);
});
return out;
}
export function validatePrices(prices: PriceDraft[], salesItem: SalesItemDraft, t: Translate, today: string, country = ""): FieldErrors {
const errors: FieldErrors = {};
const variations = new Map(salesItem.variations.map((v) => [v.key, v]));
prices.forEach((p, i) => {
const path = `pricing.rows[${i}]`;
const variation = variations.get(p.variationKey);
if (!variation) errors[`${path}.variationId`] = t("PricingErrPickVariation");
if (!p.priceType) errors[`${path}.priceType`] = t("PricingErrPriceTypeRequired");
if (!p.price.trim() || Number(p.price) < 0) errors[`${path}.price`] = t("PricingErrPriceMin");
if (p.id == null && !p.effectiveFrom.trim()) errors[`${path}.effectiveFrom`] = t("PricingErrFromRequired");
if (p.effectiveFrom && p.effectiveTo && toMillis(p.effectiveTo, 0) < toMillis(p.effectiveFrom, 0)) {
errors[`${path}.effectiveTo`] = t("PricingErrEndBeforeStart");
}
const from = p.effectiveFrom.trim();
if (p.later && from && from.slice(0, 10) <= today) errors[`${path}.effectiveFrom`] = t("PricingErrFromAfterToday");
});
if (prices.some((p) => p.id == null && !p.country)) errors["pricing"] = t("PricingErrNoMalaysia");
for (const i of findPriceOverlaps(prices, country)) {
errors[`pricing.rows[${i}]`] = t("PricingErrDuplicateOverlap");
}
return errors;
}
const FIELD_PATH = /^([A-Za-z]\w*(?:\[\d+\])?(?:\.[A-Za-z]\w*(?:\[\d+\])?)*): ([\s\S]+)$/;
/** Splits a backend reason "sku.variations[2].code: message" into its field path and message. */
export function parseServerError(message: string): { path: string | null; message: string } {
const match = FIELD_PATH.exec(message.trim());
return match ? { path: match[1], message: match[2] } : { path: null, message };
}
export function errorsUnder(errors: FieldErrors, prefix: string): FieldErrors {
return Object.fromEntries(Object.entries(errors).filter(([path]) => path === prefix || path.startsWith(`${prefix}.`)));
}