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

@@ -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);