feat: 收口模板升级与阶段七持续回归
This commit is contained in:
1 parent
ec16fff70e
commit
71c528de34
29 files changed
+1962
-304
No files matched your search
+16
@@ -0,0 +1,16 @@
|
||||
CREATE TABLE "TemplateOperationFailureEvent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"action" TEXT NOT NULL,
|
||||
"resultCode" TEXT NOT NULL,
|
||||
"requestId" TEXT,
|
||||
"actorId" TEXT,
|
||||
"brandId" TEXT,
|
||||
"packageKey" TEXT,
|
||||
"version" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "TemplateOperationFailureEvent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE INDEX "TemplateOperationFailureEvent_createdAt_action_idx" ON "TemplateOperationFailureEvent"("createdAt", "action");
|
||||
CREATE INDEX "TemplateOperationFailureEvent_packageKey_createdAt_idx" ON "TemplateOperationFailureEvent"("packageKey", "createdAt");
|
||||
@@ -112,25 +112,25 @@ enum MiniAppReleaseStatus {
|
||||
}
|
||||
|
||||
model MiniAppReleaseTask {
|
||||
id String @id @default(uuid())
|
||||
id String @id @default(uuid())
|
||||
brandId String
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
releaseId String?
|
||||
release BrandRelease? @relation(fields: [releaseId], references: [id], onDelete: SetNull)
|
||||
release BrandRelease? @relation(fields: [releaseId], references: [id], onDelete: SetNull)
|
||||
version Int
|
||||
status MiniAppReleaseStatus @default(built)
|
||||
status MiniAppReleaseStatus @default(built)
|
||||
artifactPath String?
|
||||
buildLogs Json?
|
||||
buildStatus MiniAppBuildStatus @default(idle)
|
||||
uploadStatus MiniAppUploadStatus @default(idle)
|
||||
reviewStatus MiniAppReviewStatus @default(not_submitted)
|
||||
buildStatus MiniAppBuildStatus @default(idle)
|
||||
uploadStatus MiniAppUploadStatus @default(idle)
|
||||
reviewStatus MiniAppReviewStatus @default(not_submitted)
|
||||
actorId String
|
||||
error String?
|
||||
weappUploadId String?
|
||||
audit Json?
|
||||
attempts MiniAppReleaseAttempt[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([brandId, version])
|
||||
@@index([brandId, createdAt])
|
||||
@@ -171,7 +171,7 @@ enum MiniAppAttemptStatus {
|
||||
}
|
||||
|
||||
model MiniAppReleaseAttempt {
|
||||
id String @id @default(uuid())
|
||||
id String @id @default(uuid())
|
||||
taskId String
|
||||
task MiniAppReleaseTask @relation(fields: [taskId], references: [id], onDelete: Cascade)
|
||||
brandId String
|
||||
@@ -179,17 +179,17 @@ model MiniAppReleaseAttempt {
|
||||
phase MiniAppAttemptPhase
|
||||
attempt Int
|
||||
status MiniAppAttemptStatus @default(running)
|
||||
leaseToken String @unique
|
||||
leaseToken String @unique
|
||||
leaseExpiresAt DateTime
|
||||
startedAt DateTime @default(now())
|
||||
heartbeatAt DateTime @default(now())
|
||||
startedAt DateTime @default(now())
|
||||
heartbeatAt DateTime @default(now())
|
||||
finishedAt DateTime?
|
||||
artifactPath String?
|
||||
externalId String?
|
||||
error String?
|
||||
logs Json?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([taskId, phase, attempt])
|
||||
@@index([brandId, taskId, phase, status])
|
||||
@@ -223,19 +223,19 @@ model CapabilityAuditLog {
|
||||
}
|
||||
|
||||
model BrandTemplateInstallation {
|
||||
id String @id @default(uuid())
|
||||
id String @id @default(uuid())
|
||||
brandId String
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
templateKey String
|
||||
templateVersion String @default("1.0.0")
|
||||
templateVersion String @default("1.0.0")
|
||||
visualTemplateKey String?
|
||||
templatePackageVersionId String?
|
||||
templatePackageVersion TemplatePackageVersion? @relation("BrandTemplateInstallationPackageVersion", fields: [templatePackageVersionId], references: [id], onDelete: SetNull)
|
||||
templatePackageVersion TemplatePackageVersion? @relation("BrandTemplateInstallationPackageVersion", fields: [templatePackageVersionId], references: [id], onDelete: SetNull)
|
||||
contentChecksum String?
|
||||
configSnapshot Json
|
||||
previousSnapshots Json @default("[]")
|
||||
installedAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
previousSnapshots Json @default("[]")
|
||||
installedAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([brandId, templateKey])
|
||||
@@index([brandId])
|
||||
@@ -453,52 +453,52 @@ model Tag {
|
||||
}
|
||||
|
||||
model AdminUser {
|
||||
id String @id @default(uuid())
|
||||
username String @unique
|
||||
passwordHash String
|
||||
displayName String
|
||||
role String @default("admin")
|
||||
platformTemplateRole PlatformTemplateRole @default(none)
|
||||
isEnabled Boolean @default(true)
|
||||
mustChangePassword Boolean @default(false)
|
||||
lastLoginAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
memberships BrandMembership[]
|
||||
importedTemplateVersions TemplatePackageVersion[] @relation("TemplatePackageImportedBy")
|
||||
templateAuditLogs TemplatePackageAuditLog[] @relation("TemplatePackageAuditActor")
|
||||
id String @id @default(uuid())
|
||||
username String @unique
|
||||
passwordHash String
|
||||
displayName String
|
||||
role String @default("admin")
|
||||
platformTemplateRole PlatformTemplateRole @default(none)
|
||||
isEnabled Boolean @default(true)
|
||||
mustChangePassword Boolean @default(false)
|
||||
lastLoginAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
memberships BrandMembership[]
|
||||
importedTemplateVersions TemplatePackageVersion[] @relation("TemplatePackageImportedBy")
|
||||
templateAuditLogs TemplatePackageAuditLog[] @relation("TemplatePackageAuditActor")
|
||||
}
|
||||
|
||||
model TemplatePackage {
|
||||
id String @id @default(uuid())
|
||||
packageKey String @unique
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
versions TemplatePackageVersion[]
|
||||
id String @id @default(uuid())
|
||||
packageKey String @unique
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
versions TemplatePackageVersion[]
|
||||
}
|
||||
|
||||
model TemplatePackageVersion {
|
||||
id String @id @default(uuid())
|
||||
id String @id @default(uuid())
|
||||
templatePackageId String
|
||||
templatePackage TemplatePackage @relation(fields: [templatePackageId], references: [id], onDelete: Cascade)
|
||||
packageKey String
|
||||
version String
|
||||
displayName String
|
||||
templatePackage TemplatePackage @relation(fields: [templatePackageId], references: [id], onDelete: Cascade)
|
||||
packageKey String
|
||||
version String
|
||||
displayName String
|
||||
visualTemplateKey String?
|
||||
status TemplatePackageVersionStatus @default(imported)
|
||||
manifestSnapshot Json
|
||||
validationReport Json
|
||||
contentChecksum String
|
||||
archiveChecksum String
|
||||
artifactPath String
|
||||
importedById String
|
||||
importedBy AdminUser @relation("TemplatePackageImportedBy", fields: [importedById], references: [id], onDelete: Restrict)
|
||||
auditLogs TemplatePackageAuditLog[]
|
||||
installations BrandTemplateInstallation[] @relation("BrandTemplateInstallationPackageVersion")
|
||||
bootstrapImports TemplateBootstrapImport[]
|
||||
importedAt DateTime @default(now())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
status TemplatePackageVersionStatus @default(imported)
|
||||
manifestSnapshot Json
|
||||
validationReport Json
|
||||
contentChecksum String
|
||||
archiveChecksum String
|
||||
artifactPath String
|
||||
importedById String
|
||||
importedBy AdminUser @relation("TemplatePackageImportedBy", fields: [importedById], references: [id], onDelete: Restrict)
|
||||
auditLogs TemplatePackageAuditLog[]
|
||||
installations BrandTemplateInstallation[] @relation("BrandTemplateInstallationPackageVersion")
|
||||
bootstrapImports TemplateBootstrapImport[]
|
||||
importedAt DateTime @default(now())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([templatePackageId, version])
|
||||
@@index([packageKey, status])
|
||||
@@ -506,20 +506,20 @@ model TemplatePackageVersion {
|
||||
}
|
||||
|
||||
model TemplateBootstrapImport {
|
||||
id String @id @default(uuid())
|
||||
id String @id @default(uuid())
|
||||
brandId String
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
templatePackageVersionId String
|
||||
templatePackageVersion TemplatePackageVersion @relation(fields: [templatePackageVersionId], references: [id], onDelete: Restrict)
|
||||
templatePackageVersion TemplatePackageVersion @relation(fields: [templatePackageVersionId], references: [id], onDelete: Restrict)
|
||||
packageKey String
|
||||
packageVersion String
|
||||
contentChecksum String
|
||||
actorId String
|
||||
strategy String @default("missing_only")
|
||||
strategy String @default("missing_only")
|
||||
status String
|
||||
result Json?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([brandId, createdAt])
|
||||
@@index([templatePackageVersionId, createdAt])
|
||||
@@ -527,22 +527,37 @@ model TemplateBootstrapImport {
|
||||
}
|
||||
|
||||
model TemplatePackageAuditLog {
|
||||
id String @id @default(uuid())
|
||||
id String @id @default(uuid())
|
||||
templatePackageVersionId String
|
||||
templatePackageVersion TemplatePackageVersion @relation(fields: [templatePackageVersionId], references: [id], onDelete: Cascade)
|
||||
actorId String
|
||||
actor AdminUser @relation("TemplatePackageAuditActor", fields: [actorId], references: [id], onDelete: Restrict)
|
||||
action String
|
||||
fromStatus TemplatePackageVersionStatus?
|
||||
toStatus TemplatePackageVersionStatus?
|
||||
requestId String?
|
||||
metadata Json?
|
||||
createdAt DateTime @default(now())
|
||||
templatePackageVersion TemplatePackageVersion @relation(fields: [templatePackageVersionId], references: [id], onDelete: Cascade)
|
||||
actorId String
|
||||
actor AdminUser @relation("TemplatePackageAuditActor", fields: [actorId], references: [id], onDelete: Restrict)
|
||||
action String
|
||||
fromStatus TemplatePackageVersionStatus?
|
||||
toStatus TemplatePackageVersionStatus?
|
||||
requestId String?
|
||||
metadata Json?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([templatePackageVersionId, createdAt])
|
||||
@@index([actorId, createdAt])
|
||||
}
|
||||
|
||||
model TemplateOperationFailureEvent {
|
||||
id String @id @default(uuid())
|
||||
action String
|
||||
resultCode String
|
||||
requestId String?
|
||||
actorId String?
|
||||
brandId String?
|
||||
packageKey String?
|
||||
version String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([createdAt, action])
|
||||
@@index([packageKey, createdAt])
|
||||
}
|
||||
|
||||
model BrandMembership {
|
||||
id String @id @default(uuid())
|
||||
adminUserId String
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
IsObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
ValidateNested,
|
||||
MinLength,
|
||||
Matches,
|
||||
Max,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
} from "class-validator";
|
||||
import { brandTemplateKeys } from "@personal-brand/config";
|
||||
import type { BrandTemplateKey } from "@personal-brand/config";
|
||||
import { Type } from "class-transformer";
|
||||
export class UpdateBrandDto {
|
||||
@IsOptional() @IsString() name?: string;
|
||||
@IsOptional() @IsString() tagline?: string;
|
||||
@@ -107,6 +109,29 @@ export class InstallTemplateDto {
|
||||
@IsOptional() @IsUUID() templatePackageVersionId?: string;
|
||||
}
|
||||
|
||||
export class UpgradeTemplateDto {
|
||||
@IsUUID() templatePackageVersionId!: string;
|
||||
@IsString() @MinLength(1) expectedContentChecksum!: string;
|
||||
@IsString() @MinLength(1) expectedCurrentVersion!: string;
|
||||
@IsOptional() @IsUUID() expectedCurrentPackageVersionId?: string | null;
|
||||
@IsBoolean() confirm!: boolean;
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => PreserveTemplateBindingDto)
|
||||
preservedBindings!: PreserveTemplateBindingDto[];
|
||||
}
|
||||
|
||||
export class PreserveTemplateBindingDto {
|
||||
@IsString() key!: string;
|
||||
@IsString() binding!: string;
|
||||
@IsIn(["preserve"]) action!: "preserve";
|
||||
}
|
||||
|
||||
export class RollbackTemplateDto {
|
||||
@IsString() @MinLength(1) expectedCurrentVersion!: string;
|
||||
@IsBoolean() confirm!: boolean;
|
||||
}
|
||||
|
||||
export class PreviewTemplateSampleDto {
|
||||
@IsOptional() @IsUUID() templatePackageVersionId?: string;
|
||||
@IsOptional() @IsIn(["missing_only"]) strategy?: "missing_only";
|
||||
|
||||
@@ -27,7 +27,11 @@ export class AdminTemplatePackageController {
|
||||
@Post("import")
|
||||
async import(@Req() request: FastifyRequest) {
|
||||
const { subject } = await this.access.requireTemplateAdmin(request);
|
||||
return this.templates.importArchive(request, subject);
|
||||
return this.templates.importArchive(
|
||||
request,
|
||||
subject,
|
||||
request.headers["x-request-id"]?.toString() ?? request.id,
|
||||
);
|
||||
}
|
||||
|
||||
@Post(":id/publish")
|
||||
|
||||
@@ -14,6 +14,7 @@ import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { recordTemplateOperationFailure } from "./template-operation-failure.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const MAX_ARCHIVE_BYTES = 50 * 1024 * 1024;
|
||||
@@ -181,13 +182,15 @@ export class AdminTemplatePackageService {
|
||||
};
|
||||
}
|
||||
|
||||
async importArchive(request: FastifyRequest, actorId: string) {
|
||||
async importArchive(request: FastifyRequest, actorId: string, requestId?: string) {
|
||||
const part = await request.file({ limits: { files: 1, fileSize: MAX_ARCHIVE_BYTES } });
|
||||
if (!part) throw new BadRequestException("请上传模板 archive 文件");
|
||||
if (part.fieldname !== "archive") throw new BadRequestException("上传字段必须是 archive");
|
||||
const chunks: Buffer[] = [];
|
||||
let bytes = 0;
|
||||
let storedArtifactPath: string | null = null;
|
||||
let failurePackageKey: string | undefined;
|
||||
let failureVersion: string | undefined;
|
||||
try {
|
||||
for await (const chunk of part.file) {
|
||||
const buffer = Buffer.from(chunk as Uint8Array);
|
||||
@@ -242,6 +245,8 @@ export class AdminTemplatePackageService {
|
||||
path.join(packageRoot, "template.json"),
|
||||
"template.json",
|
||||
)) as Manifest;
|
||||
failurePackageKey = typeof manifest.packageKey === "string" ? manifest.packageKey : undefined;
|
||||
failureVersion = typeof manifest.version === "string" ? manifest.version : undefined;
|
||||
const packageJson = jsonObject(
|
||||
await this.readJson(path.join(packageRoot, "package.json"), "package.json"),
|
||||
"package.json",
|
||||
@@ -304,6 +309,7 @@ export class AdminTemplatePackageService {
|
||||
errors: [],
|
||||
fileCount: files.length,
|
||||
extractedBytes: files.reduce((total, file) => total + file.bytes, 0),
|
||||
files: checksums.files.map((file) => ({ ...file })),
|
||||
},
|
||||
contentChecksum: checksums.contentChecksum,
|
||||
archiveChecksum,
|
||||
@@ -328,6 +334,14 @@ export class AdminTemplatePackageService {
|
||||
return { imported: true, idempotent: false, version: this.publicVersion(version) };
|
||||
} catch (error) {
|
||||
if (storedArtifactPath) await fs.rm(storedArtifactPath, { force: true });
|
||||
await recordTemplateOperationFailure(this.prisma, {
|
||||
action: "import",
|
||||
error,
|
||||
...(requestId ? { requestId } : {}),
|
||||
actorId,
|
||||
...(failurePackageKey ? { packageKey: failurePackageKey } : {}),
|
||||
...(failureVersion ? { version: failureVersion } : {}),
|
||||
});
|
||||
throw error;
|
||||
} finally {
|
||||
await fs.rm(temporaryRoot, { recursive: true, force: true });
|
||||
|
||||
@@ -18,6 +18,7 @@ import type { BrandReleaseSnapshot } from "../../brand-release.service.js";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { assemblePublicWorkspace } from "../public/public-workspace.snapshot-assembler.js";
|
||||
import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-assets.service.js";
|
||||
import { recordTemplateOperationFailure } from "./template-operation-failure.js";
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
@@ -118,7 +119,18 @@ export class AdminTemplatePreviewService {
|
||||
};
|
||||
}
|
||||
|
||||
const projection = await this.buildPreview(id, industry);
|
||||
let projection: Awaited<ReturnType<AdminTemplatePreviewService["buildPreview"]>>;
|
||||
try {
|
||||
projection = await this.buildPreview(id, industry);
|
||||
} catch (error) {
|
||||
await recordTemplateOperationFailure(this.prisma, {
|
||||
action: "preview",
|
||||
error,
|
||||
...(requestId ? { requestId } : {}),
|
||||
actorId,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
this.cleanupPreviewSessions();
|
||||
const token = randomBytes(32).toString("hex");
|
||||
const expiresAt = Date.now() + 15 * 60 * 1000;
|
||||
|
||||
@@ -15,6 +15,8 @@ import { AdminUploadService } from "./admin-upload.service.js";
|
||||
import { AdminUploadController } from "./admin-upload.controller.js";
|
||||
import { AdminTemplatePackageController } from "./admin-template-package.controller.js";
|
||||
import { AdminTemplatePackageService } from "./admin-template-package.service.js";
|
||||
import { TemplateOperationMetricsController } from "./template-operation-metrics.controller.js";
|
||||
import { TemplateOperationMetricsService } from "./template-operation-metrics.service.js";
|
||||
|
||||
import { AdminTemplatePreviewService } from "./admin-template-preview.service.js";
|
||||
import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-assets.service.js";
|
||||
@@ -29,6 +31,7 @@ import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-asse
|
||||
AdminLocalUploadController,
|
||||
AdminBookingController,
|
||||
AdminTemplatePackageController,
|
||||
TemplateOperationMetricsController,
|
||||
],
|
||||
providers: [
|
||||
AdminBrandConfigService,
|
||||
@@ -40,6 +43,7 @@ import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-asse
|
||||
AdminTemplatePackageService,
|
||||
AdminTemplatePreviewService,
|
||||
AdminTemplatePreviewAssetsService,
|
||||
TemplateOperationMetricsService,
|
||||
],
|
||||
})
|
||||
export class AdminModule {}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { HttpException } from "@nestjs/common";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
|
||||
export async function recordTemplateOperationFailure(
|
||||
prisma: PrismaService,
|
||||
input: {
|
||||
action: string;
|
||||
error: unknown;
|
||||
requestId?: string;
|
||||
actorId?: string;
|
||||
brandId?: string;
|
||||
packageKey?: string;
|
||||
version?: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
const status = input.error instanceof HttpException ? input.error.getStatus() : 500;
|
||||
try {
|
||||
await prisma.templateOperationFailureEvent.create({
|
||||
data: {
|
||||
action: input.action,
|
||||
resultCode: `HTTP_${status}`,
|
||||
...(input.requestId ? { requestId: input.requestId } : {}),
|
||||
...(input.actorId ? { actorId: input.actorId } : {}),
|
||||
...(input.brandId ? { brandId: input.brandId } : {}),
|
||||
...(input.packageKey ? { packageKey: input.packageKey } : {}),
|
||||
...(input.version ? { version: input.version } : {}),
|
||||
},
|
||||
});
|
||||
await prisma.templateOperationFailureEvent.deleteMany({
|
||||
where: { createdAt: { lt: new Date(Date.now() - 180 * 24 * 60 * 60 * 1000) } },
|
||||
});
|
||||
} catch {
|
||||
// Failure telemetry must never replace the operation's original result.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Controller, Get, Query, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { Type } from "class-transformer";
|
||||
import { IsInt, IsOptional, Max, Min } from "class-validator";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { TemplateOperationMetricsService } from "./template-operation-metrics.service.js";
|
||||
|
||||
class TemplateOperationMetricsQueryDto {
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(90)
|
||||
days = 30;
|
||||
}
|
||||
|
||||
@Controller("admin/template-operations")
|
||||
export class TemplateOperationMetricsController {
|
||||
constructor(
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly metrics: TemplateOperationMetricsService,
|
||||
) {}
|
||||
|
||||
@Get("failures")
|
||||
async failures(@Req() request: FastifyRequest, @Query() query: TemplateOperationMetricsQueryDto) {
|
||||
await this.access.requireTemplateAdmin(request);
|
||||
return this.metrics.failures(query.days);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
|
||||
const trackedActions = [
|
||||
"import",
|
||||
"preview",
|
||||
"install",
|
||||
"upgrade",
|
||||
"rollback",
|
||||
"install_conflict",
|
||||
] as const;
|
||||
|
||||
@Injectable()
|
||||
export class TemplateOperationMetricsService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async failures(days = 30) {
|
||||
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
|
||||
const [templateEvents, releaseAttempts] = await Promise.all([
|
||||
this.prisma.templateOperationFailureEvent.groupBy({
|
||||
by: ["action"],
|
||||
where: { createdAt: { gte: since } },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
this.prisma.miniAppReleaseAttempt.groupBy({
|
||||
by: ["phase", "status"],
|
||||
where: {
|
||||
createdAt: { gte: since },
|
||||
status: { in: ["failed", "timed_out"] },
|
||||
},
|
||||
_count: { _all: true },
|
||||
}),
|
||||
]);
|
||||
const eventCounts = new Map(templateEvents.map((item) => [item.action, item._count._all]));
|
||||
const buildUploadCounts = new Map<string, number>();
|
||||
for (const item of releaseAttempts) {
|
||||
const action = item.phase === "build" ? "build" : "upload";
|
||||
buildUploadCounts.set(action, (buildUploadCounts.get(action) ?? 0) + item._count._all);
|
||||
}
|
||||
return {
|
||||
since: since.toISOString(),
|
||||
until: new Date().toISOString(),
|
||||
days,
|
||||
backfilled: false,
|
||||
failures: [
|
||||
...trackedActions.map((action) => ({ action, count: eventCounts.get(action) ?? 0 })),
|
||||
{ action: "build", count: buildUploadCounts.get("build") ?? 0 },
|
||||
{ action: "upload", count: buildUploadCounts.get("upload") ?? 0 },
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,17 @@
|
||||
import { Controller, Get, Post, Req } from "@nestjs/common";
|
||||
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 { PrismaService } from "../../prisma.service.js";
|
||||
import { recordTemplateOperationFailure } from "../admin/template-operation-failure.js";
|
||||
import { requireAdminIdentity } from "./admin-access.identity.js";
|
||||
|
||||
@Controller("admin/workspace")
|
||||
class AdminTemplateController {
|
||||
constructor(private readonly templateWorkspace: TemplateWorkspaceService) {}
|
||||
constructor(
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
private readonly prisma: PrismaService,
|
||||
) {}
|
||||
|
||||
@Get("template/preview")
|
||||
preview(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
@@ -13,13 +19,58 @@ class AdminTemplateController {
|
||||
}
|
||||
|
||||
@Post("template/upgrade")
|
||||
upgrade(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
return this.templateWorkspace.upgrade(requireAdminIdentity(request).brandId);
|
||||
async upgrade(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: UpgradeTemplateDto,
|
||||
): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||
try {
|
||||
return await this.templateWorkspace.upgrade(
|
||||
identity.brandId,
|
||||
body,
|
||||
identity.subject,
|
||||
requestId,
|
||||
);
|
||||
} catch (error) {
|
||||
await recordTemplateOperationFailure(this.prisma, {
|
||||
action:
|
||||
error instanceof Error && error.name.includes("Conflict")
|
||||
? "install_conflict"
|
||||
: "upgrade",
|
||||
error,
|
||||
requestId,
|
||||
actorId: identity.subject,
|
||||
brandId: identity.brandId,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@Post("template/rollback")
|
||||
rollback(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
return this.templateWorkspace.rollback(requireAdminIdentity(request).brandId);
|
||||
async rollback(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: RollbackTemplateDto,
|
||||
): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||
try {
|
||||
return await this.templateWorkspace.rollback(
|
||||
identity.brandId,
|
||||
identity.subject,
|
||||
body,
|
||||
requestId,
|
||||
);
|
||||
} catch (error) {
|
||||
await recordTemplateOperationFailure(this.prisma, {
|
||||
action: "rollback",
|
||||
error,
|
||||
requestId,
|
||||
actorId: identity.subject,
|
||||
brandId: identity.brandId,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,12 +4,15 @@ import { InstallTemplateDto } from "../../admin.dto.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { requireAdminIdentity } from "./admin-access.identity.js";
|
||||
import { AdminWorkspaceService } from "./admin-workspace.service.js";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { recordTemplateOperationFailure } from "../admin/template-operation-failure.js";
|
||||
|
||||
@Controller("admin/workspace")
|
||||
class AdminWorkspacePreviewController {
|
||||
constructor(
|
||||
private readonly workspaceService: AdminWorkspaceService,
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
private readonly prisma: PrismaService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@@ -23,12 +26,31 @@ class AdminWorkspacePreviewController {
|
||||
}
|
||||
|
||||
@Post("install")
|
||||
install(@Req() request: FastifyRequest, @Body() body: InstallTemplateDto): Promise<unknown> {
|
||||
return this.templateWorkspace.install(
|
||||
requireAdminIdentity(request).brandId,
|
||||
body.templateKey,
|
||||
body.templatePackageVersionId,
|
||||
);
|
||||
async install(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: InstallTemplateDto,
|
||||
): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||
try {
|
||||
return await this.templateWorkspace.install(
|
||||
identity.brandId,
|
||||
body.templateKey,
|
||||
body.templatePackageVersionId,
|
||||
);
|
||||
} catch (error) {
|
||||
await recordTemplateOperationFailure(this.prisma, {
|
||||
action:
|
||||
error instanceof Error && error.name.includes("Conflict")
|
||||
? "install_conflict"
|
||||
: "install",
|
||||
error,
|
||||
requestId,
|
||||
actorId: identity.subject,
|
||||
brandId: identity.brandId,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
|
||||
import type { TemplatePackageVersion } from "@prisma/client";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import {
|
||||
type BrandTemplateKey,
|
||||
defaultBrandTemplateKey,
|
||||
@@ -12,8 +14,11 @@ import {
|
||||
isVisualTemplateCompatible,
|
||||
} 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";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
@Injectable()
|
||||
export class TemplateWorkspaceService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
@@ -230,65 +235,230 @@ export class TemplateWorkspaceService {
|
||||
const templateKey = await this.getEffectiveTemplateKey(brandId);
|
||||
const template = getBrandTemplate(templateKey);
|
||||
if (!template) throw new BadRequestException("当前行业模板不存在");
|
||||
const [installation, fields] = await Promise.all([
|
||||
const [installation, brand] = await Promise.all([
|
||||
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
|
||||
this.prisma.brandFieldDefinition.findMany({ where: { brandId } }),
|
||||
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
|
||||
]);
|
||||
// 品牌一直有行业模板,但版本台账可能还没建立;此时以模板目录的版本为准,不报错。
|
||||
const currentVersion = installation?.templateVersion ?? template.version;
|
||||
const config = record(brand?.config);
|
||||
const visualTemplateKey =
|
||||
installation?.visualTemplateKey ??
|
||||
(typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : undefined) ??
|
||||
getDefaultVisualTemplateKey(templateKey);
|
||||
const currentPackage = installation?.templatePackageVersionId
|
||||
? await this.prisma.templatePackageVersion.findUnique({
|
||||
where: { id: installation.templatePackageVersionId },
|
||||
})
|
||||
: null;
|
||||
const targetPackage = visualTemplateKey
|
||||
? await this.prisma.templatePackageVersion.findFirst({
|
||||
where: { packageKey: visualTemplateKey, status: "published" },
|
||||
orderBy: { importedAt: "desc" },
|
||||
})
|
||||
: null;
|
||||
const targetManifest = record(targetPackage?.manifestSnapshot);
|
||||
const currentManifest = record(currentPackage?.manifestSnapshot);
|
||||
const currentDeclarations = manifestRecords(currentManifest.templateFields);
|
||||
const targetDeclarations = manifestRecords(targetManifest.templateFields);
|
||||
const currentByKey = new Map(currentDeclarations.map((item) => [String(item.key), item]));
|
||||
const targetByKey = new Map(targetDeclarations.map((item) => [String(item.key), item]));
|
||||
const addedBindings = targetDeclarations.filter((item) => !currentByKey.has(String(item.key)));
|
||||
const removedBindings = currentDeclarations.filter(
|
||||
(item) => !targetByKey.has(String(item.key)),
|
||||
);
|
||||
const changedBindings = targetDeclarations.flatMap((item) => {
|
||||
const current = currentByKey.get(String(item.key));
|
||||
if (!current || JSON.stringify(current) === JSON.stringify(item)) return [];
|
||||
return [{ key: String(item.key), current, proposed: item }];
|
||||
});
|
||||
const conflicts = [
|
||||
...addedBindings.flatMap((item) =>
|
||||
hasBindingValue(config, item.binding)
|
||||
? [
|
||||
{
|
||||
key: String(item.key),
|
||||
binding: String(item.binding),
|
||||
reason: "新增字段已有同路径品牌值,升级会原样保留",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
),
|
||||
...changedBindings.flatMap(({ key, current }) =>
|
||||
hasBindingValue(config, current.binding)
|
||||
? [{ key, binding: String(current.binding), reason: "该品牌配置已填写,升级不会覆盖" }]
|
||||
: [],
|
||||
),
|
||||
...removedBindings.flatMap((item) =>
|
||||
hasBindingValue(config, item.binding)
|
||||
? [
|
||||
{
|
||||
key: String(item.key),
|
||||
binding: String(item.binding),
|
||||
reason: "新版不再声明该字段,已有品牌值仍会保留",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
),
|
||||
];
|
||||
const currentEntrypoints = record(currentManifest.entrypoints);
|
||||
const targetEntrypoints = record(targetManifest.entrypoints);
|
||||
const currentAssets = manifestRecords(currentManifest.assetSlots);
|
||||
const targetAssets = manifestRecords(targetManifest.assetSlots);
|
||||
const [currentFiles, targetFiles] = await Promise.all([
|
||||
currentPackage ? readPackageFiles(currentPackage) : Promise.resolve([]),
|
||||
targetPackage ? readPackageFiles(targetPackage) : Promise.resolve([]),
|
||||
]);
|
||||
const currentCapabilities = stringList(currentManifest.requiredCapabilities);
|
||||
const targetCapabilities = stringList(targetManifest.requiredCapabilities);
|
||||
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
|
||||
return {
|
||||
templateKey,
|
||||
currentVersion,
|
||||
latestVersion: template.version,
|
||||
canUpgrade: currentVersion !== template.version,
|
||||
latestVersion: targetPackage?.version ?? template.version,
|
||||
currentPackageVersionId: currentPackage?.id ?? null,
|
||||
currentContentChecksum:
|
||||
currentPackage?.contentChecksum ?? installation?.contentChecksum ?? null,
|
||||
targetPackageVersionId: targetPackage?.id ?? null,
|
||||
targetContentChecksum: targetPackage?.contentChecksum ?? null,
|
||||
canUpgrade: Boolean(targetPackage && targetPackage.id !== currentPackage?.id),
|
||||
canRollback:
|
||||
Array.isArray(installation?.previousSnapshots) && installation.previousSnapshots.length > 0,
|
||||
missingFields: template.fields.filter(
|
||||
(item) =>
|
||||
!fields.some((current) => current.scope === item.scope && current.key === item.key),
|
||||
),
|
||||
changes: {
|
||||
brandFields: { available: false, reason: "行业字段不由视觉模板包声明" },
|
||||
templateBindings: {
|
||||
added: addedBindings,
|
||||
changed: changedBindings,
|
||||
removed: removedBindings,
|
||||
},
|
||||
pages: compareRecords(currentEntrypoints, targetEntrypoints),
|
||||
modules: {
|
||||
available: Boolean(visualManifest),
|
||||
source: "platform_visual_manifest",
|
||||
packageUpgradeChangesRenderer: false,
|
||||
pages:
|
||||
visualManifest?.pages.map((page) => ({
|
||||
key: page.key,
|
||||
renderer: page.renderer ?? null,
|
||||
modules: page.modules,
|
||||
})) ?? [],
|
||||
},
|
||||
assets: {
|
||||
slots: compareKeyedRecords(currentAssets, targetAssets),
|
||||
files: compareFiles(currentFiles, targetFiles),
|
||||
},
|
||||
capabilities: {
|
||||
added: targetCapabilities.filter((item) => !currentCapabilities.includes(item)),
|
||||
removed: currentCapabilities.filter((item) => !targetCapabilities.includes(item)),
|
||||
},
|
||||
renderer: {
|
||||
available: Boolean(visualManifest),
|
||||
source: "platform_visual_manifest",
|
||||
packageUpgradeChangesRenderer: false,
|
||||
pages:
|
||||
visualManifest?.pages.map((page) => ({
|
||||
key: page.key,
|
||||
renderer: page.renderer ?? null,
|
||||
})) ?? [],
|
||||
},
|
||||
package: {
|
||||
currentContentChecksum: currentPackage?.contentChecksum ?? null,
|
||||
targetContentChecksum: targetPackage?.contentChecksum ?? null,
|
||||
runtimeContract: {
|
||||
current: currentManifest.runtimeContract ?? null,
|
||||
target: targetManifest.runtimeContract ?? null,
|
||||
},
|
||||
},
|
||||
},
|
||||
conflicts,
|
||||
};
|
||||
}
|
||||
async upgrade(brandId: string) {
|
||||
async upgrade(brandId: string, body: UpgradeTemplateDto, actorId: string, requestId?: string) {
|
||||
if (!body.confirm) throw new BadRequestException("升级模板必须显式确认");
|
||||
const installation = await this.installation(brandId);
|
||||
const template = getBrandTemplate(installation.templateKey);
|
||||
if (!template) throw new BadRequestException("已安装模板不存在");
|
||||
if (installation.templateVersion === template.version)
|
||||
throw new BadRequestException("当前模板已经是最新版本");
|
||||
const target = await this.prisma.templatePackageVersion.findUnique({
|
||||
where: { id: body.templatePackageVersionId },
|
||||
});
|
||||
if (!target || target.status !== "published")
|
||||
throw new BadRequestException("目标模板包版本不存在或未发布");
|
||||
if (target.contentChecksum !== body.expectedContentChecksum)
|
||||
throw new ConflictException("目标模板包内容已变化,请重新预览升级差异");
|
||||
if (installation.templateVersion !== body.expectedCurrentVersion)
|
||||
throw new ConflictException("品牌模板版本已变化,请重新预览升级差异");
|
||||
if (
|
||||
(body.expectedCurrentPackageVersionId ?? null) !==
|
||||
(installation.templatePackageVersionId ?? null)
|
||||
)
|
||||
throw new ConflictException("当前模板包版本已变化,请重新预览升级差异");
|
||||
const preview = await this.preview(brandId);
|
||||
const expectedConflicts = preview.conflicts
|
||||
.map(({ key, binding }) => `${key}\u0000${binding}`)
|
||||
.sort();
|
||||
const preserved = body.preservedBindings
|
||||
.map(({ key, binding, action }) => {
|
||||
if (action !== "preserve") throw new BadRequestException("当前只允许保留已有品牌配置");
|
||||
return `${key}\u0000${binding}`;
|
||||
})
|
||||
.sort();
|
||||
if (JSON.stringify(expectedConflicts) !== JSON.stringify(preserved))
|
||||
throw new ConflictException("冲突处理与当前预览不一致,请重新预览并逐项确认");
|
||||
const manifest = record(target.manifestSnapshot);
|
||||
if (
|
||||
target.packageKey !== installation.visualTemplateKey ||
|
||||
manifest.packageKey !== target.packageKey ||
|
||||
manifest.version !== target.version ||
|
||||
!Array.isArray(manifest.supportedIndustryTemplates) ||
|
||||
!manifest.supportedIndustryTemplates.includes(installation.templateKey)
|
||||
)
|
||||
throw new BadRequestException("目标模板包与当前品牌安装不兼容");
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const fields = await tx.brandFieldDefinition.findMany({ where: { brandId } });
|
||||
const addedFields = template.fields.filter(
|
||||
(item) =>
|
||||
!fields.some((current) => current.scope === item.scope && current.key === item.key),
|
||||
);
|
||||
await tx.brandFieldDefinition.createMany({
|
||||
data: addedFields.map(({ scope, key, label, type, required }, index) => ({
|
||||
brandId,
|
||||
scope,
|
||||
key,
|
||||
label,
|
||||
type,
|
||||
required,
|
||||
sortOrder: fields.length + index,
|
||||
source: "template",
|
||||
})),
|
||||
});
|
||||
const history = Array.isArray(installation.previousSnapshots)
|
||||
? installation.previousSnapshots
|
||||
: [];
|
||||
const updated = await tx.brandTemplateInstallation.update({
|
||||
where: { id: installation.id },
|
||||
const claimed = await tx.brandTemplateInstallation.updateMany({
|
||||
where: {
|
||||
id: installation.id,
|
||||
templateVersion: body.expectedCurrentVersion,
|
||||
templatePackageVersionId: installation.templatePackageVersionId,
|
||||
},
|
||||
data: {
|
||||
templateVersion: template.version,
|
||||
configSnapshot: template as unknown as Prisma.InputJsonValue,
|
||||
templatePackageVersionId: target.id,
|
||||
contentChecksum: target.contentChecksum,
|
||||
templateVersion: target.version,
|
||||
configSnapshot: manifest as Prisma.InputJsonValue,
|
||||
previousSnapshots: [...history, installation.configSnapshot],
|
||||
},
|
||||
});
|
||||
return { installation: updated, addedFields };
|
||||
if (claimed.count !== 1)
|
||||
throw new ConflictException("品牌模板版本已变化,请重新预览升级差异");
|
||||
const updated = await tx.brandTemplateInstallation.findUniqueOrThrow({
|
||||
where: { id: installation.id },
|
||||
});
|
||||
await tx.templatePackageAuditLog.create({
|
||||
data: {
|
||||
templatePackageVersionId: target.id,
|
||||
actorId,
|
||||
action: "brand_upgrade",
|
||||
...(requestId ? { requestId } : {}),
|
||||
metadata: {
|
||||
brandId,
|
||||
fromVersionId: installation.templatePackageVersionId,
|
||||
fromVersion: installation.templateVersion,
|
||||
toVersionId: target.id,
|
||||
toVersion: target.version,
|
||||
contentChecksum: target.contentChecksum,
|
||||
preservedBindings: body.preservedBindings.map(({ key, binding }) => ({ key, binding })),
|
||||
},
|
||||
},
|
||||
});
|
||||
return { installation: updated, preservedBindings: body.preservedBindings };
|
||||
});
|
||||
}
|
||||
async rollback(brandId: string) {
|
||||
async rollback(brandId: string, actorId: string, body: RollbackTemplateDto, requestId?: string) {
|
||||
if (!body.confirm) throw new BadRequestException("回滚模板必须显式确认");
|
||||
const installation = await this.installation(brandId);
|
||||
if (installation.templateVersion !== body.expectedCurrentVersion)
|
||||
throw new ConflictException("品牌模板版本已变化,请刷新后重试回滚");
|
||||
const history = Array.isArray(installation.previousSnapshots)
|
||||
? installation.previousSnapshots
|
||||
: [];
|
||||
@@ -297,13 +467,55 @@ export class TemplateWorkspaceService {
|
||||
throw new BadRequestException("没有可回滚的模板版本");
|
||||
const version = (previous as { version?: unknown }).version;
|
||||
if (typeof version !== "string") throw new BadRequestException("模板快照无效");
|
||||
const updated = await this.prisma.brandTemplateInstallation.update({
|
||||
where: { id: installation.id },
|
||||
data: {
|
||||
templateVersion: version,
|
||||
configSnapshot: previous,
|
||||
previousSnapshots: history.slice(0, -1),
|
||||
},
|
||||
const previousManifest = record(previous);
|
||||
const previousPackage =
|
||||
typeof previousManifest.packageKey === "string"
|
||||
? await this.prisma.templatePackageVersion.findFirst({
|
||||
where: { packageKey: previousManifest.packageKey, version },
|
||||
})
|
||||
: null;
|
||||
if (
|
||||
previousPackage &&
|
||||
(previousPackage.packageKey !== installation.visualTemplateKey ||
|
||||
!stringList(record(previousPackage.manifestSnapshot).supportedIndustryTemplates).includes(
|
||||
installation.templateKey,
|
||||
))
|
||||
)
|
||||
throw new BadRequestException("上一版模板包与当前品牌行业或视觉模板不兼容");
|
||||
const updated = await this.prisma.$transaction(async (tx) => {
|
||||
const changed = await tx.brandTemplateInstallation.updateMany({
|
||||
where: {
|
||||
id: installation.id,
|
||||
templateVersion: installation.templateVersion,
|
||||
templatePackageVersionId: installation.templatePackageVersionId,
|
||||
},
|
||||
data: {
|
||||
templateVersion: version,
|
||||
templatePackageVersionId: previousPackage?.id ?? null,
|
||||
contentChecksum: previousPackage?.contentChecksum ?? null,
|
||||
configSnapshot: previous,
|
||||
previousSnapshots: history.slice(0, -1),
|
||||
},
|
||||
});
|
||||
if (changed.count !== 1) throw new ConflictException("品牌模板版本已变化,请刷新后重试回滚");
|
||||
if (installation.templatePackageVersionId) {
|
||||
await tx.templatePackageAuditLog.create({
|
||||
data: {
|
||||
templatePackageVersionId: installation.templatePackageVersionId,
|
||||
actorId,
|
||||
action: "brand_rollback",
|
||||
...(requestId ? { requestId } : {}),
|
||||
metadata: {
|
||||
brandId,
|
||||
fromVersionId: installation.templatePackageVersionId,
|
||||
fromVersion: installation.templateVersion,
|
||||
toVersionId: previousPackage?.id ?? null,
|
||||
toVersion: version,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
return tx.brandTemplateInstallation.findUniqueOrThrow({ where: { id: installation.id } });
|
||||
});
|
||||
return {
|
||||
installation: updated,
|
||||
@@ -312,8 +524,131 @@ export class TemplateWorkspaceService {
|
||||
}
|
||||
}
|
||||
|
||||
async function readPackageFiles(
|
||||
version: Pick<
|
||||
TemplatePackageVersion,
|
||||
"artifactPath" | "validationReport" | "packageKey" | "version"
|
||||
>,
|
||||
): Promise<Record<string, unknown>[]> {
|
||||
const stored = manifestRecords(record(version.validationReport).files);
|
||||
if (stored.length) return stored;
|
||||
const root = `${version.packageKey}-${version.version}`;
|
||||
const checksumEntry = `${root}/checksums.json`;
|
||||
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(version.packageKey) || root.includes("/")) return [];
|
||||
try {
|
||||
const { stdout: entries } = await execFileAsync("tar", ["-tzf", version.artifactPath], {
|
||||
maxBuffer: 4 * 1024 * 1024,
|
||||
});
|
||||
if (!entries.split("\n").some((entry) => entry === checksumEntry)) return [];
|
||||
const { stdout } = await execFileAsync("tar", ["-xOzf", version.artifactPath, checksumEntry], {
|
||||
maxBuffer: 4 * 1024 * 1024,
|
||||
});
|
||||
return manifestRecords(record(JSON.parse(stdout)).files);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
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: "版本验证报告未包含完整文件清单" }),
|
||||
};
|
||||
}
|
||||
@@ -145,6 +145,13 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
|
||||
assert.equal(listedBody.items.length, 1);
|
||||
assert.equal(listedBody.items[0].status, "imported");
|
||||
const versionId = listedBody.items[0].id;
|
||||
const importedVersion = await prisma.templatePackageVersion.findUniqueOrThrow({
|
||||
where: { id: versionId },
|
||||
});
|
||||
assert.ok(importedVersion.validationReport.files.length > 0);
|
||||
assert.ok(
|
||||
importedVersion.validationReport.files.every((file) => /^[a-f0-9]{64}$/.test(file.sha256)),
|
||||
);
|
||||
const publishMissing = await request(`/admin/templates/${versionId}/publish`, { method: "POST" });
|
||||
assert.equal(publishMissing.statusCode, 401);
|
||||
const publishCustomer = await request(`/admin/templates/${versionId}/publish`, {
|
||||
@@ -183,6 +190,83 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
|
||||
assert.equal(JSON.parse(invalidRetire.body).changed, false);
|
||||
});
|
||||
|
||||
test("模板失败指标仅平台模板管理员可查,按窗口聚合且不暴露操作内容", async () => {
|
||||
const missing = await request("/admin/template-operations/failures");
|
||||
assert.equal(missing.statusCode, 401);
|
||||
const customer = await request("/admin/template-operations/failures", {
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
});
|
||||
assert.equal(customer.statusCode, 403);
|
||||
|
||||
const ordinaryUser = await prisma.adminUser.create({
|
||||
data: {
|
||||
username: `metrics-viewer-${randomUUID()}`,
|
||||
passwordHash: "unused",
|
||||
displayName: "普通管理员",
|
||||
platformTemplateRole: "none",
|
||||
mustChangePassword: false,
|
||||
},
|
||||
});
|
||||
const headers = {
|
||||
authorization: `Bearer ${signIdentity({ subject: ordinaryUser.id, brandId, role: "admin" })}`,
|
||||
};
|
||||
try {
|
||||
const forbidden = await request("/admin/template-operations/failures", { headers });
|
||||
assert.equal(forbidden.statusCode, 403);
|
||||
} finally {
|
||||
await prisma.adminUser.delete({ where: { id: ordinaryUser.id } });
|
||||
}
|
||||
|
||||
const login = await request("/admin/session/login", {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
assert.equal(login.statusCode, 201);
|
||||
const adminHeaders = { authorization: `Bearer ${JSON.parse(login.body).token}` };
|
||||
const now = Date.now();
|
||||
const recentRequestId = `metrics-${randomUUID()}`;
|
||||
await prisma.templateOperationFailureEvent.createMany({
|
||||
data: [
|
||||
{
|
||||
action: "preview",
|
||||
resultCode: "HTTP_409",
|
||||
requestId: recentRequestId,
|
||||
actorId: "metrics-test-actor",
|
||||
brandId,
|
||||
packageKey: "metrics-test-package",
|
||||
version: "1.0.0",
|
||||
createdAt: new Date(now - 1000),
|
||||
},
|
||||
{
|
||||
action: "preview",
|
||||
resultCode: "HTTP_400",
|
||||
createdAt: new Date(now - 2 * 24 * 60 * 60 * 1000),
|
||||
},
|
||||
{
|
||||
action: "import",
|
||||
resultCode: "HTTP_400",
|
||||
createdAt: new Date(now - 200 * 24 * 60 * 60 * 1000),
|
||||
},
|
||||
],
|
||||
});
|
||||
const invalidWindow = await request("/admin/template-operations/failures?days=91", {
|
||||
headers: adminHeaders,
|
||||
});
|
||||
assert.equal(invalidWindow.statusCode, 400);
|
||||
const response = await request("/admin/template-operations/failures?days=1", {
|
||||
headers: adminHeaders,
|
||||
});
|
||||
assert.equal(response.statusCode, 200, response.body);
|
||||
const report = JSON.parse(response.body);
|
||||
assert.equal(report.days, 1);
|
||||
assert.equal(report.backfilled, false);
|
||||
assert.equal(report.failures.find((item) => item.action === "preview").count, 1);
|
||||
assert.equal(report.failures.find((item) => item.action === "import").count, 0);
|
||||
assert.equal(report.failures.find((item) => item.action === "build").count, 0);
|
||||
assert.equal(JSON.stringify(report).includes(recentRequestId), false);
|
||||
assert.deepEqual(Object.keys(report.failures[0]).sort(), ["action", "count"]);
|
||||
});
|
||||
|
||||
test("平台模板管理员可以按行业预览版本,且预览不写入品牌数据", async () => {
|
||||
const missing = await request("/admin/templates/preview-version/preview?industry=personal");
|
||||
assert.equal(missing.statusCode, 401);
|
||||
@@ -2507,12 +2591,11 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
});
|
||||
assert.equal(customerAccess.statusCode, 403);
|
||||
const currentTemplateKey = (
|
||||
await prisma.brandProfile.findUniqueOrThrow({
|
||||
where: { id: brandId },
|
||||
select: { templateKey: true },
|
||||
})
|
||||
).templateKey;
|
||||
const originalBrand = await prisma.brandProfile.findUniqueOrThrow({
|
||||
where: { id: brandId },
|
||||
select: { templateKey: true, config: true },
|
||||
});
|
||||
const currentTemplateKey = originalBrand.templateKey;
|
||||
const crossTemplate = await request("/admin/workspace/install", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
@@ -2533,6 +2616,12 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
true,
|
||||
);
|
||||
assert.equal(JSON.parse(installed.body).installation.configSnapshot.schemaVersion, "1.0");
|
||||
const installedRecord = JSON.parse(installed.body).installation;
|
||||
const createdVersionIds = [];
|
||||
let historicalReleaseId;
|
||||
let historicalFormId;
|
||||
let historicalSubmissionId;
|
||||
let historicalReleaseSnapshot;
|
||||
try {
|
||||
const previewUnauthorized = await request("/admin/workspace/template/preview");
|
||||
assert.equal(previewUnauthorized.statusCode, 401);
|
||||
@@ -2540,27 +2629,279 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(preview.statusCode, 200);
|
||||
assert.equal(JSON.parse(preview.body).canUpgrade, false);
|
||||
const rollbackUnauthorized = await request("/admin/workspace/template/rollback", {
|
||||
method: "POST",
|
||||
const admin = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
|
||||
const latestExistingRelease = await prisma.brandRelease.findFirst({
|
||||
where: { brandId },
|
||||
orderBy: { version: "desc" },
|
||||
});
|
||||
assert.ok(
|
||||
latestExistingRelease,
|
||||
"integration fixture should have a published release snapshot",
|
||||
);
|
||||
historicalReleaseSnapshot = latestExistingRelease.snapshot;
|
||||
const historicalRelease = await prisma.brandRelease.create({
|
||||
data: {
|
||||
brandId,
|
||||
version: latestExistingRelease.version + 1,
|
||||
snapshot: historicalReleaseSnapshot,
|
||||
actorId: admin.id,
|
||||
note: "Phase 6 历史快照回归",
|
||||
},
|
||||
});
|
||||
historicalReleaseId = historicalRelease.id;
|
||||
const historicalForm = await prisma.inquiryForm.create({
|
||||
data: {
|
||||
brandId,
|
||||
name: "Phase 6 历史咨询表单",
|
||||
fieldsSnapshot: [{ key: "message", label: "留言", type: "text", required: true }],
|
||||
},
|
||||
});
|
||||
historicalFormId = historicalForm.id;
|
||||
const historicalSubmission = await prisma.inquirySubmission.create({
|
||||
data: {
|
||||
brandId,
|
||||
inquiryFormId: historicalForm.id,
|
||||
customerSubject: "phase6-history-customer",
|
||||
formVersion: 1,
|
||||
fieldsSnapshot: historicalForm.fieldsSnapshot,
|
||||
values: { message: "历史咨询内容" },
|
||||
activeFields: ["message"],
|
||||
},
|
||||
});
|
||||
historicalSubmissionId = historicalSubmission.id;
|
||||
const packageKey = installedRecord.visualTemplateKey;
|
||||
const packageVersion = `9.${Date.now()}.0`;
|
||||
const initialPackageVersion = "1.0.0-phase6-test";
|
||||
const templatePackage = await prisma.templatePackage.upsert({
|
||||
where: { packageKey },
|
||||
create: { packageKey },
|
||||
update: {},
|
||||
});
|
||||
const initialPackageVersionRecord = await prisma.templatePackageVersion.create({
|
||||
data: {
|
||||
templatePackageId: templatePackage.id,
|
||||
packageKey,
|
||||
version: initialPackageVersion,
|
||||
displayName: "集成测试基线包",
|
||||
visualTemplateKey: packageKey,
|
||||
status: "published",
|
||||
manifestSnapshot: {
|
||||
packageKey,
|
||||
version: initialPackageVersion,
|
||||
supportedIndustryTemplates: [currentTemplateKey],
|
||||
requiredCapabilities: ["offerings"],
|
||||
templateFields: [{ key: "founder", binding: "brand.config.founder", label: "主理人" }],
|
||||
entrypoints: { home: "pages/index/index" },
|
||||
assetSlots: [{ key: "brand.logo", binding: "brand.avatarUrl" }],
|
||||
},
|
||||
validationReport: {},
|
||||
contentChecksum: `checksum-${initialPackageVersion}`,
|
||||
archiveChecksum: `archive-${initialPackageVersion}`,
|
||||
artifactPath: "/tmp/template-upgrade-initial-test",
|
||||
importedById: admin.id,
|
||||
},
|
||||
});
|
||||
createdVersionIds.push(initialPackageVersionRecord.id);
|
||||
const originalConfig =
|
||||
originalBrand.config && typeof originalBrand.config === "object" ? originalBrand.config : {};
|
||||
const existingFounder = "升级前的品牌主理人";
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: { config: { ...originalConfig, founder: existingFounder } },
|
||||
});
|
||||
assert.equal(rollbackUnauthorized.statusCode, 401);
|
||||
const installedRecord = JSON.parse(installed.body).installation;
|
||||
await prisma.brandTemplateInstallation.update({
|
||||
where: { id: installedRecord.id },
|
||||
data: {
|
||||
templateVersion: "2.0.0",
|
||||
previousSnapshots: [installedRecord.configSnapshot],
|
||||
templateVersion: initialPackageVersion,
|
||||
templatePackageVersionId: initialPackageVersionRecord.id,
|
||||
contentChecksum: initialPackageVersionRecord.contentChecksum,
|
||||
configSnapshot: initialPackageVersionRecord.manifestSnapshot,
|
||||
},
|
||||
});
|
||||
const packageVersionRecord = await prisma.templatePackageVersion.create({
|
||||
data: {
|
||||
templatePackageId: templatePackage.id,
|
||||
packageKey,
|
||||
version: packageVersion,
|
||||
displayName: "集成测试升级包",
|
||||
visualTemplateKey: packageKey,
|
||||
status: "published",
|
||||
manifestSnapshot: {
|
||||
packageKey,
|
||||
version: packageVersion,
|
||||
supportedIndustryTemplates: [currentTemplateKey],
|
||||
requiredCapabilities: [],
|
||||
templateFields: [
|
||||
{ key: "founder", binding: "brand.config.founder", label: "品牌主理人" },
|
||||
],
|
||||
entrypoints: { home: "pages/home/index", profile: "pages/profile/index" },
|
||||
assetSlots: [
|
||||
{ key: "brand.logo", binding: "brand.avatarUrl" },
|
||||
{ key: "home.hero", binding: "brand.config.heroImage" },
|
||||
],
|
||||
},
|
||||
validationReport: {},
|
||||
contentChecksum: `checksum-${packageVersion}`,
|
||||
archiveChecksum: `archive-${packageVersion}`,
|
||||
artifactPath: "/tmp/template-upgrade-test",
|
||||
importedById: admin.id,
|
||||
},
|
||||
});
|
||||
createdVersionIds.push(packageVersionRecord.id);
|
||||
const actionablePreview = await request("/admin/workspace/template/preview", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
const actionable = JSON.parse(actionablePreview.body);
|
||||
assert.equal(actionable.canUpgrade, true);
|
||||
assert.equal(actionable.targetPackageVersionId, packageVersionRecord.id);
|
||||
assert.equal(actionable.changes.brandFields.available, false);
|
||||
assert.equal(actionable.conflicts.length, 1);
|
||||
assert.equal(actionable.conflicts[0].binding, "brand.config.founder");
|
||||
assert.equal(actionable.changes.pages.added.length, 1);
|
||||
assert.equal(actionable.changes.assets.slots.added.length, 1);
|
||||
assert.deepEqual(actionable.changes.capabilities.removed, ["offerings"]);
|
||||
assert.equal(actionable.changes.renderer.available, true);
|
||||
assert.equal(actionable.changes.renderer.packageUpgradeChangesRenderer, false);
|
||||
assert.equal(actionable.changes.assets.files.available, false);
|
||||
const missingConfirm = await request("/admin/workspace/template/upgrade", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: {
|
||||
templatePackageVersionId: packageVersionRecord.id,
|
||||
expectedContentChecksum: packageVersionRecord.contentChecksum,
|
||||
expectedCurrentVersion: actionable.currentVersion,
|
||||
expectedCurrentPackageVersionId: actionable.currentPackageVersionId,
|
||||
confirm: false,
|
||||
preservedBindings: [],
|
||||
},
|
||||
});
|
||||
assert.equal(missingConfirm.statusCode, 400);
|
||||
const unresolvedConflict = await request("/admin/workspace/template/upgrade", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: {
|
||||
templatePackageVersionId: packageVersionRecord.id,
|
||||
expectedContentChecksum: packageVersionRecord.contentChecksum,
|
||||
expectedCurrentVersion: actionable.currentVersion,
|
||||
expectedCurrentPackageVersionId: actionable.currentPackageVersionId,
|
||||
confirm: true,
|
||||
preservedBindings: [],
|
||||
},
|
||||
});
|
||||
assert.equal(unresolvedConflict.statusCode, 409);
|
||||
const upgradePayload = {
|
||||
templatePackageVersionId: packageVersionRecord.id,
|
||||
expectedContentChecksum: packageVersionRecord.contentChecksum,
|
||||
expectedCurrentVersion: actionable.currentVersion,
|
||||
expectedCurrentPackageVersionId: actionable.currentPackageVersionId,
|
||||
confirm: true,
|
||||
preservedBindings: [{ key: "founder", binding: "brand.config.founder", action: "preserve" }],
|
||||
};
|
||||
const upgradeAttempts = await Promise.all(
|
||||
[0, 1].map(() =>
|
||||
request("/admin/workspace/template/upgrade", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: upgradePayload,
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(upgradeAttempts.map((item) => item.statusCode).sort(), [201, 409]);
|
||||
const upgraded = upgradeAttempts.find((item) => item.statusCode === 201);
|
||||
assert.ok(upgraded);
|
||||
assert.equal(
|
||||
JSON.parse(upgraded.body).installation.templatePackageVersionId,
|
||||
packageVersionRecord.id,
|
||||
);
|
||||
assert.equal(
|
||||
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).config.founder,
|
||||
existingFounder,
|
||||
);
|
||||
const retainedOldPackage = await prisma.templatePackageVersion.findUniqueOrThrow({
|
||||
where: { id: initialPackageVersionRecord.id },
|
||||
});
|
||||
assert.equal(retainedOldPackage.contentChecksum, initialPackageVersionRecord.contentChecksum);
|
||||
const retainedRelease = await prisma.brandRelease.findUniqueOrThrow({
|
||||
where: { id: historicalReleaseId },
|
||||
});
|
||||
assert.deepEqual(retainedRelease.snapshot, historicalReleaseSnapshot);
|
||||
assert.equal(
|
||||
(await prisma.inquirySubmission.findUniqueOrThrow({ where: { id: historicalSubmissionId } }))
|
||||
.values.message,
|
||||
"历史咨询内容",
|
||||
);
|
||||
await prisma.$disconnect();
|
||||
await prisma.$connect();
|
||||
await app.close();
|
||||
app = await createApp();
|
||||
await app.init();
|
||||
const afterApiRestart = await request("/admin/workspace/template/preview", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(afterApiRestart.statusCode, 200);
|
||||
assert.equal(JSON.parse(afterApiRestart.body).currentPackageVersionId, packageVersionRecord.id);
|
||||
const rollbackUnauthorized = await request("/admin/workspace/template/rollback", {
|
||||
method: "POST",
|
||||
payload: { expectedCurrentVersion: packageVersion, confirm: true },
|
||||
});
|
||||
assert.equal(rollbackUnauthorized.statusCode, 401);
|
||||
const upgradeUnauthorized = await request("/admin/workspace/template/upgrade", {
|
||||
method: "POST",
|
||||
payload: {},
|
||||
});
|
||||
assert.equal(upgradeUnauthorized.statusCode, 401);
|
||||
const upgradeForbidden = await request("/admin/workspace/template/upgrade", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
payload: {},
|
||||
});
|
||||
assert.equal(upgradeForbidden.statusCode, 403);
|
||||
const upgradeInvalidDto = await request("/admin/workspace/template/upgrade", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: {},
|
||||
});
|
||||
assert.equal(upgradeInvalidDto.statusCode, 400);
|
||||
const rollbackMissingConfirmation = await request("/admin/workspace/template/rollback", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { expectedCurrentVersion: packageVersion, confirm: false },
|
||||
});
|
||||
assert.equal(rollbackMissingConfirmation.statusCode, 400);
|
||||
const rollbackStaleVersion = await request("/admin/workspace/template/rollback", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { expectedCurrentVersion: actionable.currentVersion, confirm: true },
|
||||
});
|
||||
assert.equal(rollbackStaleVersion.statusCode, 409);
|
||||
const rollback = await request("/admin/workspace/template/rollback", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { expectedCurrentVersion: packageVersion, confirm: true },
|
||||
});
|
||||
assert.equal(rollback.statusCode, 201);
|
||||
assert.equal(JSON.parse(rollback.body).installation.templateVersion, "1.0.0");
|
||||
assert.equal(JSON.parse(rollback.body).installation.templateVersion, initialPackageVersion);
|
||||
assert.equal(
|
||||
JSON.parse(rollback.body).installation.templatePackageVersionId,
|
||||
initialPackageVersionRecord.id,
|
||||
);
|
||||
assert.equal(JSON.parse(rollback.body).installation.previousSnapshots.length, 0);
|
||||
assert.match(JSON.parse(rollback.body).note, /配置基线/);
|
||||
const operationAudit = await prisma.templatePackageAuditLog.findMany({
|
||||
where: {
|
||||
templatePackageVersionId: packageVersionRecord.id,
|
||||
action: { in: ["brand_upgrade", "brand_rollback"] },
|
||||
},
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
assert.deepEqual(
|
||||
operationAudit.map((item) => item.action),
|
||||
["brand_upgrade", "brand_rollback"],
|
||||
);
|
||||
assert.equal(operationAudit[0].metadata.brandId, brandId);
|
||||
assert.equal(operationAudit[0].metadata.contentChecksum, packageVersionRecord.contentChecksum);
|
||||
assert.ok(operationAudit[0].requestId);
|
||||
await prisma.templatePackageVersion.deleteMany({ where: { id: { in: createdVersionIds } } });
|
||||
const workspace = await request("/admin/workspace", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
@@ -2603,8 +2944,18 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
|
||||
});
|
||||
assert.equal(conflict.statusCode, 400);
|
||||
} finally {
|
||||
if (historicalSubmissionId)
|
||||
await prisma.inquirySubmission.deleteMany({ where: { id: historicalSubmissionId } });
|
||||
if (historicalFormId) await prisma.inquiryForm.deleteMany({ where: { id: historicalFormId } });
|
||||
if (historicalReleaseId)
|
||||
await prisma.brandRelease.deleteMany({ where: { id: historicalReleaseId } });
|
||||
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
|
||||
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
|
||||
await prisma.templatePackageVersion.deleteMany({ where: { id: { in: createdVersionIds } } });
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: { templateKey: originalBrand.templateKey, config: originalBrand.config },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
||||
import { cpSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { test } from "node:test";
|
||||
@@ -24,17 +24,23 @@ interface Fixture {
|
||||
|
||||
function createTemplateFixture(packageKey: string): Fixture {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), `template-preview-matrix-${packageKey}-`));
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
[
|
||||
path.resolve(process.cwd(), "../../scripts/template-pack.cjs"),
|
||||
"--template",
|
||||
packageKey,
|
||||
"--out",
|
||||
root,
|
||||
],
|
||||
{ cwd: path.resolve(process.cwd(), "../.."), stdio: "ignore" },
|
||||
);
|
||||
try {
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
[
|
||||
path.resolve(process.cwd(), "../../scripts/template-pack.cjs"),
|
||||
"--template",
|
||||
packageKey,
|
||||
"--out",
|
||||
root,
|
||||
],
|
||||
{ cwd: path.resolve(process.cwd(), "../.."), stdio: "pipe", encoding: "utf8" },
|
||||
);
|
||||
} catch (error) {
|
||||
const details =
|
||||
error instanceof Error && "stderr" in error ? String(error.stderr) : String(error);
|
||||
throw new Error(`Could not package discovered template ${packageKey}: ${details}`);
|
||||
}
|
||||
const filename = readdirSync(root).find((item) => item.endsWith(".tar.gz"));
|
||||
assert.ok(filename);
|
||||
const archivePath = path.join(root, filename);
|
||||
@@ -58,8 +64,42 @@ function createTemplateFixture(packageKey: string): Fixture {
|
||||
};
|
||||
}
|
||||
|
||||
function discoverTemplatePackages(packageRoot: string): string[] {
|
||||
return readdirSync(packageRoot, { withFileTypes: true })
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.isDirectory() &&
|
||||
entry.name.startsWith("template-") &&
|
||||
readdirSync(path.join(packageRoot, entry.name)).includes("template.json"),
|
||||
)
|
||||
.map((entry) => {
|
||||
const manifest = JSON.parse(
|
||||
readFileSync(path.join(packageRoot, entry.name, "template.json"), "utf8"),
|
||||
) as TemplatePackageManifest;
|
||||
return manifest.packageKey;
|
||||
})
|
||||
.sort();
|
||||
}
|
||||
|
||||
test("template preview matrix discovers newly added package manifests", () => {
|
||||
const packageRoot = mkdtempSync(path.join(os.tmpdir(), "template-discovery-matrix-"));
|
||||
const source = path.resolve(process.cwd(), "../../packages/template-atelier-solopreneur");
|
||||
const packageDirectory = path.join(packageRoot, "template-discovery-probe");
|
||||
cpSync(source, packageDirectory, { recursive: true });
|
||||
const manifestPath = path.join(packageDirectory, "template.json");
|
||||
const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as TemplatePackageManifest;
|
||||
writeFileSync(manifestPath, JSON.stringify({ ...manifest, packageKey: "discovery-probe" }));
|
||||
try {
|
||||
assert.deepEqual(discoverTemplatePackages(packageRoot), ["discovery-probe"]);
|
||||
} finally {
|
||||
rmSync(packageRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("template preview matrix keeps every deployed package, industry, and version isolated", async () => {
|
||||
const packageKeys = ["acheng-campus-food", "atelier-solopreneur", "linjing-editorial"];
|
||||
const packageRoot = path.resolve(process.cwd(), "../../packages");
|
||||
const packageKeys = discoverTemplatePackages(packageRoot);
|
||||
assert.ok(packageKeys.length > 0, "at least one template package must be discovered");
|
||||
const fixtures = packageKeys.map(createTemplateFixture);
|
||||
let sequence = 0;
|
||||
const versionFixture = (fixture: Fixture) => {
|
||||
|
||||
Reference in new issue
Block a user