464 lines
16 KiB
TypeScript
464 lines
16 KiB
TypeScript
import {
|
|
BadRequestException,
|
|
Body,
|
|
Controller,
|
|
Delete,
|
|
Get,
|
|
Param,
|
|
Patch,
|
|
Post,
|
|
Req,
|
|
} from "@nestjs/common";
|
|
import { Prisma } from "@prisma/client";
|
|
import type { FastifyRequest } from "fastify";
|
|
import { PrismaService } from "./prisma.service.js";
|
|
import {
|
|
InstallTemplateDto,
|
|
CreateOfferingDto,
|
|
UpdateOfferingDto,
|
|
CreateFieldDefinitionDto,
|
|
UpdateFieldDefinitionDto,
|
|
CreateInquiryFormDto,
|
|
UpdateInquiryFormDto,
|
|
UpdateInquirySubmissionDto,
|
|
UpdateCapabilityInstallationDto,
|
|
} from "./admin.dto.js";
|
|
import {
|
|
capabilityRegistry,
|
|
capabilityMetadata,
|
|
validateCapabilityConfig,
|
|
capabilityPlugins,
|
|
getBrandTemplate,
|
|
getTemplateSampleContent,
|
|
} from "@personal-brand/config";
|
|
import { TemplateWorkspaceService } from "./template-workspace.service.js";
|
|
import { validateFieldSnapshot } from "@personal-brand/validation";
|
|
import { AdminOfferingService } from "./modules/workspace/admin-offering.service.js";
|
|
import { AdminWorkspaceService } from "./modules/workspace/admin-workspace.service.js";
|
|
import { requireAdminIdentity } from "./modules/workspace/admin-access.identity.js";
|
|
|
|
@Controller("admin/workspace")
|
|
class AdminWorkspaceController {
|
|
constructor(
|
|
private readonly prisma: PrismaService,
|
|
private readonly templateWorkspace: TemplateWorkspaceService,
|
|
private readonly offeringService: AdminOfferingService,
|
|
private readonly workspaceService: AdminWorkspaceService,
|
|
) {}
|
|
|
|
@Get("offerings")
|
|
listOfferings(@Req() request: FastifyRequest): Promise<unknown> {
|
|
const brandId = requireAdminIdentity(request).brandId;
|
|
return this.offeringService.list(brandId);
|
|
}
|
|
|
|
@Post("offerings")
|
|
createOffering(
|
|
@Req() request: FastifyRequest,
|
|
@Body() body: CreateOfferingDto,
|
|
): Promise<unknown> {
|
|
const brandId = requireAdminIdentity(request).brandId;
|
|
return this.offeringService.create(brandId, body);
|
|
}
|
|
|
|
@Patch("offerings/:id")
|
|
async updateOffering(
|
|
@Req() request: FastifyRequest,
|
|
@Param("id") id: string,
|
|
@Body() body: UpdateOfferingDto,
|
|
): Promise<unknown> {
|
|
const brandId = requireAdminIdentity(request).brandId;
|
|
return this.offeringService.update(brandId, id, body);
|
|
}
|
|
|
|
@Delete("offerings/:id")
|
|
async deleteOffering(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
|
const brandId = requireAdminIdentity(request).brandId;
|
|
return this.offeringService.delete(brandId, id);
|
|
}
|
|
@Get()
|
|
get(@Req() request: FastifyRequest): Promise<unknown> {
|
|
const brandId = requireAdminIdentity(request).brandId;
|
|
return this.workspaceService.get(brandId);
|
|
}
|
|
@Get("preview")
|
|
async getPreviewWorkspace(@Req() request: FastifyRequest): Promise<unknown> {
|
|
const { brandId } = requireAdminIdentity(request);
|
|
return this.workspaceService.getPreview(brandId);
|
|
}
|
|
@Post("install")
|
|
async install(
|
|
@Req() request: FastifyRequest,
|
|
@Body() body: InstallTemplateDto,
|
|
): Promise<unknown> {
|
|
const { brandId } = requireAdminIdentity(request);
|
|
return this.templateWorkspace.install(brandId, body.templateKey);
|
|
}
|
|
|
|
@Get("capabilities")
|
|
async listCapabilities(@Req() request: FastifyRequest): Promise<unknown> {
|
|
const brandId = requireAdminIdentity(request).brandId;
|
|
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(templateKey);
|
|
const optionalCapabilityKeys = Object.entries(capabilityRegistry)
|
|
.filter(([, definition]) => "optional" in definition && definition.optional)
|
|
.map(([key]) => key);
|
|
return [...new Set([...(template?.capabilities ?? []), ...optionalCapabilityKeys])]
|
|
.map((key) => capabilityRegistry[key as keyof typeof capabilityRegistry])
|
|
.filter(Boolean)
|
|
.map((definition) => {
|
|
const item = installed.get(definition.key);
|
|
const metadata = capabilityMetadata(definition.key);
|
|
return {
|
|
id: item?.id ?? null,
|
|
capabilityKey: definition.key,
|
|
capabilityVersion: item?.capabilityVersion ?? definition.version,
|
|
status: item?.status ?? "enabled",
|
|
config: item?.config ?? {},
|
|
source: item ? "brand" : "template",
|
|
...(metadata ?? {}),
|
|
updatedAt: item?.updatedAt ?? null,
|
|
};
|
|
});
|
|
}
|
|
|
|
@Get("sample-content/preview")
|
|
async previewSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
|
|
const brandId = requireAdminIdentity(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: sample.templateKey,
|
|
alreadyImported: offerings > 0 || trustContent > 0 || fields > 0,
|
|
counts: {
|
|
offerings: sample.offerings.length,
|
|
trustContent: sample.trustContent.length,
|
|
fields: sample.fields.length,
|
|
inquiryForms: 1,
|
|
},
|
|
willCreateInquiryForm:
|
|
(await this.prisma.inquiryForm.count({ where: { brandId, isEnabled: true } })) === 0,
|
|
};
|
|
}
|
|
|
|
@Post("sample-content/import")
|
|
async importSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
|
|
const identity = requireAdminIdentity(request);
|
|
const brandId = identity.brandId;
|
|
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
|
const sample = getTemplateSampleContent(templateKey);
|
|
if (!sample) throw new BadRequestException("模板示例内容不存在");
|
|
const fieldIssues = validateFieldSnapshot(sample.fields);
|
|
if (fieldIssues.length) throw new BadRequestException("模板咨询表单示例字段无效");
|
|
const existing = await this.prisma.brandFieldDefinition.count({
|
|
where: { brandId, source: "sample" },
|
|
});
|
|
const existingOffering = await this.prisma.offering.count({
|
|
where: { brandId, name: "序章·入户门" },
|
|
});
|
|
if (existing || existingOffering) throw new BadRequestException("示例内容已经导入");
|
|
const result = await this.prisma.$transaction(async (tx) => {
|
|
const offerings = await tx.offering.createMany({
|
|
data: sample.offerings.map((item, sortOrder) => ({
|
|
brandId,
|
|
kind: item.kind,
|
|
name: item.name,
|
|
summary: item.summary,
|
|
config: { categoryKey: item.categoryKey },
|
|
sortOrder,
|
|
isEnabled: true,
|
|
})),
|
|
});
|
|
const trust = await tx.trustContent.createMany({
|
|
data: sample.trustContent.map((item, sortOrder) => ({
|
|
brandId,
|
|
type: item.type,
|
|
title: item.title,
|
|
content: item.content,
|
|
...(item.config ? { config: item.config as Prisma.InputJsonValue } : {}),
|
|
sortOrder,
|
|
isPublished: false,
|
|
})),
|
|
});
|
|
const fields = await tx.brandFieldDefinition.createMany({
|
|
data: sample.fields.map((item, sortOrder) => ({
|
|
brandId,
|
|
scope: "inquiry",
|
|
key: item.key,
|
|
label: item.label,
|
|
type: item.type,
|
|
sortOrder,
|
|
source: "sample",
|
|
required: item.required,
|
|
})),
|
|
});
|
|
const hasEnabledForm = await tx.inquiryForm.count({ where: { brandId, isEnabled: true } });
|
|
const inquiryForm = hasEnabledForm
|
|
? null
|
|
: await tx.inquiryForm.create({
|
|
data: {
|
|
brandId,
|
|
name: sample.inquiryFormName,
|
|
purpose: "inquiry",
|
|
targetType: "brand",
|
|
submissionAction: "create-inquiry",
|
|
fieldsSnapshot: sample.fields,
|
|
isEnabled: true,
|
|
},
|
|
});
|
|
await tx.capabilityAuditLog.create({
|
|
data: {
|
|
brandId,
|
|
capabilityKey: sample.capabilityKey,
|
|
actorId: identity.subject,
|
|
action: "sample_content_imported",
|
|
toStatus: "enabled",
|
|
config: {
|
|
offerings: offerings.count,
|
|
trustContent: trust.count,
|
|
fields: fields.count,
|
|
inquiryForms: inquiryForm ? 1 : 0,
|
|
},
|
|
},
|
|
});
|
|
return {
|
|
offerings: offerings.count,
|
|
trustContent: trust.count,
|
|
fields: fields.count,
|
|
inquiryForms: inquiryForm ? 1 : 0,
|
|
};
|
|
});
|
|
return { imported: true, counts: result };
|
|
}
|
|
|
|
@Patch("capabilities/:key")
|
|
async updateCapability(
|
|
@Req() request: FastifyRequest,
|
|
@Param("key") key: string,
|
|
@Body() body: UpdateCapabilityInstallationDto,
|
|
): Promise<unknown> {
|
|
const identity = requireAdminIdentity(request);
|
|
const brandId = identity.brandId;
|
|
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({
|
|
where: { brandId_capabilityKey: { brandId, capabilityKey: key } },
|
|
});
|
|
const definition = capabilityRegistry[key as keyof typeof capabilityRegistry];
|
|
if (definition && "disablePolicy" in definition && definition.disablePolicy === "disabled")
|
|
throw new BadRequestException("核心能力不可移除");
|
|
const configErrors = validateCapabilityConfig(key as never, body.config);
|
|
if (configErrors === null) throw new BadRequestException("能力配置字段无效");
|
|
if (Object.keys(configErrors).length)
|
|
throw new BadRequestException({ message: "能力配置字段无效", errors: configErrors });
|
|
return this.prisma.$transaction(async (tx) => {
|
|
const installation = await tx.capabilityInstallation.upsert({
|
|
where: { brandId_capabilityKey: { brandId, capabilityKey: key } },
|
|
create: {
|
|
brandId,
|
|
capabilityKey: key,
|
|
capabilityVersion: definition?.version ?? "1.0.0",
|
|
status: body.status,
|
|
config: (body.config ?? {}) as Prisma.InputJsonValue,
|
|
},
|
|
update: {
|
|
...(definition ? { capabilityVersion: definition.version } : {}),
|
|
status: body.status,
|
|
...(body.config === undefined ? {} : { config: body.config as Prisma.InputJsonValue }),
|
|
},
|
|
});
|
|
await tx.capabilityAuditLog.create({
|
|
data: {
|
|
brandId,
|
|
capabilityKey: key,
|
|
actorId: identity.subject,
|
|
action: existing ? "updated" : "installed",
|
|
fromStatus: existing?.status ?? null,
|
|
toStatus: body.status,
|
|
config: (body.config ?? existing?.config ?? {}) as Prisma.InputJsonValue,
|
|
},
|
|
});
|
|
return installation;
|
|
});
|
|
}
|
|
|
|
@Get("template/preview")
|
|
async previewTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
|
const { brandId } = requireAdminIdentity(request);
|
|
return this.templateWorkspace.preview(brandId);
|
|
}
|
|
|
|
@Post("template/upgrade")
|
|
async upgradeTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
|
const { brandId } = requireAdminIdentity(request);
|
|
return this.templateWorkspace.upgrade(brandId);
|
|
}
|
|
|
|
@Post("template/rollback")
|
|
async rollbackTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
|
const { brandId } = requireAdminIdentity(request);
|
|
return this.templateWorkspace.rollback(brandId);
|
|
}
|
|
|
|
@Post("fields")
|
|
createField(
|
|
@Req() request: FastifyRequest,
|
|
@Body() body: CreateFieldDefinitionDto,
|
|
): Promise<unknown> {
|
|
const brandId = requireAdminIdentity(request).brandId;
|
|
return this.prisma.brandFieldDefinition.create({
|
|
data: {
|
|
...body,
|
|
brandId,
|
|
source: "custom",
|
|
options: body.options as Prisma.InputJsonValue,
|
|
visibleWhen: body.visibleWhen as Prisma.InputJsonValue,
|
|
},
|
|
});
|
|
}
|
|
|
|
@Patch("fields/:id")
|
|
async updateField(
|
|
@Req() request: FastifyRequest,
|
|
@Param("id") id: string,
|
|
@Body() body: UpdateFieldDefinitionDto,
|
|
): Promise<unknown> {
|
|
const brandId = requireAdminIdentity(request).brandId;
|
|
const item = await this.prisma.brandFieldDefinition.findFirst({
|
|
where: { id, brandId },
|
|
});
|
|
if (!item) throw new BadRequestException("品牌字段不存在");
|
|
const { options, visibleWhen, ...fields } = body;
|
|
return this.prisma.brandFieldDefinition.update({
|
|
where: { id },
|
|
data: {
|
|
...fields,
|
|
...(options === undefined ? {} : { options: options as Prisma.InputJsonValue }),
|
|
...(visibleWhen === undefined ? {} : { visibleWhen: visibleWhen as Prisma.InputJsonValue }),
|
|
},
|
|
});
|
|
}
|
|
|
|
@Delete("fields/:id")
|
|
async deleteField(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
|
const brandId = requireAdminIdentity(request).brandId;
|
|
const item = await this.prisma.brandFieldDefinition.findFirst({
|
|
where: { id, brandId, source: "custom" },
|
|
});
|
|
if (!item) throw new BadRequestException("自定义字段不存在或不可删除");
|
|
await this.prisma.brandFieldDefinition.delete({ where: { id } });
|
|
return { deleted: true };
|
|
}
|
|
|
|
@Get("forms")
|
|
listForms(@Req() request: FastifyRequest): Promise<unknown> {
|
|
const brandId = requireAdminIdentity(request).brandId;
|
|
return this.prisma.inquiryForm.findMany({
|
|
where: { brandId },
|
|
orderBy: { updatedAt: "desc" },
|
|
});
|
|
}
|
|
|
|
@Get("submissions")
|
|
listSubmissions(@Req() request: FastifyRequest): Promise<unknown> {
|
|
const brandId = requireAdminIdentity(request).brandId;
|
|
return this.prisma.inquirySubmission.findMany({
|
|
where: { brandId },
|
|
include: {
|
|
inquiryForm: { select: { name: true } },
|
|
offering: { select: { id: true, name: true } },
|
|
},
|
|
orderBy: { createdAt: "desc" },
|
|
});
|
|
}
|
|
|
|
@Patch("submissions/:id")
|
|
async updateSubmission(
|
|
@Req() request: FastifyRequest,
|
|
@Param("id") id: string,
|
|
@Body() body: UpdateInquirySubmissionDto,
|
|
): Promise<unknown> {
|
|
const brandId = requireAdminIdentity(request).brandId;
|
|
const item = await this.prisma.inquirySubmission.findFirst({
|
|
where: { id, brandId },
|
|
});
|
|
if (!item) throw new BadRequestException("咨询记录不存在");
|
|
return this.prisma.$transaction(async (tx) => {
|
|
const updated = await tx.inquirySubmission.update({
|
|
where: { id },
|
|
data: {
|
|
status: body.status,
|
|
...(body.adminNote === undefined ? {} : { adminNote: body.adminNote }),
|
|
},
|
|
});
|
|
if (item.status !== body.status || body.adminNote !== undefined) {
|
|
await tx.inquirySubmissionStatusHistory.create({
|
|
data: {
|
|
submissionId: id,
|
|
fromStatus: item.status,
|
|
toStatus: body.status,
|
|
adminNote: body.adminNote ?? null,
|
|
},
|
|
});
|
|
}
|
|
return updated;
|
|
});
|
|
}
|
|
|
|
@Post("forms")
|
|
createForm(@Req() request: FastifyRequest, @Body() body: CreateInquiryFormDto): Promise<unknown> {
|
|
const brandId = requireAdminIdentity(request).brandId;
|
|
if (validateFieldSnapshot(body.fieldsSnapshot).length)
|
|
throw new BadRequestException("咨询表单字段定义无效");
|
|
return this.prisma.inquiryForm.create({
|
|
data: {
|
|
...body,
|
|
brandId,
|
|
version: 1,
|
|
fieldsSnapshot: body.fieldsSnapshot as Prisma.InputJsonValue,
|
|
},
|
|
});
|
|
}
|
|
|
|
@Patch("forms/:id")
|
|
async updateForm(
|
|
@Req() request: FastifyRequest,
|
|
@Param("id") id: string,
|
|
@Body() body: UpdateInquiryFormDto,
|
|
): Promise<unknown> {
|
|
const brandId = requireAdminIdentity(request).brandId;
|
|
const item = await this.prisma.inquiryForm.findFirst({
|
|
where: { id, brandId },
|
|
});
|
|
if (!item) throw new BadRequestException("咨询表单不存在");
|
|
const { fieldsSnapshot, ...fields } = body;
|
|
if (fieldsSnapshot !== undefined && validateFieldSnapshot(fieldsSnapshot).length)
|
|
throw new BadRequestException("咨询表单字段定义无效");
|
|
return this.prisma.inquiryForm.update({
|
|
where: { id },
|
|
data: {
|
|
...fields,
|
|
...(fieldsSnapshot === undefined
|
|
? {}
|
|
: { fieldsSnapshot: fieldsSnapshot as Prisma.InputJsonValue }),
|
|
...(fieldsSnapshot === undefined ? {} : { version: { increment: 1 } }),
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|
|
export { AdminWorkspaceController };
|