import { BadRequestException, ConflictException, ForbiddenException, 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 { CreateBrandDto, CreateBrandMemberDto, UpdateBrandMemberDto, } from "../../admin.dto.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 }; @Injectable() export class TenantService { constructor( private readonly prisma: PrismaService, private readonly pageSchemes: PageSchemeService, private readonly templateInstallations: TemplateInstallationService, ) {} async getCreationOptions() { const catalog = await this.pageSchemes.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.templateInstallations.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({ where: { brandId }, include: { adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } }, }, orderBy: { createdAt: "asc" }, }); } async createMember(brandId: string, body: CreateBrandMemberDto) { const username = body.username.trim(); const displayName = body.displayName.trim(); if (!username || !displayName) throw new BadRequestException("账号和显示名称不能为空"); const existing = await this.prisma.adminUser.findUnique({ where: { username } }); if (existing) throw new ConflictException("账号已存在,请使用其他账号"); const passwordHash = await bcrypt.hash(body.password, 12); return this.prisma.$transaction(async (tx) => { const adminUser = await tx.adminUser.create({ data: { username, displayName, passwordHash, role: "admin", isEnabled: true, mustChangePassword: true, }, }); return tx.brandMembership.create({ data: { adminUserId: adminUser.id, brandId, role: body.role, isEnabled: true, }, include: { adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } }, }, }); }); } async updateMember( brandId: string, actorSubject: string, id: string, body: UpdateBrandMemberDto, ) { const membership = await this.prisma.brandMembership.findFirst({ where: { id, brandId }, }); if (!membership) throw new BadRequestException("成员不存在"); if (membership.adminUserId === actorSubject) { if (body.isEnabled === false || (body.role && body.role !== membership.role)) { throw new BadRequestException("不能修改自己的角色或停用自己"); } } const nextRole = body.role ?? membership.role; const nextEnabled = body.isEnabled ?? membership.isEnabled; if (membership.role === "owner" && (nextRole !== "owner" || !nextEnabled)) { const ownerCount = await this.prisma.brandMembership.count({ where: { brandId, role: "owner", isEnabled: true }, }); if (ownerCount <= 1) throw new BadRequestException("品牌至少需要保留一位启用的负责人"); } return this.prisma.brandMembership.update({ where: { id: membership.id }, data: { ...(body.role ? { role: body.role } : {}), ...(body.isEnabled === undefined ? {} : { isEnabled: body.isEnabled }), }, include: { adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } }, }, }); } listMemberships(subject: string) { return this.prisma.brandMembership.findMany({ where: { adminUserId: subject, isEnabled: true }, include: { brand: { select: { id: true, slug: true, name: true, templateKey: true } } }, orderBy: { createdAt: "asc" }, }); } async switchBrand(identity: AdminIdentity, brandId: string) { const membership = await this.prisma.brandMembership.findFirst({ where: { adminUserId: identity.subject, brandId, isEnabled: true }, include: { brand: { select: { id: true, slug: true, name: true, templateKey: true } } }, }); if (!membership) throw new ForbiddenException("没有该品牌的管理权限"); return { token: signIdentity({ subject: identity.subject, brandId, role: "admin", tokenVersion: identity.tokenVersion ?? 0, }), role: membership.role, brand: membership.brand, }; } }