373 lines
15 KiB
TypeScript
373 lines
15 KiB
TypeScript
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,
|
|
getTemplatePackageManifestForVisualKey,
|
|
} from "@personal-brand/config";
|
|
import type {
|
|
RuntimeInquiryField,
|
|
RuntimeOffering,
|
|
RuntimeTrustItem,
|
|
RuntimeWorkspace,
|
|
} from "@personal-brand/types";
|
|
import {
|
|
projectBrandAliases,
|
|
projectOfferingDetails,
|
|
projectTemplateData,
|
|
projectTrustItem,
|
|
projectTrustPresentation,
|
|
} from "@personal-brand/types";
|
|
|
|
@Controller("public/workspace")
|
|
export class PublicWorkspaceController {
|
|
constructor(
|
|
private readonly prisma: PrismaService,
|
|
private readonly brandContext: PublicBrandContextService,
|
|
) {}
|
|
@Get()
|
|
async get(@Query("brandSlug") brandSlug?: string): Promise<unknown> {
|
|
const brandId = await this.brandContext.resolveId(brandSlug);
|
|
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,
|
|
offerings: [],
|
|
inquiryForms: [],
|
|
trustItems: [],
|
|
capabilities: [],
|
|
trustPresentation: {},
|
|
navigation: { tabs: [] },
|
|
plugins: [],
|
|
theme: { colors: {} },
|
|
};
|
|
}
|
|
const brandData = this.jsonObject(releaseSnapshot.brand);
|
|
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>)
|
|
: {},
|
|
}))
|
|
: template
|
|
? resolveCapabilities(template.capabilities).map((item) => ({
|
|
key: item.key,
|
|
version: item.version,
|
|
status: "enabled" as const,
|
|
config: {},
|
|
}))
|
|
: [];
|
|
const brandConfig =
|
|
brandData.config && typeof brandData.config === "object" && !Array.isArray(brandData.config)
|
|
? (brandData.config as Record<string, unknown>)
|
|
: {};
|
|
const visualTemplateKey =
|
|
typeof brandConfig.visualTemplateKey === "string"
|
|
? brandConfig.visualTemplateKey
|
|
: getDefaultVisualTemplateKey(templateKey);
|
|
const visualTemplate =
|
|
releaseSnapshot.visualTemplateDefinition ?? getVisualTemplate(visualTemplateKey);
|
|
const visualTemplateManifest =
|
|
releaseSnapshot.visualTemplateManifest ?? getVisualTemplateManifest(visualTemplateKey);
|
|
const templatePackageManifest =
|
|
releaseSnapshot.templatePackageManifest ??
|
|
getTemplatePackageManifestForVisualKey(visualTemplateKey);
|
|
// 标准 BrandProfile 字段优先,兼容旧模板仍使用的 config 字段。
|
|
// 这样后台编辑 description/contactPhone 等标准字段后,旧模板也会立即读取新值。
|
|
const runtimeBrand = projectBrandAliases(brandData, brandConfig);
|
|
const declaredTemplateFields = templatePackageManifest?.templateFields ?? [];
|
|
const templateData = projectTemplateData(
|
|
brandConfig,
|
|
declaredTemplateFields.map((field) => field.key),
|
|
);
|
|
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 = projectOfferingDetails(config);
|
|
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,
|
|
},
|
|
]
|
|
: [];
|
|
})
|
|
: [];
|
|
return {
|
|
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: {
|
|
...Object.fromEntries(
|
|
Object.entries(config).filter(
|
|
([key]) =>
|
|
![
|
|
"schemaKey",
|
|
"schemaVersion",
|
|
"details",
|
|
"sections",
|
|
"media",
|
|
"presentation",
|
|
].includes(key),
|
|
),
|
|
),
|
|
...this.jsonObject(config.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: details.background,
|
|
designConcept: details.designConcept,
|
|
crafts: details.crafts,
|
|
materialsList: details.materialsList,
|
|
},
|
|
},
|
|
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 toInquiryFields = (snapshot: Prisma.JsonValue): RuntimeInquiryField[] =>
|
|
this.jsonArray(snapshot).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 sourceType = this.string(value.type);
|
|
const type =
|
|
sourceType === "phone"
|
|
? "tel"
|
|
: sourceType === "multi-select"
|
|
? "checkbox"
|
|
: [
|
|
"text",
|
|
"tel",
|
|
"number",
|
|
"select",
|
|
"radio",
|
|
"checkbox",
|
|
"checkbox",
|
|
"textarea",
|
|
"date",
|
|
].includes(sourceType)
|
|
? (sourceType 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"
|
|
? [{ label: item.label, value: item.value }]
|
|
: [];
|
|
})
|
|
: undefined;
|
|
return [
|
|
{
|
|
key: value.key,
|
|
label: value.label,
|
|
type,
|
|
required: value.required === true,
|
|
...(options?.length ? { options } : {}),
|
|
},
|
|
];
|
|
});
|
|
const trustDeclarations = templatePackageManifest?.trustContentTypes ?? [];
|
|
const trustItems: RuntimeTrustItem[] = trustData.flatMap((raw) => {
|
|
const item = projectTrustItem(this.jsonObject(raw));
|
|
return item && trustDeclarations.some((declaration) => declaration.type === item.type)
|
|
? [item]
|
|
: [];
|
|
});
|
|
const trustPresentation = projectTrustPresentation(trustItems, trustDeclarations);
|
|
const runtimeWorkspace: RuntimeWorkspace = {
|
|
schemaVersion: "1.0.0",
|
|
publication: {
|
|
status: "published",
|
|
version: release.version,
|
|
publishedAt: release.createdAt.toISOString(),
|
|
},
|
|
brand: runtimeBrand,
|
|
templateData,
|
|
navigation: {
|
|
tabs:
|
|
templatePackageManifest?.navigation.map((tab) => ({
|
|
key: tab.key,
|
|
label: tab.label,
|
|
page: templatePackageManifest.entrypoints[tab.page] ?? tab.page,
|
|
})) ?? [],
|
|
},
|
|
offerings: runtimeOfferings,
|
|
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),
|
|
};
|
|
}),
|
|
trustItems,
|
|
trustPresentation,
|
|
capabilities: runtimeCapabilities,
|
|
plugins: runtimeCapabilities
|
|
.filter((capability) => capability.status === "enabled")
|
|
.map((capability) => capability.key)
|
|
.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 } : {}),
|
|
};
|
|
const response = {
|
|
...runtimeWorkspace,
|
|
contractVersion: "1.0",
|
|
brand: runtimeBrand,
|
|
template: template
|
|
? {
|
|
key: template.key,
|
|
version:
|
|
typeof installationData.templateVersion === "string"
|
|
? installationData.templateVersion
|
|
: template.version,
|
|
name: template.name,
|
|
}
|
|
: null,
|
|
visualTemplate: visualTemplate
|
|
? {
|
|
key: visualTemplate.key,
|
|
version: visualTemplate.version,
|
|
name: visualTemplate.name,
|
|
supportedIndustryTemplates: visualTemplate.supportedIndustryTemplates,
|
|
variants: visualTemplate.variants,
|
|
}
|
|
: null,
|
|
visualTemplateManifest,
|
|
};
|
|
return response;
|
|
}
|
|
private jsonObject(value: unknown): Record<string, unknown> {
|
|
return value && typeof value === "object" && !Array.isArray(value)
|
|
? (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 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 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";
|
|
}
|
|
private submissionAction(
|
|
value: string,
|
|
): RuntimeWorkspace["inquiryForms"][number]["submissionAction"] {
|
|
return value === "create-booking" || value === "create-quote" ? value : "create-inquiry";
|
|
}
|
|
}
|