feat: 收口模板升级与阶段七持续回归
This commit is contained in:
1 parent
ec16fff70e
commit
71c528de34
29 files changed
+1962
-304
No files matched your search
@@ -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: "版本验证报告未包含完整文件清单" }),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user