From b4e3e86dcd99c18081769c378d8b1d9278e2aeaf Mon Sep 17 00:00:00 2001 From: que01 Date: Fri, 23 Oct 2026 12:26:37 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E6=8B=86=E5=88=86=E6=A8=A1?= =?UTF-8?q?=E6=9D=BF=E5=B7=A5=E4=BD=9C=E5=8C=BA=E6=9C=8D=E5=8A=A1=E5=B9=B6?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E5=90=8E=E5=8F=B0=E8=AE=BF=E9=97=AE=E6=8E=A7?= =?UTF-8?q?=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../raw/completion-evidence.json | 4 +- .../modules/admin/admin-booking.controller.ts | 74 ++--- .../modules/admin/admin-config.controller.ts | 12 +- apps/api/src/modules/infrastructure.module.ts | 12 +- apps/api/src/modules/tenant/tenant.service.ts | 10 +- .../workspace/admin-template.controller.ts | 16 +- .../admin-workspace-capabilities.service.ts | 8 +- .../admin-workspace-preview.controller.ts | 8 +- .../api/src/template/manifest-diff.helpers.ts | 114 ++++++++ apps/api/src/template/page-scheme.service.ts | 105 +++++++ .../template-installation.service.ts} | 273 +----------------- .../api/src/template/trust-content.service.ts | 69 +++++ apps/api/test/http.integration.test.js | 65 +++++ 13 files changed, 441 insertions(+), 329 deletions(-) create mode 100644 apps/api/src/template/manifest-diff.helpers.ts create mode 100644 apps/api/src/template/page-scheme.service.ts rename apps/api/src/{template-workspace.service.ts => template/template-installation.service.ts} (72%) create mode 100644 apps/api/src/template/trust-content.service.ts diff --git a/.codex-tasks/template-audit-execution/raw/completion-evidence.json b/.codex-tasks/template-audit-execution/raw/completion-evidence.json index 4aac64f..d1e30bc 100644 --- a/.codex-tasks/template-audit-execution/raw/completion-evidence.json +++ b/.codex-tasks/template-audit-execution/raw/completion-evidence.json @@ -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" } diff --git a/apps/api/src/modules/admin/admin-booking.controller.ts b/apps/api/src/modules/admin/admin-booking.controller.ts index 2460a5e..0cff204 100644 --- a/apps/api/src/modules/admin/admin-booking.controller.ts +++ b/apps/api/src/modules/admin/admin-booking.controller.ts @@ -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 { - const brandId = this.requireAdmin(request); + async list( + @Req() request: FastifyRequest, + @Query() query: AdminBookingQueryDto, + ): Promise { + const { brandId } = await this.access.requireBrand(request); return this.bookings.listForAdmin(brandId, query); } @Get("unread-count") - unreadCount(@Req() request: FastifyRequest): Promise { - return this.bookings.unreadCountForAdmin(this.requireAdmin(request)); + async unreadCount(@Req() request: FastifyRequest): Promise { + const { brandId } = await this.access.requireBrand(request); + return this.bookings.unreadCountForAdmin(brandId); } @Get(":id") - detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise { - return this.bookings.getForAdmin(this.requireAdmin(request), id); + async detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise { + 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 { - 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 { - return this.bookings.markRead(this.requireAdmin(request), id); + async markRead(@Req() request: FastifyRequest, @Param("id") id: string): Promise { + 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 { - 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 { - return this.bookings.listTags(this.requireAdmin(request)); + async listTags(@Req() request: FastifyRequest): Promise { + const { brandId } = await this.access.requireBrand(request); + return this.bookings.listTags(brandId); } @Post("tags") - createTag(@Req() request: FastifyRequest, @Body() body: CreateTagDto): Promise { - 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 { + const { brandId } = await this.access.requireBrand(request); + return this.bookings.createTag(brandId, body.name); } } diff --git a/apps/api/src/modules/admin/admin-config.controller.ts b/apps/api/src/modules/admin/admin-config.controller.ts index 2980ee4..2bb229c 100644 --- a/apps/api/src/modules/admin/admin-config.controller.ts +++ b/apps/api/src/modules/admin/admin-config.controller.ts @@ -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 { 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 { 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 { 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 { const identity = requireAdminIdentity(request); - return this.templateWorkspace.deleteTrustContent(identity.brandId, id); + return this.trustContent.deleteTrustContent(identity.brandId, id); } } diff --git a/apps/api/src/modules/infrastructure.module.ts b/apps/api/src/modules/infrastructure.module.ts index 0ba48e9..8402988 100644 --- a/apps/api/src/modules/infrastructure.module.ts +++ b/apps/api/src/modules/infrastructure.module.ts @@ -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 {} diff --git a/apps/api/src/modules/tenant/tenant.service.ts b/apps/api/src/modules/tenant/tenant.service.ts index 83e591a..8281a9b 100644 --- a/apps/api/src/modules/tenant/tenant.service.ts +++ b/apps/api/src/modules/tenant/tenant.service.ts @@ -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, ); diff --git a/apps/api/src/modules/workspace/admin-template.controller.ts b/apps/api/src/modules/workspace/admin-template.controller.ts index 689ab86..70a72b7 100644 --- a/apps/api/src/modules/workspace/admin-template.controller.ts +++ b/apps/api/src/modules/workspace/admin-template.controller.ts @@ -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 { - 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 { - 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 { 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 { 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); } } diff --git a/apps/api/src/modules/workspace/admin-workspace-capabilities.service.ts b/apps/api/src/modules/workspace/admin-workspace-capabilities.service.ts index e4970bd..121dcba 100644 --- a/apps/api/src/modules/workspace/admin-workspace-capabilities.service.ts +++ b/apps/api/src/modules/workspace/admin-workspace-capabilities.service.ts @@ -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("能力未被当前模板声明"); diff --git a/apps/api/src/modules/workspace/admin-workspace-preview.controller.ts b/apps/api/src/modules/workspace/admin-workspace-preview.controller.ts index ee729a6..631c94e 100644 --- a/apps/api/src/modules/workspace/admin-workspace-preview.controller.ts +++ b/apps/api/src/modules/workspace/admin-workspace-preview.controller.ts @@ -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 { 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 { 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, diff --git a/apps/api/src/template/manifest-diff.helpers.ts b/apps/api/src/template/manifest-diff.helpers.ts new file mode 100644 index 0000000..af879df --- /dev/null +++ b/apps/api/src/template/manifest-diff.helpers.ts @@ -0,0 +1,114 @@ +import type { TemplatePackageVersion } from "@prisma/client"; + +export function record(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : {}; +} + +export function manifestRecords(value: unknown): Record[] { + return Array.isArray(value) + ? value.filter((item): item is Record => + 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, binding: unknown): boolean { + if (typeof binding !== "string" || !binding.startsWith("brand.config.")) return false; + const value = binding + .slice("brand.config.".length) + .split(".") + .reduce((current, key) => record(current)[key], config); + return value !== undefined && value !== null && value !== ""; +} + +export function compareRecords(current: Record, target: Record) { + 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[], + target: Record[], +) { + 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[], + target: Record[], +) { + 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, +): Record[] { + return manifestRecords(record(version.validationReport).files); +} diff --git a/apps/api/src/template/page-scheme.service.ts b/apps/api/src/template/page-scheme.service.ts new file mode 100644 index 0000000..c4a3126 --- /dev/null +++ b/apps/api/src/template/page-scheme.service.ts @@ -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(); + 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), + ), + }; + } +} diff --git a/apps/api/src/template-workspace.service.ts b/apps/api/src/template/template-installation.service.ts similarity index 72% rename from apps/api/src/template-workspace.service.ts rename to apps/api/src/template/template-installation.service.ts index 6da304e..a44663e 100644 --- a/apps/api/src/template-workspace.service.ts +++ b/apps/api/src/template/template-installation.service.ts @@ -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(); - 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 { - 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 { const [brand, installation] = await Promise.all([ this.prisma.brandProfile.findUnique({ @@ -759,113 +626,3 @@ export class TemplateWorkspaceService { }; } } - -function readPackageFiles( - version: Pick, -): Record[] { - return manifestRecords(record(version.validationReport).files); -} - -function record(value: unknown): Record { - return value && typeof value === "object" && !Array.isArray(value) - ? (value as Record) - : {}; -} - -function manifestRecords(value: unknown): Record[] { - return Array.isArray(value) - ? value.filter((item): item is Record => - 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, binding: unknown): boolean { - if (typeof binding !== "string" || !binding.startsWith("brand.config.")) return false; - const value = binding - .slice("brand.config.".length) - .split(".") - .reduce((current, key) => record(current)[key], config); - return value !== undefined && value !== null && value !== ""; -} - -function compareRecords(current: Record, target: Record) { - 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[], - target: Record[], -) { - 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[], target: Record[]) { - 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: "版本验证报告未包含完整文件清单" }), - }; -} diff --git a/apps/api/src/template/trust-content.service.ts b/apps/api/src/template/trust-content.service.ts new file mode 100644 index 0000000..20993e2 --- /dev/null +++ b/apps/api/src/template/trust-content.service.ts @@ -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 { + 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 }; + } +} diff --git a/apps/api/test/http.integration.test.js b/apps/api/test/http.integration.test.js index f416cd6..7347bab 100644 --- a/apps/api/test/http.integration.test.js +++ b/apps/api/test/http.integration.test.js @@ -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",