feat: 新增独立工坊宣传模板及配置导入验证
This commit is contained in:
1 parent
bf4bbf81c7
commit
04e42b3a80
43 files changed
+5726
-13
No files matched your search
@@ -350,7 +350,7 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
||||
{Object.entries(sample.data.counts)
|
||||
.map(([key, count]) => `${key} ${count} 项`)
|
||||
.join("、")}
|
||||
;发布前请替换示例文案和图片。
|
||||
;同时补齐当前模板缺失的页面初始配置,保留已有配置和已启用表单。发布前请替换示例文案和图片。
|
||||
</p>
|
||||
)}
|
||||
<MutationError error={importSample.error} />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { getTemplateSampleContent } from "@personal-brand/config";
|
||||
import { getTemplateSampleContent, getDefaultVisualTemplateKey } from "@personal-brand/config";
|
||||
import { validateFieldSnapshot } from "@personal-brand/validation";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
@@ -14,7 +14,20 @@ export class AdminSampleContentService {
|
||||
|
||||
async preview(brandId: string) {
|
||||
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
||||
const sample = getTemplateSampleContent(templateKey);
|
||||
const brand = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { config: true },
|
||||
});
|
||||
const config =
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
: {};
|
||||
const sample = getTemplateSampleContent(
|
||||
templateKey,
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(templateKey),
|
||||
);
|
||||
if (!sample) throw new BadRequestException("模板示例内容不存在");
|
||||
const [offerings, trustContent, fields, enabledForms] = await Promise.all([
|
||||
this.prisma.offering.count({ where: { brandId } }),
|
||||
@@ -37,7 +50,20 @@ export class AdminSampleContentService {
|
||||
|
||||
async import(brandId: string, actorId: string) {
|
||||
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
||||
const sample = getTemplateSampleContent(templateKey);
|
||||
const brand = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { config: true },
|
||||
});
|
||||
const config =
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
: {};
|
||||
const sample = getTemplateSampleContent(
|
||||
templateKey,
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(templateKey),
|
||||
);
|
||||
if (!sample) throw new BadRequestException("模板示例内容不存在");
|
||||
if (validateFieldSnapshot(sample.fields).length)
|
||||
throw new BadRequestException("模板咨询表单示例字段无效");
|
||||
@@ -49,12 +75,42 @@ export class AdminSampleContentService {
|
||||
});
|
||||
if (existing || existingOffering) throw new BadRequestException("示例内容已经导入");
|
||||
const result = await this.prisma.$transaction(async (tx) => {
|
||||
if (sample.brandConfig) {
|
||||
// 仅显式导入时补齐缺失配置,已有品牌内容(包括空值)始终优先。
|
||||
const merge = (
|
||||
defaults: Record<string, unknown>,
|
||||
saved: Record<string, unknown>,
|
||||
): Record<string, unknown> =>
|
||||
Object.fromEntries(
|
||||
[...new Set([...Object.keys(defaults), ...Object.keys(saved)])].map((key) => {
|
||||
const a = defaults[key];
|
||||
const b = saved[key];
|
||||
if (!Object.prototype.hasOwnProperty.call(saved, key)) return [key, a];
|
||||
return [
|
||||
key,
|
||||
a &&
|
||||
b &&
|
||||
typeof a === "object" &&
|
||||
typeof b === "object" &&
|
||||
!Array.isArray(a) &&
|
||||
!Array.isArray(b)
|
||||
? merge(a as Record<string, unknown>, b as Record<string, unknown>)
|
||||
: b,
|
||||
];
|
||||
}),
|
||||
);
|
||||
await tx.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: { config: merge(sample.brandConfig, config) as Prisma.InputJsonValue },
|
||||
});
|
||||
}
|
||||
const offerings = await tx.offering.createMany({
|
||||
data: sample.offerings.map((item, sortOrder) => ({
|
||||
brandId,
|
||||
kind: item.kind,
|
||||
name: item.name,
|
||||
summary: item.summary,
|
||||
...(item.coverUrl ? { coverUrl: item.coverUrl } : {}),
|
||||
config: { categoryKey: item.categoryKey },
|
||||
sortOrder,
|
||||
isEnabled: true,
|
||||
|
||||
@@ -3455,3 +3455,272 @@ test("admin can advance booking status but cannot skip the state machine", async
|
||||
});
|
||||
assert.equal(skipped.statusCode, 400);
|
||||
});
|
||||
|
||||
test("atelier template imports selected package and preserves draft publication isolation", async () => {
|
||||
const slug = "atelier-acceptance-" + randomUUID();
|
||||
const user = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
|
||||
const originalOther = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
|
||||
const brand = await prisma.brandProfile.create({
|
||||
data: {
|
||||
slug,
|
||||
name: "品牌小程序工坊",
|
||||
templateKey: "personal",
|
||||
tagline: "独立开发者 · 品牌小程序构建",
|
||||
description: "专注个人品牌表达、内容管理与咨询承接。",
|
||||
config: {
|
||||
visualTemplateKey: "atelier-solopreneur",
|
||||
founder: "验收主理人",
|
||||
title: "产品设计 / 全栈开发",
|
||||
visualPresentation: { home: { subtitle: "保留已有品牌说明" } },
|
||||
},
|
||||
},
|
||||
});
|
||||
const headers = {
|
||||
authorization: `Bearer ${signIdentity({ subject: user.id, brandId: brand.id, role: "admin" })}`,
|
||||
};
|
||||
await prisma.brandMembership.create({
|
||||
data: { brandId: brand.id, adminUserId: user.id, role: "owner" },
|
||||
});
|
||||
const json = async (url, options = {}) => {
|
||||
const response = await request(url, options);
|
||||
assert.ok(response.statusCode < 300, response.body);
|
||||
return JSON.parse(response.body);
|
||||
};
|
||||
try {
|
||||
for (const path of ["preview", "import"]) {
|
||||
const method = path === "import" ? "POST" : "GET";
|
||||
const url = "/admin/workspace/sample-content/" + path;
|
||||
assert.equal((await request(url, { method })).statusCode, 401);
|
||||
assert.equal(
|
||||
(await request(url, { method, headers: { authorization: "Bearer invalid" } })).statusCode,
|
||||
401,
|
||||
);
|
||||
assert.equal(
|
||||
(await request(url, { method, headers: { authorization: `Bearer ${customerToken}` } }))
|
||||
.statusCode,
|
||||
403,
|
||||
);
|
||||
}
|
||||
const preview = await json("/admin/workspace/sample-content/preview", { headers });
|
||||
assert.equal(preview.counts.fields, 5);
|
||||
await json("/admin/workspace/sample-content/import", { method: "POST", headers });
|
||||
const imported = await json("/admin/config/brand", { headers });
|
||||
assert.equal(imported.config.visualPresentation.home.subtitle, "保留已有品牌说明");
|
||||
assert.equal(imported.config.atelier.deliverables.length, 7);
|
||||
const form = await prisma.inquiryForm.findFirstOrThrow({ where: { brandId: brand.id } });
|
||||
assert.equal(form.name, "品牌小程序需求意向单");
|
||||
assert.deepEqual(
|
||||
form.fieldsSnapshot.map((field) => field.key),
|
||||
["name", "industry", "needs", "timeline", "contact"],
|
||||
);
|
||||
assert.equal(
|
||||
(await request("/admin/workspace/sample-content/import", { method: "POST", headers }))
|
||||
.statusCode,
|
||||
400,
|
||||
);
|
||||
const manifest = (await json("/admin/workspace", { headers })).templateContent;
|
||||
const exampleOffering = await prisma.offering.findFirstOrThrow({
|
||||
where: { brandId: brand.id },
|
||||
});
|
||||
assert.match(exampleOffering.coverUrl, /^\/assets\/cases\//);
|
||||
const offeringFields = [
|
||||
...new Map(
|
||||
manifest.admin.sections
|
||||
.flatMap((section) => section.fields)
|
||||
.filter((field) => field.binding.startsWith("offering."))
|
||||
.map((field) => [field.binding, field]),
|
||||
).values(),
|
||||
];
|
||||
const offeringPatch = { config: structuredClone(exampleOffering.config) };
|
||||
for (const field of offeringFields) {
|
||||
const token = "atelier-offering-" + field.key;
|
||||
const value =
|
||||
field.input === "list"
|
||||
? [
|
||||
field.itemValueKey
|
||||
? token
|
||||
: Object.fromEntries(
|
||||
field.itemFields.map((child) => [child.key, token + "-" + child.key]),
|
||||
),
|
||||
]
|
||||
: field.input === "image"
|
||||
? "https://example.com/atelier-case.jpg"
|
||||
: field.input === "select"
|
||||
? field.options[0].value
|
||||
: token;
|
||||
const path = field.binding.split(".").slice(1);
|
||||
const last = path.pop();
|
||||
const parent = path.reduce((current, key) => (current[key] ??= {}), offeringPatch);
|
||||
parent[last] = value;
|
||||
}
|
||||
await json("/admin/workspace/offerings/" + exampleOffering.id, {
|
||||
method: "PATCH",
|
||||
headers,
|
||||
payload: offeringPatch,
|
||||
});
|
||||
const storedOffering = await prisma.offering.findUniqueOrThrow({
|
||||
where: { id: exampleOffering.id },
|
||||
});
|
||||
const draftOffering = (await json("/admin/workspace/preview", { headers })).offerings.find(
|
||||
(item) => item.id === exampleOffering.id,
|
||||
);
|
||||
const { runtimeContractForBinding } = await import("@personal-brand/types");
|
||||
for (const field of offeringFields) {
|
||||
const path = field.binding.split(".").slice(1);
|
||||
const read = (value, path) => path.reduce((current, key) => current?.[key], value);
|
||||
assert.deepEqual(
|
||||
read(storedOffering, path),
|
||||
read(offeringPatch, path),
|
||||
field.binding + " offering persistence",
|
||||
);
|
||||
const runtimePath =
|
||||
field.binding === "offering.config.detailHero"
|
||||
? ["presentation", "heroImage"]
|
||||
: runtimeContractForBinding(field.binding)
|
||||
.runtimePath.replace("workspace.offerings[].", "")
|
||||
.split(".");
|
||||
assert.deepEqual(
|
||||
read(draftOffering, runtimePath),
|
||||
read(offeringPatch, path),
|
||||
field.binding + " offering projection",
|
||||
);
|
||||
}
|
||||
await prisma.offering.update({
|
||||
where: { id: exampleOffering.id },
|
||||
data: {
|
||||
name: exampleOffering.name,
|
||||
summary: exampleOffering.summary,
|
||||
coverUrl: exampleOffering.coverUrl,
|
||||
priceText: exampleOffering.priceText,
|
||||
config: exampleOffering.config,
|
||||
},
|
||||
});
|
||||
const defaults = structuredClone(imported.config);
|
||||
const patch = { config: structuredClone(defaults) };
|
||||
delete patch.config.visualTemplateKey;
|
||||
const read = (value, path) => path.reduce((current, key) => current?.[key], value);
|
||||
const write = (value, path, replacement) => {
|
||||
const last = path.pop();
|
||||
const parent = path.reduce((current, key) => (current[key] ??= {}), value);
|
||||
parent[last] = replacement;
|
||||
};
|
||||
const fields = [
|
||||
...new Map(
|
||||
manifest.admin.sections
|
||||
.flatMap((section) => section.fields)
|
||||
.filter((field) => field.binding.startsWith("brand."))
|
||||
.map((field) => [field.binding, field]),
|
||||
).values(),
|
||||
];
|
||||
for (const field of fields) {
|
||||
const token = "验收-" + field.key;
|
||||
const value =
|
||||
field.input === "list"
|
||||
? [
|
||||
Object.fromEntries(
|
||||
field.itemFields.map((child) => [child.key, token + "-" + child.key]),
|
||||
),
|
||||
]
|
||||
: field.input === "image"
|
||||
? "https://example.com/atelier-avatar.jpg"
|
||||
: token;
|
||||
write(patch, field.binding.split(".").slice(1), value);
|
||||
}
|
||||
await json("/admin/config/brand", { method: "PATCH", headers, payload: patch });
|
||||
const saved = await json("/admin/config/brand", { headers });
|
||||
const draft = await json("/admin/workspace/preview", { headers });
|
||||
for (const field of fields) {
|
||||
const path = field.binding.split(".").slice(1);
|
||||
assert.deepEqual(read(saved, path), read(patch, path), field.binding + " persistence");
|
||||
assert.deepEqual(
|
||||
read(draft.brand, path[0] === "config" ? path.slice(1) : path),
|
||||
read(patch, path),
|
||||
field.binding + " preview",
|
||||
);
|
||||
}
|
||||
assert.equal((await json("/public/workspace?brandSlug=" + slug)).brand, null);
|
||||
// 恢复设计基线用于视觉回归,再验证发布后的草稿隔离。
|
||||
await json("/admin/config/brand", {
|
||||
method: "PATCH",
|
||||
headers,
|
||||
payload: { config: defaults, avatarUrl: null, contactWechat: null },
|
||||
});
|
||||
await prisma.trustContent.updateMany({
|
||||
where: { brandId: brand.id },
|
||||
data: { isPublished: true },
|
||||
});
|
||||
await json("/admin/releases/publish", {
|
||||
method: "POST",
|
||||
headers,
|
||||
payload: { note: "宣传模板独立品牌验收" },
|
||||
});
|
||||
const published = await json("/public/workspace?brandSlug=" + slug);
|
||||
assert.equal(published.brand.visualPresentation.home.subtitle, "保留已有品牌说明");
|
||||
const next = structuredClone(defaults);
|
||||
next.visualPresentation.home.title = "仅草稿可见的新标题";
|
||||
await json("/admin/config/brand", { method: "PATCH", headers, payload: { config: next } });
|
||||
assert.equal(
|
||||
(await json("/admin/workspace/preview", { headers })).brand.visualPresentation.home.title,
|
||||
"仅草稿可见的新标题",
|
||||
);
|
||||
assert.equal(
|
||||
(await json("/public/workspace?brandSlug=" + slug)).brand.visualPresentation.home.title,
|
||||
defaults.visualPresentation.home.title,
|
||||
);
|
||||
await json("/admin/releases/publish", {
|
||||
method: "POST",
|
||||
headers,
|
||||
payload: { note: "发布新标题" },
|
||||
});
|
||||
assert.equal(
|
||||
(await json("/public/workspace?brandSlug=" + slug)).brand.visualPresentation.home.title,
|
||||
"仅草稿可见的新标题",
|
||||
);
|
||||
const customerHeaders = {
|
||||
authorization: `Bearer ${signIdentity({ subject: "atelier-test-customer", brandId: brand.id, role: "customer" })}`,
|
||||
};
|
||||
assert.equal(
|
||||
(
|
||||
await request("/customer/inquiry-submissions", {
|
||||
method: "POST",
|
||||
headers: customerHeaders,
|
||||
payload: { formId: form.id, values: {} },
|
||||
})
|
||||
).statusCode,
|
||||
400,
|
||||
);
|
||||
const submitted = await json("/customer/inquiry-submissions", {
|
||||
method: "POST",
|
||||
headers: customerHeaders,
|
||||
payload: {
|
||||
formId: form.id,
|
||||
values: {
|
||||
name: "验收品牌",
|
||||
industry: "独立设计 / 建筑",
|
||||
needs: "展示作品与承接合作",
|
||||
timeline: "先期评估",
|
||||
contact: "acceptance_wechat",
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.ok(submitted.id);
|
||||
assert.equal(
|
||||
(await prisma.inquirySubmission.findUniqueOrThrow({ where: { id: submitted.id } })).brandId,
|
||||
brand.id,
|
||||
);
|
||||
assert.deepEqual(
|
||||
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).config,
|
||||
originalOther.config,
|
||||
);
|
||||
if (process.env.ATELIER_ACCEPTANCE_OUTPUT) {
|
||||
const { mkdir, writeFile } = await import("node:fs/promises");
|
||||
await mkdir(process.env.ATELIER_ACCEPTANCE_OUTPUT, { recursive: true });
|
||||
await writeFile(
|
||||
process.env.ATELIER_ACCEPTANCE_OUTPUT + "/published-runtime.json",
|
||||
JSON.stringify(published, null, 2),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await prisma.brandProfile.delete({ where: { id: brand.id } });
|
||||
}
|
||||
});
|
||||
@@ -17,13 +17,16 @@ const templates = fs
|
||||
const key = process.env.TEMPLATE_KEY || templates[0];
|
||||
if (!key) throw new Error("No Taro template package found");
|
||||
if (!templates.includes(key)) throw new Error(`Unsupported Taro template: ${key}`);
|
||||
process.env.TARO_APP_ID ||= process.env.WEAPP_APP_ID;
|
||||
process.env.TARO_APP_ID ||= process.env.WEAPP_APP_ID || "touristappid";
|
||||
const template = path.join(root, "packages", `template-${key}`);
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(template, "template.json"), "utf8")) as {
|
||||
packageKey: string;
|
||||
defaultBrandSlug?: string;
|
||||
};
|
||||
if (manifest.packageKey !== key) throw new Error(`Template key mismatch: ${key}`);
|
||||
const templateApp = JSON.parse(
|
||||
fs.readFileSync(path.join(template, "miniapp/app.json"), "utf8"),
|
||||
) as { tabBar?: { color?: string; selectedColor?: string; backgroundColor?: string } };
|
||||
const brand = process.env.BRAND_SLUG || manifest.defaultBrandSlug || "default-brand";
|
||||
fs.cpSync(path.join(template, "miniapp/assets"), path.resolve(__dirname, "../src/assets"), {
|
||||
recursive: true,
|
||||
@@ -46,6 +49,7 @@ export default defineConfig({
|
||||
: path.join(template, "taro"),
|
||||
},
|
||||
defineConstants: {
|
||||
TEMPLATE_TAB_STYLE: JSON.stringify(templateApp.tabBar || {}),
|
||||
TEMPLATE_KEY: JSON.stringify(key),
|
||||
BRAND_SLUG: JSON.stringify(brand),
|
||||
API_BASE_URL: JSON.stringify(process.env.API_BASE_URL || "http://localhost:3001"),
|
||||
|
||||
@@ -24,9 +24,9 @@ export default defineAppConfig({
|
||||
...(!PREVIEW_ALL_TEMPLATES
|
||||
? {
|
||||
tabBar: {
|
||||
color: "#8b8178",
|
||||
selectedColor: "#3b2118",
|
||||
backgroundColor: "#ffffff",
|
||||
color: TEMPLATE_TAB_STYLE.color || "#8b8178",
|
||||
selectedColor: TEMPLATE_TAB_STYLE.selectedColor || "#3b2118",
|
||||
backgroundColor: TEMPLATE_TAB_STYLE.backgroundColor || "#ffffff",
|
||||
list: TEMPLATE_MANIFEST.navigation.map((tab) => ({
|
||||
pagePath: routes[tab.page],
|
||||
text: tab.label,
|
||||
|
||||
@@ -21,9 +21,13 @@ import "./forms.css";
|
||||
export function Inquiry({
|
||||
workspace,
|
||||
preview = false,
|
||||
choiceStyle = "picker",
|
||||
beforeSubmit,
|
||||
}: {
|
||||
workspace: RuntimeWorkspace;
|
||||
preview?: boolean;
|
||||
choiceStyle?: "chips" | "picker";
|
||||
beforeSubmit?: React.ReactNode;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [offeringId, setOfferingId] = useState(router.params.offeringId || "");
|
||||
@@ -107,7 +111,8 @@ export function Inquiry({
|
||||
const value = values[field.key];
|
||||
const stringValue = typeof value === "string" ? value : "";
|
||||
const chips =
|
||||
compactForm && field.key === "type" && ["select", "radio"].includes(field.type);
|
||||
(choiceStyle === "chips" || (compactForm && field.key === "type")) &&
|
||||
["select", "radio"].includes(field.type);
|
||||
return (
|
||||
<View
|
||||
className={`form-field ${compactForm && compactFieldKeys.has(field.key) ? "half-field" : ""}`}
|
||||
@@ -200,6 +205,7 @@ export function Inquiry({
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
{beforeSubmit}
|
||||
{error && (
|
||||
<View className="form-error" role="alert">
|
||||
{error}
|
||||
|
||||
Vendored
+5
@@ -1,3 +1,8 @@
|
||||
declare const TEMPLATE_TAB_STYLE: {
|
||||
color?: string;
|
||||
selectedColor?: string;
|
||||
backgroundColor?: string;
|
||||
};
|
||||
declare const TEMPLATE_KEY: string;
|
||||
declare const BRAND_SLUG: string;
|
||||
declare const API_BASE_URL: string;
|
||||
|
||||
Reference in new issue
Block a user