Files
persionalBrand/apps/api/src/brand-release-api.service.ts
T

399 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
BadRequestException,
ConflictException,
Injectable,
NotFoundException,
} from "@nestjs/common";
import { Prisma } from "@prisma/client";
import {
getBrandTemplate,
getVisualTemplate,
isVisualTemplateCompatible,
validateTemplatePackageManifest,
type TemplatePackageManifest,
} from "@personal-brand/config";
import { isTrustContentComplete } from "@personal-brand/types";
import { PrismaService } from "./prisma.service.js";
import { BrandReleaseService } from "./brand-release.service.js";
import { validateFieldSnapshot } from "@personal-brand/validation";
@Injectable()
export class BrandReleaseApiService {
constructor(
private readonly prisma: PrismaService,
private readonly snapshots: BrandReleaseService,
) {}
async list(brandId: string): Promise<unknown[]> {
return this.prisma.brandRelease.findMany({
where: { brandId },
orderBy: { version: "desc" },
select: {
id: true,
version: true,
status: true,
note: true,
actorId: true,
createdAt: true,
revokedAt: true,
revokedBy: true,
},
});
}
async readiness(
brandId: string,
database: Prisma.TransactionClient = this.prisma,
): Promise<{
ready: boolean;
checks: Array<{
key: string;
label: string;
passed: boolean;
help?: string;
destination?: string;
}>;
}> {
const brand = await database.brandProfile.findUnique({
where: { id: brandId },
select: { name: true, tagline: true, description: true, templateKey: true, config: true },
});
const installation = await database.brandTemplateInstallation.findUnique({
where: { brandId },
});
const packageVersion = installation?.templatePackageVersionId
? await database.templatePackageVersion.findUnique({
where: { id: installation.templatePackageVersionId },
select: {
packageKey: true,
version: true,
status: true,
contentChecksum: true,
manifestSnapshot: true,
},
})
: null;
const template = getBrandTemplate(brand?.templateKey ?? "");
const storedManifest = packageVersion?.manifestSnapshot as TemplatePackageManifest | undefined;
const visualKey = storedManifest?.visualTemplateKey ?? "";
const visual = getVisualTemplate(visualKey);
const packageManifest = storedManifest;
const packageVersionValid = Boolean(
installation?.templatePackageVersionId &&
packageVersion &&
packageVersion.status === "published" &&
/^[a-f0-9]{64}$/.test(packageVersion.contentChecksum) &&
packageVersion.packageKey === (storedManifest?.packageKey ?? "") &&
packageVersion.version === (storedManifest?.version ?? "") &&
packageVersion.packageKey === storedManifest?.packageKey &&
packageVersion.packageKey === storedManifest?.visualTemplateKey &&
storedManifest?.supportedIndustryTemplates.includes(brand?.templateKey ?? "") &&
validateTemplatePackageManifest(storedManifest).length === 0,
);
const config = this.jsonObject(brand?.config);
const [offerings, forms, trustItems] = await Promise.all([
database.offering.findMany({
where: { brandId, isEnabled: true },
select: { id: true, name: true, coverUrl: true, config: true },
}),
database.inquiryForm.findMany({
where: { brandId, isEnabled: true },
select: { offeringId: true, name: true, fieldsSnapshot: true },
}),
database.trustContent.findMany({
where: { brandId, isPublished: true },
select: { type: true, title: true, content: true, config: true },
}),
]);
const validTrustItems = trustItems.filter((item) =>
isTrustContentComplete(
item,
packageManifest?.trustContentTypes?.find((type) => type.type === item.type),
),
);
const offeringIds = new Set(offerings.map((item) => item.id));
const validFields = (form: { fieldsSnapshot: unknown }) =>
Array.isArray(form.fieldsSnapshot) &&
form.fieldsSnapshot.length > 0 &&
validateFieldSnapshot(form.fieldsSnapshot).length === 0;
const usableForms = forms.filter(
(form) => (form.offeringId === null || offeringIds.has(form.offeringId)) && validFields(form),
);
// 挂在某个业务上的表单,一旦该业务被停用就再也进不去,小程序也没有入口。这种情况要在发布清单里说清楚,
// 否则只会显示「可用的咨询表单:待完善」,运营者不知道去哪儿改。
const dormantForms = forms.filter(
(form) => form.offeringId !== null && !offeringIds.has(form.offeringId) && validFields(form),
);
const checks: Array<{
key: string;
label: string;
passed: boolean;
help?: string;
destination?: string;
}> = [
{
key: "brand",
label: "品牌名称",
passed: Boolean(brand?.name.trim()),
destination: "/admin/brand",
},
{
key: "positioning",
label: "品牌定位和介绍",
passed: Boolean(brand?.tagline?.trim() && brand.description?.trim()),
destination: "/admin/brand",
},
{ key: "template", label: "行业模板配置", passed: Boolean(template) },
{
key: "template-package-version",
label: "模板包版本台账",
passed: packageVersionValid,
...(packageVersionValid
? {}
: {
help: "当前安装记录引用的模板包版本不可用、未发布或与 manifest 不一致,请重新安装已发布版本。",
}),
destination: "/admin/publication",
},
{
key: "visual",
label: "视觉模板与行业模板的适配",
passed: Boolean(visual && template && isVisualTemplateCompatible(visual, template.key)),
destination: "/admin/publication",
},
{
key: "offerings",
label: "已启用的业务提供项",
passed: offerings.length > 0,
destination: "/admin/services",
},
{
key: "forms",
label: "可用的咨询表单",
passed: usableForms.length > 0,
...(dormantForms.length === 0
? {}
: {
help: `「${dormantForms.map((form) => form.name).join("」「")}」关联的业务提供项已停用,该表单在小程序里没有入口;请启用对应业务,或把表单改回品牌通用入口。`,
}),
destination: "/admin/workspace",
},
{
key: "trust",
label: "已发布的信任内容",
passed: validTrustItems.length > 0,
destination: "/admin/trust",
},
];
const publishedTrustTypes = new Set(validTrustItems.map((item) => item.type));
for (const type of packageManifest?.trustContentTypes ?? []) {
if (type.required !== true) continue;
checks.push({
key: `trust:${type.type}`,
label: type.label,
passed:
publishedTrustTypes.has(type.type) &&
(type.maxPublishedItems === undefined ||
trustItems.filter((item) => item.type === type.type).length <= type.maxPublishedItems),
help: [
"请完整填写该区块的可编辑字段。",
type.maxPublishedItems === undefined
? undefined
: `此区块最多保留 ${type.maxPublishedItems} 条公开记录。`,
type.help,
]
.filter(Boolean)
.join(" "),
destination: "/admin/trust",
});
}
const brandRecord = { ...this.jsonObject(brand), config };
for (const section of packageManifest?.admin.sections ?? []) {
for (const field of section.fields) {
if (field.required !== true) continue;
const present = this.resolveBinding(field.binding, {
brand: brandRecord,
offerings,
});
checks.push({
key: `content:${section.key}:${field.key}`,
// 检查项只描述「要检查什么」,是否完成由 UI 的状态标签表达,避免出现「已完成 · 请先完善…」这类自相矛盾的文案。
label: `${section.title}:${field.label}`,
passed: present,
help: section.description,
destination:
section.target === "offering"
? "/admin/services"
: section.target === "trust"
? "/admin/trust"
: section.target === "inquiry"
? "/admin/workspace"
: "/admin/brand",
});
}
}
for (const slot of packageManifest?.assetSlots ?? []) {
if (slot.required !== true) continue;
const present =
slot.target === "offering"
? offerings.length > 0 && offerings.every((item) => Boolean(item.coverUrl?.trim()))
: slot.target === "brand"
? this.resolveBinding(slot.binding, { brand: brandRecord, offerings })
: trustItems.length > 0;
checks.push({
key: `asset:${String(slot.key)}`,
label: String(slot.label),
passed: present,
help: String(slot.help),
destination: slot.target === "offering" ? "/admin/services" : "/admin/brand",
});
}
return { ready: checks.every((check) => check.passed), checks };
}
private resolveBinding(
binding: string,
context: {
brand: Record<string, unknown>;
offerings: Array<{ id: string; name: string; coverUrl: string | null; config: unknown }>;
},
): boolean {
const segments = binding.split(".");
let value: unknown;
if (segments[0] === "brand") value = context.brand;
else if (segments[0] === "offering") value = context.offerings[0];
else return false;
for (const segment of segments.slice(1)) {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
value = (value as Record<string, unknown>)[segment];
}
return typeof value === "string" ? value.trim().length > 0 : Boolean(value);
}
async publish(brandId: string, actorId: string, note?: string): Promise<unknown> {
return this.withVersionRetry(() =>
this.prisma.$transaction(
async (tx) => {
await this.validateForPublish(brandId, tx);
const snapshot = await this.snapshots.buildSnapshot(brandId, tx);
const latest = await tx.brandRelease.findFirst({
where: { brandId },
orderBy: { version: "desc" },
select: { version: true },
});
await tx.brandRelease.updateMany({
where: { brandId, status: "published" },
data: { status: "superseded" },
});
return tx.brandRelease.create({
data: {
brandId,
version: (latest?.version ?? 0) + 1,
status: "published",
snapshot: this.snapshots.toPrismaJson(snapshot),
actorId,
...(note === undefined ? {} : { note }),
},
});
},
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
),
);
}
async rollback(
brandId: string,
actorId: string,
version: number,
note?: string,
): Promise<unknown> {
return this.withVersionRetry(() =>
this.prisma.$transaction(
async (tx) => {
const source = await tx.brandRelease.findFirst({
where: { brandId, version, status: { in: ["published", "superseded"] } },
});
if (!source) throw new NotFoundException("发布版本不存在");
const snapshot = this.withCurrentTimestamp(source.snapshot);
const latest = await tx.brandRelease.findFirst({
where: { brandId },
orderBy: { version: "desc" },
select: { version: true },
});
await tx.brandRelease.updateMany({
where: { brandId, status: "published" },
data: { status: "superseded" },
});
return tx.brandRelease.create({
data: {
brandId,
version: (latest?.version ?? 0) + 1,
status: "published",
snapshot,
actorId,
note: note ?? `回滚自版本 ${version}`,
},
});
},
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
),
);
}
async revoke(brandId: string, actorId: string): Promise<unknown> {
return this.withVersionRetry(() =>
this.prisma.$transaction(
async (tx) => {
const current = await tx.brandRelease.findFirst({
where: { brandId, status: "published" },
orderBy: { version: "desc" },
});
if (!current) throw new NotFoundException("当前没有已发布版本");
return tx.brandRelease.update({
where: { id: current.id },
data: { status: "revoked", revokedAt: new Date(), revokedBy: actorId },
select: { id: true, version: true, status: true, revokedAt: true, revokedBy: true },
});
},
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
),
);
}
private async validateForPublish(
brandId: string,
database: Prisma.TransactionClient,
): Promise<void> {
const readiness = await this.readiness(brandId, database);
const missing = readiness.checks.find((check) => !check.passed);
if (missing) throw new BadRequestException(missing.label);
}
private async withVersionRetry<T>(operation: () => Promise<T>): Promise<T> {
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return await operation();
} catch (error) {
if (
!(error instanceof Prisma.PrismaClientKnownRequestError) ||
!["P2002", "P2034"].includes(error.code)
)
throw error;
if (attempt === 2) throw new ConflictException("发布版本冲突,请重试");
}
}
throw new ConflictException("发布版本冲突,请重试");
}
private jsonObject(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
private withCurrentTimestamp(value: Prisma.JsonValue): Prisma.InputJsonValue {
const snapshot = this.jsonObject(value);
return { ...snapshot, generatedAt: new Date().toISOString() };
}
}