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

224 lines
6.3 KiB
TypeScript

import type { FieldErrors } from "@/app/lib/catalogSetup";
import type { Translate } from "@/app/lib/i18n/t";
// Storefront collections in the admin portal (add-storefront-collections): wire types, the form
// draft, its request bodies and the client checks. The server re-validates everything.
export type CollectionType = "MANUAL" | "AUTOMATIC";
export type CollectionMatch = "ALL" | "ANY";
export type CollectionSort = "MANUAL" | "PRICE_ASC" | "PRICE_DESC" | "NEWEST" | "NAME";
export type RuleField = "BRAND" | "CATEGORY" | "TAG";
export interface CollectionRule {
field: RuleField;
/** A brand id, a category id, or a tag. */
value: string;
}
export interface CollectionProductRef {
id: number;
code: string;
name: string;
status?: string;
}
export interface CollectionListItem {
id: number;
slug: string;
title: string;
type: CollectionType;
status: "Y" | "N";
productCount: number;
updatedAt?: string | null;
}
export interface CollectionView {
id: number;
slug: string;
title: string;
description?: string | null;
imageUrl?: string | null;
type: CollectionType;
match: CollectionMatch;
sort: CollectionSort;
status: "Y" | "N";
metaDescription?: string | null;
updatedAt?: string | null;
rules: CollectionRule[];
products: CollectionProductRef[];
}
export interface CollectionSaveBody {
id?: number;
slug: string;
title: string;
description?: string;
imageUrl?: string;
type: CollectionType;
match: CollectionMatch;
sort: CollectionSort;
status: "Y" | "N";
metaDescription?: string;
rules: CollectionRule[];
productIds: number[];
}
export interface CollectionPreview {
count: number;
names: string[];
}
export interface CollectionDraft {
id?: number;
title: string;
slug: string;
/** Once the admin edits the slug, the title stops rewriting it. */
slugTouched: boolean;
description: string;
imageUrl: string;
type: CollectionType;
match: CollectionMatch;
sort: CollectionSort;
status: "Y" | "N";
metaDescription: string;
rules: CollectionRule[];
products: CollectionProductRef[];
}
export const SORT_LABELS: Record<CollectionSort, string> = {
MANUAL: "CollSortManual",
PRICE_ASC: "CollSortPriceAsc",
PRICE_DESC: "CollSortPriceDesc",
NEWEST: "CollSortNewest",
NAME: "CollSortName",
};
export const RULE_FIELD_LABELS: Record<RuleField, string> = {
BRAND: "Brand",
CATEGORY: "Category",
TAG: "CollRuleTag",
};
export const SLUG_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
const RESERVED_SLUGS = ["all"];
const MAX_SLUG = 80;
const MAX_TITLE = 120;
const MAX_META = 160;
const MAX_RULES = 10;
export function slugify(title: string): string {
return title
.normalize("NFKD")
.replace(/[̀-ͯ]/g, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, MAX_SLUG)
.replace(/-+$/, "");
}
export function emptyCollection(type: CollectionType): CollectionDraft {
return {
title: "",
slug: "",
slugTouched: false,
description: "",
imageUrl: "",
type,
match: "ALL",
sort: type === "MANUAL" ? "MANUAL" : "NEWEST",
status: "Y",
metaDescription: "",
rules: type === "AUTOMATIC" ? [{ field: "TAG", value: "" }] : [],
products: [],
};
}
export function collectionFromView(view: CollectionView): CollectionDraft {
return {
id: view.id,
title: view.title,
slug: view.slug,
slugTouched: true,
description: view.description ?? "",
imageUrl: view.imageUrl ?? "",
type: view.type,
match: view.match ?? "ALL",
sort: view.sort,
status: view.status,
metaDescription: view.metaDescription ?? "",
rules: view.rules ?? [],
products: view.products ?? [],
};
}
export function withTitle(d: CollectionDraft, title: string): CollectionDraft {
return { ...d, title, slug: d.slugTouched ? d.slug : slugify(title) };
}
export function withType(d: CollectionDraft, type: CollectionType): CollectionDraft {
if (type === "MANUAL") return { ...d, type, sort: "MANUAL" };
return { ...d, type, sort: d.sort === "MANUAL" ? "NEWEST" : d.sort };
}
export function moveProduct(products: CollectionProductRef[], index: number, delta: number): CollectionProductRef[] {
const target = index + delta;
if (target < 0 || target >= products.length) return products;
const next = [...products];
[next[index], next[target]] = [next[target], next[index]];
return next;
}
function trimmedOrUndefined(value: string): string | undefined {
const trimmed = value.trim();
return trimmed ? trimmed : undefined;
}
export function collectionBody(d: CollectionDraft): CollectionSaveBody {
const automatic = d.type === "AUTOMATIC";
return {
id: d.id,
slug: d.slug.trim(),
title: d.title.trim(),
description: trimmedOrUndefined(d.description),
imageUrl: trimmedOrUndefined(d.imageUrl),
type: d.type,
match: d.match,
sort: d.sort,
status: d.status,
metaDescription: trimmedOrUndefined(d.metaDescription),
rules: automatic ? d.rules.map((r) => ({ field: r.field, value: r.value.trim() })) : [],
productIds: automatic ? [] : d.products.map((p) => p.id),
};
}
/** The draft as the server would see it, minus rules that have no value yet. */
export function previewBody(d: CollectionDraft): CollectionSaveBody {
const body = collectionBody(d);
return { ...body, rules: body.rules.filter((r) => r.value !== "") };
}
export function validateCollection(d: CollectionDraft, t: Translate): FieldErrors {
const errors: FieldErrors = {};
const title = d.title.trim();
if (!title) errors.title = t("CollErrTitleRequired");
else if (title.length > MAX_TITLE) errors.title = t("CollErrTitleMax", { max: MAX_TITLE });
const slug = d.slug.trim();
if (!SLUG_PATTERN.test(slug) || slug.length > MAX_SLUG) {
errors.slug = t("CollErrSlugFormat", { max: MAX_SLUG });
} else if (RESERVED_SLUGS.includes(slug)) {
errors.slug = t("CollErrSlugReserved", { slug });
}
if (d.metaDescription.trim().length > MAX_META) {
errors.metaDescription = t("CollErrMetaMax", { max: MAX_META });
}
if (d.type === "AUTOMATIC") {
if (d.rules.length === 0) errors.rules = t("CollErrNoConditions");
else if (d.rules.length > MAX_RULES) errors.rules = t("CollErrMaxConditions", { max: MAX_RULES });
d.rules.forEach((rule, i) => {
if (!rule.value.trim()) errors[`rules[${i}].value`] = t("CollErrChooseValue");
});
}
return errors;
}