feat: 收口多品牌与模板构建基础
This commit is contained in:
1 parent
0425a1c672
commit
77224ea51f
317 files changed
+11290
-1158
No files matched your search
@@ -0,0 +1,225 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import {
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
isVisualTemplateCompatible,
|
||||
getDefaultVisualTemplateKey,
|
||||
} from "@personal-brand/config";
|
||||
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 }>;
|
||||
}> {
|
||||
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.findFirst({
|
||||
where: { brandId },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
});
|
||||
const template = getBrandTemplate(installation?.templateKey ?? brand?.templateKey ?? "");
|
||||
const config = this.jsonObject(brand?.config);
|
||||
const visualKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? "personal");
|
||||
const visual = getVisualTemplate(visualKey);
|
||||
const [offerings, forms, trust] = await Promise.all([
|
||||
database.offering.findMany({ where: { brandId, isEnabled: true }, select: { id: true } }),
|
||||
database.inquiryForm.findMany({
|
||||
where: { brandId, isEnabled: true },
|
||||
select: { offeringId: true, fieldsSnapshot: true },
|
||||
}),
|
||||
database.trustContent.count({ where: { brandId, isPublished: true } }),
|
||||
]);
|
||||
const offeringIds = new Set(offerings.map((item) => item.id));
|
||||
const usableForms = forms.filter(
|
||||
(form) =>
|
||||
(form.offeringId === null || offeringIds.has(form.offeringId)) &&
|
||||
Array.isArray(form.fieldsSnapshot) &&
|
||||
form.fieldsSnapshot.length > 0 &&
|
||||
validateFieldSnapshot(form.fieldsSnapshot).length === 0,
|
||||
);
|
||||
const checks = [
|
||||
{ key: "brand", label: "请先完善品牌名称", passed: Boolean(brand?.name.trim()) },
|
||||
{
|
||||
key: "positioning",
|
||||
label: "请先完善品牌定位和介绍",
|
||||
passed: Boolean(brand?.tagline?.trim() && brand.description?.trim()),
|
||||
},
|
||||
{ key: "template", label: "当前行业模板不存在", passed: Boolean(template) },
|
||||
{
|
||||
key: "visual",
|
||||
label: "当前视觉模板不适配行业模板",
|
||||
passed: Boolean(visual && template && isVisualTemplateCompatible(visual, template.key)),
|
||||
},
|
||||
{ key: "offerings", label: "至少需要一项已启用的业务提供项", passed: offerings.length > 0 },
|
||||
{ key: "forms", label: "至少需要一个可用的咨询表单", passed: usableForms.length > 0 },
|
||||
{ key: "trust", label: "至少需要一条已发布的信任内容", passed: trust > 0 },
|
||||
];
|
||||
return { ready: checks.every((check) => check.passed), checks };
|
||||
}
|
||||
|
||||
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() };
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user