feat: 收口多品牌与模板构建基础
This commit is contained in:
1 parent
0425a1c672
commit
77224ea51f
317 files changed
+11290
-1158
No files matched your search
@@ -25,4 +25,12 @@ export class AdminAccessService {
|
||||
if (!membership?.isEnabled) throw new ForbiddenException("管理员没有当前品牌权限");
|
||||
return { subject: identity.subject, brandId: identity.brandId, role: membership.role };
|
||||
}
|
||||
|
||||
async requireRole(request: FastifyRequest, allowedRoles: string[]): Promise<boolean> {
|
||||
const access = await this.requireBrand(request);
|
||||
if (!allowedRoles.includes(access.role)) {
|
||||
throw new ForbiddenException("当前账号没有系统设置权限");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,10 @@ import { signIdentity } from "./auth.js";
|
||||
export class AdminAuthService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async login(username: string, password: string): Promise<{ token: string; displayName: string }> {
|
||||
async login(
|
||||
username: string,
|
||||
password: string,
|
||||
): Promise<{ token: string; displayName: string; mustChangePassword: boolean; role: string }> {
|
||||
const user = await this.prisma.adminUser.findUnique({ where: { username } });
|
||||
if (!user || !user.isEnabled || !(await bcrypt.compare(password, user.passwordHash))) {
|
||||
throw new UnauthorizedException("账号或密码错误");
|
||||
@@ -36,6 +39,23 @@ export class AdminAuthService {
|
||||
role: "admin",
|
||||
}),
|
||||
displayName: user.displayName,
|
||||
mustChangePassword: user.mustChangePassword,
|
||||
role: activeMembership.role,
|
||||
};
|
||||
}
|
||||
|
||||
async changePassword(
|
||||
userId: string,
|
||||
currentPassword: string,
|
||||
newPassword: string,
|
||||
): Promise<void> {
|
||||
const user = await this.prisma.adminUser.findUnique({ where: { id: userId } });
|
||||
if (!user || !(await bcrypt.compare(currentPassword, user.passwordHash))) {
|
||||
throw new UnauthorizedException("当前密码不正确");
|
||||
}
|
||||
await this.prisma.adminUser.update({
|
||||
where: { id: userId },
|
||||
data: { passwordHash: await bcrypt.hash(newPassword, 12), mustChangePassword: false },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,14 @@ export class AdminMembershipGuard implements CanActivate {
|
||||
const request = context.switchToHttp().getRequest<FastifyRequest>();
|
||||
if (request.url.startsWith("/admin/session/login")) return Promise.resolve(true);
|
||||
if (!request.url.startsWith("/admin/")) return Promise.resolve(true);
|
||||
if (
|
||||
/^\/admin\/workspace\/(install|capabilities(?:\/|$)|template(?:\/|$)|modules(?:\/|$)|fields(?:\/|$))/.test(
|
||||
request.url,
|
||||
) ||
|
||||
/^\/admin\/config\/visual-template(?:\/|$)/.test(request.url)
|
||||
) {
|
||||
return this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
}
|
||||
return this.access.requireBrand(request).then(() => true);
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,12 @@ import {
|
||||
UpdateInquirySubmissionDto,
|
||||
UpdateCapabilityInstallationDto,
|
||||
} from "./admin.dto.js";
|
||||
import { capabilityPlugins, getBrandTemplate, resolveCapabilities } from "@personal-brand/config";
|
||||
import {
|
||||
capabilityPlugins,
|
||||
getBrandTemplate,
|
||||
getTemplateSampleContent,
|
||||
resolveCapabilities,
|
||||
} from "@personal-brand/config";
|
||||
import { TemplateWorkspaceService } from "./template-workspace.service.js";
|
||||
import { validateFieldSnapshot, validateOfferingConfig } from "@personal-brand/validation";
|
||||
|
||||
@@ -176,15 +181,12 @@ class AdminWorkspaceController {
|
||||
@Get("capabilities")
|
||||
async listCapabilities(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const [brand, installations] = await Promise.all([
|
||||
this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { templateKey: true },
|
||||
}),
|
||||
const [templateKey, installations] = await Promise.all([
|
||||
this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
||||
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
|
||||
]);
|
||||
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
|
||||
const template = getBrandTemplate(brand?.templateKey ?? "personal");
|
||||
const template = getBrandTemplate(templateKey);
|
||||
return (template ? resolveCapabilities(template.capabilities) : []).map((definition) => {
|
||||
const item = installed.get(definition.key);
|
||||
return {
|
||||
@@ -202,15 +204,22 @@ class AdminWorkspaceController {
|
||||
@Get("sample-content/preview")
|
||||
async previewSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
||||
const sample = getTemplateSampleContent(templateKey);
|
||||
if (!sample) throw new BadRequestException("模板示例内容不存在");
|
||||
const [offerings, trustContent, fields] = await Promise.all([
|
||||
this.prisma.offering.count({ where: { brandId } }),
|
||||
this.prisma.trustContent.count({ where: { brandId } }),
|
||||
this.prisma.brandFieldDefinition.count({ where: { brandId, source: "sample" } }),
|
||||
]);
|
||||
return {
|
||||
templateKey: "doors",
|
||||
templateKey: sample.templateKey,
|
||||
alreadyImported: offerings > 0 || trustContent > 0 || fields > 0,
|
||||
counts: { offerings: 4, trustContent: 4, fields: 4 },
|
||||
counts: {
|
||||
offerings: sample.offerings.length,
|
||||
trustContent: sample.trustContent.length,
|
||||
fields: sample.fields.length,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -218,6 +227,9 @@ class AdminWorkspaceController {
|
||||
async importSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const identity = this.requireAdmin(request);
|
||||
const brandId = identity.brandId;
|
||||
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
||||
const sample = getTemplateSampleContent(templateKey);
|
||||
if (!sample) throw new BadRequestException("模板示例内容不存在");
|
||||
const existing = await this.prisma.brandFieldDefinition.count({
|
||||
where: { brandId, source: "sample" },
|
||||
});
|
||||
@@ -227,54 +239,42 @@ class AdminWorkspaceController {
|
||||
if (existing || existingOffering) throw new BadRequestException("示例内容已经导入");
|
||||
const result = await this.prisma.$transaction(async (tx) => {
|
||||
const offerings = await tx.offering.createMany({
|
||||
data: [
|
||||
["序章·入户门", "为别墅入口定制的整樘门系统", "entrance-door"],
|
||||
["庭院·边界门", "连接建筑与庭院的定制门", "garden-door"],
|
||||
["室内·静谧门", "统一室内空间秩序的户内门", "interior-door"],
|
||||
["一对一门系统设计咨询", "从现场到方案的完整设计沟通", "custom"],
|
||||
].map((item, sortOrder) => ({
|
||||
data: sample.offerings.map((item, sortOrder) => ({
|
||||
brandId,
|
||||
kind: sortOrder === 3 ? "service" : "product",
|
||||
name: item[0]!,
|
||||
summary: item[1]!,
|
||||
config: { categoryKey: item[2]! },
|
||||
kind: item.kind,
|
||||
name: item.name,
|
||||
summary: item.summary,
|
||||
config: { categoryKey: item.categoryKey },
|
||||
sortOrder,
|
||||
isEnabled: true,
|
||||
})),
|
||||
});
|
||||
const trust = await tx.trustContent.createMany({
|
||||
data: ["主理人的门作观", "别墅门系统案例", "从测量到交付", "材料与工艺标准"].map(
|
||||
(title, sortOrder) => ({
|
||||
brandId,
|
||||
type: ["profile", "portfolio", "process", "credential"][sortOrder]!,
|
||||
title,
|
||||
content: "示例内容,待品牌主理人完善。",
|
||||
sortOrder,
|
||||
isPublished: false,
|
||||
}),
|
||||
),
|
||||
data: sample.trustContent.map((item, sortOrder) => ({
|
||||
brandId,
|
||||
type: item.type,
|
||||
title: item.title,
|
||||
content: item.content,
|
||||
sortOrder,
|
||||
isPublished: false,
|
||||
})),
|
||||
});
|
||||
const fields = await tx.brandFieldDefinition.createMany({
|
||||
data: [
|
||||
["projectType", "项目类型", "select"],
|
||||
["projectStage", "项目阶段", "select"],
|
||||
["siteDescription", "项目概况", "textarea"],
|
||||
["phone", "联系方式", "phone"],
|
||||
].map((item, sortOrder) => ({
|
||||
data: sample.fields.map((item, sortOrder) => ({
|
||||
brandId,
|
||||
scope: "inquiry",
|
||||
key: item[0]!,
|
||||
label: item[1]!,
|
||||
type: item[2]!,
|
||||
key: item.key,
|
||||
label: item.label,
|
||||
type: item.type,
|
||||
sortOrder,
|
||||
source: "sample",
|
||||
required: item[2] === "phone",
|
||||
required: item.required,
|
||||
})),
|
||||
});
|
||||
await tx.capabilityAuditLog.create({
|
||||
data: {
|
||||
brandId,
|
||||
capabilityKey: "doors",
|
||||
capabilityKey: sample.capabilityKey,
|
||||
actorId: identity.subject,
|
||||
action: "sample_content_imported",
|
||||
toStatus: "enabled",
|
||||
@@ -294,8 +294,9 @@ class AdminWorkspaceController {
|
||||
): Promise<unknown> {
|
||||
const identity = this.requireAdmin(request);
|
||||
const brandId = identity.brandId;
|
||||
const brand = await this.prisma.brandProfile.findUnique({ where: { id: brandId } });
|
||||
const template = getBrandTemplate(brand?.templateKey ?? "personal");
|
||||
const template = getBrandTemplate(
|
||||
await this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
||||
);
|
||||
if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins))
|
||||
throw new BadRequestException("能力未被当前模板声明");
|
||||
const existing = await this.prisma.capabilityInstallation.findUnique({
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
IsObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MinLength,
|
||||
Matches,
|
||||
Max,
|
||||
Min,
|
||||
@@ -26,6 +27,34 @@ export class UpdateBrandDto {
|
||||
@IsOptional() @IsObject() config?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export class UpdateBrandPresentationDto {
|
||||
@IsOptional() @IsObject() identity?: Record<string, unknown>;
|
||||
@IsOptional() @IsObject() home?: Record<string, unknown>;
|
||||
@IsOptional() @IsObject() offerings?: Record<string, unknown>;
|
||||
@IsOptional() @IsObject() detail?: Record<string, unknown>;
|
||||
@IsOptional() @IsObject() profile?: Record<string, unknown>;
|
||||
@IsOptional() @IsObject() inquiry?: Record<string, unknown>;
|
||||
@IsOptional() @IsObject() success?: Record<string, unknown>;
|
||||
@IsOptional() @IsObject() records?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export class UpdateBrandMemberDto {
|
||||
@IsOptional() @IsIn(["owner", "editor"]) role?: "owner" | "editor";
|
||||
@IsOptional() @IsBoolean() isEnabled?: boolean;
|
||||
}
|
||||
|
||||
export class CreateBrandMemberDto {
|
||||
@IsString() username!: string;
|
||||
@IsString() displayName!: string;
|
||||
@IsString() @MinLength(8) password!: string;
|
||||
@IsIn(["owner", "editor"]) role!: "owner" | "editor";
|
||||
}
|
||||
|
||||
export class ChangeAdminPasswordDto {
|
||||
@IsString() currentPassword!: string;
|
||||
@IsString() @MinLength(8) newPassword!: string;
|
||||
}
|
||||
|
||||
export class CreateTrustContentDto {
|
||||
@IsIn(["profile", "experience", "credential", "portfolio", "process", "testimonial"])
|
||||
type!: string;
|
||||
|
||||
@@ -16,6 +16,9 @@ import { CustomerInquirySubmissionController } from "./modules/customer/customer
|
||||
import { TemplateWorkspaceService } from "./template-workspace.service.js";
|
||||
import { AdminAccessService } from "./admin-access.service.js";
|
||||
import { AdminMembershipGuard } from "./admin-membership.guard.js";
|
||||
import { BrandReleaseService } from "./brand-release.service.js";
|
||||
import { BrandReleaseApiService } from "./brand-release-api.service.js";
|
||||
import { AdminReleaseController } from "./modules/admin/admin-release.controller.js";
|
||||
import {
|
||||
CustomerSessionController,
|
||||
AdminSessionController,
|
||||
@@ -54,6 +57,7 @@ export class HealthController {
|
||||
TenantController,
|
||||
AdminBookingController,
|
||||
AdminConfigController,
|
||||
AdminReleaseController,
|
||||
],
|
||||
providers: [
|
||||
PrismaService,
|
||||
@@ -63,6 +67,8 @@ export class HealthController {
|
||||
TemplateWorkspaceService,
|
||||
AdminAccessService,
|
||||
AdminMembershipGuard,
|
||||
BrandReleaseService,
|
||||
BrandReleaseApiService,
|
||||
PublicBrandContextService,
|
||||
],
|
||||
exports: [PrismaService, WechatAuthService],
|
||||
|
||||
@@ -2,6 +2,7 @@ import { BadRequestException, Injectable, NotFoundException } from "@nestjs/comm
|
||||
import { BookingStatus, Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
import { canTransitionWorkflow, workflowRegistry } from "@personal-brand/config";
|
||||
import { BrandReleaseService } from "./brand-release.service.js";
|
||||
|
||||
const BASIC_BOOKING_WORKFLOW = workflowRegistry["booking.basic"];
|
||||
|
||||
@@ -23,9 +24,32 @@ export interface CreateBookingInput {
|
||||
|
||||
@Injectable()
|
||||
export class BookingService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly releases: BrandReleaseService,
|
||||
) {}
|
||||
|
||||
async create(brandId: string, customerUserId: string, input: CreateBookingInput) {
|
||||
const snapshot = await this.releases.getPublishedSnapshot(brandId);
|
||||
if (!snapshot) throw new BadRequestException("品牌尚未发布");
|
||||
const publishedOfferingIds = this.releases.publishedOfferingIds(snapshot);
|
||||
if (
|
||||
(input.offeringId && !publishedOfferingIds.has(input.offeringId)) ||
|
||||
input.items?.some((item) => !publishedOfferingIds.has(item.offeringId))
|
||||
) {
|
||||
throw new BadRequestException("业务提供项不存在或暂不可预订");
|
||||
}
|
||||
const requestedOfferingIds = [
|
||||
...(input.offeringId ? [input.offeringId] : []),
|
||||
...(input.items ?? []).map((item) => item.offeringId),
|
||||
];
|
||||
if (requestedOfferingIds.length) {
|
||||
const enabledCount = await this.prisma.offering.count({
|
||||
where: { id: { in: requestedOfferingIds }, brandId, isEnabled: true },
|
||||
});
|
||||
if (enabledCount !== new Set(requestedOfferingIds).size)
|
||||
throw new BadRequestException("业务提供项不存在或暂不可预订");
|
||||
}
|
||||
if (!input.customerName.trim() || (!input.phone?.trim() && !input.wechatId?.trim())) {
|
||||
throw new BadRequestException("称呼和至少一种联系方式为必填项");
|
||||
}
|
||||
@@ -52,23 +76,22 @@ export class BookingService {
|
||||
) {
|
||||
throw new BadRequestException("私厨需求必须填写日期、人数和地点");
|
||||
}
|
||||
const offerings = input.items?.length
|
||||
? await this.prisma.offering.findMany({
|
||||
where: {
|
||||
id: { in: input.items.map((item) => item.offeringId) },
|
||||
brandId,
|
||||
isEnabled: true,
|
||||
},
|
||||
})
|
||||
: [];
|
||||
const offeringMap = new Map(offerings.map((offering) => [offering.id, offering]));
|
||||
const offeringMap = new Map(
|
||||
snapshot.offerings.flatMap((raw) => {
|
||||
if (!raw || typeof raw !== "object") return [];
|
||||
const item = raw as Record<string, unknown>;
|
||||
return typeof item.id === "string" && item.isEnabled === true
|
||||
? [[item.id, item] as const]
|
||||
: [];
|
||||
}),
|
||||
);
|
||||
const items = (input.items ?? []).map((item) => {
|
||||
const offering = offeringMap.get(item.offeringId);
|
||||
if (!offering || offering.priceAmount === null)
|
||||
if (!offering || typeof offering.priceAmount !== "number")
|
||||
throw new BadRequestException("套餐不存在或暂不可预订");
|
||||
return {
|
||||
offeringId: offering.id,
|
||||
serviceNameSnapshot: offering.name,
|
||||
offeringId: item.offeringId,
|
||||
serviceNameSnapshot: String(offering.name),
|
||||
unitPriceSnapshot: offering.priceAmount,
|
||||
quantity: item.quantity,
|
||||
subtotalSnapshot: offering.priceAmount * item.quantity,
|
||||
|
||||
@@ -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() };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import {
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
getVisualTemplateManifest,
|
||||
getDefaultVisualTemplateKey,
|
||||
} from "@personal-brand/config";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
|
||||
export interface BrandReleaseSnapshot {
|
||||
schemaVersion: "1.0.0";
|
||||
generatedAt: string;
|
||||
templateKey: string;
|
||||
templateDefinition?: ReturnType<typeof getBrandTemplate> | null;
|
||||
visualTemplateDefinition?: ReturnType<typeof getVisualTemplate> | null;
|
||||
visualTemplateManifest?: ReturnType<typeof getVisualTemplateManifest> | null;
|
||||
brand: Record<string, unknown> | null;
|
||||
installation: Record<string, unknown> | null;
|
||||
modules: unknown[];
|
||||
fields: unknown[];
|
||||
offerings: unknown[];
|
||||
forms: unknown[];
|
||||
trustContents: unknown[];
|
||||
capabilities: unknown[];
|
||||
}
|
||||
|
||||
export async function buildBrandReleaseSnapshot(
|
||||
database: Prisma.TransactionClient,
|
||||
brandId: string,
|
||||
): Promise<BrandReleaseSnapshot> {
|
||||
const [brand, installation, modules, fields, offerings, forms, trustContents, capabilities] =
|
||||
await Promise.all([
|
||||
database.brandProfile.findUnique({ where: { id: brandId } }),
|
||||
database.brandTemplateInstallation.findFirst({
|
||||
where: { brandId },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
}),
|
||||
database.brandModule.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
|
||||
database.brandFieldDefinition.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
|
||||
database.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
|
||||
database.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" } }),
|
||||
database.trustContent.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
|
||||
database.capabilityInstallation.findMany({ where: { brandId } }),
|
||||
]);
|
||||
const templateKey = installation?.templateKey ?? brand?.templateKey ?? "personal";
|
||||
const config =
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
: {};
|
||||
const visualKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? "personal");
|
||||
const jsonObject = (value: object): Record<string, unknown> =>
|
||||
JSON.parse(JSON.stringify(value)) as Record<string, unknown>;
|
||||
return {
|
||||
schemaVersion: "1.0.0",
|
||||
generatedAt: new Date().toISOString(),
|
||||
templateKey,
|
||||
templateDefinition: getBrandTemplate(templateKey) ?? null,
|
||||
visualTemplateDefinition: getVisualTemplate(visualKey) ?? null,
|
||||
visualTemplateManifest: getVisualTemplateManifest(visualKey) ?? null,
|
||||
brand: brand ? jsonObject(brand) : null,
|
||||
installation: installation ? jsonObject(installation) : null,
|
||||
modules: modules.map((item) => jsonObject(item)),
|
||||
fields: fields.map((item) => jsonObject(item)),
|
||||
offerings: offerings.map((item) => jsonObject(item)),
|
||||
forms: forms.map((item) => jsonObject(item)),
|
||||
trustContents: trustContents.map((item) => jsonObject(item)),
|
||||
capabilities: capabilities.map((item) => jsonObject(item)),
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class BrandReleaseService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getPublishedSnapshot(brandId: string): Promise<BrandReleaseSnapshot | null> {
|
||||
const release = await this.prisma.brandRelease.findFirst({
|
||||
where: { brandId, status: "published" },
|
||||
orderBy: { version: "desc" },
|
||||
select: { snapshot: true },
|
||||
});
|
||||
return release ? (release.snapshot as unknown as BrandReleaseSnapshot) : null;
|
||||
}
|
||||
|
||||
publishedOfferingIds(snapshot: BrandReleaseSnapshot): Set<string> {
|
||||
return new Set(
|
||||
snapshot.offerings.flatMap((raw) => {
|
||||
const item = this.record(raw);
|
||||
return item.isEnabled === true && typeof item.id === "string" ? [item.id] : [];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
publishedForm(snapshot: BrandReleaseSnapshot, formId: string): Record<string, unknown> | null {
|
||||
const offeringIds = this.publishedOfferingIds(snapshot);
|
||||
return (
|
||||
snapshot.forms
|
||||
.map((raw) => this.record(raw))
|
||||
.find((form) => {
|
||||
return (
|
||||
form.id === formId &&
|
||||
form.isEnabled === true &&
|
||||
(form.offeringId === null ||
|
||||
(typeof form.offeringId === "string" && offeringIds.has(form.offeringId)))
|
||||
);
|
||||
}) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
private record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
async buildSnapshot(
|
||||
brandId: string,
|
||||
database: Prisma.TransactionClient = this.prisma,
|
||||
): Promise<BrandReleaseSnapshot> {
|
||||
return buildBrandReleaseSnapshot(database, brandId);
|
||||
}
|
||||
|
||||
toPrismaJson(snapshot: BrandReleaseSnapshot): Prisma.InputJsonValue {
|
||||
return snapshot as unknown as Prisma.InputJsonValue;
|
||||
}
|
||||
}
|
||||
@@ -15,12 +15,29 @@ import { Prisma } from "@prisma/client";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
import { CreateTrustContentDto, UpdateBrandDto, UpdateTrustContentDto } from "../../admin.dto.js";
|
||||
import { getVisualTemplate } from "@personal-brand/config";
|
||||
import {
|
||||
CreateTrustContentDto,
|
||||
UpdateBrandDto,
|
||||
UpdateBrandPresentationDto,
|
||||
UpdateTrustContentDto,
|
||||
} from "../../admin.dto.js";
|
||||
import {
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
isVisualTemplateCompatible,
|
||||
listVisualTemplateKeys,
|
||||
getDefaultVisualTemplateKey,
|
||||
} from "@personal-brand/config";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
|
||||
@Controller("admin/config")
|
||||
export class AdminConfigController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
) {}
|
||||
private brandId(request?: FastifyRequest): string {
|
||||
if (!request) return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
@@ -52,6 +69,9 @@ export class AdminConfigController {
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const { config, ...fields } = body;
|
||||
if (config?.visualTemplateKey !== undefined) {
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
}
|
||||
const current = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: this.brandId(request) },
|
||||
select: { config: true },
|
||||
@@ -62,6 +82,19 @@ export class AdminConfigController {
|
||||
: {};
|
||||
const nextConfig = config ? { ...currentConfig, ...config } : undefined;
|
||||
if (config?.visualTemplateKey && config.visualTemplateKey !== currentConfig.visualTemplateKey) {
|
||||
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(
|
||||
this.brandId(request),
|
||||
);
|
||||
const visualTemplate =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? getVisualTemplate(config.visualTemplateKey)
|
||||
: undefined;
|
||||
if (
|
||||
!visualTemplate ||
|
||||
!getBrandTemplate(templateKey) ||
|
||||
!isVisualTemplateCompatible(visualTemplate, templateKey)
|
||||
)
|
||||
throw new BadRequestException("当前视觉模板不适配该行业模板");
|
||||
const installation = await this.prisma.brandTemplateInstallation.findFirst({
|
||||
where: { brandId: this.brandId(request) },
|
||||
});
|
||||
@@ -75,7 +108,8 @@ export class AdminConfigController {
|
||||
previousSnapshots: [
|
||||
...history,
|
||||
{
|
||||
visualTemplateKey: currentConfig.visualTemplateKey ?? "linjing-editorial",
|
||||
visualTemplateKey:
|
||||
currentConfig.visualTemplateKey ?? getDefaultVisualTemplateKey(templateKey),
|
||||
savedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
@@ -91,6 +125,74 @@ export class AdminConfigController {
|
||||
},
|
||||
});
|
||||
}
|
||||
@Patch("presentation")
|
||||
async updatePresentation(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: UpdateBrandPresentationDto,
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const brandId = this.brandId(request);
|
||||
const brand = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { config: true },
|
||||
});
|
||||
const config =
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
: {};
|
||||
const previous =
|
||||
config.visualPresentation &&
|
||||
typeof config.visualPresentation === "object" &&
|
||||
!Array.isArray(config.visualPresentation)
|
||||
? (config.visualPresentation as Record<string, unknown>)
|
||||
: {};
|
||||
const nextPresentation = { ...previous };
|
||||
const identity = body.identity;
|
||||
const identityFields = ["founder", "title", "slogan", "phone", "wechat", "studioAddress"];
|
||||
const nextIdentity = identity
|
||||
? Object.fromEntries(
|
||||
identityFields
|
||||
.filter((key) => typeof identity[key] === "string")
|
||||
.map((key) => [key, identity[key]]),
|
||||
)
|
||||
: {};
|
||||
for (const section of [
|
||||
"home",
|
||||
"offerings",
|
||||
"detail",
|
||||
"profile",
|
||||
"inquiry",
|
||||
"success",
|
||||
"records",
|
||||
] as const) {
|
||||
const input = body[section];
|
||||
if (!input) continue;
|
||||
const current =
|
||||
previous[section] &&
|
||||
typeof previous[section] === "object" &&
|
||||
!Array.isArray(previous[section])
|
||||
? (previous[section] as Record<string, unknown>)
|
||||
: {};
|
||||
const values = Object.fromEntries(
|
||||
Object.entries(input).filter(([, value]) => typeof value === "string"),
|
||||
);
|
||||
nextPresentation[section] = { ...current, ...values };
|
||||
}
|
||||
const updated = await this.prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: {
|
||||
config: {
|
||||
...config,
|
||||
...nextIdentity,
|
||||
visualPresentation: nextPresentation,
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
select: { config: true },
|
||||
});
|
||||
return {
|
||||
visualPresentation: (updated.config as Record<string, unknown>).visualPresentation,
|
||||
};
|
||||
}
|
||||
@Get("visual-template/history")
|
||||
getVisualTemplateHistory(@Req() request: FastifyRequest): unknown {
|
||||
this.requireAdmin(request);
|
||||
@@ -169,7 +271,7 @@ export class AdminConfigController {
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: "linjing-editorial";
|
||||
const current = getVisualTemplate(currentKey) ?? getVisualTemplate("linjing-editorial");
|
||||
const current = getVisualTemplate(currentKey);
|
||||
return {
|
||||
current: current
|
||||
? {
|
||||
@@ -180,7 +282,7 @@ export class AdminConfigController {
|
||||
variants: current.variants,
|
||||
}
|
||||
: null,
|
||||
available: ["linjing-editorial", "minimal-neutral"],
|
||||
available: listVisualTemplateKeys(),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Controller, Get, Param, ParseIntPipe, Post, Body, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { BrandReleaseApiService } from "../../brand-release-api.service.js";
|
||||
import { PublishBrandReleaseDto } from "../../release.dto.js";
|
||||
|
||||
@Controller("admin/releases")
|
||||
export class AdminReleaseController {
|
||||
constructor(
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly releases: BrandReleaseApiService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
async list(@Req() request: FastifyRequest): Promise<unknown[]> {
|
||||
const identity = await this.requireBrand(request);
|
||||
return this.releases.list(identity.brandId);
|
||||
}
|
||||
|
||||
@Get("readiness")
|
||||
async readiness(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const identity = await this.requireBrand(request);
|
||||
return this.releases.readiness(identity.brandId);
|
||||
}
|
||||
|
||||
@Post("publish")
|
||||
async publish(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: PublishBrandReleaseDto,
|
||||
): Promise<unknown> {
|
||||
const identity = await this.requireBrand(request);
|
||||
return this.releases.publish(identity.brandId, identity.subject, body.note);
|
||||
}
|
||||
|
||||
@Post(":version/rollback")
|
||||
async rollback(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("version", ParseIntPipe) version: number,
|
||||
@Body() body: PublishBrandReleaseDto,
|
||||
): Promise<unknown> {
|
||||
const identity = await this.requireBrand(request);
|
||||
return this.releases.rollback(identity.brandId, identity.subject, version, body.note);
|
||||
}
|
||||
|
||||
@Post("revoke")
|
||||
async revoke(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const identity = await this.requireBrand(request);
|
||||
return this.releases.revoke(identity.brandId, identity.subject);
|
||||
}
|
||||
|
||||
private requireBrand(request: FastifyRequest): Promise<{ subject: string; brandId: string }> {
|
||||
return this.access.requireBrand(request);
|
||||
}
|
||||
}
|
||||
@@ -15,10 +15,14 @@ import type { FastifyRequest } from "fastify";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
import { CreateInquirySubmissionDto } from "../../booking.dto.js";
|
||||
import { BrandReleaseService } from "../../brand-release.service.js";
|
||||
|
||||
@Controller("customer/inquiry-submissions")
|
||||
export class CustomerInquirySubmissionController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly releases: BrandReleaseService,
|
||||
) {}
|
||||
private present<T extends { customerSubject: string; adminNote?: string | null }>(submission: T) {
|
||||
const {
|
||||
customerSubject: _customerSubject,
|
||||
@@ -84,16 +88,27 @@ export class CustomerInquirySubmissionController {
|
||||
@Body() body: CreateInquirySubmissionDto,
|
||||
): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const snapshot = await this.releases.getPublishedSnapshot(identity.brandId);
|
||||
const publishedForm = snapshot && this.releases.publishedForm(snapshot, body.formId);
|
||||
if (!publishedForm) throw new BadRequestException("咨询表单不存在或品牌尚未发布");
|
||||
const form = await this.prisma.inquiryForm.findFirst({
|
||||
where: {
|
||||
id: body.formId,
|
||||
brandId: identity.brandId,
|
||||
isEnabled: true,
|
||||
OR: [{ offeringId: null }, { offering: { isEnabled: true } }],
|
||||
},
|
||||
});
|
||||
if (!form) throw new BadRequestException("咨询表单不存在");
|
||||
const capabilityKey = form.purpose === "quote-request" ? "quote-request" : "inquiry";
|
||||
const offeringId =
|
||||
typeof publishedForm.offeringId === "string" ? publishedForm.offeringId : null;
|
||||
if (offeringId) {
|
||||
const offering = await this.prisma.offering.findFirst({
|
||||
where: { id: offeringId, brandId: identity.brandId, isEnabled: true },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!offering) throw new BadRequestException("当前业务提供项不可用");
|
||||
}
|
||||
const capabilityKey = publishedForm.purpose === "quote-request" ? "quote-request" : "inquiry";
|
||||
const capability = await this.prisma.capabilityInstallation.findUnique({
|
||||
where: {
|
||||
brandId_capabilityKey: { brandId: identity.brandId, capabilityKey },
|
||||
@@ -101,8 +116,8 @@ export class CustomerInquirySubmissionController {
|
||||
});
|
||||
if (capability && capability.status !== "enabled")
|
||||
throw new BadRequestException("当前咨询能力不可用");
|
||||
const fields = Array.isArray(form.fieldsSnapshot)
|
||||
? (form.fieldsSnapshot as Array<Record<string, unknown>>)
|
||||
const fields = Array.isArray(publishedForm.fieldsSnapshot)
|
||||
? (publishedForm.fieldsSnapshot as Array<Record<string, unknown>>)
|
||||
: [];
|
||||
for (const field of fields) {
|
||||
const key = typeof field.key === "string" ? field.key : "";
|
||||
@@ -126,9 +141,9 @@ export class CustomerInquirySubmissionController {
|
||||
brandId: identity.brandId,
|
||||
customerSubject: identity.subject,
|
||||
inquiryFormId: form.id,
|
||||
offeringId: form.offeringId,
|
||||
formVersion: form.version,
|
||||
fieldsSnapshot: form.fieldsSnapshot as Prisma.InputJsonValue,
|
||||
offeringId,
|
||||
formVersion: Number(publishedForm.version),
|
||||
fieldsSnapshot: publishedForm.fieldsSnapshot as Prisma.InputJsonValue,
|
||||
values: values as Prisma.InputJsonValue,
|
||||
activeFields: Object.fromEntries(Object.keys(values).map((key) => [key, true])),
|
||||
},
|
||||
|
||||
@@ -1,23 +1,19 @@
|
||||
import { BadRequestException, Controller, Get, Param, Query } from "@nestjs/common";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { PublicBrandContextService } from "./public-brand-context.service.js";
|
||||
import { BrandReleaseService } from "../../brand-release.service.js";
|
||||
|
||||
@Controller("public/inquiry-forms")
|
||||
export class PublicInquiryFormController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly releases: BrandReleaseService,
|
||||
private readonly brandContext: PublicBrandContextService,
|
||||
) {}
|
||||
@Get(":id")
|
||||
async get(@Param("id") id: string, @Query("brandSlug") brandSlug?: string): Promise<unknown> {
|
||||
const form = await this.prisma.inquiryForm.findFirst({
|
||||
where: {
|
||||
id,
|
||||
brandId: await this.brandContext.resolveId(brandSlug),
|
||||
isEnabled: true,
|
||||
OR: [{ offeringId: null }, { offering: { isEnabled: true } }],
|
||||
},
|
||||
});
|
||||
const snapshot = await this.releases.getPublishedSnapshot(
|
||||
await this.brandContext.resolveId(brandSlug),
|
||||
);
|
||||
const form = snapshot && this.releases.publishedForm(snapshot, id);
|
||||
if (!form) throw new BadRequestException("咨询表单不存在");
|
||||
return form;
|
||||
}
|
||||
|
||||
@@ -1,51 +1,52 @@
|
||||
import { BadRequestException, Controller, Get, Param, Query } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { PublicBrandContextService } from "./public-brand-context.service.js";
|
||||
import { BrandReleaseService } from "../../brand-release.service.js";
|
||||
|
||||
@Controller("public/offerings")
|
||||
export class PublicOfferingController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly releases: BrandReleaseService,
|
||||
private readonly brandContext: PublicBrandContextService,
|
||||
) {}
|
||||
@Get()
|
||||
async list(@Query("brandSlug") brandSlug?: string): Promise<unknown> {
|
||||
const brandId = await this.brandContext.resolveId(brandSlug);
|
||||
const items = await this.prisma.offering.findMany({
|
||||
where: { brandId, isEnabled: true },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
include: {
|
||||
inquiryForms: {
|
||||
where: { isEnabled: true },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
select: { id: true, name: true, purpose: true, targetType: true, version: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
return items.map((item) => this.present(item));
|
||||
const snapshot = await this.releases.getPublishedSnapshot(brandId);
|
||||
const forms = snapshot?.forms ?? [];
|
||||
return (snapshot?.offerings ?? [])
|
||||
.filter((raw) => this.object(raw).isEnabled === true)
|
||||
.map((raw) => this.object(raw))
|
||||
.sort((a, b) => Number(a.sortOrder ?? 0) - Number(b.sortOrder ?? 0))
|
||||
.map((item) =>
|
||||
this.present({
|
||||
...item,
|
||||
inquiryForms: forms.filter((raw) => {
|
||||
const form = this.object(raw);
|
||||
return form.offeringId === item.id && form.isEnabled === true;
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
@Get(":id")
|
||||
async get(@Param("id") id: string, @Query("brandSlug") brandSlug?: string): Promise<unknown> {
|
||||
const brandId = await this.brandContext.resolveId(brandSlug);
|
||||
const item = await this.prisma.offering.findFirst({
|
||||
where: {
|
||||
id,
|
||||
brandId,
|
||||
isEnabled: true,
|
||||
},
|
||||
include: {
|
||||
inquiryForms: {
|
||||
where: { isEnabled: true },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
select: { id: true, name: true, purpose: true, targetType: true, version: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
const snapshot = await this.releases.getPublishedSnapshot(brandId);
|
||||
const item = (snapshot?.offerings ?? [])
|
||||
.map((raw) => this.object(raw))
|
||||
.find((offering) => offering.id === id && offering.isEnabled === true);
|
||||
if (!item) throw new BadRequestException("业务提供项不存在");
|
||||
return this.present(item);
|
||||
const forms = (snapshot?.forms ?? []).filter((raw) => {
|
||||
const form = this.object(raw);
|
||||
return form.offeringId === id && form.isEnabled === true;
|
||||
});
|
||||
return this.present({ ...item, inquiryForms: forms });
|
||||
}
|
||||
private present(item: { config: Prisma.JsonValue; [key: string]: unknown }): unknown {
|
||||
private object(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
private present(item: { config?: unknown; [key: string]: unknown }): unknown {
|
||||
const config = (item.config ?? {}) as Record<string, unknown>;
|
||||
return {
|
||||
...item,
|
||||
|
||||
@@ -2,12 +2,14 @@ import { Controller, Get, Query } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { PublicBrandContextService } from "./public-brand-context.service.js";
|
||||
import type { BrandReleaseSnapshot } from "../../brand-release.service.js";
|
||||
import {
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
getVisualTemplateManifest,
|
||||
resolveCapabilities,
|
||||
capabilityPlugins,
|
||||
getDefaultVisualTemplateKey,
|
||||
} from "@personal-brand/config";
|
||||
import type {
|
||||
RuntimeInquiryField,
|
||||
@@ -22,60 +24,77 @@ export class PublicWorkspaceController {
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly brandContext: PublicBrandContextService,
|
||||
) {}
|
||||
private readonly cache = new Map<string, { expiresAt: number; value: unknown }>();
|
||||
@Get()
|
||||
async get(@Query("brandSlug") brandSlug?: string): Promise<unknown> {
|
||||
const brandId = await this.brandContext.resolveId(brandSlug);
|
||||
const cached = process.env.NODE_ENV === "test" ? undefined : this.cache.get(brandId);
|
||||
if (cached && cached.expiresAt > Date.now()) return cached.value;
|
||||
const [
|
||||
brand,
|
||||
modules,
|
||||
fields,
|
||||
offerings,
|
||||
inquiryForms,
|
||||
installation,
|
||||
capabilityInstallations,
|
||||
trustContents,
|
||||
] = await Promise.all([
|
||||
this.prisma.brandProfile.findUnique({ where: { id: brandId } }),
|
||||
this.prisma.brandModule.findMany({
|
||||
where: { brandId, isEnabled: true },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
}),
|
||||
this.prisma.brandFieldDefinition.findMany({
|
||||
where: { brandId, isVisible: true },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
}),
|
||||
this.prisma.offering.findMany({
|
||||
where: { brandId, isEnabled: true },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
}),
|
||||
this.prisma.inquiryForm.findMany({
|
||||
where: {
|
||||
brandId,
|
||||
isEnabled: true,
|
||||
OR: [{ offeringId: null }, { offering: { isEnabled: true } }],
|
||||
},
|
||||
orderBy: { updatedAt: "desc" },
|
||||
}),
|
||||
this.prisma.brandTemplateInstallation.findFirst({
|
||||
where: { brandId },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
}),
|
||||
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
|
||||
this.prisma.trustContent.findMany({
|
||||
where: { brandId, isPublished: true },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
}),
|
||||
]);
|
||||
const templateKey = installation?.templateKey ?? brand?.templateKey ?? "personal";
|
||||
const template = getBrandTemplate(templateKey);
|
||||
const runtimeCapabilities = capabilityInstallations.length
|
||||
? capabilityInstallations.map((item) => ({
|
||||
key: item.capabilityKey,
|
||||
version: item.capabilityVersion,
|
||||
status: item.status as "enabled" | "disabled" | "degraded",
|
||||
const release = await this.prisma.brandRelease.findFirst({
|
||||
where: { brandId, status: "published" },
|
||||
orderBy: { version: "desc" },
|
||||
select: { version: true, createdAt: true, snapshot: true },
|
||||
});
|
||||
const releaseSnapshot = this.jsonObject(release?.snapshot) as unknown as BrandReleaseSnapshot;
|
||||
if (!release) {
|
||||
return {
|
||||
contractVersion: "1.0",
|
||||
schemaVersion: "1.0.0",
|
||||
publication: { status: "unpublished", version: null },
|
||||
brand: null,
|
||||
template: null,
|
||||
visualTemplate: null,
|
||||
modules: [],
|
||||
offerings: [],
|
||||
inquiryForms: [],
|
||||
capabilities: [],
|
||||
runtimeCapabilities: [],
|
||||
runtimeModules: [],
|
||||
fields: [],
|
||||
trustContent: [],
|
||||
trustPresentation: {},
|
||||
inquiryForm: null,
|
||||
navigation: { tabs: [] },
|
||||
plugins: [],
|
||||
theme: { colors: {} },
|
||||
};
|
||||
}
|
||||
const brandData = this.jsonObject(releaseSnapshot.brand);
|
||||
const modulesData = this.jsonArray(releaseSnapshot.modules).filter(
|
||||
(item) => this.jsonObject(item).isEnabled === true,
|
||||
) as Array<Record<string, unknown>>;
|
||||
const fieldsData = this.jsonArray(releaseSnapshot.fields).filter(
|
||||
(item) => this.jsonObject(item).isVisible === true,
|
||||
);
|
||||
const offeringsData = this.jsonArray(releaseSnapshot.offerings).filter(
|
||||
(item) => this.jsonObject(item).isEnabled === true,
|
||||
) as Array<Record<string, unknown>>;
|
||||
const enabledOfferingIds = new Set(offeringsData.map((item) => item.id));
|
||||
const formsData = this.jsonArray(releaseSnapshot.forms).filter((item) => {
|
||||
const form = this.jsonObject(item);
|
||||
return (
|
||||
form.isEnabled === true &&
|
||||
(form.offeringId === null || enabledOfferingIds.has(form.offeringId))
|
||||
);
|
||||
});
|
||||
const trustData = this.jsonArray(releaseSnapshot.trustContents).filter(
|
||||
(item) => this.jsonObject(item).isPublished === true,
|
||||
) as Array<Record<string, unknown>>;
|
||||
const installationData = this.jsonObject(releaseSnapshot.installation);
|
||||
const templateKeyFromSnapshot =
|
||||
typeof releaseSnapshot.templateKey === "string" ? releaseSnapshot.templateKey : undefined;
|
||||
const templateKey =
|
||||
templateKeyFromSnapshot ??
|
||||
(typeof installationData.templateKey === "string"
|
||||
? installationData.templateKey
|
||||
: undefined) ??
|
||||
(typeof brandData.templateKey === "string" ? brandData.templateKey : "personal");
|
||||
const template = releaseSnapshot.templateDefinition ?? getBrandTemplate(templateKey);
|
||||
const capabilityData = this.jsonArray(releaseSnapshot.capabilities) as Array<
|
||||
Record<string, unknown>
|
||||
>;
|
||||
const runtimeCapabilities = capabilityData.length
|
||||
? capabilityData.map((item) => ({
|
||||
key: this.string(item.capabilityKey),
|
||||
version: this.string(item.capabilityVersion, "1.0.0"),
|
||||
status: this.capabilityStatus(item.status),
|
||||
config:
|
||||
item.config && typeof item.config === "object" && !Array.isArray(item.config)
|
||||
? (item.config as Record<string, unknown>)
|
||||
@@ -90,43 +109,96 @@ export class PublicWorkspaceController {
|
||||
}))
|
||||
: [];
|
||||
const brandConfig =
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
brandData.config && typeof brandData.config === "object" && !Array.isArray(brandData.config)
|
||||
? (brandData.config as Record<string, unknown>)
|
||||
: {};
|
||||
const visualTemplateKey =
|
||||
typeof brandConfig.visualTemplateKey === "string"
|
||||
? brandConfig.visualTemplateKey
|
||||
: "linjing-editorial";
|
||||
: getDefaultVisualTemplateKey(templateKey);
|
||||
const visualTemplate =
|
||||
getVisualTemplate(visualTemplateKey) ?? getVisualTemplate("linjing-editorial");
|
||||
releaseSnapshot.visualTemplateDefinition ?? getVisualTemplate(visualTemplateKey);
|
||||
const visualTemplateManifest =
|
||||
getVisualTemplateManifest(visualTemplateKey) ??
|
||||
getVisualTemplateManifest("linjing-editorial");
|
||||
releaseSnapshot.visualTemplateManifest ?? getVisualTemplateManifest(visualTemplateKey);
|
||||
const runtimeBrand = {
|
||||
...(brand ?? {}),
|
||||
...brandData,
|
||||
...brandConfig,
|
||||
};
|
||||
const runtimeModules: RuntimeModule[] = modules.map((module) => ({
|
||||
key: module.type,
|
||||
type: this.moduleType(module.type),
|
||||
const runtimeModules: RuntimeModule[] = modulesData.map((item) => ({
|
||||
key: this.string(item.type, "custom"),
|
||||
type: this.moduleType(this.string(item.type, "custom")),
|
||||
version: "1.0.0",
|
||||
propsSchema: `module.${module.type}.v1`,
|
||||
dataSource: module.type,
|
||||
config: this.jsonObject(module.config),
|
||||
propsSchema: `module.${this.string(item.type, "custom")}.v1`,
|
||||
dataSource: this.string(item.type, "custom"),
|
||||
config: this.jsonObject(item.config),
|
||||
source:
|
||||
module.source === "custom" ? "custom" : module.source === "template" ? "template" : "core",
|
||||
item.source === "custom" ? "custom" : item.source === "template" ? "template" : "core",
|
||||
schemaVersion: "1.0",
|
||||
}));
|
||||
const runtimeOfferings: RuntimeOffering[] = offerings.map((item) => {
|
||||
const runtimeOfferings: RuntimeOffering[] = offeringsData.map((raw) => {
|
||||
const item = raw;
|
||||
const config = this.jsonObject(item.config);
|
||||
const sections = Array.isArray(config.sections) ? config.sections : [];
|
||||
const details = this.jsonObject(config.details);
|
||||
const media = Array.isArray(config.media)
|
||||
? config.media.flatMap((entry) => {
|
||||
const value = this.jsonObject(entry);
|
||||
return typeof value.url === "string"
|
||||
? [
|
||||
{
|
||||
url: value.url,
|
||||
alt:
|
||||
typeof value.alt === "string"
|
||||
? value.alt
|
||||
: this.string(item.name, "业务提供项"),
|
||||
type: "image" as const,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
})
|
||||
: [];
|
||||
const materialsList = Array.isArray(details.materialsList)
|
||||
? details.materialsList.flatMap((entry) => {
|
||||
const value = this.jsonObject(entry);
|
||||
return typeof value.name === "string" && typeof value.spec === "string"
|
||||
? [{ name: value.name, spec: value.spec }]
|
||||
: [];
|
||||
})
|
||||
: [];
|
||||
return {
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
summary: item.summary ?? item.description ?? "",
|
||||
enabled: item.isEnabled,
|
||||
id: this.string(item.id),
|
||||
name: this.string(item.name),
|
||||
summary: typeof item.summary === "string" ? item.summary : this.string(item.description),
|
||||
enabled: item.isEnabled !== false,
|
||||
kind: this.offeringKind(this.string(item.kind, "service")),
|
||||
coverUrl: typeof item.coverUrl === "string" ? item.coverUrl : null,
|
||||
priceText: typeof item.priceText === "string" ? item.priceText : null,
|
||||
priceAmount: typeof item.priceAmount === "number" ? item.priceAmount : null,
|
||||
schemaKey: typeof config.schemaKey === "string" ? config.schemaKey : "offering.default",
|
||||
schemaVersion: typeof config.schemaVersion === "string" ? config.schemaVersion : "1.0.0",
|
||||
presentation: {
|
||||
categoryKey: typeof config.categoryKey === "string" ? config.categoryKey : "custom",
|
||||
categoryLabel:
|
||||
typeof config.categoryLabel === "string" ? config.categoryLabel : "业务提供项",
|
||||
heroImage:
|
||||
typeof config.detailHero === "string"
|
||||
? config.detailHero
|
||||
: typeof item.coverUrl === "string"
|
||||
? item.coverUrl
|
||||
: null,
|
||||
keywords: Array.isArray(config.keywords)
|
||||
? config.keywords.filter((keyword): keyword is string => typeof keyword === "string")
|
||||
: [],
|
||||
media,
|
||||
details: {
|
||||
background: typeof details.background === "string" ? details.background : "",
|
||||
designConcept: typeof details.designConcept === "string" ? details.designConcept : "",
|
||||
crafts: Array.isArray(details.crafts)
|
||||
? details.crafts.filter((craft): craft is string => typeof craft === "string")
|
||||
: [],
|
||||
materialsList,
|
||||
},
|
||||
},
|
||||
sections: sections
|
||||
.filter((section): section is Record<string, unknown> =>
|
||||
Boolean(section && typeof section === "object"),
|
||||
@@ -152,11 +224,12 @@ export class PublicWorkspaceController {
|
||||
"checkbox",
|
||||
"textarea",
|
||||
"date",
|
||||
].includes(String(value.type))
|
||||
].includes(this.string(value.type))
|
||||
? (value.type as RuntimeInquiryField["type"])
|
||||
: "text";
|
||||
const options = Array.isArray(value.options)
|
||||
? value.options.flatMap((option) => {
|
||||
if (typeof option === "string") return [{ label: option, value: option }];
|
||||
if (!option || typeof option !== "object") return [];
|
||||
const item = option as Record<string, unknown>;
|
||||
return typeof item.label === "string" && typeof item.value === "string"
|
||||
@@ -174,9 +247,23 @@ export class PublicWorkspaceController {
|
||||
},
|
||||
];
|
||||
});
|
||||
const inquiryForm = inquiryForms[0] ?? null;
|
||||
const inquiryForm = formsData[0] ?? null;
|
||||
const trustPresentation = trustData.reduce<Record<string, unknown>>((result, raw) => {
|
||||
const item = this.jsonObject(raw);
|
||||
const config = this.jsonObject(item.config);
|
||||
for (const [key, value] of Object.entries(config)) {
|
||||
if (!(key in result)) result[key] = value;
|
||||
}
|
||||
if (item.type === "profile" && typeof result.bio !== "string") result.bio = item.content;
|
||||
return result;
|
||||
}, {});
|
||||
const runtimeWorkspace: RuntimeWorkspace = {
|
||||
schemaVersion: "1.0.0",
|
||||
publication: {
|
||||
status: "published",
|
||||
version: release.version,
|
||||
publishedAt: release.createdAt.toISOString(),
|
||||
},
|
||||
brand: runtimeBrand,
|
||||
navigation: {
|
||||
tabs: [
|
||||
@@ -187,15 +274,24 @@ export class PublicWorkspaceController {
|
||||
},
|
||||
modules: runtimeModules,
|
||||
offerings: runtimeOfferings,
|
||||
inquiryForms: inquiryForms.map((form) => ({
|
||||
key: form.id,
|
||||
version: String(form.version),
|
||||
purpose: this.formPurpose(form.purpose),
|
||||
target: form.targetType === "offering" ? "offering" : "brand",
|
||||
...(form.offeringId ? { targetId: form.offeringId } : {}),
|
||||
submissionAction: this.submissionAction(form.submissionAction),
|
||||
fields: toInquiryFields(form.fieldsSnapshot),
|
||||
})),
|
||||
inquiryForms: formsData.map((raw) => {
|
||||
const form = this.jsonObject(raw);
|
||||
return {
|
||||
key: this.string(form.id),
|
||||
version:
|
||||
typeof form.version === "number"
|
||||
? String(form.version)
|
||||
: this.string(form.version, "1"),
|
||||
purpose: this.formPurpose(this.string(form.purpose, "inquiry")),
|
||||
target: form.targetType === "offering" ? "offering" : "brand",
|
||||
...(typeof form.offeringId === "string" ? { targetId: form.offeringId } : {}),
|
||||
submissionAction: this.submissionAction(
|
||||
this.string(form.submissionAction, "create-inquiry"),
|
||||
),
|
||||
fields: toInquiryFields(form.fieldsSnapshot as Prisma.JsonValue),
|
||||
};
|
||||
}),
|
||||
trustPresentation,
|
||||
capabilities: runtimeCapabilities,
|
||||
plugins: runtimeCapabilities
|
||||
.filter((capability) => capability.status === "enabled")
|
||||
@@ -215,7 +311,10 @@ export class PublicWorkspaceController {
|
||||
template: template
|
||||
? {
|
||||
key: template.key,
|
||||
version: installation?.templateVersion ?? template.version,
|
||||
version:
|
||||
typeof installationData.templateVersion === "string"
|
||||
? installationData.templateVersion
|
||||
: template.version,
|
||||
name: template.name,
|
||||
}
|
||||
: null,
|
||||
@@ -224,21 +323,19 @@ export class PublicWorkspaceController {
|
||||
key: visualTemplate.key,
|
||||
version: visualTemplate.version,
|
||||
name: visualTemplate.name,
|
||||
supportedIndustryTemplates: visualTemplate.supportedIndustryTemplates,
|
||||
variants: visualTemplate.variants,
|
||||
}
|
||||
: null,
|
||||
visualTemplateManifest,
|
||||
capabilities: runtimeCapabilities,
|
||||
runtimeCapabilities,
|
||||
modules,
|
||||
runtimeModules,
|
||||
fields,
|
||||
offerings,
|
||||
trustContent: trustContents,
|
||||
fields: fieldsData,
|
||||
trustContent: trustData,
|
||||
trustPresentation,
|
||||
inquiryForm,
|
||||
};
|
||||
if (process.env.NODE_ENV !== "test")
|
||||
this.cache.set(brandId, { expiresAt: Date.now() + 30_000, value: response });
|
||||
return response;
|
||||
}
|
||||
private jsonObject(value: unknown): Record<string, unknown> {
|
||||
@@ -246,10 +343,22 @@ export class PublicWorkspaceController {
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
private string(value: unknown, fallback = ""): string {
|
||||
return typeof value === "string" ? value : fallback;
|
||||
}
|
||||
private capabilityStatus(value: unknown): "enabled" | "disabled" | "degraded" {
|
||||
return value === "disabled" || value === "degraded" ? value : "enabled";
|
||||
}
|
||||
private jsonArray(value: unknown): Prisma.JsonValue[] {
|
||||
return Array.isArray(value) ? (value as Prisma.JsonValue[]) : [];
|
||||
}
|
||||
private moduleType(value: string): RuntimeModule["type"] {
|
||||
const aliases: Record<string, RuntimeModule["type"]> = {
|
||||
identity: "brand-hero",
|
||||
trust: "trust-proof",
|
||||
offering: "offering-list",
|
||||
contact: "founder-card",
|
||||
};
|
||||
const known: RuntimeModule["type"][] = [
|
||||
"brand-hero",
|
||||
"founder-card",
|
||||
@@ -264,8 +373,9 @@ export class PublicWorkspaceController {
|
||||
"records",
|
||||
"custom",
|
||||
];
|
||||
const type = aliases[value] ?? value;
|
||||
return (
|
||||
known.includes(value as RuntimeModule["type"]) ? value : "custom"
|
||||
known.includes(type as RuntimeModule["type"]) ? type : "custom"
|
||||
) as RuntimeModule["type"];
|
||||
}
|
||||
private sectionType(value: unknown): RuntimeOffering["sections"][number]["type"] {
|
||||
@@ -274,6 +384,12 @@ export class PublicWorkspaceController {
|
||||
? (value as (typeof known)[number])
|
||||
: "text";
|
||||
}
|
||||
private offeringKind(value: string): RuntimeOffering["kind"] {
|
||||
const known: RuntimeOffering["kind"][] = ["service", "product", "package", "subscription"];
|
||||
return known.includes(value as RuntimeOffering["kind"])
|
||||
? (value as RuntimeOffering["kind"])
|
||||
: "service";
|
||||
}
|
||||
private formPurpose(value: string): RuntimeWorkspace["inquiryForms"][number]["purpose"] {
|
||||
return value === "booking" || value === "quote-request" ? value : "inquiry";
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { BadRequestException, Controller, Get, Param, Query } from "@nestjs/common";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { PublicBrandContextService } from "./public-brand-context.service.js";
|
||||
import { BrandReleaseService } from "../../brand-release.service.js";
|
||||
import {
|
||||
brandTemplates,
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
isVisualTemplateCompatible,
|
||||
resolveCapabilities,
|
||||
visualTemplates,
|
||||
} from "@personal-brand/config";
|
||||
@@ -12,50 +13,59 @@ import {
|
||||
@Controller("public")
|
||||
export class PublicController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly releases: BrandReleaseService,
|
||||
private readonly brandContext: PublicBrandContextService,
|
||||
) {}
|
||||
|
||||
@Get("brand")
|
||||
async brand(@Query("brandSlug") brandSlug?: string): Promise<unknown> {
|
||||
return this.prisma.brandProfile.findUnique({
|
||||
where: {
|
||||
id: await this.brandContext.resolveId(brandSlug),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
templateKey: true,
|
||||
tagline: true,
|
||||
description: true,
|
||||
avatarUrl: true,
|
||||
coverUrl: true,
|
||||
hours: true,
|
||||
address: true,
|
||||
deliveryNote: true,
|
||||
contactPhone: true,
|
||||
contactWechat: true,
|
||||
},
|
||||
});
|
||||
const snapshot = await this.releases.getPublishedSnapshot(
|
||||
await this.brandContext.resolveId(brandSlug),
|
||||
);
|
||||
if (!snapshot?.brand) return null;
|
||||
const keys = [
|
||||
"id",
|
||||
"name",
|
||||
"templateKey",
|
||||
"tagline",
|
||||
"description",
|
||||
"avatarUrl",
|
||||
"coverUrl",
|
||||
"hours",
|
||||
"address",
|
||||
"deliveryNote",
|
||||
"contactPhone",
|
||||
"contactWechat",
|
||||
];
|
||||
return Object.fromEntries(keys.map((key) => [key, snapshot.brand?.[key] ?? null]));
|
||||
}
|
||||
}
|
||||
|
||||
@Controller("public/trust-content")
|
||||
export class PublicTrustContentController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly releases: BrandReleaseService,
|
||||
private readonly brandContext: PublicBrandContextService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
async list(@Query("brandSlug") brandSlug?: string): Promise<unknown> {
|
||||
return this.prisma.trustContent.findMany({
|
||||
where: {
|
||||
brandId: await this.brandContext.resolveId(brandSlug),
|
||||
isPublished: true,
|
||||
},
|
||||
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
|
||||
});
|
||||
const snapshot = await this.releases.getPublishedSnapshot(
|
||||
await this.brandContext.resolveId(brandSlug),
|
||||
);
|
||||
return (snapshot?.trustContents ?? [])
|
||||
.filter((item) =>
|
||||
Boolean(
|
||||
item &&
|
||||
typeof item === "object" &&
|
||||
(item as Record<string, unknown>).isPublished === true,
|
||||
),
|
||||
)
|
||||
.sort((left, right) => {
|
||||
const a = left as { type: string; sortOrder: number };
|
||||
const b = right as { type: string; sortOrder: number };
|
||||
return a.type.localeCompare(b.type) || a.sortOrder - b.sortOrder;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,7 +73,10 @@ export class PublicTrustContentController {
|
||||
export class PublicTemplateController {
|
||||
@Get()
|
||||
list(): unknown {
|
||||
return { industries: Object.values(brandTemplates), visuals: Object.values(visualTemplates) };
|
||||
return {
|
||||
industries: Object.values(brandTemplates),
|
||||
visuals: Object.values(visualTemplates),
|
||||
};
|
||||
}
|
||||
|
||||
@Get("preview")
|
||||
@@ -72,8 +85,10 @@ export class PublicTemplateController {
|
||||
@Query("visual") visual = "linjing-editorial",
|
||||
): unknown {
|
||||
const industryTemplate = getBrandTemplate(industry);
|
||||
const visualTemplate = getVisualTemplate(visual) ?? getVisualTemplate("linjing-editorial");
|
||||
const visualTemplate = getVisualTemplate(visual);
|
||||
if (!industryTemplate || !visualTemplate) throw new BadRequestException("模板组合不存在");
|
||||
if (!isVisualTemplateCompatible(visualTemplate, industryTemplate.key))
|
||||
throw new BadRequestException("当前视觉模板不适配所选行业模板");
|
||||
return {
|
||||
industry: industryTemplate,
|
||||
visual: visualTemplate,
|
||||
|
||||
@@ -1,22 +1,39 @@
|
||||
import { BadRequestException, Body, Controller, Post } from "@nestjs/common";
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
} from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { WechatAuthService } from "../../wechat-auth.js";
|
||||
import { AdminAuthService } from "../../admin-auth.service.js";
|
||||
import { AdminLoginDto, WechatLoginDto } from "../../admin-auth.dto.js";
|
||||
import { signIdentity } from "../../auth.js";
|
||||
import { PublicBrandContextService } from "../public/public-brand-context.service.js";
|
||||
import { ChangeAdminPasswordDto } from "../../admin.dto.js";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
|
||||
@Controller("customer/session")
|
||||
export class CustomerSessionController {
|
||||
constructor(
|
||||
private readonly wechatAuth: WechatAuthService,
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly brandContext: PublicBrandContextService,
|
||||
) {}
|
||||
|
||||
@Post("wechat")
|
||||
async wechatLogin(@Body() body: WechatLoginDto): Promise<{ token: string }> {
|
||||
async wechatLogin(
|
||||
@Body() body: WechatLoginDto,
|
||||
@Query("brandSlug") brandSlug?: string,
|
||||
): Promise<{ token: string }> {
|
||||
const session = await this.wechatAuth.exchangeCode(body.code);
|
||||
const brandId = await this.brandContext.resolveId(brandSlug);
|
||||
const brand = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001" },
|
||||
where: { id: brandId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!brand) throw new BadRequestException("品牌尚未初始化");
|
||||
@@ -36,7 +53,22 @@ export class AdminSessionController {
|
||||
constructor(private readonly auth: AdminAuthService) {}
|
||||
|
||||
@Post("login")
|
||||
login(@Body() body: AdminLoginDto): Promise<{ token: string; displayName: string }> {
|
||||
login(
|
||||
@Body() body: AdminLoginDto,
|
||||
): Promise<{ token: string; displayName: string; mustChangePassword: boolean; role: string }> {
|
||||
return this.auth.login(body.username, body.password);
|
||||
}
|
||||
|
||||
@Post("change-password")
|
||||
async changePassword(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: ChangeAdminPasswordDto,
|
||||
): Promise<{ changed: true }> {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
const identity = readIdentity(token);
|
||||
if (identity.role !== "admin") throw new UnauthorizedException("管理员登录态无效");
|
||||
await this.auth.changePassword(identity.subject, body.currentPassword, body.newPassword);
|
||||
return { changed: true };
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
import {
|
||||
Controller,
|
||||
BadRequestException,
|
||||
Body,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
@@ -10,10 +14,105 @@ import {
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { readIdentity, signIdentity } from "../../auth.js";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { CreateBrandMemberDto, UpdateBrandMemberDto } from "../../admin.dto.js";
|
||||
import bcrypt from "bcryptjs";
|
||||
|
||||
@Controller("admin/brands")
|
||||
export class TenantController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly access: AdminAccessService,
|
||||
) {}
|
||||
|
||||
@Get("members")
|
||||
async listMembers(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
const current = this.adminIdentity(request);
|
||||
return this.prisma.brandMembership.findMany({
|
||||
where: { brandId: current.brandId },
|
||||
include: {
|
||||
adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } },
|
||||
},
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
}
|
||||
|
||||
@Post("members")
|
||||
async createMember(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: CreateBrandMemberDto,
|
||||
): Promise<unknown> {
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
const actor = this.adminIdentity(request);
|
||||
const username = body.username.trim();
|
||||
const displayName = body.displayName.trim();
|
||||
if (!username || !displayName) throw new BadRequestException("账号和显示名称不能为空");
|
||||
const existing = await this.prisma.adminUser.findUnique({ where: { username } });
|
||||
if (existing) throw new ConflictException("账号已存在,请使用其他账号");
|
||||
const passwordHash = await bcrypt.hash(body.password, 12);
|
||||
const member = await this.prisma.$transaction(async (tx) => {
|
||||
const adminUser = await tx.adminUser.create({
|
||||
data: {
|
||||
username,
|
||||
displayName,
|
||||
passwordHash,
|
||||
role: "admin",
|
||||
isEnabled: true,
|
||||
mustChangePassword: true,
|
||||
},
|
||||
});
|
||||
return tx.brandMembership.create({
|
||||
data: {
|
||||
adminUserId: adminUser.id,
|
||||
brandId: actor.brandId,
|
||||
role: body.role,
|
||||
isEnabled: true,
|
||||
},
|
||||
include: {
|
||||
adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } },
|
||||
},
|
||||
});
|
||||
});
|
||||
return member;
|
||||
}
|
||||
|
||||
@Patch("members/:id")
|
||||
async updateMember(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("id") id: string,
|
||||
@Body() body: UpdateBrandMemberDto,
|
||||
): Promise<unknown> {
|
||||
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
|
||||
const actor = this.adminIdentity(request);
|
||||
const membership = await this.prisma.brandMembership.findFirst({
|
||||
where: { id, brandId: actor.brandId },
|
||||
});
|
||||
if (!membership) throw new BadRequestException("成员不存在");
|
||||
if (membership.adminUserId === actor.subject) {
|
||||
if (body.isEnabled === false || (body.role && body.role !== membership.role)) {
|
||||
throw new BadRequestException("不能修改自己的角色或停用自己");
|
||||
}
|
||||
}
|
||||
const nextRole = body.role ?? membership.role;
|
||||
const nextEnabled = body.isEnabled ?? membership.isEnabled;
|
||||
if (membership.role === "owner" && (nextRole !== "owner" || !nextEnabled)) {
|
||||
const ownerCount = await this.prisma.brandMembership.count({
|
||||
where: { brandId: actor.brandId, role: "owner", isEnabled: true },
|
||||
});
|
||||
if (ownerCount <= 1) throw new BadRequestException("品牌至少需要保留一位启用的负责人");
|
||||
}
|
||||
return this.prisma.brandMembership.update({
|
||||
where: { id: membership.id },
|
||||
data: {
|
||||
...(body.role ? { role: body.role } : {}),
|
||||
...(body.isEnabled === undefined ? {} : { isEnabled: body.isEnabled }),
|
||||
},
|
||||
include: {
|
||||
adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@Get()
|
||||
async list(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { IsOptional, IsString } from "class-validator";
|
||||
|
||||
export class PublishBrandReleaseDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
note?: string;
|
||||
}
|
||||
@@ -1,11 +1,33 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { getBrandTemplate, getVisualTemplateManifest } from "@personal-brand/config";
|
||||
import {
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
getVisualTemplateManifest,
|
||||
getDefaultVisualTemplateKey,
|
||||
isVisualTemplateCompatible,
|
||||
} from "@personal-brand/config";
|
||||
import type { BrandTemplateKey } from "@personal-brand/types";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
|
||||
@Injectable()
|
||||
export class TemplateWorkspaceService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
async getEffectiveTemplateKey(brandId: string): Promise<BrandTemplateKey> {
|
||||
const [installation, brand] = await Promise.all([
|
||||
this.prisma.brandTemplateInstallation.findFirst({
|
||||
where: { brandId },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
select: { templateKey: true },
|
||||
}),
|
||||
this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { templateKey: true },
|
||||
}),
|
||||
]);
|
||||
const key = installation?.templateKey ?? brand?.templateKey ?? "personal";
|
||||
return getBrandTemplate(key) ? (key as BrandTemplateKey) : "personal";
|
||||
}
|
||||
async install(brandId: string, templateKey: "personal" | "food" | "doors") {
|
||||
const template = getBrandTemplate(templateKey);
|
||||
if (!template) throw new BadRequestException("行业模板不存在");
|
||||
@@ -23,14 +45,22 @@ export class TemplateWorkspaceService {
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
: {};
|
||||
const configuredVisualTemplateKey =
|
||||
typeof brandConfig.visualTemplateKey === "string" ? brandConfig.visualTemplateKey : undefined;
|
||||
const visualTemplateKey =
|
||||
typeof brandConfig.visualTemplateKey === "string"
|
||||
? brandConfig.visualTemplateKey
|
||||
: templateKey === "doors"
|
||||
? "linjing-editorial"
|
||||
: "minimal-neutral";
|
||||
configuredVisualTemplateKey &&
|
||||
getVisualTemplate(configuredVisualTemplateKey) &&
|
||||
isVisualTemplateCompatible(getVisualTemplate(configuredVisualTemplateKey)!, templateKey)
|
||||
? configuredVisualTemplateKey
|
||||
: getDefaultVisualTemplateKey(templateKey);
|
||||
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
|
||||
if (!visualManifest) throw new BadRequestException("视觉模板不存在");
|
||||
const visualTemplate = getVisualTemplate(visualTemplateKey);
|
||||
if (
|
||||
!visualManifest ||
|
||||
!visualTemplate ||
|
||||
!isVisualTemplateCompatible(visualTemplate, templateKey)
|
||||
)
|
||||
throw new BadRequestException("当前视觉模板不适配行业模板");
|
||||
const templatePackageSnapshot = {
|
||||
schemaVersion: "1.0",
|
||||
version: template.version,
|
||||
@@ -39,6 +69,14 @@ export class TemplateWorkspaceService {
|
||||
capabilities: template.capabilities,
|
||||
};
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
if (brandConfig.visualTemplateKey === undefined) {
|
||||
await tx.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: {
|
||||
config: { ...brandConfig, visualTemplateKey },
|
||||
},
|
||||
});
|
||||
}
|
||||
const installation = await tx.brandTemplateInstallation.create({
|
||||
data: {
|
||||
brandId,
|
||||
|
||||
Reference in new issue
Block a user