feat: 收口多品牌与模板构建基础

This commit is contained in:
que01 committed 2026-09-25 02:55:46 +08:00
1 parent 0425a1c672
commit 77224ea51f
317 files changed
+11290 -1158

No files matched your search

@@ -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> {