fix: 收敛模板编辑发布契约并还原餐饮页面视觉

This commit is contained in:
que01 committed 2026-10-08 13:36:59 +08:00
1 parent 20bcb43534
commit f4061a24bd
102 files changed
+4510 -870

No files matched your search

@@ -10,8 +10,18 @@ export function TemplateListField({
}) {
return (
<Form.Item label={field.label} help={field.help}>
<Form.List name={name}>
{(rows, { add, remove }) => (
<Form.List
name={name}
rules={[
{
validator: (_rule, values: unknown) =>
field.required && (!Array.isArray(values) || values.length === 0)
? Promise.reject(new Error(`请至少填写一项${field.label}`))
: Promise.resolve(),
},
]}
>
{(rows, { add, remove }, { errors }) => (
<Space direction="vertical" style={{ width: "100%" }}>
{rows.map((row, index) => (
<Space key={row.key} align="start" wrap>
@@ -32,6 +42,7 @@ export function TemplateListField({
<Button onClick={() => remove(row.name)}>删除</Button>
</Space>
))}
<Form.ErrorList errors={errors} />
<Button onClick={() => add()}>新增{field.label}</Button>
</Space>
)}
+4 -2
View File
@@ -33,7 +33,7 @@ export function BrandPage() {
{!brand.data ? null : (
<>
<AdminPageHeader
title="品牌表达"
title="品牌资料"
description="先让访客理解你是谁、服务谁,以及为什么值得信任。"
extra={<Tag color="blue">{template.data?.name ?? "当前模板"}</Tag>}
/>
@@ -152,7 +152,9 @@ export function BrandPage() {
</Col>
<Col xs={24} xl={9}>
<Card title="公开表达预览" style={{ position: "sticky", top: 24 }}>
<Typography.Text type="secondary">小程序首页将优先使用以下信息</Typography.Text>
<Typography.Text type="secondary">
这些资料会用于小程序首页和联系区域
</Typography.Text>
<Typography.Title level={3}>{brand.data.name || "品牌名称"}</Typography.Title>
<Typography.Title level={5}>{brand.data.tagline || "一句话定位"}</Typography.Title>
<Typography.Paragraph>
@@ -2,17 +2,23 @@ import {
Alert,
Button,
Card,
Divider,
Col,
Form,
Grid,
Input,
InputNumber,
Row,
Select,
Segmented,
Space,
Tag,
Typography,
message,
} from "antd";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useEffect, useMemo } from "react";
import { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import type { AdminTemplateContent, TemplateAdminField } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import { ImageUrlField } from "../../components/ImageUrlField.js";
@@ -46,6 +52,22 @@ function renderField(field: TemplateAdminField) {
return <ImageUrlField {...(field.placeholder ? { placeholder: field.placeholder } : {})} />;
if (field.input === "number")
return <InputNumber style={{ width: "100%" }} placeholder={field.placeholder} />;
if (field.input === "boolean")
return (
<Select
options={[
{ value: true, label: "是" },
{ value: false, label: "否" },
]}
/>
);
if (field.input === "select" || field.input === "multi-select")
return (
<Select
{...(field.input === "multi-select" ? { mode: "multiple" as const } : {})}
options={field.options ?? []}
/>
);
return (
<Input
type={field.input === "phone" ? "tel" : "text"}
@@ -63,15 +85,88 @@ export function PresentationEditor({
}: PresentationEditorProps) {
const [form] = Form.useForm<PresentationValues>();
const queryClient = useQueryClient();
const sections = useMemo(
() =>
(templateContent?.admin.sections ?? [])
.map((section) => ({
...section,
fields: section.fields.filter((field) => field.binding.startsWith("brand.config.")),
}))
.filter((section) => section.fields.length > 0),
[templateContent],
const navigate = useNavigate();
const breakpoints = Grid.useBreakpoint();
const [activePage, setActivePage] = useState<string>();
const sections = useMemo(() => {
const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({
...field,
binding: field.binding ?? `brand.config.templateData.${field.key}`,
}));
return [
...(declaredTemplateFields.length
? [
{
key: "template-data",
title: "模板专属内容",
description: "这些字段由当前小程序模板定义,保存后发布才会对外展示。",
page: templateContent?.templateFields?.[0]?.page ?? "home",
target: "brand" as const,
fields: declaredTemplateFields,
},
]
: []),
...(templateContent?.admin.sections ?? []),
]
.map((section) => ({
...section,
fields: section.fields.filter(
(field) =>
field.binding.startsWith("brand.config.") ||
[
"brand.avatarUrl",
"brand.description",
"brand.contactPhone",
"brand.contactWechat",
"brand.address",
].includes(field.binding),
),
}))
.filter((section) => section.fields.length > 0);
}, [templateContent]);
const pageOptions = useMemo(() => {
const pages = new Map<string, string>();
for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label);
for (const section of templateContent?.admin.sections ?? []) {
const navigation = templateContent?.navigation.find((item) => item.page === section.page);
if (!pages.has(section.page))
pages.set(section.page, navigation?.label ?? pageTitle(section.page));
}
return [...pages].map(([value, label]) => ({ value, label }));
}, [templateContent]);
const selectedPage = pageOptions.some((item) => item.value === activePage)
? activePage
: pageOptions[0]?.value;
const visibleSections = sections.filter((section) => section.page === selectedPage);
const relatedTargets = [
...(templateContent?.admin.sections ?? [])
.filter((section) => section.page === selectedPage && section.target !== "brand")
.map((section) => section.target),
...((templateContent?.trustContentTypes ?? []).some((item) =>
item.pages?.includes(selectedPage ?? ""),
)
? ["trust"]
: []),
];
const pageLinks = [...new Set(relatedTargets)].flatMap((target) =>
target === "trust"
? (templateContent?.trustContentTypes ?? [])
.filter((item) => item.pages?.includes(selectedPage ?? ""))
.map((item) => ({
target: `trust:${item.type}`,
label: `编辑${item.label}`,
}))
: [
{
target,
label: (
{ offering: "管理此页展示的业务内容", inquiry: "管理此页的咨询表单" } as Record<
string,
string
>
)[target],
},
],
);
const initialValues = useMemo(() => {
const values: PresentationValues = {};
@@ -105,10 +200,20 @@ export function PresentationEditor({
form.setFieldsValue(initialValues);
}, [form, initialValues]);
useEffect(() => {
if (!pageOptions.some((item) => item.value === activePage))
setActivePage(pageOptions[0]?.value);
}, [activePage, pageOptions]);
return (
<Card title="小程序页面内容" style={{ marginTop: 24 }}>
<Card
title="小程序页面配置"
extra={templateContent ? <Tag color="blue">{templateContent.displayName}</Tag> : null}
style={{ marginTop: 32 }}
styles={{ body: { minHeight: breakpoints.md ? 760 : 620 } }}
>
<Typography.Paragraph type="secondary">
编辑访客在小程序中看到的文字和图片。不同模板会提供适合本行业的内容项目。
按小程序页面查找内容。这里修改的是草稿,发布后访客才会看到更新。
</Typography.Paragraph>
{loading ? <Alert type="info" showIcon message="正在读取当前模板的编辑项目" /> : null}
{error ? (
@@ -119,51 +224,108 @@ export function PresentationEditor({
) : null}
{templateContent ? (
<>
<Typography.Title level={5}>{templateContent.displayName}</Typography.Title>
<Space wrap style={{ marginBottom: 24 }}>
{breakpoints.xs ? (
<Select
aria-label="选择小程序页面"
value={selectedPage}
options={pageOptions}
onChange={setActivePage}
style={{ minWidth: 180 }}
/>
) : (
<Segmented
value={selectedPage}
options={pageOptions}
onChange={(value) => setActivePage(String(value))}
/>
)}
</Space>
<Form
form={form}
layout="vertical"
initialValues={initialValues}
onFinish={(values) => save.mutate(values)}
style={{ minHeight: 540, display: "flex", flexDirection: "column" }}
>
{sections.map((section) => (
<Card
key={section.key}
size="small"
title={section.title}
style={{ marginBottom: 16 }}
>
<Typography.Paragraph type="secondary">{section.description}</Typography.Paragraph>
<Row gutter={16}>
{section.fields.map((field) => (
<Col
key={field.key}
xs={24}
md={field.input === "textarea" || field.input === "list" ? 24 : 12}
>
{field.input === "list" ? (
<TemplateListField
field={field}
name={presentationFieldName(section.key, field.key)}
/>
) : (
<Form.Item
name={presentationFieldName(section.key, field.key)}
label={field.label}
{...(field.help ? { help: field.help } : {})}
{...(field.required
? { rules: [{ required: true, message: `请填写${field.label}` }] }
: {})}
<div style={{ flex: 1 }}>
{visibleSections.map((section, index) => (
<section key={section.key} aria-labelledby={`section-${section.key}`}>
{index > 0 ? <Divider /> : null}
<Typography.Title id={`section-${section.key}`} level={5}>
{section.title}
</Typography.Title>
<Typography.Paragraph type="secondary">
{section.description}
</Typography.Paragraph>
<Row gutter={16}>
{section.fields.map((field) => (
<Col
key={field.key}
xs={24}
md={field.input === "textarea" || field.input === "list" ? 24 : 12}
>
{field.input === "list" ? (
<TemplateListField
field={field}
name={presentationFieldName(section.key, field.key)}
/>
) : (
<Form.Item
name={presentationFieldName(section.key, field.key)}
label={field.label}
{...(field.help ? { help: field.help } : {})}
{...(field.required
? { rules: [{ required: true, message: `请填写${field.label}` }] }
: {})}
>
{renderField(field)}
</Form.Item>
)}
</Col>
))}
</Row>
</section>
))}
{pageLinks.length ? (
<Alert
type="info"
showIcon
style={{ marginBottom: 24 }}
message="这个页面还有关联内容"
description={
<Space wrap>
{pageLinks.map((item) => (
<Button
key={item.target}
type="link"
onClick={() => {
if (item.target.startsWith("trust:")) {
void navigate(
`/admin/trust?type=${encodeURIComponent(item.target.slice(6))}`,
);
return;
}
void navigate(
item.target === "offering" ? "/admin/services" : "/admin/workspace",
);
}}
style={{ padding: 0 }}
>
{renderField(field)}
</Form.Item>
)}
</Col>
))}
</Row>
</Card>
))}
<Space direction="vertical" style={{ width: "100%" }}>
{item.label}
</Button>
))}
</Space>
}
/>
) : null}
{!visibleSections.length && !pageLinks.length ? (
<Typography.Paragraph type="secondary">
这个页面没有单独的品牌文案配置。
</Typography.Paragraph>
) : null}
</div>
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
<MutationError error={save.error} />
<Button type="primary" htmlType="submit" loading={save.isPending}>
保存页面内容
@@ -175,3 +337,20 @@ export function PresentationEditor({
</Card>
);
}
function pageTitle(page: string): string {
return (
(
{
home: "首页",
offerings: "业务展示",
service: "服务说明",
detail: "详情页",
inquiry: "咨询页",
success: "提交成功页",
records: "记录页",
profile: "主理人页",
} as Record<string, string>
)[page] ?? page
);
}
@@ -48,7 +48,10 @@ export function readPresentationValue(
? (value as unknown[]).map((item) => ({ [field.itemValueKey as string]: item }))
: value;
}
return typeof value === "string" || typeof value === "number" ? value : undefined;
if (field?.input === "multi-select") return Array.isArray(value) ? value : [];
return typeof value === "string" || typeof value === "number" || typeof value === "boolean"
? value
: undefined;
}
function writePath(
@@ -98,7 +98,7 @@ export function OverviewPage() {
<Col xs={24} sm={12} lg={6}>
<Card>
<Statistic
title="信任内容"
title="信任证明"
value={trust?.filter((item) => item.isPublished).length ?? 0}
suffix="条已发布"
/>
@@ -107,7 +107,7 @@ export function OverviewPage() {
<Col xs={24} sm={12} lg={6}>
<Card>
<Statistic
title="业务提供项"
title="业务展示内容"
value={offerings?.filter((item) => item.isEnabled).length ?? 0}
suffix="项公开"
/>
@@ -98,8 +98,12 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
});
const importSample = useMutation({
mutationFn: () => client.importAdminSampleContent(),
onSuccess: () => {
message.success("示例内容已导入草稿");
onSuccess: ({ counts }) => {
message.success(
counts.inquiryForms
? "示例内容和客户咨询表单已导入草稿"
: "示例内容已导入草稿,现有客户咨询表单已保留",
);
refresh();
},
});
@@ -259,9 +263,9 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
.join("、") || "无"}
</Typography.Text>
<Space wrap>
<Button onClick={() => navigate("/admin/brand")}>编辑品牌</Button>
<Button onClick={() => navigate("/admin/services")}>编辑业务项</Button>
<Button onClick={() => navigate("/admin/trust")}>编辑信任内容</Button>
<Button onClick={() => navigate("/admin/brand")}>编辑小程序页面</Button>
<Button onClick={() => navigate("/admin/services")}>编辑业务展示和详情</Button>
<Button onClick={() => navigate("/admin/trust")}>编辑信任证明</Button>
</Space>
</Space>
</section>
@@ -1,6 +1,5 @@
import {
Button,
Card,
Form,
Input,
Modal,
@@ -47,6 +46,18 @@ export function ServicesPage() {
.flatMap((section) =>
section.fields.filter((field) => field.binding.startsWith("offering.config.")),
);
const offeringPageLabel =
workspace.data?.templateContent?.navigation.find((item) => item.page === "offerings")?.label ??
"业务展示页";
const detailPageLabel =
workspace.data?.templateContent?.navigation.find((item) => item.page === "detail")?.label ??
"详情页";
const detailSections = (workspace.data?.templateContent?.admin.sections ?? []).filter(
(section) => section.target === "offering" && section.page === "detail",
);
const hasTemplateDetailCopy = templateFields.some(
(field) => field.binding === "offering.config.details.background",
);
const saveOffering = useMutation({
mutationFn: (values: Record<string, unknown>) => {
const fields = Object.fromEntries(
@@ -129,15 +140,28 @@ export function ServicesPage() {
}}
>
<AdminPageHeader
title="业务提供项"
description="管理你向外提供的服务、产品、套餐和合作项目,让访客清楚知道如何与你合作。"
title="小程序内容:业务展示与详情"
description={`在「${offeringPageLabel}」管理访客能选择的服务、产品或案例;每项内容的补充资料会显示在对应的「${detailPageLabel}」。`}
extra={
<Button type="primary" onClick={() => beginOffering()}>
新增业务提供项
</Button>
}
/>
<Card title="公开业务提供项" extra={<Tag color="blue">小程序优先展示</Tag>}>
<section aria-label="业务提供项列表">
<Space wrap style={{ marginBottom: 16 }}>
<Typography.Title level={5} style={{ margin: 0 }}>
{offeringPageLabel}中的内容
</Typography.Title>
<Tag color="blue">已启用的项目会公开展示</Tag>
</Space>
{detailSections.length ? (
<Typography.Paragraph type="secondary">
编辑单项详情时,附加字段将用于:
{detailSections.map((section) => section.title).join("、")}
。列表中的名称、说明、价格和封面也会显示在业务展示页。
</Typography.Paragraph>
) : null}
<Table
scroll={{ x: 760 }}
rowKey="id"
@@ -211,7 +235,7 @@ export function ServicesPage() {
<MutationError error={saveOffering.error} />
<MutationError error={toggleOffering.error} />
<MutationError error={deleteOffering.error} />
</Card>
</section>
<Modal
open={offeringOpen}
title={editingOffering ? "编辑业务提供项" : "新增业务提供项"}
@@ -244,9 +268,11 @@ export function ServicesPage() {
<Form.Item name="summary" label="一句话说明">
<Input />
</Form.Item>
<Form.Item name="description" label="详细介绍">
<Input.TextArea rows={5} />
</Form.Item>
{!hasTemplateDetailCopy ? (
<Form.Item name="description" label="详细介绍">
<Input.TextArea rows={5} />
</Form.Item>
) : null}
<Form.Item name="priceText" label="价格展示">
<Input placeholder="例如:按现场评估报价 / ¥ 2,800 起" />
</Form.Item>
@@ -1,6 +1,6 @@
import {
Button,
Card,
Divider,
Form,
Input,
List,
@@ -14,12 +14,14 @@ import {
message,
} from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { isTrustContentComplete } from "@personal-brand/api-client";
import type {
TemplateAdminField,
TrustContent,
TrustContentInput,
} from "@personal-brand/api-client";
import { useState } from "react";
import { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { ImageUrlField } from "../../components/ImageUrlField.js";
@@ -61,14 +63,25 @@ const types = [
type TrustTypeOption = {
type: string;
label: string;
adminFields: {
title: string;
summary: string;
content: string;
summaryHelp?: string;
summaryPlaceholder?: string;
};
pages?: string[];
help?: string;
placeholder?: string;
required?: boolean;
configFields?: TemplateAdminField[];
hideStandardFields?: Array<"summary" | "content">;
maxPublishedItems?: number;
};
const fallbackTypes: TrustTypeOption[] = types.map(({ value, label, help }) => ({
type: value,
label,
adminFields: { title: "标题", summary: "摘要", content: "详细内容" },
help,
}));
@@ -78,6 +91,7 @@ export function TrustContentPage() {
const [editing, setEditing] = useState<TrustContent | null>(null);
const [open, setOpen] = useState(false);
const [form] = Form.useForm<TrustContentInput>();
const [searchParams] = useSearchParams();
const selectedType = Form.useWatch("type", form);
const query = useQuery({
queryKey: ["trust-content"],
@@ -91,6 +105,21 @@ export function TrustContentPage() {
?.length
? workspace.data.templateContent.trustContentTypes
: fallbackTypes;
const pageLabel = (page: string) =>
workspace.data?.templateContent?.navigation.find((item) => item.page === page)?.label ??
(
{ home: "首页", offerings: "业务展示页", detail: "详情页", profile: "主理人页" } as Record<
string,
string
>
)[page] ??
page;
const trustPageLabels = [
...new Set(availableTypes.flatMap((item) => item.pages ?? []).map(pageLabel)),
];
const trustPlacement = trustPageLabels.length
? `小程序的${trustPageLabels.join("、")}中`
: "小程序对应的信任展示区域中";
const selectedTypeMeta = availableTypes.find((item) => item.type === selectedType);
const contentByType = new Map<string, TrustContent>();
for (const item of query.data ?? []) {
@@ -109,13 +138,14 @@ export function TrustContentPage() {
availableTypes.find((item) => item.required && !contentByType.has(item.type))?.type ??
availableTypes[0]?.type ??
"credential";
const requestedType = searchParams.get("type");
const save = useMutation({
mutationFn: (values: TrustContentInput) =>
editing
? client.updateAdminTrustContent(editing.id, values)
: client.createAdminTrustContent(values),
onSuccess: () => {
message.success("信任内容已保存");
message.success("品牌内容已保存为草稿,发布后小程序才会更新");
setOpen(false);
setEditing(null);
form.resetFields();
@@ -125,7 +155,7 @@ export function TrustContentPage() {
const remove = useMutation({
mutationFn: (id: string) => client.deleteAdminTrustContent(id),
onSuccess: () => {
message.success("内容已删除");
message.success("品牌内容已删除");
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
},
});
@@ -146,6 +176,10 @@ export function TrustContentPage() {
: { type: type ?? firstMissingRequiredType, isPublished: false, config: {} },
);
};
useEffect(() => {
if (!requestedType || !availableTypes.some((item) => item.type === requestedType)) return;
begin(contentByType.get(requestedType), requestedType);
}, [requestedType, availableTypes.length]);
return (
<QueryState
loading={query.isLoading || workspace.isLoading}
@@ -153,24 +187,32 @@ export function TrustContentPage() {
onRetry={() => void Promise.all([query.refetch(), workspace.refetch()])}
>
<AdminPageHeader
title="信任内容"
description="用经历、案例、资历、流程和反馈,让访客知道为什么可以信任你。"
title="小程序内容:品牌介绍与信任"
description={`填写真实的经历、案例、资历、流程和服务说明。这些内容会显示在${trustPlacement};保存后需发布品牌,小程序才会更新。`}
extra={
<Button type="primary" onClick={() => begin()}>
新增信任内容
添加品牌内容
</Button>
}
/>
<Card title="当前模板需要哪些信任内容?" style={{ marginBottom: 24 }}>
<section aria-labelledby="trust-requirements-title">
<Typography.Title id="trust-requirements-title" level={5}>
当前模板需要配置的内容
</Typography.Title>
<Typography.Paragraph type="secondary">
这些内容会帮助访客判断你是否值得信任。带有“发布必需”的项目需要填写完整后,才能发布小程序。
标记为“发布必填”的项目需要填写完整后,才能发布小程序。
</Typography.Paragraph>
<List
size="small"
dataSource={availableTypes}
renderItem={(item) => {
const content = contentByType.get(item.type);
const complete = Boolean(content?.title?.trim() && content?.content?.trim());
const publishedCount = (query.data ?? []).filter(
(record) => record.type === item.type && record.isPublished,
).length;
const tooMany =
item.maxPublishedItems !== undefined && publishedCount > item.maxPublishedItems;
const complete = Boolean(content && isTrustContentComplete(content, item) && !tooMany);
return (
<List.Item
actions={[
@@ -186,9 +228,18 @@ export function TrustContentPage() {
>
<Space wrap>
<Typography.Text strong>{item.label}</Typography.Text>
{item.required && <Tag color="orange">发布必需</Tag>}
{item.required && <Tag color="orange">发布必填</Tag>}
{(item.pages ?? []).map((page) => (
<Tag key={page}>{pageLabel(page)}</Tag>
))}
<Tag color={complete ? "success" : "default"}>
{complete ? "内容完整" : content ? "需要完善" : "尚未填写"}
{tooMany
? `公开内容过多(${publishedCount} 条)`
: complete
? "内容完整"
: content
? "需要完善"
: "尚未填写"}
</Tag>
{item.help && <Typography.Text type="secondary">{item.help}</Typography.Text>}
</Space>
@@ -196,15 +247,16 @@ export function TrustContentPage() {
);
}}
/>
</Card>
<Card>
</section>
<Divider />
<section aria-label="已配置的品牌内容">
<Table
rowKey="id"
dataSource={query.data ?? []}
locale={{ emptyText: "还没有信任内容,请先按上方模板要求添加。" }}
locale={{ emptyText: "还没有品牌内容,请先按上方模板要求添加。" }}
columns={[
{
title: "证据类型",
title: "内容类型",
dataIndex: "type",
render: (value) => (
<Tag>{availableTypes.find((item) => item.type === value)?.label ?? value}</Tag>
@@ -212,15 +264,32 @@ export function TrustContentPage() {
},
{ title: "标题", dataIndex: "title" },
{
title: "摘要",
dataIndex: "summary",
render: (value) => (typeof value === "string" && value ? value : "未填写"),
title: "内容预览",
ellipsis: { showTitle: true },
render: (_value: unknown, item: TrustContent) => {
const meta = availableTypes.find((type) => type.type === item.type);
if (meta?.hideStandardFields?.includes("content")) {
return (
meta.configFields
?.flatMap((field) => {
const value = item.config?.[field.key];
if (Array.isArray(value))
return value.length ? [`${field.label}:${value.length} 项`] : [];
return typeof value === "string" && value.trim()
? [`${field.label}:${value}`]
: [];
})
.join(";") || "尚未填写区块内容"
);
}
return item.summary || item.content || "未填写";
},
},
{
title: "状态",
title: "发布状态",
dataIndex: "isPublished",
render: (value) => (
<Tag color={value ? "success" : "default"}>{value ? "已公开" : "草稿"}</Tag>
<Tag color={value ? "success" : "default"}>{value ? "随发布展示" : "草稿"}</Tag>
),
},
{
@@ -232,7 +301,7 @@ export function TrustContentPage() {
</Button>
<Popconfirm
title="确认删除这条信任内容?"
description="删除后小程序将不再展示。"
description="删除后需发布品牌,才会更新小程序展示。"
onConfirm={() => remove.mutate(item.id)}
>
<Button size="small" danger loading={remove.isPending}>
@@ -245,10 +314,10 @@ export function TrustContentPage() {
]}
/>
<MutationError error={remove.error} />
</Card>
</section>
<Modal
open={open}
title={editing ? "编辑信任内容" : "新增信任内容"}
title={editing ? "编辑品牌内容" : "添加品牌内容"}
onCancel={() => {
setOpen(false);
setEditing(null);
@@ -258,48 +327,70 @@ export function TrustContentPage() {
confirmLoading={save.isPending}
destroyOnClose
>
<Form form={form} layout="vertical" onFinish={(values) => save.mutate(values)}>
<Form.Item name="type" label="内容用途" rules={[{ required: true }]}>
<Form
form={form}
layout="vertical"
onFinish={(values) => save.mutate({ ...values, content: values.content ?? "" })}
>
<Form.Item name="type" label="内容类型" rules={[{ required: true }]}>
<Select
options={availableTypes.map((item) => ({ value: item.type, label: item.label }))}
/>
</Form.Item>
<Form.Item name="title" label="标题" rules={[{ required: true }]}>
<Input placeholder="例如:服务过 30+ 位独立创作者" />
</Form.Item>
<Form.Item name="summary" label="摘要">
<Input />
</Form.Item>
{selectedTypeMeta?.pages?.length ? (
<Typography.Paragraph type="secondary">
这类内容会显示在:
{selectedTypeMeta.pages.map(pageLabel).join("、")}
</Typography.Paragraph>
) : null}
<Form.Item
name="content"
label="详细内容"
help={
selectedTypeMeta?.help ?? "每行写一项,页面会按模板样式展示。不要填写 HTML 或代码。"
}
name="title"
label={selectedTypeMeta?.adminFields.title ?? "标题"}
rules={[{ required: true }]}
>
<Input.TextArea
rows={8}
showCount
maxLength={2000}
placeholder={selectedTypeMeta?.placeholder ?? "例如:\n第一项内容\n第二项内容"}
/>
<Input placeholder="例如:服务过 30+ 位独立创作者" />
</Form.Item>
{(!editing || contentByType.get(selectedType)?.id === editing.id) &&
selectedTypeMeta?.configFields?.map((field) =>
field.input === "list" ? (
<TemplateListField key={field.key} field={field} name={["config", field.key]} />
) : (
<Form.Item
key={field.key}
name={["config", field.key]}
label={field.label}
help={field.help}
>
{field.input === "textarea" ? <Input.TextArea rows={3} /> : <Input />}
</Form.Item>
),
)}
{!selectedTypeMeta?.hideStandardFields?.includes("summary") && (
<Form.Item
name="summary"
label={selectedTypeMeta?.adminFields.summary ?? "摘要"}
help={selectedTypeMeta?.adminFields.summaryHelp}
>
<Input placeholder={selectedTypeMeta?.adminFields.summaryPlaceholder} />
</Form.Item>
)}
{!selectedTypeMeta?.hideStandardFields?.includes("content") && (
<Form.Item
name="content"
label={selectedTypeMeta?.adminFields.content ?? "详细内容"}
help={
selectedTypeMeta?.help ?? "每行写一项,页面会按模板样式展示。不要填写 HTML 或代码。"
}
rules={[{ required: true }]}
>
<Input.TextArea
rows={8}
showCount
maxLength={2000}
placeholder={selectedTypeMeta?.placeholder ?? "例如:\n第一项内容\n第二项内容"}
/>
</Form.Item>
)}
{selectedTypeMeta?.configFields?.map((field) =>
field.input === "list" ? (
<TemplateListField key={field.key} field={field} name={["config", field.key]} />
) : (
<Form.Item
key={field.key}
name={["config", field.key]}
label={field.label}
help={field.help}
rules={[{ required: field.required === true }]}
>
{field.input === "textarea" ? <Input.TextArea rows={3} /> : <Input />}
</Form.Item>
),
)}
<Form.Item
name="coverUrl"
label="配图地址"
@@ -310,7 +401,7 @@ export function TrustContentPage() {
<Form.Item name="isPublished" label="公开状态">
<Select
options={[
{ value: true, label: "立即公开" },
{ value: true, label: "随品牌发布展示" },
{ value: false, label: "保存为草稿" },
]}
/>
@@ -256,16 +256,16 @@ export function WorkspacePage() {
<Space direction="vertical" size="large" style={{ width: "100%" }}>
<AdminPageHeader
title="模板与表单设置"
description="日常内容请从品牌表达、业务提供项和信任内容进入;这里主要管理模板、咨询入口和负责人设置。"
description="日常小程序内容请从页面配置、业务展示和信任证明进入;这里主要管理模板、咨询入口和负责人设置。"
/>
<Card title="先完成日常配置" style={{ marginBottom: 24 }}>
<Typography.Paragraph type="secondary">
下面这些入口面向日常经营,不需要理解模板或技术设置。完成后回到“配置与发布”统一检查并上线。
</Typography.Paragraph>
<Space wrap>
<Button onClick={() => navigate("/admin/brand")}>完善品牌表达</Button>
<Button onClick={() => navigate("/admin/services")}>添加业务提供项</Button>
<Button onClick={() => navigate("/admin/trust")}>补充信任内容</Button>
<Button onClick={() => navigate("/admin/brand")}>配置小程序页面</Button>
<Button onClick={() => navigate("/admin/services")}>添加业务展示内容</Button>
<Button onClick={() => navigate("/admin/trust")}>补充信任证明</Button>
<Button type="primary" onClick={() => navigate("/admin/publication")}>
检查并发布
</Button>
+1 -1
View File
@@ -185,7 +185,7 @@ function Dashboard({ onLogout, role }: { onLogout: () => void; role: string }) {
children: [
{ key: "overview", label: "当前品牌概览" },
{ key: "publication", label: "配置与发布" },
{ key: "brand", label: "品牌表达" },
{ key: "brand", label: "小程序页面" },
{ key: "trust", label: "信任内容" },
{ key: "services", label: "业务提供项" },
{ key: "inquiries", label: "咨询记录" },
+52 -69
View File
@@ -1,7 +1,7 @@
import { PrismaClient } from "@prisma/client";
import { PrismaClient, type Prisma } from "@prisma/client";
import { getTemplatePackageManifestForVisualKey } from "@personal-brand/config";
import bcrypt from "bcryptjs";
import { buildBrandReleaseSnapshot } from "../src/brand-release.service.js";
import { getTemplateSampleContent } from "@personal-brand/config";
const prisma = new PrismaClient();
@@ -20,7 +20,7 @@ const runtimeImages = {
"https://images.unsplash.com/photo-1556761175-b413da4baf72?auto=format&fit=crop&w=1000&q=85",
"https://images.unsplash.com/photo-1521737711867-e3b97375f902?auto=format&fit=crop&w=1000&q=85",
],
};
} as const;
type OfferingKind = "service" | "product" | "package" | "subscription";
@@ -41,9 +41,10 @@ interface RuntimeSeedTemplate {
type: string;
title: string;
content: string;
summary?: string;
config?: Record<string, unknown>;
}>;
inquiryForm: { name: string; fieldsSnapshot: Array<Record<string, unknown>> };
inquiryForm?: { name: string; fieldsSnapshot: Array<Record<string, unknown>> };
}
const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTemplate> = {
@@ -51,6 +52,7 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
templateKey: "personal",
brandConfig: {
visualTemplateKey: "linjing-editorial",
templateData: { designPhilosophy: "先厘清问题,再设计表达" },
founder: "林然",
title: "品牌策略顾问",
slogan: "用清晰的定位与可执行的表达,让专业被看见。",
@@ -186,8 +188,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
flowTitle: "从预订到取餐",
},
service: {
coverageLabel: "取餐与配送",
stepLabel: "步骤",
processAction: "立即预订",
},
offerings: {
@@ -277,24 +277,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
},
],
trustContent: [
{
type: "schedule",
title: "每周出摊日程",
summary: "周一至周五晚餐与夜宵档",
content: "二号校门外小吃商业街 · 17:00 - 22:30\n周六、周日承接团体单与夜市流动出摊",
},
{
type: "coverage",
title: "取餐与配送范围",
summary: "提前预订,按约定时间取餐或配送",
content: "摊位现场自取;满 3 份可配送至校内宿舍楼栋或实验楼门前。",
},
{
type: "process",
title: "定制餐品流程",
summary: "从需求沟通到保温交付",
content: "提交基本需求\n确认菜单与预算\n当日新鲜烹饪打包\n保温直达交付",
},
{
type: "credential",
title: "食品安全与制作承诺",
@@ -312,20 +294,13 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
content: "备料期 15 分钟内联系,出摊高峰 1 小时内回复。",
},
],
inquiryForm: {
name: "家庭聚餐咨询",
fieldsSnapshot: [
{ key: "name", label: "您的称呼", type: "text", required: true },
{ key: "phone", label: "联系电话", type: "phone", required: true },
{ key: "remark", label: "需求说明", type: "textarea", required: false },
],
},
},
doors: {
templateKey: "doors",
retiredOfferingNames: ["别墅入户大门", "院门与围合系统", "室内户内门系统"],
brandConfig: {
visualTemplateKey: "linjing-editorial",
templateData: { designPhilosophy: "让门与空间建立长期、克制的关系" },
founder: "林叙安 (Lin XUAN)",
title: "高端门系统建筑研造主理人",
slogan: "为当代别墅空间,定制有秩序感与呼吸感的门",
@@ -679,40 +654,39 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
};
async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTemplate): Promise<void> {
const packageSample = getTemplateSampleContent(template.templateKey);
const sampleOfferings = packageSample?.offerings ?? [];
const offerings = template.offerings.map((item, index) => ({
...item,
...(sampleOfferings[index]
? {
name: sampleOfferings[index].name,
summary: sampleOfferings[index].summary,
config: {
...item.config,
categoryKey: sampleOfferings[index].categoryKey,
},
}
: {}),
}));
// 模板 package 的 sampleContent 只用于导入预览;演示品牌使用明确的品牌 fixture,
// 避免把模板示例内容误当成所有品牌的数据库初始数据。
const trustContent = template.trustContent;
const inquiryFields = (packageSample?.fields ?? template.inquiryForm.fieldsSnapshot).map(
(field) => ({
...field,
...(Array.isArray(field.options)
? {
options: field.options.map((option) =>
typeof option === "string" ? { label: option, value: option } : option,
),
}
: {}),
}),
);
// 这里只初始化明确的开发演示品牌;餐饮结构化槽位和表单取自对应 package,
// 新增生产模板无需添加 seed 分支,品牌样例内容仍须由管理员显式导入。
const offerings = template.offerings;
const foodSample =
template.templateKey === "food"
? getTemplatePackageManifestForVisualKey("acheng-campus-food")?.sampleContent?.food
: undefined;
if (template.templateKey === "food" && !foodSample)
throw new Error("Food development sample is missing");
const trustContent = foodSample
? foodSample.trustContent.map((item) => {
const fixture = template.trustContent.find((entry) => entry.type === item.type);
return { ...item, ...fixture, config: { ...item.config, ...fixture?.config } };
})
: template.trustContent;
const inquiryFields = foodSample?.fields ?? template.inquiryForm?.fieldsSnapshot;
const inquiryFormName = foodSample?.inquiryFormName ?? template.inquiryForm?.name;
if (!inquiryFields?.length || !inquiryFormName)
throw new Error("Development inquiry fixture is missing");
const existingBrand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
const existingConfig =
existingBrand.config &&
typeof existingBrand.config === "object" &&
!Array.isArray(existingBrand.config)
? (existingBrand.config as Record<string, unknown>)
: {};
await prisma.brandProfile.update({
where: { id: brandId },
data: {
config: template.brandConfig,
config: { ...existingConfig, ...template.brandConfig } as Prisma.InputJsonValue,
...(existingBrand.slug === "default-brand" && !existingBrand.avatarUrl
? { avatarUrl: "/assets/owner/portrait.jpg" }
: {}),
},
});
for (const [sortOrder, item] of offerings.entries()) {
@@ -747,7 +721,8 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
select: { id: true, name: true },
});
for (const [index, item] of incompleteOfferings.entries()) {
const image = template.offerings[index % template.offerings.length].image;
const image = template.offerings[index % template.offerings.length]?.image;
if (!image) throw new Error("Development fixture has no offering image");
await prisma.offering.update({
where: { id: item.id },
data: {
@@ -764,9 +739,17 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
}
for (const [sortOrder, item] of trustContent.entries()) {
const existing = await prisma.trustContent.findFirst({
where: { brandId, type: item.type, title: item.title },
where: { brandId, type: item.type },
orderBy: [{ isPublished: "desc" }, { sortOrder: "asc" }],
});
const data = { ...item, brandId, sortOrder, isPublished: true };
const { config, ...fields } = item;
const data = {
...fields,
brandId,
sortOrder,
isPublished: true,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
};
if (existing) await prisma.trustContent.update({ where: { id: existing.id }, data });
else await prisma.trustContent.create({ data });
}
@@ -775,7 +758,7 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
orderBy: { createdAt: "asc" },
});
const formData = {
name: template.inquiryForm.name,
name: inquiryFormName,
purpose: "inquiry",
targetType: "brand",
submissionAction: "create-inquiry",
@@ -788,14 +771,14 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
}
async function ensureSeedRelease(brandId: string, actorId: string): Promise<void> {
if (await prisma.brandRelease.findFirst({ where: { brandId } })) return;
const snapshot = await buildBrandReleaseSnapshot(prisma, brandId);
await prisma.brandRelease.deleteMany({ where: { brandId } });
await prisma.brandRelease.create({
data: {
brandId,
version: 1,
status: "published",
snapshot,
snapshot: snapshot as unknown as Prisma.InputJsonValue,
actorId,
note: "seed 基线发布版本",
},
@@ -0,0 +1,85 @@
/** 仅恢复开发餐饮品牌的原型视觉槽位,不覆盖已有结构化编辑和发布历史。 */
import "reflect-metadata";
import fs from "node:fs";
import { PrismaClient, type Prisma } from "@prisma/client";
import { getTemplatePackageManifestForVisualKey } from "@personal-brand/config";
import { BrandReleaseService } from "../src/brand-release.service.js";
import { BrandReleaseApiService } from "../src/brand-release-api.service.js";
import type { PrismaService } from "../src/prisma.service.js";
const prisma = new PrismaClient();
const note = "餐饮主理人原型视觉槽位迁移 v1";
try {
const brand = await prisma.brandProfile.findUniqueOrThrow({ where: { slug: "default-brand" } });
const config = (brand.config ?? {}) as Record<string, unknown>;
if (brand.templateKey !== "food" || config.visualTemplateKey !== "acheng-campus-food")
throw new Error("Migration is restricted to the development food brand");
const previous = await prisma.brandRelease.findFirst({
where: { brandId: brand.id },
orderBy: { version: "desc" },
});
if (await prisma.brandRelease.findFirst({ where: { brandId: brand.id, note } })) {
console.log("Already migrated; no changes");
} else {
const trust = await prisma.trustContent.findMany({
where: { brandId: brand.id },
orderBy: [{ sortOrder: "asc" }, { createdAt: "asc" }],
});
const backup = `/tmp/food-owner-visual-backup-${Date.now()}.json`;
fs.writeFileSync(backup, JSON.stringify({ brand, trust, previous }, null, 2), { mode: 0o600 });
console.log(`Backup: ${backup}`);
if (!process.argv.includes("--apply"))
console.log("Dry run; pass --apply to migrate and publish");
else {
const sample =
getTemplatePackageManifestForVisualKey("acheng-campus-food")!.sampleContent!.food!;
const service = new BrandReleaseService(prisma as PrismaService);
const publisher = new BrandReleaseApiService(prisma as PrismaService, service);
await prisma.$transaction(async (tx) => {
await tx.brandProfile.update({
where: { id: brand.id },
data: { avatarUrl: brand.avatarUrl || "/assets/owner/portrait.jpg" },
});
for (const type of ["credential", "case", "promise"]) {
const item = trust.find((item) => item.type === type && item.isPublished);
if (!item) continue;
const defaults = sample.trustContent.find((item) => item.type === type)!;
const existing = (item.config ?? {}) as Record<string, unknown>;
// 只补迁移前已确认的开发样例内容;用户改写的正文不能被模板样例遮挡。
const known =
type === "credential"
? item.content === "当天采购,现做现出餐;食具每日清洁消毒,按约定标注和分装。"
: item.content === defaults.content;
if (!known) continue;
await tx.trustContent.update({
where: { id: item.id },
data: {
config: { ...defaults.config, ...existing } as Prisma.InputJsonValue,
},
});
}
const readiness = await publisher.readiness(brand.id, tx);
if (!readiness.ready)
throw new Error(JSON.stringify(readiness.checks.filter((check) => !check.passed)));
const snapshot = await service.buildSnapshot(brand.id, tx);
await tx.brandRelease.updateMany({
where: { brandId: brand.id, status: "published" },
data: { status: "superseded" },
});
await tx.brandRelease.create({
data: {
brandId: brand.id,
version: (previous?.version ?? 0) + 1,
actorId: previous?.actorId ?? "content-migration",
note,
snapshot: snapshot as unknown as Prisma.InputJsonValue,
},
});
});
console.log(
"Owner visual slots migrated and published; existing edits and historical releases retained",
);
}
}
} finally {
await prisma.$disconnect();
}
@@ -0,0 +1,157 @@
/** 开发餐饮品牌的幂等内容迁移。保留旧记录为草稿,历史快照和提交不变。 */
import "reflect-metadata";
import fs from "node:fs";
import type { Prisma } from "@prisma/client";
import { PrismaClient } from "@prisma/client";
import { getTemplatePackageManifestForVisualKey } from "@personal-brand/config";
import { BrandReleaseService } from "../src/brand-release.service.js";
import { BrandReleaseApiService } from "../src/brand-release-api.service.js";
import type { PrismaService } from "../src/prisma.service.js";
const prisma = new PrismaClient();
const note = "餐饮模板结构化内容迁移 v3";
try {
const brand = await prisma.brandProfile.findUniqueOrThrow({ where: { slug: "default-brand" } });
if (
brand.templateKey !== "food" ||
(brand.config as Record<string, unknown>)?.visualTemplateKey !== "acheng-campus-food"
)
throw new Error("Migration is restricted to the development food brand");
const previous = await prisma.brandRelease.findFirst({
where: { brandId: brand.id },
orderBy: { version: "desc" },
});
if (previous?.note === note) {
console.log("Already migrated; no changes");
} else {
const trust = await prisma.trustContent.findMany({
where: { brandId: brand.id },
orderBy: { updatedAt: "desc" },
});
const forms = await prisma.inquiryForm.findMany({ where: { brandId: brand.id } });
const backup = `/tmp/food-template-content-backup-${Date.now()}.json`;
fs.writeFileSync(backup, JSON.stringify({ brand, trust, forms, previous }, null, 2), {
mode: 0o600,
});
console.log(`Backup: ${backup}`);
if (!process.argv.includes("--apply")) {
console.log("Dry run; pass --apply to migrate and publish");
} else {
const sample =
getTemplatePackageManifestForVisualKey("acheng-campus-food")!.sampleContent!.food!;
const releaseService = new BrandReleaseService(prisma as PrismaService);
const publisher = new BrandReleaseApiService(prisma as PrismaService, releaseService);
await prisma.$transaction(async (tx) => {
for (const type of ["schedule", "coverage", "process"]) {
const candidates = trust.filter((item) => item.type === type);
const structured = candidates.find(
(item) => item.config && Object.keys(item.config as object).length,
);
const current = structured ?? candidates[0];
const defaults = sample.trustContent.find((item) => item.type === type)!;
const config = {
...defaults.config,
...((structured?.config as Record<string, unknown>) ?? {}),
};
// 已有的结构化配置保留。旧配送记录中的用户地点保留在自取说明中。
if (type === "coverage") {
const custom = candidates.find(
(item) =>
item.title !== defaults.title && item.content !== "示例内容,待品牌主理人完善。",
);
if (custom && !structured)
config.pickupDetail = `${custom.content}。${String(config.pickupDetail)}`;
}
if (type === "schedule") {
if (config.weekdayDetail === "二号校门外小吃商业街 #07 号铺位 · 17:00 - 22:30")
config.weekdayDetail = defaults.config!.weekdayDetail;
if (config.weekendDetail === "白天承接团体单;晚间 18:00 - 23:00 体育馆南侧流动出摊")
config.weekendDetail = defaults.config!.weekendDetail;
const custom = candidates.find((item) => !item.config && item.summary && item.content);
if (custom) {
config.weekdayHours = custom.summary!.replace(/^周一(?:到|至)周五\s*/, "");
config.weekendHours = custom.content.replace(/^周六(?:到|至)周(?:天|日)\s*/, "");
}
}
if (current)
await tx.trustContent.update({
where: { id: current.id },
data: {
title: defaults.title,
content: "",
summary: null,
config: config as Prisma.InputJsonValue,
isPublished: true,
},
});
else
await tx.trustContent.create({
data: {
brandId: brand.id,
type,
title: defaults.title,
content: "",
config: config as Prisma.InputJsonValue,
isPublished: true,
},
});
await tx.trustContent.updateMany({
where: {
brandId: brand.id,
type,
id: {
in: candidates.filter((item) => item.id !== current?.id).map((item) => item.id),
},
},
data: { isPublished: false },
});
}
const supportedTypes = getTemplatePackageManifestForVisualKey(
"acheng-campus-food",
)!.trustContentTypes!.map((item) => item.type);
await tx.trustContent.updateMany({
where: { brandId: brand.id, type: { notIn: supportedTypes } },
data: { isPublished: false },
});
const form = forms.find((item) => item.targetType === "brand" && item.isEnabled);
if (!form) throw new Error("Expected existing brand inquiry form");
const oldFields = form.fieldsSnapshot as Array<Record<string, unknown>>;
const keys = new Set(sample.fields.map((field) => field.key));
const fields = [
...sample.fields.map((field) => ({
...field,
...oldFields.find((old) => old.key === field.key),
})),
...oldFields.filter((field) => !keys.has(String(field.key))),
];
await tx.inquiryForm.update({
where: { id: form.id },
data: {
name: sample.inquiryFormName,
fieldsSnapshot: fields as Prisma.InputJsonValue,
version: { increment: 1 },
},
});
const readiness = await publisher.readiness(brand.id, tx);
if (!readiness.ready)
throw new Error(JSON.stringify(readiness.checks.filter((check) => !check.passed)));
const snapshot = await releaseService.buildSnapshot(brand.id, tx);
await tx.brandRelease.updateMany({
where: { brandId: brand.id, status: "published" },
data: { status: "superseded" },
});
await tx.brandRelease.create({
data: {
brandId: brand.id,
version: (previous?.version ?? 0) + 1,
actorId: previous?.actorId ?? "content-migration",
note,
snapshot: snapshot as unknown as Prisma.InputJsonValue,
},
});
});
console.log("Migrated and published development food brand; old content retained as drafts");
}
}
} finally {
await prisma.$disconnect();
}
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "../tsconfig.json",
"compilerOptions": { "rootDir": "..", "noEmit": true },
"include": ["*.ts", "../src/**/*.ts", "../prisma/seed.ts"]
}
+153
View File
@@ -0,0 +1,153 @@
import fs from "node:fs";
import vm from "node:vm";
import assert from "node:assert/strict";
process.env.NODE_ENV = "test";
const { createApp } = await import("../dist/main.js");
const app = await createApp();
try {
await app.init();
const response = await app
.getHttpAdapter()
.getInstance()
.inject({ method: "GET", url: "/public/workspace?brandSlug=default-brand" });
assert.equal(response.statusCode, 200);
const workspace = JSON.parse(response.body) as Record<string, unknown>;
const trustItems = workspace.trustItems as { id?: string }[];
assert.ok(trustItems.every((item) => typeof item.id === "string"));
const live = await fetch(
`http://127.0.0.1:${process.env.API_PORT ?? 3001}/public/workspace?brandSlug=default-brand`,
);
assert.equal(live.status, 200);
const liveWorkspace = (await live.json()) as Record<string, unknown>;
assert.deepEqual(liveWorkspace.trustItems, workspace.trustItems);
assert.deepEqual(liveWorkspace.inquiryForms, workspace.inquiryForms);
fs.writeFileSync("/tmp/food-template-public-workspace.json", JSON.stringify(workspace, null, 2));
let page:
| {
data: Record<string, unknown>;
load: () => Promise<void>;
setData: (value: Record<string, unknown>) => void;
}
| undefined;
vm.runInNewContext(
fs.readFileSync("../../dist/miniapp/default-brand/pages/stall-service/index.js", "utf8"),
{
Page(value: typeof page) {
page = value;
},
require(name: string) {
return name.includes("runtime-workspace")
? { loadWorkspaceWithFallback: () => Promise.resolve(workspace) }
: { openPage() {} };
},
},
);
assert.ok(page);
page.setData = (data) => Object.assign(page!.data, data);
await page.load();
const data = page.data as {
schedule: { rows: unknown[] };
coverage: { config: { pickupDetail: string; deliveryDetail: string } };
process: { steps: unknown[] };
};
assert.equal(data.schedule.rows.length, 2);
assert.ok(data.coverage.config.pickupDetail && data.coverage.config.deliveryDetail);
assert.equal(data.process.steps.length, 4);
const forms = workspace.inquiryForms as { fields: { key: string }[] }[];
for (const key of ["type", "people", "date", "budget", "delivery", "remark", "phone"])
assert.ok(forms.some((form) => form.fields.some((field) => field.key === key)));
fs.writeFileSync("/tmp/food-template-service-page-data.json", JSON.stringify(page.data, null, 2));
let inquiry:
| {
data: Record<string, unknown>;
onLoad: (options: Record<string, unknown>) => Promise<void>;
setData: (value: Record<string, unknown>) => void;
}
| undefined;
vm.runInNewContext(
fs.readFileSync("../../dist/miniapp/default-brand/pages/inquiry/index.js", "utf8"),
{
Page(value: typeof inquiry) {
inquiry = value;
},
require(name: string) {
return name.includes("runtime-workspace")
? { loadWorkspaceWithFallback: () => Promise.resolve(workspace) }
: {};
},
},
);
assert.ok(inquiry);
inquiry.setData = (value) => Object.assign(inquiry!.data, value);
await inquiry.onLoad({});
const inquiryFields = inquiry.data.fields as {
key: string;
useChips: boolean;
halfWidth: boolean;
}[];
assert.equal(inquiryFields.find((field) => field.key === "type")?.useChips, true);
assert.equal(inquiryFields.filter((field) => field.halfWidth).length, 4);
fs.writeFileSync(
"/tmp/food-template-inquiry-page-data.json",
JSON.stringify(inquiry.data, null, 2),
);
console.log(
"Actual database -> published API -> generated page: 2 schedule cards, 2 delivery columns, 4 steps, food inquiry fields verified",
);
const doorsResponse = await app
.getHttpAdapter()
.getInstance()
.inject({ method: "GET", url: "/public/workspace?brandSlug=linjing-doors" });
assert.equal(doorsResponse.statusCode, 200);
const doors = JSON.parse(doorsResponse.body) as {
trustItems: { type: string; content: string; config: Record<string, unknown> }[];
trustPresentation: Record<string, unknown>;
};
assert.equal(
doors.trustItems.some((item: { type: string }) => item.type === "profile"),
false,
);
const credentials = doors.trustItems.filter(
(item: { type: string }) => item.type === "credential",
);
const primary = credentials.find(
(item: { config: object }) => Object.keys(item.config).length > 0,
);
assert.ok(primary);
assert.deepEqual(doors.trustPresentation.stats, primary.config.stats);
const liveDoors = await fetch(
`http://127.0.0.1:${process.env.API_PORT ?? 3001}/public/workspace?brandSlug=linjing-doors`,
);
assert.equal(liveDoors.status, 200);
const liveDoorsWorkspace = (await liveDoors.json()) as Record<string, unknown>;
assert.deepEqual(liveDoorsWorkspace.trustPresentation, doors.trustPresentation);
type DoorsPage = {
data: { trustPresentation: { bio: string } };
setData: (value: object) => void;
onLoad: () => void;
};
let doorsPage: DoorsPage | undefined;
vm.runInNewContext(
fs.readFileSync("../../dist/miniapp/linjing-doors/pages/index/index.js", "utf8"),
{
Page(value: DoorsPage) {
doorsPage = value;
},
require() {
return { loadWorkspaceWithFallback: () => Promise.resolve(doors) };
},
wx: { setNavigationBarTitle() {} },
},
);
assert.ok(doorsPage);
doorsPage.setData = (value: object) => Object.assign(doorsPage!.data, value);
doorsPage.onLoad();
await new Promise((resolve) => setImmediate(resolve));
assert.equal(doorsPage.data.trustPresentation.bio, primary.content);
fs.writeFileSync("/tmp/linjing-template-page-data.json", JSON.stringify(doorsPage.data, null, 2));
console.log(
"Linjing published API -> generated page: declared credential stats and biography verified; obsolete profile excluded",
);
} finally {
await app.close();
}
+37 -2
View File
@@ -183,6 +183,11 @@ class AdminWorkspaceController {
? {
displayName: manifest.displayName,
admin: manifest.admin,
navigation: manifest.navigation.map(({ key, label, page }) => ({ key, label, page })),
templateFields: (manifest.templateFields ?? []).map((field) => ({
...field,
binding: field.binding ?? `brand.config.templateData.${field.key}`,
})),
assetSlots: manifest.assetSlots,
trustContentTypes: manifest.trustContentTypes ?? [],
}
@@ -244,7 +249,10 @@ class AdminWorkspaceController {
offerings: sample.offerings.length,
trustContent: sample.trustContent.length,
fields: sample.fields.length,
inquiryForms: 1,
},
willCreateInquiryForm:
(await this.prisma.inquiryForm.count({ where: { brandId, isEnabled: true } })) === 0,
};
}
@@ -255,6 +263,8 @@ class AdminWorkspaceController {
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
const sample = getTemplateSampleContent(templateKey);
if (!sample) throw new BadRequestException("模板示例内容不存在");
const fieldIssues = validateFieldSnapshot(sample.fields);
if (fieldIssues.length) throw new BadRequestException("模板咨询表单示例字段无效");
const existing = await this.prisma.brandFieldDefinition.count({
where: { brandId, source: "sample" },
});
@@ -280,6 +290,7 @@ class AdminWorkspaceController {
type: item.type,
title: item.title,
content: item.content,
...(item.config ? { config: item.config as Prisma.InputJsonValue } : {}),
sortOrder,
isPublished: false,
})),
@@ -296,6 +307,20 @@ class AdminWorkspaceController {
required: item.required,
})),
});
const hasEnabledForm = await tx.inquiryForm.count({ where: { brandId, isEnabled: true } });
const inquiryForm = hasEnabledForm
? null
: await tx.inquiryForm.create({
data: {
brandId,
name: sample.inquiryFormName,
purpose: "inquiry",
targetType: "brand",
submissionAction: "create-inquiry",
fieldsSnapshot: sample.fields,
isEnabled: true,
},
});
await tx.capabilityAuditLog.create({
data: {
brandId,
@@ -303,10 +328,20 @@ class AdminWorkspaceController {
actorId: identity.subject,
action: "sample_content_imported",
toStatus: "enabled",
config: { offerings: offerings.count, trustContent: trust.count, fields: fields.count },
config: {
offerings: offerings.count,
trustContent: trust.count,
fields: fields.count,
inquiryForms: inquiryForm ? 1 : 0,
},
},
});
return { offerings: offerings.count, trustContent: trust.count, fields: fields.count };
return {
offerings: offerings.count,
trustContent: trust.count,
fields: fields.count,
inquiryForms: inquiryForm ? 1 : 0,
};
});
return { imported: true, counts: result };
}
+6 -9
View File
@@ -56,28 +56,25 @@ export class ChangeAdminPasswordDto {
}
export class CreateTrustContentDto {
@IsIn(["schedule", "coverage", "process", "credential", "case", "promise"])
type!: string;
@IsString() type!: string;
@IsString() title!: string;
@IsOptional() @IsString() summary?: string;
@IsString() content!: string;
@IsOptional() @IsString() coverUrl?: string;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() @IsBoolean() isPublished?: boolean;
@IsOptional() config?: Record<string, unknown>;
@IsOptional() @IsObject() config?: Record<string, unknown>;
}
export class UpdateTrustContentDto {
@IsOptional()
@IsIn(["schedule", "coverage", "process", "credential", "case", "promise"])
type?: string;
@IsOptional() @IsString() type?: string;
@IsOptional() @IsString() title?: string;
@IsOptional() @IsString() summary?: string;
@IsOptional() @IsString() content?: string;
@IsOptional() @IsString() coverUrl?: string;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() @IsBoolean() isPublished?: boolean;
@IsOptional() config?: Record<string, unknown>;
@IsOptional() @IsObject() config?: Record<string, unknown>;
}
export class UpdateBookingStatusDto {
@@ -125,7 +122,7 @@ export class CreateOfferingDto {
@IsOptional() @IsInt() @Min(0) priceAmount?: number;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() @IsBoolean() isEnabled?: boolean;
@IsOptional() config?: Record<string, unknown>;
@IsOptional() @IsObject() config?: Record<string, unknown>;
@IsOptional() sections?: Array<{
type: string;
title: string;
@@ -146,7 +143,7 @@ export class UpdateOfferingDto {
@IsOptional() @IsInt() @Min(0) priceAmount?: number;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() @IsBoolean() isEnabled?: boolean;
@IsOptional() config?: Record<string, unknown>;
@IsOptional() @IsObject() config?: Record<string, unknown>;
@IsOptional() sections?: Array<{
type: string;
title: string;
+20 -5
View File
@@ -12,6 +12,7 @@ import {
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
} from "@personal-brand/config";
import { isTrustContentComplete } from "@personal-brand/types";
import { PrismaService } from "./prisma.service.js";
import { BrandReleaseService } from "./brand-release.service.js";
import { validateFieldSnapshot } from "@personal-brand/validation";
@@ -80,11 +81,14 @@ export class BrandReleaseApiService {
}),
database.trustContent.findMany({
where: { brandId, isPublished: true },
select: { type: true, title: true, content: true },
select: { type: true, title: true, content: true, config: true },
}),
]);
const validTrustItems = trustItems.filter(
(item) => item.title.trim().length > 0 && item.content.trim().length > 0,
const validTrustItems = trustItems.filter((item) =>
isTrustContentComplete(
item,
packageManifest?.trustContentTypes?.find((type) => type.type === item.type),
),
);
const offeringIds = new Set(offerings.map((item) => item.id));
const usableForms = forms.filter(
@@ -145,8 +149,19 @@ export class BrandReleaseApiService {
checks.push({
key: `trust:${type.type}`,
label: `请完善${type.label}`,
passed: publishedTrustTypes.has(type.type),
help: ["标题和详细内容都填写后才能发布。", type.help].filter(Boolean).join(" "),
passed:
publishedTrustTypes.has(type.type) &&
(type.maxPublishedItems === undefined ||
trustItems.filter((item) => item.type === type.type).length <= type.maxPublishedItems),
help: [
"请完整填写该区块的可编辑字段。",
type.maxPublishedItems === undefined
? undefined
: `此区块最多保留 ${type.maxPublishedItems} 条公开记录。`,
type.help,
]
.filter(Boolean)
.join(" "),
destination: "/admin/trust",
});
}
@@ -80,7 +80,15 @@ export class AdminConfigController {
current?.config && typeof current.config === "object" && !Array.isArray(current.config)
? (current.config as Record<string, unknown>)
: {};
const nextConfig = config ? { ...currentConfig, ...config } : undefined;
const nextConfig = {
...currentConfig,
...(config ?? {}),
// 兼容旧模板:品牌简介的唯一编辑入口是 BrandProfile.description,
// 旧视觉模板仍从 config.slogan 读取,保存时保持两者同步。
...(fields.description !== undefined && config?.slogan === undefined
? { slogan: fields.description }
: {}),
};
if (config?.visualTemplateKey && config.visualTemplateKey !== currentConfig.visualTemplateKey) {
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(
this.brandId(request),
@@ -121,7 +129,7 @@ export class AdminConfigController {
where: { id: this.brandId(request) },
data: {
...fields,
...(nextConfig ? { config: nextConfig as Prisma.InputJsonValue } : {}),
...(Object.keys(nextConfig).length ? { config: nextConfig } : {}),
},
});
}
@@ -300,34 +308,17 @@ export class AdminConfigController {
@Body() body: CreateTrustContentDto,
): Promise<unknown> {
this.requireAdmin(request);
const { config, ...fields } = body;
return this.prisma.trustContent.create({
data: {
...fields,
brandId: this.brandId(request),
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
const brandId = this.brandId(request);
return this.templateWorkspace.createTrustContent(brandId, body);
}
@Patch("trust-content/:id")
async updateTrustContent(
updateTrustContent(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateTrustContentDto,
): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.trustContent.findFirst({
where: { id, brandId: this.brandId(request) },
});
if (!item) throw new BadRequestException("信任内容不存在");
const { config, ...fields } = body;
return this.prisma.trustContent.update({
where: { id },
data: {
...fields,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
return this.templateWorkspace.updateTrustContent(this.brandId(request), id, body);
}
@Delete("trust-content/:id")
async deleteTrustContent(
@@ -18,6 +18,13 @@ import type {
RuntimeTrustItem,
RuntimeWorkspace,
} from "@personal-brand/types";
import {
projectBrandAliases,
projectOfferingDetails,
projectTemplateData,
projectTrustItem,
projectTrustPresentation,
} from "@personal-brand/types";
@Controller("public/workspace")
export class PublicWorkspaceController {
@@ -113,15 +120,19 @@ export class PublicWorkspaceController {
const templatePackageManifest =
releaseSnapshot.templatePackageManifest ??
getTemplatePackageManifestForVisualKey(visualTemplateKey);
const runtimeBrand = {
...brandData,
...brandConfig,
};
// 标准 BrandProfile 字段优先,兼容旧模板仍使用的 config 字段。
// 这样后台编辑 description/contactPhone 等标准字段后,旧模板也会立即读取新值。
const runtimeBrand = projectBrandAliases(brandData, brandConfig);
const declaredTemplateFields = templatePackageManifest?.templateFields ?? [];
const templateData = projectTemplateData(
brandConfig,
declaredTemplateFields.map((field) => field.key),
);
const runtimeOfferings: RuntimeOffering[] = offeringsData.map((raw) => {
const item = raw;
const config = this.jsonObject(item.config);
const sections = Array.isArray(config.sections) ? config.sections : [];
const details = this.jsonObject(config.details);
const details = projectOfferingDetails(config);
const media = Array.isArray(config.media)
? config.media.flatMap((entry) => {
const value = this.jsonObject(entry);
@@ -139,14 +150,6 @@ export class PublicWorkspaceController {
: [];
})
: [];
const materialsList = Array.isArray(details.materialsList)
? details.materialsList.flatMap((entry) => {
const value = this.jsonObject(entry);
return typeof value.name === "string" && typeof value.spec === "string"
? [{ name: value.name, spec: value.spec }]
: [];
})
: [];
return {
id: this.string(item.id),
name: this.string(item.name),
@@ -187,12 +190,10 @@ export class PublicWorkspaceController {
: [],
media,
details: {
background: typeof details.background === "string" ? details.background : "",
designConcept: typeof details.designConcept === "string" ? details.designConcept : "",
crafts: Array.isArray(details.crafts)
? details.crafts.filter((craft): craft is string => typeof craft === "string")
: [],
materialsList,
background: details.background,
designConcept: details.designConcept,
crafts: details.crafts,
materialsList: details.materialsList,
},
},
sections: sections
@@ -211,18 +212,25 @@ export class PublicWorkspaceController {
if (!field || typeof field !== "object") return [];
const value = field as Record<string, unknown>;
if (typeof value.key !== "string" || typeof value.label !== "string") return [];
const type = [
"text",
"tel",
"number",
"select",
"radio",
"checkbox",
"textarea",
"date",
].includes(this.string(value.type))
? (value.type as RuntimeInquiryField["type"])
: "text";
const sourceType = this.string(value.type);
const type =
sourceType === "phone"
? "tel"
: sourceType === "multi-select"
? "checkbox"
: [
"text",
"tel",
"number",
"select",
"radio",
"checkbox",
"checkbox",
"textarea",
"date",
].includes(sourceType)
? (sourceType as RuntimeInquiryField["type"])
: "text";
const options = Array.isArray(value.options)
? value.options.flatMap((option) => {
if (typeof option === "string") return [{ label: option, value: option }];
@@ -243,28 +251,14 @@ export class PublicWorkspaceController {
},
];
});
const trustPresentation = trustData.reduce<Record<string, unknown>>((result, raw) => {
const item = this.jsonObject(raw);
const config = this.jsonObject(item.config);
for (const [key, value] of Object.entries(config)) {
if (!(key in result)) result[key] = value;
}
if (item.type === "profile" && typeof result.bio !== "string") result.bio = item.content;
return result;
}, {});
const trustDeclarations = templatePackageManifest?.trustContentTypes ?? [];
const trustItems: RuntimeTrustItem[] = trustData.flatMap((raw) => {
const item = this.jsonObject(raw);
if (typeof item.type !== "string" || typeof item.title !== "string") return [];
return [
{
type: item.type,
title: item.title,
summary: typeof item.summary === "string" ? item.summary : null,
content: typeof item.content === "string" ? item.content : "",
config: this.jsonObject(item.config),
},
];
const item = projectTrustItem(this.jsonObject(raw));
return item && trustDeclarations.some((declaration) => declaration.type === item.type)
? [item]
: [];
});
const trustPresentation = projectTrustPresentation(trustItems, trustDeclarations);
const runtimeWorkspace: RuntimeWorkspace = {
schemaVersion: "1.0.0",
publication: {
@@ -273,6 +267,7 @@ export class PublicWorkspaceController {
publishedAt: release.createdAt.toISOString(),
},
brand: runtimeBrand,
templateData,
navigation: {
tabs:
templatePackageManifest?.navigation.map((tab) => ({
@@ -5,14 +5,61 @@ import {
getVisualTemplate,
getVisualTemplateManifest,
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
isVisualTemplateCompatible,
} from "@personal-brand/config";
import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.js";
import type { BrandTemplateKey } from "@personal-brand/types";
import { PrismaService } from "./prisma.service.js";
@Injectable()
export class TemplateWorkspaceService {
constructor(private readonly prisma: PrismaService) {}
async getTrustContentTypes(brandId: string): Promise<string[]> {
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true, config: true },
});
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const visualKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: getDefaultVisualTemplateKey(brand?.templateKey ?? "personal");
return (
getTemplatePackageManifestForVisualKey(visualKey)?.trustContentTypes?.map(
(item) => item.type,
) ?? []
);
}
async createTrustContent(brandId: string, body: CreateTrustContentDto) {
if (!(await this.getTrustContentTypes(brandId)).includes(body.type))
throw new BadRequestException("当前模板不支持此信任内容类型");
const { config, ...fields } = body;
return this.prisma.trustContent.create({
data: {
...fields,
brandId,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
async updateTrustContent(brandId: string, id: string, body: UpdateTrustContentDto) {
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
if (!item) throw new BadRequestException("信任内容不存在");
if (body.type !== undefined && !(await this.getTrustContentTypes(brandId)).includes(body.type))
throw new BadRequestException("当前模板不支持此信任内容类型");
const { config, ...fields } = body;
return this.prisma.trustContent.update({
where: { id },
data: {
...fields,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
async getEffectiveTemplateKey(brandId: string): Promise<BrandTemplateKey> {
const [installation, brand] = await Promise.all([
this.prisma.brandTemplateInstallation.findFirst({
+358 -7
View File
@@ -28,6 +28,211 @@ after(async () => {
await prisma.$disconnect();
});
test("food structured edits survive publication and reach the generated page slots", async () => {
const { readFileSync } = await import("node:fs");
const { runInNewContext } = await import("node:vm");
const user = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
const headers = {
authorization: `Bearer ${signIdentity({ subject: user.id, brandId, role: "admin" })}`,
};
const records = await prisma.trustContent.findMany({
where: {
brandId,
type: { in: ["schedule", "coverage", "process", "credential", "case", "promise"] },
isPublished: true,
},
});
const latest = await prisma.brandRelease.findFirstOrThrow({
where: { brandId },
orderBy: { version: "desc" },
});
const before = JSON.parse((await request("/public/workspace")).body);
try {
for (const item of records) {
const url = `/admin/config/trust-content/${item.id}`;
assert.equal(
(await request(url, { method: "PATCH", payload: { config: {} } })).statusCode,
401,
);
assert.equal(
(
await request(url, {
method: "PATCH",
headers: { authorization: `Bearer ${customerToken}` },
payload: { config: {} },
})
).statusCode,
403,
);
assert.equal(
(await request(url, { method: "PATCH", headers, payload: { config: "invalid" } }))
.statusCode,
400,
);
const config = { ...item.config };
if (item.type === "schedule") {
config.weekdayDetail = "测试工作日地点";
config.weekendDetail = "测试周末地点";
}
if (item.type === "coverage") {
config.pickupDetail = "测试自取说明";
config.deliveryDetail = "测试配送说明";
}
if (item.type === "process")
config.steps = [{ title: "测试第一步", detail: "测试步骤说明" }, ...config.steps.slice(1)];
if (item.type === "credential")
config.standards = [{ title: "编辑后的卫生标准", detail: "编辑后的说明" }];
if (item.type === "case")
config.entries = [
{ badge: "测", title: "编辑后的合作案例", detail: "编辑后的交付", result: "完成" },
];
if (item.type === "promise")
config.commitments = [
{ label: "测试时段", detail: "编辑后的回复说明", highlight: "30 分钟内" },
];
assert.equal(
(
await request(url, {
method: "PATCH",
headers,
payload: {
content: ["schedule", "coverage", "process"].includes(item.type) ? "" : item.content,
config,
},
})
).statusCode,
200,
);
}
assert.deepEqual(
JSON.parse((await request("/public/workspace")).body).trustItems,
before.trustItems,
);
assert.equal(
(
await request("/admin/releases/publish", {
method: "POST",
headers,
payload: { note: "结构化页面集成测试" },
})
).statusCode,
201,
);
const workspace = JSON.parse((await request("/public/workspace")).body);
let page;
runInNewContext(
readFileSync(
new URL(
"../../../packages/template-acheng-campus-food/miniapp/pages/stall-service/index.js",
import.meta.url,
),
"utf8",
),
{
Page(value) {
page = value;
},
require(name) {
return name.includes("runtime-workspace")
? { loadWorkspaceWithFallback: () => Promise.resolve(workspace) }
: { openPage() {} };
},
},
);
page.setData = (data) => Object.assign(page.data, data);
await page.load();
assert.equal(page.data.schedule.rows.length, 2);
assert.equal(page.data.schedule.rows[0].detail, "测试工作日地点");
assert.equal(page.data.schedule.rows[1].detail, "测试周末地点");
assert.equal(page.data.coverage.config.pickupDetail, "测试自取说明");
assert.equal(page.data.coverage.config.deliveryDetail, "测试配送说明");
assert.equal(page.data.process.steps.length, 4);
assert.equal(page.data.process.steps[0].detail, "测试步骤说明");
let owner;
runInNewContext(
readFileSync(
new URL(
"../../../packages/template-acheng-campus-food/miniapp/pages/bookings/index.js",
import.meta.url,
),
"utf8",
),
{
Page(value) {
owner = value;
},
require(name) {
return name.includes("runtime-workspace")
? { loadWorkspaceWithFallback: () => Promise.resolve(workspace) }
: {};
},
},
);
owner.setData = (data) => Object.assign(owner.data, data);
owner.onLoad();
await new Promise((resolve) => setImmediate(resolve));
assert.equal(owner.data.credentials[0].config.standards[0].title, "编辑后的卫生标准");
assert.equal(owner.data.cases[0].entries[0].result, "完成");
assert.equal(owner.data.promises[0].config.commitments[0].highlight, "30 分钟内");
assert.ok(workspace.trustItems.every((item) => typeof item.summary === "string"));
assert.ok(workspace.trustItems.every((item) => typeof item.id === "string"));
assert.equal(
new Set(workspace.trustItems.map((item) => item.id)).size,
workspace.trustItems.length,
);
const schedule = records.find((item) => item.type === "schedule");
await request(`/admin/config/trust-content/${schedule.id}`, {
method: "PATCH",
headers,
payload: { config: {} },
});
const blocked = await request("/admin/releases/publish", {
method: "POST",
headers,
payload: {},
});
assert.equal(blocked.statusCode, 400);
await prisma.trustContent.update({
where: { id: schedule.id },
data: { config: schedule.config },
});
const duplicate = await prisma.trustContent.create({
data: {
brandId,
type: "schedule",
title: "重复公开日程",
content: "",
config: schedule.config,
isPublished: true,
},
});
try {
const duplicateReadiness = JSON.parse(
(await request("/admin/releases/readiness", { headers })).body,
);
assert.equal(
duplicateReadiness.checks.find((check) => check.key === "trust:schedule").passed,
false,
);
assert.equal(
(await request("/admin/releases/publish", { method: "POST", headers, payload: {} }))
.statusCode,
400,
);
} finally {
await prisma.trustContent.delete({ where: { id: duplicate.id } });
}
} finally {
for (const item of records)
await prisma.trustContent.update({
where: { id: item.id },
data: { config: item.config, content: item.content },
});
await prisma.brandRelease.deleteMany({ where: { brandId, version: { gt: latest.version } } });
await prisma.brandRelease.update({ where: { id: latest.id }, data: { status: latest.status } });
}
});
test("admin release lifecycle is authorized, brand-scoped, and versioned", async () => {
const missing = await request("/admin/releases");
assert.equal(missing.statusCode, 401);
@@ -241,6 +446,7 @@ test("admin release lifecycle is authorized, brand-scoped, and versioned", async
isPublished: scheduleTrust.isPublished,
title: scheduleTrust.title,
content: scheduleTrust.content,
config: scheduleTrust.config,
};
try {
await prisma.trustContent.update({
@@ -274,7 +480,7 @@ test("admin release lifecycle is authorized, brand-scoped, and versioned", async
);
await prisma.trustContent.update({
where: { id: scheduleTrust.id },
data: { title: originalScheduleTrust.title, content: " \n " },
data: { title: originalScheduleTrust.title, content: " \n ", config: {} },
});
const missingContent = JSON.parse(
(
@@ -920,6 +1126,7 @@ test("admin can install doors industry template through the shared runtime contr
test("admin can preview and import sample content idempotently", async () => {
const originalBrand = await prisma.brandProfile.findUnique({ where: { id: brandId } });
const originalForms = await prisma.inquiryForm.findMany({ where: { brandId } });
const originalSampleTrust = await prisma.trustContent.findMany({
where: { brandId, content: "示例内容,待品牌主理人完善。" },
});
@@ -934,6 +1141,15 @@ test("admin can preview and import sample content idempotently", async () => {
where: { brandId, content: "示例内容,待品牌主理人完善。" },
});
await prisma.brandFieldDefinition.deleteMany({ where: { brandId, source: "sample" } });
if (!originalForms.some((item) => item.isEnabled)) {
await prisma.inquiryForm.create({
data: {
brandId,
name: "现有客户表单",
fieldsSnapshot: [{ key: "phone", label: "联系电话", type: "tel", required: true }],
},
});
}
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
@@ -943,11 +1159,35 @@ test("admin can preview and import sample content idempotently", async () => {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(preview.statusCode, 200);
assert.equal(JSON.parse(preview.body).willCreateInquiryForm, false);
const imported = await request("/admin/workspace/sample-content/import", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
});
assert.equal(imported.statusCode, 201);
assert.equal(JSON.parse(imported.body).counts.inquiryForms, 0);
assert.ok(await prisma.inquiryForm.findFirst({ where: { brandId, name: "现有客户表单" } }));
await prisma.offering.deleteMany({
where: {
brandId,
name: { in: ["序章·入户门", "庭院·边界门", "室内·静谧门", "一对一门系统设计咨询"] },
},
});
await prisma.trustContent.deleteMany({
where: { brandId, content: "示例内容,待品牌主理人完善。" },
});
await prisma.brandFieldDefinition.deleteMany({ where: { brandId, source: "sample" } });
await prisma.inquiryForm.deleteMany({ where: { brandId } });
const importedWithoutForm = await request("/admin/workspace/sample-content/import", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
});
assert.equal(importedWithoutForm.statusCode, 201);
assert.equal(JSON.parse(importedWithoutForm.body).counts.inquiryForms, 1);
const importedForm = await prisma.inquiryForm.findFirstOrThrow({
where: { brandId, name: "门系统咨询表单" },
});
assert.ok(Array.isArray(importedForm.fieldsSnapshot) && importedForm.fieldsSnapshot.length > 0);
const duplicate = await request("/admin/workspace/sample-content/import", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
@@ -970,6 +1210,14 @@ test("admin can preview and import sample content idempotently", async () => {
});
}
await prisma.brandFieldDefinition.deleteMany({ where: { brandId, source: "sample" } });
await prisma.inquiryForm.deleteMany({ where: { brandId, name: "门系统咨询表单" } });
if (originalForms.length) {
await prisma.inquiryForm.createMany({
data: originalForms.map(
({ id: _id, createdAt: _createdAt, updatedAt: _updatedAt, ...item }) => item,
),
});
}
await prisma.capabilityAuditLog.deleteMany({ where: { brandId, capabilityKey: "doors" } });
await prisma.brandProfile.update({
where: { id: brandId },
@@ -1039,8 +1287,14 @@ test("admin can install a template and public workspace exposes enabled configur
const templateContent = JSON.parse(workspace.body).templateContent;
assert.equal(templateContent.displayName, "阿成校园餐");
assert.ok(templateContent.trustContentTypes.some((item) => item.type === "schedule"));
assert.ok(templateContent.trustContentTypes.some((item) => item.label === "出摊与营业安排"));
assert.ok(templateContent.trustContentTypes.some((item) => item.label === "每周出摊安排"));
assert.ok(templateContent.admin.sections.some((section) => section.title === "首页出摊信息"));
assert.ok(
templateContent.admin.sections
.filter((section) => section.title === "首页出摊信息")
.every((section) => section.page === "home"),
);
assert.ok(templateContent.navigation.some((item) => item.page === "home" && item.label));
assert.ok(
templateContent.admin.sections
.flatMap((section) => section.fields)
@@ -1197,7 +1451,14 @@ test("public workspace exposes declared brand and trust presentation data", asyn
);
const doorType = body.inquiryForms[0].fields.find((field) => field.key === "doorType");
assert.equal(doorType.options.length, 5);
assert.equal(doorType.options[0].value, "入户大门(防暴铸铜 / 实木)");
assert.equal(doorType.options[0].value, "entry");
const phone = body.inquiryForms[0].fields.find((field) => field.key === "contactPhone");
assert.equal(phone.type, "tel");
const foodWorkspace = await request("/public/workspace?brandSlug=default-brand");
const foodPhone = JSON.parse(foodWorkspace.body).inquiryForms[0].fields.find(
(field) => field.key === "phone",
);
assert.equal(foodPhone.type, "tel");
} finally {
await prisma.brandProfile.update({
where: { id: doorsBrand.id },
@@ -1233,7 +1494,20 @@ test("edited template facts reach public workspace only after publication", asyn
const changedIntro = "集成测试发布后联系说明";
const changedHint = "集成测试咨询后处理说明";
const changedDetailHero = "https://example.com/integration-detail.jpg";
const changedDetailBackground = "集成测试案例详情正文";
const changedTemplateData = "集成测试设计理念";
const changedStats = [{ value: "42", label: "测试成果" }];
const obsolete = await prisma.trustContent.create({
data: {
brandId: doorsBrand.id,
type: "profile",
title: "旧类型不得覆盖模板配置",
content: "旧简介",
config: { stats: [{ value: "旧值", label: "不得显示" }], internalOnly: "不得公开" },
isPublished: true,
sortOrder: -100,
},
});
try {
const brandConfig = originalBrandConfig ?? {};
const presentation = brandConfig.visualPresentation ?? {};
@@ -1248,6 +1522,11 @@ test("edited template facts reach public workspace only after publication", asyn
success: { ...presentation.success, intro: changedIntro },
detail: { ...presentation.detail, inquiryHint: changedHint },
},
templateData: {
...(brandConfig.templateData ?? {}),
designPhilosophy: changedTemplateData,
internalOnly: "不得公开",
},
},
},
});
@@ -1266,6 +1545,10 @@ test("edited template facts reach public workspace only after publication", asyn
...(offering.config ?? {}),
area: changedArea,
detailHero: changedDetailHero,
details: {
...((offering.config ?? {}).details ?? {}),
background: changedDetailBackground,
},
},
},
});
@@ -1298,12 +1581,24 @@ test("edited template facts reach public workspace only after publication", asyn
(await request("/public/workspace?brandSlug=linjing-doors")).body,
);
assert.equal(afterPublish.brand.homeHero.title, changedTitle);
assert.equal(afterPublish.templateData.designPhilosophy, changedTemplateData);
assert.equal(Object.hasOwn(afterPublish.templateData, "internalOnly"), false);
assert.equal(afterPublish.brand.visualPresentation.success.intro, changedIntro);
assert.equal(afterPublish.brand.visualPresentation.detail.inquiryHint, changedHint);
assert.deepEqual(afterPublish.trustPresentation.stats, changedStats);
assert.equal(
afterPublish.trustItems.some((item) => item.type === "profile"),
false,
);
assert.equal(Object.hasOwn(afterPublish.trustPresentation, "internalOnly"), false);
assert.equal(afterPublish.offerings[0].presentation.area, changedArea);
assert.equal(afterPublish.offerings[0].presentation.heroImage, changedDetailHero);
assert.equal(
afterPublish.offerings[0].presentation.details.background,
changedDetailBackground,
);
} finally {
await prisma.trustContent.delete({ where: { id: obsolete.id } });
await prisma.brandProfile.update({
where: { id: doorsBrand.id },
data: { config: originalBrandConfig },
@@ -1377,6 +1672,15 @@ test("admin can create and version an inquiry form", async () => {
label: "联系渠道",
options: [{ label: "微信", value: "wechat" }],
},
{
key: "topics",
type: "multi-select",
label: "关注方向",
options: [
{ label: "咨询", value: "consulting" },
{ label: "设计", value: "design" },
],
},
],
},
});
@@ -1425,20 +1729,25 @@ test("admin can create and version an inquiry form", async () => {
assert.equal((await publishReleaseForTests()).statusCode, 201);
const publicForm = await request(`/public/inquiry-forms/${id}`);
assert.equal(publicForm.statusCode, 200);
assert.equal(
JSON.parse(publicForm.body).fieldsSnapshot.find((field) => field.key === "topics").type,
"multi-select",
);
const publicOffering = await request(`/public/offerings/${offering.id}`);
assert.equal(publicOffering.statusCode, 200);
assert.equal(JSON.parse(publicOffering.body).inquiryForms[0].id, id);
const publicWorkspace = await request("/public/workspace");
assert.equal(publicWorkspace.statusCode, 200);
assert.ok(JSON.parse(publicWorkspace.body).inquiryForms.some((form) => form.key === id));
const runtimeForm = JSON.parse(publicWorkspace.body).inquiryForms.find(
(form) => form.key === id,
);
assert.ok(runtimeForm);
assert.equal(runtimeForm.fields.find((field) => field.key === "topics").type, "checkbox");
assert.ok(
JSON.parse(publicWorkspace.body).inquiryForms.some(
(form) => form.key === id && form.targetId === offering.id,
),
);
const runtimeForm = JSON.parse(publicWorkspace.body).inquiryForms.find(
(form) => form.key === id,
);
assert.deepEqual(runtimeForm.fields[1].options, [{ label: "微信", value: "wechat" }]);
await prisma.inquiryForm.update({
where: { id },
@@ -1833,6 +2142,8 @@ test("admin can read and update brand and service configuration", async () => {
assert.equal(updatedBrand.statusCode, 200);
assert.equal(JSON.parse(updatedBrand.body).description, "集成测试品牌简介");
assert.equal(JSON.parse(updatedBrand.body).templateKey, "personal");
const updatedConfig = JSON.parse(updatedBrand.body).config;
assert.equal(updatedConfig.slogan, "集成测试品牌简介");
const updatedService = await request(`/admin/workspace/offerings/${serviceBefore.id}`, {
method: "PATCH",
@@ -1950,6 +2261,26 @@ test("admin can manage trust content", async () => {
});
const token = JSON.parse(login.body).token;
assert.equal((await request("/admin/config/trust-content")).statusCode, 401);
assert.equal(
(
await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: "Bearer invalid" },
payload: { type: "schedule", title: "安排", content: "时间" },
})
).statusCode,
401,
);
assert.equal(
(
await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: { type: "schedule", title: "安排", content: "时间" },
})
).statusCode,
403,
);
const created = await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
@@ -1957,6 +2288,25 @@ test("admin can manage trust content", async () => {
});
assert.equal(created.statusCode, 201);
const id = JSON.parse(created.body).id;
const schedule = await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: {
type: "schedule",
title: "每周营业安排",
summary: "周一至周五 17:00 - 22:30",
content: "周六、周日承接团体单",
},
});
assert.equal(schedule.statusCode, 201);
assert.equal(JSON.parse(schedule.body).summary, "周一至周五 17:00 - 22:30");
assert.equal(JSON.parse(schedule.body).content, "周六、周日承接团体单");
const unsupported = await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { type: "unregistered-template-type", title: "不支持", content: "不应保存" },
});
assert.equal(unsupported.statusCode, 400);
const draft = await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
@@ -1981,6 +2331,7 @@ test("admin can manage trust content", async () => {
assert.equal(updated.statusCode, 200);
assert.equal(JSON.parse(updated.body).content, "更新后的内容");
} finally {
await prisma.trustContent.delete({ where: { id: JSON.parse(schedule.body).id } });
const deleted = await request(`/admin/config/trust-content/${id}`, {
method: "DELETE",
headers: { authorization: `Bearer ${token}` },
+23
View File
@@ -1,3 +1,4 @@
const assert = require("node:assert/strict");
const { randomBytes } = require("node:crypto");
const { spawnSync } = require("node:child_process");
const { PrismaClient } = require("@prisma/client");
@@ -10,6 +11,7 @@ const testUrl = new URL(databaseUrl);
testUrl.searchParams.set("schema", schema);
const testEnvironment = { ...process.env, DATABASE_URL: testUrl.toString(), NODE_ENV: "test" };
const administrator = new PrismaClient();
const fixtureDatabase = new PrismaClient({ datasourceUrl: testUrl.toString() });
function run(command, args) {
const result = spawnSync(command, args, { stdio: "inherit", env: testEnvironment });
@@ -25,9 +27,30 @@ async function main() {
created = true;
if (run("pnpm", ["exec", "prisma", "migrate", "deploy"]) !== 0) return status;
if (run("pnpm", ["db:seed"]) !== 0) return status;
const initialTrustCount = await fixtureDatabase.trustContent.count();
const initialFormCount = await fixtureDatabase.inquiryForm.count();
const initialReleases = await fixtureDatabase.brandRelease.findMany({ orderBy: { id: "asc" } });
if (run("pnpm", ["db:seed"]) !== 0) return status;
assert.equal(
await fixtureDatabase.trustContent.count(),
initialTrustCount,
"Repeated seed must not duplicate trust content",
);
assert.equal(
await fixtureDatabase.inquiryForm.count(),
initialFormCount,
"Repeated seed must not duplicate forms",
);
assert.deepEqual(
await fixtureDatabase.brandRelease.findMany({ orderBy: { id: "asc" } }),
initialReleases,
"Repeated seed must preserve release history and snapshots",
);
console.log("Seed idempotency verified: content, forms and release history preserved");
status = run(process.execPath, ["--test", "test/http.integration.test.js"]);
return status;
} finally {
await fixtureDatabase.$disconnect();
if (created) await administrator.$executeRawUnsafe(`DROP SCHEMA "${schema}" CASCADE`);
await administrator.$disconnect();
process.exitCode = status;
@@ -5,6 +5,22 @@ Component({
submitting: { type: Boolean, value: false },
submitLabel: { type: String, value: "提交需求" },
},
observers: {
"fields, values": function (fields, values) {
const selectedValues = values || {};
this.setData({
renderFields: (fields || []).map((field) => ({
...field,
options: (field.options || []).map((option) => ({
...option,
checked:
Array.isArray(selectedValues[field.key]) &&
selectedValues[field.key].includes(option.value),
})),
})),
});
},
},
methods: {
input(e) {
this.triggerEvent("input", { key: e.currentTarget.dataset.key, value: e.detail.value });
@@ -14,6 +30,12 @@ Component({
const option = field?.options?.[e.detail.value];
if (option) this.triggerEvent("input", { key: field.key, value: option.value ?? option });
},
checkboxChange(e) {
this.triggerEvent("input", {
key: e.currentTarget.dataset.key,
value: e.detail.value,
});
},
dateChange(e) {
this.triggerEvent("input", { key: e.currentTarget.dataset.key, value: e.detail.value });
},
@@ -1 +1,16 @@
<view class="form"><view wx:for="{{fields}}" wx:key="key" class="field"><text class="label">{{item.label}}{{item.required ? ' *' : ''}}</text><input wx:if="{{item.type === 'tel' || item.type === 'phone' || item.type === 'number' || item.type === 'text'}}" type="{{item.type === 'number' ? 'number' : item.type === 'tel' || item.type === 'phone' ? 'number' : 'text'}}" data-key="{{item.key}}" placeholder="{{item.placeholder || '请填写'}}" value="{{values[item.key]}}" bindinput="input"/><textarea wx:elif="{{item.type === 'textarea'}}" data-key="{{item.key}}" placeholder="{{item.placeholder || '请填写'}}" value="{{values[item.key]}}" bindinput="input" auto-height="true"/><picker wx:elif="{{item.type === 'date'}}" mode="date" data-key="{{item.key}}" value="{{values[item.key]}}" bindchange="dateChange"><view class="picker-value">{{values[item.key] || '请选择日期'}}</view></picker><picker wx:elif="{{item.type === 'select' || item.type === 'radio'}}" mode="selector" range="{{item.options}}" range-key="label" data-key="{{item.key}}" bindchange="choose"><view class="picker-value">{{values[item.key] || '请选择'}}</view></picker></view><button class="submit" loading="{{submitting}}" bindtap="submit">{{submitLabel || '提交需求'}}</button></view>
<view class="form">
<view wx:for="{{renderFields}}" wx:key="key" class="field">
<text class="label">{{item.label}}{{item.required ? ' *' : ''}}</text>
<input wx:if="{{item.type === 'tel' || item.type === 'phone' || item.type === 'number' || item.type === 'text'}}" type="{{item.type === 'number' ? 'number' : item.type === 'tel' || item.type === 'phone' ? 'number' : 'text'}}" data-key="{{item.key}}" placeholder="{{item.placeholder || '请填写'}}" value="{{values[item.key]}}" bindinput="input" />
<textarea wx:elif="{{item.type === 'textarea'}}" data-key="{{item.key}}" placeholder="{{item.placeholder || '请填写'}}" value="{{values[item.key]}}" bindinput="input" auto-height="true" />
<picker wx:elif="{{item.type === 'date'}}" mode="date" data-key="{{item.key}}" value="{{values[item.key]}}" bindchange="dateChange"><view class="picker-value">{{values[item.key] || '请选择日期'}}</view></picker>
<picker wx:elif="{{item.type === 'select' || item.type === 'radio'}}" mode="selector" range="{{item.options}}" range-key="label" data-key="{{item.key}}" bindchange="choose"><view class="picker-value">{{values[item.key] || '请选择'}}</view></picker>
<checkbox-group wx:elif="{{item.type === 'checkbox'}}" class="checkbox-group" data-key="{{item.key}}" bindchange="checkboxChange">
<label wx:for="{{item.options}}" wx:for-item="option" wx:key="value" class="checkbox-option">
<checkbox value="{{option.value}}" checked="{{option.checked}}" />
<text>{{option.label}}</text>
</label>
</checkbox-group>
</view>
<button class="submit" loading="{{submitting}}" bindtap="submit">{{submitLabel || '提交需求'}}</button>
</view>
@@ -29,6 +29,16 @@
.picker-value {
color: #77736b;
}
.checkbox-group {
flex: 1;
}
.checkbox-option {
display: flex;
align-items: center;
min-height: 64rpx;
color: #252827;
font-size: 24rpx;
}
.submit {
margin-top: 30rpx;
background: #252827;
@@ -1 +1 @@
<view class="detail"><view class="hero-wrap"><image class="hero" src="{{item.detailHero || item.image}}" mode="aspectFill"/><view class="hero-shade"></view><view class="hero-copy"><text>{{item.category}} · {{item.area}}</text><text>{{item.name}}</text><text>{{item.series}}</text></view></view><view class="content"><view class="price-card"><view><text>{{presentation.priceLabel}}</text><text>{{item.priceRange}}</text></view><view><text>{{presentation.spaceLabel}}</text><text>{{item.spaceType}}</text></view></view><view class="detail-section"><text class="section-title">{{presentation.backgroundTitle}}</text><text class="body">{{item.details.background || item.desc}}</text></view><view wx:if="{{item.details.designConcept}}" class="detail-section"><text class="section-title">{{presentation.conceptTitle}}</text><text class="body warm">{{item.details.designConcept}}</text></view><view wx:if="{{item.details.crafts.length}}" class="detail-section"><text class="section-title">{{presentation.craftsTitle}}</text><view wx:for="{{item.details.crafts}}" wx:key="*this" class="craft"><text>0{{index + 1}}</text><text>{{item}}</text></view></view><view wx:if="{{item.details.materialsList.length}}" class="detail-section"><text class="section-title">{{presentation.materialsTitle}}</text><view class="materials"><view wx:for="{{item.details.materialsList}}" wx:key="name"><text>{{item.name}}</text><text>{{item.spec}}</text></view></view></view><view class="chips"><text wx:for="{{item.keywords}}" wx:key="*this">{{item}}</text></view></view><view class="bar"><button bindtap="inquire">{{presentation.inquiryAction}}</button><text>{{presentation.inquiryHint}}</text></view></view>
<view class="detail"><view class="hero-wrap"><image class="hero" src="{{item.detailHero || item.image}}" mode="aspectFill"/><view class="hero-shade"></view><view class="hero-copy"><text>{{item.presentation.categoryLabel || item.category}} · {{item.area}}</text><text>{{item.name}}</text><text>{{item.series}}</text></view></view><view class="content"><view class="price-card"><view><text>{{presentation.priceLabel}}</text><text>{{item.priceRange}}</text></view><view><text>{{presentation.spaceLabel}}</text><text>{{item.spaceType}}</text></view></view><view class="detail-section"><text class="section-title">{{presentation.backgroundTitle}}</text><text class="body">{{item.details.background || item.desc}}</text></view><view wx:if="{{item.details.designConcept}}" class="detail-section"><text class="section-title">{{presentation.conceptTitle}}</text><text class="body warm">{{item.details.designConcept}}</text></view><view wx:if="{{item.details.crafts.length}}" class="detail-section"><text class="section-title">{{presentation.craftsTitle}}</text><view wx:for="{{item.details.crafts}}" wx:key="*this" class="craft"><text>0{{index + 1}}</text><text>{{item}}</text></view></view><view wx:if="{{item.details.materialsList.length}}" class="detail-section"><text class="section-title">{{presentation.materialsTitle}}</text><view class="materials"><view wx:for="{{item.details.materialsList}}" wx:key="name"><text>{{item.name}}</text><text>{{item.spec}}</text></view></view></view><view class="chips"><text wx:for="{{item.keywords}}" wx:key="*this">{{item}}</text></view></view><view class="bar"><button bindtap="inquire">{{presentation.inquiryAction}}</button><text>{{presentation.inquiryHint}}</text></view></view>
+1 -1
View File
@@ -8,7 +8,7 @@
"tdesign-miniprogram": "^1.16.1"
},
"scripts": {
"test:fixture": "node test/validate-fixture.cjs && node --test test/runtime-workspace.test.cjs",
"test:fixture": "node test/validate-fixture.cjs && node --test test/*.test.cjs",
"test:visual-fixture": "node test/validate-visual-fixture.cjs",
"lint": "eslint src --ext .ts",
"typecheck": "tsc -p tsconfig.json --noEmit",
@@ -0,0 +1,66 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const test = require("node:test");
const root = path.resolve(__dirname, "../../..");
const template = path.join(root, "packages/template-acheng-campus-food");
const fields = JSON.parse(fs.readFileSync(path.join(template, "template.json"))).sampleContent.food
.fields;
async function loadPage() {
let page;
vm.runInNewContext(
fs.readFileSync(path.join(template, "miniapp/pages/inquiry/index.js"), "utf8"),
{
Page(value) {
page = value;
},
require(name) {
if (name.includes("runtime-workspace"))
return {
loadWorkspaceWithFallback: () =>
Promise.resolve({
brand: {},
inquiryForms: [{ id: "brand-form", target: "brand", fields }],
}),
};
if (name.includes("navigation")) return { takePageQuery: () => ({}) };
return {};
},
},
);
page.setData = (data) => {
for (const [key, value] of Object.entries(data)) {
if (key.startsWith("values.")) page.data.values[key.slice(7)] = value;
else if (key.startsWith("displayValues.")) page.data.displayValues[key.slice(14)] = value;
else page.data[key] = value;
}
};
await page.onLoad({});
return page;
}
test("餐饮咨询布局保留原型类型按钮和双列字段,文案与选项仍读取表单", async () => {
const page = await loadPage();
assert.equal(page.data.formId, "brand-form");
assert.equal(page.data.fields.find((field) => field.key === "type").useChips, true);
assert.equal(page.data.fields.filter((field) => field.halfWidth).length, 4);
assert.equal(page.data.fields.find((field) => field.key === "type").options.length, 6);
assert.equal(
page.data.fields.find((field) => field.key === "remark").label,
"餐品 / 口味 / 忌口备注",
);
});
test("选择类型或选项保存真实值,选择器展示标签;空数组不能通过必填检查", async () => {
const page = await loadPage();
page.chooseChip({ currentTarget: { dataset: { key: "type", value: "日常留餐" } } });
assert.equal(page.data.values.type, "日常留餐");
const people = page.data.fields.find((field) => field.key === "people");
people.options = [{ label: "人数显示标签", value: "people-value" }];
page.choose({ currentTarget: { dataset: { key: "people" } }, detail: { value: "0" } });
assert.equal(page.data.values.people, "people-value");
assert.equal(page.data.displayValues.people, "人数显示标签");
page.data.fields = [{ key: "allergy", label: "饮食要求", required: true }];
page.data.values = { allergy: [] };
page.submit();
assert.equal(page.data.formError, "请填写饮食要求");
});
@@ -0,0 +1,38 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const test = require("node:test");
const root = path.resolve(__dirname, "../../../packages/template-acheng-campus-food/miniapp");
test("主理人页只呈现资质、案例和承诺,不混入出摊区块", async () => {
let page;
const items = ["schedule", "coverage", "process", "credential", "case", "promise"].map(
(type) => ({ id: type, type, title: type, content: "后台编辑内容" }),
);
vm.runInNewContext(fs.readFileSync(path.join(root, "pages/bookings/index.js"), "utf8"), {
Page(value) {
page = value;
},
require(name) {
return name.includes("runtime-workspace")
? {
loadWorkspaceWithFallback: () =>
Promise.resolve({ brand: { description: "主理人简介" }, trustItems: items }),
}
: {};
},
});
page.setData = (data) => Object.assign(page.data, data);
page.onLoad();
await new Promise((resolve) => setImmediate(resolve));
assert.equal(page.data.credentials.length, 1);
assert.equal(page.data.cases[0].content, "后台编辑内容");
assert.equal(page.data.promises.length, 1);
const markup = fs.readFileSync(
path.join(root, "components/templates/acheng-profile/acheng-profile.wxml"),
"utf8",
);
assert.ok(markup.includes("brand.description"));
assert.ok(!markup.includes("brand.slogan"));
assert.ok(!markup.includes("coverageContent"));
});
@@ -0,0 +1,63 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const test = require("node:test");
const root = path.resolve(__dirname, "../../..");
const template = path.join(root, "packages/template-acheng-campus-food");
const sample = JSON.parse(fs.readFileSync(path.join(template, "template.json"))).sampleContent.food;
async function loadPage(items) {
let page;
vm.runInNewContext(
fs.readFileSync(path.join(template, "miniapp/pages/stall-service/index.js"), "utf8"),
{
Page(value) {
page = value;
},
require(name) {
return name.includes("runtime-workspace")
? { loadWorkspaceWithFallback: () => Promise.resolve({ brand: {}, trustItems: items }) }
: { openPage() {} };
},
},
);
page.setData = (data) => Object.assign(page.data, data);
await page.load();
return page.data;
}
test("旧记录不遮住结构化内容,每种内容只投影一个固定区域", async () => {
const old = ["schedule", "coverage", "process"].map((type) => ({
type,
title: "旧记录",
content: "旧正文",
}));
const data = await loadPage([...old, ...sample.trustContent, ...sample.trustContent]);
assert.equal(data.schedule.rows.length, 2);
assert.equal(data.schedule.rows[0].title, sample.trustContent[0].config.weekdayLabel);
assert.equal(data.schedule.rows[1].title, sample.trustContent[0].config.weekendLabel);
assert.equal(data.coverage.config.pickupDetail, sample.trustContent[1].config.pickupDetail);
assert.equal(data.coverage.config.deliveryDetail, sample.trustContent[1].config.deliveryDetail);
assert.equal(data.process.steps.length, 4);
assert.equal(new Set(data.process.steps.map((step) => step.index)).size, 4);
assert.ok(data.process.steps.every((step) => step.title && step.detail));
});
test("缺少配置时不渲染空配送卡和空流程卡", async () => {
const data = await loadPage([
{ type: "coverage", title: "地点", config: {} },
{ type: "process", title: "旧流程", content: "步骤一\n步骤二" },
]);
assert.equal(data.coverage, null);
assert.equal(data.process, null);
});
test("编辑工作日、周末、配送和步骤变量后页面数据同时更新", async () => {
const items = JSON.parse(JSON.stringify(sample.trustContent));
items[0].config.weekdayDetail = "工作日新地点";
items[0].config.weekendHours = "周末新时间";
items[1].config.deliveryDetail = "新配送规则";
items[2].config.steps[0].detail = "新第一步";
const data = await loadPage(items);
assert.equal(data.schedule.rows[0].detail, "工作日新地点");
assert.equal(data.schedule.rows[1].hours, "周末新时间");
assert.equal(data.coverage.config.deliveryDetail, "新配送规则");
assert.equal(data.process.steps[0].detail, "新第一步");
});
@@ -0,0 +1,50 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const test = require("node:test");
const vm = require("node:vm");
const componentDirectory = path.join(__dirname, "../components/modules/inquiry-form");
let definition;
vm.runInNewContext(fs.readFileSync(path.join(componentDirectory, "inquiry-form.js"), "utf8"), {
Component: (value) => {
definition = value;
},
});
test("多选字段根据已有值标记选项并把选中值数组传回表单", () => {
const context = {
data: {},
events: [],
setData(value) {
this.data = { ...this.data, ...value };
},
triggerEvent(name, detail) {
this.events.push({ name, detail });
},
};
definition.observers["fields, values"].call(
context,
[
{
key: "topics",
type: "checkbox",
options: [
{ label: "咨询", value: "consulting" },
{ label: "设计", value: "design" },
],
},
],
{ topics: ["design"] },
);
assert.equal(context.data.renderFields[0].options[0].checked, false);
assert.equal(context.data.renderFields[0].options[1].checked, true);
definition.methods.checkboxChange.call(context, {
currentTarget: { dataset: { key: "topics" } },
detail: { value: ["consulting", "design"] },
});
assert.equal(context.events[0].name, "input");
assert.equal(context.events[0].detail.key, "topics");
assert.deepEqual(context.events[0].detail.value, ["consulting", "design"]);
});
+1 -1
View File
@@ -53,7 +53,7 @@ test("运行时保留模板业务数据,不再解释视觉模块", async () =>
modules: [{ key: "brand-hero" }],
visualTemplateManifest: { pages: [] },
});
assert.deepEqual(workspace.trustContent, { bio: "品牌介绍" });
assert.deepEqual(workspace.trustPresentation, { bio: "品牌介绍" });
assert.equal(workspace.fields, undefined);
assert.equal(workspace.inquiryForm, undefined);
assert.equal(workspace.modules[0].key, "brand-hero");
+24
View File
@@ -0,0 +1,24 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const test = require("node:test");
const vm = require("node:vm");
const source = fs.readFileSync(path.join(__dirname, "../utils/trust-content.js"), "utf8");
const trustModule = { exports: {} };
vm.runInNewContext(source, { module: trustModule });
const { prepareTrustItems } = trustModule.exports;
test("流程信任内容按换行整理为非空步骤", () => {
const [process] = prepareTrustItems([
{ type: "process", title: "定制流程", content: " 沟通需求\r\n\n确认菜单\n 现场交付 " },
]);
assert.equal(JSON.stringify(process.lines), JSON.stringify(["沟通需求", "确认菜单", "现场交付"]));
assert.equal(process.content, " 沟通需求\r\n\n确认菜单\n 现场交付 ");
});
test("非流程信任内容不添加步骤列表", () => {
const [schedule] = prepareTrustItems([{ type: "schedule", content: "工作日营业" }]);
assert.equal("lines" in schedule, false);
assert.equal(prepareTrustItems(null).length, 0);
});
+2 -2
View File
@@ -29,7 +29,7 @@ function normalizeWorkspace(workspace) {
const offerings = Array.isArray(workspace && workspace.offerings)
? workspace.offerings.map(toOffering)
: [];
const trustContent =
const trustPresentation =
workspace && workspace.trustPresentation && typeof workspace.trustPresentation === "object"
? workspace.trustPresentation
: {};
@@ -43,7 +43,7 @@ function normalizeWorkspace(workspace) {
...workspace,
brand,
offerings,
trustContent,
trustPresentation,
trustItems,
plugins: Array.isArray(workspace.plugins) ? workspace.plugins : [],
};
+19
View File
@@ -0,0 +1,19 @@
function prepareTrustItems(items) {
if (!Array.isArray(items)) return [];
return items.map((item) => ({
...item,
...(item.type === "process"
? {
lines:
typeof item.content === "string"
? item.content
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean)
: [],
}
: {}),
}));
}
module.exports = { prepareTrustItems };