Files
persionalBrand/apps/api/src/main.ts
T

950 lines
32 KiB
TypeScript

import "reflect-metadata";
import {
BadRequestException,
UnauthorizedException,
ForbiddenException,
Body,
Controller,
Delete,
Get,
Module,
Param,
Post,
Patch,
Query,
Req,
ValidationPipe,
} from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { BookingStatus, Prisma } from "@prisma/client";
import { FastifyAdapter } from "@nestjs/platform-fastify";
import type { NestFastifyApplication } from "@nestjs/platform-fastify";
import { PrismaService } from "./prisma.service.js";
import { WechatAuthService } from "./wechat-auth.js";
import { BookingService } from "./booking.service.js";
import { CreateBookingDto, CreateInquirySubmissionDto } from "./booking.dto.js";
import {
CreateTagDto,
CreateTrustContentDto,
UpdateBookingStatusDto,
UpdateBookingTagsDto,
UpdateBrandDto,
UpdateTrustContentDto,
} from "./admin.dto.js";
import { AdminAuthService } from "./admin-auth.service.js";
import { AdminLoginDto, WechatLoginDto } from "./admin-auth.dto.js";
import type { FastifyRequest } from "fastify";
import { Transform } from "class-transformer";
import type { TransformFnParams } from "class-transformer";
import { IsBoolean, IsEnum, IsOptional, IsString } from "class-validator";
import { readIdentity, signIdentity } from "./auth.js";
import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js";
import {
brandTemplates,
getBrandTemplate,
getVisualTemplate,
resolveCapabilities,
capabilityPlugins,
visualTemplates,
} from "@personal-brand/config";
import { AdminWorkspaceController } from "./admin-workspace.controller.js";
import { TemplateWorkspaceService } from "./template-workspace.service.js";
import type {
RuntimeInquiryField,
RuntimeOffering,
RuntimeWorkspace,
RuntimeModule,
} from "@personal-brand/types";
@Controller("health")
export class HealthController {
@Get()
check(): { status: string; service: string } {
return { status: "ok", service: "personal-brand-api" };
}
}
@Controller("public")
export class PublicController {
constructor(private readonly prisma: PrismaService) {}
@Get("brand")
async brand(): Promise<unknown> {
return this.prisma.brandProfile.findFirst({
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,
},
});
}
}
@Controller("public/trust-content")
export class PublicTrustContentController {
constructor(private readonly prisma: PrismaService) {}
@Get()
list(): Promise<unknown> {
return this.prisma.trustContent.findMany({
where: {
brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
isPublished: true,
},
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
});
}
}
@Controller("public/templates")
export class PublicTemplateController {
@Get()
list(): unknown {
return { industries: Object.values(brandTemplates), visuals: Object.values(visualTemplates) };
}
@Get("preview")
preview(
@Query("industry") industry = "personal",
@Query("visual") visual = "linjing-editorial",
): unknown {
const industryTemplate = getBrandTemplate(industry);
const visualTemplate = getVisualTemplate(visual) ?? getVisualTemplate("linjing-editorial");
if (!industryTemplate || !visualTemplate) throw new BadRequestException("模板组合不存在");
return {
industry: industryTemplate,
visual: visualTemplate,
runtime: {
schemaVersion: "1.0.0",
modules: industryTemplate.modules.map((module) => ({
key: module.key,
type: module.type,
title: module.title,
variant: visualTemplate.variants[module.type] ?? "default",
})),
capabilities: resolveCapabilities(industryTemplate.capabilities),
theme: visualTemplate.theme,
},
};
}
@Get(":key")
get(@Param("key") key: string): unknown {
const template = getBrandTemplate(key);
if (!template) throw new BadRequestException("行业模板不存在");
return template;
}
}
@Controller("public/workspace")
export class PublicWorkspaceController {
constructor(private readonly prisma: PrismaService) {}
@Get()
async get(): Promise<unknown> {
const brandId = process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
const [
brand,
modules,
fields,
offerings,
inquiryForm,
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.findFirst({
where: { brandId, 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",
config:
item.config && typeof item.config === "object" && !Array.isArray(item.config)
? (item.config as Record<string, unknown>)
: {},
}))
: template
? resolveCapabilities(template.capabilities).map((item) => ({
key: item.key,
version: item.version,
status: "enabled" as const,
config: {},
}))
: [];
const brandConfig =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const visualTemplateKey =
typeof brandConfig.visualTemplateKey === "string"
? brandConfig.visualTemplateKey
: "linjing-editorial";
const visualTemplate =
getVisualTemplate(visualTemplateKey) ?? getVisualTemplate("linjing-editorial");
const runtimeModules: RuntimeModule[] = modules.map((module) => ({
key: module.type,
type: this.moduleType(module.type),
version: "1.0.0",
propsSchema: `module.${module.type}.v1`,
dataSource: module.type,
config: this.jsonObject(module.config),
source:
module.source === "custom" ? "custom" : module.source === "template" ? "template" : "core",
schemaVersion: "1.0",
}));
const runtimeOfferings: RuntimeOffering[] = offerings.map((item) => {
const config = this.jsonObject(item.config);
const sections = Array.isArray(config.sections) ? config.sections : [];
return {
id: item.id,
name: item.name,
summary: item.summary ?? item.description ?? "",
enabled: item.isEnabled,
schemaKey: typeof config.schemaKey === "string" ? config.schemaKey : "offering.default",
schemaVersion: typeof config.schemaVersion === "string" ? config.schemaVersion : "1.0.0",
sections: sections
.filter((section): section is Record<string, unknown> =>
Boolean(section && typeof section === "object"),
)
.map((section) => ({
key: typeof section.key === "string" ? section.key : "section",
type: this.sectionType(section.type),
config: this.jsonObject(section.config),
})),
};
});
const inquiryFields: RuntimeInquiryField[] = this.jsonArray(
inquiryForm?.fieldsSnapshot,
).flatMap((field) => {
if (!field || typeof field !== "object") return [];
const value = field as Record<string, unknown>;
if (typeof value.key !== "string" || typeof value.label !== "string") return [];
const type = [
"text",
"tel",
"number",
"select",
"radio",
"checkbox",
"textarea",
"date",
].includes(String(value.type))
? (value.type as RuntimeInquiryField["type"])
: "text";
return [{ key: value.key, label: value.label, type, required: value.required === true }];
});
const runtimeWorkspace: RuntimeWorkspace = {
schemaVersion: "1.0.0",
brand: (brand ?? {}) as Record<string, unknown>,
navigation: {
tabs: [
{ key: "home", label: "首页", page: "pages/index/index" },
{ key: "offerings", label: "案例与体系", page: "pages/services/index" },
{ key: "profile", label: "主理人与我", page: "pages/bookings/index" },
],
},
modules: runtimeModules,
offerings: runtimeOfferings,
inquiryForms: inquiryForm
? [
{
key: inquiryForm.id,
version: String(inquiryForm.version),
purpose: this.formPurpose(inquiryForm.purpose),
target: inquiryForm.targetType === "offering" ? "offering" : "brand",
submissionAction: this.submissionAction(inquiryForm.submissionAction),
fields: inquiryFields,
},
]
: [],
capabilities: runtimeCapabilities,
plugins: (template ? template.capabilities : [])
.map((key) => capabilityPlugins[key as keyof typeof capabilityPlugins])
.filter(Boolean)
.map((plugin) => ({ ...plugin, status: "enabled" as const, config: {} })),
theme: visualTemplate?.theme ?? {
colors: { background: "#F7F5F1", foreground: "#252525", accent: "#8A6846" },
},
...(visualTemplate?.layout ? { layout: visualTemplate.layout } : {}),
};
return {
...runtimeWorkspace,
contractVersion: "1.0",
brand,
template: template
? {
key: template.key,
version: installation?.templateVersion ?? template.version,
name: template.name,
}
: null,
visualTemplate: visualTemplate
? {
key: visualTemplate.key,
version: visualTemplate.version,
name: visualTemplate.name,
variants: visualTemplate.variants,
}
: null,
capabilities: runtimeCapabilities,
runtimeCapabilities,
modules,
runtimeModules,
fields,
offerings,
trustContent: trustContents,
inquiryForm,
};
}
private jsonObject(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
private jsonArray(value: unknown): Prisma.JsonValue[] {
return Array.isArray(value) ? value : [];
}
private moduleType(value: string): RuntimeModule["type"] {
const known: RuntimeModule["type"][] = [
"brand-hero",
"founder-card",
"trust-proof",
"offering-list",
"offering-detail",
"gallery",
"timeline",
"faq",
"contact",
"inquiry",
"records",
"custom",
];
return (
known.includes(value as RuntimeModule["type"]) ? value : "custom"
) as RuntimeModule["type"];
}
private sectionType(value: unknown): RuntimeOffering["sections"][number]["type"] {
const known = ["text", "image-list", "timeline", "faq", "specification"] as const;
return known.includes(value as (typeof known)[number])
? (value as (typeof known)[number])
: "text";
}
private formPurpose(value: string): RuntimeWorkspace["inquiryForms"][number]["purpose"] {
return value === "booking" || value === "quote-request" ? value : "inquiry";
}
private submissionAction(
value: string,
): RuntimeWorkspace["inquiryForms"][number]["submissionAction"] {
return value === "create-booking" || value === "create-quote" ? value : "create-inquiry";
}
}
@Controller("public/offerings")
export class PublicOfferingController {
constructor(private readonly prisma: PrismaService) {}
@Get()
async list(): Promise<unknown> {
const brandId = process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
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));
}
@Get(":id")
async get(@Param("id") id: string): Promise<unknown> {
const item = await this.prisma.offering.findFirst({
where: {
id,
brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
isEnabled: true,
},
include: {
inquiryForms: {
where: { isEnabled: true },
orderBy: { updatedAt: "desc" },
select: { id: true, name: true, purpose: true, targetType: true, version: true },
},
},
});
if (!item) throw new BadRequestException("业务提供项不存在");
return this.present(item);
}
private present(item: { config: Prisma.JsonValue; [key: string]: unknown }): unknown {
const config = (item.config ?? {}) as Record<string, unknown>;
return {
...item,
sections: config.sections ?? [],
media: config.media ?? [],
cta: config.cta ?? null,
};
}
}
@Controller("public/inquiry-forms")
export class PublicInquiryFormController {
constructor(private readonly prisma: PrismaService) {}
@Get(":id")
async get(@Param("id") id: string): Promise<unknown> {
const form = await this.prisma.inquiryForm.findFirst({
where: {
id,
brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
isEnabled: true,
OR: [{ offeringId: null }, { offering: { isEnabled: true } }],
},
});
if (!form) throw new BadRequestException("咨询表单不存在");
return form;
}
}
@Controller("customer/inquiry-submissions")
export class CustomerInquirySubmissionController {
constructor(private readonly prisma: PrismaService) {}
@Post()
async create(
@Req() request: FastifyRequest,
@Body() body: CreateInquirySubmissionDto,
): Promise<unknown> {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少客户登录态");
let identity;
try {
identity = readIdentity(token);
} catch {
throw new UnauthorizedException("客户登录态无效或已过期");
}
if (identity.role !== "customer") throw new ForbiddenException("无客户权限");
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("咨询表单不存在");
return this.prisma.inquirySubmission.create({
data: {
brandId: identity.brandId,
inquiryFormId: form.id,
offeringId: form.offeringId,
formVersion: form.version,
fieldsSnapshot: form.fieldsSnapshot as Prisma.InputJsonValue,
values: body.values as Prisma.InputJsonValue,
activeFields: Object.fromEntries(Object.keys(body.values).map((key) => [key, true])),
},
});
}
}
@Controller("customer/session")
export class CustomerSessionController {
constructor(
private readonly wechatAuth: WechatAuthService,
private readonly prisma: PrismaService,
) {}
@Post("wechat")
async wechatLogin(@Body() body: WechatLoginDto): Promise<{ token: string }> {
const session = await this.wechatAuth.exchangeCode(body.code);
const brand = await this.prisma.brandProfile.findFirst({ select: { id: true } });
if (!brand) throw new BadRequestException("品牌尚未初始化");
await this.prisma.customerUser.upsert({
where: { brandId_openid: { brandId: brand.id, openid: session.openid } },
update: { lastLoginAt: new Date() },
create: { brandId: brand.id, openid: session.openid },
});
return {
token: signIdentity({ subject: session.openid, brandId: brand.id, role: "customer" }),
};
}
}
@Controller("admin/session")
export class AdminSessionController {
constructor(private readonly auth: AdminAuthService) {}
@Post("login")
login(@Body() body: AdminLoginDto): Promise<{ token: string; displayName: string }> {
return this.auth.login(body.username, body.password);
}
}
class AdminBookingQueryDto {
@IsOptional()
@IsEnum(BookingStatus)
status?: BookingStatus;
@IsOptional()
@Transform((params: TransformFnParams): unknown => {
const value: unknown = params.value;
if (value === "true") return true;
if (value === "false") return false;
return value;
})
@IsBoolean()
unreadOnly?: boolean;
@IsOptional()
@IsString()
tagId?: string;
}
@Controller("customer/bookings")
export class CustomerBookingController {
constructor(
private readonly prisma: PrismaService,
private readonly bookings: BookingService,
) {}
@Post()
async create(@Req() request: FastifyRequest, @Body() body: CreateBookingDto): Promise<unknown> {
const identity = this.identity(request);
const customer = await this.prisma.customerUser.findUnique({
where: { brandId_openid: identity },
});
if (!customer) throw new BadRequestException("请先完成微信登录");
return this.bookings.create(identity.brandId, customer.id, {
...body,
extraData: body.extraData as Prisma.InputJsonObject,
});
}
@Get()
async list(@Req() request: FastifyRequest): Promise<unknown> {
const identity = this.identity(request);
const customer = await this.prisma.customerUser.findUnique({
where: { brandId_openid: identity },
});
if (!customer) throw new BadRequestException("请先完成微信登录");
return this.bookings.listForCustomer(identity.brandId, customer.id);
}
@Post(":id/cancel")
async cancel(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
const identity = this.identity(request);
const customer = await this.prisma.customerUser.findUnique({
where: { brandId_openid: identity },
});
if (!customer) throw new BadRequestException("请先完成微信登录");
return this.bookings.cancelForCustomer(identity.brandId, customer.id, id);
}
private identity(request: FastifyRequest): { brandId: string; openid: string } {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new BadRequestException("缺少客户登录态");
try {
const identity = readIdentity(token);
if (identity.role !== "customer") throw new BadRequestException("客户登录态无效");
return { brandId: identity.brandId, openid: identity.subject };
} catch (error) {
if (error instanceof BadRequestException) throw error;
throw new BadRequestException("客户登录态无效");
}
}
}
@Controller("admin/bookings")
export class AdminBookingController {
constructor(private readonly bookings: BookingService) {}
@Get()
list(@Req() request: FastifyRequest, @Query() query: AdminBookingQueryDto): Promise<unknown> {
this.requireAdmin(request);
return this.bookings.listForAdmin(
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
query,
);
}
@Get("unread-count")
unreadCount(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.bookings.unreadCountForAdmin(
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
);
}
@Get(":id")
detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
this.requireAdmin(request);
return this.bookings.getForAdmin(
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
id,
);
}
@Post(":id/status")
update(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body()
body: UpdateBookingStatusDto,
): Promise<unknown> {
this.requireAdmin(request);
return this.bookings.updateStatus(
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
id,
body.status,
body.adminNote,
);
}
@Post(":id/read")
markRead(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
this.requireAdmin(request);
return this.bookings.markRead(
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
id,
);
}
@Post(":id/tags")
updateTags(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateBookingTagsDto,
): Promise<unknown> {
this.requireAdmin(request);
return this.bookings.updateTags(
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
id,
body.tagIds,
);
}
@Get("/tags")
listTags(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.bookings.listTags(
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
);
}
@Post("/tags")
createTag(@Req() request: FastifyRequest, @Body() body: CreateTagDto): Promise<unknown> {
this.requireAdmin(request);
return this.bookings.createTag(
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
body.name,
);
}
private requireAdmin(request: FastifyRequest): void {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
try {
identity = readIdentity(token);
} catch {
throw new UnauthorizedException("管理员登录态无效或已过期");
}
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
}
}
@Controller("admin/config")
export class AdminConfigController {
constructor(private readonly prisma: PrismaService) {}
private brandId(): string {
return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
}
private requireAdmin(request: FastifyRequest): void {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
try {
identity = readIdentity(token);
} catch {
throw new UnauthorizedException("管理员登录态无效或已过期");
}
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
}
@Get("brand")
getBrand(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.prisma.brandProfile.findUnique({ where: { id: this.brandId() } });
}
@Patch("brand")
async updateBrand(
@Req() request: FastifyRequest,
@Body() body: UpdateBrandDto,
): Promise<unknown> {
this.requireAdmin(request);
const { config, ...fields } = body;
const current = await this.prisma.brandProfile.findUnique({
where: { id: this.brandId() },
select: { config: true },
});
const currentConfig =
current?.config && typeof current.config === "object" && !Array.isArray(current.config)
? (current.config as Record<string, unknown>)
: {};
const nextConfig = config ? { ...currentConfig, ...config } : undefined;
if (config?.visualTemplateKey && config.visualTemplateKey !== currentConfig.visualTemplateKey) {
const installation = await this.prisma.brandTemplateInstallation.findFirst({
where: { brandId: this.brandId() },
});
if (installation) {
const history = Array.isArray(installation.previousSnapshots)
? installation.previousSnapshots
: [];
await this.prisma.brandTemplateInstallation.update({
where: { id: installation.id },
data: {
previousSnapshots: [
...history,
{
visualTemplateKey: currentConfig.visualTemplateKey ?? "linjing-editorial",
savedAt: new Date().toISOString(),
},
],
},
});
}
}
return this.prisma.brandProfile.update({
where: { id: this.brandId() },
data: {
...fields,
...(nextConfig ? { config: nextConfig as Prisma.InputJsonValue } : {}),
},
});
}
@Get("visual-template/history")
getVisualTemplateHistory(@Req() request: FastifyRequest): unknown {
this.requireAdmin(request);
return this.prisma.brandTemplateInstallation
.findFirst({ where: { brandId: this.brandId() }, select: { previousSnapshots: true } })
.then((installation) => ({
history: Array.isArray(installation?.previousSnapshots)
? installation.previousSnapshots.filter(
(item) =>
item &&
typeof item === "object" &&
!Array.isArray(item) &&
"visualTemplateKey" in item,
)
: [],
}));
}
@Post("visual-template/rollback")
async rollbackVisualTemplate(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
const brandId = this.brandId();
const [brand, installation] = await Promise.all([
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
]);
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const history = Array.isArray(installation?.previousSnapshots)
? installation.previousSnapshots
: [];
const index = [...history]
.map((item, i) => ({ item, i }))
.reverse()
.find(
({ item }) =>
item && typeof item === "object" && !Array.isArray(item) && "visualTemplateKey" in item,
)?.i;
const previous =
index === undefined ? undefined : (history[index] as { visualTemplateKey?: unknown });
if (!previous || typeof previous.visualTemplateKey !== "string")
throw new BadRequestException("没有可回滚的视觉模板版本");
await this.prisma.$transaction([
this.prisma.brandProfile.update({
where: { id: brandId },
data: {
config: {
...config,
visualTemplateKey: previous.visualTemplateKey,
} as Prisma.InputJsonValue,
},
}),
...(installation
? [
this.prisma.brandTemplateInstallation.update({
where: { id: installation.id },
data: { previousSnapshots: history.slice(0, index) },
}),
]
: []),
]);
return { visualTemplateKey: previous.visualTemplateKey, rolledBack: true };
}
@Get("visual-template/preview")
getVisualTemplatePreview(@Req() request: FastifyRequest): unknown {
this.requireAdmin(request);
return this.prisma.brandProfile
.findUnique({ where: { id: this.brandId() }, select: { config: true } })
.then((brand) => {
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const currentKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: "linjing-editorial";
const current = getVisualTemplate(currentKey) ?? getVisualTemplate("linjing-editorial");
return {
current: current
? {
key: current.key,
version: current.version,
name: current.name,
theme: current.theme,
variants: current.variants,
}
: null,
available: ["linjing-editorial", "minimal-neutral"],
};
});
}
@Get("trust-content")
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.prisma.trustContent.findMany({
where: { brandId: this.brandId() },
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
});
}
@Post("trust-content")
createTrustContent(
@Req() request: FastifyRequest,
@Body() body: CreateTrustContentDto,
): Promise<unknown> {
this.requireAdmin(request);
const { config, ...fields } = body;
return this.prisma.trustContent.create({
data: {
...fields,
brandId: this.brandId(),
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
@Patch("trust-content/:id")
async updateTrustContent(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateTrustContentDto,
): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.trustContent.findFirst({
where: { id, brandId: this.brandId() },
});
if (!item) throw new BadRequestException("信任内容不存在");
const { config, ...fields } = body;
return this.prisma.trustContent.update({
where: { id },
data: {
...fields,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
@Delete("trust-content/:id")
async deleteTrustContent(
@Req() request: FastifyRequest,
@Param("id") id: string,
): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.trustContent.findFirst({
where: { id, brandId: this.brandId() },
});
if (!item) throw new BadRequestException("信任内容不存在");
await this.prisma.trustContent.delete({ where: { id } });
return { deleted: true };
}
}
@Module({
controllers: [
HealthController,
PublicController,
PublicTrustContentController,
PublicTemplateController,
PublicWorkspaceController,
PublicOfferingController,
PublicInquiryFormController,
CustomerInquirySubmissionController,
AdminWorkspaceController,
CustomerSessionController,
AdminSessionController,
CustomerBookingController,
AdminBookingController,
AdminConfigController,
],
providers: [
PrismaService,
WechatAuthService,
BookingService,
AdminAuthService,
TemplateWorkspaceService,
],
exports: [PrismaService, WechatAuthService],
})
export class AppModule {}
export async function createApp(): Promise<NestFastifyApplication> {
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
app.useGlobalPipes(
new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }),
);
app.useGlobalFilters(new ApiExceptionFilter());
const apiPrefix = process.env.API_PREFIX?.replace(/^\/+|\/+$/g, "");
if (apiPrefix) app.setGlobalPrefix(apiPrefix);
app.use(new RequestIdMiddleware().use.bind(new RequestIdMiddleware()));
app.enableCors();
return app;
}
if (process.env.NODE_ENV !== "test") {
const app = await createApp();
await app.listen({ port: Number(process.env.API_PORT ?? 3001), host: "0.0.0.0" });
}