feat: 完善模板驱动的品牌内容工作台
This commit is contained in:
1 parent
77224ea51f
commit
dd55af8d73
46 files changed
+2204
-295
No files matched your search
@@ -13,6 +13,7 @@
|
||||
"scripts": {
|
||||
"build": "pnpm --filter @personal-brand/api-client build && vite build",
|
||||
"dev": "pnpm --filter @personal-brand/api-client build && vite",
|
||||
"test": "node --experimental-strip-types --test test/*.test.mjs",
|
||||
"lint": "eslint .",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"clean": "rimraf dist"
|
||||
|
||||
@@ -7,24 +7,20 @@ import { ImageUrlField } from "../../components/ImageUrlField.js";
|
||||
import { MutationError, QueryState } from "../../components/QueryState.js";
|
||||
import { PresentationEditor } from "./PresentationEditor.js";
|
||||
|
||||
function textValue(value: unknown): string {
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
export function BrandPage() {
|
||||
const client = createApiClient();
|
||||
const queryClient = useQueryClient();
|
||||
const [form] = Form.useForm<BrandProfile>();
|
||||
const brand = useQuery({ queryKey: ["admin-brand"], queryFn: () => client.getAdminBrand() });
|
||||
const workspace = useQuery({
|
||||
queryKey: ["admin-workspace"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
});
|
||||
const template = useQuery({
|
||||
queryKey: ["template", brand.data?.templateKey],
|
||||
queryFn: () => client.getPublicTemplate(brand.data!.templateKey),
|
||||
enabled: Boolean(brand.data?.templateKey),
|
||||
});
|
||||
const runtime = useQuery({
|
||||
queryKey: ["public-runtime-workspace"],
|
||||
queryFn: () => client.getPublicWorkspace(),
|
||||
});
|
||||
const save = useMutation({
|
||||
mutationFn: (values: Partial<BrandProfile>) => client.updateAdminBrand(values),
|
||||
onSuccess: () => {
|
||||
@@ -148,43 +144,10 @@ export function BrandPage() {
|
||||
</Space>
|
||||
</Form>
|
||||
<PresentationEditor
|
||||
initialValue={{
|
||||
identity: {
|
||||
founder: textValue(brand.data.config?.founder),
|
||||
title: textValue(brand.data.config?.title),
|
||||
slogan: textValue(brand.data.config?.slogan),
|
||||
phone: textValue(brand.data.config?.phone),
|
||||
wechat: textValue(brand.data.config?.wechat),
|
||||
studioAddress: textValue(brand.data.config?.studioAddress),
|
||||
},
|
||||
...((brand.data.config?.visualPresentation as {
|
||||
home?: Record<string, string>;
|
||||
offerings?: Record<string, string>;
|
||||
detail?: Record<string, string>;
|
||||
profile?: Record<string, string>;
|
||||
inquiry?: Record<string, string>;
|
||||
success?: Record<string, string>;
|
||||
records?: Record<string, string>;
|
||||
}) ?? {}),
|
||||
}}
|
||||
runtimeValue={
|
||||
runtime.data?.brand
|
||||
? {
|
||||
identity: {
|
||||
founder: textValue(runtime.data.brand.config?.founder),
|
||||
title: textValue(runtime.data.brand.config?.title),
|
||||
slogan: textValue(runtime.data.brand.config?.slogan),
|
||||
},
|
||||
...((runtime.data.brand.config?.visualPresentation as {
|
||||
home?: Record<string, string>;
|
||||
inquiry?: Record<string, string>;
|
||||
profile?: Record<string, string>;
|
||||
}) ?? {}),
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
runtimeLoading={runtime.isLoading}
|
||||
runtimeError={runtime.error}
|
||||
templateContent={workspace.data?.templateContent}
|
||||
config={brand.data.config}
|
||||
loading={workspace.isLoading}
|
||||
error={workspace.error}
|
||||
/>
|
||||
</Col>
|
||||
<Col xs={24} xl={9}>
|
||||
|
||||
@@ -1,189 +1,155 @@
|
||||
import { Alert, Button, Card, Col, Form, Input, Row, Space, Typography, message } from "antd";
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Card,
|
||||
Col,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
Row,
|
||||
Space,
|
||||
Typography,
|
||||
message,
|
||||
} from "antd";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect } from "react";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import type { AdminTemplateContent, TemplateAdminField } from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
||||
import { MutationError } from "../../components/QueryState.js";
|
||||
import {
|
||||
applyPresentationValues,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
type PresentationValues,
|
||||
} from "./presentation-bindings.js";
|
||||
|
||||
interface PresentationEditorProps {
|
||||
initialValue: PresentationFormValues;
|
||||
runtimeValue?: PresentationFormValues | undefined;
|
||||
runtimeLoading?: boolean | undefined;
|
||||
runtimeError?: unknown;
|
||||
templateContent: AdminTemplateContent | null | undefined;
|
||||
config: Record<string, unknown> | null | undefined;
|
||||
loading?: boolean;
|
||||
error?: unknown;
|
||||
}
|
||||
|
||||
type PresentationFormValues = {
|
||||
identity?: Record<string, string>;
|
||||
home?: Record<string, string>;
|
||||
offerings?: Record<string, string>;
|
||||
detail?: Record<string, string>;
|
||||
profile?: Record<string, string>;
|
||||
inquiry?: Record<string, string>;
|
||||
success?: Record<string, string>;
|
||||
records?: Record<string, string>;
|
||||
};
|
||||
function renderField(field: TemplateAdminField) {
|
||||
if (field.input === "textarea")
|
||||
return (
|
||||
<Input.TextArea
|
||||
rows={3}
|
||||
maxLength={field.maxLength}
|
||||
showCount={!!field.maxLength}
|
||||
placeholder={field.placeholder}
|
||||
/>
|
||||
);
|
||||
if (field.input === "image")
|
||||
return <ImageUrlField {...(field.placeholder ? { placeholder: field.placeholder } : {})} />;
|
||||
if (field.input === "number")
|
||||
return <InputNumber style={{ width: "100%" }} placeholder={field.placeholder} />;
|
||||
return (
|
||||
<Input
|
||||
type={field.input === "phone" ? "tel" : "text"}
|
||||
maxLength={field.maxLength}
|
||||
placeholder={field.placeholder}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function PresentationEditor({
|
||||
initialValue,
|
||||
runtimeValue,
|
||||
runtimeLoading,
|
||||
runtimeError,
|
||||
templateContent,
|
||||
config,
|
||||
loading,
|
||||
error,
|
||||
}: PresentationEditorProps) {
|
||||
const [form] = Form.useForm<PresentationFormValues>();
|
||||
const [form] = Form.useForm<PresentationValues>();
|
||||
const queryClient = useQueryClient();
|
||||
const sections = templateContent?.admin.sections ?? [];
|
||||
const initialValues = useMemo(() => {
|
||||
const values: PresentationValues = {};
|
||||
for (const section of sections) {
|
||||
for (const field of section.fields) {
|
||||
values[presentationFieldName(section.key, field.key)] = readPresentationValue(
|
||||
config,
|
||||
field.binding,
|
||||
);
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}, [config, sections]);
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: (values: PresentationFormValues) =>
|
||||
createApiClient().updateAdminBrandPresentation(values),
|
||||
mutationFn: (values: PresentationValues) => {
|
||||
const nextConfig = applyPresentationValues(config, sections, values);
|
||||
return createApiClient().updateAdminBrand({ config: nextConfig });
|
||||
},
|
||||
onSuccess: () => {
|
||||
message.success("页面表达已保存,小程序将使用最新内容");
|
||||
message.success("页面内容已保存,小程序将使用最新内容");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["publication-readiness"] });
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
form.setFieldsValue(initialValue);
|
||||
}, [form, initialValue]);
|
||||
form.setFieldsValue(initialValues);
|
||||
}, [form, initialValues]);
|
||||
|
||||
return (
|
||||
<Card
|
||||
title="小程序页面表达"
|
||||
style={{ marginTop: 24 }}
|
||||
extra={<Typography.Text type="secondary">普通用户配置</Typography.Text>}
|
||||
>
|
||||
<Card title="小程序页面内容" style={{ marginTop: 24 }}>
|
||||
<Typography.Paragraph type="secondary">
|
||||
这里的内容会显示在小程序中。只填写你希望访客看到的话,不需要理解模板或技术配置。
|
||||
编辑访客在小程序中看到的文字和图片。不同模板会提供适合本行业的内容项目。
|
||||
</Typography.Paragraph>
|
||||
{runtimeLoading ? <Alert type="info" showIcon message="正在读取小程序当前内容" /> : null}
|
||||
{runtimeError ? (
|
||||
<Alert type="warning" showIcon message="小程序当前内容暂时无法读取,保存后可重新加载。" />
|
||||
) : runtimeValue ? (
|
||||
<Card size="small" title="小程序当前已生效内容" style={{ marginBottom: 16 }}>
|
||||
<Typography.Text strong>
|
||||
{runtimeValue.identity?.founder || "尚未设置主理人 / 老板姓名"}
|
||||
</Typography.Text>
|
||||
{runtimeValue.identity?.title ? (
|
||||
<Typography.Text type="secondary"> · {runtimeValue.identity.title}</Typography.Text>
|
||||
) : null}
|
||||
<Typography.Paragraph strong>
|
||||
{runtimeValue.home?.proofTitle || "尚未设置信任介绍标题"}
|
||||
</Typography.Paragraph>
|
||||
<Typography.Paragraph type="secondary">
|
||||
{runtimeValue.inquiry?.subtitle || "尚未设置咨询说明"}
|
||||
</Typography.Paragraph>
|
||||
<Typography.Text type="secondary">
|
||||
咨询按钮:{runtimeValue.inquiry?.submitLabel || "未设置"} · 记录入口:
|
||||
{runtimeValue.profile?.recordsTitle || "未设置"}
|
||||
</Typography.Text>
|
||||
</Card>
|
||||
{loading ? <Alert type="info" showIcon message="正在读取当前模板的编辑项目" /> : null}
|
||||
{error ? (
|
||||
<Alert type="warning" showIcon message="模板编辑项目读取失败,请刷新后重试。" />
|
||||
) : null}
|
||||
{!loading && !error && !templateContent ? (
|
||||
<Alert type="warning" showIcon message="当前模板暂未提供可编辑的页面内容。" />
|
||||
) : null}
|
||||
{templateContent ? (
|
||||
<>
|
||||
<Typography.Title level={5}>{templateContent.displayName}</Typography.Title>
|
||||
<Form
|
||||
form={form}
|
||||
layout="vertical"
|
||||
initialValues={initialValues}
|
||||
onFinish={(values) => save.mutate(values)}
|
||||
>
|
||||
{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" ? 24 : 12}>
|
||||
<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>
|
||||
</Card>
|
||||
))}
|
||||
<Space direction="vertical" style={{ width: "100%" }}>
|
||||
<MutationError error={save.error} />
|
||||
<Button type="primary" htmlType="submit" loading={save.isPending}>
|
||||
保存页面内容
|
||||
</Button>
|
||||
</Space>
|
||||
</Form>
|
||||
</>
|
||||
) : null}
|
||||
<Form
|
||||
form={form}
|
||||
layout="vertical"
|
||||
initialValues={initialValue}
|
||||
onFinish={(values) => save.mutate(values)}
|
||||
>
|
||||
<Card size="small" title="主理人信息" style={{ marginBottom: 16 }}>
|
||||
<Typography.Paragraph type="secondary">
|
||||
访客需要先知道是谁在提供服务。这里填写主理人或老板的公开信息。
|
||||
</Typography.Paragraph>
|
||||
<Row gutter={16}>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name={["identity", "founder"]} label="主理人 / 老板姓名">
|
||||
<Input placeholder="例如:林然" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name={["identity", "title"]} label="身份或职位">
|
||||
<Input placeholder="例如:品牌顾问 / 工作室主理人" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24}>
|
||||
<Form.Item name={["identity", "slogan"]} label="主理人希望传达的一句话">
|
||||
<Input placeholder="例如:认真做好每一次定制" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name={["identity", "phone"]} label="公开联系电话">
|
||||
<Input placeholder="选填" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name={["identity", "wechat"]} label="公开微信号">
|
||||
<Input placeholder="选填" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24}>
|
||||
<Form.Item name={["identity", "studioAddress"]} label="工作地点或服务范围">
|
||||
<Input placeholder="例如:杭州及周边地区 / 某某工作室" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
<Card size="small" title="首页" style={{ marginBottom: 16 }}>
|
||||
<Row gutter={16}>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name={["home", "founderBadge"]} label="主理人标签">
|
||||
<Input placeholder="例如:亲自主理 / 10 年经验" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name={["home", "proofTitle"]} label="信任介绍标题">
|
||||
<Input placeholder="例如:用经历和作品建立信任" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name={["home", "worksTitle"]} label="作品区域标题">
|
||||
<Input placeholder="例如:精选作品" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name={["home", "flowTitle"]} label="合作流程标题">
|
||||
<Input placeholder="例如:从沟通到交付" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
<Card size="small" title="咨询页面" style={{ marginBottom: 16 }}>
|
||||
<Form.Item name={["inquiry", "title"]} label="页面标题">
|
||||
<Input placeholder="例如:告诉我你的需求" />
|
||||
</Form.Item>
|
||||
<Form.Item name={["inquiry", "subtitle"]} label="说明文字">
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
showCount
|
||||
maxLength={120}
|
||||
placeholder="告诉访客提交后会发生什么。"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name={["inquiry", "submitLabel"]} label="提交按钮文字">
|
||||
<Input placeholder="例如:提交咨询" />
|
||||
</Form.Item>
|
||||
</Card>
|
||||
<Card size="small" title="主理人与我" style={{ marginBottom: 16 }}>
|
||||
<Row gutter={16}>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name={["profile", "recordsTitle"]} label="咨询记录入口标题">
|
||||
<Input placeholder="例如:我的咨询记录" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name={["profile", "coverageTitle"]} label="服务范围标题">
|
||||
<Input placeholder="例如:服务范围与合作方式" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name={["profile", "warrantyTitle"]} label="承诺标题">
|
||||
<Input placeholder="例如:我的服务承诺" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
<Space direction="vertical" style={{ width: "100%" }}>
|
||||
<MutationError error={save.error} />
|
||||
<Button type="primary" htmlType="submit" loading={save.isPending}>
|
||||
保存页面表达
|
||||
</Button>
|
||||
</Space>
|
||||
</Form>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
export type PresentationField = {
|
||||
key: string;
|
||||
binding: string;
|
||||
};
|
||||
|
||||
export type PresentationSection = {
|
||||
key: string;
|
||||
fields: PresentationField[];
|
||||
};
|
||||
|
||||
export type PresentationValues = Record<string, string | number | null | undefined>;
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function safePath(binding: string): string[] | null {
|
||||
if (!binding.startsWith("brand.config.")) return null;
|
||||
const path = binding.slice("brand.config.".length).split(".");
|
||||
if (path.some((part) => !part || ["__proto__", "prototype", "constructor"].includes(part)))
|
||||
return null;
|
||||
return path;
|
||||
}
|
||||
|
||||
export function presentationFieldName(sectionKey: string, fieldKey: string): string {
|
||||
return `${sectionKey}:${fieldKey}`;
|
||||
}
|
||||
|
||||
export function readPresentationValue(
|
||||
config: Record<string, unknown> | null | undefined,
|
||||
binding: string,
|
||||
): string | number | undefined {
|
||||
const path = safePath(binding);
|
||||
if (!path) return undefined;
|
||||
let value: unknown = asObject(config);
|
||||
for (const part of path) value = asObject(value)[part];
|
||||
return typeof value === "string" || typeof value === "number" ? value : undefined;
|
||||
}
|
||||
|
||||
function writePath(
|
||||
source: Record<string, unknown>,
|
||||
path: string[],
|
||||
value: string | number | null | undefined,
|
||||
): Record<string, unknown> {
|
||||
const [head, ...tail] = path;
|
||||
if (!head) return source;
|
||||
if (!tail.length) return { ...source, [head]: value ?? "" };
|
||||
return {
|
||||
...source,
|
||||
[head]: writePath(asObject(source[head]), tail, value),
|
||||
};
|
||||
}
|
||||
|
||||
export function applyPresentationValues(
|
||||
config: Record<string, unknown> | null | undefined,
|
||||
sections: PresentationSection[],
|
||||
values: PresentationValues,
|
||||
): Record<string, unknown> {
|
||||
let nextConfig = { ...asObject(config) };
|
||||
for (const section of sections) {
|
||||
for (const field of section.fields) {
|
||||
const path = safePath(field.binding);
|
||||
if (!path) continue;
|
||||
nextConfig = writePath(
|
||||
nextConfig,
|
||||
path,
|
||||
values[presentationFieldName(section.key, field.key)],
|
||||
);
|
||||
}
|
||||
}
|
||||
return nextConfig;
|
||||
}
|
||||
@@ -281,10 +281,15 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
||||
{check.passed ? "已完成" : "待完善"}
|
||||
</Tag>
|
||||
<Typography.Text>{check.label}</Typography.Text>
|
||||
{check.help ? (
|
||||
<Typography.Text type="secondary">{check.help}</Typography.Text>
|
||||
) : null}
|
||||
{!check.passed && (
|
||||
<Button
|
||||
type="link"
|
||||
onClick={() => navigate(destinations[check.key] ?? "/admin/overview")}
|
||||
onClick={() =>
|
||||
navigate(check.destination ?? destinations[check.key] ?? "/admin/overview")
|
||||
}
|
||||
>
|
||||
去处理
|
||||
</Button>
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
applyPresentationValues,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
} from "../src/features/brand/presentation-bindings.ts";
|
||||
|
||||
const config = {
|
||||
founder: "阿成",
|
||||
visualPresentation: {
|
||||
home: { worksTitle: "原标题", preserveMe: "保留" },
|
||||
inquiry: { subtitle: "原说明" },
|
||||
},
|
||||
unrelatedSetting: true,
|
||||
};
|
||||
const sections = [
|
||||
{
|
||||
key: "home",
|
||||
fields: [
|
||||
{ key: "founder", binding: "brand.config.founder" },
|
||||
{ key: "worksTitle", binding: "brand.config.visualPresentation.home.worksTitle" },
|
||||
],
|
||||
},
|
||||
];
|
||||
const next = applyPresentationValues(config, sections, {
|
||||
[presentationFieldName("home", "founder")]: "阿成主理人",
|
||||
[presentationFieldName("home", "worksTitle")]: "今日套餐",
|
||||
});
|
||||
|
||||
assert.equal(readPresentationValue(next, "brand.config.founder"), "阿成主理人");
|
||||
assert.equal(
|
||||
readPresentationValue(next, "brand.config.visualPresentation.home.worksTitle"),
|
||||
"今日套餐",
|
||||
);
|
||||
assert.equal(next.visualPresentation.home.preserveMe, "保留");
|
||||
assert.equal(next.visualPresentation.inquiry.subtitle, "原说明");
|
||||
assert.equal(next.unrelatedSetting, true);
|
||||
assert.equal(config.founder, "阿成");
|
||||
|
||||
const unsafe = applyPresentationValues(
|
||||
{ founder: "原主理人" },
|
||||
[
|
||||
{
|
||||
key: "unsafe",
|
||||
fields: [
|
||||
{ key: "tenant", binding: "brand.id" },
|
||||
{ key: "prototype", binding: "brand.config.__proto__.polluted" },
|
||||
],
|
||||
},
|
||||
],
|
||||
{
|
||||
[presentationFieldName("unsafe", "tenant")]: "other-brand",
|
||||
[presentationFieldName("unsafe", "prototype")]: "yes",
|
||||
},
|
||||
);
|
||||
|
||||
assert.deepEqual(unsafe, { founder: "原主理人" });
|
||||
assert.equal({}.polluted, undefined);
|
||||
@@ -31,6 +31,8 @@ import {
|
||||
capabilityPlugins,
|
||||
getBrandTemplate,
|
||||
getTemplateSampleContent,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
getDefaultVisualTemplateKey,
|
||||
resolveCapabilities,
|
||||
} from "@personal-brand/config";
|
||||
import { TemplateWorkspaceService } from "./template-workspace.service.js";
|
||||
@@ -167,7 +169,32 @@ class AdminWorkspaceController {
|
||||
this.prisma.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
|
||||
this.prisma.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" } }),
|
||||
]);
|
||||
return { brand, installations, modules, fields, offerings, forms };
|
||||
const config = this.jsonObject(brand?.config);
|
||||
const templateKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? "personal");
|
||||
const manifest = getTemplatePackageManifestForVisualKey(templateKey);
|
||||
return {
|
||||
brand,
|
||||
installations,
|
||||
modules,
|
||||
fields,
|
||||
offerings,
|
||||
forms,
|
||||
templateContent: manifest
|
||||
? {
|
||||
displayName: manifest.displayName,
|
||||
admin: manifest.admin,
|
||||
assetSlots: manifest.assetSlots,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
private jsonObject(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
@Post("install")
|
||||
async install(
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
getVisualTemplate,
|
||||
isVisualTemplateCompatible,
|
||||
getDefaultVisualTemplateKey,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
} from "@personal-brand/config";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
import { BrandReleaseService } from "./brand-release.service.js";
|
||||
@@ -44,7 +45,13 @@ export class BrandReleaseApiService {
|
||||
database: Prisma.TransactionClient = this.prisma,
|
||||
): Promise<{
|
||||
ready: boolean;
|
||||
checks: Array<{ key: string; label: string; passed: boolean }>;
|
||||
checks: Array<{
|
||||
key: string;
|
||||
label: string;
|
||||
passed: boolean;
|
||||
help?: string;
|
||||
destination?: string;
|
||||
}>;
|
||||
}> {
|
||||
const brand = await database.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
@@ -61,8 +68,12 @@ export class BrandReleaseApiService {
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? "personal");
|
||||
const visual = getVisualTemplate(visualKey);
|
||||
const packageManifest = getTemplatePackageManifestForVisualKey(visualKey);
|
||||
const [offerings, forms, trust] = await Promise.all([
|
||||
database.offering.findMany({ where: { brandId, isEnabled: true }, select: { id: true } }),
|
||||
database.offering.findMany({
|
||||
where: { brandId, isEnabled: true },
|
||||
select: { id: true, name: true, coverUrl: true, config: true },
|
||||
}),
|
||||
database.inquiryForm.findMany({
|
||||
where: { brandId, isEnabled: true },
|
||||
select: { offeringId: true, fieldsSnapshot: true },
|
||||
@@ -77,26 +88,115 @@ export class BrandReleaseApiService {
|
||||
form.fieldsSnapshot.length > 0 &&
|
||||
validateFieldSnapshot(form.fieldsSnapshot).length === 0,
|
||||
);
|
||||
const checks = [
|
||||
{ key: "brand", label: "请先完善品牌名称", passed: Boolean(brand?.name.trim()) },
|
||||
const checks: Array<{
|
||||
key: string;
|
||||
label: string;
|
||||
passed: boolean;
|
||||
help?: string;
|
||||
destination?: string;
|
||||
}> = [
|
||||
{
|
||||
key: "brand",
|
||||
label: "请先完善品牌名称",
|
||||
passed: Boolean(brand?.name.trim()),
|
||||
destination: "/admin/brand",
|
||||
},
|
||||
{
|
||||
key: "positioning",
|
||||
label: "请先完善品牌定位和介绍",
|
||||
passed: Boolean(brand?.tagline?.trim() && brand.description?.trim()),
|
||||
destination: "/admin/brand",
|
||||
},
|
||||
{ key: "template", label: "当前行业模板不存在", passed: Boolean(template) },
|
||||
{
|
||||
key: "visual",
|
||||
label: "当前视觉模板不适配行业模板",
|
||||
passed: Boolean(visual && template && isVisualTemplateCompatible(visual, template.key)),
|
||||
destination: "/admin/publication",
|
||||
},
|
||||
{
|
||||
key: "offerings",
|
||||
label: "至少需要一项已启用的业务提供项",
|
||||
passed: offerings.length > 0,
|
||||
destination: "/admin/services",
|
||||
},
|
||||
{
|
||||
key: "forms",
|
||||
label: "至少需要一个可用的咨询表单",
|
||||
passed: usableForms.length > 0,
|
||||
destination: "/admin/workspace",
|
||||
},
|
||||
{
|
||||
key: "trust",
|
||||
label: "至少需要一条已发布的信任内容",
|
||||
passed: trust > 0,
|
||||
destination: "/admin/trust",
|
||||
},
|
||||
{ key: "offerings", label: "至少需要一项已启用的业务提供项", passed: offerings.length > 0 },
|
||||
{ key: "forms", label: "至少需要一个可用的咨询表单", passed: usableForms.length > 0 },
|
||||
{ key: "trust", label: "至少需要一条已发布的信任内容", passed: trust > 0 },
|
||||
];
|
||||
const brandRecord = { ...this.jsonObject(brand), config };
|
||||
for (const section of packageManifest?.admin.sections ?? []) {
|
||||
for (const field of section.fields) {
|
||||
if (field.required !== true) continue;
|
||||
const present = this.resolveBinding(field.binding, {
|
||||
brand: brandRecord,
|
||||
offerings,
|
||||
});
|
||||
checks.push({
|
||||
key: `content:${section.key}:${field.key}`,
|
||||
label: present
|
||||
? `${section.title}:${field.label}`
|
||||
: `请补充「${section.title}」中的「${field.label}」`,
|
||||
passed: present,
|
||||
help: section.description,
|
||||
destination:
|
||||
section.target === "offering"
|
||||
? "/admin/services"
|
||||
: section.target === "trust"
|
||||
? "/admin/trust"
|
||||
: section.target === "inquiry"
|
||||
? "/admin/workspace"
|
||||
: "/admin/brand",
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const slot of packageManifest?.assetSlots ?? []) {
|
||||
if (slot.required !== true) continue;
|
||||
const present =
|
||||
slot.target === "offering"
|
||||
? offerings.length > 0 && offerings.every((item) => Boolean(item.coverUrl?.trim()))
|
||||
: slot.target === "brand"
|
||||
? this.resolveBinding(slot.binding, { brand: brandRecord, offerings })
|
||||
: trust > 0;
|
||||
checks.push({
|
||||
key: `asset:${String(slot.key)}`,
|
||||
label: present ? `已添加${String(slot.label)}` : `请添加${String(slot.label)}`,
|
||||
passed: present,
|
||||
help: String(slot.help),
|
||||
destination: slot.target === "offering" ? "/admin/services" : "/admin/brand",
|
||||
});
|
||||
}
|
||||
return { ready: checks.every((check) => check.passed), checks };
|
||||
}
|
||||
|
||||
private resolveBinding(
|
||||
binding: string,
|
||||
context: {
|
||||
brand: Record<string, unknown>;
|
||||
offerings: Array<{ id: string; name: string; coverUrl: string | null; config: unknown }>;
|
||||
},
|
||||
): boolean {
|
||||
const segments = binding.split(".");
|
||||
let value: unknown;
|
||||
if (segments[0] === "brand") value = context.brand;
|
||||
else if (segments[0] === "offering") value = context.offerings[0];
|
||||
else return false;
|
||||
for (const segment of segments.slice(1)) {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
||||
value = (value as Record<string, unknown>)[segment];
|
||||
}
|
||||
return typeof value === "string" ? value.trim().length > 0 : Boolean(value);
|
||||
}
|
||||
|
||||
async publish(brandId: string, actorId: string, note?: string): Promise<unknown> {
|
||||
return this.withVersionRetry(() =>
|
||||
this.prisma.$transaction(
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
getVisualTemplate,
|
||||
getVisualTemplateManifest,
|
||||
getDefaultVisualTemplateKey,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
} from "@personal-brand/config";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
|
||||
@@ -15,6 +16,7 @@ export interface BrandReleaseSnapshot {
|
||||
templateDefinition?: ReturnType<typeof getBrandTemplate> | null;
|
||||
visualTemplateDefinition?: ReturnType<typeof getVisualTemplate> | null;
|
||||
visualTemplateManifest?: ReturnType<typeof getVisualTemplateManifest> | null;
|
||||
templatePackageManifest?: ReturnType<typeof getTemplatePackageManifestForVisualKey> | null;
|
||||
brand: Record<string, unknown> | null;
|
||||
installation: Record<string, unknown> | null;
|
||||
modules: unknown[];
|
||||
@@ -61,6 +63,7 @@ export async function buildBrandReleaseSnapshot(
|
||||
templateDefinition: getBrandTemplate(templateKey) ?? null,
|
||||
visualTemplateDefinition: getVisualTemplate(visualKey) ?? null,
|
||||
visualTemplateManifest: getVisualTemplateManifest(visualKey) ?? null,
|
||||
templatePackageManifest: getTemplatePackageManifestForVisualKey(visualKey) ?? null,
|
||||
brand: brand ? jsonObject(brand) : null,
|
||||
installation: installation ? jsonObject(installation) : null,
|
||||
modules: modules.map((item) => jsonObject(item)),
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
resolveCapabilities,
|
||||
capabilityPlugins,
|
||||
getDefaultVisualTemplateKey,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
} from "@personal-brand/config";
|
||||
import type {
|
||||
RuntimeInquiryField,
|
||||
@@ -120,6 +121,9 @@ export class PublicWorkspaceController {
|
||||
releaseSnapshot.visualTemplateDefinition ?? getVisualTemplate(visualTemplateKey);
|
||||
const visualTemplateManifest =
|
||||
releaseSnapshot.visualTemplateManifest ?? getVisualTemplateManifest(visualTemplateKey);
|
||||
const templatePackageManifest =
|
||||
releaseSnapshot.templatePackageManifest ??
|
||||
getTemplatePackageManifestForVisualKey(visualTemplateKey);
|
||||
const runtimeBrand = {
|
||||
...brandData,
|
||||
...brandConfig,
|
||||
@@ -177,6 +181,20 @@ export class PublicWorkspaceController {
|
||||
schemaKey: typeof config.schemaKey === "string" ? config.schemaKey : "offering.default",
|
||||
schemaVersion: typeof config.schemaVersion === "string" ? config.schemaVersion : "1.0.0",
|
||||
presentation: {
|
||||
...Object.fromEntries(
|
||||
Object.entries(config).filter(
|
||||
([key]) =>
|
||||
![
|
||||
"schemaKey",
|
||||
"schemaVersion",
|
||||
"details",
|
||||
"sections",
|
||||
"media",
|
||||
"presentation",
|
||||
].includes(key),
|
||||
),
|
||||
),
|
||||
...this.jsonObject(config.presentation),
|
||||
categoryKey: typeof config.categoryKey === "string" ? config.categoryKey : "custom",
|
||||
categoryLabel:
|
||||
typeof config.categoryLabel === "string" ? config.categoryLabel : "业务提供项",
|
||||
@@ -266,11 +284,15 @@ export class PublicWorkspaceController {
|
||||
},
|
||||
brand: runtimeBrand,
|
||||
navigation: {
|
||||
tabs: [
|
||||
{ key: "home", label: "首页", page: "pages/index/index" },
|
||||
{ key: "offerings", label: "案例与体系", page: "pages/services/index" },
|
||||
{ key: "profile", label: "主理人与我", page: "pages/bookings/index" },
|
||||
],
|
||||
tabs:
|
||||
templatePackageManifest?.navigation.map((tab) => ({
|
||||
key: tab.key,
|
||||
label: tab.label,
|
||||
page:
|
||||
templatePackageManifest.entrypoints[
|
||||
tab.page as keyof typeof templatePackageManifest.entrypoints
|
||||
] ?? tab.page,
|
||||
})) ?? [],
|
||||
},
|
||||
modules: runtimeModules,
|
||||
offerings: runtimeOfferings,
|
||||
|
||||
@@ -77,6 +77,70 @@ test("admin release lifecycle is authorized, brand-scoped, and versioned", async
|
||||
});
|
||||
}
|
||||
const originalBrand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
|
||||
const originalConfig = originalBrand.config;
|
||||
const originalOffering = await prisma.offering.findFirstOrThrow({ where: { brandId } });
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: {
|
||||
config: {
|
||||
...(originalConfig && typeof originalConfig === "object" ? originalConfig : {}),
|
||||
heroImage: "",
|
||||
founder: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
const missingBrandContent = JSON.parse(
|
||||
(
|
||||
await request("/admin/releases/readiness", {
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
})
|
||||
).body,
|
||||
);
|
||||
assert.equal(missingBrandContent.ready, false);
|
||||
assert.equal(
|
||||
missingBrandContent.checks.find((check) => check.key === "asset:brand.stallHero")?.passed,
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
missingBrandContent.checks.find((check) => check.key === "content:identity:founder")
|
||||
?.destination,
|
||||
"/admin/brand",
|
||||
);
|
||||
assert.match(
|
||||
missingBrandContent.checks.find((check) => check.key === "asset:brand.stallHero")?.help,
|
||||
/真实摊位/,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await request("/admin/releases/publish", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: {},
|
||||
})
|
||||
).statusCode,
|
||||
400,
|
||||
);
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: { config: originalConfig },
|
||||
});
|
||||
await prisma.offering.update({ where: { id: originalOffering.id }, data: { coverUrl: null } });
|
||||
const missingOfferingImage = JSON.parse(
|
||||
(
|
||||
await request("/admin/releases/readiness", {
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
})
|
||||
).body,
|
||||
);
|
||||
assert.equal(missingOfferingImage.ready, false);
|
||||
assert.equal(
|
||||
missingOfferingImage.checks.find((check) => check.key === "asset:offering.cover")?.passed,
|
||||
false,
|
||||
);
|
||||
await prisma.offering.update({
|
||||
where: { id: originalOffering.id },
|
||||
data: { coverUrl: originalOffering.coverUrl },
|
||||
});
|
||||
await prisma.brandProfile.update({ where: { id: brandId }, data: { tagline: "" } });
|
||||
const incomplete = await request("/admin/releases/readiness", {
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
@@ -319,6 +383,8 @@ test("seeded public workspaces keep personal, food, and doors brands isolated",
|
||||
assert.equal(workspace.template.key, item.templateKey);
|
||||
assert.ok(workspace.visualTemplate?.key);
|
||||
assert.ok(workspace.visualTemplateManifest?.pages?.length > 0);
|
||||
assert.equal(workspace.navigation.tabs.length, item.templateKey === "food" ? 5 : 3);
|
||||
assert.equal("templatePackageManifest" in workspace, false);
|
||||
assert.equal(workspace.brand.founder, item.founder);
|
||||
assert.ok(workspace.trustContent.length > 0);
|
||||
assert.ok(workspace.trustPresentation);
|
||||
@@ -333,6 +399,10 @@ test("seeded public workspaces keep personal, food, and doors brands isolated",
|
||||
offering.presentation?.categoryLabel === item.categoryLabel,
|
||||
),
|
||||
);
|
||||
if (item.templateKey === "doors") {
|
||||
assert.ok(workspace.offerings.some((offering) => offering.presentation.series));
|
||||
assert.ok(workspace.offerings.some((offering) => offering.presentation.hardware));
|
||||
}
|
||||
return workspace;
|
||||
}),
|
||||
);
|
||||
@@ -683,6 +753,10 @@ test("admin can install a template and public workspace exposes enabled configur
|
||||
const token = JSON.parse(login.body).token;
|
||||
const before = await request("/admin/workspace");
|
||||
assert.equal(before.statusCode, 401);
|
||||
const customerAccess = await request("/admin/workspace", {
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
});
|
||||
assert.equal(customerAccess.statusCode, 403);
|
||||
const installed = await request("/admin/workspace/install", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
@@ -726,6 +800,14 @@ test("admin can install a template and public workspace exposes enabled configur
|
||||
assert.equal(workspace.statusCode, 200);
|
||||
assert.equal(JSON.parse(workspace.body).installations.length, 1);
|
||||
assert.equal(JSON.parse(workspace.body).fields.length, 5);
|
||||
const templateContent = JSON.parse(workspace.body).templateContent;
|
||||
assert.equal(templateContent.displayName, "阿成校园餐");
|
||||
assert.ok(templateContent.admin.sections.some((section) => section.title === "首页出摊信息"));
|
||||
assert.ok(
|
||||
templateContent.admin.sections
|
||||
.flatMap((section) => section.fields)
|
||||
.some((field) => field.binding === "brand.config.heroImage"),
|
||||
);
|
||||
const publicWorkspace = await request("/public/workspace");
|
||||
assert.equal(publicWorkspace.statusCode, 200);
|
||||
const workspaceBody = JSON.parse(publicWorkspace.body);
|
||||
@@ -733,6 +815,7 @@ test("admin can install a template and public workspace exposes enabled configur
|
||||
assert.equal(workspaceBody.template.key, "food");
|
||||
assert.ok(workspaceBody.modules.length > 0);
|
||||
assert.equal(workspaceBody.modules.length, workspaceBody.runtimeModules.length);
|
||||
assert.equal("templateContent" in workspaceBody, false);
|
||||
assert.equal(workspaceBody.runtimeModules[0].schemaVersion, "1.0");
|
||||
assert.ok(workspaceBody.inquiryForm);
|
||||
const conflict = await request("/admin/workspace/install", {
|
||||
@@ -1276,22 +1359,35 @@ test("brand switching isolates admin configuration, offerings, and public worksp
|
||||
assert.equal(switched.statusCode, 201);
|
||||
const doorsToken = JSON.parse(switched.body).token;
|
||||
|
||||
const [defaultConfig, doorsConfig, defaultOfferings, doorsOfferings, doorsWorkspace] =
|
||||
await Promise.all([
|
||||
request("/admin/config/brand", {
|
||||
headers: { authorization: `Bearer ${defaultToken}` },
|
||||
}),
|
||||
request("/admin/config/brand", {
|
||||
headers: { authorization: `Bearer ${doorsToken}` },
|
||||
}),
|
||||
request("/admin/workspace/offerings", {
|
||||
headers: { authorization: `Bearer ${defaultToken}` },
|
||||
}),
|
||||
request("/admin/workspace/offerings", {
|
||||
headers: { authorization: `Bearer ${doorsToken}` },
|
||||
}),
|
||||
request("/public/workspace?brandSlug=linjing-doors"),
|
||||
]);
|
||||
const [
|
||||
defaultConfig,
|
||||
doorsConfig,
|
||||
defaultOfferings,
|
||||
doorsOfferings,
|
||||
defaultAdminWorkspace,
|
||||
doorsAdminWorkspace,
|
||||
doorsWorkspace,
|
||||
] = await Promise.all([
|
||||
request("/admin/config/brand", {
|
||||
headers: { authorization: `Bearer ${defaultToken}` },
|
||||
}),
|
||||
request("/admin/config/brand", {
|
||||
headers: { authorization: `Bearer ${doorsToken}` },
|
||||
}),
|
||||
request("/admin/workspace/offerings", {
|
||||
headers: { authorization: `Bearer ${defaultToken}` },
|
||||
}),
|
||||
request("/admin/workspace/offerings", {
|
||||
headers: { authorization: `Bearer ${doorsToken}` },
|
||||
}),
|
||||
request("/admin/workspace", {
|
||||
headers: { authorization: `Bearer ${defaultToken}` },
|
||||
}),
|
||||
request("/admin/workspace", {
|
||||
headers: { authorization: `Bearer ${doorsToken}` },
|
||||
}),
|
||||
request("/public/workspace?brandSlug=linjing-doors"),
|
||||
]);
|
||||
assert.equal(defaultConfig.statusCode, 200);
|
||||
assert.equal(doorsConfig.statusCode, 200);
|
||||
assert.equal(JSON.parse(defaultConfig.body).id, brandId);
|
||||
@@ -1305,6 +1401,10 @@ test("brand switching isolates admin configuration, offerings, and public worksp
|
||||
assert.equal(doorsWorkspace.statusCode, 200);
|
||||
assert.equal(JSON.parse(doorsWorkspace.body).brand.id, doorsBrand.id);
|
||||
assert.equal(JSON.parse(doorsWorkspace.body).template.key, "doors");
|
||||
assert.equal(defaultAdminWorkspace.statusCode, 200);
|
||||
assert.equal(doorsAdminWorkspace.statusCode, 200);
|
||||
assert.equal(JSON.parse(defaultAdminWorkspace.body).templateContent.displayName, "阿成校园餐");
|
||||
assert.equal(JSON.parse(doorsAdminWorkspace.body).templateContent.displayName, "林境建筑画册");
|
||||
});
|
||||
|
||||
test("disabled brand membership blocks existing admin token", async () => {
|
||||
|
||||
@@ -43,3 +43,28 @@ test("已发布 workspace 正常返回", async () => {
|
||||
});
|
||||
assert.equal(workspace.brand.name, "测试品牌");
|
||||
});
|
||||
|
||||
test("模板声明的业务提供项展示字段会保留在小程序 view model", async () => {
|
||||
const workspace = await loadWithResponse({
|
||||
publication: { status: "published" },
|
||||
brand: { name: "测试品牌" },
|
||||
offerings: [
|
||||
{
|
||||
id: "offering-1",
|
||||
name: "别墅入户门",
|
||||
summary: "山庄项目",
|
||||
coverUrl: "/cover.jpg",
|
||||
priceText: "按项目报价",
|
||||
presentation: {
|
||||
categoryLabel: "入户大门",
|
||||
series: "万籁系列",
|
||||
area: "莫干山",
|
||||
hardware: "隐藏式地轴",
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
assert.equal(workspace.offerings[0].series, "万籁系列");
|
||||
assert.equal(workspace.offerings[0].area, "莫干山");
|
||||
assert.equal(workspace.offerings[0].hardware, "隐藏式地轴");
|
||||
});
|
||||
@@ -8,6 +8,7 @@ function toOffering(item) {
|
||||
presentation.details && typeof presentation.details === "object" ? presentation.details : {};
|
||||
return {
|
||||
...item,
|
||||
...presentation,
|
||||
id: item.id,
|
||||
category: presentation.categoryLabel || "业务提供项",
|
||||
name: item.name,
|
||||
|
||||
Reference in new issue
Block a user