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

482 lines
23 KiB
TypeScript

import {
newVariationKey,
variantLabel,
isDefaultVariant,
validateSku,
validateSalesItem,
validatePrices,
skuPart,
suggestVariantCode,
salesItemPart,
pricingPart,
type FieldErrors,
type PriceDraft,
type SalesItemDraft,
type SalesItemView,
type SkuDraft,
type SkuView,
type SalesVariationDraft,
} from "./catalogSetup";
import type { Translate } from "@/app/lib/i18n/t";
import type { AdminLocationNode, QianyiLinkStatus } from "./types";
import type { CatalogSetupRequestBody } from "@/app/lib/services/adminCatalogSetup";
// Product page save model: view → draft sync, validation, and request-body assembly.
export type ProductType = "product" | "bundle" | "group";
/** Infer the product type from a SalesItemView's shape. */
export function typeOfView(view: SalesItemView): ProductType {
if (view.productType === "GROUP") return "group";
// Bundle when any variation has >1 component, or a component with qty≠1 or qtyFoc≠0,
// or the same skuVariationId appears in two variations (shared across SKUs).
const seenIds = new Set<number>();
for (const v of view.variations) {
if (v.components.length !== 1) return "bundle";
for (const c of v.components) {
if (c.qty !== 1 || c.qtyFoc !== 0) return "bundle";
if (seenIds.has(c.skuVariationId)) return "bundle";
seenIds.add(c.skuVariationId);
}
}
return "product";
}
/** Whether the sales item references a SKU that differs from its own code or is shared. */
export function isLinked(item: SalesItemDraft, skus: SkuView[]): boolean {
if (skus.length > 1) return true;
if (skus.length === 0) return false;
const sku = skus[0];
const itemCode = item.code.toLowerCase();
if (sku.code.toLowerCase() !== itemCode) return true;
// Check every variant's usedBy for entries that differ from the item's code.
for (const v of sku.variations) {
for (const ref of v.usedBy) {
if (ref.toLowerCase() !== itemCode) return true;
}
}
return false;
}
/**
* One variation per variant of the product's own SKU, in SKU order, each with one component at qty 1.
* A saved variant keeps its variation by SKU variant id, else (unsaved, or saved but not sold yet) by its
* client-only rowKey, assigned here on first sync, so a renamed option value keeps its row and its typed prices.
*/
export function syncOwnedVariations(item: SalesItemDraft, sku: SkuDraft): { item: SalesItemDraft; sku: SkuDraft } {
const variants = sku.variants.map((v) => (v.rowKey ? v : { ...v, rowKey: newVariationKey() }));
const variations = variants.map((variant): SalesVariationDraft => {
const existing =
item.variations.find((v) => variant.id != null && v.components[0]?.skuVariationId === variant.id) ??
item.variations.find((v) => v.key === variant.rowKey);
// The same code rule as validateSku: a default variant's code is the SKU code.
const code = variant.code.trim() || (isDefaultVariant(variant.variant, variant.variantName) ? sku.code.trim() : "");
return {
id: existing?.id,
key: existing?.key ?? (variant.rowKey as string),
variant: variant.variant,
variantName: variant.variantName,
removable: existing?.removable ?? true,
components: [
{
skuVariationId: variant.id,
skuVariationCode: code,
skuId: sku.id,
label: "",
qty: "1",
qtyFoc: "0",
qySku: variant.qySku,
qyTitle: variant.qyTitle ?? null,
qyStatus: variant.qyStatus,
qyTouched: existing?.components[0]?.qyTouched ?? false,
},
],
};
});
return { item: { ...item, variations }, sku: { ...sku, variants } };
}
/**
* The SKU a product owns. A new SKU takes the product's code and name; a saved SKU keeps its code and takes the
* name. Either way every unsaved variant (`id == null`) gets the code suggested from the SKU's code, because a
* variant's code is generated and read-only (a QianYi pick must not replace it). Saved variants are untouched.
*/
export function ownedSku(sku: SkuDraft, item: SalesItemDraft): SkuDraft {
// A blank product code keeps the SKU code, so the codes suggested from it still move once a code is typed.
const code = sku.id ? sku.code : item.code;
if (!code.trim()) return { ...sku, name: item.name };
const variants = sku.variants.map((v) => (v.id == null ? { ...v, code: suggestVariantCode(code, v.variant, v.variantName) } : v));
return { ...sku, code: sku.id ? sku.code : item.code, name: item.name, variants };
}
/** The error for a compare-at price that does not exceed the highest active MYR price of any type (a Malaysian figure). */
export function compareAtError(item: SalesItemDraft, prices: PriceDraft[], today: string, t: Translate): FieldErrors {
if (!item.compareAtPrice.trim()) return {};
const highest = Math.max(0, ...prices.filter((p) => p.status === "Y" && p.currency === "MYR" && !ended(p, today)).map((p) => Number(p.price) || 0));
return Number(item.compareAtPrice) > highest ? {} : { "salesItem.compareAtPrice": t("PageCompareAtTooLow") };
}
/** Indexes of variants missing a dimension (weight/length/width/height > 0). */
export function missingShipping(sku: SkuDraft): number[] {
const fields = ["weight", "lengthCm", "widthCm", "heightCm"] as const;
return sku.variants.flatMap((v, i) => (fields.some((f) => !(Number(v[f]) > 0)) ? [i] : []));
}
/**
* Swaps the SKU a product sells: every variation is new (no kept id), so the backend's removal guard refuses
* the swap when an old variation has stock or orders. `replacing` is the SKU id swapped out of a product that
* sells several: only its variations are replaced, the new ones taking their place. Without it every variation
* is replaced. The caller drops the old price rows (syncPrices).
*/
export function replaceSku(item: SalesItemDraft, view: SkuView, replacing?: number): SalesItemDraft {
const variations = view.variations.map((v): SalesVariationDraft => ({
key: newVariationKey(),
variant: v.variant === "DEFAULT" ? "" : v.variant,
variantName: v.variantName === "DEFAULT" ? "" : v.variantName,
removable: true,
components: [
{
skuVariationId: v.id,
skuVariationCode: v.code,
skuId: view.id,
label: "",
qty: "1",
qtyFoc: "0",
qySku: v.qySku ?? undefined,
qyTitle: v.qyTitle ?? null,
qyStatus: v.qyStatus ?? undefined,
qyTouched: false,
},
],
}));
if (replacing == null) return { ...item, variations };
const isOld = (v: SalesVariationDraft) => v.components[0]?.skuId === replacing;
const at = item.variations.findIndex(isOld);
const rest = item.variations.filter((v) => !isOld(v));
rest.splice(at < 0 ? rest.length : at, 0, ...variations);
return { ...item, variations: rest };
}
/**
* The price rows after the variations change from `before` to `after`: rows of a variation that went are dropped, and a
* saved variation that came back (ticked again) gets its saved rows. A variation that stayed is left alone, so saved rows
* the admin deleted from it never return.
*/
export function syncPrices(prices: PriceDraft[], savedPrices: PriceDraft[], before: SalesVariationDraft[], after: SalesVariationDraft[]): PriceDraft[] {
const keys = new Set(after.map((v) => v.key));
const returned = new Set([...keys].filter((k) => !before.some((v) => v.key === k)));
return [...prices.filter((p) => keys.has(p.variationKey)), ...savedPrices.filter((p) => returned.has(p.variationKey))];
}
export interface SaveOutcome {
body: CatalogSetupRequestBody | null;
errors: FieldErrors;
/** Indexes of owned-SKU variants left unsaved because they lack shipping details. */
deferred: number[];
}
/** The Product Setup request for one page Save (design.md "Save shapes"), or null with the errors to show. */
export function buildSave(args: {
type: ProductType;
item: SalesItemDraft;
saved: SalesItemDraft;
prices: PriceDraft[];
sku: SkuDraft | null;
linked: boolean;
today: string;
t: Translate;
/** The default (Malaysia) country id: a stored empty country is checked for overlaps as this country. */
country?: string;
/** The sellable markets; each one's current row is taken over by its later prices. Defaults to Malaysia only. */
markets?: PriceMarket[];
}): SaveOutcome {
const { type, item, saved, sku, linked, today, t, country } = args;
const defaultMarket: PriceMarket = args.markets?.find((m) => m.isDefault) ?? { id: country ?? "", code: "MY", currency: "MYR", isDefault: true };
const prices = (args.markets ?? [defaultMarket]).reduce((rows, m) => withTakeOver(rows, today, m), args.prices);
const ownSku = type === "product" && !linked && sku != null ? { ...ownedSku(sku, item), status: "Y" as const } : null;
const synced = ownSku ? syncOwnedVariations(item, ownSku) : null;
const d = synced?.item ?? item;
const deferred = synced ? missingShipping(synced.sku) : [];
// An Inactive draft with unfinished variants saves its details only; its saved variations stay as they are.
if (synced && deferred.length > 0 && d.status !== "Y") {
const draft = { ...d, variations: saved.variations };
const draftErrors = { ...validateSalesItem(draft, t), ...compareAtError(draft, prices, today, t) };
if (Object.keys(draftErrors).length > 0) return { body: null, errors: draftErrors, deferred };
return { body: { salesItem: salesItemPart(draft) }, errors: {}, deferred };
}
const errors: FieldErrors = validateSalesItem(d, t);
if (type === "bundle" && d.variations.every((v) => v.components.length === 0)) {
errors["salesItem.variations"] = t("BundleErrComponentRequired");
}
// A bundle option holds at least 2 units in total (qty + free qty); an empty one already has its own error.
if (type === "bundle") {
d.variations.forEach((v, i) => {
const key = `salesItem.variations[${i}].components`;
const units = v.components.reduce((n, c) => n + (Number(c.qty) || 0) + (Number(c.qtyFoc) || 0), 0);
if (v.components.length > 0 && units < 2 && !errors[key]) errors[key] = t("BundleErrMinTwoUnits");
});
}
// Several variations are named options: each needs a type and name (a saved DEFAULT one may stay unnamed).
if (type === "bundle" && d.variations.length > 1) {
d.variations.forEach((v, i) => {
if (v.id != null && isDefaultVariant(v.variant, v.variantName)) return;
if (!v.variant.trim() || !v.variantName.trim()) errors[`salesItem.variations[${i}].variantName`] = t("BundleVariantAndNameRequired");
});
}
if (synced) {
Object.assign(errors, validateSku(synced.sku, t));
// The SKU code and name, and each component's variant code, mirror the product's own fields, which report them;
// so does an empty generated variant code, when its cause (the product code or an option value) is itself reported.
for (const key of Object.keys(errors)) {
if (/^(sku\.(code|name)|salesItem\.variations\[\d+\]\.components\[\d+\]\.skuVariationCode)$/.test(key)) delete errors[key];
}
synced.sku.variants.forEach((v, i) => {
const empty = !(v.code.trim() || (synced.sku.optionNames.length === 0 ? synced.sku.code.trim() : ""));
if (empty && (errors["salesItem.code"] || errors[`sku.variations[${i}].options`])) delete errors[`sku.variations[${i}].code`];
});
// A sold variation's row cannot be removed: the backend would refuse the whole save.
const kept = new Set(d.variations.map((v) => v.key));
if (saved.variations.some((v) => v.removable === false && !kept.has(v.key))) {
errors["salesItem.variations"] = t("SetupHasOrdersCantRemove");
}
}
if (type !== "group") {
Object.assign(errors, validatePrices(prices, d, t, today, country), compareAtError(d, prices, today, t));
if (d.status === "Y") {
for (const key of unpricedVariationKeys(prices, d, today, defaultMarket)) errors[`pricing.quick.${key}`] = t("SetupSellingPriceRequired");
}
}
if (Object.keys(errors).length > 0) return { body: null, errors, deferred };
return {
body: {
...(synced ? { sku: skuPart(synced.sku) } : {}),
salesItem: salesItemPart(d),
...(type !== "group" ? { pricing: pricingPart(prices, d) } : {}),
},
errors: {},
deferred,
};
}
// The SKU variant checklist and the slot rows (one per variation and active price type) of the Prices list.
export type QuickType = string;
/** The price types that get a slot row in the Prices list: the active ones, MEMBER first, then load order. */
export function quickTypes(priceTypes: { code?: string; status: string }[]): string[] {
const codes = priceTypes.filter((p) => p.status === "Y" && p.code).map((p) => p.code as string);
return [...new Set(codes.includes("MEMBER") ? ["MEMBER", ...codes] : codes)];
}
export function todayKL(now: Date = new Date()): string {
return new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Kuala_Lumpur" }).format(now);
}
/** `day` (YYYY-MM-DD) moved by `days` calendar days. */
export function shiftDay(day: string, days: number): string {
const d = new Date(`${day}T00:00:00Z`);
d.setUTCDate(d.getUTCDate() + days);
return d.toISOString().slice(0, 10);
}
const dayBefore = (day: string) => shiftDay(day, -1);
export const ended = (p: PriceDraft, today: string) => p.effectiveTo !== "" && p.effectiveTo.slice(0, 10) < today;
/** An Active slot row of this variation, type and market with a price that has not ended (current or upcoming). */
export function hasOpenSlotRow(prices: PriceDraft[], variationKey: string, type: QuickType, today: string, market: PriceMarket): boolean {
return prices.some((p) => p.variationKey === variationKey && inSlot(p, type, market) && !ended(p, today) && p.price.trim() !== "");
}
/**
* The sales item as Save sends it: a product that owns its SKU has its variations synced from the SKU's
* variants first (a new product's draft has none until then). Read readiness from this, not the raw draft.
*/
export function asSaved(type: ProductType, item: SalesItemDraft, sku: SkuDraft | null, linked: boolean): SalesItemDraft {
return type === "product" && !linked && sku != null ? syncOwnedVariations(item, ownedSku(sku, item)).item : item;
}
export function unpricedVariationKeys(prices: PriceDraft[], d: SalesItemDraft, today: string, market: PriceMarket = DEFAULT_MARKET): string[] {
// Activation needs a selling (MEMBER) price that has not ended; a later start counts, another type does not.
return d.variations.filter((v) => !hasOpenSlotRow(prices, v.key, "MEMBER", today, market)).map((v) => v.key);
}
export interface ChecklistRow {
skuVariationId: number;
code: string;
label: string;
weight: number | null;
qySku?: string | null;
qyTitle?: string | null;
qyStatus?: QianyiLinkStatus | null;
qyLinkSource?: "MANUAL" | "AUTO" | null;
ticked: boolean;
locked: boolean;
isNew: boolean;
variationKey?: string;
}
function soldBy(d: SalesItemDraft, skuVariationId: number): SalesVariationDraft | undefined {
return d.variations.find((v) => v.components.length === 1 && v.components[0].skuVariationId === skuVariationId);
}
export function checklistRows(sku: SkuView, d: SalesItemDraft, t: Translate): ChecklistRow[] {
const fresh = d.variations.length === 0;
return sku.variations.map((sv) => {
const sold = soldBy(d, sv.id);
// A QianYi pick made on the page shows until it is saved; otherwise the SKU variant's stored link.
const touched = sold?.components[0]?.qyTouched ? sold.components[0] : undefined;
return {
skuVariationId: sv.id,
code: sv.code,
label: variantLabel(sv.variant, sv.variantName, t),
weight: sv.weight,
qySku: touched ? touched.qySku ?? null : sv.qySku,
qyTitle: touched ? touched.qyTitle ?? null : sv.qyTitle,
qyStatus: touched ? touched.qyStatus ?? null : sv.qyStatus,
qyLinkSource: touched ? (touched.qySku ? "MANUAL" : null) : sv.qyLinkSource,
ticked: fresh || sold != null,
locked: sold != null && sold.removable === false,
isNew: !fresh && sold == null,
variationKey: sold?.key,
};
});
}
/** Links (or, with no qySku, unlinks) one SKU variant on every component that ships it; sent with the step's save. */
export function setComponentQianyi(d: SalesItemDraft, skuVariationId: number, qySku: string | undefined, title?: string | null): SalesItemDraft {
return {
...d,
variations: d.variations.map((v) => ({
...v,
components: v.components.map((c) =>
c.skuVariationId === skuVariationId
? { ...c, qySku, qyTitle: title ?? null, qyStatus: qySku ? ("OK" as const) : undefined, qyTouched: true }
: c,
),
})),
};
}
/** `saved`: the item as last saved, so re-ticking an unticked variant restores its saved variation and prices. */
export function variationsFromChecklist(
sku: SkuView,
d: SalesItemDraft,
ticked: ReadonlySet<number>,
saved?: SalesItemDraft,
): SalesVariationDraft[] {
return sku.variations
.filter((sv) => ticked.has(sv.id))
.map((sv) => soldBy(d, sv.id) ?? (saved && soldBy(saved, sv.id)) ?? {
key: newVariationKey(),
variant: sv.variant === "DEFAULT" ? "" : sv.variant,
variantName: sv.variantName === "DEFAULT" ? "" : sv.variantName,
removable: true,
components: [{
skuVariationId: sv.id, skuVariationCode: sv.code, skuId: sku.id,
label: `${sv.code} — ${sku.name}`, qty: "1", qtyFoc: "0", qyTouched: false,
}],
});
}
/** A sellable country the editor prices in: its node id, ISO code, currency and whether it is the default (Malaysia). */
export interface PriceMarket {
id: string;
code: string;
currency: string;
isDefault: boolean;
}
const DEFAULT_MARKET: PriceMarket = { id: "", code: "MY", currency: "MYR", isDefault: true };
/**
* The markets the editor can price in: each sellable country that has an active country node, Malaysia first.
* With no sellable list (or none that matches a node) it is Malaysia only, so the editor reads as it always did.
*/
export function sellableMarkets(locations: AdminLocationNode[], countries: { code: string; currency: string }[]): PriceMarket[] {
const markets = countries.flatMap((c) => {
const node = locations.find((l) => l.type === "C" && l.status === "Y" && l.code.toUpperCase() === c.code.toUpperCase());
const code = c.code.toUpperCase();
return node ? [{ id: String(node.id), code, currency: c.currency, isDefault: code === "MY" }] : [];
});
return markets.length > 0 ? markets : [{ ...DEFAULT_MARKET, id: defaultCountryId(locations) }];
}
// A row is in a market's slot when type, currency and country match (a blank country is the default market's), with no region.
function inSlot(p: PriceDraft, type: QuickType, market: PriceMarket): boolean {
return p.priceType === type && p.currency === market.currency && !p.region && p.status === "Y"
&& (p.country ? p.country === market.id : market.isDefault);
}
// A row added by Add a later price is never a slot, even if its From is edited to today (it then fails validation).
function isQuick(p: PriceDraft, type: QuickType, market: PriceMarket): boolean {
return !p.later && inSlot(p, type, market);
}
/** The id of the active Malaysia country node, "" when Locations has none. */
export function defaultCountryId(locations: AdminLocationNode[]): string {
const my = locations.find((l) => l.type === "C" && l.status === "Y" && l.code.toUpperCase() === "MY");
return my ? String(my.id) : "";
}
/**
* The slot row of this variation and type: the current row (in effect today, whatever its end date). When several
* qualify it prefers an empty-country row, then array order; the list shows the others as rows.
*/
export function quickPrice(prices: PriceDraft[], variationKey: string, type: QuickType, today: string, market: PriceMarket): PriceDraft | undefined {
const current = prices.filter(
(p) => p.variationKey === variationKey && isQuick(p, type, market) && p.effectiveFrom.slice(0, 10) <= today && !ended(p, today),
);
return current.find((p) => !p.country) ?? current[0];
}
/** The earliest From after today of an Active row in the same slot (variation, type, market, no region). */
function nextLaterFrom(prices: PriceDraft[], variationKey: string, type: QuickType, today: string, market: PriceMarket): string | undefined {
return prices
.filter((q) => q.variationKey === variationKey && inSlot(q, type, market) && q.effectiveFrom.slice(0, 10) > today)
.map((q) => q.effectiveFrom.slice(0, 10))
.sort()[0];
}
export function setQuickPrice(prices: PriceDraft[], variationKey: string, type: QuickType, price: string, today: string, market: PriceMarket): PriceDraft[] {
const value = price.trim();
if (value === "") return prices;
const current = quickPrice(prices, variationKey, type, today, market);
if (current && Number(current.price) === Number(value)) return prices;
if (current && (current.id == null || current.effectiveFrom.slice(0, 10) === today)) {
return prices.map((p) => (p === current ? { ...p, price: value } : p));
}
// The new price runs to the end of the period it replaces, and never into a scheduled later price.
const nextStart = nextLaterFrom(prices, variationKey, type, today, market);
const effectiveTo = current?.effectiveTo ? current.effectiveTo.slice(0, 10) : nextStart ? dayBefore(nextStart) : "";
const added: PriceDraft = { variationKey, currency: market.currency, priceType: type, country: market.id, region: "", price: value,
status: "Y", effectiveFrom: today, effectiveTo };
const closed = current ? prices.map((p) => (p === current ? { ...p, effectiveTo: dayBefore(today) } : p)) : prices;
return [...closed, added];
}
/** Appends one Active row in the market's country and currency with the given dates; a blank price adds nothing. */
export function addPrice(prices: PriceDraft[], variationKey: string, type: QuickType, price: string, from: string, to: string, market: PriceMarket): PriceDraft[] {
const value = price.trim();
if (value === "") return prices;
return [...prices, { variationKey, currency: market.currency, priceType: type, country: market.id, region: "", price: value, status: "Y", effectiveFrom: from, effectiveTo: to }];
}
/**
* Derives the take-over of a later price: each current row (the slot `quickPrice` picks for a variation and type)
* ends the day before the earliest Active row of that variation and type starting after today. It only shortens an
* end, never lengthens it. Pure: the draft keeps the end the admin set; the list shows and the save sends this.
*/
export function withTakeOver(prices: PriceDraft[], today: string, market: PriceMarket): PriceDraft[] {
const ends = new Map<PriceDraft, string>();
for (const p of prices) {
const current = quickPrice(prices, p.variationKey, p.priceType, today, market);
if (!current || ends.has(current)) continue;
const from = nextLaterFrom(prices, current.variationKey, current.priceType, today, market);
if (from && (current.effectiveTo === "" || current.effectiveTo.slice(0, 10) >= from)) ends.set(current, dayBefore(from));
}
return ends.size === 0 ? prices : prices.map((p) => (ends.has(p) ? { ...p, effectiveTo: ends.get(p)! } : p));
}