refactor: 拆分品牌业务类型与页面方案
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Taro builds (acheng-campus-food) (push) Has been cancelled
CI / Taro builds (atelier-solopreneur) (push) Has been cancelled
CI / Taro builds (linjing-editorial) (push) Has been cancelled
CI / Browser regression (push) Has been cancelled

This commit is contained in:
que01 committed 2026-10-20 17:04:30 +08:00
1 parent f02e2cafbb
commit 0d9f4a7d6f
86 files changed
+4111 -1543

No files matched your search

+15 -13
View File
@@ -270,19 +270,21 @@
以下为各页面的视觉结构约定,业务逻辑不变。
| 页面 | 结构要点 |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| 登录 | 居中 400px 卡片,标识 + 说明 + 表单 + 通栏主按钮;错误态展示在字段下方 |
| 首次改密 | 同登录卡片形态,说明文案 + 三个密码字段 + 「保存新密码」 |
| 品牌概览 | 品牌卡 + 三张指标卡(等宽一行)+ 两栏(发布准备度 / 品牌内容检查) |
| 配置与发布 | 三 Tab(内容发布 / 小程序发布 / 小程序配置);内容发布含「选择表达方式」(行业模板 + 视觉模板 + 版本升级/回滚)+ 发布状态卡 + 草稿卡 + 历史版本表 |
| 小程序页面 | 左右两栏:左 380px 编辑面板,右预览画布;预览内选中区域虚线高亮 + 区域名气泡 |
| 信任内容 | 列表行(类型图标或配图 + 标题 + 发布状态标签 + 类型/展示位置说明 + 两行摘要 + 行内操作),按模板类型顺序排列,不用表格 |
| 业务提供项 | 表格(名称 / 价格 / 状态开关 / 排序 / 操作)+ 新增弹窗 |
| 咨询记录 | 顶部三指标 + 左 380px 列表 + 右详情的主从布局 |
| 咨询表单与字段 | 咨询表单表(名称 / 版本 / 字段数 / 状态 / 操作)+ 新增与编辑弹窗(含选项编辑);高级自定义字段表 + 新增弹窗 |
| 能力插件 | 插件卡片列表(图标 + 名称 + 说明 + 开关),停用态降低对比度 |
| 团队成员 | 表格(成员 / 角色 / 状态 / 最近登录 / 操作)+ 邀请弹窗 |
| 页面 | 结构要点 |
| -------------- | ---------------------------------------------------------------------------------------------------------------------- |
| 登录 | 居中 400px 卡片,标识 + 说明 + 表单 + 通栏主按钮;错误态展示在字段下方 |
| 首次改密 | 同登录卡片形态,说明文案 + 三个密码字段 + 「保存新密码」 |
| 品牌概览 | 品牌卡 + 三张指标卡(等宽一行)+ 两栏(发布准备度 / 品牌内容检查) |
| 内容与发布 | 内容发布 / 小程序发布 / 小程序配置三个分区;内容发布含发布状态卡、草稿卡和历史版本表,不承载业务类型或页面方案选择 |
| 页面方案 | 当前业务类型与页面方案 + 升级预览 + 版本选择 + 配置恢复 + 高级示例内容导入 |
| 品牌管理 | 品牌列表与创建入口;创建品牌先选不可变的业务类型,再选兼容页面方案,创建时不导入示例内容 |
| 小程序页面 | 左右两栏:左 380px 编辑面板,右预览画布;预览内选中区域虚线高亮 + 区域名气泡 |
| 信任内容 | 列表行(类型图标或配图 + 标题 + 发布状态标签 + 类型/展示位置说明 + 两行摘要 + 行内操作),按模板类型顺序排列,不用表格 |
| 业务提供项 | 表格(名称 / 价格 / 状态开关 / 排序 / 操作)+ 新增弹窗 |
| 咨询记录 | 顶部三指标 + 左 380px 列表 + 右详情的主从布局 |
| 咨询表单与字段 | 咨询表单表(名称 / 版本 / 字段数 / 状态 / 操作)+ 新增与编辑弹窗(含选项编辑);高级自定义字段表 + 新增弹窗 |
| 能力插件 | 插件卡片列表(图标 + 名称 + 说明 + 开关),停用态降低对比度 |
| 团队成员 | 表格(成员 / 角色 / 状态 / 最近登录 / 操作)+ 邀请弹窗 |
两栏页面在小屏下折叠为单列,编辑/预览改为上下排列。
+20 -6
View File
@@ -4,9 +4,11 @@ import {
BarsOutlined,
CloudUploadOutlined,
FormOutlined,
LayoutOutlined,
MessageOutlined,
MobileOutlined,
SafetyCertificateOutlined,
ShopOutlined,
TeamOutlined,
ThunderboltOutlined,
} from "@ant-design/icons";
@@ -16,10 +18,13 @@ import { BrandMark } from "../components/BrandMark.js";
import { StatusTag } from "../components/StatusTag.js";
import {
FeatureBrandPage,
FeatureBrandsPage,
FeatureCapabilitiesPage,
FeatureCreateBrandPage,
FeatureInquiriesPage,
FeatureMembersPage,
FeatureOverviewPage,
FeaturePageSchemePage,
FeaturePublicationPage,
FeatureTemplateManagementPage,
FeatureServicesPage,
@@ -34,6 +39,7 @@ import { AdminSelect } from "../components/AdminSelect.js";
import { AdminLayout } from "../components/AdminLayout.js";
import { Route, Routes } from "react-router-dom";
import { AdminOverviewRedirect } from "./AdminRouter.js";
import { createBrandRouteElement } from "./route-access.js";
import { Suspense } from "react";
export function Dashboard({
@@ -70,7 +76,7 @@ export function Dashboard({
label: "日常经营",
children: [
{ key: "overview", label: "当前品牌概览", icon: <AppstoreOutlined /> },
{ key: "publication", label: "配置与发布", icon: <CloudUploadOutlined /> },
{ key: "publication", label: "内容与发布", icon: <CloudUploadOutlined /> },
{ key: "brand", label: "小程序页面", icon: <MobileOutlined /> },
{ key: "trust", label: "信任内容", icon: <SafetyCertificateOutlined /> },
{ key: "services", label: "业务提供项", icon: <BarsOutlined /> },
@@ -83,8 +89,10 @@ export function Dashboard({
: [
{
type: "group" as const,
label: "系统管理",
label: "品牌设置",
children: [
{ key: "brands", label: "品牌管理", icon: <ShopOutlined /> },
{ key: "page-scheme", label: "页面方案", icon: <LayoutOutlined /> },
{ key: "capabilities", label: "能力插件", icon: <ThunderboltOutlined /> },
{ key: "members", label: "团队成员", icon: <TeamOutlined /> },
...(platformTemplateRole === "template_admin"
@@ -141,10 +149,7 @@ export function Dashboard({
<Routes>
<Route index element={<AdminOverviewRedirect />} />
<Route path="overview" element={<FeatureOverviewPage />} />
<Route
path="publication"
element={<FeaturePublicationPage canManageTemplate={role !== "editor"} />}
/>
<Route path="publication" element={<FeaturePublicationPage />} />
<Route path="brand" element={<FeatureBrandPage />} />
<Route path="trust" element={<FeatureTrustContentPage />} />
<Route path="services" element={<FeatureServicesPage />} />
@@ -152,6 +157,15 @@ export function Dashboard({
<Route path="workspace" element={<FeatureWorkspacePage />} />
{role === "editor" ? null : (
<>
<Route
path="brands"
element={<FeatureBrandsPage canCreate={role === "owner"} />}
/>
<Route
path="brands/new"
element={createBrandRouteElement(role, <FeatureCreateBrandPage />)}
/>
<Route path="page-scheme" element={<FeaturePageSchemePage />} />
<Route path="capabilities" element={<FeatureCapabilitiesPage />} />
<Route path="members" element={<FeatureMembersPage />} />
{platformTemplateRole === "template_admin" ? (
+14
View File
@@ -0,0 +1,14 @@
import { createElement, type ReactNode } from "react";
import { Navigate } from "react-router-dom";
export const createBrandFallbackPath = "/admin/brands";
export function canCreateBrand(role: string) {
return role === "owner";
}
export function createBrandRouteElement(role: string, content: ReactNode) {
return canCreateBrand(role)
? content
: createElement(Navigate, { to: createBrandFallbackPath, replace: true });
}
+15
View File
@@ -48,3 +48,18 @@ export const FeatureTemplateManagementPage = React.lazy(() =>
default: module.TemplateManagementPage,
})),
);
export const FeatureBrandsPage = React.lazy(() =>
import("../features/brands/BrandsPage.js").then((module) => ({
default: module.BrandsPage,
})),
);
export const FeatureCreateBrandPage = React.lazy(() =>
import("../features/brands/CreateBrandPage.js").then((module) => ({
default: module.CreateBrandPage,
})),
);
export const FeaturePageSchemePage = React.lazy(() =>
import("../features/page-scheme/PageSchemePage.js").then((module) => ({
default: module.PageSchemePage,
})),
);
+17 -21
View File
@@ -1,4 +1,4 @@
import { Alert, Button, Col, Form, Input, Row, Select, Segmented, message } from "antd";
import { Alert, Button, Col, Form, Input, Row, Segmented, message } from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { Link, useLocation } from "react-router-dom";
@@ -36,10 +36,6 @@ export function BrandPage() {
queryFn: () => client.getPublicTemplate(brand.data!.templateKey),
enabled: Boolean(brand.data?.templateKey),
});
const templateCatalog = useQuery({
queryKey: ["template-catalog"],
queryFn: () => client.listPublicTemplates(),
});
const save = useMutation({
mutationFn: (values: Partial<BrandProfile>) => client.updateAdminBrand(values),
onSuccess: () => {
@@ -60,7 +56,12 @@ export function BrandPage() {
? `先让访客理解你是谁、服务谁,以及为什么值得信任。${template.data.description}`
: "先让访客理解你是谁、服务谁,以及为什么值得信任。"
}
extra={<StatusTag tone="info" label={template.data?.name ?? "当前模板"} />}
extra={
<StatusTag
tone="info"
label={workspace.data?.templateContent?.displayName ?? "当前页面方案"}
/>
}
/>
<div className="brand-page__toolbar">
<Segmented
@@ -169,25 +170,20 @@ export function BrandPage() {
<div className="admin-section-head">
<div>
<h2 id="brand-visual-title" className="admin-section-title">
模板与品牌视觉
品牌视觉
</h2>
<p className="admin-section-description">
模板负责业务表达,品牌信息仍由你统一维护。
头像和封面会用于品牌身份展示;页面结构和资源位由页面方案统一管理。
</p>
</div>
</div>
<Form.Item
name="templateKey"
label="业务表达模板"
help="模板只改变业务表达,不改变个人品牌主线。"
>
<Select
disabled
options={(templateCatalog.data?.industries ?? []).map((item) => ({
value: item.key,
label: item.name,
}))}
/>
<Form.Item label="当前页面方案">
<div>
<strong>{workspace.data?.templateContent?.displayName ?? "尚未安装"}</strong>
<p className="admin-section-description">
页面方案的版本、升级和资源位由品牌负责人统一维护。
</p>
</div>
</Form.Item>
<Row gutter={16}>
<Col xs={24} md={12}>
@@ -223,7 +219,7 @@ export function BrandPage() {
className="brand-page__template-note"
type="info"
showIcon
message={`当前使用:${template.data.name}`}
message={`当前页面方案:${workspace.data?.templateContent?.displayName ?? template.data.name}`}
description={`适用场景:${template.data.serviceCategories.join("、") || "通用品牌展示"}`}
/>
) : null}
@@ -311,12 +311,12 @@ export function PresentationEditor({
</div>
{templateContent ? <StatusTag tone="info" label={templateContent.displayName} /> : null}
</div>
{loading ? <Alert type="info" showIcon message="正在读取当前模板的编辑项目" /> : null}
{loading ? <Alert type="info" showIcon message="正在读取当前页面方案的编辑项目" /> : null}
{error ? (
<Alert type="warning" showIcon message="模板编辑项目读取失败,请刷新后重试。" />
<Alert type="warning" showIcon message="页面方案编辑项目读取失败,请刷新后重试。" />
) : null}
{!loading && !error && !templateContent ? (
<Alert type="warning" showIcon message="当前模板暂未提供可编辑的页面内容。" />
<Alert type="warning" showIcon message="当前页面方案暂未提供可编辑的页面内容。" />
) : null}
{templateContent ? (
<>
@@ -46,8 +46,8 @@ export function useBrandPresentationSections(
return [
...[...new Set(declaredTemplateFields.map((field) => field.page ?? "home"))].map((page) => ({
key: `template-data:${page}`,
title: "模板专属内容",
description: "这些字段由当前小程序模板定义,保存后发布才会对外展示。",
title: "页面方案专属内容",
description: "这些字段由当前页面方案定义,保存后发布才会对外展示。",
page,
target: "brand" as const,
fields: declaredTemplateFields.filter((field) => (field.page ?? "home") === page),
@@ -0,0 +1,129 @@
import { Alert, Button, Card, Col, Row, Space } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { createApiClient } from "../../lib/api.js";
import { adminMessage as message } from "../../components/AdminMessage.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { EmptyState } from "../../components/EmptyState.js";
import { QueryState } from "../../components/QueryState.js";
import { StatusTag } from "../../components/StatusTag.js";
const client = createApiClient();
export function BrandsPage({ canCreate }: { canCreate: boolean }) {
const navigate = useNavigate();
const brands = useQuery({
queryKey: ["admin-brand-memberships"],
queryFn: () => client.listAdminBrands(),
});
const current = useQuery({
queryKey: ["admin-shell-brand"],
queryFn: () => client.getAdminBrand(),
});
const switchBrand = async (brandId: string) => {
try {
await client.switchAdminBrand(brandId);
window.location.assign("/admin/overview");
} catch (error) {
message.error(error instanceof Error ? error.message : "品牌切换失败,请重试");
}
};
return (
<QueryState
loading={brands.isLoading || current.isLoading}
error={brands.error || current.error}
onRetry={() => {
void brands.refetch();
void current.refetch();
}}
>
<AdminPageHeader
title="品牌管理"
description="每个品牌拥有独立的业务类型、页面方案、内容与发布记录。"
extra={
canCreate ? (
<Button
type="primary"
icon={<PlusOutlined />}
onClick={() => navigate("/admin/brands/new")}
>
创建品牌
</Button>
) : null
}
/>
<Alert
className="admin-offset-bottom"
type="info"
showIcon
message="切换品牌会进入对应品牌的工作区"
description="品牌之间的业务内容、成员、发布记录和页面方案相互隔离。"
/>
{brands.data?.length ? (
<Row gutter={[16, 16]} className="admin-equal-height">
{brands.data.map((membership) => {
const isCurrent = membership.brand.id === current.data?.id;
return (
<Col key={membership.brand.id} xs={24} lg={12}>
<Card
title={membership.brand.name}
extra={
<StatusTag
tone={isCurrent ? "success" : "neutral"}
label={
isCurrent ? "当前品牌" : membership.role === "owner" ? "负责人" : "编辑"
}
/>
}
actions={[
<Button
key="switch"
type={isCurrent ? "default" : "primary"}
disabled={isCurrent}
onClick={() => void switchBrand(membership.brand.id)}
>
{isCurrent ? "正在使用" : "进入此品牌"}
</Button>,
]}
>
<Space direction="vertical" size={8}>
<span className="admin-section-description">
小程序地址标识:{membership.brand.slug}
</span>
{membership.role === "owner" ? (
<span className="admin-section-description">
你可以在该品牌中管理页面方案、成员和发布。
</span>
) : (
<span className="admin-section-description">
你在该品牌中的角色是内容编辑,不能管理页面方案或成员。
</span>
)}
</Space>
</Card>
</Col>
);
})}
</Row>
) : (
<Card>
<EmptyState
title="还没有可管理的品牌"
description={
canCreate ? "创建第一个品牌后即可开始配置内容。" : "请联系品牌负责人邀请你加入。"
}
action={
canCreate ? (
<Button type="primary" onClick={() => navigate("/admin/brands/new")}>
创建品牌
</Button>
) : undefined
}
/>
</Card>
)}
</QueryState>
);
}
@@ -0,0 +1,202 @@
import { Alert, Button, Col, Form, Input, Radio, Row, Space } from "antd";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import type {
BrandCreationOptionBusiness,
BrandCreationOptionPageScheme,
CreateBrandInput,
} from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { AdminSection } from "../../components/AdminSection.js";
import { EmptyState } from "../../components/EmptyState.js";
import { MutationError, QueryState } from "../../components/QueryState.js";
import { StatusTag } from "../../components/StatusTag.js";
const client = createApiClient();
function compatibleSchemes(
schemes: BrandCreationOptionPageScheme[],
businessType?: CreateBrandInput["businessType"],
) {
return businessType
? schemes.filter((scheme) => scheme.supportedBusinessTypes.includes(businessType))
: [];
}
export function CreateBrandPage() {
const navigate = useNavigate();
const [form] = Form.useForm<CreateBrandInput>();
const businessType = Form.useWatch("businessType", form);
const options = useQuery({
queryKey: ["admin-brand-creation-options"],
queryFn: () => client.getAdminBrandCreationOptions(),
});
const create = useMutation({
mutationFn: (values: CreateBrandInput) => client.createAdminBrand(values),
onSuccess: () => {
// 创建接口会切换品牌会话;完整导航确保所有查询重新绑定到新品牌。
window.location.assign("/admin/overview");
},
});
const schemes = compatibleSchemes(options.data?.pageSchemes ?? [], businessType);
return (
<QueryState
loading={options.isLoading}
error={options.error}
onRetry={() => void options.refetch()}
>
<AdminPageHeader
title="创建品牌"
description="先确定业务类型,再选择与该业务兼容的页面方案。业务类型创建后不可更改。"
/>
<Form
form={form}
layout="vertical"
onFinish={(values) => create.mutate(values)}
onValuesChange={(changed: Partial<CreateBrandInput>) => {
if (!changed.businessType) return;
const nextSchemes = compatibleSchemes(
options.data?.pageSchemes ?? [],
changed.businessType,
);
const selected = form.getFieldValue("templatePackageVersionId") as unknown;
if (!nextSchemes.some((scheme) => scheme.templatePackageVersionId === selected)) {
form.setFieldValue("templatePackageVersionId", undefined);
}
}}
>
<div className="admin-stack">
<AdminSection title="品牌身份" description="这些信息会展示给访客,之后仍可继续完善。">
<Row gutter={16}>
<Col xs={24} md={12}>
<Form.Item
name="name"
label="品牌名称"
rules={[{ required: true, message: "请输入品牌名称" }]}
>
<Input size="large" maxLength={80} placeholder="例如:林境建筑" />
</Form.Item>
</Col>
<Col xs={24} md={12}>
<Form.Item
name="slug"
label="小程序地址标识"
help="用于生成和识别公开品牌地址,只能使用小写字母、数字和连字符。"
rules={[
{ required: true, message: "请输入小程序地址标识" },
{
pattern: /^[a-z0-9]+(?:-[a-z0-9]+)*$/,
message: "只能使用小写字母、数字和连字符",
},
]}
>
<Input size="large" maxLength={80} placeholder="例如:linjing-architecture" />
</Form.Item>
</Col>
</Row>
</AdminSection>
<AdminSection
title="业务类型"
description="业务类型决定品牌需要填写哪些内容。不同业务类型的字段和能力不同,创建后不能修改。"
>
<Form.Item name="businessType" rules={[{ required: true, message: "请选择业务类型" }]}>
<Radio.Group className="admin-stack">
<Row gutter={[12, 12]}>
{(options.data?.businesses ?? []).map((business: BrandCreationOptionBusiness) => (
<Col key={business.key} xs={24} lg={8}>
<Radio.Button value={business.key} className="admin-choice-card">
<strong>{business.name}</strong>
<span>{business.description}</span>
</Radio.Button>
</Col>
))}
</Row>
</Radio.Group>
</Form.Item>
{businessType ? (
schemes.length ? null : (
<Alert
type="warning"
showIcon
message="当前业务类型还没有可用的页面方案"
description="请先联系平台管理员发布兼容的页面方案。"
/>
)
) : (
<Alert type="info" showIcon message="选择业务类型后,将只显示兼容的页面方案" />
)}
</AdminSection>
<AdminSection
title="页面方案"
description="页面方案决定页面结构、视觉和资源位。版本可在创建后继续升级或切换。"
>
{schemes.length ? (
<Form.Item
name="templatePackageVersionId"
rules={[{ required: true, message: "请选择页面方案" }]}
>
<Radio.Group className="admin-stack">
<Space direction="vertical" size={12} className="admin-full-width">
{schemes.map((scheme) => (
<Radio.Button
key={scheme.templatePackageVersionId}
value={scheme.templatePackageVersionId}
className="admin-choice-card admin-choice-card--wide"
>
<span className="admin-row-line">
<strong>{scheme.name}</strong>
<StatusTag
tone={scheme.isLatestForPackage ? "success" : "neutral"}
label={
scheme.isLatestForPackage
? `最新版 ${scheme.version}`
: `版本 ${scheme.version}`
}
/>
</span>
<span>{scheme.description}</span>
</Radio.Button>
))}
</Space>
</Radio.Group>
</Form.Item>
) : (
<EmptyState
title={businessType ? "没有兼容的页面方案" : "先选择业务类型"}
description={
businessType
? "平台尚未发布适配该业务类型的页面方案。"
: "选择业务类型后,这里会列出可用的页面结构和视觉方案。"
}
/>
)}
</AdminSection>
<Alert
type="info"
showIcon
message="创建品牌不会自动导入示例内容"
description="新品牌会从空白内容开始,避免把示例品牌、案例或联系方式误当成真实信息发布。"
/>
<MutationError error={create.error} />
<Space>
<Button onClick={() => navigate("/admin/brands")}>取消</Button>
<Button
type="primary"
htmlType="submit"
size="large"
loading={create.isPending}
disabled={!businessType || schemes.length === 0}
>
创建并进入品牌
</Button>
</Space>
</div>
</Form>
</QueryState>
);
}
@@ -15,7 +15,7 @@ export function CapabilitiesPage() {
<QueryState loading={query.isLoading} error={query.error} onRetry={() => void query.refetch()}>
<AdminPageHeader
title="能力插件"
description="以经营者视角调整模板能力的开关与展示设置;保存后进入草稿,发布后生效。"
description="以经营者视角调整当前页面方案提供的业务能力;保存后进入草稿,发布后生效。"
/>
{query.data?.length ? (
<Row gutter={[16, 16]} className="admin-equal-height">
@@ -29,9 +29,9 @@ export function CapabilitiesPage() {
<Card>
<EmptyState
icon={<AppstoreOutlined />}
title="当前模板没有可配置能力"
description="能力的开关由品牌当前使用的行业模板决定;更换行业模板不在本版本范围内。"
action={<Button onClick={() => navigate("/admin/publication")}>查看模板与发布</Button>}
title="当前页面方案没有可配置能力"
description="能力由品牌当前使用的业务类型和页面方案决定。"
action={<Button onClick={() => navigate("/admin/page-scheme")}>查看页面方案</Button>}
/>
</Card>
)}
@@ -8,12 +8,12 @@ import { CapabilityStatusControl, CapabilityStatusTag } from "./CapabilityStatus
const sourceLabels = {
brand: "品牌覆盖",
template: "模板默认",
template: "方案默认",
} as const;
const disablePolicyLabels = {
allowed: "该能力允许停用,保存后进入草稿。",
disabled: "该能力为模板必需项,保存后进入草稿。",
disabled: "该能力为页面方案必需项,保存后进入草稿。",
} as const;
const updatedTimeFormatter = new Intl.DateTimeFormat("zh-CN", {
@@ -143,7 +143,7 @@ export function CapabilityCard({ capability }: { capability: AdminCapability })
) : null}
<Typography.Text type="secondary">
{capability.source === "template"
? "当前使用模板默认设置;修改后保存会创建品牌覆盖。"
? "当前使用页面方案默认设置;修改后保存会创建品牌覆盖。"
: "当前已创建品牌覆盖;修改后保存会更新草稿。"}
{capability.updatedAt
? ` 最近更新:${updatedTimeFormatter.format(new Date(capability.updatedAt))}`
@@ -213,7 +213,7 @@ export function InquiriesPage() {
</AdminSection>
<AdminSection
title={`动态咨询提交${submissions.data ? `(${submissions.data.length})` : ""}`}
description="按模板表单提交的咨询记录,字段随表单配置变化。"
description="按咨询表单提交的记录,字段随表单配置变化。"
extra={
<Button onClick={() => void submissions.refetch()} loading={submissions.isFetching}>
刷新提交记录
@@ -248,7 +248,7 @@ export function InquiriesPage() {
<EmptyState
compact
title="暂无动态咨询提交"
description="按模板表单提交的咨询会汇总在这里。"
description="按咨询表单提交的内容会汇总在这里。"
/>
),
}}
@@ -90,7 +90,7 @@ export function OverviewPage() {
<p className="admin-brand-tagline">{brand?.tagline || "还没有设置一句话定位"}</p>
<StatusTag
tone="info"
label={`当前模板:${workspace?.templateContent?.displayName ?? "尚未安装模板"}`}
label={`当前页面方案:${workspace?.templateContent?.displayName ?? "尚未安装页面方案"}`}
/>
</Card>
<Row gutter={[16, 16]}>
@@ -0,0 +1,375 @@
import { useEffect, useState } from "react";
import { Alert, Button, Card, Collapse, Descriptions, Empty, List, Modal, Space, Tag } from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { createApiClient } from "../../lib/api.js";
import { adminMessage as message } from "../../components/AdminMessage.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { AdminSection } from "../../components/AdminSection.js";
import { MutationError, QueryState } from "../../components/QueryState.js";
import { StatusTag } from "../../components/StatusTag.js";
const client = createApiClient();
export function PageSchemePage() {
const queryClient = useQueryClient();
const [selectedVersionId, setSelectedVersionId] = useState<string>();
const [samplePreview, setSamplePreview] = useState<Awaited<
ReturnType<typeof client.previewAdminSampleContent>
> | null>(null);
const workspace = useQuery({
queryKey: ["page-scheme-workspace"],
queryFn: () => client.getAdminWorkspace(),
});
const options = useQuery({
queryKey: ["admin-page-scheme-options"],
queryFn: () => client.getAdminPageSchemeOptions(),
});
const upgradePreview = useQuery({
queryKey: ["page-scheme-upgrade-preview"],
queryFn: () => client.getAdminTemplateUpgradePreview(),
});
const installation = workspace.data?.installations[0];
const currentVersionId = installation?.templatePackageVersionId;
const currentScheme = options.data?.pageSchemes.find(
(scheme) => scheme.templatePackageVersionId === currentVersionId,
);
const business = options.data?.business;
const compatibleSchemes = options.data?.pageSchemes ?? [];
useEffect(() => {
if (currentVersionId) setSelectedVersionId(currentVersionId);
}, [currentVersionId]);
const refresh = () => {
for (const queryKey of [
"page-scheme-workspace",
"page-scheme-upgrade-preview",
"admin-workspace",
"admin-preview-workspace",
"admin-overview-workspace",
"publication-workspace",
"publication-readiness",
]) {
void queryClient.invalidateQueries({ queryKey: [queryKey] });
}
};
const selectVersion = useMutation({
mutationFn: (templatePackageVersionId: string) =>
client.selectAdminTemplateVersion({
templatePackageVersionId,
expectedCurrentPackageVersionId: currentVersionId ?? null,
confirm: true,
}),
onSuccess: () => {
message.success("页面方案版本已切换");
refresh();
},
});
const upgrade = useMutation({
mutationFn: async () => {
const preview = upgradePreview.data;
if (
!preview?.canUpgrade ||
!preview.targetPackageVersionId ||
!preview.targetContentChecksum
) {
throw new Error("当前没有可升级的页面方案版本,请刷新后重试");
}
return client.upgradeAdminTemplate({
templatePackageVersionId: preview.targetPackageVersionId,
expectedContentChecksum: preview.targetContentChecksum,
expectedCurrentVersion: preview.currentVersion,
expectedCurrentPackageVersionId: preview.currentPackageVersionId,
confirm: true,
preservedBindings: preview.conflicts.map(({ key, binding }) => ({
key,
binding,
action: "preserve",
})),
});
},
onSuccess: () => {
message.success("页面方案已升级,现有内容已全部保留");
refresh();
},
});
const rollback = useMutation({
mutationFn: () => {
const preview = upgradePreview.data;
if (!preview?.canRollback) throw new Error("当前没有可恢复的上一版配置基线");
return client.rollbackAdminTemplate({
expectedCurrentVersion: preview.currentVersion,
confirm: true,
});
},
onSuccess: () => {
message.success("已恢复上一版页面方案配置基线");
refresh();
},
});
const previewSample = useMutation({
mutationFn: () =>
client.previewAdminSampleContent({
...(currentVersionId ? { templatePackageVersionId: currentVersionId } : {}),
strategy: "missing_only",
}),
onSuccess: (data) => setSamplePreview(data),
});
const importSample = useMutation({
mutationFn: () =>
client.importAdminSampleContent({
...(currentVersionId ? { templatePackageVersionId: currentVersionId } : {}),
strategy: "missing_only",
confirm: true,
}),
onSuccess: () => {
message.success("示例内容已按缺失项导入,现有内容未被覆盖");
setSamplePreview(null);
refresh();
},
});
const confirmSelect = (templatePackageVersionId: string) => {
const target = compatibleSchemes.find(
(scheme) => scheme.templatePackageVersionId === templatePackageVersionId,
);
Modal.confirm({
title: "切换页面方案版本",
content: target
? `将当前品牌切换到「${target.name}」版本 ${target.version}。现有品牌内容会保留。`
: "将切换当前品牌使用的页面方案版本。现有品牌内容会保留。",
okText: "确认切换",
cancelText: "取消",
onOk: () => selectVersion.mutateAsync(templatePackageVersionId),
});
};
const confirmUpgrade = () => {
const preview = upgradePreview.data;
Modal.confirm({
title: "升级页面方案",
content:
preview && preview.conflicts.length
? `将升级到版本 ${preview.latestVersion},并全部保留 ${preview.conflicts.length} 项现有内容。`
: `将升级到版本 ${preview?.latestVersion ?? "最新版"},现有品牌内容会保留。`,
okText: "确认升级",
cancelText: "取消",
onOk: () => upgrade.mutateAsync(),
});
};
const confirmRollback = () => {
Modal.confirm({
title: "恢复上一版配置基线",
content: "此操作只恢复上一版页面方案配置,不会删除品牌内容、业务提供项或咨询记录。",
okText: "确认恢复",
cancelText: "取消",
onOk: () => rollback.mutateAsync(),
});
};
return (
<QueryState
loading={workspace.isLoading || options.isLoading || upgradePreview.isLoading}
error={workspace.error || options.error || upgradePreview.error}
onRetry={() => {
void workspace.refetch();
void options.refetch();
void upgradePreview.refetch();
}}
>
<AdminPageHeader
title="页面方案"
description="页面方案决定小程序有哪些页面、页面结构、视觉和资源位。它可以独立于内容发布进行升级或版本切换。"
/>
<div className="admin-stack">
<AdminSection
title="当前方案"
description="业务类型创建后固定;页面方案和版本可以继续调整。"
>
<Descriptions column={{ xs: 1, md: 2 }} bordered>
<Descriptions.Item label="业务类型">{business?.name ?? "未识别"}</Descriptions.Item>
<Descriptions.Item label="页面方案">
{currentScheme?.name ?? workspace.data?.templateContent?.displayName ?? "尚未安装"}
</Descriptions.Item>
<Descriptions.Item label="当前状态">
<StatusTag
tone={installation ? "info" : "neutral"}
label={
installation ? `正在使用版本 ${installation.templateVersion}` : "尚未安装页面方案"
}
/>
</Descriptions.Item>
</Descriptions>
{business?.description ? (
<p className="admin-section-description admin-offset-top">{business.description}</p>
) : null}
</AdminSection>
<AdminSection
title="升级预览"
description="升级前先查看页面、模块、资源和绑定的变化;冲突项默认保留现有内容。"
>
<Card>
{upgradePreview.data?.canUpgrade ? (
<Space direction="vertical" size={12} className="admin-full-width">
<div className="admin-row-line">
<strong>可升级到版本 {upgradePreview.data.latestVersion}</strong>
<Tag color="blue">建议先预览</Tag>
</div>
<Descriptions column={{ xs: 1, md: 2 }} size="small">
<Descriptions.Item label="新增页面">
{upgradePreview.data.changes.pages.added.length}
</Descriptions.Item>
<Descriptions.Item label="变更页面">
{upgradePreview.data.changes.pages.changed.length}
</Descriptions.Item>
<Descriptions.Item label="新增字段绑定">
{upgradePreview.data.changes.templateBindings.added.length}
</Descriptions.Item>
<Descriptions.Item label="需要保留的冲突">
{upgradePreview.data.conflicts.length}
</Descriptions.Item>
</Descriptions>
{upgradePreview.data.conflicts.length ? (
<Alert
type="warning"
showIcon
message={`发现 ${upgradePreview.data.conflicts.length} 项自定义内容与新版布局存在差异`}
description="升级时会全部保留现有内容,不会逐项覆盖。请确认后再执行升级。"
/>
) : (
<Alert type="success" showIcon message="未发现内容绑定冲突" />
)}
<Button type="primary" onClick={confirmUpgrade} loading={upgrade.isPending}>
升级到 {upgradePreview.data.latestVersion}
</Button>
</Space>
) : (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description="当前已是可用的最新页面方案版本,暂无可升级版本。"
/>
)}
<MutationError error={upgrade.error} />
</Card>
</AdminSection>
<AdminSection
title="选择版本"
description="可切换到同一业务类型下的其他已发布版本。切换会保留品牌内容。"
>
<List
dataSource={compatibleSchemes}
locale={{ emptyText: "没有可切换的页面方案版本" }}
renderItem={(scheme) => {
const isCurrent = scheme.templatePackageVersionId === currentVersionId;
return (
<List.Item
actions={[
<Button
key="select"
type={isCurrent ? "default" : "primary"}
disabled={isCurrent}
loading={
selectVersion.isPending &&
selectedVersionId === scheme.templatePackageVersionId
}
onClick={() => {
setSelectedVersionId(scheme.templatePackageVersionId);
confirmSelect(scheme.templatePackageVersionId);
}}
>
{isCurrent ? "当前版本" : "切换到此版本"}
</Button>,
]}
>
<List.Item.Meta
title={
<Space>
<span>{scheme.name}</span>
<Tag color={scheme.isLatestForPackage ? "green" : "default"}>
{scheme.isLatestForPackage ? "最新版" : `版本 ${scheme.version}`}
</Tag>
</Space>
}
description={`${scheme.description} · 版本 ${scheme.version}`}
/>
</List.Item>
);
}}
/>
<MutationError error={selectVersion.error} />
</AdminSection>
<AdminSection
title="配置恢复"
description="恢复上一版页面方案配置基线,仅用于升级后出现配置问题时回退。"
>
<Button danger onClick={confirmRollback} disabled={!upgradePreview.data?.canRollback}>
恢复上一版配置
</Button>
<MutationError error={rollback.error} />
</AdminSection>
<Collapse
items={[
{
key: "sample-content",
label: "高级:导入示例内容",
children: (
<Space direction="vertical" size={12} className="admin-full-width">
<Alert
type="warning"
showIcon
message="此操作会写入当前品牌内容"
description="仅导入当前缺失的内容,不会覆盖已有品牌资料。创建品牌时不会自动执行。"
/>
<Space>
<Button
onClick={() => previewSample.mutate()}
loading={previewSample.isPending}
>
预览将导入的内容
</Button>
<Button
type="primary"
danger
disabled={!samplePreview}
loading={importSample.isPending}
onClick={() => importSample.mutate()}
>
确认导入缺失内容
</Button>
</Space>
<MutationError error={previewSample.error || importSample.error} />
{samplePreview ? (
<Descriptions bordered size="small" column={{ xs: 1, md: 2 }}>
<Descriptions.Item label="品牌资料">
{samplePreview.counts.brandConfig}
</Descriptions.Item>
<Descriptions.Item label="业务提供项">
{samplePreview.counts.offerings}
</Descriptions.Item>
<Descriptions.Item label="信任内容">
{samplePreview.counts.trustContent}
</Descriptions.Item>
<Descriptions.Item label="字段">
{samplePreview.counts.fields}
</Descriptions.Item>
<Descriptions.Item label="咨询表单">
{samplePreview.counts.inquiryForms}
</Descriptions.Item>
<Descriptions.Item label="是否已导入">
{samplePreview.alreadyImported ? "是" : "否"}
</Descriptions.Item>
</Descriptions>
) : null}
</Space>
),
},
]}
/>
</div>
</QueryState>
);
}
@@ -1,26 +1,11 @@
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import {
Alert,
Button,
Checkbox,
Divider,
Input,
Popconfirm,
Modal,
Form,
Select,
Space,
Spin,
Tabs,
Typography,
} from "antd";
import type { BrandTemplateKey } from "@personal-brand/api-client";
import { Alert, Button, Divider, Form, Input, Modal, Space, Tabs, Typography } from "antd";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { AdminSection } from "../../components/AdminSection.js";
import { EmptyState } from "../../components/EmptyState.js";
import { ErrorNote, MutationError, QueryState } from "../../components/QueryState.js";
import { MutationError, QueryState } from "../../components/QueryState.js";
import { StatusTag, statusLabel } from "../../components/StatusTag.js";
import { MiniAppReleaseCard } from "./MiniAppReleaseCard.js";
import { MiniAppSettingsTab, type MiniAppSettingsValues } from "./MiniAppSettingsTab.js";
@@ -30,34 +15,28 @@ import { usePublicationMutations } from "./use-publication-mutations.js";
const destinations: Record<string, string> = {
brand: "/admin/brand",
positioning: "/admin/brand",
template: "/admin/publication",
visual: "/admin/publication",
template: "/admin/page-scheme",
visual: "/admin/page-scheme",
offerings: "/admin/services",
forms: "/admin/workspace",
trust: "/admin/trust",
};
export function PublicationPage({ canManageTemplate }: { canManageTemplate: boolean }) {
export function PublicationPage() {
const navigate = useNavigate();
const queryClient = useQueryClient();
const [industryTarget, setIndustryTarget] = useState<BrandTemplateKey | null>(null);
const [confirmAction, setConfirmAction] = useState<"publish" | "revoke" | null>(null);
const [rollbackVersion, setRollbackVersion] = useState<number | null>(null);
const [preservedBindings, setPreservedBindings] = useState<Record<string, boolean>>({});
const [note, setNote] = useState("");
const [activeTab, setActiveTab] = useState("content");
const [miniAppSettingsForm] = Form.useForm<MiniAppSettingsValues>();
const queries = usePublicationQueries(miniAppSettingsForm);
const {
brand,
workspace,
catalog,
sample,
readiness,
releases,
miniAppReleases,
miniAppSettings,
templatePreview,
loading,
error,
retry,
@@ -66,11 +45,10 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
for (const key of [
"publication-brand",
"publication-workspace",
"publication-sample",
"publication-readiness",
"publication-template-preview",
"publication-releases",
"publication-miniapp-releases",
"publication-miniapp-settings",
"admin-shell-brand",
"admin-workspace",
"public-runtime-workspace",
@@ -80,18 +58,11 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
};
const mutations = usePublicationMutations({
refresh,
currentTemplatePackageVersionId: workspace.data?.installations[0]?.templatePackageVersionId,
onInstallClose: () => setIndustryTarget(null),
onPublishClose: () => setConfirmAction(null),
onNoteClear: () => setNote(""),
onRollbackClose: () => setRollbackVersion(null),
});
const {
install,
upgradeTemplate,
rollbackTemplate,
selectVisual,
importSample,
publish,
revoke,
rollback,
@@ -100,18 +71,6 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
uploadMiniAppRelease,
updateMiniAppStatus,
} = mutations;
const industryKey =
workspace.data?.installations[0]?.templateKey ??
workspace.data?.brand?.templateKey ??
brand.data?.templateKey ??
null;
const selectablePackageVersions = (queries.packages.data?.items ?? []).filter(
(item) =>
item.status === "published" &&
typeof industryKey === "string" &&
item.manifestSummary?.supportedIndustryTemplates.includes(industryKey),
);
const visualKey = workspace.data?.installations[0]?.visualTemplateKey ?? null;
const currentRelease = releases.data?.find((item) => item.status === "published");
const publishedHistory = (releases.data ?? []).filter(
(item) => item.status === "published" || item.status === "superseded",
@@ -123,12 +82,12 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
isEnabled: boolean;
}>;
const contentTab = null;
return (
<QueryState loading={loading} error={error} onRetry={retry}>
<AdminPageHeader
title="配置与发布"
description="编辑内容不会立即影响小程序;确认后统一发布当前品牌。"
title="内容与发布"
description="检查当前草稿并发布品牌内容;页面方案与内容发布互不混用。"
extra={<Button onClick={() => navigate("/admin/page-scheme")}>管理页面方案</Button>}
/>
<Tabs
activeKey={activeTab}
@@ -137,418 +96,175 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
{
key: "content",
label: "内容发布",
children: contentTab,
children: (
<div className="admin-stack">
<AdminSection
title="发布前检查"
description="请先处理未完成的检查项,再发布当前草稿。发布不会自动修改页面方案。"
>
{draftOfferings.length || draftForms.length ? (
<p className="admin-section-description">
当前草稿包含 {draftOfferings.length} 个启用中的业务提供项和{" "}
{draftForms.length} 个咨询表单。
</p>
) : null}
<ul className="admin-list">
{(readiness.data?.checks ?? []).map((check) => (
<li key={check.key} className="admin-row">
<div className="admin-row-main">
<div className="admin-row-line">
<StatusTag
tone={check.passed ? "success" : "warning"}
label={check.passed ? "已完成" : "待完善"}
/>
<span className="admin-row-title">{check.label}</span>
{!check.passed && check.help ? (
<span className="admin-row-meta">{check.help}</span>
) : null}
</div>
</div>
{!check.passed ? (
<Button
type="link"
size="small"
onClick={() =>
navigate(
check.destination ?? destinations[check.key] ?? "/admin/overview",
)
}
>
去处理
</Button>
) : null}
</li>
))}
</ul>
<Space wrap className="admin-offset-top">
<Button
type="primary"
disabled={!readiness.data?.ready}
onClick={() => setConfirmAction("publish")}
>
发布当前草稿
</Button>
{currentRelease && (
<Button danger onClick={() => setConfirmAction("revoke")}>
撤回当前版本
</Button>
)}
</Space>
<MutationError error={publish.error || revoke.error} />
<Divider className="admin-divider" />
<h3 className="admin-section-title">发布记录</h3>
{releases.data?.length ? (
<ul className="admin-list admin-offset-top-xs">
{releases.data.map((item) => (
<li key={item.id} className="admin-row">
<div className="admin-row-main">
<div className="admin-row-line">
<span className="admin-row-title">v{item.version}</span>
<StatusTag
tone={item.status === "published" ? "success" : "neutral"}
label={statusLabel(item.status)}
/>
<span className="admin-row-meta">
{new Date(item.createdAt).toLocaleString("zh-CN")}
</span>
{item.note ? (
<span className="admin-row-meta">{item.note}</span>
) : null}
</div>
</div>
{item.status === "superseded" && publishedHistory.length > 1 ? (
<Button
type="link"
size="small"
onClick={() => setRollbackVersion(item.version)}
>
恢复此版本
</Button>
) : null}
</li>
))}
</ul>
) : (
<EmptyState
compact
title="暂无发布记录"
description="完成检查并发布后,这里会保留每个版本的记录。"
/>
)}
<MutationError error={rollback.error} />
</AdminSection>
</div>
),
},
{
key: "miniapp",
label: "小程序发布",
children: (
<div className="admin-stack admin-stack-lg">
<AdminSection
title="小程序代码发布"
description="使用微信官方工具上传代码;审核与发布状态需按微信平台结果人工确认。"
extra={
<Space wrap>
<Button
type="primary"
disabled={!currentRelease}
loading={uploadLatestMiniAppRelease.isPending}
onClick={() => uploadLatestMiniAppRelease.mutate()}
>
上传当前版本到微信
</Button>
{miniAppSettings.data?.hasStoredCredentials ? (
<StatusTag tone="success" label="已配置上传凭据" />
) : (
<StatusTag tone="warning" label="未配置上传凭据" />
)}
</Space>
}
>
{miniAppReleases.data?.length ? (
<div className="admin-stack admin-stack-tight">
{miniAppReleases.data.map((task) => (
<MiniAppReleaseCard
key={task.id}
task={task}
uploading={uploadMiniAppRelease.isPending}
onUpload={() => uploadMiniAppRelease.mutate(task.id)}
onStatusChange={(status) =>
updateMiniAppStatus.mutate({ id: task.id, status })
}
/>
))}
</div>
) : (
<EmptyState
compact
title="暂无小程序发布任务"
description="先发布品牌内容,再上传当前版本到微信。"
/>
)}
</AdminSection>
</div>
),
},
{ key: "miniapp", label: "小程序发布", children: null },
{
key: "settings",
label: "小程序配置",
children:
activeTab === "settings" ? (
<MiniAppSettingsTab
form={miniAppSettingsForm}
settings={miniAppSettings.data}
saving={saveMiniAppSettings.isPending}
error={saveMiniAppSettings.error}
onSave={(values) => saveMiniAppSettings.mutate(values)}
/>
) : null,
children: (
<MiniAppSettingsTab
form={miniAppSettingsForm}
settings={miniAppSettings.data}
saving={saveMiniAppSettings.isPending}
error={saveMiniAppSettings.error}
onSave={(values) => saveMiniAppSettings.mutate(values)}
/>
),
},
]}
/>
{activeTab === "content" && (
<div className="admin-stack">
<AdminSection
title="选择表达方式"
description="行业模板决定内容结构,视觉模板决定小程序的排版风格。"
>
<Space wrap>
<Select
aria-label="行业模板"
className="admin-field-w-xl"
value={industryKey}
disabled={!canManageTemplate || Boolean(workspace.data?.installations.length)}
options={(catalog.data?.industries ?? []).map((item) => ({
value: item.key,
label: item.name,
}))}
onChange={(key: BrandTemplateKey) => setIndustryTarget(key)}
/>
<Select
aria-label="视觉模板"
className="admin-field-w-xl"
value={visualKey}
disabled={!canManageTemplate}
loading={selectVisual.isPending}
options={selectablePackageVersions.map((item) => ({
value: item.id,
label: `${item.displayName} · ${item.version}`,
}))}
onChange={(versionId) => selectVisual.mutate(versionId)}
/>
</Space>
{industryKey ? (
<div className="admin-offset-top-sm">
<Space wrap>
<StatusTag
tone="neutral"
label={`当前版本 ${templatePreview.data?.currentVersion ?? "加载中"}`}
/>
<StatusTag
tone="info"
label={`最新版本 ${templatePreview.data?.latestVersion ?? "加载中"}`}
/>
{templatePreview.data?.canUpgrade ? (
<Popconfirm
title="确认升级到已发布模板包?"
description={`新增 binding ${templatePreview.data.changes.templateBindings.added.length} 项;冲突值需逐项确认保留。升级不会删除字段或业务内容。`}
okText="确认升级"
cancelText="取消"
onConfirm={() => {
const preview = templatePreview.data;
if (!preview?.targetPackageVersionId || !preview.targetContentChecksum)
return;
if (
!preview.conflicts.every(
(item) => preservedBindings[`${item.key}:${item.binding}`],
)
)
return;
upgradeTemplate.mutate({
templatePackageVersionId: preview.targetPackageVersionId,
expectedContentChecksum: preview.targetContentChecksum,
expectedCurrentVersion: preview.currentVersion,
expectedCurrentPackageVersionId: preview.currentPackageVersionId,
confirm: true,
preservedBindings: preview.conflicts.map(({ key, binding }) => ({
key,
binding,
action: "preserve" as const,
})),
});
}}
>
<Button
type="primary"
size="small"
disabled={
!canManageTemplate ||
!templatePreview.data?.targetPackageVersionId ||
!templatePreview.data.conflicts.every(
(item) => preservedBindings[`${item.key}:${item.binding}`],
)
}
loading={upgradeTemplate.isPending}
>
升级模板
</Button>
</Popconfirm>
) : (
<StatusTag tone="success" label="已是最新版本" />
)}
{templatePreview.data?.canRollback ? (
<Popconfirm
title="确认恢复上一版模板配置基线?"
description="不会删除品牌字段、业务内容、历史发布或客户咨询记录。"
okText="确认回滚"
cancelText="取消"
onConfirm={() => {
const currentVersion = templatePreview.data?.currentVersion;
if (!currentVersion) return;
rollbackTemplate.mutate({
expectedCurrentVersion: currentVersion,
confirm: true,
});
}}
>
<Button
danger
size="small"
disabled={!canManageTemplate}
loading={rollbackTemplate.isPending}
>
回滚到上一版
</Button>
</Popconfirm>
) : null}
</Space>
<p className="admin-section-description admin-offset-top-sm">
行业模板随品牌身份固定。升级目标为当前视觉模板最新已发布包,并按包版本与 checksum
锁定预览;新增字段会补入,改动冲突和已移除字段不会覆盖或删除。回滚仅恢复配置基线,不删除品牌字段、内容或历史发布。
</p>
{templatePreview.data?.conflicts.length ? (
<Alert
type="warning"
showIcon
message={`请逐项确认保留 ${templatePreview.data.conflicts.length} 个现有品牌配置值`}
description={
<Space direction="vertical">
{templatePreview.data.conflicts.map((item) => {
const key = `${item.key}:${item.binding}`;
return (
<Checkbox
key={key}
checked={Boolean(preservedBindings[key])}
onChange={(event) =>
setPreservedBindings((current) => ({
...current,
[key]: event.target.checked,
}))
}
>
保留 {item.binding}({item.reason})
</Checkbox>
);
})}
</Space>
}
/>
) : null}
{templatePreview.data ? (
<div className="admin-section-description admin-offset-top-sm">
页面入口变更:新增 {templatePreview.data.changes.pages.added.length}、变更{" "}
{templatePreview.data.changes.pages.changed.length}、移除{" "}
{templatePreview.data.changes.pages.removed.length};资源槽位变更:新增{" "}
{templatePreview.data.changes.assets.slots.added.length}、变更{" "}
{templatePreview.data.changes.assets.slots.changed.length}、移除{" "}
{templatePreview.data.changes.assets.slots.removed.length};
{templatePreview.data.changes.assets.files.available
? `包内文件变更:新增 ${templatePreview.data.changes.assets.files.added?.length ?? 0}、变更 ${templatePreview.data.changes.assets.files.changed?.length ?? 0}、移除 ${templatePreview.data.changes.assets.files.removed?.length ?? 0}`
: templatePreview.data.changes.assets.files.reason}
。模块与 renderer 由已部署的平台视觉模板管理,此次包升级不会替换 renderer。
</div>
) : null}
<MutationError
error={templatePreview.error || upgradeTemplate.error || rollbackTemplate.error}
/>
</div>
) : null}
<MutationError error={install.error || selectVisual.error} />
<Divider className="admin-divider" />
<Space wrap>
<Typography.Text>示例内容</Typography.Text>
{sample.isLoading && <Spin size="small" />}
{sample.data && (
<StatusTag
tone={sample.data.alreadyImported ? "success" : "info"}
label={sample.data.alreadyImported ? "已导入" : "可导入"}
/>
)}
<Button
disabled={!canManageTemplate || !sample.data || sample.data.alreadyImported}
loading={importSample.isPending}
onClick={() => importSample.mutate(sample.data?.source.templatePackageVersionId)}
>
导入示例内容
</Button>
{sample.isError && <Button onClick={() => void sample.refetch()}>重试</Button>}
</Space>
{sample.isError && (
<div className="admin-offset-top-sm">
<ErrorNote error={sample.error} onRetry={() => void sample.refetch()} />
</div>
)}
{sample.data && !sample.data.alreadyImported && (
<p className="admin-section-description admin-offset-top-sm">
来源:{sample.data.source.packageKey}@{sample.data.source.version}
(checksum {(sample.data.source.contentChecksum ?? "").slice(0, 12)})
。将向草稿添加{" "}
{Object.entries(sample.data.counts)
.map(([key, count]) => `${key} ${count} 项`)
.join("、")}
;同时补齐当前模板缺失的页面初始配置,保留已有配置和已启用表单。发布前请替换示例文案和图片。
</p>
)}
<MutationError error={importSample.error} />
</AdminSection>
<AdminSection
title="核对草稿内容"
description="此处核对的是待发布内容,不是小程序视觉预览。"
>
<ul className="admin-list">
<li className="admin-row">
<div className="admin-row-main">
<div className="admin-row-line">
<span className="admin-row-title">{brand.data?.name || "未命名品牌"}</span>
<span className="admin-row-meta">
{brand.data?.tagline || "尚未填写品牌定位"}
</span>
</div>
</div>
</li>
<li className="admin-row">
<div className="admin-row-main">
<div className="admin-row-line">
<span className="admin-row-title">已启用业务项</span>
<span className="admin-row-meta">
{draftOfferings.map((item) => item.name).join("、") || "无"}
</span>
</div>
</div>
</li>
<li className="admin-row">
<div className="admin-row-main">
<div className="admin-row-line">
<span className="admin-row-title">已启用咨询表单</span>
<span className="admin-row-meta">
{draftForms
.filter((item) => item.isEnabled)
.map((item) => item.name)
.join("、") || "无"}
</span>
</div>
</div>
</li>
</ul>
<Space wrap className="admin-offset-top">
<Button onClick={() => navigate("/admin/brand")}>编辑小程序页面</Button>
<Button onClick={() => navigate("/admin/services")}>编辑业务展示和详情</Button>
<Button onClick={() => navigate("/admin/trust")}>编辑信任证明</Button>
</Space>
</AdminSection>
<AdminSection
title="检查并发布"
extra={
<Space wrap>
<StatusTag
tone={currentRelease ? "success" : "neutral"}
label={currentRelease ? `已发布 v${currentRelease.version}` : "尚未发布"}
/>
<Button onClick={() => void readiness.refetch()}>重新检查</Button>
</Space>
}
>
<ul className="admin-list">
{(readiness.data?.checks ?? []).map((check) => (
<li key={check.key} className="admin-row">
<div className="admin-row-main">
<div className="admin-row-line">
<StatusTag
tone={check.passed ? "success" : "warning"}
label={check.passed ? "已完成" : "待完善"}
/>
<span className="admin-row-title">{check.label}</span>
{!check.passed && check.help ? (
<span className="admin-row-meta">{check.help}</span>
) : null}
</div>
</div>
{!check.passed ? (
<Button
type="link"
size="small"
onClick={() =>
navigate(check.destination ?? destinations[check.key] ?? "/admin/overview")
}
>
去处理
</Button>
) : null}
</li>
))}
</ul>
<Space wrap className="admin-offset-top">
<Button
type="primary"
disabled={!readiness.data?.ready}
onClick={() => setConfirmAction("publish")}
>
发布当前草稿
</Button>
{currentRelease && (
<Button danger onClick={() => setConfirmAction("revoke")}>
撤回当前版本
</Button>
)}
</Space>
<MutationError error={publish.error || revoke.error} />
<Divider className="admin-divider" />
<h3 className="admin-section-title">发布记录</h3>
{releases.data?.length ? (
<ul className="admin-list admin-offset-top-xs">
{releases.data.map((item) => (
<li key={item.id} className="admin-row">
<div className="admin-row-main">
<div className="admin-row-line">
<span className="admin-row-title">v{item.version}</span>
<StatusTag
tone={item.status === "published" ? "success" : "neutral"}
label={statusLabel(item.status)}
/>
<span className="admin-row-meta">
{new Date(item.createdAt).toLocaleString("zh-CN")}
</span>
{item.note ? <span className="admin-row-meta">{item.note}</span> : null}
</div>
</div>
{item.status === "superseded" && publishedHistory.length > 1 ? (
<Button
type="link"
size="small"
onClick={() => setRollbackVersion(item.version)}
>
恢复此版本
</Button>
) : null}
</li>
))}
</ul>
) : (
<EmptyState
compact
title="暂无发布记录"
description="完成检查并发布后,这里会保留每个版本的记录。"
/>
)}
<MutationError error={rollback.error} />
</AdminSection>
</div>
)}
{activeTab === "miniapp" && (
<div className="admin-stack admin-stack-lg">
<AdminSection
title="小程序代码发布"
description="使用微信官方工具上传代码;审核与发布状态需按微信平台结果人工确认。"
extra={
<Space wrap>
<Button
type="primary"
disabled={!currentRelease}
loading={uploadLatestMiniAppRelease.isPending}
onClick={() => uploadLatestMiniAppRelease.mutate()}
>
上传当前版本到微信
</Button>
{miniAppSettings.data?.hasStoredCredentials ? (
<StatusTag tone="success" label="已配置上传凭据" />
) : (
<StatusTag tone="warning" label="未配置上传凭据" />
)}
</Space>
}
>
{miniAppReleases.data?.length ? (
<div className="admin-stack admin-stack-tight">
{miniAppReleases.data.map((task) => (
<MiniAppReleaseCard
key={task.id}
task={task}
uploading={uploadMiniAppRelease.isPending}
onUpload={() => uploadMiniAppRelease.mutate(task.id)}
onStatusChange={(status) => updateMiniAppStatus.mutate({ id: task.id, status })}
/>
))}
</div>
) : (
<EmptyState
compact
title="暂无小程序发布任务"
description="先发布品牌内容,再上传当前版本到微信。"
/>
)}
</AdminSection>
</div>
)}
<Modal
title={confirmAction === "revoke" ? "确认撤回品牌" : "确认发布品牌"}
open={confirmAction !== null}
@@ -584,23 +300,6 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
>
将 v{rollbackVersion} 重新发布为新版本;当前草稿不会被覆盖。
</Modal>
<Modal
title="确认安装行业模板"
open={industryTarget !== null}
onCancel={() => setIndustryTarget(null)}
okButtonProps={{ disabled: !templatePreview.data?.targetPackageVersionId }}
onOk={() =>
industryTarget &&
templatePreview.data?.targetPackageVersionId &&
install.mutate({
key: industryTarget,
versionId: templatePreview.data.targetPackageVersionId,
})
}
confirmLoading={install.isPending}
>
模板会更新当前品牌的草稿结构,不会立即改变已发布的小程序。请安装后核对业务内容与视觉模板。
</Modal>
</QueryState>
);
}
@@ -1,14 +1,11 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { message } from "antd";
import type { BrandTemplateKey } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
const client = createApiClient();
interface MutationOptions {
refresh: () => void;
currentTemplatePackageVersionId: string | null | undefined;
onInstallClose: () => void;
onPublishClose: () => void;
onNoteClear: () => void;
onRollbackClose: () => void;
@@ -16,83 +13,11 @@ interface MutationOptions {
export function usePublicationMutations({
refresh,
onInstallClose,
onPublishClose,
onNoteClear,
onRollbackClose,
currentTemplatePackageVersionId,
}: MutationOptions) {
const queryClient = useQueryClient();
const install = useMutation({
mutationFn: ({ key, versionId }: { key: BrandTemplateKey; versionId: string }) =>
client.installAdminTemplate(key, versionId),
onSuccess: () => {
onInstallClose();
message.success("行业模板已安装");
refresh();
},
});
const upgradeTemplate = useMutation({
mutationFn: (input: {
templatePackageVersionId: string;
expectedContentChecksum: string;
expectedCurrentVersion: string;
expectedCurrentPackageVersionId: string | null;
confirm: true;
preservedBindings: Array<{ key: string; binding: string; action: "preserve" }>;
}) => client.upgradeAdminTemplate(input),
onSuccess: () => {
message.success("行业模板已升级,现有内容未被覆盖");
refresh();
},
});
const rollbackTemplate = useMutation({
mutationFn: (input: { expectedCurrentVersion: string; confirm: true }) =>
client.rollbackAdminTemplate(input),
onSuccess: () => {
message.success("行业模板配置基线已回滚");
refresh();
},
});
const selectVisual = useMutation({
mutationFn: (templatePackageVersionId: string) =>
client.selectAdminTemplateVersion({
templatePackageVersionId,
...(currentTemplatePackageVersionId !== undefined
? { expectedCurrentPackageVersionId: currentTemplatePackageVersionId }
: {}),
confirm: true,
}),
onSuccess: () => {
message.success("模板版本已切换");
refresh();
},
});
const importSample = useMutation<
Awaited<ReturnType<typeof client.importAdminSampleContent>>,
Error,
string | undefined
>({
mutationFn: (templatePackageVersionId) =>
client.importAdminSampleContent({
...(templatePackageVersionId ? { templatePackageVersionId } : {}),
strategy: "missing_only",
confirm: true,
}),
onSuccess: ({ counts, alreadyImported }) => {
if (alreadyImported) {
message.info("该模板包版本的示例内容已导入,未重复创建");
refresh();
return;
}
message.success(
counts.inquiryForms
? "示例内容和客户咨询表单已导入草稿"
: "示例内容已导入草稿,现有客户咨询表单已保留",
);
refresh();
},
});
const publish = useMutation({
mutationFn: (note: string) => client.publishAdminRelease(note || undefined),
onSuccess: () => {
@@ -163,11 +88,6 @@ export function usePublicationMutations({
});
return {
install,
upgradeTemplate,
rollbackTemplate,
selectVisual,
importSample,
publish,
revoke,
rollback,
@@ -20,25 +20,6 @@ export function usePublicationQueries(
queryKey: ["publication-workspace"],
queryFn: () => client.getAdminWorkspace(),
});
const catalog = useQuery<Awaited<ReturnType<typeof client.listPublicTemplates>>>({
queryKey: ["publication-catalog"],
queryFn: () => client.listPublicTemplates(),
});
const packages = useQuery<Awaited<ReturnType<typeof client.listAdminTemplatePackages>>>({
queryKey: ["publication-template-packages"],
queryFn: () => client.listAdminTemplatePackages({ page: 1, pageSize: 100 }),
});
const sample = useQuery<Awaited<ReturnType<typeof client.previewAdminSampleContent>>>({
queryKey: ["publication-sample", workspace.data?.installations[0]?.templatePackageVersionId],
queryFn: () =>
client.previewAdminSampleContent({
...(workspace.data?.installations[0]?.templatePackageVersionId
? { templatePackageVersionId: workspace.data.installations[0].templatePackageVersionId }
: {}),
strategy: "missing_only",
}),
enabled: Boolean(workspace.data),
});
const readiness = useQuery<Awaited<ReturnType<typeof client.getAdminReleaseReadiness>>>({
queryKey: ["publication-readiness"],
queryFn: () => client.getAdminReleaseReadiness(),
@@ -55,12 +36,6 @@ export function usePublicationQueries(
queryKey: ["publication-miniapp-settings"],
queryFn: () => client.getAdminMiniAppSettings(),
});
const templatePreview = useQuery<
Awaited<ReturnType<typeof client.getAdminTemplateUpgradePreview>>
>({
queryKey: ["publication-template-preview"],
queryFn: () => client.getAdminTemplateUpgradePreview(),
});
useEffect(() => {
if (!miniAppSettings.data) return;
@@ -82,31 +57,15 @@ export function usePublicationQueries(
return () => clearInterval(timer);
}, [miniAppReleases]);
const loading = [
brand,
workspace,
catalog,
packages,
readiness,
releases,
miniAppReleases,
miniAppSettings,
].some((query) => query.isLoading);
const error = [
brand,
workspace,
catalog,
packages,
readiness,
releases,
miniAppReleases,
miniAppSettings,
].find((query) => query.isError)?.error;
const loading = [brand, workspace, readiness, releases, miniAppReleases, miniAppSettings].some(
(query) => query.isLoading,
);
const error = [brand, workspace, readiness, releases, miniAppReleases, miniAppSettings].find(
(query) => query.isError,
)?.error;
const retry = () => {
void brand.refetch();
void workspace.refetch();
void catalog.refetch();
void packages.refetch();
void readiness.refetch();
void releases.refetch();
void miniAppReleases.refetch();
@@ -116,14 +75,10 @@ export function usePublicationQueries(
return {
brand,
workspace,
catalog,
packages,
sample,
readiness,
releases,
miniAppReleases,
miniAppSettings,
templatePreview,
loading,
error,
retry,
@@ -20,7 +20,7 @@ export function useOfferingEditor(templateFields: TemplateAdminField[]) {
const templateFieldSection = useMemo<TemplateAdminSection>(
() => ({
key: "offering",
title: "模板内容",
title: "页面方案内容",
description: "",
page: "detail",
target: "offering",
@@ -66,7 +66,7 @@ export function TrustContentPage() {
}
/>
<AdminSection
title="当前模板需要配置的内容"
title="当前页面方案需要配置的内容"
description="标记为「发布必填」的项目需要填写完整后,才能发布小程序。"
>
<TrustRequirementsList
@@ -137,7 +137,7 @@ function sharesMeaningfulOverlap(label: string, token: string): boolean {
return false;
}
// 列表按模板声明的类型顺序排列,与「当前模板需要配置的内容」保持一致。
// 列表按页面方案声明的类型顺序排列,与「当前页面方案需要配置的内容」保持一致。
export function sortTrustContentByTypeOrder(
items: TrustContent[],
availableTypes: TrustTypeOption[],
+38
View File
@@ -156,6 +156,44 @@ body {
height: 100%;
}
.admin-full-width {
width: 100%;
}
.admin-choice-card.ant-radio-button-wrapper {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 6px;
width: 100%;
height: 100%;
min-height: 104px;
padding: 16px;
white-space: normal;
line-height: 1.5;
}
.admin-choice-card--wide.ant-radio-button-wrapper {
min-height: 0;
}
.admin-choice-card.ant-radio-button-wrapper > span:last-child {
display: block;
width: 100%;
}
.admin-choice-card .ant-radio-button {
display: none;
}
.admin-choice-card span {
color: var(--admin-text-secondary);
}
.admin-choice-card strong {
color: var(--admin-text);
}
.admin-content {
flex: 1;
padding: 24px;
+22
View File
@@ -4,12 +4,20 @@ import { createElement } from "react";
import { renderToString } from "react-dom/server";
import { MemoryRouter, Route, Routes, resolvePath } from "react-router-dom";
import { AdminOverviewRedirect, AdminRouter } from "../src/app/AdminRouter.ts";
import {
canCreateBrand,
createBrandFallbackPath,
createBrandRouteElement,
} from "../src/app/route-access.ts";
test("后台父路由正确匹配所有菜单及深层链接", () => {
const pages = [
"overview",
"publication",
"brand",
"brands",
"brands/new",
"page-scheme",
"trust",
"services",
"inquiries",
@@ -51,3 +59,17 @@ test("默认与无效地址的概览重定向为绝对地址且替换历史记
assert.equal(resolvePath(redirect.props.to, pathname).pathname, "/admin/overview");
}
});
test("只有品牌负责人可以进入创建品牌路由", () => {
assert.equal(canCreateBrand("owner"), true);
for (const role of ["admin", "editor", "platform-admin"]) {
assert.equal(canCreateBrand(role), false);
}
const content = createElement("h1", null, "create-brand");
assert.equal(createBrandRouteElement("owner", content), content);
const denied = createBrandRouteElement("admin", content);
assert.equal(denied.props.to, createBrandFallbackPath);
assert.equal(denied.props.replace, true);
});
@@ -0,0 +1,2 @@
ALTER TABLE "BrandProfile" ALTER COLUMN "slug" DROP DEFAULT;
ALTER TABLE "BrandProfile" ALTER COLUMN "templateKey" DROP DEFAULT;
+2 -2
View File
@@ -35,9 +35,9 @@ enum FulfillmentType {
model BrandProfile {
id String @id @default(uuid())
slug String @unique @default("default-brand")
slug String @unique
name String
templateKey String @default("food")
templateKey String
tagline String?
description String?
avatarUrl String?
+52 -20
View File
@@ -1,9 +1,20 @@
import { existsSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { PrismaClient, type Prisma } from "@prisma/client";
import type { TemplatePackageManifest } from "@personal-brand/config";
import bcrypt from "bcryptjs";
import { buildBrandReleaseSnapshot } from "../src/brand-release.service.js";
import { latestTemplateVersion } from "../src/template-version-order.js";
const prisma = new PrismaClient();
const seedAssetsDirectory = path.join(path.dirname(fileURLToPath(import.meta.url)), "assets");
function seedMediaExists(url: unknown): boolean {
if (typeof url !== "string" || !url) return false;
if (!url.startsWith("/media/seed/")) return true;
return existsSync(path.join(seedAssetsDirectory, path.basename(url)));
}
const runtimeImages = {
doors: [
@@ -48,7 +59,7 @@ interface RuntimeSeedTemplate {
const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTemplate> = {
personal: {
templateKey: "personal",
visualTemplateKey: "linjing-editorial",
visualTemplateKey: "atelier-solopreneur",
brandConfig: {
templateData: { designPhilosophy: "先厘清问题,再设计表达" },
title: "品牌策略顾问",
@@ -299,7 +310,7 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
phone: "186-0218-9908",
wechat: "LIN-ATELIER-2024",
studioAddress: "上海市静安区威海路设计中心 A 座 / 杭州良渚研造工坊",
avatarUrl: "/media/seed/personal-avatar.jpg",
avatarUrl: "/media/seed/founder-portrait.jpg",
profilePresentation: {
coverage: [
{
@@ -718,23 +729,42 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
data: { isEnabled: false },
});
}
const incompleteOfferings = await prisma.offering.findMany({
where: { brandId, isEnabled: true, coverUrl: null },
select: { id: true, name: true },
});
for (const [index, item] of incompleteOfferings.entries()) {
const image = offerings[index % offerings.length]?.image;
if (!image) throw new Error("Development fixture has no offering image");
// 旧模板迁移后可能留下数组形态的 config 或失效媒体引用。开发种子只修复结构,
// 不删除品牌内容,也不擅自重新启用已停用的业务提供项。
const allOfferings = await prisma.offering.findMany({ where: { brandId } });
const fallbackImage = offerings[0]?.image;
if (!fallbackImage) throw new Error("Development fixture has no offering image");
for (const offering of allOfferings) {
const rawConfig = offering.config;
const config =
rawConfig && typeof rawConfig === "object" && !Array.isArray(rawConfig)
? (rawConfig as Record<string, unknown>)
: {};
const media = config.media;
const hasValidMedia =
Array.isArray(media) &&
media.length > 0 &&
media.every(
(entry) =>
entry &&
typeof entry === "object" &&
!Array.isArray(entry) &&
seedMediaExists((entry as Record<string, unknown>).url),
);
const hasValidCover = seedMediaExists(offering.coverUrl);
const coverUrl = hasValidCover ? (offering.coverUrl as string) : fallbackImage;
if (hasValidCover && hasValidMedia && !Array.isArray(rawConfig)) continue;
await prisma.offering.update({
where: { id: item.id },
where: { id: offering.id },
data: {
coverUrl: image,
coverUrl,
config: {
categoryKey: "custom",
keywords: [],
media: [{ url: image, alt: item.name, type: "image" }],
sections: [],
},
...config,
...(config.categoryKey === undefined ? { categoryKey: "custom" } : {}),
...(Array.isArray(config.keywords) ? {} : { keywords: [] }),
media: [{ url: coverUrl, alt: offering.name, type: "image" }],
...(Array.isArray(config.sections) ? {} : { sections: [] }),
} as Prisma.InputJsonValue,
},
});
}
@@ -812,10 +842,12 @@ async function ensureTemplateInstallation(brandId: string): Promise<void> {
throw new Error("Development brand installation does not satisfy the template contract");
return;
}
const packageVersion = await prisma.templatePackageVersion.findFirst({
where: { packageKey: visualKey, status: "published" },
orderBy: { importedAt: "desc" },
});
// 版本升级必须按 SemVer 判断最新版,导入时间只用于同版本排序。
const packageVersion = latestTemplateVersion(
await prisma.templatePackageVersion.findMany({
where: { packageKey: visualKey, status: "published" },
}),
);
if (!packageVersion)
throw new Error(`Development brand requires a published package version: ${visualKey}`);
const configSnapshot = packageVersion.manifestSnapshot as Prisma.InputJsonValue;
+21
View File
@@ -11,6 +11,7 @@ import {
MinLength,
Matches,
Max,
MaxLength,
Min,
} from "class-validator";
import { brandTemplateKeys } from "@personal-brand/config";
@@ -53,6 +54,26 @@ export class CreateBrandMemberDto {
@IsIn(["owner", "editor"]) role!: "owner" | "editor";
}
export class CreateBrandDto {
@IsString()
@MinLength(1)
@MaxLength(80)
name!: string;
@IsString()
@Matches(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, {
message: "slug 只能包含小写字母、数字和连字符",
})
@MaxLength(80)
slug!: string;
@IsIn(brandTemplateKeys)
businessType!: BrandTemplateKey;
@IsUUID()
templatePackageVersionId!: string;
}
export class ChangeAdminPasswordDto {
@IsString() currentPassword!: string;
@IsString() @MinLength(8) newPassword!: string;
@@ -3,7 +3,8 @@ import { Body, Controller, Get, Param, Patch, Post, Req, Res } from "@nestjs/com
import type { FastifyReply, FastifyRequest } from "fastify";
import { setAdminSessionCookie } from "../../admin-session-cookie.js";
import { requireAdminIdentity } from "../../admin-access.identity.js";
import { CreateBrandMemberDto, UpdateBrandMemberDto } from "../../admin.dto.js";
import { signIdentity } from "../../auth.js";
import { CreateBrandDto, CreateBrandMemberDto, UpdateBrandMemberDto } from "../../admin.dto.js";
import { TenantService } from "./tenant.service.js";
@AdminBrand()
@@ -11,10 +12,38 @@ import { TenantService } from "./tenant.service.js";
export class TenantController {
constructor(private readonly tenants: TenantService) {}
@AdminRoles(["owner"])
@Get("creation-options")
async creationOptions(): Promise<unknown> {
return this.tenants.getCreationOptions();
}
@AdminRoles(["owner"])
@Post()
async create(
@Req() request: FastifyRequest,
@Body() body: CreateBrandDto,
@Res({ passthrough: true }) reply: FastifyReply,
): Promise<{ role: string; brand: unknown }> {
const identity = adminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
const brand = await this.tenants.createBrand(identity, body, requestId);
setAdminSessionCookie(
reply,
signIdentity({
subject: identity.subject,
brandId: brand.id,
role: "admin",
...(identity.tokenVersion === undefined ? {} : { tokenVersion: identity.tokenVersion }),
}),
);
return { role: "owner", brand };
}
@AdminRoles(["owner", "admin", "platform-admin"])
@Get("members")
async listMembers(@Req() request: FastifyRequest): Promise<unknown> {
const current = this.adminIdentity(request);
const current = adminIdentity(request);
return this.tenants.listMembers(current.brandId);
}
@@ -24,7 +53,7 @@ export class TenantController {
@Req() request: FastifyRequest,
@Body() body: CreateBrandMemberDto,
): Promise<unknown> {
const actor = this.adminIdentity(request);
const actor = adminIdentity(request);
return this.tenants.createMember(actor.brandId, body);
}
@@ -35,13 +64,13 @@ export class TenantController {
@Param("id") id: string,
@Body() body: UpdateBrandMemberDto,
): Promise<unknown> {
const actor = this.adminIdentity(request);
const actor = adminIdentity(request);
return this.tenants.updateMember(actor.brandId, actor.subject, id, body);
}
@Get()
async list(@Req() request: FastifyRequest): Promise<unknown> {
const identity = this.adminIdentity(request);
const identity = adminIdentity(request);
return this.tenants.listMemberships(identity.subject);
}
@@ -51,13 +80,13 @@ export class TenantController {
@Param("brandId") brandId: string,
@Res({ passthrough: true }) reply: FastifyReply,
): Promise<{ role: string; brand: unknown }> {
const identity = this.adminIdentity(request);
const identity = adminIdentity(request);
const result = await this.tenants.switchBrand(identity, brandId);
setAdminSessionCookie(reply, result.token);
return { role: result.role, brand: result.brand };
}
}
private adminIdentity(request: FastifyRequest) {
return requireAdminIdentity(request);
}
function adminIdentity(request: FastifyRequest) {
return requireAdminIdentity(request);
}
+94 -2
View File
@@ -5,15 +5,107 @@ import {
Injectable,
} from "@nestjs/common";
import bcrypt from "bcryptjs";
import { Prisma } from "@prisma/client";
import { getBrandTemplate } from "@personal-brand/config";
import { PrismaService } from "../../prisma.service.js";
import { signIdentity } from "../../auth.js";
import type { CreateBrandMemberDto, UpdateBrandMemberDto } from "../../admin.dto.js";
import type {
CreateBrandDto,
CreateBrandMemberDto,
UpdateBrandMemberDto,
} from "../../admin.dto.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
type AdminIdentity = { subject: string; brandId: string; tokenVersion?: number };
@Injectable()
export class TenantService {
constructor(private readonly prisma: PrismaService) {}
constructor(
private readonly prisma: PrismaService,
private readonly templateWorkspace: TemplateWorkspaceService,
) {}
async getCreationOptions() {
const catalog = await this.templateWorkspace.getPageSchemeCatalog();
// 创建品牌只应从每个页面方案的最新已发布版本开始;旧版本仍可在页面方案页显式切换。
return {
...catalog,
pageSchemes: catalog.pageSchemes.filter((scheme) => scheme.isLatestForPackage),
};
}
async createBrand(identity: AdminIdentity, body: CreateBrandDto, requestId?: string) {
const template = getBrandTemplate(body.businessType);
if (!template) throw new BadRequestException("业务类型不存在");
const name = body.name.trim();
const slug = body.slug.trim();
if (!name || !slug) throw new BadRequestException("品牌名称和小程序地址标识不能为空");
const packageVersion = await this.templateWorkspace.resolveInstallablePackageVersion(
body.businessType,
body.templatePackageVersionId,
);
try {
return await this.prisma.$transaction(async (tx) => {
const brand = await tx.brandProfile.create({
data: {
name,
slug,
templateKey: body.businessType,
config: {},
},
});
await tx.brandTemplateInstallation.create({
data: {
brandId: brand.id,
templateKey: body.businessType,
templateVersion: packageVersion.version,
templatePackageVersionId: packageVersion.id,
contentChecksum: packageVersion.contentChecksum,
configSnapshot: packageVersion.manifestSnapshot as Prisma.InputJsonValue,
},
});
await tx.brandFieldDefinition.createMany({
data: template.fields.map(({ scope, key, label, type, required }, sortOrder) => ({
brandId: brand.id,
scope,
key,
label,
type,
required,
sortOrder,
source: "core",
})),
});
await tx.brandMembership.create({
data: {
adminUserId: identity.subject,
brandId: brand.id,
role: "owner",
isEnabled: true,
},
});
await tx.templatePackageAuditLog.create({
data: {
templatePackageVersionId: packageVersion.id,
actorId: identity.subject,
action: "brand_created",
...(requestId ? { requestId } : {}),
metadata: {
brandId: brand.id,
businessType: body.businessType,
slug: brand.slug,
},
},
});
return brand;
});
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002")
throw new ConflictException("小程序地址标识已被使用,请更换后重试");
throw error;
}
}
listMembers(brandId: string) {
return this.prisma.brandMembership.findMany({
@@ -10,6 +10,13 @@ import { requireAdminIdentity } from "../../admin-access.identity.js";
class AdminTemplateController {
constructor(private readonly templateWorkspace: TemplateWorkspaceService) {}
@AdminRoles(["owner", "admin", "platform-admin"])
@Get("template/options")
options(@Req() request: FastifyRequest): Promise<unknown> {
return this.templateWorkspace.getPageSchemeOptions(requireAdminIdentity(request).brandId);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@Get("template/preview")
preview(@Req() request: FastifyRequest): Promise<unknown> {
return this.templateWorkspace.preview(requireAdminIdentity(request).brandId);
+60
View File
@@ -0,0 +1,60 @@
const SEMVER_PATTERN =
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
const fallbackVersionCollator = new Intl.Collator("en", {
numeric: true,
sensitivity: "base",
});
type VersionOrderable = {
version: string;
importedAt?: Date;
createdAt?: Date;
};
function comparePrerelease(left: string, right: string) {
if (left === right) return 0;
if (!left) return 1;
if (!right) return -1;
const leftParts = left.split(".");
const rightParts = right.split(".");
for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {
const leftPart = leftParts[index];
const rightPart = rightParts[index];
if (leftPart === undefined) return -1;
if (rightPart === undefined) return 1;
if (leftPart === rightPart) continue;
const leftNumeric = /^\d+$/.test(leftPart);
const rightNumeric = /^\d+$/.test(rightPart);
if (leftNumeric && rightNumeric) return Number(leftPart) - Number(rightPart);
if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;
return leftPart.localeCompare(rightPart);
}
return 0;
}
export function compareTemplateVersions(left: string, right: string) {
const leftMatch = SEMVER_PATTERN.exec(left);
const rightMatch = SEMVER_PATTERN.exec(right);
if (!leftMatch || !rightMatch) return fallbackVersionCollator.compare(left, right);
for (let index = 1; index <= 3; index += 1) {
const difference = Number(leftMatch[index]) - Number(rightMatch[index]);
if (difference !== 0) return difference;
}
return comparePrerelease(leftMatch[4] ?? "", rightMatch[4] ?? "");
}
/** 按 SemVer 从新到旧排序;同版本使用导入和创建时间保证顺序稳定。 */
export function compareTemplateVersionOrder(left: VersionOrderable, right: VersionOrderable) {
const versionOrder = compareTemplateVersions(right.version, left.version);
if (versionOrder !== 0) return versionOrder;
const importedOrder = (right.importedAt?.getTime() ?? 0) - (left.importedAt?.getTime() ?? 0);
if (importedOrder !== 0) return importedOrder;
return (right.createdAt?.getTime() ?? 0) - (left.createdAt?.getTime() ?? 0);
}
export function latestTemplateVersion<T extends VersionOrderable>(versions: readonly T[]) {
return versions.reduce<T | undefined>((latest, current) => {
if (!latest || compareTemplateVersionOrder(current, latest) < 0) return current;
return latest;
}, undefined);
}
+117 -11
View File
@@ -3,6 +3,7 @@ import type { TemplatePackageVersion } from "@prisma/client";
import { Prisma } from "@prisma/client";
import {
type BrandTemplateKey,
brandTemplateKeys,
getBrandTemplate,
getVisualTemplate,
getVisualTemplateManifest,
@@ -14,10 +15,99 @@ import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.j
import type { RollbackTemplateDto, UpgradeTemplateDto } from "./admin.dto.js";
import { PrismaService } from "./prisma.service.js";
import { recordTemplateOperationFailure } from "./modules/admin/template-operation-failure.js";
import { compareTemplateVersions, latestTemplateVersion } from "./template-version-order.js";
@Injectable()
export class TemplateWorkspaceService {
constructor(private readonly prisma: PrismaService) {}
async getPageSchemeCatalog() {
const versions = await this.prisma.templatePackageVersion.findMany({
where: { status: "published" },
orderBy: [{ importedAt: "desc" }, { createdAt: "desc" }],
});
const candidates = versions.flatMap((version) => {
const manifest = record(version.manifestSnapshot);
const visualTemplateKey = manifest.visualTemplateKey;
if (
manifest.packageKey !== version.packageKey ||
manifest.version !== version.version ||
typeof visualTemplateKey !== "string" ||
visualTemplateKey !== version.packageKey
)
return [];
const visualTemplate = getVisualTemplate(visualTemplateKey);
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
if (!visualTemplate || !visualManifest) return [];
const supportedBusinessTypes = Array.isArray(manifest.supportedIndustryTemplates)
? manifest.supportedIndustryTemplates.filter(
(value): value is BrandTemplateKey =>
typeof value === "string" &&
brandTemplateKeys.includes(value) &&
Boolean(getBrandTemplate(value)),
)
: [];
if (
supportedBusinessTypes.length === 0 ||
supportedBusinessTypes.some(
(businessType) => !isVisualTemplateCompatible(visualTemplate, businessType),
) ||
validateTemplatePackageManifest(manifest).length > 0
)
return [];
return [
{
templatePackageVersionId: version.id,
packageKey: version.packageKey,
name: version.displayName,
description: visualManifest.description,
version: version.version,
supportedBusinessTypes,
},
];
});
const latestByPackage = new Map<string, string>();
for (const candidate of candidates) {
const latestVersion = latestByPackage.get(candidate.packageKey);
if (!latestVersion || compareTemplateVersions(candidate.version, latestVersion) > 0) {
latestByPackage.set(candidate.packageKey, candidate.version);
}
}
const pageSchemes = candidates.map(({ packageKey, ...candidate }) => ({
...candidate,
isLatestForPackage: latestByPackage.get(packageKey) === candidate.version,
}));
return {
businesses: brandTemplateKeys.map((key) => {
const template = getBrandTemplate(key);
if (!template) throw new BadRequestException("业务类型配置不完整");
return { key, name: template.name, description: template.description };
}),
pageSchemes,
};
}
async getPageSchemeOptions(brandId: string) {
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true },
});
const template = brand ? getBrandTemplate(brand.templateKey) : undefined;
if (!brand || !template) throw new BadRequestException("品牌业务类型无效");
const catalog = await this.getPageSchemeCatalog();
return {
business: {
key: template.key,
name: template.name,
description: template.description,
},
pageSchemes: catalog.pageSchemes.filter((scheme) =>
scheme.supportedBusinessTypes.includes(template.key),
),
};
}
async getTrustContentTypes(brandId: string): Promise<string[]> {
const installation = await this.prisma.brandTemplateInstallation.findUnique({
where: { brandId },
@@ -124,6 +214,7 @@ export class TemplateWorkspaceService {
select: { templateKey: true },
}),
]);
if (!brand) throw new BadRequestException("品牌不存在");
// 一个品牌只使用一个行业模板(BrandProfile.templateKey 即身份)。安装只允许补建当前模板的版本台账,
// 不得换成别的行业模板,否则会出现「身份是 A、台账是 B」的漂移,并把发布快照接到不适配的视觉模板上。
const currentTemplate = brand?.templateKey ? getBrandTemplate(brand.templateKey) : undefined;
@@ -147,15 +238,11 @@ export class TemplateWorkspaceService {
)
throw new BadRequestException("当前视觉模板不适配行业模板");
return this.prisma.$transaction(async (tx) => {
await tx.brandProfile.update({
where: { id: brandId },
data: { templateKey },
});
const installation = await tx.brandTemplateInstallation.create({
data: {
brandId,
templateKey,
templateVersion: template.version,
templateVersion: packageVersion.version,
templatePackageVersionId: packageVersion.id,
contentChecksum: packageVersion.contentChecksum,
configSnapshot: packageVersion.manifestSnapshot as Prisma.InputJsonValue,
@@ -176,7 +263,7 @@ export class TemplateWorkspaceService {
return { installation, template, visualTemplate: visualManifest };
});
}
private async resolveInstallablePackageVersion(
async resolveInstallablePackageVersion(
templateKey: BrandTemplateKey,
templatePackageVersionId: string,
): Promise<TemplatePackageVersion> {
@@ -195,7 +282,7 @@ export class TemplateWorkspaceService {
!Array.isArray(manifest.supportedIndustryTemplates) ||
!manifest.supportedIndustryTemplates.includes(templateKey)
) {
throw new BadRequestException("模板包版本与行业或视觉模板不匹配");
throw new BadRequestException("页面方案与所选业务类型不兼容,请重新选择");
}
if (validateTemplatePackageManifest(manifest).length)
throw new BadRequestException("模板包版本不符合统一模板契约");
@@ -253,11 +340,17 @@ export class TemplateWorkspaceService {
if (!target || target.status !== "published")
throw new BadRequestException("指定模板包版本不存在或未发布");
const manifest = record(target.manifestSnapshot) as unknown as TemplatePackageManifest;
const visualTemplate =
typeof manifest.visualTemplateKey === "string"
? getVisualTemplate(manifest.visualTemplateKey)
: undefined;
if (
target.packageKey !== manifest.packageKey ||
target.version !== manifest.version ||
manifest.packageKey !== manifest.visualTemplateKey ||
!manifest.supportedIndustryTemplates?.includes(brand.templateKey) ||
!visualTemplate ||
!isVisualTemplateCompatible(visualTemplate, brand.templateKey) ||
validateTemplatePackageManifest(manifest).length
)
throw new BadRequestException("指定模板包版本不符合当前品牌的统一模板契约");
@@ -329,15 +422,28 @@ export class TemplateWorkspaceService {
).visualTemplateKey;
if (typeof visualTemplateKey !== "string")
throw new BadRequestException("已安装模板版本缺少 visualTemplateKey 声明");
const [currentPackage, targetPackage] = await Promise.all([
const [currentPackage, publishedTargets] = await Promise.all([
this.prisma.templatePackageVersion.findUnique({
where: { id: installation.templatePackageVersionId },
}),
this.prisma.templatePackageVersion.findFirst({
this.prisma.templatePackageVersion.findMany({
where: { packageKey: visualTemplateKey, status: "published" },
orderBy: { importedAt: "desc" },
}),
]);
const targetPackage = latestTemplateVersion(
publishedTargets.filter((candidate) => {
const manifest = record(candidate.manifestSnapshot);
return (
candidate.packageKey === visualTemplateKey &&
manifest.packageKey === candidate.packageKey &&
manifest.version === candidate.version &&
manifest.visualTemplateKey === visualTemplateKey &&
Array.isArray(manifest.supportedIndustryTemplates) &&
manifest.supportedIndustryTemplates.includes(installation.templateKey) &&
validateTemplatePackageManifest(manifest).length === 0
);
}),
);
if (!currentPackage) throw new BadRequestException("当前安装引用的模板包版本不存在");
if (
currentPackage.packageKey !== visualTemplateKey ||
@@ -507,7 +613,7 @@ export class TemplateWorkspaceService {
})
.sort();
if (JSON.stringify(expectedConflicts) !== JSON.stringify(preserved))
throw new ConflictException("冲突处理与当前预览不一致,请重新预览并逐项确认");
throw new ConflictException("冲突处理与当前预览不一致,请重新预览后再升级");
const manifest = record(target.manifestSnapshot);
if (
target.packageKey !==
+10
View File
@@ -12,11 +12,20 @@ import { AdminCapabilityController } from "../src/modules/workspace/admin-capabi
import { AdminOfferingController } from "../src/modules/workspace/admin-offering.controller.js";
import { AdminInquiryController } from "../src/modules/workspace/admin-inquiry.controller.js";
import { AdminTemplatePackageController } from "../src/modules/admin/admin-template-package.controller.js";
import { TenantController } from "../src/modules/tenant/tenant.controller.js";
const expectedRoutes = new Set([
"GET /admin/brands/creation-options",
"POST /admin/brands",
"GET /admin/brands/members",
"POST /admin/brands/members",
"PATCH /admin/brands/members/:id",
"GET /admin/brands",
"POST /admin/brands/:brandId/switch",
"GET /admin/workspace",
"GET /admin/workspace/preview",
"POST /admin/workspace/install",
"GET /admin/workspace/template/options",
"GET /admin/workspace/template/preview",
"POST /admin/workspace/template/upgrade",
"POST /admin/workspace/template/rollback",
@@ -50,6 +59,7 @@ const expectedRoutes = new Set([
test("refactored admin controllers preserve their declared API routes", () => {
const controllers = [
TenantController,
AdminWorkspacePreviewController,
AdminTemplateController,
AdminCapabilityController,
+481 -32
View File
@@ -137,11 +137,12 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
const baseline = JSON.parse(empty.body);
assert.deepEqual(baseline.items.map((item) => item.packageKey).sort(), [
"acheng-campus-food",
"atelier-solopreneur",
"linjing-editorial",
]);
const linjingVersion = baseline.items.find((item) => item.packageKey === "linjing-editorial");
assert.ok(linjingVersion);
assert.equal(linjingVersion.version, "1.0.6");
assert.equal(linjingVersion.version, "1.0.7");
const linjingPreview = await request(
`/admin/templates/${linjingVersion.id}/preview?industry=doors`,
{ headers },
@@ -380,15 +381,12 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
assert.equal(rejectedImport.statusCode, 400, rejectedImport.body);
assert.match(JSON.parse(rejectedImport.body).error.message, /previewFixture/);
assert.equal(await prisma.templatePackageVersion.count(), versionCount);
const archive = createTemplateArchive("atelier-solopreneur");
const multipart = multipartArchive(archive);
const imported = await request("/admin/templates/import", {
method: "POST",
headers: { ...headers, ...multipart.headers },
rawPayload: multipart.payload,
// 预览只允许使用平台当前已部署的精确 renderer 版本;复用 prepare 阶段导入的基线版本,
// 避免测试自造一个 renderer 尚未部署的新版本。
const baselineVersion = await prisma.templatePackageVersion.findFirstOrThrow({
where: { packageKey: "atelier-solopreneur", version: "1.3.2", status: "published" },
});
assert.equal(imported.statusCode, 201);
const versionId = JSON.parse(imported.body).version.id;
const versionId = baselineVersion.id;
const businessCounts = () =>
Promise.all([
@@ -625,21 +623,17 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
assert.match(JSON.parse(incompatible.body).error.message, /不支持所选行业/);
assert.deepEqual(await businessCounts(), before);
const repeatedPublish = await request(`/admin/templates/${versionId}/publish`, {
method: "POST",
headers,
});
assert.equal(repeatedPublish.statusCode, 201);
assert.equal(JSON.parse(repeatedPublish.body).changed, false);
const retired = await request(`/admin/templates/${versionId}/retire`, {
method: "POST",
headers,
});
assert.equal(retired.statusCode, 409);
const published = await request(`/admin/templates/${versionId}/publish`, {
method: "POST",
headers,
});
assert.equal(published.statusCode, 201);
const retiredAfterPublish = await request(`/admin/templates/${versionId}/retire`, {
method: "POST",
headers,
});
assert.equal(retiredAfterPublish.statusCode, 201);
assert.equal(retired.statusCode, 201);
const retiredPreview = await request(`/admin/templates/${versionId}/preview?industry=personal`, {
headers,
});
@@ -1988,7 +1982,7 @@ test("visual template compatibility is enforced by catalog, preview, and version
}
assert.deepEqual(
visuals.find((visual) => visual.key === "linjing-editorial").supportedIndustryTemplates,
["personal", "doors"],
["doors"],
);
const incompatiblePreview = await request(
"/public/templates/preview?industry=food&visual=linjing-editorial",
@@ -2149,6 +2143,337 @@ test("seeded public workspaces keep personal, food, and doors brands isolated",
assert.equal(new Set(workspaces.map((workspace) => workspace.brand.id)).size, 2);
});
test("brand creation options are owner-scoped", async () => {
const unauthorized = await request("/admin/brands/creation-options");
assert.equal(unauthorized.statusCode, 401);
const customerForbidden = await request("/admin/brands/creation-options", {
headers: { authorization: `Bearer ${customerToken}` },
});
assert.equal(customerForbidden.statusCode, 403);
const ownerLogin = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const ownerToken = sessionToken(ownerLogin);
const editorUser = await prisma.adminUser.create({
data: {
username: `creation-options-editor-${randomUUID()}`,
passwordHash: "unused",
displayName: "建品牌权限测试编辑",
mustChangePassword: false,
},
});
const editorMembership = await prisma.brandMembership.create({
data: { adminUserId: editorUser.id, brandId, role: "editor" },
});
try {
const editorToken = signIdentity({
subject: editorUser.id,
brandId,
role: "admin",
tokenVersion: editorUser.tokenVersion,
});
const editorForbidden = await request("/admin/brands/creation-options", {
headers: { authorization: `Bearer ${editorToken}` },
});
assert.equal(editorForbidden.statusCode, 403);
const response = await request("/admin/brands/creation-options", {
headers: { authorization: `Bearer ${ownerToken}` },
});
assert.equal(response.statusCode, 200, response.body);
const options = JSON.parse(response.body);
assert.deepEqual(options.businesses.map((business) => business.key).sort(), [
"doors",
"food",
"personal",
]);
assert.ok(options.businesses.every((business) => business.name && business.description));
// 创建品牌只暴露每个页面方案的最新版本,避免新品牌起步在旧版本上。
assert.equal(options.pageSchemes.length, 3, JSON.stringify(options.pageSchemes));
const linjingScheme = options.pageSchemes.find((scheme) => scheme.name.includes("林境"));
assert.ok(linjingScheme);
assert.equal(linjingScheme.version, "1.0.7");
assert.deepEqual(linjingScheme.supportedBusinessTypes, ["doors"]);
assert.equal(linjingScheme.isLatestForPackage, true);
const atelierScheme = options.pageSchemes.find((scheme) => scheme.name.includes("工坊"));
assert.ok(atelierScheme);
assert.equal(atelierScheme.version, "1.3.2");
assert.deepEqual(atelierScheme.supportedBusinessTypes, ["personal"]);
assert.equal(
options.pageSchemes.some(
(scheme) =>
scheme.supportedBusinessTypes.includes("personal") &&
scheme.supportedBusinessTypes.includes("doors"),
),
false,
"页面方案不应同时兼容 personal 和 doors",
);
assert.equal(JSON.stringify(options).includes("visualTemplateKey"), false);
assert.equal(JSON.stringify(options).includes("packageKey"), false);
} finally {
await prisma.brandMembership.delete({ where: { id: editorMembership.id } });
await prisma.adminUser.delete({ where: { id: editorUser.id } });
}
});
test("owner can create an isolated brand", async () => {
const startedAt = new Date();
const suffix = randomUUID().slice(0, 8);
const personalSlug = `atelier-created-${suffix}`;
const doorsSlug = `linjing-created-${suffix}`;
// 集成 fixture 必须锁定精确版本,避免导入时间或历史版本影响测试语义。
const atelier = await prisma.templatePackageVersion.findFirstOrThrow({
where: {
packageKey: "atelier-solopreneur",
version: "1.3.2",
status: "published",
},
});
const linjing = await prisma.templatePackageVersion.findFirstOrThrow({
where: {
packageKey: "linjing-editorial",
version: "1.0.7",
status: "published",
},
});
const ownerLogin = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const ownerToken = sessionToken(ownerLogin);
const ownerIdentity = readIdentity(ownerToken);
const unauthorizedPayload = {
name: "未授权品牌",
slug: `unauthorized-${suffix}`,
businessType: "personal",
templatePackageVersionId: atelier.id,
};
const unauthorized = await request("/admin/brands", {
method: "POST",
payload: unauthorizedPayload,
});
assert.equal(unauthorized.statusCode, 401);
const customerForbidden = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: unauthorizedPayload,
});
assert.equal(customerForbidden.statusCode, 403);
const incompatible = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "不兼容品牌",
slug: `incompatible-${suffix}`,
businessType: "personal",
templatePackageVersionId: linjing.id,
},
});
assert.equal(incompatible.statusCode, 400, incompatible.body);
assert.match(errorMessage(incompatible.body), /业务类型|页面方案|兼容/);
assert.equal(await prisma.brandProfile.count({ where: { slug: `incompatible-${suffix}` } }), 0);
try {
const created = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "新建独立工坊",
slug: personalSlug,
businessType: "personal",
templatePackageVersionId: atelier.id,
},
});
assert.equal(created.statusCode, 201, created.body);
const createdBrand = JSON.parse(created.body).brand;
assert.equal(createdBrand.slug, personalSlug);
assert.equal(createdBrand.templateKey, "personal");
const profile = await prisma.brandProfile.findUniqueOrThrow({
where: { id: createdBrand.id },
});
assert.equal(profile.templateKey, "personal");
assert.deepEqual(profile.config, {});
const installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId: createdBrand.id },
});
assert.equal(installation.templateKey, "personal");
assert.equal(installation.templatePackageVersionId, atelier.id);
assert.equal(installation.templateVersion, atelier.version);
assert.ok(
(await prisma.brandFieldDefinition.count({ where: { brandId: createdBrand.id } })) > 0,
);
const membership = await prisma.brandMembership.findUniqueOrThrow({
where: {
adminUserId_brandId: {
adminUserId: ownerIdentity.subject,
brandId: createdBrand.id,
},
},
});
assert.equal(membership.role, "owner");
assert.equal(membership.isEnabled, true);
const audit = await prisma.templatePackageAuditLog.findFirstOrThrow({
where: {
templatePackageVersionId: atelier.id,
actorId: ownerIdentity.subject,
action: "brand_created",
createdAt: { gte: startedAt },
},
orderBy: { createdAt: "desc" },
});
assert.equal(audit.metadata.brandId, createdBrand.id);
assert.equal(audit.metadata.businessType, "personal");
const newCookie = sessionToken(created);
assert.equal(readIdentity(newCookie).brandId, createdBrand.id);
const current = await request("/admin/config/brand", {
headers: { authorization: `Bearer ${newCookie}` },
});
assert.equal(current.statusCode, 200, current.body);
assert.equal(JSON.parse(current.body).id, createdBrand.id);
const duplicate = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "重复地址品牌",
slug: personalSlug,
businessType: "personal",
templatePackageVersionId: atelier.id,
},
});
assert.equal(duplicate.statusCode, 409, duplicate.body);
assert.equal(await prisma.brandProfile.count({ where: { slug: personalSlug } }), 1);
const invalidBusinessType = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "非法业务品牌",
slug: `invalid-business-${suffix}`,
businessType: "consulting",
templatePackageVersionId: atelier.id,
},
});
assert.equal(invalidBusinessType.statusCode, 400);
const incompatible = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "不兼容页面方案品牌",
slug: `incompatible-${suffix}`,
businessType: "personal",
templatePackageVersionId: linjing.id,
},
});
assert.equal(incompatible.statusCode, 400, incompatible.body);
assert.equal(await prisma.brandProfile.count({ where: { slug: `incompatible-${suffix}` } }), 0);
const doorsCreated = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "新建林境门窗",
slug: doorsSlug,
businessType: "doors",
templatePackageVersionId: linjing.id,
},
});
assert.equal(doorsCreated.statusCode, 201, doorsCreated.body);
const doorsBrand = JSON.parse(doorsCreated.body).brand;
const doorsInstallation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId: doorsBrand.id },
});
assert.equal(doorsInstallation.templateKey, "doors");
assert.equal(doorsInstallation.templatePackageVersionId, linjing.id);
} finally {
await prisma.templatePackageAuditLog.deleteMany({
where: {
actorId: ownerIdentity.subject,
action: "brand_created",
createdAt: { gte: startedAt },
},
});
await prisma.brandProfile.deleteMany({
where: { slug: { in: [personalSlug, doorsSlug] } },
});
}
});
test("page scheme options are readable by owners and admins only", async () => {
const unauthorized = await request("/admin/workspace/template/options");
assert.equal(unauthorized.statusCode, 401);
const customerForbidden = await request("/admin/workspace/template/options", {
headers: { authorization: `Bearer ${customerToken}` },
});
assert.equal(customerForbidden.statusCode, 403);
const ownerLogin = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const ownerToken = sessionToken(ownerLogin);
const members = [];
try {
for (const role of ["admin", "editor"]) {
const user = await prisma.adminUser.create({
data: {
username: `page-scheme-${role}-${randomUUID()}`,
passwordHash: "unused",
displayName: `页面方案${role}测试`,
mustChangePassword: false,
},
});
const membership = await prisma.brandMembership.create({
data: { adminUserId: user.id, brandId, role },
});
members.push({ userId: user.id, membershipId: membership.id });
const token = signIdentity({
subject: user.id,
brandId,
role: "admin",
tokenVersion: user.tokenVersion,
});
if (role === "admin") {
const adminResponse = await request("/admin/workspace/template/options", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(adminResponse.statusCode, 200, adminResponse.body);
const adminOptions = JSON.parse(adminResponse.body);
assert.equal(adminOptions.business.key, "food");
assert.equal(adminOptions.pageSchemes.length > 0, true);
assert.ok(
adminOptions.pageSchemes.every((scheme) =>
scheme.supportedBusinessTypes.includes("food"),
),
);
} else {
const editorForbidden = await request("/admin/workspace/template/options", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(editorForbidden.statusCode, 403);
}
}
const ownerResponse = await request("/admin/workspace/template/options", {
headers: { authorization: `Bearer ${ownerToken}` },
});
assert.equal(ownerResponse.statusCode, 200, ownerResponse.body);
const ownerOptions = JSON.parse(ownerResponse.body);
assert.equal(ownerOptions.business.key, "food");
assert.equal(JSON.stringify(ownerOptions).includes("visualTemplateKey"), false);
assert.equal(JSON.stringify(ownerOptions).includes("packageKey"), false);
} finally {
for (const item of members.reverse()) {
await prisma.brandMembership.delete({ where: { id: item.membershipId } });
await prisma.adminUser.delete({ where: { id: item.userId } });
}
}
});
test("public workspace uses brand-scoped capability installations and preserves status", async () => {
await prisma.capabilityInstallation.deleteMany({ where: { brandId } });
const installation = await prisma.capabilityInstallation.create({
@@ -2281,6 +2606,10 @@ test("editor membership can manage brand content but cannot change system settin
payload: { config: { visualTemplateKey: "unknown-visual" } },
});
assert.equal(visualUpdate.statusCode, 400);
const pageSchemePreview = await request("/admin/workspace/template/preview", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(pageSchemePreview.statusCode, 403);
} finally {
await prisma.brandMembership.update({
where: { id: membership.id },
@@ -2887,10 +3216,19 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
const initialManifest = structuredClone(installedPackageVersion.manifestSnapshot);
initialManifest.version = initialPackageVersion;
initialManifest.templateFields = [
{ key: "founder", binding: "brand.config.founder", label: "主理人" },
{ key: "founder", binding: "brand.config.templateData.founder", label: "主理人" },
];
initialManifest.assetSlots = [
{
key: "brand.logo",
binding: "brand.avatarUrl",
target: "brand",
label: "品牌标志",
help: "用于品牌身份展示。",
required: false,
kind: "logo",
},
];
initialManifest.entrypoints = { home: "pages/index/index" };
initialManifest.assetSlots = [{ key: "brand.logo", binding: "brand.avatarUrl" }];
initialManifest.requiredCapabilities = ["offerings"];
const initialPackageVersionRecord = await prisma.templatePackageVersion.create({
data: {
@@ -2911,9 +3249,20 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
const originalConfig =
originalBrand.config && typeof originalBrand.config === "object" ? originalBrand.config : {};
const existingFounder = "升级前的品牌主理人";
const originalTemplateData =
originalConfig.templateData &&
typeof originalConfig.templateData === "object" &&
!Array.isArray(originalConfig.templateData)
? originalConfig.templateData
: {};
await prisma.brandProfile.update({
where: { id: brandId },
data: { config: { ...originalConfig, founder: existingFounder } },
data: {
config: {
...originalConfig,
templateData: { ...originalTemplateData, founder: existingFounder },
},
},
});
await prisma.brandTemplateInstallation.update({
where: { id: installedRecord.id },
@@ -2927,15 +3276,32 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
const targetManifest = structuredClone(initialManifest);
targetManifest.version = packageVersion;
targetManifest.templateFields = [
{ key: "founder", binding: "brand.config.founder", label: "品牌主理人" },
{ key: "founder", binding: "brand.config.templateData.founder", label: "品牌主理人" },
];
targetManifest.entrypoints = {
...initialManifest.entrypoints,
home: "pages/home/index",
profile: "pages/profile/index",
gallery: "pages/gallery/index",
};
targetManifest.assetSlots = [
{ key: "brand.logo", binding: "brand.avatarUrl" },
{ key: "home.hero", binding: "brand.config.heroImage" },
{
key: "brand.logo",
binding: "brand.avatarUrl",
target: "brand",
label: "品牌标志",
help: "用于品牌身份展示。",
required: false,
kind: "logo",
},
{
key: "home.hero",
binding: "brand.config.heroImage",
target: "brand",
label: "首页主图",
help: "用于首页展示品牌重点内容。",
required: false,
kind: "image",
},
];
targetManifest.requiredCapabilities = [];
const packageVersionRecord = await prisma.templatePackageVersion.create({
@@ -2962,7 +3328,7 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
assert.equal(actionable.targetPackageVersionId, packageVersionRecord.id);
assert.equal(actionable.changes.brandFields.available, false);
assert.equal(actionable.conflicts.length, 1);
assert.equal(actionable.conflicts[0].binding, "brand.config.founder");
assert.equal(actionable.conflicts[0].binding, "brand.config.templateData.founder");
assert.equal(actionable.changes.pages.added.length, 1);
assert.equal(actionable.changes.assets.slots.added.length, 1);
assert.deepEqual(actionable.changes.capabilities.removed, ["offerings"]);
@@ -3001,7 +3367,9 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
expectedCurrentVersion: actionable.currentVersion,
expectedCurrentPackageVersionId: actionable.currentPackageVersionId,
confirm: true,
preservedBindings: [{ key: "founder", binding: "brand.config.founder", action: "preserve" }],
preservedBindings: [
{ key: "founder", binding: "brand.config.templateData.founder", action: "preserve" },
],
};
const upgradeAttempts = await Promise.all(
[0, 1].map(() =>
@@ -3020,7 +3388,8 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
packageVersionRecord.id,
);
assert.equal(
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).config.founder,
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).config.templateData
.founder,
existingFounder,
);
const retainedOldPackage = await prisma.templatePackageVersion.findUniqueOrThrow({
@@ -3391,6 +3760,86 @@ test("selected package version is reflected in public runtime workspace", async
assert.equal(body.visualTemplateManifest.key, selectedVersion.manifestSnapshot.visualTemplateKey);
});
test("legacy doors installation preview separates content package and platform renderer versions", async () => {
const doorsBrand = await prisma.brandProfile.findUniqueOrThrow({
where: { slug: "linjing-doors" },
});
const adminUser = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
const installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId: doorsBrand.id },
});
const currentPackage = await prisma.templatePackageVersion.findFirstOrThrow({
where: {
packageKey: "linjing-editorial",
version: "1.0.7",
status: "published",
},
});
// 模拟真实旧安装:内容包锁定 1.0.6,但平台 renderer 已是 1.0.7。
const legacyManifest = {
...currentPackage.manifestSnapshot,
version: "1.0.6",
supportedIndustryTemplates: ["personal", "doors"],
};
const legacyPackage = await prisma.templatePackageVersion.create({
data: {
templatePackageId: currentPackage.templatePackageId,
packageKey: currentPackage.packageKey,
version: "1.0.6",
displayName: currentPackage.displayName,
status: "published",
manifestSnapshot: legacyManifest,
validationReport: currentPackage.validationReport,
contentChecksum: `legacy-${randomUUID()}`,
archiveChecksum: `legacy-archive-${randomUUID()}`,
artifactPath: currentPackage.artifactPath,
importedById: adminUser.id,
},
});
const headers = {
authorization: `Bearer ${signIdentity({
subject: adminUser.id,
brandId: doorsBrand.id,
role: "admin",
tokenVersion: adminUser.tokenVersion,
})}`,
};
try {
await prisma.brandTemplateInstallation.update({
where: { brandId: doorsBrand.id },
data: {
templateVersion: legacyPackage.version,
templatePackageVersionId: legacyPackage.id,
contentChecksum: legacyPackage.contentChecksum,
configSnapshot: legacyPackage.manifestSnapshot,
},
});
const previewResponse = await request("/admin/workspace/template/preview", { headers });
assert.equal(previewResponse.statusCode, 200, previewResponse.body);
const preview = JSON.parse(previewResponse.body);
assert.equal(preview.currentVersion, "1.0.6");
assert.equal(preview.latestVersion, "1.0.7");
assert.equal(preview.canUpgrade, true);
assert.equal(preview.targetPackageVersionId, currentPackage.id);
assert.equal(preview.changes.renderer.available, true);
assert.equal(preview.changes.renderer.source, "platform_visual_manifest");
assert.equal(preview.changes.renderer.packageUpgradeChangesRenderer, false);
assert.ok(preview.changes.renderer.pages.length > 0);
} finally {
await prisma.brandTemplateInstallation.update({
where: { brandId: doorsBrand.id },
data: {
templateVersion: installation.templateVersion,
templatePackageVersionId: installation.templatePackageVersionId,
contentChecksum: installation.contentChecksum,
configSnapshot: installation.configSnapshot,
},
});
await prisma.templatePackageVersion.delete({ where: { id: legacyPackage.id } });
}
});
test("public workspace exposes declared brand and trust presentation data", async () => {
const doorsBrand = await prisma.brandProfile.findUnique({ where: { slug: "linjing-doors" } });
assert.ok(doorsBrand);
+25
View File
@@ -0,0 +1,25 @@
import assert from "node:assert/strict";
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import { test } from "node:test";
const projectRoot = path.resolve(import.meta.dirname, "../../..");
const seedPath = path.join(projectRoot, "apps/api/prisma/seed.ts");
const assetDirectory = path.join(projectRoot, "apps/api/prisma/assets");
test("开发 seed 引用的本地媒体都有随仓库分发的源文件", () => {
const seed = readFileSync(seedPath, "utf8");
const references = [...seed.matchAll(/["'](\/media\/seed\/[^"']+)["']/g)].map(
([, mediaPath]) => mediaPath,
);
assert.ok(references.length > 0, "seed 中没有找到本地媒体引用");
for (const mediaPath of new Set(references)) {
const filename = path.basename(mediaPath);
assert.equal(
existsSync(path.join(assetDirectory, filename)),
true,
`seed 引用的媒体缺少源文件: ${mediaPath}`,
);
}
});
@@ -10,7 +10,7 @@ import { createApp } from "../dist/main.js";
import { signIdentity } from "../dist/auth.js";
const prisma = new PrismaClient();
const packageKeys = ["acheng-campus-food", "linjing-editorial"];
const packageKeys = ["acheng-campus-food", "linjing-editorial", "atelier-solopreneur"];
function run(command, args, options = {}) {
const result = spawnSync(command, args, { stdio: "inherit", ...options });
+26 -1
View File
@@ -69,6 +69,14 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
authorizationTest: "admin can list and switch only enabled brand memberships",
successTest: "admin can list and switch only enabled brand memberships",
},
{
method: "GET",
path: "/admin/brands/creation-options",
auth: "roles",
roles: ["owner"],
authorizationTest: "brand creation options are owner-scoped",
successTest: "brand creation options are owner-scoped",
},
{
method: "GET",
path: "/admin/brands/members",
@@ -222,10 +230,19 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
{
method: "GET",
path: "/admin/workspace/template/preview",
auth: "brand",
auth: "roles",
roles: ["owner", "admin", "platform-admin"],
authorizationTest: "template ledger install, upgrade preview, and rollback stay brand-scoped",
successTest: "template ledger install, upgrade preview, and rollback stay brand-scoped",
},
{
method: "GET",
path: "/admin/workspace/template/options",
auth: "roles",
roles: ["owner", "admin", "platform-admin"],
authorizationTest: "page scheme options are readable by owners and admins only",
successTest: "page scheme options are readable by owners and admins only",
},
{
method: "GET",
path: "/customer/bookings",
@@ -436,6 +453,14 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
authorizationTest: "admin can list and switch only enabled brand memberships",
successTest: "admin can list and switch only enabled brand memberships",
},
{
method: "POST",
path: "/admin/brands",
auth: "roles",
roles: ["owner"],
authorizationTest: "owner can create an isolated brand",
successTest: "owner can create an isolated brand",
},
{
method: "POST",
path: "/admin/brands/members",
+68
View File
@@ -1,5 +1,7 @@
const assert = require("node:assert/strict");
const { randomBytes } = require("node:crypto");
const { existsSync } = require("node:fs");
const path = require("node:path");
const { spawnSync } = require("node:child_process");
const { PrismaClient } = require("@prisma/client");
@@ -32,7 +34,47 @@ async function main() {
const initialTrustCount = await fixtureDatabase.trustContent.count();
const initialFormCount = await fixtureDatabase.inquiryForm.count();
const initialReleases = await fixtureDatabase.brandRelease.findMany({ orderBy: { id: "asc" } });
// 模拟旧模板遗留数据:数组 config、失效封面和媒体引用。重复 seed 必须修复结构,
// 同时保留记录本身和停用状态。
const doorsBrand = await fixtureDatabase.brandProfile.findUniqueOrThrow({
where: { slug: "linjing-doors" },
});
const legacyOfferingName = "legacy-offering-repair-fixture";
await fixtureDatabase.offering.create({
data: {
brandId: doorsBrand.id,
kind: "service",
name: legacyOfferingName,
coverUrl: "/media/seed/seed-02.jpg",
isEnabled: false,
config: [{ url: "/media/seed/seed-02.jpg" }],
},
});
if (run("pnpm", ["db:seed"]) !== 0) return status;
const repairedLegacyOffering = await fixtureDatabase.offering.findUniqueOrThrow({
where: { brandId_name: { brandId: doorsBrand.id, name: legacyOfferingName } },
});
assert.equal(
Array.isArray(repairedLegacyOffering.config),
false,
"Repeated seed must repair legacy array config",
);
assert.ok(
repairedLegacyOffering.config &&
typeof repairedLegacyOffering.config === "object" &&
Array.isArray(repairedLegacyOffering.config.media),
"Repeated seed must rebuild legacy media config",
);
assert.notEqual(
repairedLegacyOffering.coverUrl,
"/media/seed/seed-02.jpg",
"Repeated seed must replace a missing local cover",
);
assert.equal(
repairedLegacyOffering.isEnabled,
false,
"Repeated seed must preserve disabled offering state",
);
assert.equal(
await fixtureDatabase.trustContent.count(),
initialTrustCount,
@@ -48,6 +90,32 @@ async function main() {
initialReleases,
"Repeated seed must preserve release history and snapshots",
);
const seededOfferings = await fixtureDatabase.offering.findMany({
select: { name: true, coverUrl: true, config: true },
});
assert.ok(seededOfferings.length > 0, "Seed must create offering fixtures");
for (const offering of seededOfferings) {
assert.ok(
offering.config && typeof offering.config === "object" && !Array.isArray(offering.config),
`Seed offering config must be an object: ${offering.name}`,
);
const config = offering.config;
const mediaUrls = Array.isArray(config.media)
? config.media.flatMap((item) =>
item && typeof item === "object" && typeof item.url === "string" ? [item.url] : [],
)
: [];
const localMedia = [offering.coverUrl, ...mediaUrls].filter(
(url) => typeof url === "string" && url.startsWith("/media/seed/"),
);
for (const mediaPath of new Set(localMedia)) {
assert.equal(
existsSync(path.join(__dirname, "prisma/assets", path.basename(mediaPath))),
true,
`Seed offering references missing media: ${offering.name} -> ${mediaPath}`,
);
}
}
await fixtureDatabase.adminUser.updateMany({
where: { username: "admin" },
data: { mustChangePassword: false },
@@ -45,7 +45,7 @@ async function main() {
.filter((entry) => entry.isDirectory() && entry.name !== targetMigration)
.map((entry) => entry.name)
.sort();
assert.equal(migrationDirs.at(-1), "20261018180000_add_customer_token_version");
assert.equal(migrationDirs.at(-1), "20261019100000_remove_brand_profile_defaults");
await admin.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
createdSchema = true;
@@ -180,8 +180,8 @@ test("template preview matrix keeps every deployed package, industry, and versio
}
}
}
// 3 个包 x 支持行业(1 + 1 + 2)x 2 个版本 = 8 个隔离模拟品牌。
assert.equal(visibleBrands.size, 8);
// 3 个包 × 每个包一个支持行业 × 2 个版本 = 6 个隔离模拟品牌。
assert.equal(visibleBrands.size, 6);
} finally {
for (const fixture of fixtures) rmSync(fixture.root, { recursive: true, force: true });
}
@@ -0,0 +1,33 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { compareTemplateVersions, latestTemplateVersion } from "../src/template-version-order.js";
test("模板版本按 SemVer 而不是导入时间判断最新版", () => {
const importedLaterOldVersion = {
version: "1.9.0",
importedAt: new Date("2026-10-20T00:00:00Z"),
};
const importedEarlierNewVersion = {
version: "1.10.0",
importedAt: new Date("2026-10-19T00:00:00Z"),
};
assert.equal(
latestTemplateVersion([importedEarlierNewVersion, importedLaterOldVersion])?.version,
"1.10.0",
);
assert.ok(compareTemplateVersions("1.10.0", "1.9.0") > 0);
});
test("模板版本排序正确处理预发布版本和同版本稳定性", () => {
assert.ok(compareTemplateVersions("1.0.0", "1.0.0-beta.2") > 0);
assert.ok(compareTemplateVersions("1.0.0-beta.10", "1.0.0-beta.2") > 0);
const first = {
version: "1.0.0",
importedAt: new Date("2026-10-19T00:00:00Z"),
};
const second = {
version: "1.0.0",
importedAt: new Date("2026-10-20T00:00:00Z"),
};
assert.equal(latestTemplateVersion([first, second]), second);
});
+9 -9
View File
@@ -657,13 +657,13 @@ test("林境模板支持首页和主理人区域点选", async ({ page }) => {
await page.setViewportSize({ width: 1600, height: 900 });
const editorialBrand = {
...structuredClone(brand),
templateKey: "personal",
avatarUrl: "/assets/acheng-campus-food/owner/portrait.jpg",
templateKey: "doors",
avatarUrl: "/template-preview/assets/linjing-editorial/content/founder-portrait.jpg",
config: {
visualTemplateKey: "linjing-editorial",
founder: "林境主理人",
title: "建筑设计师",
heroImage: "/assets/acheng-campus-food/owner/portrait.jpg",
title: "门系统设计师",
heroImage: "/template-preview/assets/linjing-editorial/content/entry-door.jpg",
homeHero: { title: "林境作品" },
visualPresentation: {
home: {
@@ -697,13 +697,13 @@ test("林境模板支持首页和主理人区域点选", async ({ page }) => {
...editorialBrand,
...editorialBrand.config,
founder: "林境主理人",
title: "建筑设计师",
heroImage: "/assets/acheng-campus-food/owner/portrait.jpg",
title: "门系统设计师",
heroImage: "/template-preview/assets/linjing-editorial/content/entry-door.jpg",
homeHero: { title: "林境作品" },
},
offerings: structuredClone(runtimeWorkspace.offerings).map((item) => ({
...item,
coverUrl: "/assets/acheng-campus-food/owner/portrait.jpg",
coverUrl: "/template-preview/assets/linjing-editorial/content/entry-door.jpg",
})),
trustItems: [
{
@@ -800,9 +800,9 @@ test("林境模板支持首页和主理人区域点选", async ({ page }) => {
}
if (path === "/admin/config/trust-content")
return route.fulfill({ json: editorialWorkspace.trustItems });
if (path === "/public/templates/personal")
if (path === "/public/templates/doors")
return route.fulfill({
json: { name: "个人品牌", description: "林境模板", serviceCategories: [] },
json: { name: "门窗业务", description: "林境页面方案", serviceCategories: [] },
});
if (path === "/admin/workspace")
return route.fulfill({
@@ -52,7 +52,6 @@ type MediaCase = {
const mediaCases: MediaCase[] = [
{ packageKey: "acheng-campus-food", industry: "food", founder: "阿成" },
{ packageKey: "atelier-solopreneur", industry: "personal", founder: "林予 · 示例主理人" },
{ packageKey: "linjing-editorial", industry: "personal", founder: "示例主理人" },
{ packageKey: "linjing-editorial", industry: "doors", founder: "林叙安 (Lin XUAN)" },
];