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

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

No files matched your search

@@ -0,0 +1,2 @@
ALTER TABLE "BrandProfile" ALTER COLUMN "slug" DROP DEFAULT;
ALTER TABLE "BrandProfile" ALTER COLUMN "templateKey" DROP DEFAULT;
+2 -2
View File
@@ -35,9 +35,9 @@ enum FulfillmentType {
model BrandProfile {
id String @id @default(uuid())
slug String @unique @default("default-brand")
slug String @unique
name String
templateKey String @default("food")
templateKey String
tagline String?
description String?
avatarUrl String?
+52 -20
View File
@@ -1,9 +1,20 @@
import { existsSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { PrismaClient, type Prisma } from "@prisma/client";
import type { TemplatePackageManifest } from "@personal-brand/config";
import bcrypt from "bcryptjs";
import { buildBrandReleaseSnapshot } from "../src/brand-release.service.js";
import { latestTemplateVersion } from "../src/template-version-order.js";
const prisma = new PrismaClient();
const seedAssetsDirectory = path.join(path.dirname(fileURLToPath(import.meta.url)), "assets");
function seedMediaExists(url: unknown): boolean {
if (typeof url !== "string" || !url) return false;
if (!url.startsWith("/media/seed/")) return true;
return existsSync(path.join(seedAssetsDirectory, path.basename(url)));
}
const runtimeImages = {
doors: [
@@ -48,7 +59,7 @@ interface RuntimeSeedTemplate {
const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTemplate> = {
personal: {
templateKey: "personal",
visualTemplateKey: "linjing-editorial",
visualTemplateKey: "atelier-solopreneur",
brandConfig: {
templateData: { designPhilosophy: "先厘清问题,再设计表达" },
title: "品牌策略顾问",
@@ -299,7 +310,7 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
phone: "186-0218-9908",
wechat: "LIN-ATELIER-2024",
studioAddress: "上海市静安区威海路设计中心 A 座 / 杭州良渚研造工坊",
avatarUrl: "/media/seed/personal-avatar.jpg",
avatarUrl: "/media/seed/founder-portrait.jpg",
profilePresentation: {
coverage: [
{
@@ -718,23 +729,42 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
data: { isEnabled: false },
});
}
const incompleteOfferings = await prisma.offering.findMany({
where: { brandId, isEnabled: true, coverUrl: null },
select: { id: true, name: true },
});
for (const [index, item] of incompleteOfferings.entries()) {
const image = offerings[index % offerings.length]?.image;
if (!image) throw new Error("Development fixture has no offering image");
// 旧模板迁移后可能留下数组形态的 config 或失效媒体引用。开发种子只修复结构,
// 不删除品牌内容,也不擅自重新启用已停用的业务提供项。
const allOfferings = await prisma.offering.findMany({ where: { brandId } });
const fallbackImage = offerings[0]?.image;
if (!fallbackImage) throw new Error("Development fixture has no offering image");
for (const offering of allOfferings) {
const rawConfig = offering.config;
const config =
rawConfig && typeof rawConfig === "object" && !Array.isArray(rawConfig)
? (rawConfig as Record<string, unknown>)
: {};
const media = config.media;
const hasValidMedia =
Array.isArray(media) &&
media.length > 0 &&
media.every(
(entry) =>
entry &&
typeof entry === "object" &&
!Array.isArray(entry) &&
seedMediaExists((entry as Record<string, unknown>).url),
);
const hasValidCover = seedMediaExists(offering.coverUrl);
const coverUrl = hasValidCover ? (offering.coverUrl as string) : fallbackImage;
if (hasValidCover && hasValidMedia && !Array.isArray(rawConfig)) continue;
await prisma.offering.update({
where: { id: item.id },
where: { id: offering.id },
data: {
coverUrl: image,
coverUrl,
config: {
categoryKey: "custom",
keywords: [],
media: [{ url: image, alt: item.name, type: "image" }],
sections: [],
},
...config,
...(config.categoryKey === undefined ? { categoryKey: "custom" } : {}),
...(Array.isArray(config.keywords) ? {} : { keywords: [] }),
media: [{ url: coverUrl, alt: offering.name, type: "image" }],
...(Array.isArray(config.sections) ? {} : { sections: [] }),
} as Prisma.InputJsonValue,
},
});
}
@@ -812,10 +842,12 @@ async function ensureTemplateInstallation(brandId: string): Promise<void> {
throw new Error("Development brand installation does not satisfy the template contract");
return;
}
const packageVersion = await prisma.templatePackageVersion.findFirst({
where: { packageKey: visualKey, status: "published" },
orderBy: { importedAt: "desc" },
});
// 版本升级必须按 SemVer 判断最新版,导入时间只用于同版本排序。
const packageVersion = latestTemplateVersion(
await prisma.templatePackageVersion.findMany({
where: { packageKey: visualKey, status: "published" },
}),
);
if (!packageVersion)
throw new Error(`Development brand requires a published package version: ${visualKey}`);
const configSnapshot = packageVersion.manifestSnapshot as Prisma.InputJsonValue;
+21
View File
@@ -11,6 +11,7 @@ import {
MinLength,
Matches,
Max,
MaxLength,
Min,
} from "class-validator";
import { brandTemplateKeys } from "@personal-brand/config";
@@ -53,6 +54,26 @@ export class CreateBrandMemberDto {
@IsIn(["owner", "editor"]) role!: "owner" | "editor";
}
export class CreateBrandDto {
@IsString()
@MinLength(1)
@MaxLength(80)
name!: string;
@IsString()
@Matches(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, {
message: "slug 只能包含小写字母、数字和连字符",
})
@MaxLength(80)
slug!: string;
@IsIn(brandTemplateKeys)
businessType!: BrandTemplateKey;
@IsUUID()
templatePackageVersionId!: string;
}
export class ChangeAdminPasswordDto {
@IsString() currentPassword!: string;
@IsString() @MinLength(8) newPassword!: string;
@@ -3,7 +3,8 @@ import { Body, Controller, Get, Param, Patch, Post, Req, Res } from "@nestjs/com
import type { FastifyReply, FastifyRequest } from "fastify";
import { setAdminSessionCookie } from "../../admin-session-cookie.js";
import { requireAdminIdentity } from "../../admin-access.identity.js";
import { CreateBrandMemberDto, UpdateBrandMemberDto } from "../../admin.dto.js";
import { signIdentity } from "../../auth.js";
import { CreateBrandDto, CreateBrandMemberDto, UpdateBrandMemberDto } from "../../admin.dto.js";
import { TenantService } from "./tenant.service.js";
@AdminBrand()
@@ -11,10 +12,38 @@ import { TenantService } from "./tenant.service.js";
export class TenantController {
constructor(private readonly tenants: TenantService) {}
@AdminRoles(["owner"])
@Get("creation-options")
async creationOptions(): Promise<unknown> {
return this.tenants.getCreationOptions();
}
@AdminRoles(["owner"])
@Post()
async create(
@Req() request: FastifyRequest,
@Body() body: CreateBrandDto,
@Res({ passthrough: true }) reply: FastifyReply,
): Promise<{ role: string; brand: unknown }> {
const identity = adminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
const brand = await this.tenants.createBrand(identity, body, requestId);
setAdminSessionCookie(
reply,
signIdentity({
subject: identity.subject,
brandId: brand.id,
role: "admin",
...(identity.tokenVersion === undefined ? {} : { tokenVersion: identity.tokenVersion }),
}),
);
return { role: "owner", brand };
}
@AdminRoles(["owner", "admin", "platform-admin"])
@Get("members")
async listMembers(@Req() request: FastifyRequest): Promise<unknown> {
const current = this.adminIdentity(request);
const current = adminIdentity(request);
return this.tenants.listMembers(current.brandId);
}
@@ -24,7 +53,7 @@ export class TenantController {
@Req() request: FastifyRequest,
@Body() body: CreateBrandMemberDto,
): Promise<unknown> {
const actor = this.adminIdentity(request);
const actor = adminIdentity(request);
return this.tenants.createMember(actor.brandId, body);
}
@@ -35,13 +64,13 @@ export class TenantController {
@Param("id") id: string,
@Body() body: UpdateBrandMemberDto,
): Promise<unknown> {
const actor = this.adminIdentity(request);
const actor = adminIdentity(request);
return this.tenants.updateMember(actor.brandId, actor.subject, id, body);
}
@Get()
async list(@Req() request: FastifyRequest): Promise<unknown> {
const identity = this.adminIdentity(request);
const identity = adminIdentity(request);
return this.tenants.listMemberships(identity.subject);
}
@@ -51,13 +80,13 @@ export class TenantController {
@Param("brandId") brandId: string,
@Res({ passthrough: true }) reply: FastifyReply,
): Promise<{ role: string; brand: unknown }> {
const identity = this.adminIdentity(request);
const identity = adminIdentity(request);
const result = await this.tenants.switchBrand(identity, brandId);
setAdminSessionCookie(reply, result.token);
return { role: result.role, brand: result.brand };
}
}
private adminIdentity(request: FastifyRequest) {
return requireAdminIdentity(request);
}
function adminIdentity(request: FastifyRequest) {
return requireAdminIdentity(request);
}
+94 -2
View File
@@ -5,15 +5,107 @@ import {
Injectable,
} from "@nestjs/common";
import bcrypt from "bcryptjs";
import { Prisma } from "@prisma/client";
import { getBrandTemplate } from "@personal-brand/config";
import { PrismaService } from "../../prisma.service.js";
import { signIdentity } from "../../auth.js";
import type { CreateBrandMemberDto, UpdateBrandMemberDto } from "../../admin.dto.js";
import type {
CreateBrandDto,
CreateBrandMemberDto,
UpdateBrandMemberDto,
} from "../../admin.dto.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
type AdminIdentity = { subject: string; brandId: string; tokenVersion?: number };
@Injectable()
export class TenantService {
constructor(private readonly prisma: PrismaService) {}
constructor(
private readonly prisma: PrismaService,
private readonly templateWorkspace: TemplateWorkspaceService,
) {}
async getCreationOptions() {
const catalog = await this.templateWorkspace.getPageSchemeCatalog();
// 创建品牌只应从每个页面方案的最新已发布版本开始;旧版本仍可在页面方案页显式切换。
return {
...catalog,
pageSchemes: catalog.pageSchemes.filter((scheme) => scheme.isLatestForPackage),
};
}
async createBrand(identity: AdminIdentity, body: CreateBrandDto, requestId?: string) {
const template = getBrandTemplate(body.businessType);
if (!template) throw new BadRequestException("业务类型不存在");
const name = body.name.trim();
const slug = body.slug.trim();
if (!name || !slug) throw new BadRequestException("品牌名称和小程序地址标识不能为空");
const packageVersion = await this.templateWorkspace.resolveInstallablePackageVersion(
body.businessType,
body.templatePackageVersionId,
);
try {
return await this.prisma.$transaction(async (tx) => {
const brand = await tx.brandProfile.create({
data: {
name,
slug,
templateKey: body.businessType,
config: {},
},
});
await tx.brandTemplateInstallation.create({
data: {
brandId: brand.id,
templateKey: body.businessType,
templateVersion: packageVersion.version,
templatePackageVersionId: packageVersion.id,
contentChecksum: packageVersion.contentChecksum,
configSnapshot: packageVersion.manifestSnapshot as Prisma.InputJsonValue,
},
});
await tx.brandFieldDefinition.createMany({
data: template.fields.map(({ scope, key, label, type, required }, sortOrder) => ({
brandId: brand.id,
scope,
key,
label,
type,
required,
sortOrder,
source: "core",
})),
});
await tx.brandMembership.create({
data: {
adminUserId: identity.subject,
brandId: brand.id,
role: "owner",
isEnabled: true,
},
});
await tx.templatePackageAuditLog.create({
data: {
templatePackageVersionId: packageVersion.id,
actorId: identity.subject,
action: "brand_created",
...(requestId ? { requestId } : {}),
metadata: {
brandId: brand.id,
businessType: body.businessType,
slug: brand.slug,
},
},
});
return brand;
});
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002")
throw new ConflictException("小程序地址标识已被使用,请更换后重试");
throw error;
}
}
listMembers(brandId: string) {
return this.prisma.brandMembership.findMany({
@@ -10,6 +10,13 @@ import { requireAdminIdentity } from "../../admin-access.identity.js";
class AdminTemplateController {
constructor(private readonly templateWorkspace: TemplateWorkspaceService) {}
@AdminRoles(["owner", "admin", "platform-admin"])
@Get("template/options")
options(@Req() request: FastifyRequest): Promise<unknown> {
return this.templateWorkspace.getPageSchemeOptions(requireAdminIdentity(request).brandId);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@Get("template/preview")
preview(@Req() request: FastifyRequest): Promise<unknown> {
return this.templateWorkspace.preview(requireAdminIdentity(request).brandId);
+60
View File
@@ -0,0 +1,60 @@
const SEMVER_PATTERN =
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
const fallbackVersionCollator = new Intl.Collator("en", {
numeric: true,
sensitivity: "base",
});
type VersionOrderable = {
version: string;
importedAt?: Date;
createdAt?: Date;
};
function comparePrerelease(left: string, right: string) {
if (left === right) return 0;
if (!left) return 1;
if (!right) return -1;
const leftParts = left.split(".");
const rightParts = right.split(".");
for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {
const leftPart = leftParts[index];
const rightPart = rightParts[index];
if (leftPart === undefined) return -1;
if (rightPart === undefined) return 1;
if (leftPart === rightPart) continue;
const leftNumeric = /^\d+$/.test(leftPart);
const rightNumeric = /^\d+$/.test(rightPart);
if (leftNumeric && rightNumeric) return Number(leftPart) - Number(rightPart);
if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;
return leftPart.localeCompare(rightPart);
}
return 0;
}
export function compareTemplateVersions(left: string, right: string) {
const leftMatch = SEMVER_PATTERN.exec(left);
const rightMatch = SEMVER_PATTERN.exec(right);
if (!leftMatch || !rightMatch) return fallbackVersionCollator.compare(left, right);
for (let index = 1; index <= 3; index += 1) {
const difference = Number(leftMatch[index]) - Number(rightMatch[index]);
if (difference !== 0) return difference;
}
return comparePrerelease(leftMatch[4] ?? "", rightMatch[4] ?? "");
}
/** 按 SemVer 从新到旧排序;同版本使用导入和创建时间保证顺序稳定。 */
export function compareTemplateVersionOrder(left: VersionOrderable, right: VersionOrderable) {
const versionOrder = compareTemplateVersions(right.version, left.version);
if (versionOrder !== 0) return versionOrder;
const importedOrder = (right.importedAt?.getTime() ?? 0) - (left.importedAt?.getTime() ?? 0);
if (importedOrder !== 0) return importedOrder;
return (right.createdAt?.getTime() ?? 0) - (left.createdAt?.getTime() ?? 0);
}
export function latestTemplateVersion<T extends VersionOrderable>(versions: readonly T[]) {
return versions.reduce<T | undefined>((latest, current) => {
if (!latest || compareTemplateVersionOrder(current, latest) < 0) return current;
return latest;
}, undefined);
}
+117 -11
View File
@@ -3,6 +3,7 @@ import type { TemplatePackageVersion } from "@prisma/client";
import { Prisma } from "@prisma/client";
import {
type BrandTemplateKey,
brandTemplateKeys,
getBrandTemplate,
getVisualTemplate,
getVisualTemplateManifest,
@@ -14,10 +15,99 @@ import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.j
import type { RollbackTemplateDto, UpgradeTemplateDto } from "./admin.dto.js";
import { PrismaService } from "./prisma.service.js";
import { recordTemplateOperationFailure } from "./modules/admin/template-operation-failure.js";
import { compareTemplateVersions, latestTemplateVersion } from "./template-version-order.js";
@Injectable()
export class TemplateWorkspaceService {
constructor(private readonly prisma: PrismaService) {}
async getPageSchemeCatalog() {
const versions = await this.prisma.templatePackageVersion.findMany({
where: { status: "published" },
orderBy: [{ importedAt: "desc" }, { createdAt: "desc" }],
});
const candidates = versions.flatMap((version) => {
const manifest = record(version.manifestSnapshot);
const visualTemplateKey = manifest.visualTemplateKey;
if (
manifest.packageKey !== version.packageKey ||
manifest.version !== version.version ||
typeof visualTemplateKey !== "string" ||
visualTemplateKey !== version.packageKey
)
return [];
const visualTemplate = getVisualTemplate(visualTemplateKey);
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
if (!visualTemplate || !visualManifest) return [];
const supportedBusinessTypes = Array.isArray(manifest.supportedIndustryTemplates)
? manifest.supportedIndustryTemplates.filter(
(value): value is BrandTemplateKey =>
typeof value === "string" &&
brandTemplateKeys.includes(value) &&
Boolean(getBrandTemplate(value)),
)
: [];
if (
supportedBusinessTypes.length === 0 ||
supportedBusinessTypes.some(
(businessType) => !isVisualTemplateCompatible(visualTemplate, businessType),
) ||
validateTemplatePackageManifest(manifest).length > 0
)
return [];
return [
{
templatePackageVersionId: version.id,
packageKey: version.packageKey,
name: version.displayName,
description: visualManifest.description,
version: version.version,
supportedBusinessTypes,
},
];
});
const latestByPackage = new Map<string, string>();
for (const candidate of candidates) {
const latestVersion = latestByPackage.get(candidate.packageKey);
if (!latestVersion || compareTemplateVersions(candidate.version, latestVersion) > 0) {
latestByPackage.set(candidate.packageKey, candidate.version);
}
}
const pageSchemes = candidates.map(({ packageKey, ...candidate }) => ({
...candidate,
isLatestForPackage: latestByPackage.get(packageKey) === candidate.version,
}));
return {
businesses: brandTemplateKeys.map((key) => {
const template = getBrandTemplate(key);
if (!template) throw new BadRequestException("业务类型配置不完整");
return { key, name: template.name, description: template.description };
}),
pageSchemes,
};
}
async getPageSchemeOptions(brandId: string) {
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true },
});
const template = brand ? getBrandTemplate(brand.templateKey) : undefined;
if (!brand || !template) throw new BadRequestException("品牌业务类型无效");
const catalog = await this.getPageSchemeCatalog();
return {
business: {
key: template.key,
name: template.name,
description: template.description,
},
pageSchemes: catalog.pageSchemes.filter((scheme) =>
scheme.supportedBusinessTypes.includes(template.key),
),
};
}
async getTrustContentTypes(brandId: string): Promise<string[]> {
const installation = await this.prisma.brandTemplateInstallation.findUnique({
where: { brandId },
@@ -124,6 +214,7 @@ export class TemplateWorkspaceService {
select: { templateKey: true },
}),
]);
if (!brand) throw new BadRequestException("品牌不存在");
// 一个品牌只使用一个行业模板(BrandProfile.templateKey 即身份)。安装只允许补建当前模板的版本台账,
// 不得换成别的行业模板,否则会出现「身份是 A、台账是 B」的漂移,并把发布快照接到不适配的视觉模板上。
const currentTemplate = brand?.templateKey ? getBrandTemplate(brand.templateKey) : undefined;
@@ -147,15 +238,11 @@ export class TemplateWorkspaceService {
)
throw new BadRequestException("当前视觉模板不适配行业模板");
return this.prisma.$transaction(async (tx) => {
await tx.brandProfile.update({
where: { id: brandId },
data: { templateKey },
});
const installation = await tx.brandTemplateInstallation.create({
data: {
brandId,
templateKey,
templateVersion: template.version,
templateVersion: packageVersion.version,
templatePackageVersionId: packageVersion.id,
contentChecksum: packageVersion.contentChecksum,
configSnapshot: packageVersion.manifestSnapshot as Prisma.InputJsonValue,
@@ -176,7 +263,7 @@ export class TemplateWorkspaceService {
return { installation, template, visualTemplate: visualManifest };
});
}
private async resolveInstallablePackageVersion(
async resolveInstallablePackageVersion(
templateKey: BrandTemplateKey,
templatePackageVersionId: string,
): Promise<TemplatePackageVersion> {
@@ -195,7 +282,7 @@ export class TemplateWorkspaceService {
!Array.isArray(manifest.supportedIndustryTemplates) ||
!manifest.supportedIndustryTemplates.includes(templateKey)
) {
throw new BadRequestException("模板包版本与行业或视觉模板不匹配");
throw new BadRequestException("页面方案与所选业务类型不兼容,请重新选择");
}
if (validateTemplatePackageManifest(manifest).length)
throw new BadRequestException("模板包版本不符合统一模板契约");
@@ -253,11 +340,17 @@ export class TemplateWorkspaceService {
if (!target || target.status !== "published")
throw new BadRequestException("指定模板包版本不存在或未发布");
const manifest = record(target.manifestSnapshot) as unknown as TemplatePackageManifest;
const visualTemplate =
typeof manifest.visualTemplateKey === "string"
? getVisualTemplate(manifest.visualTemplateKey)
: undefined;
if (
target.packageKey !== manifest.packageKey ||
target.version !== manifest.version ||
manifest.packageKey !== manifest.visualTemplateKey ||
!manifest.supportedIndustryTemplates?.includes(brand.templateKey) ||
!visualTemplate ||
!isVisualTemplateCompatible(visualTemplate, brand.templateKey) ||
validateTemplatePackageManifest(manifest).length
)
throw new BadRequestException("指定模板包版本不符合当前品牌的统一模板契约");
@@ -329,15 +422,28 @@ export class TemplateWorkspaceService {
).visualTemplateKey;
if (typeof visualTemplateKey !== "string")
throw new BadRequestException("已安装模板版本缺少 visualTemplateKey 声明");
const [currentPackage, targetPackage] = await Promise.all([
const [currentPackage, publishedTargets] = await Promise.all([
this.prisma.templatePackageVersion.findUnique({
where: { id: installation.templatePackageVersionId },
}),
this.prisma.templatePackageVersion.findFirst({
this.prisma.templatePackageVersion.findMany({
where: { packageKey: visualTemplateKey, status: "published" },
orderBy: { importedAt: "desc" },
}),
]);
const targetPackage = latestTemplateVersion(
publishedTargets.filter((candidate) => {
const manifest = record(candidate.manifestSnapshot);
return (
candidate.packageKey === visualTemplateKey &&
manifest.packageKey === candidate.packageKey &&
manifest.version === candidate.version &&
manifest.visualTemplateKey === visualTemplateKey &&
Array.isArray(manifest.supportedIndustryTemplates) &&
manifest.supportedIndustryTemplates.includes(installation.templateKey) &&
validateTemplatePackageManifest(manifest).length === 0
);
}),
);
if (!currentPackage) throw new BadRequestException("当前安装引用的模板包版本不存在");
if (
currentPackage.packageKey !== visualTemplateKey ||
@@ -507,7 +613,7 @@ export class TemplateWorkspaceService {
})
.sort();
if (JSON.stringify(expectedConflicts) !== JSON.stringify(preserved))
throw new ConflictException("冲突处理与当前预览不一致,请重新预览并逐项确认");
throw new ConflictException("冲突处理与当前预览不一致,请重新预览后再升级");
const manifest = record(target.manifestSnapshot);
if (
target.packageKey !==
+10
View File
@@ -12,11 +12,20 @@ import { AdminCapabilityController } from "../src/modules/workspace/admin-capabi
import { AdminOfferingController } from "../src/modules/workspace/admin-offering.controller.js";
import { AdminInquiryController } from "../src/modules/workspace/admin-inquiry.controller.js";
import { AdminTemplatePackageController } from "../src/modules/admin/admin-template-package.controller.js";
import { TenantController } from "../src/modules/tenant/tenant.controller.js";
const expectedRoutes = new Set([
"GET /admin/brands/creation-options",
"POST /admin/brands",
"GET /admin/brands/members",
"POST /admin/brands/members",
"PATCH /admin/brands/members/:id",
"GET /admin/brands",
"POST /admin/brands/:brandId/switch",
"GET /admin/workspace",
"GET /admin/workspace/preview",
"POST /admin/workspace/install",
"GET /admin/workspace/template/options",
"GET /admin/workspace/template/preview",
"POST /admin/workspace/template/upgrade",
"POST /admin/workspace/template/rollback",
@@ -50,6 +59,7 @@ const expectedRoutes = new Set([
test("refactored admin controllers preserve their declared API routes", () => {
const controllers = [
TenantController,
AdminWorkspacePreviewController,
AdminTemplateController,
AdminCapabilityController,
+481 -32
View File
@@ -137,11 +137,12 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
const baseline = JSON.parse(empty.body);
assert.deepEqual(baseline.items.map((item) => item.packageKey).sort(), [
"acheng-campus-food",
"atelier-solopreneur",
"linjing-editorial",
]);
const linjingVersion = baseline.items.find((item) => item.packageKey === "linjing-editorial");
assert.ok(linjingVersion);
assert.equal(linjingVersion.version, "1.0.6");
assert.equal(linjingVersion.version, "1.0.7");
const linjingPreview = await request(
`/admin/templates/${linjingVersion.id}/preview?industry=doors`,
{ headers },
@@ -380,15 +381,12 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
assert.equal(rejectedImport.statusCode, 400, rejectedImport.body);
assert.match(JSON.parse(rejectedImport.body).error.message, /previewFixture/);
assert.equal(await prisma.templatePackageVersion.count(), versionCount);
const archive = createTemplateArchive("atelier-solopreneur");
const multipart = multipartArchive(archive);
const imported = await request("/admin/templates/import", {
method: "POST",
headers: { ...headers, ...multipart.headers },
rawPayload: multipart.payload,
// 预览只允许使用平台当前已部署的精确 renderer 版本;复用 prepare 阶段导入的基线版本,
// 避免测试自造一个 renderer 尚未部署的新版本。
const baselineVersion = await prisma.templatePackageVersion.findFirstOrThrow({
where: { packageKey: "atelier-solopreneur", version: "1.3.2", status: "published" },
});
assert.equal(imported.statusCode, 201);
const versionId = JSON.parse(imported.body).version.id;
const versionId = baselineVersion.id;
const businessCounts = () =>
Promise.all([
@@ -625,21 +623,17 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
assert.match(JSON.parse(incompatible.body).error.message, /不支持所选行业/);
assert.deepEqual(await businessCounts(), before);
const repeatedPublish = await request(`/admin/templates/${versionId}/publish`, {
method: "POST",
headers,
});
assert.equal(repeatedPublish.statusCode, 201);
assert.equal(JSON.parse(repeatedPublish.body).changed, false);
const retired = await request(`/admin/templates/${versionId}/retire`, {
method: "POST",
headers,
});
assert.equal(retired.statusCode, 409);
const published = await request(`/admin/templates/${versionId}/publish`, {
method: "POST",
headers,
});
assert.equal(published.statusCode, 201);
const retiredAfterPublish = await request(`/admin/templates/${versionId}/retire`, {
method: "POST",
headers,
});
assert.equal(retiredAfterPublish.statusCode, 201);
assert.equal(retired.statusCode, 201);
const retiredPreview = await request(`/admin/templates/${versionId}/preview?industry=personal`, {
headers,
});
@@ -1988,7 +1982,7 @@ test("visual template compatibility is enforced by catalog, preview, and version
}
assert.deepEqual(
visuals.find((visual) => visual.key === "linjing-editorial").supportedIndustryTemplates,
["personal", "doors"],
["doors"],
);
const incompatiblePreview = await request(
"/public/templates/preview?industry=food&visual=linjing-editorial",
@@ -2149,6 +2143,337 @@ test("seeded public workspaces keep personal, food, and doors brands isolated",
assert.equal(new Set(workspaces.map((workspace) => workspace.brand.id)).size, 2);
});
test("brand creation options are owner-scoped", async () => {
const unauthorized = await request("/admin/brands/creation-options");
assert.equal(unauthorized.statusCode, 401);
const customerForbidden = await request("/admin/brands/creation-options", {
headers: { authorization: `Bearer ${customerToken}` },
});
assert.equal(customerForbidden.statusCode, 403);
const ownerLogin = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const ownerToken = sessionToken(ownerLogin);
const editorUser = await prisma.adminUser.create({
data: {
username: `creation-options-editor-${randomUUID()}`,
passwordHash: "unused",
displayName: "建品牌权限测试编辑",
mustChangePassword: false,
},
});
const editorMembership = await prisma.brandMembership.create({
data: { adminUserId: editorUser.id, brandId, role: "editor" },
});
try {
const editorToken = signIdentity({
subject: editorUser.id,
brandId,
role: "admin",
tokenVersion: editorUser.tokenVersion,
});
const editorForbidden = await request("/admin/brands/creation-options", {
headers: { authorization: `Bearer ${editorToken}` },
});
assert.equal(editorForbidden.statusCode, 403);
const response = await request("/admin/brands/creation-options", {
headers: { authorization: `Bearer ${ownerToken}` },
});
assert.equal(response.statusCode, 200, response.body);
const options = JSON.parse(response.body);
assert.deepEqual(options.businesses.map((business) => business.key).sort(), [
"doors",
"food",
"personal",
]);
assert.ok(options.businesses.every((business) => business.name && business.description));
// 创建品牌只暴露每个页面方案的最新版本,避免新品牌起步在旧版本上。
assert.equal(options.pageSchemes.length, 3, JSON.stringify(options.pageSchemes));
const linjingScheme = options.pageSchemes.find((scheme) => scheme.name.includes("林境"));
assert.ok(linjingScheme);
assert.equal(linjingScheme.version, "1.0.7");
assert.deepEqual(linjingScheme.supportedBusinessTypes, ["doors"]);
assert.equal(linjingScheme.isLatestForPackage, true);
const atelierScheme = options.pageSchemes.find((scheme) => scheme.name.includes("工坊"));
assert.ok(atelierScheme);
assert.equal(atelierScheme.version, "1.3.2");
assert.deepEqual(atelierScheme.supportedBusinessTypes, ["personal"]);
assert.equal(
options.pageSchemes.some(
(scheme) =>
scheme.supportedBusinessTypes.includes("personal") &&
scheme.supportedBusinessTypes.includes("doors"),
),
false,
"页面方案不应同时兼容 personal 和 doors",
);
assert.equal(JSON.stringify(options).includes("visualTemplateKey"), false);
assert.equal(JSON.stringify(options).includes("packageKey"), false);
} finally {
await prisma.brandMembership.delete({ where: { id: editorMembership.id } });
await prisma.adminUser.delete({ where: { id: editorUser.id } });
}
});
test("owner can create an isolated brand", async () => {
const startedAt = new Date();
const suffix = randomUUID().slice(0, 8);
const personalSlug = `atelier-created-${suffix}`;
const doorsSlug = `linjing-created-${suffix}`;
// 集成 fixture 必须锁定精确版本,避免导入时间或历史版本影响测试语义。
const atelier = await prisma.templatePackageVersion.findFirstOrThrow({
where: {
packageKey: "atelier-solopreneur",
version: "1.3.2",
status: "published",
},
});
const linjing = await prisma.templatePackageVersion.findFirstOrThrow({
where: {
packageKey: "linjing-editorial",
version: "1.0.7",
status: "published",
},
});
const ownerLogin = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const ownerToken = sessionToken(ownerLogin);
const ownerIdentity = readIdentity(ownerToken);
const unauthorizedPayload = {
name: "未授权品牌",
slug: `unauthorized-${suffix}`,
businessType: "personal",
templatePackageVersionId: atelier.id,
};
const unauthorized = await request("/admin/brands", {
method: "POST",
payload: unauthorizedPayload,
});
assert.equal(unauthorized.statusCode, 401);
const customerForbidden = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: unauthorizedPayload,
});
assert.equal(customerForbidden.statusCode, 403);
const incompatible = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "不兼容品牌",
slug: `incompatible-${suffix}`,
businessType: "personal",
templatePackageVersionId: linjing.id,
},
});
assert.equal(incompatible.statusCode, 400, incompatible.body);
assert.match(errorMessage(incompatible.body), /业务类型|页面方案|兼容/);
assert.equal(await prisma.brandProfile.count({ where: { slug: `incompatible-${suffix}` } }), 0);
try {
const created = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "新建独立工坊",
slug: personalSlug,
businessType: "personal",
templatePackageVersionId: atelier.id,
},
});
assert.equal(created.statusCode, 201, created.body);
const createdBrand = JSON.parse(created.body).brand;
assert.equal(createdBrand.slug, personalSlug);
assert.equal(createdBrand.templateKey, "personal");
const profile = await prisma.brandProfile.findUniqueOrThrow({
where: { id: createdBrand.id },
});
assert.equal(profile.templateKey, "personal");
assert.deepEqual(profile.config, {});
const installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId: createdBrand.id },
});
assert.equal(installation.templateKey, "personal");
assert.equal(installation.templatePackageVersionId, atelier.id);
assert.equal(installation.templateVersion, atelier.version);
assert.ok(
(await prisma.brandFieldDefinition.count({ where: { brandId: createdBrand.id } })) > 0,
);
const membership = await prisma.brandMembership.findUniqueOrThrow({
where: {
adminUserId_brandId: {
adminUserId: ownerIdentity.subject,
brandId: createdBrand.id,
},
},
});
assert.equal(membership.role, "owner");
assert.equal(membership.isEnabled, true);
const audit = await prisma.templatePackageAuditLog.findFirstOrThrow({
where: {
templatePackageVersionId: atelier.id,
actorId: ownerIdentity.subject,
action: "brand_created",
createdAt: { gte: startedAt },
},
orderBy: { createdAt: "desc" },
});
assert.equal(audit.metadata.brandId, createdBrand.id);
assert.equal(audit.metadata.businessType, "personal");
const newCookie = sessionToken(created);
assert.equal(readIdentity(newCookie).brandId, createdBrand.id);
const current = await request("/admin/config/brand", {
headers: { authorization: `Bearer ${newCookie}` },
});
assert.equal(current.statusCode, 200, current.body);
assert.equal(JSON.parse(current.body).id, createdBrand.id);
const duplicate = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "重复地址品牌",
slug: personalSlug,
businessType: "personal",
templatePackageVersionId: atelier.id,
},
});
assert.equal(duplicate.statusCode, 409, duplicate.body);
assert.equal(await prisma.brandProfile.count({ where: { slug: personalSlug } }), 1);
const invalidBusinessType = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "非法业务品牌",
slug: `invalid-business-${suffix}`,
businessType: "consulting",
templatePackageVersionId: atelier.id,
},
});
assert.equal(invalidBusinessType.statusCode, 400);
const incompatible = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "不兼容页面方案品牌",
slug: `incompatible-${suffix}`,
businessType: "personal",
templatePackageVersionId: linjing.id,
},
});
assert.equal(incompatible.statusCode, 400, incompatible.body);
assert.equal(await prisma.brandProfile.count({ where: { slug: `incompatible-${suffix}` } }), 0);
const doorsCreated = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "新建林境门窗",
slug: doorsSlug,
businessType: "doors",
templatePackageVersionId: linjing.id,
},
});
assert.equal(doorsCreated.statusCode, 201, doorsCreated.body);
const doorsBrand = JSON.parse(doorsCreated.body).brand;
const doorsInstallation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId: doorsBrand.id },
});
assert.equal(doorsInstallation.templateKey, "doors");
assert.equal(doorsInstallation.templatePackageVersionId, linjing.id);
} finally {
await prisma.templatePackageAuditLog.deleteMany({
where: {
actorId: ownerIdentity.subject,
action: "brand_created",
createdAt: { gte: startedAt },
},
});
await prisma.brandProfile.deleteMany({
where: { slug: { in: [personalSlug, doorsSlug] } },
});
}
});
test("page scheme options are readable by owners and admins only", async () => {
const unauthorized = await request("/admin/workspace/template/options");
assert.equal(unauthorized.statusCode, 401);
const customerForbidden = await request("/admin/workspace/template/options", {
headers: { authorization: `Bearer ${customerToken}` },
});
assert.equal(customerForbidden.statusCode, 403);
const ownerLogin = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const ownerToken = sessionToken(ownerLogin);
const members = [];
try {
for (const role of ["admin", "editor"]) {
const user = await prisma.adminUser.create({
data: {
username: `page-scheme-${role}-${randomUUID()}`,
passwordHash: "unused",
displayName: `页面方案${role}测试`,
mustChangePassword: false,
},
});
const membership = await prisma.brandMembership.create({
data: { adminUserId: user.id, brandId, role },
});
members.push({ userId: user.id, membershipId: membership.id });
const token = signIdentity({
subject: user.id,
brandId,
role: "admin",
tokenVersion: user.tokenVersion,
});
if (role === "admin") {
const adminResponse = await request("/admin/workspace/template/options", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(adminResponse.statusCode, 200, adminResponse.body);
const adminOptions = JSON.parse(adminResponse.body);
assert.equal(adminOptions.business.key, "food");
assert.equal(adminOptions.pageSchemes.length > 0, true);
assert.ok(
adminOptions.pageSchemes.every((scheme) =>
scheme.supportedBusinessTypes.includes("food"),
),
);
} else {
const editorForbidden = await request("/admin/workspace/template/options", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(editorForbidden.statusCode, 403);
}
}
const ownerResponse = await request("/admin/workspace/template/options", {
headers: { authorization: `Bearer ${ownerToken}` },
});
assert.equal(ownerResponse.statusCode, 200, ownerResponse.body);
const ownerOptions = JSON.parse(ownerResponse.body);
assert.equal(ownerOptions.business.key, "food");
assert.equal(JSON.stringify(ownerOptions).includes("visualTemplateKey"), false);
assert.equal(JSON.stringify(ownerOptions).includes("packageKey"), false);
} finally {
for (const item of members.reverse()) {
await prisma.brandMembership.delete({ where: { id: item.membershipId } });
await prisma.adminUser.delete({ where: { id: item.userId } });
}
}
});
test("public workspace uses brand-scoped capability installations and preserves status", async () => {
await prisma.capabilityInstallation.deleteMany({ where: { brandId } });
const installation = await prisma.capabilityInstallation.create({
@@ -2281,6 +2606,10 @@ test("editor membership can manage brand content but cannot change system settin
payload: { config: { visualTemplateKey: "unknown-visual" } },
});
assert.equal(visualUpdate.statusCode, 400);
const pageSchemePreview = await request("/admin/workspace/template/preview", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(pageSchemePreview.statusCode, 403);
} finally {
await prisma.brandMembership.update({
where: { id: membership.id },
@@ -2887,10 +3216,19 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
const initialManifest = structuredClone(installedPackageVersion.manifestSnapshot);
initialManifest.version = initialPackageVersion;
initialManifest.templateFields = [
{ key: "founder", binding: "brand.config.founder", label: "主理人" },
{ key: "founder", binding: "brand.config.templateData.founder", label: "主理人" },
];
initialManifest.assetSlots = [
{
key: "brand.logo",
binding: "brand.avatarUrl",
target: "brand",
label: "品牌标志",
help: "用于品牌身份展示。",
required: false,
kind: "logo",
},
];
initialManifest.entrypoints = { home: "pages/index/index" };
initialManifest.assetSlots = [{ key: "brand.logo", binding: "brand.avatarUrl" }];
initialManifest.requiredCapabilities = ["offerings"];
const initialPackageVersionRecord = await prisma.templatePackageVersion.create({
data: {
@@ -2911,9 +3249,20 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
const originalConfig =
originalBrand.config && typeof originalBrand.config === "object" ? originalBrand.config : {};
const existingFounder = "升级前的品牌主理人";
const originalTemplateData =
originalConfig.templateData &&
typeof originalConfig.templateData === "object" &&
!Array.isArray(originalConfig.templateData)
? originalConfig.templateData
: {};
await prisma.brandProfile.update({
where: { id: brandId },
data: { config: { ...originalConfig, founder: existingFounder } },
data: {
config: {
...originalConfig,
templateData: { ...originalTemplateData, founder: existingFounder },
},
},
});
await prisma.brandTemplateInstallation.update({
where: { id: installedRecord.id },
@@ -2927,15 +3276,32 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
const targetManifest = structuredClone(initialManifest);
targetManifest.version = packageVersion;
targetManifest.templateFields = [
{ key: "founder", binding: "brand.config.founder", label: "品牌主理人" },
{ key: "founder", binding: "brand.config.templateData.founder", label: "品牌主理人" },
];
targetManifest.entrypoints = {
...initialManifest.entrypoints,
home: "pages/home/index",
profile: "pages/profile/index",
gallery: "pages/gallery/index",
};
targetManifest.assetSlots = [
{ key: "brand.logo", binding: "brand.avatarUrl" },
{ key: "home.hero", binding: "brand.config.heroImage" },
{
key: "brand.logo",
binding: "brand.avatarUrl",
target: "brand",
label: "品牌标志",
help: "用于品牌身份展示。",
required: false,
kind: "logo",
},
{
key: "home.hero",
binding: "brand.config.heroImage",
target: "brand",
label: "首页主图",
help: "用于首页展示品牌重点内容。",
required: false,
kind: "image",
},
];
targetManifest.requiredCapabilities = [];
const packageVersionRecord = await prisma.templatePackageVersion.create({
@@ -2962,7 +3328,7 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
assert.equal(actionable.targetPackageVersionId, packageVersionRecord.id);
assert.equal(actionable.changes.brandFields.available, false);
assert.equal(actionable.conflicts.length, 1);
assert.equal(actionable.conflicts[0].binding, "brand.config.founder");
assert.equal(actionable.conflicts[0].binding, "brand.config.templateData.founder");
assert.equal(actionable.changes.pages.added.length, 1);
assert.equal(actionable.changes.assets.slots.added.length, 1);
assert.deepEqual(actionable.changes.capabilities.removed, ["offerings"]);
@@ -3001,7 +3367,9 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
expectedCurrentVersion: actionable.currentVersion,
expectedCurrentPackageVersionId: actionable.currentPackageVersionId,
confirm: true,
preservedBindings: [{ key: "founder", binding: "brand.config.founder", action: "preserve" }],
preservedBindings: [
{ key: "founder", binding: "brand.config.templateData.founder", action: "preserve" },
],
};
const upgradeAttempts = await Promise.all(
[0, 1].map(() =>
@@ -3020,7 +3388,8 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
packageVersionRecord.id,
);
assert.equal(
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).config.founder,
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).config.templateData
.founder,
existingFounder,
);
const retainedOldPackage = await prisma.templatePackageVersion.findUniqueOrThrow({
@@ -3391,6 +3760,86 @@ test("selected package version is reflected in public runtime workspace", async
assert.equal(body.visualTemplateManifest.key, selectedVersion.manifestSnapshot.visualTemplateKey);
});
test("legacy doors installation preview separates content package and platform renderer versions", async () => {
const doorsBrand = await prisma.brandProfile.findUniqueOrThrow({
where: { slug: "linjing-doors" },
});
const adminUser = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
const installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId: doorsBrand.id },
});
const currentPackage = await prisma.templatePackageVersion.findFirstOrThrow({
where: {
packageKey: "linjing-editorial",
version: "1.0.7",
status: "published",
},
});
// 模拟真实旧安装:内容包锁定 1.0.6,但平台 renderer 已是 1.0.7。
const legacyManifest = {
...currentPackage.manifestSnapshot,
version: "1.0.6",
supportedIndustryTemplates: ["personal", "doors"],
};
const legacyPackage = await prisma.templatePackageVersion.create({
data: {
templatePackageId: currentPackage.templatePackageId,
packageKey: currentPackage.packageKey,
version: "1.0.6",
displayName: currentPackage.displayName,
status: "published",
manifestSnapshot: legacyManifest,
validationReport: currentPackage.validationReport,
contentChecksum: `legacy-${randomUUID()}`,
archiveChecksum: `legacy-archive-${randomUUID()}`,
artifactPath: currentPackage.artifactPath,
importedById: adminUser.id,
},
});
const headers = {
authorization: `Bearer ${signIdentity({
subject: adminUser.id,
brandId: doorsBrand.id,
role: "admin",
tokenVersion: adminUser.tokenVersion,
})}`,
};
try {
await prisma.brandTemplateInstallation.update({
where: { brandId: doorsBrand.id },
data: {
templateVersion: legacyPackage.version,
templatePackageVersionId: legacyPackage.id,
contentChecksum: legacyPackage.contentChecksum,
configSnapshot: legacyPackage.manifestSnapshot,
},
});
const previewResponse = await request("/admin/workspace/template/preview", { headers });
assert.equal(previewResponse.statusCode, 200, previewResponse.body);
const preview = JSON.parse(previewResponse.body);
assert.equal(preview.currentVersion, "1.0.6");
assert.equal(preview.latestVersion, "1.0.7");
assert.equal(preview.canUpgrade, true);
assert.equal(preview.targetPackageVersionId, currentPackage.id);
assert.equal(preview.changes.renderer.available, true);
assert.equal(preview.changes.renderer.source, "platform_visual_manifest");
assert.equal(preview.changes.renderer.packageUpgradeChangesRenderer, false);
assert.ok(preview.changes.renderer.pages.length > 0);
} finally {
await prisma.brandTemplateInstallation.update({
where: { brandId: doorsBrand.id },
data: {
templateVersion: installation.templateVersion,
templatePackageVersionId: installation.templatePackageVersionId,
contentChecksum: installation.contentChecksum,
configSnapshot: installation.configSnapshot,
},
});
await prisma.templatePackageVersion.delete({ where: { id: legacyPackage.id } });
}
});
test("public workspace exposes declared brand and trust presentation data", async () => {
const doorsBrand = await prisma.brandProfile.findUnique({ where: { slug: "linjing-doors" } });
assert.ok(doorsBrand);
+25
View File
@@ -0,0 +1,25 @@
import assert from "node:assert/strict";
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import { test } from "node:test";
const projectRoot = path.resolve(import.meta.dirname, "../../..");
const seedPath = path.join(projectRoot, "apps/api/prisma/seed.ts");
const assetDirectory = path.join(projectRoot, "apps/api/prisma/assets");
test("开发 seed 引用的本地媒体都有随仓库分发的源文件", () => {
const seed = readFileSync(seedPath, "utf8");
const references = [...seed.matchAll(/["'](\/media\/seed\/[^"']+)["']/g)].map(
([, mediaPath]) => mediaPath,
);
assert.ok(references.length > 0, "seed 中没有找到本地媒体引用");
for (const mediaPath of new Set(references)) {
const filename = path.basename(mediaPath);
assert.equal(
existsSync(path.join(assetDirectory, filename)),
true,
`seed 引用的媒体缺少源文件: ${mediaPath}`,
);
}
});
@@ -10,7 +10,7 @@ import { createApp } from "../dist/main.js";
import { signIdentity } from "../dist/auth.js";
const prisma = new PrismaClient();
const packageKeys = ["acheng-campus-food", "linjing-editorial"];
const packageKeys = ["acheng-campus-food", "linjing-editorial", "atelier-solopreneur"];
function run(command, args, options = {}) {
const result = spawnSync(command, args, { stdio: "inherit", ...options });
+26 -1
View File
@@ -69,6 +69,14 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
authorizationTest: "admin can list and switch only enabled brand memberships",
successTest: "admin can list and switch only enabled brand memberships",
},
{
method: "GET",
path: "/admin/brands/creation-options",
auth: "roles",
roles: ["owner"],
authorizationTest: "brand creation options are owner-scoped",
successTest: "brand creation options are owner-scoped",
},
{
method: "GET",
path: "/admin/brands/members",
@@ -222,10 +230,19 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
{
method: "GET",
path: "/admin/workspace/template/preview",
auth: "brand",
auth: "roles",
roles: ["owner", "admin", "platform-admin"],
authorizationTest: "template ledger install, upgrade preview, and rollback stay brand-scoped",
successTest: "template ledger install, upgrade preview, and rollback stay brand-scoped",
},
{
method: "GET",
path: "/admin/workspace/template/options",
auth: "roles",
roles: ["owner", "admin", "platform-admin"],
authorizationTest: "page scheme options are readable by owners and admins only",
successTest: "page scheme options are readable by owners and admins only",
},
{
method: "GET",
path: "/customer/bookings",
@@ -436,6 +453,14 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
authorizationTest: "admin can list and switch only enabled brand memberships",
successTest: "admin can list and switch only enabled brand memberships",
},
{
method: "POST",
path: "/admin/brands",
auth: "roles",
roles: ["owner"],
authorizationTest: "owner can create an isolated brand",
successTest: "owner can create an isolated brand",
},
{
method: "POST",
path: "/admin/brands/members",
+68
View File
@@ -1,5 +1,7 @@
const assert = require("node:assert/strict");
const { randomBytes } = require("node:crypto");
const { existsSync } = require("node:fs");
const path = require("node:path");
const { spawnSync } = require("node:child_process");
const { PrismaClient } = require("@prisma/client");
@@ -32,7 +34,47 @@ async function main() {
const initialTrustCount = await fixtureDatabase.trustContent.count();
const initialFormCount = await fixtureDatabase.inquiryForm.count();
const initialReleases = await fixtureDatabase.brandRelease.findMany({ orderBy: { id: "asc" } });
// 模拟旧模板遗留数据:数组 config、失效封面和媒体引用。重复 seed 必须修复结构,
// 同时保留记录本身和停用状态。
const doorsBrand = await fixtureDatabase.brandProfile.findUniqueOrThrow({
where: { slug: "linjing-doors" },
});
const legacyOfferingName = "legacy-offering-repair-fixture";
await fixtureDatabase.offering.create({
data: {
brandId: doorsBrand.id,
kind: "service",
name: legacyOfferingName,
coverUrl: "/media/seed/seed-02.jpg",
isEnabled: false,
config: [{ url: "/media/seed/seed-02.jpg" }],
},
});
if (run("pnpm", ["db:seed"]) !== 0) return status;
const repairedLegacyOffering = await fixtureDatabase.offering.findUniqueOrThrow({
where: { brandId_name: { brandId: doorsBrand.id, name: legacyOfferingName } },
});
assert.equal(
Array.isArray(repairedLegacyOffering.config),
false,
"Repeated seed must repair legacy array config",
);
assert.ok(
repairedLegacyOffering.config &&
typeof repairedLegacyOffering.config === "object" &&
Array.isArray(repairedLegacyOffering.config.media),
"Repeated seed must rebuild legacy media config",
);
assert.notEqual(
repairedLegacyOffering.coverUrl,
"/media/seed/seed-02.jpg",
"Repeated seed must replace a missing local cover",
);
assert.equal(
repairedLegacyOffering.isEnabled,
false,
"Repeated seed must preserve disabled offering state",
);
assert.equal(
await fixtureDatabase.trustContent.count(),
initialTrustCount,
@@ -48,6 +90,32 @@ async function main() {
initialReleases,
"Repeated seed must preserve release history and snapshots",
);
const seededOfferings = await fixtureDatabase.offering.findMany({
select: { name: true, coverUrl: true, config: true },
});
assert.ok(seededOfferings.length > 0, "Seed must create offering fixtures");
for (const offering of seededOfferings) {
assert.ok(
offering.config && typeof offering.config === "object" && !Array.isArray(offering.config),
`Seed offering config must be an object: ${offering.name}`,
);
const config = offering.config;
const mediaUrls = Array.isArray(config.media)
? config.media.flatMap((item) =>
item && typeof item === "object" && typeof item.url === "string" ? [item.url] : [],
)
: [];
const localMedia = [offering.coverUrl, ...mediaUrls].filter(
(url) => typeof url === "string" && url.startsWith("/media/seed/"),
);
for (const mediaPath of new Set(localMedia)) {
assert.equal(
existsSync(path.join(__dirname, "prisma/assets", path.basename(mediaPath))),
true,
`Seed offering references missing media: ${offering.name} -> ${mediaPath}`,
);
}
}
await fixtureDatabase.adminUser.updateMany({
where: { username: "admin" },
data: { mustChangePassword: false },
@@ -45,7 +45,7 @@ async function main() {
.filter((entry) => entry.isDirectory() && entry.name !== targetMigration)
.map((entry) => entry.name)
.sort();
assert.equal(migrationDirs.at(-1), "20261018180000_add_customer_token_version");
assert.equal(migrationDirs.at(-1), "20261019100000_remove_brand_profile_defaults");
await admin.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
createdSchema = true;
@@ -180,8 +180,8 @@ test("template preview matrix keeps every deployed package, industry, and versio
}
}
}
// 3 个包 x 支持行业(1 + 1 + 2)x 2 个版本 = 8 个隔离模拟品牌。
assert.equal(visibleBrands.size, 8);
// 3 个包 × 每个包一个支持行业 × 2 个版本 = 6 个隔离模拟品牌。
assert.equal(visibleBrands.size, 6);
} finally {
for (const fixture of fixtures) rmSync(fixture.root, { recursive: true, force: true });
}
@@ -0,0 +1,33 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { compareTemplateVersions, latestTemplateVersion } from "../src/template-version-order.js";
test("模板版本按 SemVer 而不是导入时间判断最新版", () => {
const importedLaterOldVersion = {
version: "1.9.0",
importedAt: new Date("2026-10-20T00:00:00Z"),
};
const importedEarlierNewVersion = {
version: "1.10.0",
importedAt: new Date("2026-10-19T00:00:00Z"),
};
assert.equal(
latestTemplateVersion([importedEarlierNewVersion, importedLaterOldVersion])?.version,
"1.10.0",
);
assert.ok(compareTemplateVersions("1.10.0", "1.9.0") > 0);
});
test("模板版本排序正确处理预发布版本和同版本稳定性", () => {
assert.ok(compareTemplateVersions("1.0.0", "1.0.0-beta.2") > 0);
assert.ok(compareTemplateVersions("1.0.0-beta.10", "1.0.0-beta.2") > 0);
const first = {
version: "1.0.0",
importedAt: new Date("2026-10-19T00:00:00Z"),
};
const second = {
version: "1.0.0",
importedAt: new Date("2026-10-20T00:00:00Z"),
};
assert.equal(latestTemplateVersion([first, second]), second);
});