diff --git a/admin/src/main/java/com/shoplix/admin/modules/category/constants/CategoryPathConstants.java b/admin/src/main/java/com/shoplix/admin/modules/category/constants/CategoryPathConstants.java new file mode 100644 index 0000000..93f02c6 --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/modules/category/constants/CategoryPathConstants.java @@ -0,0 +1,12 @@ +package com.shoplix.admin.modules.category.constants; + +/** 分类层级路径校验常量。 */ +public final class CategoryPathConstants { + + /** 分类路径格式:每一级仅允许小写字母、数字和中划线,级别之间使用斜杠分隔。 */ + public static final String PATTERN = "^[a-z0-9]+(?:-[a-z0-9]+)*(?:/[a-z0-9]+(?:-[a-z0-9]+)*)*$"; + + /** 工具类不允许实例化。 */ + private CategoryPathConstants() { + } +} diff --git a/admin/src/main/java/com/shoplix/admin/modules/content/req/SaveContentCategoryAdminReq.java b/admin/src/main/java/com/shoplix/admin/modules/content/req/SaveContentCategoryAdminReq.java index 2df7659..3003666 100644 --- a/admin/src/main/java/com/shoplix/admin/modules/content/req/SaveContentCategoryAdminReq.java +++ b/admin/src/main/java/com/shoplix/admin/modules/content/req/SaveContentCategoryAdminReq.java @@ -1,6 +1,7 @@ package com.shoplix.admin.modules.content.req; import com.shoplix.modules.common.enums.PublishStatusEnum; +import com.shoplix.admin.modules.category.constants.CategoryPathConstants; import com.shoplix.modules.content.enums.ContentTypeEnum; import jakarta.validation.constraints.*; @@ -11,7 +12,7 @@ public record SaveContentCategoryAdminReq( /** 内容类型。 */ @NotNull ContentTypeEnum contentType, /** 父分类业务编号,顶级为空。 */ @Size(max = 16) String parentCategoryCode, /** 英文分类名称。 */ @NotBlank @Size(max = 100) String categoryName, - /** 英文路径标识。 */ @NotBlank @Pattern(regexp = "^[a-z0-9]+(?:-[a-z0-9]+)*$") @Size(max = 100) String slug, + /** 英文层级路径。 */ @NotBlank @Pattern(regexp = CategoryPathConstants.PATTERN) @Size(max = 100) String slug, /** 英文分类描述。 */ @Size(max = 500) String description, /** 封面媒体业务编号。 */ @Size(max = 16) String coverMediaCode, /** 排序值。 */ @NotNull Integer sortNo, diff --git a/admin/src/main/java/com/shoplix/admin/modules/product/req/SaveProductCategoryAdminReq.java b/admin/src/main/java/com/shoplix/admin/modules/product/req/SaveProductCategoryAdminReq.java index c0c2236..fa7cf5e 100644 --- a/admin/src/main/java/com/shoplix/admin/modules/product/req/SaveProductCategoryAdminReq.java +++ b/admin/src/main/java/com/shoplix/admin/modules/product/req/SaveProductCategoryAdminReq.java @@ -1,6 +1,7 @@ package com.shoplix.admin.modules.product.req; import com.shoplix.modules.common.enums.PublishStatusEnum; +import com.shoplix.admin.modules.category.constants.CategoryPathConstants; import jakarta.validation.constraints.*; /** 运营后台保存产品分类请求。 */ @@ -9,7 +10,7 @@ public record SaveProductCategoryAdminReq( /** 所属站点业务编号。 */ @NotBlank @Size(max = 16) String siteCode, /** 父分类业务编号,顶级为空。 */ @Size(max = 16) String parentCategoryCode, /** 英文分类名称。 */ @NotBlank @Size(max = 100) String categoryName, - /** 英文路径标识。 */ @NotBlank @Pattern(regexp = "^[a-z0-9]+(?:-[a-z0-9]+)*$") @Size(max = 100) String slug, + /** 英文层级路径。 */ @NotBlank @Pattern(regexp = CategoryPathConstants.PATTERN) @Size(max = 100) String slug, /** 英文分类描述。 */ @Size(max = 500) String description, /** 封面媒体业务编号。 */ @Size(max = 16) String coverMediaCode, /** 排序值。 */ @NotNull Integer sortNo, diff --git a/web-admin/src/CategoryManager.tsx b/web-admin/src/CategoryManager.tsx index 1b2e215..beb18f3 100644 --- a/web-admin/src/CategoryManager.tsx +++ b/web-admin/src/CategoryManager.tsx @@ -1,28 +1,448 @@ -import { ArrowLeft, ChevronDown, ChevronRight, Edit3, Plus, Save } from "lucide-react"; +import { + ArrowLeft, + ChevronDown, + ChevronRight, + Edit3, + Plus, + Save, +} from "lucide-react"; import { useEffect, useMemo, useState } from "react"; import { API } from "./api"; +import { statusLabel } from "./statusLabels"; const SITE = "SIT0000000000001"; type ContentType = "NEWS" | "CASE" | "HELP"; -type Category = { categoryCode: string; parentCategoryCode: string; categoryName: string; slug: string; description?: string; sortNo: number; status: string }; +type Category = { + categoryCode: string; + parentCategoryCode: string; + categoryName: string; + slug: string; + description?: string; + sortNo: number; + status: string; +}; type TreeCategory = Category & { depth: number; children: TreeCategory[] }; type Props = { contentType?: ContentType }; -type Seo = { title: string; description: string; keywords: string; h1: string; canonicalUrl: string; robots: string; status: string }; -async function post(path: string, body: unknown) { const response = await fetch(API + path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); if (!response.ok) throw new Error((await response.json()).message || "请求失败"); return response.json(); } +type Seo = { + title: string; + description: string; + keywords: string; + h1: string; + canonicalUrl: string; + robots: string; + status: string; +}; +async function post(path: string, body: unknown) { + const response = await fetch(API + path, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + if (!response.ok) + throw new Error((await response.json()).message || "请求失败"); + return response.json(); +} + +/** 规范分类层级路径,保留斜杠并清理每一级中的非法字符。 */ +function normalizeCategoryPath(value: string): string { + return value + .toLowerCase() + .replace(/[^a-z0-9/-]/g, "-") + .replace(/-{2,}/g, "-") + .replace(/\/{2,}/g, "/") + .replace(/^\/+/, ""); +} /** 产品、新闻、案例和帮助分类管理及分类 SEO 编辑页面。 */ export default function CategoryManager({ contentType }: Props) { - const isProduct = !contentType; const label = isProduct ? "产品" : ({ NEWS: "新闻", CASE: "案例", HELP: "帮助" } as const)[contentType]; const maxDepth = isProduct ? 3 : 2; const basePath = isProduct ? "/products/categories" : "/contents/categories"; const seoPageType = isProduct ? "PRODUCT_CATEGORY_DETAIL" : `${contentType}_CATEGORY_DETAIL`; - const [items, setItems] = useState([]); const [expanded, setExpanded] = useState>(new Set()); const [editing, setEditing] = useState(undefined); const [parentCode, setParentCode] = useState(""); const [error, setError] = useState(""); const [saving, setSaving] = useState(false); - const [form, setForm] = useState({ categoryName: "", slug: "", description: "", sortNo: 30, status: "DRAFT" }); const [seo, setSeo] = useState({ title: "", description: "", keywords: "", h1: "", canonicalUrl: "", robots: "index,follow", status: "DRAFT" }); - const load = async () => { try { setError(""); const data = await post(`${basePath}/list`, isProduct ? { siteCode: SITE } : { siteCode: SITE, contentType }); setItems(data.items || []); setExpanded(new Set((data.items || []).map((item: Category) => item.categoryCode))); } catch (e) { setError(e instanceof Error ? e.message : "分类加载失败"); } }; - useEffect(() => { void load(); }, [contentType]); - const tree = useMemo(() => { const map = new Map(); items.forEach((item) => { const parent = item.parentCategoryCode || ""; map.set(parent, [...(map.get(parent) || []), item]); }); const build = (parent: string, depth: number): TreeCategory[] => (map.get(parent) || []).sort((a, b) => a.sortNo - b.sortNo).map((item) => ({ ...item, depth, children: build(item.categoryCode, depth + 1) })); return build("", 1); }, [items]); - const rows = useMemo(() => { const result: TreeCategory[] = []; const append = (nodes: TreeCategory[]) => nodes.forEach((node) => { result.push(node); if (expanded.has(node.categoryCode)) append(node.children); }); append(tree); return result; }, [tree, expanded]); + const isProduct = !contentType; + const label = isProduct + ? "产品" + : ({ NEWS: "新闻", CASE: "案例", HELP: "帮助" } as const)[contentType]; + const maxDepth = isProduct ? 3 : 2; + const basePath = isProduct ? "/products/categories" : "/contents/categories"; + const seoPageType = isProduct + ? "PRODUCT_CATEGORY_DETAIL" + : `${contentType}_CATEGORY_DETAIL`; + const [items, setItems] = useState([]); + const [expanded, setExpanded] = useState>(new Set()); + const [editing, setEditing] = useState( + undefined, + ); + const [parentCode, setParentCode] = useState(""); + const [error, setError] = useState(""); + const [saving, setSaving] = useState(false); + const [form, setForm] = useState({ + categoryName: "", + slug: "", + description: "", + sortNo: 30, + status: "DRAFT", + }); + const [seo, setSeo] = useState({ + title: "", + description: "", + keywords: "", + h1: "", + canonicalUrl: "", + robots: "index,follow", + status: "DRAFT", + }); + const load = async () => { + try { + setError(""); + const data = await post( + `${basePath}/list`, + isProduct ? { siteCode: SITE } : { siteCode: SITE, contentType }, + ); + setItems(data.items || []); + setExpanded( + new Set((data.items || []).map((item: Category) => item.categoryCode)), + ); + } catch (e) { + setError(e instanceof Error ? e.message : "分类加载失败"); + } + }; + useEffect(() => { + void load(); + }, [contentType]); + const tree = useMemo(() => { + const map = new Map(); + items.forEach((item) => { + const parent = item.parentCategoryCode || ""; + map.set(parent, [...(map.get(parent) || []), item]); + }); + const build = (parent: string, depth: number): TreeCategory[] => + (map.get(parent) || []) + .sort((a, b) => a.sortNo - b.sortNo) + .map((item) => ({ + ...item, + depth, + children: build(item.categoryCode, depth + 1), + })); + return build("", 1); + }, [items]); + const rows = useMemo(() => { + const result: TreeCategory[] = []; + const append = (nodes: TreeCategory[]) => + nodes.forEach((node) => { + result.push(node); + if (expanded.has(node.categoryCode)) append(node.children); + }); + append(tree); + return result; + }, [tree, expanded]); /** 打开分类独立编辑页面。 */ - const openEditor = (item: Category | null, parent = "") => { setEditing(item); setParentCode(item?.parentCategoryCode || parent); setForm({ categoryName: item?.categoryName || "", slug: item?.slug || "", description: item?.description || "", sortNo: item?.sortNo || 30, status: item?.status || "DRAFT" }); setSeo({ title: item?.categoryName || "", description: item?.description || "", keywords: "", h1: item?.categoryName || "", canonicalUrl: item ? `/${isProduct ? "products" : contentType!.toLowerCase()}/${item.slug}` : "", robots: "index,follow", status: item?.status || "DRAFT" }); if (item) void post("/seo/detail", { siteCode: SITE, pageType: seoPageType, targetCode: item.categoryCode }).then((data) => setSeo({ title: data.title || item.categoryName, description: data.description || item.description || "", keywords: data.keywords || "", h1: data.h1 || item.categoryName, canonicalUrl: data.canonicalUrl || `/${isProduct ? "products" : contentType!.toLowerCase()}/${item.slug}`, robots: data.robots || "index,follow", status: data.status || item.status })).catch(() => undefined); }; + const openEditor = (item: Category | null, requestedParentCode = "") => { + setEditing(item); + setParentCode(item?.parentCategoryCode || requestedParentCode); + const parent = requestedParentCode + ? items.find((category) => category.categoryCode === requestedParentCode) + : undefined; + setForm({ + categoryName: item?.categoryName || "", + slug: item?.slug || (parent ? `${parent.slug}/` : ""), + description: item?.description || "", + sortNo: item?.sortNo || 30, + status: item?.status || "DRAFT", + }); + setSeo({ + title: item?.categoryName || "", + description: item?.description || "", + keywords: "", + h1: item?.categoryName || "", + canonicalUrl: item + ? `/${isProduct ? "products" : contentType!.toLowerCase()}/${item.slug}` + : "", + robots: "index,follow", + status: item?.status || "DRAFT", + }); + if (item) + void post("/seo/detail", { + siteCode: SITE, + pageType: seoPageType, + targetCode: item.categoryCode, + }) + .then((data) => + setSeo({ + title: data.title || item.categoryName, + description: data.description || item.description || "", + keywords: data.keywords || "", + h1: data.h1 || item.categoryName, + canonicalUrl: + data.canonicalUrl || + `/${isProduct ? "products" : contentType!.toLowerCase()}/${item.slug}`, + robots: data.robots || "index,follow", + status: data.status || item.status, + }), + ) + .catch(() => undefined); + }; /** 保存分类与已有分类 SEO。 */ - const save = async () => { try { setSaving(true); setError(""); await post(`${basePath}/save`, { categoryCode: editing?.categoryCode, siteCode: SITE, ...(isProduct ? {} : { contentType }), parentCategoryCode: parentCode, categoryName: form.categoryName, slug: form.slug, description: form.description, coverMediaCode: null, sortNo: form.sortNo, status: form.status }); if (editing?.categoryCode) await post("/seo/save", { siteCode: SITE, pageType: seoPageType, targetCode: editing.categoryCode, ...seo, ogTitle: seo.title, ogDescription: seo.description, structuredData: null, headings: [] }); setEditing(undefined); await load(); } catch (e) { setError(e instanceof Error ? e.message : "分类保存失败"); } finally { setSaving(false); } }; - if (editing !== undefined) return

{editing ? `编辑${label}分类` : `新增${label}分类`}

{parentCode ? "当前分类将创建在所选父分类下" : "创建顶级分类"}

{error &&
{error}
}

分类信息