feat: 增加能力插件启停与审计

This commit is contained in:
que01 committed 2026-09-23 00:55:25 +08:00
1 parent 0fb96bdea3
commit 8a02d09e2d
6 files changed
+147 -1

No files matched your search

@@ -0,0 +1,35 @@
-- DropIndex
DROP INDEX "Booking_brandId_offeringId_idx";
-- DropIndex
DROP INDEX "BookingItem_offeringId_idx";
-- DropIndex
DROP INDEX "InquirySubmission_offeringId_idx";
-- AlterTable
ALTER TABLE "BrandTemplateInstallation" ALTER COLUMN "configSnapshot" DROP DEFAULT;
-- AlterTable
ALTER TABLE "InquirySubmission" ALTER COLUMN "updatedAt" DROP DEFAULT;
-- CreateTable
CREATE TABLE "CapabilityAuditLog" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"capabilityKey" TEXT NOT NULL,
"actorId" TEXT NOT NULL,
"action" TEXT NOT NULL,
"fromStatus" TEXT,
"toStatus" TEXT NOT NULL,
"config" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "CapabilityAuditLog_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "CapabilityAuditLog_brandId_capabilityKey_createdAt_idx" ON "CapabilityAuditLog"("brandId", "capabilityKey", "createdAt");
-- AddForeignKey
ALTER TABLE "CapabilityAuditLog" ADD CONSTRAINT "CapabilityAuditLog_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+15
View File
@@ -59,6 +59,7 @@ model BrandProfile {
inquiryForms InquiryForm[] inquiryForms InquiryForm[]
inquirySubmissions InquirySubmission[] inquirySubmissions InquirySubmission[]
capabilityInstallations CapabilityInstallation[] capabilityInstallations CapabilityInstallation[]
capabilityAuditLogs CapabilityAuditLog[]
} }
model CapabilityInstallation { model CapabilityInstallation {
@@ -75,6 +76,20 @@ model CapabilityInstallation {
@@index([brandId, status]) @@index([brandId, status])
} }
model CapabilityAuditLog {
id String @id @default(uuid())
brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
capabilityKey String
actorId String
action String
fromStatus String?
toStatus String
config Json?
createdAt DateTime @default(now())
@@index([brandId, capabilityKey, createdAt])
}
model BrandTemplateInstallation { model BrandTemplateInstallation {
id String @id @default(uuid()) id String @id @default(uuid())
brandId String brandId String
+60 -1
View File
@@ -25,7 +25,9 @@ import {
CreateInquiryFormDto, CreateInquiryFormDto,
UpdateInquiryFormDto, UpdateInquiryFormDto,
UpdateInquirySubmissionDto, UpdateInquirySubmissionDto,
UpdateCapabilityInstallationDto,
} from "./admin.dto.js"; } from "./admin.dto.js";
import { capabilityPlugins, getBrandTemplate } from "@personal-brand/config";
import { TemplateWorkspaceService } from "./template-workspace.service.js"; import { TemplateWorkspaceService } from "./template-workspace.service.js";
import { validateFieldSnapshot, validateOfferingConfig } from "@personal-brand/validation"; import { validateFieldSnapshot, validateOfferingConfig } from "@personal-brand/validation";
@@ -130,7 +132,11 @@ class AdminWorkspaceController {
await this.prisma.offering.delete({ where: { id } }); await this.prisma.offering.delete({ where: { id } });
return { deleted: true }; return { deleted: true };
} }
private requireAdmin(request: FastifyRequest): void { private requireAdmin(request: FastifyRequest): {
subject: string;
brandId: string;
role: "admin";
} {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, ""); const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态"); if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity; let identity;
@@ -140,6 +146,7 @@ class AdminWorkspaceController {
throw new UnauthorizedException("管理员登录态无效或已过期"); throw new UnauthorizedException("管理员登录态无效或已过期");
} }
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限"); if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
return identity as { subject: string; brandId: string; role: "admin" };
} }
@Get() @Get()
async get(@Req() request: FastifyRequest): Promise<unknown> { async get(@Req() request: FastifyRequest): Promise<unknown> {
@@ -167,6 +174,58 @@ class AdminWorkspaceController {
return this.templateWorkspace.install(this.brandId(), body.templateKey); return this.templateWorkspace.install(this.brandId(), body.templateKey);
} }
@Get("capabilities")
async listCapabilities(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.prisma.capabilityInstallation.findMany({ where: { brandId: this.brandId() } });
}
@Patch("capabilities/:key")
async updateCapability(
@Req() request: FastifyRequest,
@Param("key") key: string,
@Body() body: UpdateCapabilityInstallationDto,
): Promise<unknown> {
const identity = this.requireAdmin(request);
const brandId = this.brandId();
const brand = await this.prisma.brandProfile.findUnique({ where: { id: brandId } });
const template = getBrandTemplate(brand?.templateKey ?? "personal");
if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins))
throw new BadRequestException("能力未被当前模板声明");
const existing = await this.prisma.capabilityInstallation.findUnique({
where: { brandId_capabilityKey: { brandId, capabilityKey: key } },
});
return this.prisma.$transaction(async (tx) => {
const installation = await tx.capabilityInstallation.upsert({
where: { brandId_capabilityKey: { brandId, capabilityKey: key } },
create: {
brandId,
capabilityKey: key,
capabilityVersion: body.capabilityVersion,
status: body.status,
config: (body.config ?? {}) as Prisma.InputJsonValue,
},
update: {
capabilityVersion: body.capabilityVersion,
status: body.status,
...(body.config === undefined ? {} : { config: body.config as Prisma.InputJsonValue }),
},
});
await tx.capabilityAuditLog.create({
data: {
brandId,
capabilityKey: key,
actorId: identity.subject,
action: existing ? "updated" : "installed",
fromStatus: existing?.status ?? null,
toStatus: body.status,
config: (body.config ?? existing?.config ?? {}) as Prisma.InputJsonValue,
},
});
return installation;
});
}
@Get("template/preview") @Get("template/preview")
async previewTemplate(@Req() request: FastifyRequest): Promise<unknown> { async previewTemplate(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request); this.requireAdmin(request);
+7
View File
@@ -79,6 +79,13 @@ export class InstallTemplateDto {
templateKey!: "personal" | "food"; templateKey!: "personal" | "food";
} }
export class UpdateCapabilityInstallationDto {
@IsString() capabilityVersion!: string;
@IsIn(["enabled", "disabled", "degraded"])
status!: "enabled" | "disabled" | "degraded";
@IsOptional() @IsObject() config?: Record<string, unknown>;
}
export class CreateOfferingDto { export class CreateOfferingDto {
@IsIn(["service", "product", "package", "subscription"]) kind!: string; @IsIn(["service", "product", "package", "subscription"]) kind!: string;
@IsString() name!: string; @IsString() name!: string;
+28
View File
@@ -89,6 +89,34 @@ test("public workspace uses brand-scoped capability installations and preserves
} }
}); });
test("admin can update declared capability status with authorization and audit", async () => {
const unauthorized = await request("/admin/workspace/capabilities/inquiry", {
method: "PATCH",
payload: { capabilityVersion: "1.0.0", status: "disabled" },
});
assert.equal(unauthorized.statusCode, 401);
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).token;
const updated = await request("/admin/workspace/capabilities/inquiry", {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { capabilityVersion: "1.0.0", status: "disabled", config: { mode: "manual" } },
});
assert.equal(updated.statusCode, 200);
assert.equal(JSON.parse(updated.body).status, "disabled");
const audit = await prisma.capabilityAuditLog.findFirst({
where: { brandId, capabilityKey: "inquiry" },
orderBy: { createdAt: "desc" },
});
assert.ok(audit);
assert.equal(audit.toStatus, "disabled");
await prisma.capabilityInstallation.deleteMany({ where: { brandId } });
await prisma.capabilityAuditLog.deleteMany({ where: { brandId } });
});
test("admin can install a template and public workspace exposes enabled configuration", async () => { test("admin can install a template and public workspace exposes enabled configuration", async () => {
await prisma.inquirySubmission.deleteMany({ where: { brandId } }); await prisma.inquirySubmission.deleteMany({ where: { brandId } });
await prisma.inquiryForm.deleteMany({ where: { brandId } }); await prisma.inquiryForm.deleteMany({ where: { brandId } });
+2
View File
@@ -64,6 +64,8 @@
- [x] 能力状态统一输出为 `enabled`、`disabled` 或 `degraded`,并保留能力配置。 - [x] 能力状态统一输出为 `enabled`、`disabled` 或 `degraded`,并保留能力配置。
- [x] 集成测试覆盖品牌级能力安装读取、状态保留和配置隔离。 - [x] 集成测试覆盖品牌级能力安装读取、状态保留和配置隔离。
- [ ] 增加 Admin 能力启用 / 停用写接口、DTO、权限、审计和状态转换测试。 - [ ] 增加 Admin 能力启用 / 停用写接口、DTO、权限、审计和状态转换测试。
- [x] 增加 Admin 能力列表与状态更新接口,校验模板声明、品牌隔离和状态枚举。
- [x] 增加能力变更审计日志和授权 / 审计集成测试。
- [ ] Phase 5:林境门作与第二行业双模板验证。 - [ ] Phase 5:林境门作与第二行业双模板验证。
- [ ] Phase 6:Stitch 到 Manifest 的转换流水线。 - [ ] Phase 6:Stitch 到 Manifest 的转换流水线。