refactor: 拆分模板工作区服务并统一后台访问控制

This commit is contained in:
que01 committed 2026-10-23 12:26:37 +08:00
1 parent 5051839986
commit b4e3e86dcd
13 files changed
+441 -329

No files matched your search

@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"scope": "模板完成证据登记,保留命令、日志与产物哈希",
"generatedAt": "2026-10-21T08:37:34.818Z",
"generatedAt": "2026-10-23T04:26:41.081Z",
"templates": {
"acheng-campus-food": {
"real-manifest-interaction": {
@@ -256,5 +256,5 @@
}
}
},
"sourceTreeHash": "ba35ee9629ec5aa84b9984139a4dbabc60fb576b1178f936eb8161eb905184e7"
"sourceTreeHash": "753ccedf803e63f14d8eaa3e8abcac074e274f3aed2f4f2facc3a66f8022af24"
}
@@ -1,22 +1,12 @@
import { AdminBrand } from "../../admin-auth.decorators.js";
import {
Body,
Controller,
ForbiddenException,
Get,
Param,
Post,
Query,
Req,
UnauthorizedException,
} from "@nestjs/common";
import { Body, Controller, Get, Param, Post, Query, Req } from "@nestjs/common";
import { Transform } from "class-transformer";
import type { TransformFnParams } from "class-transformer";
import { BookingStatus } from "@prisma/client";
import { IsBoolean, IsEnum, IsOptional, IsString } from "class-validator";
import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "../../admin-access.service.js";
import { BookingService } from "../../booking.service.js";
import { readIdentity } from "../../auth.js";
import { UpdateBookingStatusDto, UpdateBookingTagsDto, CreateTagDto } from "../../admin.dto.js";
class AdminBookingQueryDto {
@@ -35,67 +25,67 @@ class AdminBookingQueryDto {
@AdminBrand()
@Controller("admin/bookings")
export class AdminBookingController {
constructor(private readonly bookings: BookingService) {}
constructor(
private readonly access: AdminAccessService,
private readonly bookings: BookingService,
) {}
@Get()
list(@Req() request: FastifyRequest, @Query() query: AdminBookingQueryDto): Promise<unknown> {
const brandId = this.requireAdmin(request);
async list(
@Req() request: FastifyRequest,
@Query() query: AdminBookingQueryDto,
): Promise<unknown> {
const { brandId } = await this.access.requireBrand(request);
return this.bookings.listForAdmin(brandId, query);
}
@Get("unread-count")
unreadCount(@Req() request: FastifyRequest): Promise<unknown> {
return this.bookings.unreadCountForAdmin(this.requireAdmin(request));
async unreadCount(@Req() request: FastifyRequest): Promise<unknown> {
const { brandId } = await this.access.requireBrand(request);
return this.bookings.unreadCountForAdmin(brandId);
}
@Get(":id")
detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
return this.bookings.getForAdmin(this.requireAdmin(request), id);
async detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
const { brandId } = await this.access.requireBrand(request);
return this.bookings.getForAdmin(brandId, id);
}
@Post(":id/status")
update(
async update(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateBookingStatusDto,
): Promise<unknown> {
return this.bookings.updateStatus(this.requireAdmin(request), id, body.status, body.adminNote);
const { brandId } = await this.access.requireBrand(request);
return this.bookings.updateStatus(brandId, id, body.status, body.adminNote);
}
@Post(":id/read")
markRead(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
return this.bookings.markRead(this.requireAdmin(request), id);
async markRead(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
const { brandId } = await this.access.requireBrand(request);
return this.bookings.markRead(brandId, id);
}
@Post(":id/tags")
updateTags(
async updateTags(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateBookingTagsDto,
): Promise<unknown> {
return this.bookings.updateTags(this.requireAdmin(request), id, body.tagIds);
const { brandId } = await this.access.requireBrand(request);
return this.bookings.updateTags(brandId, id, body.tagIds);
}
@Get("tags")
listTags(@Req() request: FastifyRequest): Promise<unknown> {
return this.bookings.listTags(this.requireAdmin(request));
async listTags(@Req() request: FastifyRequest): Promise<unknown> {
const { brandId } = await this.access.requireBrand(request);
return this.bookings.listTags(brandId);
}
@Post("tags")
createTag(@Req() request: FastifyRequest, @Body() body: CreateTagDto): Promise<unknown> {
return this.bookings.createTag(this.requireAdmin(request), body.name);
}
private requireAdmin(request: FastifyRequest): string {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
try {
identity = readIdentity(token);
} catch {
throw new UnauthorizedException("管理员登录态无效或已过期");
}
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
return identity.brandId;
async createTag(@Req() request: FastifyRequest, @Body() body: CreateTagDto): Promise<unknown> {
const { brandId } = await this.access.requireBrand(request);
return this.bookings.createTag(brandId, body.name);
}
}
@@ -7,7 +7,7 @@ import {
UpdateBrandPresentationDto,
UpdateTrustContentDto,
} from "../../admin.dto.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { TrustContentService } from "../../template/trust-content.service.js";
import { requireAdminIdentity } from "../../admin-access.identity.js";
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
@@ -15,7 +15,7 @@ import { AdminBrandConfigService } from "./admin-brand-config.service.js";
@Controller("admin/config")
export class AdminConfigController {
constructor(
private readonly templateWorkspace: TemplateWorkspaceService,
private readonly trustContent: TrustContentService,
private readonly brandConfig: AdminBrandConfigService,
) {}
@Get("brand")
@@ -42,7 +42,7 @@ export class AdminConfigController {
@Get("trust-content")
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
const identity = requireAdminIdentity(request);
return this.templateWorkspace.listTrustContent(identity.brandId);
return this.trustContent.listTrustContent(identity.brandId);
}
@Post("trust-content")
createTrustContent(
@@ -50,7 +50,7 @@ export class AdminConfigController {
@Body() body: CreateTrustContentDto,
): Promise<unknown> {
const identity = requireAdminIdentity(request);
return this.templateWorkspace.createTrustContent(identity.brandId, body);
return this.trustContent.createTrustContent(identity.brandId, body);
}
@Patch("trust-content/:id")
updateTrustContent(
@@ -59,7 +59,7 @@ export class AdminConfigController {
@Body() body: UpdateTrustContentDto,
): Promise<unknown> {
const identity = requireAdminIdentity(request);
return this.templateWorkspace.updateTrustContent(identity.brandId, id, body);
return this.trustContent.updateTrustContent(identity.brandId, id, body);
}
@Delete("trust-content/:id")
async deleteTrustContent(
@@ -67,6 +67,6 @@ export class AdminConfigController {
@Param("id") id: string,
): Promise<unknown> {
const identity = requireAdminIdentity(request);
return this.templateWorkspace.deleteTrustContent(identity.brandId, id);
return this.trustContent.deleteTrustContent(identity.brandId, id);
}
}
@@ -4,7 +4,9 @@ import { AdminMembershipGuard } from "../admin-membership.guard.js";
import { BrandReleaseApiService } from "../brand-release-api.service.js";
import { BrandReleaseService } from "../brand-release.service.js";
import { PrismaService } from "../prisma.service.js";
import { TemplateWorkspaceService } from "../template-workspace.service.js";
import { PageSchemeService } from "../template/page-scheme.service.js";
import { TemplateInstallationService } from "../template/template-installation.service.js";
import { TrustContentService } from "../template/trust-content.service.js";
import { WechatAuthService } from "../wechat-auth.js";
@Module({
@@ -15,7 +17,9 @@ import { WechatAuthService } from "../wechat-auth.js";
AdminMembershipGuard,
BrandReleaseService,
BrandReleaseApiService,
TemplateWorkspaceService,
PageSchemeService,
TemplateInstallationService,
TrustContentService,
],
exports: [
PrismaService,
@@ -24,7 +28,9 @@ import { WechatAuthService } from "../wechat-auth.js";
AdminMembershipGuard,
BrandReleaseService,
BrandReleaseApiService,
TemplateWorkspaceService,
PageSchemeService,
TemplateInstallationService,
TrustContentService,
],
})
export class InfrastructureModule {}
@@ -14,7 +14,8 @@ import type {
CreateBrandMemberDto,
UpdateBrandMemberDto,
} from "../../admin.dto.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { PageSchemeService } from "../../template/page-scheme.service.js";
import { TemplateInstallationService } from "../../template/template-installation.service.js";
type AdminIdentity = { subject: string; brandId: string; tokenVersion?: number };
@@ -22,11 +23,12 @@ type AdminIdentity = { subject: string; brandId: string; tokenVersion?: number }
export class TenantService {
constructor(
private readonly prisma: PrismaService,
private readonly templateWorkspace: TemplateWorkspaceService,
private readonly pageSchemes: PageSchemeService,
private readonly templateInstallations: TemplateInstallationService,
) {}
async getCreationOptions() {
const catalog = await this.templateWorkspace.getPageSchemeCatalog();
const catalog = await this.pageSchemes.getPageSchemeCatalog();
// 创建品牌只应从每个页面方案的最新已发布版本开始;旧版本仍可在页面方案页显式切换。
return {
...catalog,
@@ -40,7 +42,7 @@ export class TenantService {
const name = body.name.trim();
const slug = body.slug.trim();
if (!name || !slug) throw new BadRequestException("品牌名称和小程序地址标识不能为空");
const packageVersion = await this.templateWorkspace.resolveInstallablePackageVersion(
const packageVersion = await this.templateInstallations.resolveInstallablePackageVersion(
body.businessType,
body.templatePackageVersionId,
);
@@ -2,24 +2,28 @@ import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { RollbackTemplateDto, UpgradeTemplateDto } from "../../admin.dto.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { PageSchemeService } from "../../template/page-scheme.service.js";
import { TemplateInstallationService } from "../../template/template-installation.service.js";
import { requireAdminIdentity } from "../../admin-access.identity.js";
@AdminBrand()
@Controller("admin/workspace")
class AdminTemplateController {
constructor(private readonly templateWorkspace: TemplateWorkspaceService) {}
constructor(
private readonly pageSchemes: PageSchemeService,
private readonly templateInstallations: TemplateInstallationService,
) {}
@AdminRoles(["owner", "admin", "platform-admin"])
@Get("template/options")
options(@Req() request: FastifyRequest): Promise<unknown> {
return this.templateWorkspace.getPageSchemeOptions(requireAdminIdentity(request).brandId);
return this.pageSchemes.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);
return this.templateInstallations.preview(requireAdminIdentity(request).brandId);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@@ -30,7 +34,7 @@ class AdminTemplateController {
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
return this.templateWorkspace.upgrade(identity.brandId, body, identity.subject, requestId);
return this.templateInstallations.upgrade(identity.brandId, body, identity.subject, requestId);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@@ -41,7 +45,7 @@ class AdminTemplateController {
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
return this.templateWorkspace.rollback(identity.brandId, identity.subject, body, requestId);
return this.templateInstallations.rollback(identity.brandId, identity.subject, body, requestId);
}
}
@@ -8,19 +8,19 @@ import {
validateCapabilityConfig,
} from "@personal-brand/config";
import { PrismaService } from "../../prisma.service.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { TemplateInstallationService } from "../../template/template-installation.service.js";
import type { UpdateCapabilityInstallationDto } from "../../admin.dto.js";
@Injectable()
export class AdminWorkspaceCapabilitiesService {
constructor(
private readonly prisma: PrismaService,
private readonly templateWorkspace: TemplateWorkspaceService,
private readonly templateInstallations: TemplateInstallationService,
) {}
async list(brandId: string) {
const [templateKey, installations] = await Promise.all([
this.templateWorkspace.getEffectiveTemplateKey(brandId),
this.templateInstallations.getEffectiveTemplateKey(brandId),
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
]);
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
@@ -54,7 +54,7 @@ export class AdminWorkspaceCapabilitiesService {
body: UpdateCapabilityInstallationDto,
) {
const template = getBrandTemplate(
await this.templateWorkspace.getEffectiveTemplateKey(brandId),
await this.templateInstallations.getEffectiveTemplateKey(brandId),
);
if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins))
throw new BadRequestException("能力未被当前模板声明");
@@ -2,7 +2,7 @@ import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
import { Controller, Get, Post, Body, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { InstallTemplateDto, SelectTemplateVersionDto } from "../../admin.dto.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { TemplateInstallationService } from "../../template/template-installation.service.js";
import { requireAdminIdentity } from "../../admin-access.identity.js";
import { AdminWorkspaceService } from "./admin-workspace.service.js";
@@ -11,7 +11,7 @@ import { AdminWorkspaceService } from "./admin-workspace.service.js";
class AdminWorkspacePreviewController {
constructor(
private readonly workspaceService: AdminWorkspaceService,
private readonly templateWorkspace: TemplateWorkspaceService,
private readonly templateInstallations: TemplateInstallationService,
) {}
@Get()
@@ -32,7 +32,7 @@ class AdminWorkspacePreviewController {
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
return this.templateWorkspace.install(
return this.templateInstallations.install(
identity.brandId,
body.templateKey,
body.templatePackageVersionId,
@@ -49,7 +49,7 @@ class AdminWorkspacePreviewController {
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
return this.templateWorkspace.selectVersion(
return this.templateInstallations.selectVersion(
identity.brandId,
body,
identity.subject,
@@ -0,0 +1,114 @@
import type { TemplatePackageVersion } from "@prisma/client";
export function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
export function manifestRecords(value: unknown): Record<string, unknown>[] {
return Array.isArray(value)
? value.filter((item): item is Record<string, unknown> =>
Boolean(item && typeof item === "object" && !Array.isArray(item)),
)
: [];
}
export function stringList(value: unknown): string[] {
return Array.isArray(value)
? value.filter((item): item is string => typeof item === "string")
: [];
}
export function hasBindingValue(config: Record<string, unknown>, binding: unknown): boolean {
if (typeof binding !== "string" || !binding.startsWith("brand.config.")) return false;
const value = binding
.slice("brand.config.".length)
.split(".")
.reduce<unknown>((current, key) => record(current)[key], config);
return value !== undefined && value !== null && value !== "";
}
export function compareRecords(current: Record<string, unknown>, target: Record<string, unknown>) {
const currentKeys = Object.keys(current);
const targetKeys = Object.keys(target);
return {
added: targetKeys
.filter((key) => !(key in current))
.map((key) => ({ key, target: target[key] })),
removed: currentKeys
.filter((key) => !(key in target))
.map((key) => ({ key, current: current[key] })),
changed: targetKeys
.filter(
(key) => key in current && JSON.stringify(current[key]) !== JSON.stringify(target[key]),
)
.map((key) => ({ key, current: current[key], target: target[key] })),
};
}
export function compareKeyedRecords(
current: Record<string, unknown>[],
target: Record<string, unknown>[],
) {
const currentByKey = new Map(
current
.filter((item) => typeof item.key === "string")
.map((item) => [item.key as string, item]),
);
const targetByKey = new Map(
target.filter((item) => typeof item.key === "string").map((item) => [item.key as string, item]),
);
return {
added: [...targetByKey].filter(([key]) => !currentByKey.has(key)).map(([, item]) => item),
removed: [...currentByKey].filter(([key]) => !targetByKey.has(key)).map(([, item]) => item),
changed: [...targetByKey].flatMap(([key, item]) => {
const previous = currentByKey.get(key);
return previous && JSON.stringify(previous) !== JSON.stringify(item)
? [{ key, current: previous, target: item }]
: [];
}),
};
}
export function compareFiles(
current: Record<string, unknown>[],
target: Record<string, unknown>[],
) {
const currentByPath = new Map(
current
.filter((item) => typeof item.path === "string")
.map((item) => [item.path as string, item]),
);
const targetByPath = new Map(
target
.filter((item) => typeof item.path === "string")
.map((item) => [item.path as string, item]),
);
const available = currentByPath.size > 0 && targetByPath.size > 0;
return {
available,
...(available
? {
added: [...targetByPath]
.filter(([path]) => !currentByPath.has(path))
.map(([, item]) => item),
removed: [...currentByPath]
.filter(([path]) => !targetByPath.has(path))
.map(([, item]) => item),
changed: [...targetByPath].flatMap(([path, item]) => {
const previous = currentByPath.get(path);
return previous && previous.sha256 !== item.sha256
? [{ path, current: previous, target: item }]
: [];
}),
}
: { reason: "版本验证报告未包含完整文件清单" }),
};
}
export function readPackageFiles(
version: Pick<TemplatePackageVersion, "validationReport">,
): Record<string, unknown>[] {
return manifestRecords(record(version.validationReport).files);
}
@@ -0,0 +1,105 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import {
type BrandTemplateKey,
brandTemplateKeys,
getBrandTemplate,
getVisualTemplate,
getVisualTemplateManifest,
isVisualTemplateCompatible,
validateTemplatePackageManifest,
} from "@personal-brand/config";
import { PrismaService } from "../prisma.service.js";
import { compareTemplateVersions } from "../template-version-order.js";
import { record } from "./manifest-diff.helpers.js";
@Injectable()
export class PageSchemeService {
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),
),
};
}
}
@@ -3,7 +3,6 @@ import type { TemplatePackageVersion } from "@prisma/client";
import { Prisma } from "@prisma/client";
import {
type BrandTemplateKey,
brandTemplateKeys,
getBrandTemplate,
getVisualTemplate,
getVisualTemplateManifest,
@@ -11,157 +10,25 @@ import {
validateTemplatePackageManifest,
} from "@personal-brand/config";
import type { TemplatePackageManifest } from "@personal-brand/config";
import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.js";
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";
import type { RollbackTemplateDto, UpgradeTemplateDto } from "../admin.dto.js";
import { PrismaService } from "../prisma.service.js";
import { recordTemplateOperationFailure } from "../modules/admin/template-operation-failure.js";
import { latestTemplateVersion } from "../template-version-order.js";
import {
compareFiles,
compareKeyedRecords,
compareRecords,
hasBindingValue,
manifestRecords,
readPackageFiles,
record,
stringList,
} from "./manifest-diff.helpers.js";
@Injectable()
export class TemplateWorkspaceService {
export class TemplateInstallationService {
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 },
include: { templatePackageVersion: true },
});
if (!installation?.templatePackageVersion)
throw new BadRequestException("品牌没有锁定精确视觉模板包版本");
const manifest = record(
installation.templatePackageVersion.manifestSnapshot,
) as unknown as TemplatePackageManifest;
if (validateTemplatePackageManifest(manifest).length)
throw new BadRequestException("当前安装的模板包不符合统一模板契约");
return manifest.trustContentTypes?.map((item) => item.type) ?? [];
}
async createTrustContent(brandId: string, body: CreateTrustContentDto) {
if (!(await this.getTrustContentTypes(brandId)).includes(body.type))
throw new BadRequestException("当前模板不支持此信任内容类型");
const { config, ...fields } = body;
return this.prisma.trustContent.create({
data: {
...fields,
brandId,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
async updateTrustContent(brandId: string, id: string, body: UpdateTrustContentDto) {
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
if (!item) throw new BadRequestException("信任内容不存在");
if (body.type !== undefined && !(await this.getTrustContentTypes(brandId)).includes(body.type))
throw new BadRequestException("当前模板不支持此信任内容类型");
const { config, ...fields } = body;
return this.prisma.trustContent.update({
where: { id },
data: {
...fields,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
listTrustContent(brandId: string) {
return this.prisma.trustContent.findMany({
where: { brandId },
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
});
}
async deleteTrustContent(brandId: string, id: string) {
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
if (!item) throw new BadRequestException("信任内容不存在");
await this.prisma.trustContent.delete({ where: { id } });
return { deleted: true };
}
async getEffectiveTemplateKey(brandId: string): Promise<BrandTemplateKey> {
const [brand, installation] = await Promise.all([
this.prisma.brandProfile.findUnique({
@@ -759,113 +626,3 @@ export class TemplateWorkspaceService {
};
}
}
function readPackageFiles(
version: Pick<TemplatePackageVersion, "validationReport">,
): Record<string, unknown>[] {
return manifestRecords(record(version.validationReport).files);
}
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
function manifestRecords(value: unknown): Record<string, unknown>[] {
return Array.isArray(value)
? value.filter((item): item is Record<string, unknown> =>
Boolean(item && typeof item === "object" && !Array.isArray(item)),
)
: [];
}
function stringList(value: unknown): string[] {
return Array.isArray(value)
? value.filter((item): item is string => typeof item === "string")
: [];
}
function hasBindingValue(config: Record<string, unknown>, binding: unknown): boolean {
if (typeof binding !== "string" || !binding.startsWith("brand.config.")) return false;
const value = binding
.slice("brand.config.".length)
.split(".")
.reduce<unknown>((current, key) => record(current)[key], config);
return value !== undefined && value !== null && value !== "";
}
function compareRecords(current: Record<string, unknown>, target: Record<string, unknown>) {
const currentKeys = Object.keys(current);
const targetKeys = Object.keys(target);
return {
added: targetKeys
.filter((key) => !(key in current))
.map((key) => ({ key, target: target[key] })),
removed: currentKeys
.filter((key) => !(key in target))
.map((key) => ({ key, current: current[key] })),
changed: targetKeys
.filter(
(key) => key in current && JSON.stringify(current[key]) !== JSON.stringify(target[key]),
)
.map((key) => ({ key, current: current[key], target: target[key] })),
};
}
function compareKeyedRecords(
current: Record<string, unknown>[],
target: Record<string, unknown>[],
) {
const currentByKey = new Map(
current
.filter((item) => typeof item.key === "string")
.map((item) => [item.key as string, item]),
);
const targetByKey = new Map(
target.filter((item) => typeof item.key === "string").map((item) => [item.key as string, item]),
);
return {
added: [...targetByKey].filter(([key]) => !currentByKey.has(key)).map(([, item]) => item),
removed: [...currentByKey].filter(([key]) => !targetByKey.has(key)).map(([, item]) => item),
changed: [...targetByKey].flatMap(([key, item]) => {
const previous = currentByKey.get(key);
return previous && JSON.stringify(previous) !== JSON.stringify(item)
? [{ key, current: previous, target: item }]
: [];
}),
};
}
function compareFiles(current: Record<string, unknown>[], target: Record<string, unknown>[]) {
const currentByPath = new Map(
current
.filter((item) => typeof item.path === "string")
.map((item) => [item.path as string, item]),
);
const targetByPath = new Map(
target
.filter((item) => typeof item.path === "string")
.map((item) => [item.path as string, item]),
);
const available = currentByPath.size > 0 && targetByPath.size > 0;
return {
available,
...(available
? {
added: [...targetByPath]
.filter(([path]) => !currentByPath.has(path))
.map(([, item]) => item),
removed: [...currentByPath]
.filter(([path]) => !targetByPath.has(path))
.map(([, item]) => item),
changed: [...targetByPath].flatMap(([path, item]) => {
const previous = currentByPath.get(path);
return previous && previous.sha256 !== item.sha256
? [{ path, current: previous, target: item }]
: [];
}),
}
: { reason: "版本验证报告未包含完整文件清单" }),
};
}
@@ -0,0 +1,69 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { validateTemplatePackageManifest } from "@personal-brand/config";
import type { TemplatePackageManifest } from "@personal-brand/config";
import type { CreateTrustContentDto, UpdateTrustContentDto } from "../admin.dto.js";
import { PrismaService } from "../prisma.service.js";
import { record } from "./manifest-diff.helpers.js";
@Injectable()
export class TrustContentService {
constructor(private readonly prisma: PrismaService) {}
async getTrustContentTypes(brandId: string): Promise<string[]> {
const installation = await this.prisma.brandTemplateInstallation.findUnique({
where: { brandId },
include: { templatePackageVersion: true },
});
if (!installation?.templatePackageVersion)
throw new BadRequestException("品牌没有锁定精确视觉模板包版本");
const manifest = record(
installation.templatePackageVersion.manifestSnapshot,
) as unknown as TemplatePackageManifest;
if (validateTemplatePackageManifest(manifest).length)
throw new BadRequestException("当前安装的模板包不符合统一模板契约");
return manifest.trustContentTypes?.map((item) => item.type) ?? [];
}
async createTrustContent(brandId: string, body: CreateTrustContentDto) {
if (!(await this.getTrustContentTypes(brandId)).includes(body.type))
throw new BadRequestException("当前模板不支持此信任内容类型");
const { config, ...fields } = body;
return this.prisma.trustContent.create({
data: {
...fields,
brandId,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
async updateTrustContent(brandId: string, id: string, body: UpdateTrustContentDto) {
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
if (!item) throw new BadRequestException("信任内容不存在");
if (body.type !== undefined && !(await this.getTrustContentTypes(brandId)).includes(body.type))
throw new BadRequestException("当前模板不支持此信任内容类型");
const { config, ...fields } = body;
return this.prisma.trustContent.update({
where: { id },
data: {
...fields,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
listTrustContent(brandId: string) {
return this.prisma.trustContent.findMany({
where: { brandId },
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
});
}
async deleteTrustContent(brandId: string, id: string) {
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
if (!item) throw new BadRequestException("信任内容不存在");
await this.prisma.trustContent.delete({ where: { id } });
return { deleted: true };
}
}
+65
View File
@@ -5123,6 +5123,71 @@ test("disabled brand membership blocks existing admin token", async () => {
}
});
test("booking endpoints share the brand access policy", async () => {
const username = `booking-policy-${randomUUID()}`;
const password = "booking-policy-password-123";
const user = await prisma.adminUser.create({
data: {
username,
passwordHash: await bcrypt.hash(password, 12),
displayName: "预订策略测试管理员",
mustChangePassword: true,
},
});
const membership = await prisma.brandMembership.create({
data: { brandId, adminUserId: user.id, role: "admin", isEnabled: true },
});
try {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username, password },
});
assert.equal(login.statusCode, 201, login.body);
const headers = { authorization: `Bearer ${sessionToken(login)}` };
const routes = [
{ method: "GET", url: "/admin/bookings" },
{ method: "GET", url: "/admin/bookings/unread-count" },
{ method: "GET", url: "/admin/bookings/tags" },
{ method: "POST", url: "/admin/bookings/tags", payload: { name: "策略测试标签" } },
];
// 初始密码未修改时,预订路由必须与其他后台路由一样被拒绝。
for (const route of routes) {
const response = await request(route.url, {
method: route.method,
headers,
...(route.payload ? { payload: route.payload } : {}),
});
assert.equal(response.statusCode, 403, `${route.method} ${route.url}: ${response.body}`);
}
// 品牌成员被停用后,同一 token 也不能再访问预订数据。
await prisma.adminUser.update({ where: { id: user.id }, data: { mustChangePassword: false } });
const changed = await request("/admin/session/login", {
method: "POST",
payload: { username, password },
});
assert.equal(changed.statusCode, 201, changed.body);
const activeHeaders = { authorization: `Bearer ${sessionToken(changed)}` };
assert.equal((await request("/admin/bookings", { headers: activeHeaders })).statusCode, 200);
await prisma.brandMembership.update({
where: { id: membership.id },
data: { isEnabled: false },
});
for (const route of routes) {
const response = await request(route.url, {
method: route.method,
headers: activeHeaders,
...(route.payload ? { payload: route.payload } : {}),
});
assert.equal(response.statusCode, 403, `${route.method} ${route.url}: ${response.body}`);
}
} finally {
await prisma.adminUser.delete({ where: { id: user.id } });
}
});
test("admin can read and update brand and service configuration", async () => {
const login = await request("/admin/session/login", {
method: "POST",