From 3003e7801d863a32f35e0cf4b40842ad78cd5bf1 Mon Sep 17 00:00:00 2001 From: que01 Date: Mon, 12 Oct 2026 03:08:24 +0800 Subject: [PATCH 1/7] =?UTF-8?q?refactor:=20=E5=BB=BA=E7=AB=8B=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E6=A0=87=E5=87=86=E5=B9=B6=E6=8B=86=E5=88=86=E5=93=81?= =?UTF-8?q?=E7=89=8C=E7=BC=96=E8=BE=91=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/features/brand/PresentationEditor.tsx | 201 +++------------- .../presentation-editor-record-preview.ts | 39 +++ .../brand/presentation-editor-state.ts | 226 ++++++++++++++++++ docs/code-standards.md | 50 ++++ 4 files changed, 344 insertions(+), 172 deletions(-) create mode 100644 apps/admin/src/features/brand/presentation-editor-record-preview.ts create mode 100644 apps/admin/src/features/brand/presentation-editor-state.ts create mode 100644 docs/code-standards.md diff --git a/apps/admin/src/features/brand/PresentationEditor.tsx b/apps/admin/src/features/brand/PresentationEditor.tsx index 2dfb633..646c56e 100644 --- a/apps/admin/src/features/brand/PresentationEditor.tsx +++ b/apps/admin/src/features/brand/PresentationEditor.tsx @@ -11,9 +11,8 @@ import { Space, Tag, Typography, - message, } from "antd"; -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useQueryClient } from "@tanstack/react-query"; import { useCallback, useEffect, useMemo, useState } from "react"; import { useNavigate } from "react-router-dom"; import type { @@ -24,7 +23,6 @@ import type { } from "@personal-brand/api-client"; import type { BrandProfile } from "@personal-brand/api-client"; import { projectBrandAliases, projectTrustPresentation } from "@personal-brand/api-client"; -import { createApiClient } from "../../lib/api.js"; import { TemplateListField } from "../../components/TemplateListField.js"; import { TemplateFieldRenderer } from "../../components/TemplateFieldRenderer.js"; import { MutationError } from "../../components/QueryState.js"; @@ -38,17 +36,20 @@ import { type PreviewTarget, } from "./preview-selection.js"; import { - applyBrandPreviewValues, - applyStandardBrandValues, - applyStandardEntityValues, - applyPresentationValues, filterSectionsForPreviewTarget, presentationFieldName, - readPresentationValue, type PresentationValues, } from "./presentation-bindings.js"; import "./PresentationEditor.css"; import { useEditorDraft } from "./use-editor-draft.js"; +import { + usePresentationRecordQueries, + useBrandPresentationSections, + useBrandSaveMutation, + useBrandPresentationForm, + useBrandPreviewDraft, +} from "./presentation-editor-state.js"; +import { useRecordPreview } from "./presentation-editor-record-preview.js"; interface PresentationEditorProps { templateContent: AdminTemplateContent | null | undefined; @@ -136,7 +137,6 @@ export function PresentationEditor({ error, initialSelection, }: PresentationEditorProps) { - const [form] = Form.useForm(); const queryClient = useQueryClient(); const navigate = useNavigate(); const breakpoints = Grid.useBreakpoint(); @@ -149,45 +149,12 @@ export function PresentationEditor({ id: string; values: PresentationValues; }>(); - const [previewConfig, setPreviewConfig] = useState(config ?? {}); - const [previewBrandValues, setPreviewBrandValues] = useState>({}); const [inquiryDraft, setInquiryDraft] = useState(); const [brandDirty, setBrandDirty] = useState(false); const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft); const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand"); - const sections = useMemo(() => { - const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({ - ...field, - binding: field.binding ?? `brand.config.templateData.${field.key}`, - })); - return [ - ...[...new Set(declaredTemplateFields.map((field) => field.page ?? "home"))].map((page) => ({ - key: `template-data:${page}`, - title: "模板专属内容", - description: "这些字段由当前小程序模板定义,保存后发布才会对外展示。", - page, - target: "brand" as const, - fields: declaredTemplateFields.filter((field) => (field.page ?? "home") === page), - })), - ...(templateContent?.admin.sections ?? []), - ].map((section) => ({ - ...section, - fields: section.fields.filter( - (field) => - field.binding.startsWith("brand.config.") || - [ - "brand.name", - "brand.tagline", - "brand.avatarUrl", - "brand.description", - "brand.contactPhone", - "brand.contactWechat", - "brand.address", - ].includes(field.binding), - ), - })); - }, [templateContent]); + const sections = useBrandPresentationSections(templateContent); const pageOptions = useMemo(() => { const pages = new Map(); for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label); @@ -248,23 +215,10 @@ export function PresentationEditor({ selectedTarget?.source === "offering" || selectedTarget?.source === "trust" ? selectedTarget.source : undefined; - const offeringsQuery = useQuery({ - queryKey: ["admin-offerings"], - queryFn: () => createApiClient().listAdminOfferings(), - enabled: selectedRecordSource === "offering", - refetchOnMount: "always", - }); - const trustQuery = useQuery({ - queryKey: ["trust-content"], - queryFn: () => createApiClient().listAdminTrustContent(), - enabled: selectedRecordSource === "trust", - }); - const selectedRecord = - selectedRecordSource === "offering" - ? offeringsQuery.data?.find((item) => item.id === selection?.recordId) - : selectedRecordSource === "trust" - ? trustQuery.data?.find((item) => item.id === selection?.recordId) - : undefined; + const { offeringsQuery, trustQuery, selectedRecord } = usePresentationRecordQueries( + selectedRecordSource, + selection?.recordId, + ); const editableSections = filterSectionsForPreviewTarget( visibleSections.filter((section) => section.fields.some((field) => field.binding.startsWith("brand.")), @@ -342,58 +296,9 @@ export function PresentationEditor({ return item.target === selectedSection.target; }) : pageLinks; - const initialValues = useMemo(() => { - const values: PresentationValues = {}; - for (const section of sections) { - for (const field of section.fields) { - values[presentationFieldName(section.key, field.key)] = readPresentationValue( - config, - field.binding, - field, - brand as unknown as Record, - ); - } - } - return values; - }, [config, sections]); - - const save = useMutation({ - mutationFn: (values: PresentationValues) => { - const nextConfig = applyPresentationValues(config, sections, values); - // 页面内容编辑不提交模板选择,避免触发切换模板的权限校验。 - const contentConfig = { ...nextConfig }; - delete contentConfig.visualTemplateKey; - const standard = applyStandardBrandValues( - brand as unknown as Record, - sections, - values, - ); - const changed = Object.fromEntries( - Object.entries(standard).filter( - ([key, value]) => - key !== "config" && value !== (brand as unknown as Record)[key], - ), - ); - return createApiClient().updateAdminBrand({ - ...changed, - config: contentConfig, - }); - }, - onSuccess: () => { - setBrandDirty(false); - message.success("页面内容已保存为草稿,发布后小程序才会更新"); - window.dispatchEvent(new Event("template-preview-refresh")); - void queryClient.invalidateQueries({ queryKey: ["admin-brand"] }); - void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); - void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] }); - void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] }); - void queryClient.invalidateQueries({ queryKey: ["publication-readiness"] }); - }, - }); - - useEffect(() => { - form.setFieldsValue(initialValues); - }, [form, initialValues]); + const formState = useBrandPresentationForm({ brand, config, sections }); + const { form, initialValues } = formState; + const save = useBrandSaveMutation({ ...formState, brand, config, sections, queryClient }); useEffect(() => { const initialPage = @@ -453,62 +358,16 @@ export function PresentationEditor({ () => setRecordDraft(undefined), [selection?.targetKey, selection?.recordId, selectedPage], ); - useEffect(() => { - setPreviewConfig(config ?? {}); - setPreviewBrandValues({}); - }, [config, initialValues]); - const previewBrand = useMemo( - () => ({ ...brand, ...previewBrandValues, config: previewConfig }), - [brand, previewBrandValues, previewConfig], - ); - const recordPreview = useMemo(() => { - if (!recordDraft || !selectedRecord || !recordSection) return undefined; - const config = applyPresentationValues( - selectedRecord.config, - [recordSection], - recordDraft.values, - ); - return { - config, - standard: applyStandardEntityValues( - selectedRecord as unknown as Record, - recordDraft.source, - [recordSection], - recordDraft.values, - ), - }; - }, [recordDraft, selectedRecord, recordSection]); - const handleValuesChange = useCallback( - (changed: PresentationValues, allValues: PresentationValues) => { - setBrandDirty(true); - const synchronized: PresentationValues = { - ...(form.getFieldsValue(true) as PresentationValues), - ...allValues, - }; - for (const section of sections) { - for (const field of section.fields) { - const name = presentationFieldName(section.key, field.key); - if (!Object.prototype.hasOwnProperty.call(changed, name)) continue; - for (const peer of sections) { - for (const item of peer.fields) { - if (item.binding === field.binding) - synchronized[presentationFieldName(peer.key, item.key)] = changed[name]; - } - } - } - } - form.setFieldsValue(synchronized); - const next = applyBrandPreviewValues( - brand as unknown as Record, - config, - sections, - synchronized, - ); - setPreviewConfig((next.config as Record) ?? {}); - setPreviewBrandValues(next); - }, - [brand, config, sections, form], - ); + const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({ + brand, + config, + sections, + form, + onDirty: () => setBrandDirty(true), + }); + const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection }); + useEffect(() => resetPreview(), [config, initialValues, resetPreview]); + const previewConfig = previewBrand.config; const draftWorkspace = useMemo(() => { if (!previewWorkspace) return undefined; const next: RuntimeWorkspace = { @@ -652,8 +511,7 @@ export function PresentationEditor({ guardDraft(() => { setBrandDirty(false); form.setFieldsValue(initialValues); - setPreviewConfig(config ?? {}); - setPreviewBrandValues({}); + resetPreview(); setRecordDraft(undefined); setInquiryDraft(undefined); setActivePage(value); @@ -669,8 +527,7 @@ export function PresentationEditor({ guardDraft(() => { setBrandDirty(false); form.setFieldsValue(initialValues); - setPreviewConfig(config ?? {}); - setPreviewBrandValues({}); + resetPreview(); setRecordDraft(undefined); setInquiryDraft(undefined); setActivePage(String(value)); diff --git a/apps/admin/src/features/brand/presentation-editor-record-preview.ts b/apps/admin/src/features/brand/presentation-editor-record-preview.ts new file mode 100644 index 0000000..533ac9e --- /dev/null +++ b/apps/admin/src/features/brand/presentation-editor-record-preview.ts @@ -0,0 +1,39 @@ +import { useMemo } from "react"; +import type { Offering, TrustContent } from "@personal-brand/api-client"; +import type { TemplateAdminSection } from "@personal-brand/api-client"; +import { applyPresentationValues, applyStandardEntityValues } from "./presentation-bindings.js"; +import type { PresentationValues } from "./presentation-bindings.js"; + +export interface RecordDraft { + source: "offering" | "trust"; + id: string; + values: PresentationValues; +} + +export function useRecordPreview({ + recordDraft, + selectedRecord, + recordSection, +}: { + recordDraft?: RecordDraft | undefined; + selectedRecord?: Offering | TrustContent | undefined; + recordSection?: TemplateAdminSection | undefined; +}) { + return useMemo(() => { + if (!recordDraft || !selectedRecord || !recordSection) return undefined; + const config = applyPresentationValues( + selectedRecord.config, + [recordSection], + recordDraft.values, + ); + return { + config, + standard: applyStandardEntityValues( + selectedRecord as unknown as Record, + recordDraft.source, + [recordSection], + recordDraft.values, + ), + }; + }, [recordDraft, selectedRecord, recordSection]); +} diff --git a/apps/admin/src/features/brand/presentation-editor-state.ts b/apps/admin/src/features/brand/presentation-editor-state.ts new file mode 100644 index 0000000..dee7a9a --- /dev/null +++ b/apps/admin/src/features/brand/presentation-editor-state.ts @@ -0,0 +1,226 @@ +import { Form, message } from "antd"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import type { QueryClient } from "@tanstack/react-query"; +import { useEffect, useMemo, useState } from "react"; +import type { FormInstance } from "antd"; +import type { + AdminTemplateContent, + BrandProfile, + Offering, + TemplateAdminSection, + TrustContent, +} from "@personal-brand/api-client"; +import { createApiClient } from "../../lib/api.js"; +import { + applyBrandPreviewValues, + applyPresentationValues, + applyStandardBrandValues, + presentationFieldName, + readPresentationValue, + type PresentationValues, +} from "./presentation-bindings.js"; + +const standardBrandBindings = [ + "brand.name", + "brand.tagline", + "brand.avatarUrl", + "brand.description", + "brand.contactPhone", + "brand.contactWechat", + "brand.address", +] as const; + +export interface BrandPresentationFormState { + form: FormInstance; + initialValues: PresentationValues; +} + +export function useBrandPresentationSections( + templateContent: AdminTemplateContent | null | undefined, +): TemplateAdminSection[] { + return useMemo(() => { + const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({ + ...field, + binding: field.binding ?? `brand.config.templateData.${field.key}`, + })); + return [ + ...[...new Set(declaredTemplateFields.map((field) => field.page ?? "home"))].map((page) => ({ + key: `template-data:${page}`, + title: "模板专属内容", + description: "这些字段由当前小程序模板定义,保存后发布才会对外展示。", + page, + target: "brand" as const, + fields: declaredTemplateFields.filter((field) => (field.page ?? "home") === page), + })), + ...(templateContent?.admin.sections ?? []), + ].map((section) => ({ + ...section, + fields: section.fields.filter( + (field) => + field.binding.startsWith("brand.config.") || + (standardBrandBindings as readonly string[]).includes(field.binding), + ), + })); + }, [templateContent]); +} + +export function useBrandPresentationForm({ + brand, + config, + sections, +}: { + brand: BrandProfile; + config: Record | null | undefined; + sections: TemplateAdminSection[]; +}): BrandPresentationFormState { + const [form] = Form.useForm(); + const initialValues = useMemo(() => { + const values: PresentationValues = {}; + for (const section of sections) { + for (const field of section.fields) { + values[presentationFieldName(section.key, field.key)] = readPresentationValue( + config, + field.binding, + field, + brand as unknown as Record, + ); + } + } + return values; + }, [brand, config, sections]); + + useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]); + return { form, initialValues }; +} + +interface BrandSaveMutationOptions extends BrandPresentationFormState { + brand: BrandProfile; + config: Record | null | undefined; + sections: TemplateAdminSection[]; + queryClient: QueryClient; +} + +export function useBrandSaveMutation({ + brand, + config, + sections, + queryClient, +}: BrandSaveMutationOptions) { + return useMutation({ + mutationFn: (values: PresentationValues) => { + const nextConfig = applyPresentationValues(config, sections, values); + const contentConfig = { ...nextConfig }; + delete contentConfig.visualTemplateKey; + const standard = applyStandardBrandValues( + brand as unknown as Record, + sections, + values, + ); + const changed = Object.fromEntries( + Object.entries(standard).filter( + ([key, value]) => + key !== "config" && value !== (brand as unknown as Record)[key], + ), + ); + return createApiClient().updateAdminBrand({ ...changed, config: contentConfig }); + }, + onSuccess: () => { + message.success("页面内容已保存为草稿,发布后小程序才会更新"); + window.dispatchEvent(new Event("template-preview-refresh")); + void queryClient.invalidateQueries({ queryKey: ["admin-brand"] }); + void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); + void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] }); + void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] }); + void queryClient.invalidateQueries({ queryKey: ["publication-readiness"] }); + }, + }); +} + +export function useBrandPreviewDraft({ + brand, + config, + sections, + form, + onDirty, +}: { + brand: BrandProfile; + config: Record | null | undefined; + sections: TemplateAdminSection[]; + form: BrandPresentationFormState["form"]; + onDirty: () => void; +}) { + const [previewConfig, setPreviewConfig] = useState(config ?? {}); + const [previewBrandValues, setPreviewBrandValues] = useState>({}); + + useEffect(() => { + setPreviewConfig(config ?? {}); + setPreviewBrandValues({}); + }, [config, form]); + + const handleValuesChange = (changed: PresentationValues, allValues: PresentationValues) => { + onDirty(); + const synchronized: PresentationValues = { + ...(form.getFieldsValue(true) as PresentationValues), + ...allValues, + }; + for (const section of sections) { + for (const field of section.fields) { + const name = presentationFieldName(section.key, field.key); + if (!Object.prototype.hasOwnProperty.call(changed, name)) continue; + for (const peer of sections) { + for (const item of peer.fields) { + if (item.binding === field.binding) + synchronized[presentationFieldName(peer.key, item.key)] = changed[name]; + } + } + } + } + form.setFieldsValue(synchronized); + const next = applyBrandPreviewValues( + brand as unknown as Record, + config, + sections, + synchronized, + ); + setPreviewConfig((next.config as Record) ?? {}); + setPreviewBrandValues(next); + }; + + const previewBrand = useMemo( + () => ({ ...brand, ...previewBrandValues, config: previewConfig }), + [brand, previewBrandValues, previewConfig], + ); + + return { + previewBrand, + handleValuesChange, + resetPreview: () => { + setPreviewConfig(config ?? {}); + setPreviewBrandValues({}); + }, + }; +} + +export function usePresentationRecordQueries( + source: "offering" | "trust" | undefined, + recordId: string | undefined, +) { + const offeringsQuery = useQuery({ + queryKey: ["admin-offerings"], + queryFn: () => createApiClient().listAdminOfferings(), + enabled: source === "offering", + refetchOnMount: "always", + }); + const trustQuery = useQuery({ + queryKey: ["trust-content"], + queryFn: () => createApiClient().listAdminTrustContent(), + enabled: source === "trust", + }); + const selectedRecord = + source === "offering" + ? offeringsQuery.data?.find((item: Offering) => item.id === recordId) + : source === "trust" + ? trustQuery.data?.find((item: TrustContent) => item.id === recordId) + : undefined; + return { offeringsQuery, trustQuery, selectedRecord }; +} diff --git a/docs/code-standards.md b/docs/code-standards.md new file mode 100644 index 0000000..b2f233e --- /dev/null +++ b/docs/code-standards.md @@ -0,0 +1,50 @@ +# 代码结构与重构标准 + +这份标准用于控制现有模块继续膨胀,并约束后续大文件重构。它不是替代 `docs/engineering-delivery-checklist.md`,而是补充结构边界。 + +## 通用规则 + +- 页面、Controller、Service 只保留一个明确入口;独立业务规则、数据映射、授权判断和视图状态必须拆出命名模块。 +- 单文件超过 500 行必须提供拆分计划;超过 800 行应拆分。拆分要按职责,不按行数机械切分。 +- 禁止在页面组件内内联完整 API 调用、复杂 JSON 转换和多层级业务规则。 +- 禁止新增全局工具函数堆积文件;按领域模块导出,不建 `utils.ts` 黑洞。 +- 迁移、DTO、API Client 类型、页面、测试和文档随行为一起变更。 + +## Admin React 标准 + +- 页面组件负责组合布局和路由;不直接实现超过一个相关领域的业务逻辑。 +- 一个页面由以下边界组成: + - 页面组件:布局、路由、页面状态组合。 + - hooks:数据查询、mutation、表单初始化、草稿与预览状态。 + - 领域工具:纯函数,可单测,不调用 `fetch`。 + - feature 组件:局部 UI 区块。 + - shared components:跨 feature 使用的表单字段、状态和基础控件。 +- React Query 的 query key、失效和成功提示统一放在 hooks 中;页面不要散落 `invalidateQueries`。 +- 表单初始化、同步字段、脏检查和失败恢复不能重复实现;优先复用同一模块。 +- 类型边界使用 API Client 导出类型,不在页面重建后端响应形状。 + +## API NestJS 标准 + +- Controller 只处理认证入口、DTO、状态码、响应形状和路由。 +- 授权、Prisma、模板安装、快照组装、工作流推进必须进入 Service 或 Guard。 +- 同一个领域不要分散在根目录和 modules 中;新代码必须归入领域模块,旧 Controller 重构时逐步迁移。 +- DTO 是唯一输入边界;禁止 `Partial`、`any`、未验证 JSON 和 Controller 内私有 schema。 +- 授权测试、成功行为、失败路径和品牌隔离测试是结构重构不可删除的回归线。 + +## API Client 标准 + +- 按资源拆分方法模块和类型模块;`index.ts` 只做聚合导出和 Client 组装。 +- 一个资源定义一组类型、一组方法、一致的错误语义,不在 Client 内做页面专用逻辑。 + +## Config 与模板包标准 + +- manifest、runtime、admin 契约、示例内容分别放独立模块;避免一个大索引文件同时承载所有契约。 +- 模板字段必须声明 binding、输入类型和预览目标;模板键使用 allow-list,不接受任意字符串。 + +## 重构流程 + +1. 先建立或修改标准,再动代码。 +2. 每轮只处理一个高影响热点,保持外部行为不变。 +3. 重构后运行 `pnpm format:check`、`pnpm lint`、`pnpm typecheck`、相关测试和生产构建。 +4. 行为变化必须有测试;纯结构重构也必须保留所有授权、品牌隔离和关键 UI 状态测试。 +5. 在分支完成并全量验证后合并回 `main`。 From 7e1dd543fb90c6b1131b74544cf2ae81629b5af3 Mon Sep 17 00:00:00 2001 From: que01 Date: Mon, 12 Oct 2026 03:17:28 +0800 Subject: [PATCH 2/7] =?UTF-8?q?refactor:=20=E6=8B=86=E5=88=86=E5=B7=A5?= =?UTF-8?q?=E4=BD=9C=E5=8F=B0=E6=9F=A5=E8=AF=A2=E4=B8=8E=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E5=8F=98=E6=9B=B4=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/features/workspace/WorkspacePage.tsx | 170 +++--------------- .../features/workspace/workspace-mutations.ts | 170 ++++++++++++++++++ .../features/workspace/workspace-templates.ts | 18 ++ 3 files changed, 217 insertions(+), 141 deletions(-) create mode 100644 apps/admin/src/features/workspace/workspace-mutations.ts create mode 100644 apps/admin/src/features/workspace/workspace-templates.ts diff --git a/apps/admin/src/features/workspace/WorkspacePage.tsx b/apps/admin/src/features/workspace/WorkspacePage.tsx index d42cada..127932f 100644 --- a/apps/admin/src/features/workspace/WorkspacePage.tsx +++ b/apps/admin/src/features/workspace/WorkspacePage.tsx @@ -1,30 +1,25 @@ -import { - Button, - Card, - Form, - Input, - Modal, - Select, - Space, - Table, - Tag, - Typography, - message, -} from "antd"; -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Button, Card, Form, Input, Modal, Select, Space, Table, Tag, Typography } from "antd"; import { useNavigate } from "react-router-dom"; -import { createApiClient } from "../../lib/api.js"; import { ApiClientError } from "@personal-brand/api-client"; +import { createApiClient } from "../../lib/api.js"; import type { BrandFieldDefinition, BrandTemplateKey, InquiryForm, } from "@personal-brand/api-client"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; import { useState } from "react"; +import { + useWorkspaceQueries, + useTemplateMutations, + useFieldMutations, + useInquiryFormMutations, +} from "./workspace-mutations.js"; +import { supportsIndustry, type IndustryTarget } from "./workspace-templates.js"; import { AdminPageHeader } from "../../components/AdminPageHeader.js"; import { MutationError } from "../../components/QueryState.js"; -const inquiryFieldTypes = [ +export const inquiryFieldTypes = [ { value: "text", label: "简短文字" }, { value: "textarea", label: "详细说明" }, { value: "phone", label: "联系电话" }, @@ -36,42 +31,26 @@ const inquiryFieldTypes = [ { value: "multi-select", label: "多项选择" }, ]; -function readOptionLabel(option: unknown): string { +export function readOptionLabel(option: unknown): string { const value = option as { label?: unknown } | null | undefined; return typeof value?.label === "string" ? value.label : ""; } -function normalizeOptionLabels(options: unknown): Array<{ label: string; value: string }> { +export function normalizeOptionLabels(options: unknown): Array<{ label: string; value: string }> { return (Array.isArray(options) ? options : []) .map(readOptionLabel) .filter((label) => label.trim()) .map((label) => ({ label, value: label })); } -function supportsIndustry( - visual: { supportedIndustryTemplates?: unknown }, - industry: string, -): boolean { - return ( - Array.isArray(visual.supportedIndustryTemplates) && - visual.supportedIndustryTemplates.includes(industry) - ); -} - export function WorkspacePage() { const navigate = useNavigate(); - const client = createApiClient(); const queryClient = useQueryClient(); const [fieldOpen, setFieldOpen] = useState(false); const [formOpen, setFormOpen] = useState(false); const [editingForm, setEditingForm] = useState(null); const [visualTarget, setVisualTarget] = useState(null); - const [industryTarget, setIndustryTarget] = useState<{ - key: "personal" | "food" | "doors"; - name: string; - description: string; - capabilities: string[]; - } | null>(null); + const [industryTarget, setIndustryTarget] = useState(null); const [previewIndustry, setPreviewIndustry] = useState("personal"); const [previewVisual, setPreviewVisual] = useState("linjing-editorial"); const [form] = Form.useForm>(); @@ -89,126 +68,35 @@ export function WorkspacePage() { }); setFormOpen(true); }; - const query = useQuery({ - queryKey: ["admin-workspace"], - queryFn: () => client.getAdminWorkspace(), - }); - const runtimeQuery = useQuery({ - queryKey: ["public-runtime-workspace"], - queryFn: () => client.getPublicWorkspace(), - }); - const templateCatalog = useQuery({ - queryKey: ["template-catalog"], - queryFn: () => client.listPublicTemplates(), - }); + const { query, runtimeQuery, templateCatalog, forms, templatePreview } = useWorkspaceQueries(); const combinationPreview = useQuery({ queryKey: ["template-combination-preview", previewIndustry, previewVisual], - queryFn: () => client.previewPublicTemplateCombination(previewIndustry, previewVisual), + queryFn: () => + createApiClient().previewPublicTemplateCombination(previewIndustry, previewVisual), enabled: Boolean(templateCatalog.data), }); const compatibleVisuals = (templateCatalog.data?.visuals ?? []).filter((visual) => supportsIndustry(visual, query.data?.brand?.templateKey ?? "personal"), ); - const visualTemplate = useMutation({ - mutationFn: (key: string) => - client.updateAdminBrand({ - config: { ...(runtimeQuery.data?.brand?.config ?? {}), visualTemplateKey: key }, - }), - onSuccess: () => { - message.success("视觉模板已切换"); - void runtimeQuery.refetch(); - void queryClient.invalidateQueries({ queryKey: ["admin-brand"] }); - }, + const { visualTemplate, rollbackVisual, install, upgrade, rollback } = useTemplateMutations({ + runtimeConfig: runtimeQuery.data?.brand?.config ?? undefined, + queryClient, }); const visualHistory = useQuery({ queryKey: ["visual-template-history"], - queryFn: () => client.getAdminVisualTemplateHistory(), + queryFn: () => createApiClient().getAdminVisualTemplateHistory(), }); - const rollbackVisual = useMutation({ - mutationFn: () => client.rollbackAdminVisualTemplate(), - onSuccess: () => { - message.success("视觉模板已回滚"); - void runtimeQuery.refetch(); - void visualHistory.refetch(); - }, + const { createField, removeField } = useFieldMutations({ + form, + queryClient, + onClose: () => setFieldOpen(false), }); - const install = useMutation({ - mutationFn: (key: "personal" | "food" | "doors") => client.installAdminTemplate(key), - onSuccess: () => { - message.success("模板已安装"); - void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); - }, - }); - const createField = useMutation({ - mutationFn: (values: Omit) => - client.createAdminField(values), - onSuccess: () => { - message.success("字段已创建"); - setFieldOpen(false); - form.resetFields(); - void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); - }, - }); - const removeField = useMutation({ - mutationFn: (id: string) => client.deleteAdminField(id), - onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }), - }); - const forms = useQuery({ - queryKey: ["admin-inquiry-forms"], - queryFn: () => client.listAdminInquiryForms(), - }); - const templatePreview = useQuery({ - queryKey: ["admin-template-preview"], - queryFn: () => client.getAdminTemplateUpgradePreview(), - enabled: Boolean(query.data?.installations?.length), - }); - const upgrade = useMutation({ - mutationFn: () => client.upgradeAdminTemplate(), - onSuccess: () => { - message.success("模板已升级,已有内容未被覆盖"); - void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); - void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] }); - }, - }); - const rollback = useMutation({ - mutationFn: () => client.rollbackAdminTemplate(), - onSuccess: () => { - message.success("模板版本已回滚,现有内容未删除"); - void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); - void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] }); - }, - }); - const createForm = useMutation({ - mutationFn: (values: { - name: string; - offeringId?: string; - purpose?: InquiryForm["purpose"]; - targetType?: InquiryForm["targetType"]; - submissionAction?: InquiryForm["submissionAction"]; - fieldsSnapshot: unknown[]; - }) => client.createAdminInquiryForm(values), - onSuccess: () => { - message.success("咨询表单已创建"); - setFormOpen(false); - inquiryForm.resetFields(); - void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-forms"] }); - }, - }); - const updateForm = useMutation({ - mutationFn: ({ id, body }: { id: string; body: Partial }) => - client.updateAdminInquiryForm(id, { - ...(body.name === undefined ? {} : { name: body.name }), - ...(body.offeringId == null ? {} : { offeringId: body.offeringId }), - ...(body.fieldsSnapshot === undefined ? {} : { fieldsSnapshot: body.fieldsSnapshot }), - ...(body.isEnabled === undefined ? {} : { isEnabled: body.isEnabled }), - }), - onSuccess: () => { - message.success("咨询表单已更新"); + const { createForm, updateForm } = useInquiryFormMutations({ + form: inquiryForm, + queryClient, + onClose: () => { setFormOpen(false); setEditingForm(null); - inquiryForm.resetFields(); - void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-forms"] }); - void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] }); }, }); if (query.isLoading) return ; diff --git a/apps/admin/src/features/workspace/workspace-mutations.ts b/apps/admin/src/features/workspace/workspace-mutations.ts new file mode 100644 index 0000000..a192de6 --- /dev/null +++ b/apps/admin/src/features/workspace/workspace-mutations.ts @@ -0,0 +1,170 @@ +import { message } from "antd"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import type { FormInstance } from "antd"; +import type { + BrandFieldDefinition, + BrandTemplateKey, + InquiryForm, +} from "@personal-brand/api-client"; +import { createApiClient } from "../../lib/api.js"; + +export function useWorkspaceQueries(client = createApiClient()) { + const query = useQuery({ + queryKey: ["admin-workspace"], + queryFn: () => client.getAdminWorkspace(), + }); + const runtimeQuery = useQuery({ + queryKey: ["public-runtime-workspace"], + queryFn: () => client.getPublicWorkspace(), + }); + const templateCatalog = useQuery({ + queryKey: ["template-catalog"], + queryFn: () => client.listPublicTemplates(), + }); + const forms = useQuery({ + queryKey: ["admin-inquiry-forms"], + queryFn: () => client.listAdminInquiryForms(), + }); + const templatePreview = useQuery({ + queryKey: ["admin-template-preview"], + queryFn: () => client.getAdminTemplateUpgradePreview(), + enabled: Boolean(query.data?.installations?.length), + }); + return { query, runtimeQuery, templateCatalog, forms, templatePreview }; +} + +interface TemplateMutationOptions { + client?: ReturnType; + runtimeConfig: Record | undefined; + queryClient: { + invalidateQueries: (options: { queryKey: readonly unknown[] }) => Promise; + }; +} + +export function useTemplateMutations({ + client = createApiClient(), + runtimeConfig, + queryClient, +}: TemplateMutationOptions) { + const visualTemplate = useMutation({ + mutationFn: (key: string) => + client.updateAdminBrand({ config: { ...(runtimeConfig ?? {}), visualTemplateKey: key } }), + onSuccess: () => { + message.success("视觉模板已切换"); + void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] }); + void queryClient.invalidateQueries({ queryKey: ["admin-brand"] }); + }, + }); + const rollbackVisual = useMutation({ + mutationFn: () => client.rollbackAdminVisualTemplate(), + onSuccess: () => { + message.success("视觉模板已回滚"); + void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] }); + void queryClient.invalidateQueries({ queryKey: ["visual-template-history"] }); + }, + }); + const install = useMutation({ + mutationFn: (key: BrandTemplateKey) => client.installAdminTemplate(key), + onSuccess: () => { + message.success("模板已安装"); + void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); + }, + }); + const upgrade = useMutation({ + mutationFn: () => client.upgradeAdminTemplate(), + onSuccess: () => { + message.success("模板已升级,已有内容未被覆盖"); + void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); + void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] }); + }, + }); + const rollback = useMutation({ + mutationFn: () => client.rollbackAdminTemplate(), + onSuccess: () => { + message.success("模板版本已回滚,现有内容未删除"); + void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); + void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] }); + }, + }); + return { visualTemplate, rollbackVisual, install, upgrade, rollback }; +} + +interface FieldMutationOptions { + client?: ReturnType; + form: FormInstance>; + queryClient: { + invalidateQueries: (options: { queryKey: readonly unknown[] }) => Promise; + }; + onClose: () => void; +} + +export function useFieldMutations({ + client = createApiClient(), + form, + queryClient, + onClose, +}: FieldMutationOptions) { + const createField = useMutation({ + mutationFn: (values: Omit) => + client.createAdminField(values), + onSuccess: () => { + message.success("字段已创建"); + onClose(); + form.resetFields(); + void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); + }, + }); + const removeField = useMutation({ + mutationFn: (id: string) => client.deleteAdminField(id), + onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }), + }); + return { createField, removeField }; +} + +export function useInquiryFormMutations({ + client = createApiClient(), + form, + queryClient, + onClose, +}: { + client?: ReturnType; + form: FormInstance>; + queryClient: { + invalidateQueries: (options: { queryKey: readonly unknown[] }) => Promise; + }; + onClose: () => void; +}) { + const createForm = useMutation({ + mutationFn: (values: { + name: string; + offeringId?: string; + purpose?: InquiryForm["purpose"]; + targetType?: InquiryForm["targetType"]; + submissionAction?: InquiryForm["submissionAction"]; + fieldsSnapshot: unknown[]; + }) => client.createAdminInquiryForm(values), + onSuccess: () => { + message.success("咨询表单已创建"); + onClose(); + form.resetFields(); + void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-forms"] }); + }, + }); + const updateForm = useMutation({ + mutationFn: ({ id, body }: { id: string; body: Partial }) => + client.updateAdminInquiryForm(id, { + ...(body.name === undefined ? {} : { name: body.name }), + ...(body.offeringId == null ? {} : { offeringId: body.offeringId }), + ...(body.fieldsSnapshot === undefined ? {} : { fieldsSnapshot: body.fieldsSnapshot }), + ...(body.isEnabled === undefined ? {} : { isEnabled: body.isEnabled }), + }), + onSuccess: () => { + message.success("咨询表单已更新"); + onClose(); + form.resetFields(); + void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-forms"] }); + void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] }); + }, + }); + return { createForm, updateForm }; +} diff --git a/apps/admin/src/features/workspace/workspace-templates.ts b/apps/admin/src/features/workspace/workspace-templates.ts new file mode 100644 index 0000000..1d5e0d8 --- /dev/null +++ b/apps/admin/src/features/workspace/workspace-templates.ts @@ -0,0 +1,18 @@ +import type { BrandTemplateKey } from "@personal-brand/api-client"; + +export interface IndustryTarget { + key: BrandTemplateKey; + name: string; + description: string; + capabilities: string[]; +} + +export function supportsIndustry( + visual: { supportedIndustryTemplates?: unknown }, + industry: string, +): boolean { + return ( + Array.isArray(visual.supportedIndustryTemplates) && + visual.supportedIndustryTemplates.includes(industry) + ); +} From d0902d6568d3524b88a1e3c1e12bb54f9d632d7b Mon Sep 17 00:00:00 2001 From: que01 Date: Mon, 12 Oct 2026 03:26:43 +0800 Subject: [PATCH 3/7] =?UTF-8?q?refactor:=20=E6=8B=86=E5=88=86=E6=A8=A1?= =?UTF-8?q?=E6=9D=BF=E9=85=8D=E7=BD=AE=E5=A5=91=E7=BA=A6=E4=B8=8E=E6=B3=A8?= =?UTF-8?q?=E5=86=8C=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/adr/0023-code-structure-standards.md | 48 + packages/config/src/brand-contracts.ts | 124 +++ packages/config/src/brand-templates.ts | 139 +++ packages/config/src/capability-contracts.ts | 57 ++ packages/config/src/index.ts | 956 +----------------- packages/config/src/template-keys.ts | 3 + .../config/src/template-package-manifest.ts | 108 ++ packages/config/src/template-packages.ts | 36 + .../config/src/template-sample-content.ts | 143 +++ packages/config/src/visual-manifests.ts | 282 ++++++ packages/config/src/visual-templates.ts | 60 ++ packages/config/src/workflow.ts | 14 + 12 files changed, 1025 insertions(+), 945 deletions(-) create mode 100644 docs/adr/0023-code-structure-standards.md create mode 100644 packages/config/src/brand-contracts.ts create mode 100644 packages/config/src/brand-templates.ts create mode 100644 packages/config/src/capability-contracts.ts create mode 100644 packages/config/src/template-keys.ts create mode 100644 packages/config/src/template-package-manifest.ts create mode 100644 packages/config/src/template-packages.ts create mode 100644 packages/config/src/template-sample-content.ts create mode 100644 packages/config/src/visual-manifests.ts create mode 100644 packages/config/src/visual-templates.ts create mode 100644 packages/config/src/workflow.ts diff --git a/docs/adr/0023-code-structure-standards.md b/docs/adr/0023-code-structure-standards.md new file mode 100644 index 0000000..0991d63 --- /dev/null +++ b/docs/adr/0023-code-structure-standards.md @@ -0,0 +1,48 @@ +# 0023. 代码结构与重构标准 + +## Context + +项目已进入多模板、多品牌和完整编辑发布阶段。Admin 页面、API Client、Config 包和部分 API Controller 出现超过 500 行甚至 900 行的文件。页面组件内同时存在查询、mutation、表单同步、预览映射和业务校验;API Client 将所有资源类型和方法集中在单个文件;Config 包将契约、注册表、示例内容和查询函数混在一个索引中。这种结构已经开始增加回归风险、review 成本和模板扩展成本。 + +项目已有交付清单要求接口授权、集成测试、数据迁移、UI 状态和生产构建一起验证。但缺少专门的代码结构标准,无法在功能继续增长前约束模块边界。 + +## Decision + +建立 `docs/code-standards.md` 作为前后端共享结构标准,并按技术边界补充专门规则: + +- Admin React 页面由页面组件、hooks、纯函数领域工具、feature 组件和 shared components 组成;页面组件不承载完整 API 调用和多领域状态。 +- API Controller 只处理路由、DTO、状态码、响应形状和传输入口;授权、Prisma、模板安装、快照组装和工作流推进进入 Service 或领域模块。 +- API Client 按资源拆分类型和方法模块,`index.ts` 只做聚合导出和 Client 组装。 +- Config 与模板包按 manifest、runtime、admin 契约、示例内容、注册表和查询函数拆分。 +- 超过 500 行的文件必须给出拆分计划;超过 800 行应拆分。 +- 结构重构优先保持外部行为不变,授权测试、品牌隔离测试、API Client 测试和生产构建必须保留并通过。 + +重构在专用分支完成,必须经过相关包测试、全仓 lint、typecheck、Admin 或相关应用生产构建后合并。 + +## Alternatives + +1. 继续只在功能交付清单中约束行为:不能阻止模块继续膨胀,review 成本和冲突风险会继续上升。 +2. 引入统一组件框架或后端 CQRS 框架:改动范围过大,会打断当前产品主线,且对现有热点没有直接收益。 +3. 只按行数机械拆分:会生成缺少领域含义的小文件,降低可读性。 + +## Consequences + +### Positive + +- Admin 编辑器、工作台、业务和信任内容可以复用同一种状态与表单边界。 +- API 授权和持久化边界更容易测试。 +- API Client 和 Config 契约变更的影响面更清晰。 +- 模板新增与多品牌扩展不再依赖膨胀的单一索引。 + +### Negative + +- 短期内会出现更多文件,需要依赖明确的领域命名。 +- 旧代码迁移需要多轮完成,不能一次替换所有结构。 + +## Migration Plan + +1. 在 `refactor/code-standards` 分支先落地标准。 +2. 优先重构当前热点:品牌编辑器、工作台、API Client、Config 包和 Admin Workspace Controller。 +3. 每轮重构保持公共导出、endpoint、请求响应和授权行为兼容。 +4. 后续新增文件直接按标准执行;旧文件在改动该领域时逐步迁移。 +5. 分支通过全部相关测试和生产构建后合并回 `main`。 diff --git a/packages/config/src/brand-contracts.ts b/packages/config/src/brand-contracts.ts new file mode 100644 index 0000000..409e9b0 --- /dev/null +++ b/packages/config/src/brand-contracts.ts @@ -0,0 +1,124 @@ +import type { BrandTemplateKey } from "./template-keys.js"; +import type { CapabilityKey } from "./template-keys.js"; +import type { VisualTemplateKey } from "./template-keys.js"; + +export type BrandTemplateModuleType = "identity" | "trust" | "offering" | "inquiry" | "contact"; + +export interface BrandTemplateModuleDefinition { + key: string; + type: BrandTemplateModuleType; + title: string; + required: boolean; +} +export interface BrandTemplateFieldDefinition { + scope: string; + key: string; + label: string; + type: string; + required: boolean; +} + +export interface BrandTemplateDefinition { + key: BrandTemplateKey; + version: string; + name: string; + description: string; + serviceCategories: string[]; + trustContentTypes: string[]; + modules: BrandTemplateModuleDefinition[]; + fields: BrandTemplateFieldDefinition[]; + capabilities: CapabilityKey[]; +} + +export interface VisualTemplateDefinition { + key: VisualTemplateKey; + version: string; + name: string; + description: string; + supportedIndustryTemplates: readonly BrandTemplateKey[]; + variants: Record; + theme: { colors: Record; radius: Record }; + layout?: { home: string[]; offerings: string[]; detail: string[]; profile: string[] }; +} + +export type VisualPageKey = + "home" | "offerings" | "detail" | "inquiry" | "success" | "records" | "profile"; + +export type VisualModuleType = + | "brand-identity" + | "hero" + | "trust" + | "offering-list" + | "offering-detail" + | "inquiry-form" + | "success-summary" + | "records-list" + | "contact"; + +export interface VisualTokenSet { + colors: Record; + spacing: Record; + typography: Record; + radius: Record; + shadows?: Record; +} + +export interface VisualAssetSlot { + key: string; + label: string; + required: boolean; + kind: "image" | "icon" | "logo" | "texture"; + aspectRatio?: string; + fallback?: string; +} + +export interface VisualDataSlot { + key: string; + source: "brand" | "trust" | "offering" | "inquiry" | "records" | "profile"; + required: boolean; + description: string; +} + +export interface VisualModuleDefinition { + key: string; + type: VisualModuleType; + variant: string; + required: boolean; + dataSlots?: string[]; + assetSlots?: string[]; + capability?: CapabilityKey; +} + +export interface VisualPageDefinition { + key: VisualPageKey; + title: string; + renderer?: string; + modules: VisualModuleDefinition[]; +} + +export interface VisualTemplateManifest { + schemaVersion: "1.0"; + key: VisualTemplateKey; + version: string; + name: string; + description: string; + supportedIndustryTemplates: BrandTemplateKey[]; + brandFirst: true; + tokens: VisualTokenSet; + pages: VisualPageDefinition[]; + assets: VisualAssetSlot[]; + dataSlots: VisualDataSlot[]; + capabilities: CapabilityKey[]; +} + +export interface TemplatePackage { + manifest: VisualTemplateManifest; + industryTemplateKey: BrandTemplateKey; + content: Record; + forms: Record[]; + capabilityConfig: Record; + fixtures: { + runtime: Record; + visual: Record; + }; +} diff --git a/packages/config/src/brand-templates.ts b/packages/config/src/brand-templates.ts new file mode 100644 index 0000000..c2f546a --- /dev/null +++ b/packages/config/src/brand-templates.ts @@ -0,0 +1,139 @@ +import type { BrandTemplateKey } from "./template-keys.js"; +import type { BrandTemplateDefinition } from "./brand-contracts.js"; + +export const brandTemplates = { + personal: { + key: "personal", + version: "1.0.0", + name: "个人品牌", + description: "围绕定位、信任、作品与合作建立个人品牌。", + serviceCategories: ["consulting", "collaboration", "custom"], + trustContentTypes: [ + "profile", + "experience", + "credential", + "portfolio", + "process", + "testimonial", + ], + modules: [ + { key: "identity", type: "identity", title: "品牌身份", required: true }, + { key: "trust", type: "trust", title: "信任内容", required: true }, + { key: "offerings", type: "offering", title: "业务提供项", required: true }, + { key: "inquiry", type: "inquiry", title: "联系与咨询", required: true }, + { key: "contact", type: "contact", title: "品牌表达", required: true }, + ], + fields: [ + { scope: "profile", key: "name", label: "品牌名称", type: "text", required: true }, + { scope: "profile", key: "tagline", label: "一句话定位", type: "text", required: true }, + { scope: "profile", key: "audience", label: "服务对象", type: "textarea", required: true }, + { + scope: "profile", + key: "valueProposition", + label: "提供的价值", + type: "textarea", + required: true, + }, + { + scope: "profile", + key: "trustProof", + label: "信任证明入口", + type: "textarea", + required: true, + }, + ], + capabilities: ["offerings", "inquiry"], + }, + food: { + key: "food", + version: "1.0.0", + name: "餐饮模板", + description: "适用于餐饮服务与套餐预约的行业模板。", + serviceCategories: ["food-package", "private-chef", "custom"], + trustContentTypes: [ + "profile", + "experience", + "credential", + "portfolio", + "process", + "testimonial", + ], + modules: [ + { key: "identity", type: "identity", title: "品牌身份", required: true }, + { key: "trust", type: "trust", title: "信任内容", required: true }, + { key: "offerings", type: "offering", title: "菜单与服务", required: true }, + { key: "inquiry", type: "inquiry", title: "预约与咨询", required: true }, + { key: "contact", type: "contact", title: "品牌表达", required: true }, + ], + fields: [ + { scope: "profile", key: "name", label: "品牌名称", type: "text", required: true }, + { scope: "profile", key: "tagline", label: "一句话定位", type: "text", required: true }, + { scope: "profile", key: "audience", label: "服务对象", type: "textarea", required: true }, + { + scope: "profile", + key: "valueProposition", + label: "提供的价值", + type: "textarea", + required: true, + }, + { + scope: "profile", + key: "trustProof", + label: "信任证明入口", + type: "textarea", + required: true, + }, + ], + capabilities: ["offerings", "inquiry", "booking"], + }, + doors: { + key: "doors", + version: "1.0.0", + name: "高端门窗模板", + description: "适用于别墅门、院门、室内门与定制门窗服务的行业模板。", + serviceCategories: ["entrance-door", "garden-door", "interior-door", "custom"], + trustContentTypes: [ + "profile", + "experience", + "credential", + "portfolio", + "process", + "testimonial", + ], + modules: [ + { key: "identity", type: "identity", title: "品牌身份", required: true }, + { key: "trust", type: "trust", title: "工艺与信任", required: true }, + { key: "offerings", type: "offering", title: "门窗系列", required: true }, + { key: "inquiry", type: "inquiry", title: "设计咨询", required: true }, + { key: "contact", type: "contact", title: "品牌表达", required: true }, + ], + fields: [ + { scope: "profile", key: "name", label: "品牌名称", type: "text", required: true }, + { scope: "profile", key: "tagline", label: "一句话定位", type: "text", required: true }, + { scope: "profile", key: "audience", label: "服务对象", type: "textarea", required: true }, + { + scope: "profile", + key: "valueProposition", + label: "提供的价值", + type: "textarea", + required: true, + }, + { + scope: "profile", + key: "trustProof", + label: "信任证明入口", + type: "textarea", + required: true, + }, + ], + capabilities: ["offerings", "inquiry"], + }, +} satisfies Record; + +export function isBrandTemplateKey(value: string): value is BrandTemplateKey { + return Object.prototype.hasOwnProperty.call(brandTemplates, value); +} + +export function getBrandTemplate(key: string): BrandTemplateDefinition | undefined { + return isBrandTemplateKey(key) ? brandTemplates[key] : undefined; +} diff --git a/packages/config/src/capability-contracts.ts b/packages/config/src/capability-contracts.ts new file mode 100644 index 0000000..6e1ea17 --- /dev/null +++ b/packages/config/src/capability-contracts.ts @@ -0,0 +1,57 @@ +import type { CapabilityKey } from "./template-keys.js"; + +export interface WorkflowDefinition { + key: string; + version: string; + initialState: string; + transitions: Record; +} + +export interface CapabilityDefinition { + key: CapabilityKey; + version: string; + workflowKey?: string; +} + +export const workflowRegistry = { + "booking.basic": { + key: "booking.basic", + version: "1.0.0", + initialState: "received", + transitions: { + received: ["contacting", "cancelled"], + contacting: ["confirmed", "cancelled"], + confirmed: ["completed", "cancelled"], + completed: [], + cancelled: [], + }, + }, +} as const satisfies Record; + +export const capabilityRegistry = { + offerings: { key: "offerings", version: "1.0.0" }, + inquiry: { key: "inquiry", version: "1.0.0" }, + booking: { key: "booking", version: "1.0.0", workflowKey: "booking.basic" }, + "quote-request": { key: "quote-request", version: "1.0.0" }, +} as const satisfies Record; + +export const capabilityPlugins = { + inquiry: { + key: "inquiry", + version: "1.0.0", + displayName: "通用咨询", + purpose: "inquiry", + requiredModules: ["inquiry", "records", "success-summary"], + apiContract: "/customer/inquiry-submissions", + configSchema: "capability.inquiry.v1", + }, + "quote-request": { + key: "quote-request", + version: "1.0.0", + displayName: "报价咨询", + purpose: "quote-request", + requiredModules: ["inquiry", "records", "success-summary"], + apiContract: "/customer/inquiry-submissions", + configSchema: "capability.quote-request.v1", + }, +} as const; diff --git a/packages/config/src/index.ts b/packages/config/src/index.ts index e98155b..84fd8c1 100644 --- a/packages/config/src/index.ts +++ b/packages/config/src/index.ts @@ -1,946 +1,12 @@ +export * from "./brand-contracts.js"; +export * from "./brand-templates.js"; +export * from "./capability-contracts.js"; +export * from "./template-keys.js"; +export * from "./template-packages.js"; +export * from "./template-package-manifest.js"; +export * from "./template-sample-content.js"; +export * from "./visual-manifests.js"; +export * from "./visual-templates.js"; +export * from "./workflow.js"; + export const configPackageName = "personal-brand-config"; - -import { generatedTemplatePackageRegistry } from "./generated-template-packages.js"; - -export type BrandTemplateKey = "personal" | "food" | "doors"; -export type VisualTemplateKey = "linjing-editorial" | "acheng-campus-food"; -export type CapabilityKey = "offerings" | "inquiry" | "booking" | "quote-request"; - -export interface WorkflowDefinition { - key: string; - version: string; - initialState: string; - transitions: Record; -} - -export interface CapabilityDefinition { - key: CapabilityKey; - version: string; - workflowKey?: string; -} - -export const workflowRegistry = { - "booking.basic": { - key: "booking.basic", - version: "1.0.0", - initialState: "received", - transitions: { - received: ["contacting", "cancelled"], - contacting: ["confirmed", "cancelled"], - confirmed: ["completed", "cancelled"], - completed: [], - cancelled: [], - }, - }, -} as const satisfies Record; - -export const capabilityRegistry = { - offerings: { key: "offerings", version: "1.0.0" }, - inquiry: { key: "inquiry", version: "1.0.0" }, - booking: { key: "booking", version: "1.0.0", workflowKey: "booking.basic" }, - "quote-request": { key: "quote-request", version: "1.0.0" }, -} as const satisfies Record; - -export const capabilityPlugins = { - inquiry: { - key: "inquiry", - version: "1.0.0", - displayName: "通用咨询", - purpose: "inquiry", - requiredModules: ["inquiry", "records", "success-summary"], - apiContract: "/customer/inquiry-submissions", - configSchema: "capability.inquiry.v1", - }, - "quote-request": { - key: "quote-request", - version: "1.0.0", - displayName: "报价咨询", - purpose: "quote-request", - requiredModules: ["inquiry", "records", "success-summary"], - apiContract: "/customer/inquiry-submissions", - configSchema: "capability.quote-request.v1", - }, -} as const; - -export type BrandTemplateModuleType = "identity" | "trust" | "offering" | "inquiry" | "contact"; - -export interface BrandTemplateModuleDefinition { - key: string; - type: BrandTemplateModuleType; - title: string; - required: boolean; -} -export interface BrandTemplateFieldDefinition { - scope: string; - key: string; - label: string; - type: string; - required: boolean; -} - -export interface BrandTemplateDefinition { - key: BrandTemplateKey; - version: string; - name: string; - description: string; - serviceCategories: string[]; - trustContentTypes: string[]; - modules: BrandTemplateModuleDefinition[]; - fields: BrandTemplateFieldDefinition[]; - capabilities: CapabilityKey[]; -} - -export interface VisualTemplateDefinition { - key: VisualTemplateKey; - version: string; - name: string; - description: string; - supportedIndustryTemplates: readonly BrandTemplateKey[]; - variants: Record; - theme: { colors: Record; radius: Record }; - layout?: { home: string[]; offerings: string[]; detail: string[]; profile: string[] }; -} - -export type VisualPageKey = - "home" | "offerings" | "detail" | "inquiry" | "success" | "records" | "profile"; - -export type VisualModuleType = - | "brand-identity" - | "hero" - | "trust" - | "offering-list" - | "offering-detail" - | "inquiry-form" - | "success-summary" - | "records-list" - | "contact"; - -export interface VisualTokenSet { - colors: Record; - spacing: Record; - typography: Record; - radius: Record; - shadows?: Record; -} - -export interface VisualAssetSlot { - key: string; - label: string; - required: boolean; - kind: "image" | "icon" | "logo" | "texture"; - aspectRatio?: string; - fallback?: string; -} - -export interface VisualDataSlot { - key: string; - source: "brand" | "trust" | "offering" | "inquiry" | "records" | "profile"; - required: boolean; - description: string; -} - -export interface VisualModuleDefinition { - key: string; - type: VisualModuleType; - variant: string; - required: boolean; - dataSlots?: string[]; - assetSlots?: string[]; - capability?: CapabilityKey; -} - -export interface VisualPageDefinition { - key: VisualPageKey; - title: string; - renderer?: string; - modules: VisualModuleDefinition[]; -} - -export interface VisualTemplateManifest { - schemaVersion: "1.0"; - key: VisualTemplateKey; - version: string; - name: string; - description: string; - supportedIndustryTemplates: BrandTemplateKey[]; - brandFirst: true; - tokens: VisualTokenSet; - pages: VisualPageDefinition[]; - assets: VisualAssetSlot[]; - dataSlots: VisualDataSlot[]; - capabilities: CapabilityKey[]; -} - -export interface TemplatePackage { - manifest: VisualTemplateManifest; - industryTemplateKey: BrandTemplateKey; - content: Record; - forms: Record[]; - capabilityConfig: Record; - fixtures: { - runtime: Record; - visual: Record; - }; -} - -export interface TemplatePackageManifest { - packageKey: string; - version: string; - displayName: string; - visualTemplateKey: VisualTemplateKey; - runtimeContract: "1.0"; - supportedIndustryTemplates: readonly BrandTemplateKey[]; - entrypoints: Readonly>; - requiredCapabilities: readonly CapabilityKey[]; - defaultBrandSlug: string; - navigation: readonly { - key: string; - label: string; - page: string; - iconPath?: string; - selectedIconPath?: string; - }[]; - renderers: Readonly>; - runtimeOwnedPages: readonly string[]; - dataSlots: readonly { - key: string; - source: string; - required: boolean; - description: string; - }[]; - templateFields?: readonly { - key: string; - page?: string; - binding?: string; - label: string; - help?: string; - input: string; - itemFields?: readonly { key: string; label: string; input?: string; required?: boolean }[]; - itemValueKey?: string; - required?: boolean; - maxLength?: number; - placeholder?: string; - options?: readonly { value: string; label: string }[]; - }[]; - assetSlots: readonly { - key: string; - binding: string; - target: "brand" | "offering" | "trust"; - label: string; - help: string; - required: boolean; - }[]; - admin: { - sections: readonly { - key: string; - title: string; - description: string; - page: string; - target: "brand" | "offering" | "trust" | "inquiry"; - previewTargets?: readonly { - key: string; - label: string; - composite?: boolean; - children?: readonly string[]; - }[]; - fields: readonly { - key: string; - binding: string; - label: string; - input: string; - help?: string; - required?: boolean; - itemFields?: readonly { key: string; label: string; input?: string; required?: boolean }[]; - itemValueKey?: string; - maxLength?: number; - placeholder?: string; - options?: readonly { value: string; label: string }[]; - previewTarget?: string; - }[]; - }[]; - }; - trustContentTypes?: readonly { - type: string; - label: string; - adminFields: { - title: string; - summary: string; - content: string; - summaryHelp?: string; - summaryPlaceholder?: string; - }; - help?: string; - placeholder?: string; - required?: boolean; - maxPublishedItems?: number; - hideStandardFields?: readonly ("summary" | "content")[]; - configFields?: readonly { - key: string; - binding: string; - label: string; - input: string; - itemFields?: readonly { key: string; label: string; input?: string; required?: boolean }[]; - itemValueKey?: string; - required?: boolean; - }[]; - }[]; - sampleContent?: Partial>; -} - -export const templatePackageRegistry: readonly TemplatePackageManifest[] = - generatedTemplatePackageRegistry; - -export function getTemplatePackageManifest(key: string): TemplatePackageManifest | undefined { - return templatePackageRegistry.find((item) => item.packageKey === key); -} - -export function getTemplatePackageManifestForVisualKey( - visualTemplateKey: string, -): TemplatePackageManifest | undefined { - return templatePackageRegistry.find((item) => item.visualTemplateKey === visualTemplateKey); -} - -export function validateTemplatePackageManifest(manifest: TemplatePackageManifest): string[] { - const errors: string[] = []; - if (!manifest.packageKey.trim()) errors.push("packageKey is required"); - if (!manifest.version.trim()) errors.push("version is required"); - if (manifest.runtimeContract !== "1.0") errors.push("unsupported runtimeContract"); - if (!manifest.supportedIndustryTemplates.length) - errors.push("supportedIndustryTemplates must not be empty"); - for (const page of [ - "home", - "offerings", - "detail", - "inquiry", - "success", - "records", - "profile", - ] as const) { - if (!manifest.entrypoints[page]?.trim()) errors.push(`entrypoints.${page} is required`); - } - return errors; -} - -export interface TemplateSampleContent { - templateKey: BrandTemplateKey; - inquiryFormName: string; - offerings: Array<{ - kind: "service" | "product" | "package" | "subscription"; - name: string; - summary: string; - categoryKey: string; - }>; - trustContent: Array<{ - type: string; - title: string; - content: string; - summary?: string; - config?: Record; - }>; - fields: Array<{ - key: string; - label: string; - type: string; - required: boolean; - options?: Array<{ label: string; value: string }>; - }>; - capabilityKey: string; -} - -const doorsSampleContent: TemplateSampleContent = { - templateKey: "doors", - inquiryFormName: "门系统咨询表单", - offerings: [ - { - kind: "product", - name: "序章·入户门", - summary: "为别墅入口定制的整樘门系统", - categoryKey: "entrance-door", - }, - { - kind: "product", - name: "庭院·边界门", - summary: "连接建筑与庭院的定制门", - categoryKey: "garden-door", - }, - { - kind: "product", - name: "室内·静谧门", - summary: "统一室内空间秩序的户内门", - categoryKey: "interior-door", - }, - { - kind: "service", - name: "一对一门系统设计咨询", - summary: "从现场到方案的完整设计沟通", - categoryKey: "custom", - }, - ], - trustContent: [ - { type: "credential", title: "主理人的门作观", content: "示例内容,待品牌主理人完善。" }, - { type: "case", title: "别墅门系统案例", content: "示例内容,待品牌主理人完善。" }, - { type: "process", title: "从测量到交付", content: "示例内容,待品牌主理人完善。" }, - { type: "credential", title: "材料与工艺标准", content: "示例内容,待品牌主理人完善。" }, - ], - fields: [ - { key: "projectType", label: "项目类型", type: "select", required: false }, - { key: "projectStage", label: "项目阶段", type: "select", required: false }, - { key: "siteDescription", label: "项目概况", type: "textarea", required: false }, - { key: "phone", label: "联系方式", type: "phone", required: true }, - ], - capabilityKey: "doors", -}; - -const foodSampleContent: TemplateSampleContent = { - templateKey: "food", - inquiryFormName: "餐品预订与定制表单", - offerings: [ - { - kind: "package", - name: "示例·今日套餐", - summary: "现做家常套餐示例内容。", - categoryKey: "set-meal", - }, - { - kind: "service", - name: "示例·聚餐定制", - summary: "按人数和口味沟通定制餐品。", - categoryKey: "private-chef", - }, - ], - trustContent: [ - { type: "credential", title: "关于主理人", content: "示例内容,待品牌主理人完善。" }, - { type: "process", title: "从预订到取餐", content: "示例内容,待品牌主理人完善。" }, - ], - fields: [ - { key: "date", label: "用餐日期", type: "date", required: true }, - { key: "number", label: "用餐人数", type: "number", required: true }, - { key: "phone", label: "联系方式", type: "phone", required: true }, - ], - capabilityKey: "booking", -}; - -const personalSampleContent: TemplateSampleContent = { - templateKey: "personal", - inquiryFormName: "合作咨询表单", - offerings: [ - { - kind: "service", - name: "示例·品牌定位咨询", - summary: "梳理品牌定位与下一步行动。", - categoryKey: "consulting", - }, - { - kind: "service", - name: "示例·长期顾问支持", - summary: "围绕表达和转化提供持续支持。", - categoryKey: "advisory", - }, - ], - trustContent: [ - { type: "credential", title: "关于主理人", content: "示例内容,待品牌主理人完善。" }, - { type: "process", title: "合作方法", content: "示例内容,待品牌主理人完善。" }, - ], - fields: [ - { key: "name", label: "您的称呼", type: "text", required: true }, - { key: "phone", label: "联系方式", type: "phone", required: true }, - { key: "remark", label: "合作需求", type: "textarea", required: true }, - ], - capabilityKey: "inquiry", -}; - -export const templateSampleContent: Record = { - personal: personalSampleContent, - food: foodSampleContent, - doors: doorsSampleContent, -}; - -export function getTemplateSampleContent(templateKey: string): TemplateSampleContent | undefined { - const packageSample = templatePackageRegistry.find((item) => - item.supportedIndustryTemplates.includes(templateKey as BrandTemplateKey), - )?.sampleContent?.[templateKey as BrandTemplateKey]; - return packageSample ?? templateSampleContent[templateKey as keyof typeof templateSampleContent]; -} - -const linjingEditorialManifest: VisualTemplateManifest = { - schemaVersion: "1.0", - key: "linjing-editorial", - version: "1.0.0", - name: "林境建筑画册", - description: "以个人品牌信任为主线、以高端项目作品为表达重点的编辑式视觉模板。", - supportedIndustryTemplates: ["personal", "doors"], - brandFirst: true, - tokens: { - colors: { - background: "#F7F5F1", - surface: "#FFFFFF", - foreground: "#252525", - muted: "#77736C", - accent: "#8A6846", - dark: "#202221", - }, - spacing: { page: "32rpx", section: "56rpx", module: "24rpx" }, - typography: { display: "56rpx", heading: "36rpx", body: "28rpx", caption: "22rpx" }, - radius: { card: "16rpx", button: "999rpx", media: "12rpx" }, - shadows: { card: "0 8rpx 32rpx rgba(32,34,33,0.08)" }, - }, - assets: [ - { key: "brand.logo", label: "品牌标志", required: false, kind: "logo" }, - { - key: "home.hero", - label: "首页首屏图", - required: true, - kind: "image", - aspectRatio: "16:9", - }, - { - key: "offering.cover", - label: "业务提供项封面", - required: true, - kind: "image", - aspectRatio: "1:1", - }, - { - key: "profile.portrait", - label: "主理人肖像", - required: false, - kind: "image", - aspectRatio: "1:1", - }, - { key: "brand.texture", label: "品牌底纹", required: false, kind: "texture" }, - ], - dataSlots: [ - { - key: "brand.identity", - source: "brand", - required: true, - description: "品牌名、定位和主理人身份", - }, - { key: "brand.hero", source: "brand", required: true, description: "品牌首屏表达和行动入口" }, - { key: "trust.proof", source: "trust", required: true, description: "经历、资质、案例和方法" }, - { - key: "offerings.list", - source: "offering", - required: true, - description: "可展示的业务提供项", - }, - { - key: "offering.detail", - source: "offering", - required: true, - description: "单个提供项的详情内容", - }, - { key: "inquiry.form", source: "inquiry", required: true, description: "品牌咨询或预约表单" }, - { - key: "records.items", - source: "records", - required: true, - description: "用户提交后的跟进记录", - }, - { - key: "profile.contact", - source: "profile", - required: true, - description: "联系方式和合作预期", - }, - ], - pages: [ - { - key: "home", - title: "首页", - renderer: "linjing-home", - modules: [ - { - key: "identity", - type: "brand-identity", - variant: "editorial-card", - required: true, - dataSlots: ["brand.identity"], - assetSlots: ["brand.logo"], - }, - { - key: "hero", - type: "hero", - variant: "architectural", - required: true, - dataSlots: ["brand.hero"], - assetSlots: ["home.hero"], - }, - { - key: "proof", - type: "trust", - variant: "proof-strip", - required: true, - dataSlots: ["trust.proof"], - }, - { - key: "offerings", - type: "offering-list", - variant: "editorial-list", - required: true, - dataSlots: ["offerings.list"], - assetSlots: ["offering.cover"], - capability: "offerings", - }, - { - key: "contact", - type: "contact", - variant: "quiet-footer", - required: true, - dataSlots: ["profile.contact"], - }, - ], - }, - { - key: "offerings", - title: "业务提供项", - renderer: "linjing-offerings", - modules: [ - { - key: "offerings", - type: "offering-list", - variant: "editorial-grid", - required: true, - dataSlots: ["offerings.list"], - assetSlots: ["offering.cover"], - capability: "offerings", - }, - ], - }, - { - key: "detail", - title: "提供项详情", - renderer: "linjing-offering-detail", - modules: [ - { - key: "detail", - type: "offering-detail", - variant: "project-case", - required: true, - dataSlots: ["offering.detail"], - assetSlots: ["offering.cover"], - capability: "offerings", - }, - ], - }, - { - key: "inquiry", - title: "咨询与预约", - renderer: "linjing-inquiry", - modules: [ - { - key: "inquiry", - type: "inquiry-form", - variant: "editorial-form", - required: true, - dataSlots: ["inquiry.form"], - capability: "inquiry", - }, - ], - }, - { - key: "success", - title: "提交成功", - renderer: "linjing-success", - modules: [ - { - key: "success", - type: "success-summary", - variant: "editorial-confirmation", - required: true, - dataSlots: ["brand.identity"], - }, - ], - }, - { - key: "records", - title: "我的记录", - renderer: "linjing-records", - modules: [ - { - key: "records", - type: "records-list", - variant: "timeline", - required: true, - dataSlots: ["records.items"], - }, - ], - }, - { - key: "profile", - title: "主理人与我", - renderer: "linjing-profile", - modules: [ - { - key: "identity", - type: "brand-identity", - variant: "profile-editorial", - required: true, - dataSlots: ["brand.identity"], - assetSlots: ["profile.portrait"], - }, - { - key: "contact", - type: "contact", - variant: "contact-sheet", - required: true, - dataSlots: ["profile.contact"], - }, - ], - }, - ], - capabilities: ["offerings", "inquiry"], -}; - -export const visualTemplateManifests: Record = { - "linjing-editorial": linjingEditorialManifest, - "acheng-campus-food": { - ...linjingEditorialManifest, - key: "acheng-campus-food", - version: "1.0.0", - name: "阿成校园餐", - description: "面向校园餐饮摊贩的菜单、出摊动态和团体预订视觉模板。", - supportedIndustryTemplates: ["food"], - tokens: { - ...linjingEditorialManifest.tokens, - colors: { - background: "#FFF8F0", - surface: "#FFFFFF", - foreground: "#29231F", - muted: "#7A6A60", - accent: "#E87532", - dark: "#3B2118", - }, - radius: { card: "24rpx", button: "999rpx", media: "20rpx" }, - }, - pages: linjingEditorialManifest.pages.map((pageDefinition) => { - const renderer = - pageDefinition.key === "home" - ? "acheng-home" - : pageDefinition.key === "offerings" - ? "acheng-offerings" - : pageDefinition.key === "profile" - ? "acheng-profile" - : pageDefinition.renderer; - return renderer ? { ...pageDefinition, renderer } : pageDefinition; - }), - capabilities: ["offerings", "inquiry", "booking"], - }, -}; - -export function getVisualTemplateManifest(key: string): VisualTemplateManifest | undefined { - return visualTemplateManifests[key as VisualTemplateKey]; -} - -export function isVisualTemplateCompatible( - visualTemplate: VisualTemplateDefinition | VisualTemplateManifest, - industryTemplateKey: string, -): boolean { - return visualTemplate.supportedIndustryTemplates.includes( - industryTemplateKey as BrandTemplateKey, - ); -} - -export const visualTemplates: Record = { - "linjing-editorial": { - key: "linjing-editorial", - version: "1.0.0", - name: "林境建筑画册", - description: "适合高端定制、建筑作品和项目型个人品牌。", - supportedIndustryTemplates: ["personal", "doors"], - variants: { hero: "architectural", offeringList: "editorial", detail: "project-case" }, - theme: { - colors: { background: "#F7F5F1", foreground: "#252525", accent: "#8A6846", dark: "#202221" }, - radius: { card: "16rpx" }, - }, - layout: { - home: ["founder-card", "brand-hero", "trust-proof", "trust-manifesto", "offering-list"], - offerings: ["offering-list"], - detail: ["offering-detail"], - profile: ["profile"], - }, - }, - "acheng-campus-food": { - key: "acheng-campus-food", - version: "1.0.0", - name: "阿成校园餐", - description: "适合校园餐饮、套餐预订和团体定制的暖橙菜单视觉。", - supportedIndustryTemplates: ["food"], - variants: { hero: "stall-board", offeringList: "menu-card", detail: "dish-detail" }, - theme: { - colors: { background: "#FFF8F0", foreground: "#29231F", accent: "#E87532", dark: "#3B2118" }, - radius: { card: "24rpx" }, - }, - layout: { - home: ["founder-card", "brand-hero", "trust-proof", "offering-list"], - offerings: ["offering-list"], - detail: ["offering-detail"], - profile: ["profile"], - }, - }, -}; - -export function listVisualTemplateKeys(): VisualTemplateKey[] { - return Object.keys(visualTemplates) as VisualTemplateKey[]; -} - -export function getVisualTemplate(key: string): VisualTemplateDefinition | undefined { - return visualTemplates[key as VisualTemplateKey]; -} - -export function getDefaultVisualTemplateKey(industryTemplateKey: string): VisualTemplateKey { - return ( - listVisualTemplateKeys().find((key) => - visualTemplates[key].supportedIndustryTemplates.includes( - industryTemplateKey as BrandTemplateKey, - ), - ) ?? "linjing-editorial" - ); -} - -export function canTransitionWorkflow(workflowKey: string, from: string, to: string): boolean { - const workflow = workflowRegistry[workflowKey as keyof typeof workflowRegistry] as - WorkflowDefinition | undefined; - return workflow ? from === to || workflow.transitions[from]?.includes(to) === true : false; -} - -export function resolveCapabilities(keys: readonly CapabilityKey[]): CapabilityDefinition[] { - return keys.map((key) => capabilityRegistry[key]); -} - -export const brandTemplates = { - personal: { - key: "personal", - version: "1.0.0", - name: "个人品牌", - description: "围绕定位、信任、作品与合作建立个人品牌。", - serviceCategories: ["consulting", "collaboration", "custom"], - trustContentTypes: [ - "profile", - "experience", - "credential", - "portfolio", - "process", - "testimonial", - ], - modules: [ - { key: "identity", type: "identity", title: "品牌身份", required: true }, - { key: "trust", type: "trust", title: "信任内容", required: true }, - { key: "offerings", type: "offering", title: "业务提供项", required: true }, - { key: "inquiry", type: "inquiry", title: "联系与咨询", required: true }, - { key: "contact", type: "contact", title: "品牌表达", required: true }, - ], - fields: [ - { scope: "profile", key: "name", label: "品牌名称", type: "text", required: true }, - { scope: "profile", key: "tagline", label: "一句话定位", type: "text", required: true }, - { scope: "profile", key: "audience", label: "服务对象", type: "textarea", required: true }, - { - scope: "profile", - key: "valueProposition", - label: "提供的价值", - type: "textarea", - required: true, - }, - { - scope: "profile", - key: "trustProof", - label: "信任证明入口", - type: "textarea", - required: true, - }, - ], - capabilities: ["offerings", "inquiry"], - }, - food: { - key: "food", - version: "1.0.0", - name: "餐饮模板", - description: "适用于餐饮服务与套餐预约的行业模板。", - serviceCategories: ["food-package", "private-chef", "custom"], - trustContentTypes: [ - "profile", - "experience", - "credential", - "portfolio", - "process", - "testimonial", - ], - modules: [ - { key: "identity", type: "identity", title: "品牌身份", required: true }, - { key: "trust", type: "trust", title: "信任内容", required: true }, - { key: "offerings", type: "offering", title: "菜单与服务", required: true }, - { key: "inquiry", type: "inquiry", title: "预约与咨询", required: true }, - { key: "contact", type: "contact", title: "品牌表达", required: true }, - ], - fields: [ - { scope: "profile", key: "name", label: "品牌名称", type: "text", required: true }, - { scope: "profile", key: "tagline", label: "一句话定位", type: "text", required: true }, - { scope: "profile", key: "audience", label: "服务对象", type: "textarea", required: true }, - { - scope: "profile", - key: "valueProposition", - label: "提供的价值", - type: "textarea", - required: true, - }, - { - scope: "profile", - key: "trustProof", - label: "信任证明入口", - type: "textarea", - required: true, - }, - ], - capabilities: ["offerings", "inquiry", "booking"], - }, - doors: { - key: "doors", - version: "1.0.0", - name: "高端门窗模板", - description: "适用于别墅门、院门、室内门与定制门窗服务的行业模板。", - serviceCategories: ["entrance-door", "garden-door", "interior-door", "custom"], - trustContentTypes: [ - "profile", - "experience", - "credential", - "portfolio", - "process", - "testimonial", - ], - modules: [ - { key: "identity", type: "identity", title: "品牌身份", required: true }, - { key: "trust", type: "trust", title: "工艺与信任", required: true }, - { key: "offerings", type: "offering", title: "门窗系列", required: true }, - { key: "inquiry", type: "inquiry", title: "设计咨询", required: true }, - { key: "contact", type: "contact", title: "品牌表达", required: true }, - ], - fields: [ - { scope: "profile", key: "name", label: "品牌名称", type: "text", required: true }, - { scope: "profile", key: "tagline", label: "一句话定位", type: "text", required: true }, - { scope: "profile", key: "audience", label: "服务对象", type: "textarea", required: true }, - { - scope: "profile", - key: "valueProposition", - label: "提供的价值", - type: "textarea", - required: true, - }, - { - scope: "profile", - key: "trustProof", - label: "信任证明入口", - type: "textarea", - required: true, - }, - ], - capabilities: ["offerings", "inquiry"], - }, -} satisfies Record; - -export function isBrandTemplateKey(value: string): value is BrandTemplateKey { - return Object.prototype.hasOwnProperty.call(brandTemplates, value); -} - -export function getBrandTemplate(key: string): BrandTemplateDefinition | undefined { - return isBrandTemplateKey(key) ? brandTemplates[key] : undefined; -} diff --git a/packages/config/src/template-keys.ts b/packages/config/src/template-keys.ts new file mode 100644 index 0000000..37a9855 --- /dev/null +++ b/packages/config/src/template-keys.ts @@ -0,0 +1,3 @@ +export type BrandTemplateKey = "personal" | "food" | "doors"; +export type VisualTemplateKey = "linjing-editorial" | "acheng-campus-food"; +export type CapabilityKey = "offerings" | "inquiry" | "booking" | "quote-request"; diff --git a/packages/config/src/template-package-manifest.ts b/packages/config/src/template-package-manifest.ts new file mode 100644 index 0000000..be9b321 --- /dev/null +++ b/packages/config/src/template-package-manifest.ts @@ -0,0 +1,108 @@ +import type { BrandTemplateKey } from "./template-keys.js"; +import type { CapabilityKey } from "./template-keys.js"; +import type { VisualTemplateKey } from "./template-keys.js"; +import type { TemplateSampleContent } from "./template-sample-content.js"; + +export interface TemplatePackageManifest { + packageKey: string; + version: string; + displayName: string; + visualTemplateKey: VisualTemplateKey; + runtimeContract: "1.0"; + supportedIndustryTemplates: readonly BrandTemplateKey[]; + entrypoints: Readonly>; + requiredCapabilities: readonly CapabilityKey[]; + defaultBrandSlug: string; + navigation: readonly { + key: string; + label: string; + page: string; + iconPath?: string; + selectedIconPath?: string; + }[]; + renderers: Readonly>; + runtimeOwnedPages: readonly string[]; + dataSlots: readonly { + key: string; + source: string; + required: boolean; + description: string; + }[]; + templateFields?: readonly { + key: string; + page?: string; + binding?: string; + label: string; + help?: string; + input: string; + itemFields?: readonly { key: string; label: string; input?: string; required?: boolean }[]; + itemValueKey?: string; + required?: boolean; + maxLength?: number; + placeholder?: string; + options?: readonly { value: string; label: string }[]; + }[]; + assetSlots: readonly { + key: string; + binding: string; + target: "brand" | "offering" | "trust"; + label: string; + help: string; + required: boolean; + }[]; + admin: { + sections: readonly { + key: string; + title: string; + description: string; + page: string; + target: "brand" | "offering" | "trust" | "inquiry"; + previewTargets?: readonly { + key: string; + label: string; + composite?: boolean; + children?: readonly string[]; + }[]; + fields: readonly { + key: string; + binding: string; + label: string; + input: string; + help?: string; + required?: boolean; + itemFields?: readonly { key: string; label: string; input?: string; required?: boolean }[]; + itemValueKey?: string; + maxLength?: number; + placeholder?: string; + options?: readonly { value: string; label: string }[]; + previewTarget?: string; + }[]; + }[]; + }; + trustContentTypes?: readonly { + type: string; + label: string; + adminFields: { + title: string; + summary: string; + content: string; + summaryHelp?: string; + summaryPlaceholder?: string; + }; + help?: string; + placeholder?: string; + required?: boolean; + maxPublishedItems?: number; + hideStandardFields?: readonly ("summary" | "content")[]; + configFields?: readonly { + key: string; + binding: string; + label: string; + input: string; + itemFields?: readonly { key: string; label: string; input?: string; required?: boolean }[]; + itemValueKey?: string; + required?: boolean; + }[]; + }[]; + sampleContent?: Partial>; +} diff --git a/packages/config/src/template-packages.ts b/packages/config/src/template-packages.ts new file mode 100644 index 0000000..bfd52ae --- /dev/null +++ b/packages/config/src/template-packages.ts @@ -0,0 +1,36 @@ +import { generatedTemplatePackageRegistry } from "./generated-template-packages.js"; +import type { TemplatePackageManifest } from "./template-package-manifest.js"; + +export const templatePackageRegistry: readonly TemplatePackageManifest[] = + generatedTemplatePackageRegistry; + +export function getTemplatePackageManifest(key: string): TemplatePackageManifest | undefined { + return templatePackageRegistry.find((item) => item.packageKey === key); +} + +export function getTemplatePackageManifestForVisualKey( + visualTemplateKey: string, +): TemplatePackageManifest | undefined { + return templatePackageRegistry.find((item) => item.visualTemplateKey === visualTemplateKey); +} + +export function validateTemplatePackageManifest(manifest: TemplatePackageManifest): string[] { + const errors: string[] = []; + if (!manifest.packageKey.trim()) errors.push("packageKey is required"); + if (!manifest.version.trim()) errors.push("version is required"); + if (manifest.runtimeContract !== "1.0") errors.push("unsupported runtimeContract"); + if (!manifest.supportedIndustryTemplates.length) + errors.push("supportedIndustryTemplates must not be empty"); + for (const page of [ + "home", + "offerings", + "detail", + "inquiry", + "success", + "records", + "profile", + ] as const) { + if (!manifest.entrypoints[page]?.trim()) errors.push(`entrypoints.${page} is required`); + } + return errors; +} diff --git a/packages/config/src/template-sample-content.ts b/packages/config/src/template-sample-content.ts new file mode 100644 index 0000000..813bad7 --- /dev/null +++ b/packages/config/src/template-sample-content.ts @@ -0,0 +1,143 @@ +import type { BrandTemplateKey } from "./template-keys.js"; +import { templatePackageRegistry } from "./template-packages.js"; + +export interface TemplateSampleContent { + templateKey: BrandTemplateKey; + inquiryFormName: string; + offerings: Array<{ + kind: "service" | "product" | "package" | "subscription"; + name: string; + summary: string; + categoryKey: string; + }>; + trustContent: Array<{ + type: string; + title: string; + content: string; + summary?: string; + config?: Record; + }>; + fields: Array<{ + key: string; + label: string; + type: string; + required: boolean; + options?: Array<{ label: string; value: string }>; + }>; + capabilityKey: string; +} + +const doorsSampleContent: TemplateSampleContent = { + templateKey: "doors", + inquiryFormName: "门系统咨询表单", + offerings: [ + { + kind: "product", + name: "序章·入户门", + summary: "为别墅入口定制的整樘门系统", + categoryKey: "entrance-door", + }, + { + kind: "product", + name: "庭院·边界门", + summary: "连接建筑与庭院的定制门", + categoryKey: "garden-door", + }, + { + kind: "product", + name: "室内·静谧门", + summary: "统一室内空间秩序的户内门", + categoryKey: "interior-door", + }, + { + kind: "service", + name: "一对一门系统设计咨询", + summary: "从现场到方案的完整设计沟通", + categoryKey: "custom", + }, + ], + trustContent: [ + { type: "credential", title: "主理人的门作观", content: "示例内容,待品牌主理人完善。" }, + { type: "case", title: "别墅门系统案例", content: "示例内容,待品牌主理人完善。" }, + { type: "process", title: "从测量到交付", content: "示例内容,待品牌主理人完善。" }, + { type: "credential", title: "材料与工艺标准", content: "示例内容,待品牌主理人完善。" }, + ], + fields: [ + { key: "projectType", label: "项目类型", type: "select", required: false }, + { key: "projectStage", label: "项目阶段", type: "select", required: false }, + { key: "siteDescription", label: "项目概况", type: "textarea", required: false }, + { key: "phone", label: "联系方式", type: "phone", required: true }, + ], + capabilityKey: "doors", +}; + +const foodSampleContent: TemplateSampleContent = { + templateKey: "food", + inquiryFormName: "餐品预订与定制表单", + offerings: [ + { + kind: "package", + name: "示例·今日套餐", + summary: "现做家常套餐示例内容。", + categoryKey: "set-meal", + }, + { + kind: "service", + name: "示例·聚餐定制", + summary: "按人数和口味沟通定制餐品。", + categoryKey: "private-chef", + }, + ], + trustContent: [ + { type: "credential", title: "关于主理人", content: "示例内容,待品牌主理人完善。" }, + { type: "process", title: "从预订到取餐", content: "示例内容,待品牌主理人完善。" }, + ], + fields: [ + { key: "date", label: "用餐日期", type: "date", required: true }, + { key: "number", label: "用餐人数", type: "number", required: true }, + { key: "phone", label: "联系方式", type: "phone", required: true }, + ], + capabilityKey: "booking", +}; + +const personalSampleContent: TemplateSampleContent = { + templateKey: "personal", + inquiryFormName: "合作咨询表单", + offerings: [ + { + kind: "service", + name: "示例·品牌定位咨询", + summary: "梳理品牌定位与下一步行动。", + categoryKey: "consulting", + }, + { + kind: "service", + name: "示例·长期顾问支持", + summary: "围绕表达和转化提供持续支持。", + categoryKey: "advisory", + }, + ], + trustContent: [ + { type: "credential", title: "关于主理人", content: "示例内容,待品牌主理人完善。" }, + { type: "process", title: "合作方法", content: "示例内容,待品牌主理人完善。" }, + ], + fields: [ + { key: "name", label: "您的称呼", type: "text", required: true }, + { key: "phone", label: "联系方式", type: "phone", required: true }, + { key: "remark", label: "合作需求", type: "textarea", required: true }, + ], + capabilityKey: "inquiry", +}; + +export const templateSampleContent: Record = { + personal: personalSampleContent, + food: foodSampleContent, + doors: doorsSampleContent, +}; + +export function getTemplateSampleContent(templateKey: string): TemplateSampleContent | undefined { + const packageSample = templatePackageRegistry.find((item) => + item.supportedIndustryTemplates.includes(templateKey as BrandTemplateKey), + )?.sampleContent?.[templateKey as BrandTemplateKey]; + return packageSample ?? templateSampleContent[templateKey as keyof typeof templateSampleContent]; +} diff --git a/packages/config/src/visual-manifests.ts b/packages/config/src/visual-manifests.ts new file mode 100644 index 0000000..1b80009 --- /dev/null +++ b/packages/config/src/visual-manifests.ts @@ -0,0 +1,282 @@ +import type { BrandTemplateKey } from "./template-keys.js"; +import type { VisualTemplateKey } from "./template-keys.js"; +import type { VisualTemplateDefinition, VisualTemplateManifest } from "./brand-contracts.js"; + +const linjingEditorialManifest: VisualTemplateManifest = { + schemaVersion: "1.0", + key: "linjing-editorial", + version: "1.0.0", + name: "林境建筑画册", + description: "以个人品牌信任为主线、以高端项目作品为表达重点的编辑式视觉模板。", + supportedIndustryTemplates: ["personal", "doors"], + brandFirst: true, + tokens: { + colors: { + background: "#F7F5F1", + surface: "#FFFFFF", + foreground: "#252525", + muted: "#77736C", + accent: "#8A6846", + dark: "#202221", + }, + spacing: { page: "32rpx", section: "56rpx", module: "24rpx" }, + typography: { display: "56rpx", heading: "36rpx", body: "28rpx", caption: "22rpx" }, + radius: { card: "16rpx", button: "999rpx", media: "12rpx" }, + shadows: { card: "0 8rpx 32rpx rgba(32,34,33,0.08)" }, + }, + assets: [ + { key: "brand.logo", label: "品牌标志", required: false, kind: "logo" }, + { + key: "home.hero", + label: "首页首屏图", + required: true, + kind: "image", + aspectRatio: "16:9", + }, + { + key: "offering.cover", + label: "业务提供项封面", + required: true, + kind: "image", + aspectRatio: "1:1", + }, + { + key: "profile.portrait", + label: "主理人肖像", + required: false, + kind: "image", + aspectRatio: "1:1", + }, + { key: "brand.texture", label: "品牌底纹", required: false, kind: "texture" }, + ], + dataSlots: [ + { + key: "brand.identity", + source: "brand", + required: true, + description: "品牌名、定位和主理人身份", + }, + { key: "brand.hero", source: "brand", required: true, description: "品牌首屏表达和行动入口" }, + { key: "trust.proof", source: "trust", required: true, description: "经历、资质、案例和方法" }, + { + key: "offerings.list", + source: "offering", + required: true, + description: "可展示的业务提供项", + }, + { + key: "offering.detail", + source: "offering", + required: true, + description: "单个提供项的详情内容", + }, + { key: "inquiry.form", source: "inquiry", required: true, description: "品牌咨询或预约表单" }, + { + key: "records.items", + source: "records", + required: true, + description: "用户提交后的跟进记录", + }, + { + key: "profile.contact", + source: "profile", + required: true, + description: "联系方式和合作预期", + }, + ], + pages: [ + { + key: "home", + title: "首页", + renderer: "linjing-home", + modules: [ + { + key: "identity", + type: "brand-identity", + variant: "editorial-card", + required: true, + dataSlots: ["brand.identity"], + assetSlots: ["brand.logo"], + }, + { + key: "hero", + type: "hero", + variant: "architectural", + required: true, + dataSlots: ["brand.hero"], + assetSlots: ["home.hero"], + }, + { + key: "proof", + type: "trust", + variant: "proof-strip", + required: true, + dataSlots: ["trust.proof"], + }, + { + key: "offerings", + type: "offering-list", + variant: "editorial-list", + required: true, + dataSlots: ["offerings.list"], + assetSlots: ["offering.cover"], + capability: "offerings", + }, + { + key: "contact", + type: "contact", + variant: "quiet-footer", + required: true, + dataSlots: ["profile.contact"], + }, + ], + }, + { + key: "offerings", + title: "业务提供项", + renderer: "linjing-offerings", + modules: [ + { + key: "offerings", + type: "offering-list", + variant: "editorial-grid", + required: true, + dataSlots: ["offerings.list"], + assetSlots: ["offering.cover"], + capability: "offerings", + }, + ], + }, + { + key: "detail", + title: "提供项详情", + renderer: "linjing-offering-detail", + modules: [ + { + key: "detail", + type: "offering-detail", + variant: "project-case", + required: true, + dataSlots: ["offering.detail"], + assetSlots: ["offering.cover"], + capability: "offerings", + }, + ], + }, + { + key: "inquiry", + title: "咨询与预约", + renderer: "linjing-inquiry", + modules: [ + { + key: "inquiry", + type: "inquiry-form", + variant: "editorial-form", + required: true, + dataSlots: ["inquiry.form"], + capability: "inquiry", + }, + ], + }, + { + key: "success", + title: "提交成功", + renderer: "linjing-success", + modules: [ + { + key: "success", + type: "success-summary", + variant: "editorial-confirmation", + required: true, + dataSlots: ["brand.identity"], + }, + ], + }, + { + key: "records", + title: "我的记录", + renderer: "linjing-records", + modules: [ + { + key: "records", + type: "records-list", + variant: "timeline", + required: true, + dataSlots: ["records.items"], + }, + ], + }, + { + key: "profile", + title: "主理人与我", + renderer: "linjing-profile", + modules: [ + { + key: "identity", + type: "brand-identity", + variant: "profile-editorial", + required: true, + dataSlots: ["brand.identity"], + assetSlots: ["profile.portrait"], + }, + { + key: "contact", + type: "contact", + variant: "contact-sheet", + required: true, + dataSlots: ["profile.contact"], + }, + ], + }, + ], + capabilities: ["offerings", "inquiry"], +}; + +export const visualTemplateManifests: Record = { + "linjing-editorial": linjingEditorialManifest, + "acheng-campus-food": { + ...linjingEditorialManifest, + key: "acheng-campus-food", + version: "1.0.0", + name: "阿成校园餐", + description: "面向校园餐饮摊贩的菜单、出摊动态和团体预订视觉模板。", + supportedIndustryTemplates: ["food"], + tokens: { + ...linjingEditorialManifest.tokens, + colors: { + background: "#FFF8F0", + surface: "#FFFFFF", + foreground: "#29231F", + muted: "#7A6A60", + accent: "#E87532", + dark: "#3B2118", + }, + radius: { card: "24rpx", button: "999rpx", media: "20rpx" }, + }, + pages: linjingEditorialManifest.pages.map((pageDefinition) => { + const renderer = + pageDefinition.key === "home" + ? "acheng-home" + : pageDefinition.key === "offerings" + ? "acheng-offerings" + : pageDefinition.key === "profile" + ? "acheng-profile" + : pageDefinition.renderer; + return renderer ? { ...pageDefinition, renderer } : pageDefinition; + }), + capabilities: ["offerings", "inquiry", "booking"], + }, +}; + +export function getVisualTemplateManifest(key: string): VisualTemplateManifest | undefined { + return visualTemplateManifests[key as VisualTemplateKey]; +} + +export function isVisualTemplateCompatible( + visualTemplate: VisualTemplateDefinition | VisualTemplateManifest, + industryTemplateKey: string, +): boolean { + return visualTemplate.supportedIndustryTemplates.includes( + industryTemplateKey as BrandTemplateKey, + ); +} diff --git a/packages/config/src/visual-templates.ts b/packages/config/src/visual-templates.ts new file mode 100644 index 0000000..2c26d8c --- /dev/null +++ b/packages/config/src/visual-templates.ts @@ -0,0 +1,60 @@ +import type { BrandTemplateKey } from "./template-keys.js"; +import type { VisualTemplateKey } from "./template-keys.js"; +import type { VisualTemplateDefinition } from "./brand-contracts.js"; + +export const visualTemplates: Record = { + "linjing-editorial": { + key: "linjing-editorial", + version: "1.0.0", + name: "林境建筑画册", + description: "适合高端定制、建筑作品和项目型个人品牌。", + supportedIndustryTemplates: ["personal", "doors"], + variants: { hero: "architectural", offeringList: "editorial", detail: "project-case" }, + theme: { + colors: { background: "#F7F5F1", foreground: "#252525", accent: "#8A6846", dark: "#202221" }, + radius: { card: "16rpx" }, + }, + layout: { + home: ["founder-card", "brand-hero", "trust-proof", "trust-manifesto", "offering-list"], + offerings: ["offering-list"], + detail: ["offering-detail"], + profile: ["profile"], + }, + }, + "acheng-campus-food": { + key: "acheng-campus-food", + version: "1.0.0", + name: "阿成校园餐", + description: "适合校园餐饮、套餐预订和团体定制的暖橙菜单视觉。", + supportedIndustryTemplates: ["food"], + variants: { hero: "stall-board", offeringList: "menu-card", detail: "dish-detail" }, + theme: { + colors: { background: "#FFF8F0", foreground: "#29231F", accent: "#E87532", dark: "#3B2118" }, + radius: { card: "24rpx" }, + }, + layout: { + home: ["founder-card", "brand-hero", "trust-proof", "offering-list"], + offerings: ["offering-list"], + detail: ["offering-detail"], + profile: ["profile"], + }, + }, +}; + +export function listVisualTemplateKeys(): VisualTemplateKey[] { + return Object.keys(visualTemplates) as VisualTemplateKey[]; +} + +export function getVisualTemplate(key: string): VisualTemplateDefinition | undefined { + return visualTemplates[key as VisualTemplateKey]; +} + +export function getDefaultVisualTemplateKey(industryTemplateKey: string): VisualTemplateKey { + return ( + listVisualTemplateKeys().find((key) => + visualTemplates[key].supportedIndustryTemplates.includes( + industryTemplateKey as BrandTemplateKey, + ), + ) ?? "linjing-editorial" + ); +} diff --git a/packages/config/src/workflow.ts b/packages/config/src/workflow.ts new file mode 100644 index 0000000..e9a8c6a --- /dev/null +++ b/packages/config/src/workflow.ts @@ -0,0 +1,14 @@ +import type { WorkflowDefinition } from "./capability-contracts.js"; +import type { CapabilityDefinition } from "./capability-contracts.js"; +import { capabilityRegistry, workflowRegistry } from "./capability-contracts.js"; +import type { CapabilityKey } from "./template-keys.js"; + +export function canTransitionWorkflow(workflowKey: string, from: string, to: string): boolean { + const workflow = workflowRegistry[workflowKey as keyof typeof workflowRegistry] as + WorkflowDefinition | undefined; + return workflow ? from === to || workflow.transitions[from]?.includes(to) === true : false; +} + +export function resolveCapabilities(keys: readonly CapabilityKey[]): CapabilityDefinition[] { + return keys.map((key) => capabilityRegistry[key]); +} From 4512d2601db1c112a47a65b611ed8f4283a8bd15 Mon Sep 17 00:00:00 2001 From: que01 Date: Mon, 12 Oct 2026 03:29:30 +0800 Subject: [PATCH 4/7] =?UTF-8?q?refactor:=20=E6=8B=86=E5=88=86=E5=B7=A5?= =?UTF-8?q?=E4=BD=9C=E5=8F=B0=E4=B8=9A=E5=8A=A1=E6=9C=8D=E5=8A=A1=E8=BE=B9?= =?UTF-8?q?=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/api/src/admin-workspace.controller.ts | 206 ++++-------------- apps/api/src/app.module.ts | 4 + .../workspace/admin-access.identity.ts | 23 ++ .../workspace/admin-offering.service.ts | 94 ++++++++ .../workspace/admin-workspace.service.ts | 65 ++++++ 5 files changed, 228 insertions(+), 164 deletions(-) create mode 100644 apps/api/src/modules/workspace/admin-access.identity.ts create mode 100644 apps/api/src/modules/workspace/admin-offering.service.ts create mode 100644 apps/api/src/modules/workspace/admin-workspace.service.ts diff --git a/apps/api/src/admin-workspace.controller.ts b/apps/api/src/admin-workspace.controller.ts index 162ec4a..1596ceb 100644 --- a/apps/api/src/admin-workspace.controller.ts +++ b/apps/api/src/admin-workspace.controller.ts @@ -1,7 +1,5 @@ import { BadRequestException, - UnauthorizedException, - ForbiddenException, Body, Controller, Delete, @@ -14,7 +12,6 @@ import { import { Prisma } from "@prisma/client"; import type { FastifyRequest } from "fastify"; import { PrismaService } from "./prisma.service.js"; -import { readIdentity } from "./auth.js"; import { InstallTemplateDto, CreateOfferingDto, @@ -27,44 +24,30 @@ import { UpdateCapabilityInstallationDto, } from "./admin.dto.js"; import { + capabilityRegistry, capabilityPlugins, getBrandTemplate, getTemplateSampleContent, - getTemplatePackageManifestForVisualKey, - getDefaultVisualTemplateKey, - resolveCapabilities, } from "@personal-brand/config"; import { TemplateWorkspaceService } from "./template-workspace.service.js"; -import { validateFieldSnapshot, validateOfferingConfig } from "@personal-brand/validation"; -import { PublicWorkspaceService } from "./modules/public/public-workspace.controller.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 publicWorkspace: PublicWorkspaceService, + private readonly offeringService: AdminOfferingService, + private readonly workspaceService: AdminWorkspaceService, ) {} - private brandId(): string { - return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001"; - } @Get("offerings") - async listOfferings(@Req() request: FastifyRequest): Promise { - const brandId = this.requireAdmin(request).brandId; - const items = await this.prisma.offering.findMany({ - where: { brandId }, - orderBy: { sortOrder: "asc" }, - }); - return items.map((item) => { - const config = (item.config ?? {}) as Record; - return { - ...item, - sections: config.sections ?? [], - media: config.media ?? [], - cta: config.cta ?? null, - }; - }); + listOfferings(@Req() request: FastifyRequest): Promise { + const brandId = requireAdminIdentity(request).brandId; + return this.offeringService.list(brandId); } @Post("offerings") @@ -72,23 +55,8 @@ class AdminWorkspaceController { @Req() request: FastifyRequest, @Body() body: CreateOfferingDto, ): Promise { - const brandId = this.requireAdmin(request).brandId; - const { config, sections, media, cta, ...fields } = body; - const configValue = { - ...(config ?? {}), - ...(sections === undefined ? {} : { sections }), - ...(media === undefined ? {} : { media }), - ...(cta === undefined ? {} : { cta }), - }; - const configIssues = validateOfferingConfig(configValue); - if (configIssues.length) throw new BadRequestException("业务提供项配置无效"); - return this.prisma.offering.create({ - data: { - ...fields, - brandId, - config: configValue as Prisma.InputJsonValue, - }, - }); + const brandId = requireAdminIdentity(request).brandId; + return this.offeringService.create(brandId, body); } @Patch("offerings/:id") @@ -97,134 +65,44 @@ class AdminWorkspaceController { @Param("id") id: string, @Body() body: UpdateOfferingDto, ): Promise { - const brandId = this.requireAdmin(request).brandId; - const item = await this.prisma.offering.findFirst({ where: { id, brandId } }); - if (!item) throw new BadRequestException("业务提供项不存在"); - const { config, sections, media, cta, ...fields } = body; - const configValue = { - ...(config ?? {}), - ...(sections === undefined ? {} : { sections }), - ...(media === undefined ? {} : { media }), - ...(cta === undefined ? {} : { cta }), - }; - if (validateOfferingConfig(configValue).length) - throw new BadRequestException("业务提供项配置无效"); - return this.prisma.offering.update({ - where: { id }, - data: { - ...fields, - ...(config === undefined && - sections === undefined && - media === undefined && - cta === undefined - ? {} - : { - config: configValue as Prisma.InputJsonValue, - }), - }, - }); + 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 { - const brandId = this.requireAdmin(request).brandId; - const item = await this.prisma.offering.findFirst({ where: { id, brandId } }); - if (!item) throw new BadRequestException("业务提供项不存在"); - const [forms, bookings, items] = await Promise.all([ - this.prisma.inquiryForm.count({ where: { offeringId: id } }), - this.prisma.booking.count({ where: { offeringId: id } }), - this.prisma.bookingItem.count({ where: { offeringId: id } }), - ]); - if (forms || bookings || items) - throw new BadRequestException("业务提供项已有业务记录,只能禁用不能删除"); - await this.prisma.offering.delete({ where: { id } }); - return { deleted: true }; - } - private requireAdmin(request: FastifyRequest): { - subject: string; - brandId: string; - role: "admin"; - } { - 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("无管理员权限"); - return identity as { subject: string; brandId: string; role: "admin" }; + const brandId = requireAdminIdentity(request).brandId; + return this.offeringService.delete(brandId, id); } @Get() - async get(@Req() request: FastifyRequest): Promise { - const brandId = this.requireAdmin(request).brandId; - const [brand, installations, fields, offerings, forms] = await Promise.all([ - this.prisma.brandProfile.findUnique({ where: { id: brandId } }), - this.prisma.brandTemplateInstallation.findMany({ where: { brandId } }), - this.prisma.brandFieldDefinition.findMany({ - where: { brandId }, - orderBy: { sortOrder: "asc" }, - }), - this.prisma.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }), - this.prisma.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" } }), - ]); - const config = this.jsonObject(brand?.config); - const templateKey = - typeof config.visualTemplateKey === "string" - ? config.visualTemplateKey - : getDefaultVisualTemplateKey(brand?.templateKey ?? "personal"); - const manifest = getTemplatePackageManifestForVisualKey(templateKey); - return { - brand, - installations, - fields, - offerings, - forms, - templateContent: manifest - ? { - displayName: manifest.displayName, - admin: manifest.admin, - navigation: manifest.navigation.map(({ key, label, page }) => ({ key, label, page })), - templateFields: (manifest.templateFields ?? []).map((field) => ({ - ...field, - binding: field.binding ?? `brand.config.templateData.${field.key}`, - })), - assetSlots: manifest.assetSlots, - trustContentTypes: manifest.trustContentTypes ?? [], - } - : null, - }; + get(@Req() request: FastifyRequest): Promise { + const brandId = requireAdminIdentity(request).brandId; + return this.workspaceService.get(brandId); } @Get("preview") async getPreviewWorkspace(@Req() request: FastifyRequest): Promise { - const { brandId } = this.requireAdmin(request); - return this.publicWorkspace.getForBrandId(brandId, true); - } - private jsonObject(value: unknown): Record { - return value && typeof value === "object" && !Array.isArray(value) - ? (value as Record) - : {}; + const { brandId } = requireAdminIdentity(request); + return this.workspaceService.getPreview(brandId); } @Post("install") async install( @Req() request: FastifyRequest, @Body() body: InstallTemplateDto, ): Promise { - this.requireAdmin(request); - return this.templateWorkspace.install(this.requireAdmin(request).brandId, body.templateKey); + const { brandId } = requireAdminIdentity(request); + return this.templateWorkspace.install(brandId, body.templateKey); } @Get("capabilities") async listCapabilities(@Req() request: FastifyRequest): Promise { - const brandId = this.requireAdmin(request).brandId; + 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); - return (template ? resolveCapabilities(template.capabilities) : []).map((definition) => { + return (template?.capabilities ?? []).map((key) => capabilityRegistry[key]).map((definition) => { const item = installed.get(definition.key); return { id: item?.id ?? null, @@ -240,7 +118,7 @@ class AdminWorkspaceController { @Get("sample-content/preview") async previewSampleContent(@Req() request: FastifyRequest): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId); const sample = getTemplateSampleContent(templateKey); if (!sample) throw new BadRequestException("模板示例内容不存在"); @@ -265,7 +143,7 @@ class AdminWorkspaceController { @Post("sample-content/import") async importSampleContent(@Req() request: FastifyRequest): Promise { - const identity = this.requireAdmin(request); + const identity = requireAdminIdentity(request); const brandId = identity.brandId; const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId); const sample = getTemplateSampleContent(templateKey); @@ -359,7 +237,7 @@ class AdminWorkspaceController { @Param("key") key: string, @Body() body: UpdateCapabilityInstallationDto, ): Promise { - const identity = this.requireAdmin(request); + const identity = requireAdminIdentity(request); const brandId = identity.brandId; const template = getBrandTemplate( await this.templateWorkspace.getEffectiveTemplateKey(brandId), @@ -402,20 +280,20 @@ class AdminWorkspaceController { @Get("template/preview") async previewTemplate(@Req() request: FastifyRequest): Promise { - this.requireAdmin(request); - return this.templateWorkspace.preview(this.requireAdmin(request).brandId); + const { brandId } = requireAdminIdentity(request); + return this.templateWorkspace.preview(brandId); } @Post("template/upgrade") async upgradeTemplate(@Req() request: FastifyRequest): Promise { - this.requireAdmin(request); - return this.templateWorkspace.upgrade(this.requireAdmin(request).brandId); + const { brandId } = requireAdminIdentity(request); + return this.templateWorkspace.upgrade(brandId); } @Post("template/rollback") async rollbackTemplate(@Req() request: FastifyRequest): Promise { - this.requireAdmin(request); - return this.templateWorkspace.rollback(this.requireAdmin(request).brandId); + const { brandId } = requireAdminIdentity(request); + return this.templateWorkspace.rollback(brandId); } @Post("fields") @@ -423,7 +301,7 @@ class AdminWorkspaceController { @Req() request: FastifyRequest, @Body() body: CreateFieldDefinitionDto, ): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; return this.prisma.brandFieldDefinition.create({ data: { ...body, @@ -441,7 +319,7 @@ class AdminWorkspaceController { @Param("id") id: string, @Body() body: UpdateFieldDefinitionDto, ): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; const item = await this.prisma.brandFieldDefinition.findFirst({ where: { id, brandId }, }); @@ -459,7 +337,7 @@ class AdminWorkspaceController { @Delete("fields/:id") async deleteField(@Req() request: FastifyRequest, @Param("id") id: string): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; const item = await this.prisma.brandFieldDefinition.findFirst({ where: { id, brandId, source: "custom" }, }); @@ -470,7 +348,7 @@ class AdminWorkspaceController { @Get("forms") listForms(@Req() request: FastifyRequest): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; return this.prisma.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" }, @@ -479,7 +357,7 @@ class AdminWorkspaceController { @Get("submissions") listSubmissions(@Req() request: FastifyRequest): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; return this.prisma.inquirySubmission.findMany({ where: { brandId }, include: { @@ -496,7 +374,7 @@ class AdminWorkspaceController { @Param("id") id: string, @Body() body: UpdateInquirySubmissionDto, ): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; const item = await this.prisma.inquirySubmission.findFirst({ where: { id, brandId }, }); @@ -525,7 +403,7 @@ class AdminWorkspaceController { @Post("forms") createForm(@Req() request: FastifyRequest, @Body() body: CreateInquiryFormDto): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; if (validateFieldSnapshot(body.fieldsSnapshot).length) throw new BadRequestException("咨询表单字段定义无效"); return this.prisma.inquiryForm.create({ @@ -544,7 +422,7 @@ class AdminWorkspaceController { @Param("id") id: string, @Body() body: UpdateInquiryFormDto, ): Promise { - const brandId = this.requireAdmin(request).brandId; + const brandId = requireAdminIdentity(request).brandId; const item = await this.prisma.inquiryForm.findFirst({ where: { id, brandId }, }); diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index b2bbcea..875f580 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -12,6 +12,8 @@ import { PublicWorkspaceService, } from "./modules/public/public-workspace.controller.js"; import { PublicBrandContextService } from "./modules/public/public-brand-context.service.js"; +import { AdminOfferingService } from "./modules/workspace/admin-offering.service.js"; +import { AdminWorkspaceService } from "./modules/workspace/admin-workspace.service.js"; import { AdminConfigController } from "./modules/admin/admin-config.controller.js"; import { AdminUploadController } from "./modules/admin/admin-upload.controller.js"; import { AdminLocalUploadController } from "./modules/admin/admin-local-upload.controller.js"; @@ -78,6 +80,8 @@ export class HealthController { BrandReleaseApiService, PublicBrandContextService, PublicWorkspaceService, + AdminOfferingService, + AdminWorkspaceService, ], exports: [PrismaService, WechatAuthService], }) diff --git a/apps/api/src/modules/workspace/admin-access.identity.ts b/apps/api/src/modules/workspace/admin-access.identity.ts new file mode 100644 index 0000000..dc16b26 --- /dev/null +++ b/apps/api/src/modules/workspace/admin-access.identity.ts @@ -0,0 +1,23 @@ +import { ForbiddenException, UnauthorizedException } from "@nestjs/common"; +import type { FastifyRequest } from "fastify"; +import { readIdentity } from "../../auth.js"; + +export type AdminIdentity = { + subject: string; + brandId: string; + role: "admin"; +}; + +export function requireAdminIdentity(request: FastifyRequest): AdminIdentity { + 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("无管理员权限"); + return identity as AdminIdentity; +} diff --git a/apps/api/src/modules/workspace/admin-offering.service.ts b/apps/api/src/modules/workspace/admin-offering.service.ts new file mode 100644 index 0000000..1d9d33f --- /dev/null +++ b/apps/api/src/modules/workspace/admin-offering.service.ts @@ -0,0 +1,94 @@ +import { BadRequestException, Injectable } from "@nestjs/common"; +import { Prisma } from "@prisma/client"; +import { PrismaService } from "../../prisma.service.js"; +import type { CreateOfferingDto, UpdateOfferingDto } from "../../admin.dto.js"; +import { validateOfferingConfig } from "@personal-brand/validation"; + +type OfferingConfigInput = { + config?: CreateOfferingDto["config"] | undefined; + sections?: CreateOfferingDto["sections"] | undefined; + media?: CreateOfferingDto["media"] | undefined; + cta?: CreateOfferingDto["cta"] | undefined; +}; + +function buildOfferingConfig(body: OfferingConfigInput): Record { + const { config, sections, media, cta } = body; + return { + ...(config ?? {}), + ...(sections === undefined ? {} : { sections }), + ...(media === undefined ? {} : { media }), + ...(cta === undefined ? {} : { cta }), + }; +} + +@Injectable() +export class AdminOfferingService { + constructor(private readonly prisma: PrismaService) {} + + async list(brandId: string): Promise { + const items = await this.prisma.offering.findMany({ + where: { brandId }, + orderBy: { sortOrder: "asc" }, + }); + return items.map((item) => { + const config = (item.config ?? {}) as Record; + return { + ...item, + sections: config.sections ?? [], + media: config.media ?? [], + cta: config.cta ?? null, + }; + }); + } + + async create(brandId: string, body: CreateOfferingDto): Promise { + const { config, sections, media, cta, ...fields } = body; + const configValue = buildOfferingConfig({ config, sections, media, cta }); + if (validateOfferingConfig(configValue).length) { + throw new BadRequestException("业务提供项配置无效"); + } + return this.prisma.offering.create({ + data: { + ...fields, + brandId, + config: configValue as Prisma.InputJsonValue, + }, + }); + } + + async update(brandId: string, id: string, body: UpdateOfferingDto): Promise { + const item = await this.prisma.offering.findFirst({ where: { id, brandId } }); + if (!item) throw new BadRequestException("业务提供项不存在"); + + const { config, sections, media, cta, ...fields } = body; + const configValue = buildOfferingConfig({ config, sections, media, cta }); + if (validateOfferingConfig(configValue).length) { + throw new BadRequestException("业务提供项配置无效"); + } + const hasConfigInput = + config !== undefined || sections !== undefined || media !== undefined || cta !== undefined; + return this.prisma.offering.update({ + where: { id }, + data: { + ...fields, + ...(hasConfigInput ? { config: configValue as Prisma.InputJsonValue } : {}), + }, + }); + } + + async delete(brandId: string, id: string): Promise { + const item = await this.prisma.offering.findFirst({ where: { id, brandId } }); + if (!item) throw new BadRequestException("业务提供项不存在"); + + const [forms, bookings, items] = await Promise.all([ + this.prisma.inquiryForm.count({ where: { offeringId: id } }), + this.prisma.booking.count({ where: { offeringId: id } }), + this.prisma.bookingItem.count({ where: { offeringId: id } }), + ]); + if (forms || bookings || items) { + throw new BadRequestException("业务提供项已有业务记录,只能禁用不能删除"); + } + await this.prisma.offering.delete({ where: { id } }); + return { deleted: true }; + } +} diff --git a/apps/api/src/modules/workspace/admin-workspace.service.ts b/apps/api/src/modules/workspace/admin-workspace.service.ts new file mode 100644 index 0000000..9a93bc7 --- /dev/null +++ b/apps/api/src/modules/workspace/admin-workspace.service.ts @@ -0,0 +1,65 @@ +import { Injectable } from "@nestjs/common"; +import { PrismaService } from "../../prisma.service.js"; +import { + getDefaultVisualTemplateKey, + getTemplatePackageManifestForVisualKey, +} from "@personal-brand/config"; +import { PublicWorkspaceService } from "../public/public-workspace.controller.js"; + +@Injectable() +export class AdminWorkspaceService { + constructor( + private readonly prisma: PrismaService, + private readonly publicWorkspace: PublicWorkspaceService, + ) {} + + async get(brandId: string): Promise { + const [brand, installations, fields, offerings, forms] = await Promise.all([ + this.prisma.brandProfile.findUnique({ where: { id: brandId } }), + this.prisma.brandTemplateInstallation.findMany({ where: { brandId } }), + this.prisma.brandFieldDefinition.findMany({ + where: { brandId }, + orderBy: { sortOrder: "asc" }, + }), + this.prisma.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }), + this.prisma.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" } }), + ]); + const config = this.jsonObject(brand?.config); + const templateKey = + typeof config.visualTemplateKey === "string" + ? config.visualTemplateKey + : getDefaultVisualTemplateKey(brand?.templateKey ?? "personal"); + const manifest = getTemplatePackageManifestForVisualKey(templateKey); + + return { + brand, + installations, + fields, + offerings, + forms, + templateContent: manifest + ? { + displayName: manifest.displayName, + admin: manifest.admin, + navigation: manifest.navigation.map(({ key, label, page }) => ({ key, label, page })), + templateFields: (manifest.templateFields ?? []).map((field) => ({ + ...field, + binding: field.binding ?? `brand.config.templateData.${field.key}`, + })), + assetSlots: manifest.assetSlots, + trustContentTypes: manifest.trustContentTypes ?? [], + } + : null, + }; + } + + getPreview(brandId: string): Promise { + return this.publicWorkspace.getForBrandId(brandId, true); + } + + private jsonObject(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : {}; + } +} From f3adf7bc153ef731c8a72204c7aa6ddb08c6ac92 Mon Sep 17 00:00:00 2001 From: que01 Date: Mon, 12 Oct 2026 03:36:57 +0800 Subject: [PATCH 5/7] =?UTF-8?q?style:=20=E6=A0=BC=E5=BC=8F=E5=8C=96?= =?UTF-8?q?=E5=B7=A5=E4=BD=9C=E5=8F=B0=E6=8E=A7=E5=88=B6=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/api/src/admin-workspace.controller.ts | 26 ++++++++++++---------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/apps/api/src/admin-workspace.controller.ts b/apps/api/src/admin-workspace.controller.ts index 1596ceb..0f6c641 100644 --- a/apps/api/src/admin-workspace.controller.ts +++ b/apps/api/src/admin-workspace.controller.ts @@ -102,18 +102,20 @@ class AdminWorkspaceController { ]); const installed = new Map(installations.map((item) => [item.capabilityKey, item])); const template = getBrandTemplate(templateKey); - return (template?.capabilities ?? []).map((key) => capabilityRegistry[key]).map((definition) => { - const item = installed.get(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", - updatedAt: item?.updatedAt ?? null, - }; - }); + return (template?.capabilities ?? []) + .map((key) => capabilityRegistry[key]) + .map((definition) => { + const item = installed.get(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", + updatedAt: item?.updatedAt ?? null, + }; + }); } @Get("sample-content/preview") From 357f27163953039a67bc4adc309a74fe739e7fc5 Mon Sep 17 00:00:00 2001 From: que01 Date: Mon, 12 Oct 2026 03:37:05 +0800 Subject: [PATCH 6/7] =?UTF-8?q?refactor:=20=E6=8B=86=E5=88=86=20API=20Clie?= =?UTF-8?q?nt=20=E8=B5=84=E6=BA=90=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/api-client/src/client/request.ts | 59 + packages/api-client/src/index.ts | 1177 ++++------------- packages/api-client/src/resources/booking.ts | 55 + packages/api-client/src/resources/brand.ts | 98 ++ packages/api-client/src/resources/inquiry.ts | 58 + packages/api-client/src/resources/media.ts | 18 + packages/api-client/src/resources/offering.ts | 32 + packages/api-client/src/resources/public.ts | 38 + packages/api-client/src/resources/session.ts | 26 + packages/api-client/src/resources/template.ts | 150 +++ packages/api-client/src/resources/trust.ts | 26 + packages/api-client/src/types/booking.ts | 51 + packages/api-client/src/types/brand.ts | 56 + packages/api-client/src/types/capability.ts | 9 + packages/api-client/src/types/common.ts | 5 + packages/api-client/src/types/field.ts | 11 + packages/api-client/src/types/inquiry.ts | 30 + packages/api-client/src/types/media.ts | 11 + packages/api-client/src/types/offering.ts | 52 + .../src/types/template-definition.ts | 27 + packages/api-client/src/types/template.ts | 80 ++ packages/api-client/src/types/trust.ts | 22 + packages/api-client/src/types/workspace.ts | 76 ++ packages/api-client/test/exports.test.ts | 18 + 24 files changed, 1280 insertions(+), 905 deletions(-) create mode 100644 packages/api-client/src/client/request.ts create mode 100644 packages/api-client/src/resources/booking.ts create mode 100644 packages/api-client/src/resources/brand.ts create mode 100644 packages/api-client/src/resources/inquiry.ts create mode 100644 packages/api-client/src/resources/media.ts create mode 100644 packages/api-client/src/resources/offering.ts create mode 100644 packages/api-client/src/resources/public.ts create mode 100644 packages/api-client/src/resources/session.ts create mode 100644 packages/api-client/src/resources/template.ts create mode 100644 packages/api-client/src/resources/trust.ts create mode 100644 packages/api-client/src/types/booking.ts create mode 100644 packages/api-client/src/types/brand.ts create mode 100644 packages/api-client/src/types/capability.ts create mode 100644 packages/api-client/src/types/common.ts create mode 100644 packages/api-client/src/types/field.ts create mode 100644 packages/api-client/src/types/inquiry.ts create mode 100644 packages/api-client/src/types/media.ts create mode 100644 packages/api-client/src/types/offering.ts create mode 100644 packages/api-client/src/types/template-definition.ts create mode 100644 packages/api-client/src/types/template.ts create mode 100644 packages/api-client/src/types/trust.ts create mode 100644 packages/api-client/src/types/workspace.ts create mode 100644 packages/api-client/test/exports.test.ts diff --git a/packages/api-client/src/client/request.ts b/packages/api-client/src/client/request.ts new file mode 100644 index 0000000..bc2bf51 --- /dev/null +++ b/packages/api-client/src/client/request.ts @@ -0,0 +1,59 @@ +import type { ApiErrorBody } from "../types/common.js"; + +export interface FetchResponse { + readonly status: number; + readonly ok: boolean; + json(): Promise; +} + +export type FetchLike = ( + input: string, + init?: { method?: string; headers?: Record; body?: string }, +) => Promise; + +export interface ApiClientOptions { + baseUrl: string; + fetcher: FetchLike; + token?: string; +} + +export type RequestFn = ( + path: string, + options?: { method?: string; body?: unknown }, +) => Promise; + +export async function request( + state: { baseUrl: string; fetcher: FetchLike; token?: string | undefined }, + path: string, + options: { method?: string; body?: unknown } = {}, +): Promise { + const headers: Record = { accept: "application/json" }; + if (options.body !== undefined) headers["content-type"] = "application/json"; + if (state.token) headers.authorization = `Bearer ${state.token}`; + const response = await state.fetcher(`${state.baseUrl}${path}`, { + method: options.method ?? "GET", + headers, + ...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }), + }); + const body = await response.json(); + if (!response.ok) throw new ApiClientError(response.status, body as ApiErrorBody); + return body as T; +} + +export class ApiClientError extends Error { + constructor( + readonly status: number, + readonly body: ApiErrorBody, + ) { + super(body.error.message); + this.name = "ApiClientError"; + } + + get code(): string { + return this.body.error.code; + } + + get requestId(): string | null { + return this.body.requestId; + } +} diff --git a/packages/api-client/src/index.ts b/packages/api-client/src/index.ts index ccafa17..0325d48 100644 --- a/packages/api-client/src/index.ts +++ b/packages/api-client/src/index.ts @@ -1,914 +1,281 @@ -import type { - BookingRequestType, - BookingStatus, - ContactPreference, - FulfillmentType, - PublicOffering, - BrandTemplateKey, - RuntimeCapability, - RuntimeInquiryForm, - RuntimeOffering, - RuntimeWorkspace, - RuntimeTrustItem, - ThemeManifest, -} from "@personal-brand/types"; +export { ApiClientError } from "./client/request.js"; +export type { ApiClientOptions, FetchLike, FetchResponse, RequestFn } from "./client/request.js"; +export type { + AdminBooking, + Booking, + BookingItemInput, + BookingSummary, + BookingTag, + CreateBookingInput, +} from "./types/booking.js"; +export type { + AdminBrandMember, + AdminBrandMembership, + BrandPresentationUpdate, + BrandProfile, + BrandReleaseSummary, + BrandUpdate, +} from "./types/brand.js"; +export type { CapabilityInstallation } from "./types/capability.js"; +export type { ApiErrorBody } from "./types/common.js"; +export type { BrandFieldDefinition } from "./types/field.js"; +export type { InquiryForm, InquirySubmission } from "./types/inquiry.js"; +export type { PresignedUpload, UploadConfig } from "./types/media.js"; +export type { + Offering, + OfferingCta, + OfferingMedia, + OfferingSection, + OfferingUpdate, +} from "./types/offering.js"; +export type { BrandTemplateDefinition } from "./types/template-definition.js"; +export type { + AdminTemplateContent, + TemplateAdminField, + TemplateAdminSection, +} from "./types/template.js"; +export type { TrustContent, TrustContentInput } from "./types/trust.js"; +export type { PublicWorkspace } from "./types/workspace.js"; export { projectBrandAliases, projectTrustPresentation } from "@personal-brand/types"; -export type { PublicOffering } from "@personal-brand/types"; -export type { BookingStatus } from "@personal-brand/types"; -export type { BrandTemplateKey } from "@personal-brand/types"; +export type { PublicOffering, BookingStatus, BrandTemplateKey } from "@personal-brand/types"; export type { EditorPreviewFrameMessage, EditorPreviewHostMessage, RuntimeWorkspace, } from "@personal-brand/types"; - -export interface BrandProfile { - id: string; - slug?: string; - name: string; - templateKey: BrandTemplateKey; - tagline: string | null; - description: string | null; - avatarUrl: string | null; - coverUrl: string | null; - hours: string | null; - address: string | null; - deliveryNote: string | null; - contactPhone: string | null; - contactWechat: string | null; - config?: Record | null; -} -export interface AdminBrandMembership { - id: string; - role: string; - brand: Pick & { slug?: string }; -} -export interface AdminBrandMember { - id: string; - role: string; - isEnabled: boolean; - adminUser: { - id: string; - username: string; - displayName: string; - isEnabled: boolean; - }; -} - -export interface UploadConfig { - configured: boolean; - status: "ok" | "unavailable" | "unconfigured"; - bucket?: string; -} - -export interface PresignedUpload { - uploadUrl: string; - key: string; - publicUrl: string; -} -export type BrandUpdate = Partial>; -export interface BrandReleaseSummary { - id: string; - version: number; - status: string; - note: string | null; - actorId: string; - createdAt: string; - revokedAt: string | null; - revokedBy?: string | null; -} -export type BrandPresentationUpdate = Partial< - Record< - "identity" | "home" | "offerings" | "detail" | "profile" | "inquiry" | "success" | "records", - Record - > ->; - -export interface TemplateAdminField { - key: string; - page?: string; - binding: string; - label: string; - help?: string; - input: - | "text" - | "textarea" - | "phone" - | "image" - | "number" - | "boolean" - | "select" - | "multi-select" - | "list"; - itemFields?: Array<{ - key: string; - label: string; - input?: "text" | "textarea"; - required?: boolean; - }>; - itemValueKey?: string; - required?: boolean; - maxLength?: number; - placeholder?: string; - options?: Array<{ value: string; label: string }>; - previewTarget?: string; -} - -export interface TemplateAdminSection { - key: string; - title: string; - description: string; - page: string; - target: "brand" | "offering" | "trust" | "inquiry"; - previewTargets?: Array<{ - key: string; - label: string; - composite?: boolean; - children?: string[]; - }>; - fields: TemplateAdminField[]; -} - -export interface AdminTemplateContent { - displayName: string; - admin: { sections: TemplateAdminSection[] }; - navigation: Array<{ key: string; label: string; page: string }>; - templateFields?: TemplateAdminField[]; - trustContentTypes?: Array<{ - type: string; - label: string; - adminFields: { - title: string; - summary: string; - content: string; - summaryHelp?: string; - summaryPlaceholder?: string; - }; - pages?: string[]; - help?: string; - placeholder?: string; - required?: boolean; - configFields?: TemplateAdminField[]; - previewTargets?: Array<{ key: string; label: string; page?: string }>; - maxPublishedItems?: number; - hideStandardFields?: Array<"summary" | "content">; - }>; - assetSlots: Array<{ - key: string; - binding: string; - target: "brand" | "offering" | "trust"; - label: string; - help: string; - required: boolean; - kind: "image" | "logo" | "portrait" | "texture"; - aspectRatio?: string; - }>; -} -export interface OfferingUpdate { - name?: string; - description?: string; - coverUrl?: string; - priceText?: string; - priceAmount?: number; - sortOrder?: number; - bookingEnabled?: boolean; - isEnabled?: boolean; - categoryKey?: string; - config?: Record; -} -export interface TrustContent { - id: string; - type: string; - title: string; - summary?: string | null; - content: string; - coverUrl?: string | null; - sortOrder: number; - isPublished: boolean; - config?: Record | null; -} -export interface TrustContentInput { - type: string; - title: string; - summary?: string; - content: string; - coverUrl?: string; - sortOrder?: number; - isPublished?: boolean; - config?: Record; -} - -export interface BookingItemInput { - offeringId: string; - quantity: number; -} -export interface CreateBookingInput { - requestType: BookingRequestType; - customerName: string; - phone?: string; - wechatId?: string; - contactPreference: ContactPreference; - fulfillmentType?: FulfillmentType; - offeringId?: string; - requestedDate?: string; - requestedTime?: string; - deliveryAddress?: string; - note?: string; - extraData?: Record; - items: BookingItemInput[]; -} -export interface BookingSummary { - bookingNo: string; - status: BookingStatus; - estimatedAmount: number | null; - createdAt: string; -} -export interface Booking extends BookingSummary { - id: string; - customerName: string; - adminNote?: string | null; -} -export interface BookingTag { - id: string; - name: string; - isPreset: boolean; - isEnabled: boolean; -} -export interface AdminBooking extends Booking { - tags?: Array<{ tag: BookingTag }>; -} -export interface ApiErrorBody { - data: null; - error: { code: string; message: string }; - requestId: string | null; -} -export interface BrandTemplateDefinition { - key: "personal" | "food" | "doors"; - version: string; - name: string; - description: string; - serviceCategories: string[]; - trustContentTypes: string[]; - modules: Array<{ - key: string; - type: string; - title: string; - required: boolean; - }>; - fields: Array<{ - scope: string; - key: string; - label: string; - type: string; - required: boolean; - }>; - capabilities: string[]; - runtimeCapabilities: Array<{ - key: string; - version: string; - workflowKey?: string; - }>; -} -export interface OfferingSection { - type: "text" | "image-list" | "timeline" | "faq"; - title: string; - content?: string; - items?: unknown[]; -} -export interface OfferingMedia { - url: string; - alt?: string; - type?: "image" | "video"; -} -export interface OfferingCta { - type: "inquiry" | "booking" | "contact" | "external-link"; - label: string; - config?: Record; -} -export interface BrandFieldDefinition { - id: string; - scope: string; - key: string; - label: string; - type: string; - required: boolean; - isVisible: boolean; - sortOrder: number; - source: string; -} -export interface InquiryForm { - id: string; - name: string; - offeringId?: string | null; - version: number; - isEnabled: boolean; - fieldsSnapshot: unknown[]; - purpose: "inquiry" | "booking" | "quote-request"; - targetType: "brand" | "offering"; - submissionAction: "create-inquiry" | "create-booking" | "create-quote"; -} -export interface InquirySubmission { - id: string; - inquiryFormId: string; - formVersion: number; - fieldsSnapshot: unknown[]; - values: Record; - activeFields: Record; - createdAt: string; - status: "new" | "reviewing" | "replied" | "qualified" | "converted" | "closed"; - adminNote?: string | null; - inquiryForm?: { name: string }; - offering?: { id: string; name: string } | null; - statusHistory?: Array<{ - fromStatus?: string | null; - toStatus: string; - createdAt: string; - }>; -} -export interface CapabilityInstallation { - id: string | null; - capabilityKey: string; - capabilityVersion: string; - status: "enabled" | "disabled" | "degraded"; - config?: Record | null; - updatedAt: string | null; - source?: "template" | "brand"; -} -export interface PublicWorkspace { - schemaVersion: string; - contractVersion: string; - publication: { - status: "published" | "unpublished"; - version: number | null; - publishedAt?: string; - }; - brand: (BrandProfile & Record) | null; - template: { key: BrandTemplateKey; version: string; name: string } | null; - visualTemplate: { - key: string; - version: string; - name: string; - supportedIndustryTemplates: BrandTemplateKey[]; - variants: Record; - } | null; - visualTemplateManifest?: { - schemaVersion: "1.0"; - key: string; - version: string; - name: string; - brandFirst: true; - tokens: { - colors: Record; - spacing: Record; - typography: Record; - radius: Record; - shadows?: Record; - }; - pages: Array<{ - key: string; - title: string; - modules: Array<{ - key: string; - type: string; - variant: string; - required: boolean; - dataSlots?: string[]; - assetSlots?: string[]; - capability?: string; - }>; - }>; - assets: Array>; - dataSlots: Array>; - capabilities: string[]; - }; - capabilities: RuntimeCapability[]; - offerings: RuntimeOffering[]; - inquiryForms: RuntimeInquiryForm[]; - trustItems: RuntimeTrustItem[]; - navigation: { tabs: Array<{ key: string; label: string; page: string }> }; - trustPresentation: Record; - theme: ThemeManifest; - layout?: { home: string[]; offerings: string[]; detail: string[]; profile: string[] }; - plugins?: Array<{ - key: string; - version: string; - displayName: string; - purpose: string; - requiredModules: string[]; - apiContract: string; - configSchema: string; - status: string; - }>; -} -export interface Offering { - id: string; - brandId?: string; - kind: "service" | "product" | "package" | "subscription"; - name: string; - summary?: string | null; - description?: string | null; - coverUrl?: string | null; - priceText?: string | null; - priceAmount?: number | null; - isEnabled: boolean; - sortOrder: number; - config?: Record | null; - sections?: OfferingSection[]; - media?: OfferingMedia[]; - cta?: OfferingCta; - inquiryForms?: Array>; -} - -export class ApiClientError extends Error { - constructor( - readonly status: number, - readonly body: ApiErrorBody, - ) { - super(body.error.message); - this.name = "ApiClientError"; - } - get code(): string { - return this.body.error.code; - } - get requestId(): string | null { - return this.body.requestId; - } -} - -export interface FetchResponse { - readonly status: number; - readonly ok: boolean; - json(): Promise; -} -export type FetchLike = ( - input: string, - init?: { method?: string; headers?: Record; body?: string }, -) => Promise; -export interface ApiClientOptions { - baseUrl: string; - fetcher: FetchLike; - token?: string; -} - -export class ApiClient { - private readonly baseUrl: string; - private readonly fetcher: FetchLike; - private token: string | undefined; - - constructor(options: ApiClientOptions) { - this.baseUrl = options.baseUrl.replace(/\/$/, ""); - this.fetcher = options.fetcher; - this.token = options.token; - } - setToken(token: string | undefined): void { - this.token = token; - } - getBrand(): Promise { - return this.request("/public/brand"); - } - listOfferings(): Promise { - return this.request("/public/offerings"); - } - getPublicWorkspace(): Promise { - return this.request("/public/workspace"); - } - getPublicInquiryForm(id: string): Promise { - return this.request(`/public/inquiry-forms/${encodeURIComponent(id)}`); - } - createCustomerInquirySubmission( - formId: string, - values: Record, - ): Promise { - return this.request("/customer/inquiry-submissions", { - method: "POST", - body: { formId, values }, - }); - } - listCustomerInquirySubmissions(): Promise { - return this.request("/customer/inquiry-submissions"); - } - getCustomerInquirySubmission(id: string): Promise { - return this.request(`/customer/inquiry-submissions/${encodeURIComponent(id)}`); - } - createCustomerSession(code: string): Promise<{ token: string }> { - return this.request("/customer/session/wechat", { method: "POST", body: { code } }); - } - listCustomerBookings(): Promise { - return this.request("/customer/bookings"); - } - createCustomerBooking(input: CreateBookingInput): Promise { - return this.request("/customer/bookings", { method: "POST", body: input }); - } - cancelCustomerBooking(id: string): Promise { - return this.request(`/customer/bookings/${encodeURIComponent(id)}/cancel`, { method: "POST" }); - } - loginAdmin( - username: string, - password: string, - ): Promise<{ - token: string; - displayName: string; - mustChangePassword: boolean; - role: string; - }> { - return this.request("/admin/session/login", { method: "POST", body: { username, password } }); - } - changeAdminPassword(currentPassword: string, newPassword: string): Promise<{ changed: true }> { - return this.request("/admin/session/change-password", { - method: "POST", - body: { currentPassword, newPassword }, - }); - } - listAdminBookings( - filters: { status?: BookingStatus; unreadOnly?: boolean; tagId?: string } = {}, - ): Promise { - const params: string[] = []; - if (filters.status) params.push(`status=${encodeURIComponent(filters.status)}`); - if (filters.unreadOnly !== undefined) params.push(`unreadOnly=${filters.unreadOnly}`); - if (filters.tagId) params.push(`tagId=${encodeURIComponent(filters.tagId)}`); - const query = params.join("&"); - return this.request(`/admin/bookings${query ? `?${query}` : ""}`); - } - getAdminBooking(id: string): Promise { - return this.request(`/admin/bookings/${encodeURIComponent(id)}`); - } - getAdminUnreadCount(): Promise<{ count: number }> { - return this.request("/admin/bookings/unread-count"); - } - updateAdminBookingStatus( - id: string, - status: BookingStatus, - adminNote?: string, - ): Promise { - return this.request(`/admin/bookings/${encodeURIComponent(id)}/status`, { - method: "POST", - body: { status, ...(adminNote === undefined ? {} : { adminNote }) }, - }); - } - markAdminBookingRead(id: string): Promise { - return this.request(`/admin/bookings/${encodeURIComponent(id)}/read`, { method: "POST" }); - } - listAdminTags(): Promise { - return this.request("/admin/bookings/tags"); - } - createAdminTag(name: string): Promise { - return this.request("/admin/bookings/tags", { method: "POST", body: { name } }); - } - getAdminBrand(): Promise { - return this.request("/admin/config/brand"); - } - listAdminBrands(): Promise { - return this.request("/admin/brands"); - } - switchAdminBrand( - brandId: string, - ): Promise<{ token: string; brand: AdminBrandMembership["brand"] }> { - return this.request(`/admin/brands/${encodeURIComponent(brandId)}/switch`, { method: "POST" }); - } - listAdminMembers(): Promise { - return this.request("/admin/brands/members"); - } - createAdminMember(body: { - username: string; - displayName: string; - password: string; - role: "owner" | "editor"; - }): Promise { - return this.request("/admin/brands/members", { method: "POST", body }); - } - updateAdminMember( - id: string, - body: Partial>, - ): Promise { - return this.request(`/admin/brands/members/${encodeURIComponent(id)}`, { - method: "PATCH", - body, - }); - } - getAdminVisualTemplatePreview(): Promise<{ - current: { - key: string; - version: string; - name: string; - theme: { colors: Record }; - variants: Record; - } | null; - available: string[]; - }> { - return this.request("/admin/config/visual-template/preview"); - } - getAdminVisualTemplateHistory(): Promise<{ - history: Array<{ visualTemplateKey: string; savedAt: string }>; - }> { - return this.request("/admin/config/visual-template/history"); - } - rollbackAdminVisualTemplate(): Promise<{ visualTemplateKey: string; rolledBack: boolean }> { - return this.request("/admin/config/visual-template/rollback", { method: "POST" }); - } - updateAdminBrand(body: BrandUpdate): Promise { - return this.request("/admin/config/brand", { method: "PATCH", body }); - } - updateAdminBrandPresentation(body: BrandPresentationUpdate): Promise<{ - visualPresentation: Record>; - }> { - return this.request("/admin/config/presentation", { method: "PATCH", body }); - } - getPublicTemplate(key: BrandTemplateKey): Promise { - return this.request(`/public/templates/${key}`); - } - listPublicTemplates(): Promise<{ - industries: BrandTemplateDefinition[]; - visuals: Array<{ - key: string; - version: string; - name: string; - description: string; - supportedIndustryTemplates: BrandTemplateKey[]; - variants: Record; - theme: { colors: Record }; - }>; - }> { - return this.request<{ - industries: BrandTemplateDefinition[]; - visuals: Array<{ - key: string; - version: string; - name: string; - description: string; - supportedIndustryTemplates?: unknown; - variants?: unknown; - theme?: unknown; - }>; - }>("/public/templates").then((catalog) => ({ - industries: Array.isArray(catalog.industries) ? catalog.industries : [], - visuals: Array.isArray(catalog.visuals) - ? catalog.visuals.map((visual) => ({ - key: String(visual.key ?? ""), - version: String(visual.version ?? ""), - name: String(visual.name ?? "未命名视觉模板"), - description: String(visual.description ?? ""), - supportedIndustryTemplates: Array.isArray(visual.supportedIndustryTemplates) - ? visual.supportedIndustryTemplates.filter( - (item): item is BrandTemplateKey => - item === "personal" || item === "food" || item === "doors", - ) - : [], - variants: - visual.variants && typeof visual.variants === "object" - ? (visual.variants as Record) - : {}, - theme: - visual.theme && typeof visual.theme === "object" - ? (visual.theme as { colors: Record }) - : { colors: {} }, - })) - : [], - })); - } - previewPublicTemplateCombination( - industry: string, - visual: string, - ): Promise<{ - industry: BrandTemplateDefinition; - visual: { - key: string; - version: string; - name: string; - description: string; - supportedIndustryTemplates: BrandTemplateKey[]; - variants: Record; - theme: { colors: Record }; - }; - runtime: { - schemaVersion: string; - capabilities: Array<{ key: string; version: string }>; - theme: unknown; - }; - }> { - return this.request( - `/public/templates/preview?industry=${encodeURIComponent(industry)}&visual=${encodeURIComponent(visual)}`, - ); - } - getPublicOffering(id: string): Promise { - return this.request(`/public/offerings/${encodeURIComponent(id)}`); - } - listPublicOfferings(): Promise { - return this.request("/public/offerings"); - } - getAdminWorkspace(): Promise<{ - brand: BrandProfile; - visualTemplate?: { - key: string; - version: string; - name: string; - supportedIndustryTemplates: BrandTemplateKey[]; - variants: Record; - } | null; - installations: Array<{ id: string; templateKey: BrandTemplateKey; templateVersion: string }>; - fields: BrandFieldDefinition[]; - offerings: Offering[]; - forms: unknown[]; - templateContent: AdminTemplateContent | null; - }> { - return this.request("/admin/workspace"); - } - getAdminPreviewWorkspace(): Promise { - return this.request("/admin/workspace/preview"); - } - listAdminReleases(): Promise { - return this.request("/admin/releases"); - } - getAdminReleaseReadiness(): Promise<{ - ready: boolean; - checks: Array<{ - key: string; - label: string; - passed: boolean; - help?: string; - destination?: string; - }>; - }> { - return this.request("/admin/releases/readiness"); - } - publishAdminRelease(note?: string): Promise { - return this.request("/admin/releases/publish", { - method: "POST", - body: note === undefined ? {} : { note }, - }); - } - rollbackAdminRelease(version: number, note?: string): Promise { - return this.request(`/admin/releases/${version}/rollback`, { - method: "POST", - body: note === undefined ? {} : { note }, - }); - } - revokeAdminRelease(): Promise< - Pick - > { - return this.request("/admin/releases/revoke", { method: "POST" }); - } - installAdminTemplate(templateKey: "personal" | "food" | "doors"): Promise { - return this.request("/admin/workspace/install", { method: "POST", body: { templateKey } }); - } - listAdminCapabilities(): Promise { - return this.request("/admin/workspace/capabilities"); - } - updateAdminCapability( - key: string, - body: { - capabilityVersion: string; - status: CapabilityInstallation["status"]; - config?: Record; - }, - ): Promise { - return this.request(`/admin/workspace/capabilities/${encodeURIComponent(key)}`, { - method: "PATCH", - body, - }); - } - previewAdminSampleContent(): Promise<{ - templateKey: string; - alreadyImported: boolean; - counts: Record; - willCreateInquiryForm: boolean; - }> { - return this.request("/admin/workspace/sample-content/preview"); - } - importAdminSampleContent(): Promise<{ imported: boolean; counts: Record }> { - return this.request("/admin/workspace/sample-content/import", { method: "POST" }); - } - getAdminTemplateUpgradePreview(): Promise<{ - currentVersion: string; - latestVersion: string; - canUpgrade: boolean; - canRollback: boolean; - missingModules: unknown[]; - missingFields: unknown[]; - }> { - return this.request("/admin/workspace/template/preview"); - } - upgradeAdminTemplate(): Promise { - return this.request("/admin/workspace/template/upgrade", { method: "POST" }); - } - rollbackAdminTemplate(): Promise { - return this.request("/admin/workspace/template/rollback", { method: "POST" }); - } - createAdminField( - body: Omit, - ): Promise { - return this.request("/admin/workspace/fields", { method: "POST", body }); - } - deleteAdminField(id: string): Promise<{ deleted: boolean }> { - return this.request(`/admin/workspace/fields/${encodeURIComponent(id)}`, { method: "DELETE" }); - } - listAdminInquiryForms(): Promise { - return this.request("/admin/workspace/forms"); - } - listAdminInquirySubmissions(): Promise { - return this.request("/admin/workspace/submissions"); - } - updateAdminInquirySubmission( - id: string, - body: { status: InquirySubmission["status"]; adminNote?: string }, - ): Promise { - return this.request(`/admin/workspace/submissions/${encodeURIComponent(id)}`, { - method: "PATCH", - body, - }); - } - createAdminInquiryForm(body: { - name: string; - offeringId?: string; - fieldsSnapshot: unknown[]; - isEnabled?: boolean; - purpose?: InquiryForm["purpose"]; - targetType?: InquiryForm["targetType"]; - submissionAction?: InquiryForm["submissionAction"]; - }): Promise { - return this.request("/admin/workspace/forms", { method: "POST", body }); - } - updateAdminInquiryForm( - id: string, - body: Partial<{ - name: string; - offeringId: string; - fieldsSnapshot: unknown[]; - isEnabled: boolean; - purpose?: InquiryForm["purpose"]; - targetType?: InquiryForm["targetType"]; - submissionAction?: InquiryForm["submissionAction"]; - }>, - ): Promise { - return this.request(`/admin/workspace/forms/${encodeURIComponent(id)}`, { - method: "PATCH", - body, - }); - } - listAdminOfferings(): Promise { - return this.request("/admin/workspace/offerings"); - } - createAdminOffering(body: Omit): Promise { - return this.request("/admin/workspace/offerings", { method: "POST", body }); - } - updateAdminOffering( - id: string, - body: Partial>, - ): Promise { - return this.request(`/admin/workspace/offerings/${encodeURIComponent(id)}`, { - method: "PATCH", - body, - }); - } - deleteAdminOffering(id: string): Promise<{ deleted: boolean }> { - return this.request(`/admin/workspace/offerings/${encodeURIComponent(id)}`, { - method: "DELETE", - }); - } - listAdminTrustContent(): Promise { - return this.request("/admin/config/trust-content"); - } - createAdminTrustContent(body: TrustContentInput): Promise { - return this.request("/admin/config/trust-content", { method: "POST", body }); - } - updateAdminTrustContent(id: string, body: Partial): Promise { - return this.request(`/admin/config/trust-content/${encodeURIComponent(id)}`, { - method: "PATCH", - body, - }); - } - deleteAdminTrustContent(id: string): Promise<{ deleted: boolean }> { - return this.request(`/admin/config/trust-content/${encodeURIComponent(id)}`, { - method: "DELETE", - }); - } - getUploadConfig(): Promise { - return this.request("/admin/uploads/config"); - } - createPresignedUpload(body: { - fileName: string; - contentType: string; - scope?: "brand" | "offering" | "trust"; - }): Promise { - return this.request("/admin/uploads/presign", { method: "POST", body }); - } - private async request( - path: string, - options: { method?: string; body?: unknown } = {}, - ): Promise { - const headers: Record = { accept: "application/json" }; - if (options.body !== undefined) headers["content-type"] = "application/json"; - if (this.token) headers.authorization = `Bearer ${this.token}`; - const response = await this.fetcher(`${this.baseUrl}${path}`, { - method: options.method ?? "GET", - headers, - ...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }), - }); - const body = await response.json(); - if (!response.ok) throw new ApiClientError(response.status, body as ApiErrorBody); - return body as T; - } -} +export { isTrustContentComplete } from "@personal-brand/types"; export const apiClientName = "personal-brand-api-client"; -export { isTrustContentComplete } from "@personal-brand/types"; +import { bookingMethods } from "./resources/booking.js"; +import { brandMethods } from "./resources/brand.js"; +import { request as createRequest, type ApiClientOptions } from "./client/request.js"; +import { inquiryMethods } from "./resources/inquiry.js"; +import { mediaMethods } from "./resources/media.js"; +import { offeringMethods } from "./resources/offering.js"; +import { publicMethods } from "./resources/public.js"; +import { sessionMethods } from "./resources/session.js"; +import { templateMethods } from "./resources/template.js"; +import { trustMethods } from "./resources/trust.js"; +import type { BookingMethods } from "./resources/booking.js"; +import type { BrandMethods } from "./resources/brand.js"; +import type { InquiryMethods } from "./resources/inquiry.js"; +import type { MediaMethods } from "./resources/media.js"; +import type { OfferingMethods } from "./resources/offering.js"; +import type { PublicMethods } from "./resources/public.js"; +import type { SessionMethods } from "./resources/session.js"; +import type { TemplateMethods } from "./resources/template.js"; +import type { TrustMethods } from "./resources/trust.js"; + +type ClientState = { + baseUrl: string; + fetcher: ApiClientOptions["fetcher"]; + token?: string | undefined; +}; + +export class ApiClient + implements + BookingMethods, + BrandMethods, + InquiryMethods, + MediaMethods, + OfferingMethods, + PublicMethods, + SessionMethods, + TemplateMethods, + TrustMethods +{ + private readonly state: ClientState; + private readonly requestFn: ( + path: string, + options?: { method?: string; body?: unknown }, + ) => Promise; + private resources!: { + booking: BookingMethods; + brand: BrandMethods; + inquiry: InquiryMethods; + media: MediaMethods; + offering: OfferingMethods; + public: PublicMethods; + session: SessionMethods; + template: TemplateMethods; + trust: TrustMethods; + }; + + constructor(options: ApiClientOptions) { + this.state = { + baseUrl: options.baseUrl.replace(/\/$/, ""), + fetcher: options.fetcher, + token: options.token, + }; + this.requestFn = (path, methodOptions) => createRequest(this.state, path, methodOptions); + this.resources = { + booking: bookingMethods({ request: this.requestFn }), + brand: brandMethods({ request: this.requestFn }), + inquiry: inquiryMethods({ request: this.requestFn }), + media: mediaMethods({ request: this.requestFn }), + offering: offeringMethods({ request: this.requestFn }), + public: publicMethods({ request: this.requestFn }), + session: sessionMethods({ request: this.requestFn }), + template: templateMethods({ request: this.requestFn }), + trust: trustMethods({ request: this.requestFn }), + }; + } + + setToken(token: string | undefined): void { + this.state.token = token; + } + + getBrand = (...arguments_: Parameters) => + this.resources.public.getBrand(...arguments_); + listOfferings = (...arguments_: Parameters) => + this.resources.public.listOfferings(...arguments_); + getPublicWorkspace = (...arguments_: Parameters) => + this.resources.public.getPublicWorkspace(...arguments_); + getPublicInquiryForm = (...arguments_: Parameters) => + this.resources.public.getPublicInquiryForm(...arguments_); + createCustomerInquirySubmission = ( + ...arguments_: Parameters + ) => this.resources.public.createCustomerInquirySubmission(...arguments_); + listCustomerInquirySubmissions = ( + ...arguments_: Parameters + ) => this.resources.public.listCustomerInquirySubmissions(...arguments_); + getCustomerInquirySubmission = ( + ...arguments_: Parameters + ) => this.resources.public.getCustomerInquirySubmission(...arguments_); + createCustomerSession = (...arguments_: Parameters) => + this.resources.public.createCustomerSession(...arguments_); + loginAdmin = (...arguments_: Parameters) => + this.resources.session.loginAdmin(...arguments_); + changeAdminPassword = (...arguments_: Parameters) => + this.resources.session.changeAdminPassword(...arguments_); + listCustomerBookings = (...arguments_: Parameters) => + this.resources.booking.listCustomerBookings(...arguments_); + createCustomerBooking = (...arguments_: Parameters) => + this.resources.booking.createCustomerBooking(...arguments_); + cancelCustomerBooking = (...arguments_: Parameters) => + this.resources.booking.cancelCustomerBooking(...arguments_); + listAdminBookings = (...arguments_: Parameters) => + this.resources.booking.listAdminBookings(...arguments_); + getAdminBooking = (...arguments_: Parameters) => + this.resources.booking.getAdminBooking(...arguments_); + getAdminUnreadCount = (...arguments_: Parameters) => + this.resources.booking.getAdminUnreadCount(...arguments_); + updateAdminBookingStatus = ( + ...arguments_: Parameters + ) => this.resources.booking.updateAdminBookingStatus(...arguments_); + markAdminBookingRead = (...arguments_: Parameters) => + this.resources.booking.markAdminBookingRead(...arguments_); + listAdminTags = (...arguments_: Parameters) => + this.resources.booking.listAdminTags(...arguments_); + createAdminTag = (...arguments_: Parameters) => + this.resources.booking.createAdminTag(...arguments_); + getAdminBrand = (...arguments_: Parameters) => + this.resources.brand.getAdminBrand(...arguments_); + listAdminBrands = (...arguments_: Parameters) => + this.resources.brand.listAdminBrands(...arguments_); + switchAdminBrand = (...arguments_: Parameters) => + this.resources.brand.switchAdminBrand(...arguments_); + listAdminMembers = (...arguments_: Parameters) => + this.resources.brand.listAdminMembers(...arguments_); + createAdminMember = (...arguments_: Parameters) => + this.resources.brand.createAdminMember(...arguments_); + updateAdminMember = (...arguments_: Parameters) => + this.resources.brand.updateAdminMember(...arguments_); + getAdminVisualTemplatePreview = ( + ...arguments_: Parameters + ) => this.resources.brand.getAdminVisualTemplatePreview(...arguments_); + getAdminVisualTemplateHistory = ( + ...arguments_: Parameters + ) => this.resources.brand.getAdminVisualTemplateHistory(...arguments_); + rollbackAdminVisualTemplate = ( + ...arguments_: Parameters + ) => this.resources.brand.rollbackAdminVisualTemplate(...arguments_); + updateAdminBrand = (...arguments_: Parameters) => + this.resources.brand.updateAdminBrand(...arguments_); + updateAdminBrandPresentation = ( + ...arguments_: Parameters + ) => this.resources.brand.updateAdminBrandPresentation(...arguments_); + listAdminReleases = (...arguments_: Parameters) => + this.resources.brand.listAdminReleases(...arguments_); + getAdminReleaseReadiness = ( + ...arguments_: Parameters + ) => this.resources.brand.getAdminReleaseReadiness(...arguments_); + publishAdminRelease = (...arguments_: Parameters) => + this.resources.brand.publishAdminRelease(...arguments_); + rollbackAdminRelease = (...arguments_: Parameters) => + this.resources.brand.rollbackAdminRelease(...arguments_); + revokeAdminRelease = (...arguments_: Parameters) => + this.resources.brand.revokeAdminRelease(...arguments_); + getPublicTemplate = (...arguments_: Parameters) => + this.resources.template.getPublicTemplate(...arguments_); + listPublicTemplates = (...arguments_: Parameters) => + this.resources.template.listPublicTemplates(...arguments_); + previewPublicTemplateCombination = ( + ...arguments_: Parameters + ) => this.resources.template.previewPublicTemplateCombination(...arguments_); + getAdminWorkspace = (...arguments_: Parameters) => + this.resources.template.getAdminWorkspace(...arguments_); + getAdminPreviewWorkspace = ( + ...arguments_: Parameters + ) => this.resources.template.getAdminPreviewWorkspace(...arguments_); + installAdminTemplate = (...arguments_: Parameters) => + this.resources.template.installAdminTemplate(...arguments_); + listAdminCapabilities = (...arguments_: Parameters) => + this.resources.template.listAdminCapabilities(...arguments_); + updateAdminCapability = (...arguments_: Parameters) => + this.resources.template.updateAdminCapability(...arguments_); + previewAdminSampleContent = ( + ...arguments_: Parameters + ) => this.resources.template.previewAdminSampleContent(...arguments_); + importAdminSampleContent = ( + ...arguments_: Parameters + ) => this.resources.template.importAdminSampleContent(...arguments_); + getAdminTemplateUpgradePreview = ( + ...arguments_: Parameters + ) => this.resources.template.getAdminTemplateUpgradePreview(...arguments_); + upgradeAdminTemplate = (...arguments_: Parameters) => + this.resources.template.upgradeAdminTemplate(...arguments_); + rollbackAdminTemplate = (...arguments_: Parameters) => + this.resources.template.rollbackAdminTemplate(...arguments_); + getPublicOffering = (...arguments_: Parameters) => + this.resources.offering.getPublicOffering(...arguments_); + listPublicOfferings = (...arguments_: Parameters) => + this.resources.offering.listPublicOfferings(...arguments_); + listAdminOfferings = (...arguments_: Parameters) => + this.resources.offering.listAdminOfferings(...arguments_); + createAdminOffering = (...arguments_: Parameters) => + this.resources.offering.createAdminOffering(...arguments_); + updateAdminOffering = (...arguments_: Parameters) => + this.resources.offering.updateAdminOffering(...arguments_); + deleteAdminOffering = (...arguments_: Parameters) => + this.resources.offering.deleteAdminOffering(...arguments_); + createAdminField = (...arguments_: Parameters) => + this.resources.inquiry.createAdminField(...arguments_); + deleteAdminField = (...arguments_: Parameters) => + this.resources.inquiry.deleteAdminField(...arguments_); + listAdminInquiryForms = (...arguments_: Parameters) => + this.resources.inquiry.listAdminInquiryForms(...arguments_); + listAdminInquirySubmissions = ( + ...arguments_: Parameters + ) => this.resources.inquiry.listAdminInquirySubmissions(...arguments_); + updateAdminInquirySubmission = ( + ...arguments_: Parameters + ) => this.resources.inquiry.updateAdminInquirySubmission(...arguments_); + createAdminInquiryForm = (...arguments_: Parameters) => + this.resources.inquiry.createAdminInquiryForm(...arguments_); + updateAdminInquiryForm = (...arguments_: Parameters) => + this.resources.inquiry.updateAdminInquiryForm(...arguments_); + listAdminTrustContent = (...arguments_: Parameters) => + this.resources.trust.listAdminTrustContent(...arguments_); + createAdminTrustContent = (...arguments_: Parameters) => + this.resources.trust.createAdminTrustContent(...arguments_); + updateAdminTrustContent = (...arguments_: Parameters) => + this.resources.trust.updateAdminTrustContent(...arguments_); + deleteAdminTrustContent = (...arguments_: Parameters) => + this.resources.trust.deleteAdminTrustContent(...arguments_); + getUploadConfig = (...arguments_: Parameters) => + this.resources.media.getUploadConfig(...arguments_); + createPresignedUpload = (...arguments_: Parameters) => + this.resources.media.createPresignedUpload(...arguments_); +} diff --git a/packages/api-client/src/resources/booking.ts b/packages/api-client/src/resources/booking.ts new file mode 100644 index 0000000..d55fa88 --- /dev/null +++ b/packages/api-client/src/resources/booking.ts @@ -0,0 +1,55 @@ +import type { BookingStatus } from "@personal-brand/types"; +import type { RequestFn } from "../client/request.js"; +import type { + AdminBooking, + Booking, + BookingTag, + CreateBookingInput, + BookingSummary, +} from "../types/booking.js"; + +export interface BookingMethods { + listCustomerBookings(): Promise; + createCustomerBooking(input: CreateBookingInput): Promise; + cancelCustomerBooking(id: string): Promise; + listAdminBookings(filters?: { + status?: BookingStatus; + unreadOnly?: boolean; + tagId?: string; + }): Promise; + getAdminBooking(id: string): Promise; + getAdminUnreadCount(): Promise<{ count: number }>; + updateAdminBookingStatus(id: string, status: BookingStatus, adminNote?: string): Promise; + markAdminBookingRead(id: string): Promise; + listAdminTags(): Promise; + createAdminTag(name: string): Promise; +} + +export function bookingMethods({ request }: { request: RequestFn }): BookingMethods { + return { + listCustomerBookings: () => request("/customer/bookings"), + createCustomerBooking: (input) => + request("/customer/bookings", { method: "POST", body: input }), + cancelCustomerBooking: (id) => + request(`/customer/bookings/${encodeURIComponent(id)}/cancel`, { method: "POST" }), + listAdminBookings: (filters = {}) => { + const params: string[] = []; + if (filters.status) params.push(`status=${encodeURIComponent(filters.status)}`); + if (filters.unreadOnly !== undefined) params.push(`unreadOnly=${filters.unreadOnly}`); + if (filters.tagId) params.push(`tagId=${encodeURIComponent(filters.tagId)}`); + const query = params.join("&"); + return request(`/admin/bookings${query ? `?${query}` : ""}`); + }, + getAdminBooking: (id) => request(`/admin/bookings/${encodeURIComponent(id)}`), + getAdminUnreadCount: () => request("/admin/bookings/unread-count"), + updateAdminBookingStatus: (id, status, adminNote) => + request(`/admin/bookings/${encodeURIComponent(id)}/status`, { + method: "POST", + body: { status, ...(adminNote === undefined ? {} : { adminNote }) }, + }), + markAdminBookingRead: (id) => + request(`/admin/bookings/${encodeURIComponent(id)}/read`, { method: "POST" }), + listAdminTags: () => request("/admin/bookings/tags"), + createAdminTag: (name) => request("/admin/bookings/tags", { method: "POST", body: { name } }), + }; +} diff --git a/packages/api-client/src/resources/brand.ts b/packages/api-client/src/resources/brand.ts new file mode 100644 index 0000000..1cc89c5 --- /dev/null +++ b/packages/api-client/src/resources/brand.ts @@ -0,0 +1,98 @@ +import type { RequestFn } from "../client/request.js"; +import type { + AdminBrandMember, + AdminBrandMembership, + BrandPresentationUpdate, + BrandProfile, + BrandReleaseSummary, + BrandUpdate, +} from "../types/brand.js"; + +export interface BrandMethods { + getAdminBrand(): Promise; + listAdminBrands(): Promise; + switchAdminBrand( + brandId: string, + ): Promise<{ token: string; brand: AdminBrandMembership["brand"] }>; + listAdminMembers(): Promise; + createAdminMember(body: { + username: string; + displayName: string; + password: string; + role: "owner" | "editor"; + }): Promise; + updateAdminMember( + id: string, + body: Partial>, + ): Promise; + getAdminVisualTemplatePreview(): Promise<{ + current: { + key: string; + version: string; + name: string; + theme: { colors: Record }; + variants: Record; + } | null; + available: string[]; + }>; + getAdminVisualTemplateHistory(): Promise<{ + history: Array<{ visualTemplateKey: string; savedAt: string }>; + }>; + rollbackAdminVisualTemplate(): Promise<{ visualTemplateKey: string; rolledBack: boolean }>; + updateAdminBrand(body: BrandUpdate): Promise; + updateAdminBrandPresentation(body: BrandPresentationUpdate): Promise<{ + visualPresentation: Record>; + }>; + listAdminReleases(): Promise; + getAdminReleaseReadiness(): Promise<{ + ready: boolean; + checks: Array<{ + key: string; + label: string; + passed: boolean; + help?: string; + destination?: string; + }>; + }>; + publishAdminRelease(note?: string): Promise; + rollbackAdminRelease(version: number, note?: string): Promise; + revokeAdminRelease(): Promise< + Pick + >; +} + +export function brandMethods({ request }: { request: RequestFn }): BrandMethods { + return { + getAdminBrand: () => request("/admin/config/brand"), + listAdminBrands: () => request("/admin/brands"), + switchAdminBrand: (brandId) => + request(`/admin/brands/${encodeURIComponent(brandId)}/switch`, { method: "POST" }), + listAdminMembers: () => request("/admin/brands/members"), + createAdminMember: (body) => request("/admin/brands/members", { method: "POST", body }), + updateAdminMember: (id, body) => + request(`/admin/brands/members/${encodeURIComponent(id)}`, { + method: "PATCH", + body, + }), + getAdminVisualTemplatePreview: () => request("/admin/config/visual-template/preview"), + getAdminVisualTemplateHistory: () => request("/admin/config/visual-template/history"), + rollbackAdminVisualTemplate: () => + request("/admin/config/visual-template/rollback", { method: "POST" }), + updateAdminBrand: (body) => request("/admin/config/brand", { method: "PATCH", body }), + updateAdminBrandPresentation: (body) => + request("/admin/config/presentation", { method: "PATCH", body }), + listAdminReleases: () => request("/admin/releases"), + getAdminReleaseReadiness: () => request("/admin/releases/readiness"), + publishAdminRelease: (note) => + request("/admin/releases/publish", { + method: "POST", + body: note === undefined ? {} : { note }, + }), + rollbackAdminRelease: (version, note) => + request(`/admin/releases/${version}/rollback`, { + method: "POST", + body: note === undefined ? {} : { note }, + }), + revokeAdminRelease: () => request("/admin/releases/revoke", { method: "POST" }), + }; +} diff --git a/packages/api-client/src/resources/inquiry.ts b/packages/api-client/src/resources/inquiry.ts new file mode 100644 index 0000000..71850da --- /dev/null +++ b/packages/api-client/src/resources/inquiry.ts @@ -0,0 +1,58 @@ +import type { RequestFn } from "../client/request.js"; +import type { BrandFieldDefinition } from "../types/field.js"; +import type { InquiryForm, InquirySubmission } from "../types/inquiry.js"; + +export interface InquiryMethods { + createAdminField( + body: Omit, + ): Promise; + deleteAdminField(id: string): Promise<{ deleted: boolean }>; + listAdminInquiryForms(): Promise; + listAdminInquirySubmissions(): Promise; + updateAdminInquirySubmission( + id: string, + body: { status: InquirySubmission["status"]; adminNote?: string }, + ): Promise; + createAdminInquiryForm(body: { + name: string; + offeringId?: string; + fieldsSnapshot: unknown[]; + isEnabled?: boolean; + purpose?: InquiryForm["purpose"]; + targetType?: InquiryForm["targetType"]; + submissionAction?: InquiryForm["submissionAction"]; + }): Promise; + updateAdminInquiryForm( + id: string, + body: Partial<{ + name: string; + offeringId: string; + fieldsSnapshot: unknown[]; + isEnabled: boolean; + purpose?: InquiryForm["purpose"]; + targetType?: InquiryForm["targetType"]; + submissionAction?: InquiryForm["submissionAction"]; + }>, + ): Promise; +} + +export function inquiryMethods({ request }: { request: RequestFn }): InquiryMethods { + return { + createAdminField: (body) => request("/admin/workspace/fields", { method: "POST", body }), + deleteAdminField: (id) => + request(`/admin/workspace/fields/${encodeURIComponent(id)}`, { method: "DELETE" }), + listAdminInquiryForms: () => request("/admin/workspace/forms"), + listAdminInquirySubmissions: () => request("/admin/workspace/submissions"), + updateAdminInquirySubmission: (id, body) => + request(`/admin/workspace/submissions/${encodeURIComponent(id)}`, { + method: "PATCH", + body, + }), + createAdminInquiryForm: (body) => request("/admin/workspace/forms", { method: "POST", body }), + updateAdminInquiryForm: (id, body) => + request(`/admin/workspace/forms/${encodeURIComponent(id)}`, { + method: "PATCH", + body, + }), + }; +} diff --git a/packages/api-client/src/resources/media.ts b/packages/api-client/src/resources/media.ts new file mode 100644 index 0000000..2a291dc --- /dev/null +++ b/packages/api-client/src/resources/media.ts @@ -0,0 +1,18 @@ +import type { RequestFn } from "../client/request.js"; +import type { PresignedUpload, UploadConfig } from "../types/media.js"; + +export interface MediaMethods { + getUploadConfig(): Promise; + createPresignedUpload(body: { + fileName: string; + contentType: string; + scope?: "brand" | "offering" | "trust"; + }): Promise; +} + +export function mediaMethods({ request }: { request: RequestFn }): MediaMethods { + return { + getUploadConfig: () => request("/admin/uploads/config"), + createPresignedUpload: (body) => request("/admin/uploads/presign", { method: "POST", body }), + }; +} diff --git a/packages/api-client/src/resources/offering.ts b/packages/api-client/src/resources/offering.ts new file mode 100644 index 0000000..715f4f2 --- /dev/null +++ b/packages/api-client/src/resources/offering.ts @@ -0,0 +1,32 @@ +import type { RequestFn } from "../client/request.js"; +import type { Offering } from "../types/offering.js"; + +export interface OfferingMethods { + getPublicOffering(id: string): Promise; + listPublicOfferings(): Promise; + listAdminOfferings(): Promise; + createAdminOffering(body: Omit): Promise; + updateAdminOffering( + id: string, + body: Partial>, + ): Promise; + deleteAdminOffering(id: string): Promise<{ deleted: boolean }>; +} + +export function offeringMethods({ request }: { request: RequestFn }): OfferingMethods { + return { + getPublicOffering: (id) => request(`/public/offerings/${encodeURIComponent(id)}`), + listPublicOfferings: () => request("/public/offerings"), + listAdminOfferings: () => request("/admin/workspace/offerings"), + createAdminOffering: (body) => request("/admin/workspace/offerings", { method: "POST", body }), + updateAdminOffering: (id, body) => + request(`/admin/workspace/offerings/${encodeURIComponent(id)}`, { + method: "PATCH", + body, + }), + deleteAdminOffering: (id) => + request(`/admin/workspace/offerings/${encodeURIComponent(id)}`, { + method: "DELETE", + }), + }; +} diff --git a/packages/api-client/src/resources/public.ts b/packages/api-client/src/resources/public.ts new file mode 100644 index 0000000..532f3d5 --- /dev/null +++ b/packages/api-client/src/resources/public.ts @@ -0,0 +1,38 @@ +import type { PublicOffering } from "@personal-brand/types"; +import type { RequestFn } from "../client/request.js"; +import type { BrandProfile } from "../types/brand.js"; +import type { InquiryForm, InquirySubmission } from "../types/inquiry.js"; +import type { PublicWorkspace } from "../types/workspace.js"; + +export interface PublicMethods { + getBrand(): Promise; + listOfferings(): Promise; + getPublicWorkspace(): Promise; + getPublicInquiryForm(id: string): Promise; + createCustomerInquirySubmission( + formId: string, + values: Record, + ): Promise; + listCustomerInquirySubmissions(): Promise; + getCustomerInquirySubmission(id: string): Promise; + createCustomerSession(code: string): Promise<{ token: string }>; +} + +export function publicMethods({ request }: { request: RequestFn }): PublicMethods { + return { + getBrand: () => request("/public/brand"), + listOfferings: () => request("/public/offerings"), + getPublicWorkspace: () => request("/public/workspace"), + getPublicInquiryForm: (id) => request(`/public/inquiry-forms/${encodeURIComponent(id)}`), + createCustomerInquirySubmission: (formId, values) => + request("/customer/inquiry-submissions", { + method: "POST", + body: { formId, values }, + }), + listCustomerInquirySubmissions: () => request("/customer/inquiry-submissions"), + getCustomerInquirySubmission: (id) => + request(`/customer/inquiry-submissions/${encodeURIComponent(id)}`), + createCustomerSession: (code) => + request("/customer/session/wechat", { method: "POST", body: { code } }), + }; +} diff --git a/packages/api-client/src/resources/session.ts b/packages/api-client/src/resources/session.ts new file mode 100644 index 0000000..ed89cbb --- /dev/null +++ b/packages/api-client/src/resources/session.ts @@ -0,0 +1,26 @@ +import type { RequestFn } from "../client/request.js"; + +export interface SessionMethods { + loginAdmin( + username: string, + password: string, + ): Promise<{ + token: string; + displayName: string; + mustChangePassword: boolean; + role: string; + }>; + changeAdminPassword(currentPassword: string, newPassword: string): Promise<{ changed: true }>; +} + +export function sessionMethods({ request }: { request: RequestFn }): SessionMethods { + return { + loginAdmin: (username, password) => + request("/admin/session/login", { method: "POST", body: { username, password } }), + changeAdminPassword: (currentPassword, newPassword) => + request("/admin/session/change-password", { + method: "POST", + body: { currentPassword, newPassword }, + }), + }; +} diff --git a/packages/api-client/src/resources/template.ts b/packages/api-client/src/resources/template.ts new file mode 100644 index 0000000..15483ee --- /dev/null +++ b/packages/api-client/src/resources/template.ts @@ -0,0 +1,150 @@ +import type { BrandTemplateKey, RuntimeWorkspace } from "@personal-brand/types"; +import type { RequestFn } from "../client/request.js"; +import type { BrandProfile } from "../types/brand.js"; +import type { CapabilityInstallation } from "../types/capability.js"; +import type { BrandFieldDefinition } from "../types/field.js"; +import type { Offering } from "../types/offering.js"; +import type { AdminTemplateContent } from "../types/template.js"; +import type { BrandTemplateDefinition } from "../types/template-definition.js"; + +export interface TemplateMethods { + getPublicTemplate(key: BrandTemplateKey): Promise; + listPublicTemplates(): Promise<{ + industries: BrandTemplateDefinition[]; + visuals: Array<{ + key: string; + version: string; + name: string; + description: string; + supportedIndustryTemplates: BrandTemplateKey[]; + variants: Record; + theme: { colors: Record }; + }>; + }>; + previewPublicTemplateCombination( + industry: string, + visual: string, + ): Promise<{ + industry: BrandTemplateDefinition; + visual: { + key: string; + version: string; + name: string; + description: string; + supportedIndustryTemplates: BrandTemplateKey[]; + variants: Record; + theme: { colors: Record }; + }; + runtime: { + schemaVersion: string; + capabilities: Array<{ key: string; version: string }>; + theme: unknown; + }; + }>; + getAdminWorkspace(): Promise<{ + brand: BrandProfile; + visualTemplate?: { + key: string; + version: string; + name: string; + supportedIndustryTemplates: BrandTemplateKey[]; + variants: Record; + } | null; + installations: Array<{ id: string; templateKey: BrandTemplateKey; templateVersion: string }>; + fields: BrandFieldDefinition[]; + offerings: Offering[]; + forms: unknown[]; + templateContent: AdminTemplateContent | null; + }>; + getAdminPreviewWorkspace(): Promise; + installAdminTemplate(templateKey: "personal" | "food" | "doors"): Promise; + listAdminCapabilities(): Promise; + updateAdminCapability( + key: string, + body: { + capabilityVersion: string; + status: CapabilityInstallation["status"]; + config?: Record; + }, + ): Promise; + previewAdminSampleContent(): Promise<{ + templateKey: string; + alreadyImported: boolean; + counts: Record; + willCreateInquiryForm: boolean; + }>; + importAdminSampleContent(): Promise<{ imported: boolean; counts: Record }>; + getAdminTemplateUpgradePreview(): Promise<{ + currentVersion: string; + latestVersion: string; + canUpgrade: boolean; + canRollback: boolean; + missingModules: unknown[]; + missingFields: unknown[]; + }>; + upgradeAdminTemplate(): Promise; + rollbackAdminTemplate(): Promise; +} + +export function templateMethods({ request }: { request: RequestFn }): TemplateMethods { + return { + getPublicTemplate: (key) => request(`/public/templates/${key}`), + listPublicTemplates: () => + request<{ + industries: BrandTemplateDefinition[]; + visuals: Array<{ + key: string; + version: string; + name: string; + description: string; + supportedIndustryTemplates?: unknown; + variants?: unknown; + theme?: unknown; + }>; + }>("/public/templates").then((catalog) => ({ + industries: Array.isArray(catalog.industries) ? catalog.industries : [], + visuals: Array.isArray(catalog.visuals) + ? catalog.visuals.map((visual) => ({ + key: String(visual.key ?? ""), + version: String(visual.version ?? ""), + name: String(visual.name ?? "未命名视觉模板"), + description: String(visual.description ?? ""), + supportedIndustryTemplates: Array.isArray(visual.supportedIndustryTemplates) + ? visual.supportedIndustryTemplates.filter( + (item): item is BrandTemplateKey => + item === "personal" || item === "food" || item === "doors", + ) + : [], + variants: + visual.variants && typeof visual.variants === "object" + ? (visual.variants as Record) + : {}, + theme: + visual.theme && typeof visual.theme === "object" + ? (visual.theme as { colors: Record }) + : { colors: {} }, + })) + : [], + })), + previewPublicTemplateCombination: (industry, visual) => + request( + `/public/templates/preview?industry=${encodeURIComponent(industry)}&visual=${encodeURIComponent(visual)}`, + ), + getAdminWorkspace: () => request("/admin/workspace"), + getAdminPreviewWorkspace: () => request("/admin/workspace/preview"), + installAdminTemplate: (templateKey) => + request("/admin/workspace/install", { method: "POST", body: { templateKey } }), + listAdminCapabilities: () => request("/admin/workspace/capabilities"), + updateAdminCapability: (key, body) => + request(`/admin/workspace/capabilities/${encodeURIComponent(key)}`, { + method: "PATCH", + body, + }), + previewAdminSampleContent: () => request("/admin/workspace/sample-content/preview"), + importAdminSampleContent: () => + request("/admin/workspace/sample-content/import", { method: "POST" }), + getAdminTemplateUpgradePreview: () => request("/admin/workspace/template/preview"), + upgradeAdminTemplate: () => request("/admin/workspace/template/upgrade", { method: "POST" }), + rollbackAdminTemplate: () => request("/admin/workspace/template/rollback", { method: "POST" }), + }; +} diff --git a/packages/api-client/src/resources/trust.ts b/packages/api-client/src/resources/trust.ts new file mode 100644 index 0000000..f7f9611 --- /dev/null +++ b/packages/api-client/src/resources/trust.ts @@ -0,0 +1,26 @@ +import type { RequestFn } from "../client/request.js"; +import type { TrustContent, TrustContentInput } from "../types/trust.js"; + +export interface TrustMethods { + listAdminTrustContent(): Promise; + createAdminTrustContent(body: TrustContentInput): Promise; + updateAdminTrustContent(id: string, body: Partial): Promise; + deleteAdminTrustContent(id: string): Promise<{ deleted: boolean }>; +} + +export function trustMethods({ request }: { request: RequestFn }): TrustMethods { + return { + listAdminTrustContent: () => request("/admin/config/trust-content"), + createAdminTrustContent: (body) => + request("/admin/config/trust-content", { method: "POST", body }), + updateAdminTrustContent: (id, body) => + request(`/admin/config/trust-content/${encodeURIComponent(id)}`, { + method: "PATCH", + body, + }), + deleteAdminTrustContent: (id) => + request(`/admin/config/trust-content/${encodeURIComponent(id)}`, { + method: "DELETE", + }), + }; +} diff --git a/packages/api-client/src/types/booking.ts b/packages/api-client/src/types/booking.ts new file mode 100644 index 0000000..d993849 --- /dev/null +++ b/packages/api-client/src/types/booking.ts @@ -0,0 +1,51 @@ +import type { + BookingRequestType, + BookingStatus, + ContactPreference, + FulfillmentType, +} from "@personal-brand/types"; + +export interface BookingItemInput { + offeringId: string; + quantity: number; +} + +export interface CreateBookingInput { + requestType: BookingRequestType; + customerName: string; + phone?: string; + wechatId?: string; + contactPreference: ContactPreference; + fulfillmentType?: FulfillmentType; + offeringId?: string; + requestedDate?: string; + requestedTime?: string; + deliveryAddress?: string; + note?: string; + extraData?: Record; + items: BookingItemInput[]; +} + +export interface BookingSummary { + bookingNo: string; + status: BookingStatus; + estimatedAmount: number | null; + createdAt: string; +} + +export interface Booking extends BookingSummary { + id: string; + customerName: string; + adminNote?: string | null; +} + +export interface BookingTag { + id: string; + name: string; + isPreset: boolean; + isEnabled: boolean; +} + +export interface AdminBooking extends Booking { + tags?: Array<{ tag: BookingTag }>; +} diff --git a/packages/api-client/src/types/brand.ts b/packages/api-client/src/types/brand.ts new file mode 100644 index 0000000..20d6b0c --- /dev/null +++ b/packages/api-client/src/types/brand.ts @@ -0,0 +1,56 @@ +import type { BrandTemplateKey } from "@personal-brand/types"; + +export interface BrandProfile { + id: string; + slug?: string; + name: string; + templateKey: BrandTemplateKey; + tagline: string | null; + description: string | null; + avatarUrl: string | null; + coverUrl: string | null; + hours: string | null; + address: string | null; + deliveryNote: string | null; + contactPhone: string | null; + contactWechat: string | null; + config?: Record | null; +} + +export interface AdminBrandMembership { + id: string; + role: string; + brand: Pick & { slug?: string }; +} + +export interface AdminBrandMember { + id: string; + role: string; + isEnabled: boolean; + adminUser: { + id: string; + username: string; + displayName: string; + isEnabled: boolean; + }; +} + +export type BrandUpdate = Partial>; + +export interface BrandReleaseSummary { + id: string; + version: number; + status: string; + note: string | null; + actorId: string; + createdAt: string; + revokedAt: string | null; + revokedBy?: string | null; +} + +export type BrandPresentationUpdate = Partial< + Record< + "identity" | "home" | "offerings" | "detail" | "profile" | "inquiry" | "success" | "records", + Record + > +>; diff --git a/packages/api-client/src/types/capability.ts b/packages/api-client/src/types/capability.ts new file mode 100644 index 0000000..53b5f09 --- /dev/null +++ b/packages/api-client/src/types/capability.ts @@ -0,0 +1,9 @@ +export interface CapabilityInstallation { + id: string | null; + capabilityKey: string; + capabilityVersion: string; + status: "enabled" | "disabled" | "degraded"; + config?: Record | null; + updatedAt: string | null; + source?: "template" | "brand"; +} diff --git a/packages/api-client/src/types/common.ts b/packages/api-client/src/types/common.ts new file mode 100644 index 0000000..e23973e --- /dev/null +++ b/packages/api-client/src/types/common.ts @@ -0,0 +1,5 @@ +export interface ApiErrorBody { + data: null; + error: { code: string; message: string }; + requestId: string | null; +} diff --git a/packages/api-client/src/types/field.ts b/packages/api-client/src/types/field.ts new file mode 100644 index 0000000..243180f --- /dev/null +++ b/packages/api-client/src/types/field.ts @@ -0,0 +1,11 @@ +export interface BrandFieldDefinition { + id: string; + scope: string; + key: string; + label: string; + type: string; + required: boolean; + isVisible: boolean; + sortOrder: number; + source: string; +} diff --git a/packages/api-client/src/types/inquiry.ts b/packages/api-client/src/types/inquiry.ts new file mode 100644 index 0000000..a8d695a --- /dev/null +++ b/packages/api-client/src/types/inquiry.ts @@ -0,0 +1,30 @@ +export interface InquiryForm { + id: string; + name: string; + offeringId?: string | null; + version: number; + isEnabled: boolean; + fieldsSnapshot: unknown[]; + purpose: "inquiry" | "booking" | "quote-request"; + targetType: "brand" | "offering"; + submissionAction: "create-inquiry" | "create-booking" | "create-quote"; +} + +export interface InquirySubmission { + id: string; + inquiryFormId: string; + formVersion: number; + fieldsSnapshot: unknown[]; + values: Record; + activeFields: Record; + createdAt: string; + status: "new" | "reviewing" | "replied" | "qualified" | "converted" | "closed"; + adminNote?: string | null; + inquiryForm?: { name: string }; + offering?: { id: string; name: string } | null; + statusHistory?: Array<{ + fromStatus?: string | null; + toStatus: string; + createdAt: string; + }>; +} diff --git a/packages/api-client/src/types/media.ts b/packages/api-client/src/types/media.ts new file mode 100644 index 0000000..b69f4b5 --- /dev/null +++ b/packages/api-client/src/types/media.ts @@ -0,0 +1,11 @@ +export interface UploadConfig { + configured: boolean; + status: "ok" | "unavailable" | "unconfigured"; + bucket?: string; +} + +export interface PresignedUpload { + uploadUrl: string; + key: string; + publicUrl: string; +} diff --git a/packages/api-client/src/types/offering.ts b/packages/api-client/src/types/offering.ts new file mode 100644 index 0000000..93597e2 --- /dev/null +++ b/packages/api-client/src/types/offering.ts @@ -0,0 +1,52 @@ +import type { InquiryForm } from "./inquiry.js"; + +export interface OfferingSection { + type: "text" | "image-list" | "timeline" | "faq"; + title: string; + content?: string; + items?: unknown[]; +} + +export interface OfferingMedia { + url: string; + alt?: string; + type?: "image" | "video"; +} + +export interface OfferingCta { + type: "inquiry" | "booking" | "contact" | "external-link"; + label: string; + config?: Record; +} + +export interface Offering { + id: string; + brandId?: string; + kind: "service" | "product" | "package" | "subscription"; + name: string; + summary?: string | null; + description?: string | null; + coverUrl?: string | null; + priceText?: string | null; + priceAmount?: number | null; + isEnabled: boolean; + sortOrder: number; + config?: Record | null; + sections?: OfferingSection[]; + media?: OfferingMedia[]; + cta?: OfferingCta; + inquiryForms?: Array>; +} + +export interface OfferingUpdate { + name?: string; + description?: string; + coverUrl?: string; + priceText?: string; + priceAmount?: number; + sortOrder?: number; + bookingEnabled?: boolean; + isEnabled?: boolean; + categoryKey?: string; + config?: Record; +} diff --git a/packages/api-client/src/types/template-definition.ts b/packages/api-client/src/types/template-definition.ts new file mode 100644 index 0000000..ed49e90 --- /dev/null +++ b/packages/api-client/src/types/template-definition.ts @@ -0,0 +1,27 @@ +export interface BrandTemplateDefinition { + key: "personal" | "food" | "doors"; + version: string; + name: string; + description: string; + serviceCategories: string[]; + trustContentTypes: string[]; + modules: Array<{ + key: string; + type: string; + title: string; + required: boolean; + }>; + fields: Array<{ + scope: string; + key: string; + label: string; + type: string; + required: boolean; + }>; + capabilities: string[]; + runtimeCapabilities: Array<{ + key: string; + version: string; + workflowKey?: string; + }>; +} diff --git a/packages/api-client/src/types/template.ts b/packages/api-client/src/types/template.ts new file mode 100644 index 0000000..ea39dd7 --- /dev/null +++ b/packages/api-client/src/types/template.ts @@ -0,0 +1,80 @@ +export interface TemplateAdminField { + key: string; + page?: string; + binding: string; + label: string; + help?: string; + input: + | "text" + | "textarea" + | "phone" + | "image" + | "number" + | "boolean" + | "select" + | "multi-select" + | "list"; + itemFields?: Array<{ + key: string; + label: string; + input?: "text" | "textarea"; + required?: boolean; + }>; + itemValueKey?: string; + required?: boolean; + maxLength?: number; + placeholder?: string; + options?: Array<{ value: string; label: string }>; + previewTarget?: string; +} + +export interface TemplateAdminSection { + key: string; + title: string; + description: string; + page: string; + target: "brand" | "offering" | "trust" | "inquiry"; + previewTargets?: Array<{ + key: string; + label: string; + composite?: boolean; + children?: string[]; + }>; + fields: TemplateAdminField[]; +} + +export interface AdminTemplateContent { + displayName: string; + admin: { sections: TemplateAdminSection[] }; + navigation: Array<{ key: string; label: string; page: string }>; + templateFields?: TemplateAdminField[]; + trustContentTypes?: Array<{ + type: string; + label: string; + adminFields: { + title: string; + summary: string; + content: string; + summaryHelp?: string; + summaryPlaceholder?: string; + }; + pages?: string[]; + help?: string; + placeholder?: string; + required?: boolean; + configFields?: TemplateAdminField[]; + previewTargets?: Array<{ key: string; label: string; page?: string }>; + maxPublishedItems?: number; + hideStandardFields?: Array<"summary" | "content">; + }>; + assetSlots: Array<{ + key: string; + binding: string; + target: "brand" | "offering" | "trust"; + label: string; + help: string; + required: boolean; + kind: "image" | "logo" | "portrait" | "texture"; + aspectRatio?: string; + }>; +} diff --git a/packages/api-client/src/types/trust.ts b/packages/api-client/src/types/trust.ts new file mode 100644 index 0000000..f2b313f --- /dev/null +++ b/packages/api-client/src/types/trust.ts @@ -0,0 +1,22 @@ +export interface TrustContent { + id: string; + type: string; + title: string; + summary?: string | null; + content: string; + coverUrl?: string | null; + sortOrder: number; + isPublished: boolean; + config?: Record | null; +} + +export interface TrustContentInput { + type: string; + title: string; + summary?: string; + content: string; + coverUrl?: string; + sortOrder?: number; + isPublished?: boolean; + config?: Record; +} diff --git a/packages/api-client/src/types/workspace.ts b/packages/api-client/src/types/workspace.ts new file mode 100644 index 0000000..496aa84 --- /dev/null +++ b/packages/api-client/src/types/workspace.ts @@ -0,0 +1,76 @@ +import type { + BrandTemplateKey, + RuntimeCapability, + RuntimeInquiryForm, + RuntimeOffering, + RuntimeTrustItem, + ThemeManifest, +} from "@personal-brand/types"; +import type { BrandProfile } from "./brand.js"; + +export interface PublicWorkspace { + schemaVersion: string; + contractVersion: string; + publication: { + status: "published" | "unpublished"; + version: number | null; + publishedAt?: string; + }; + brand: (BrandProfile & Record) | null; + template: { key: BrandTemplateKey; version: string; name: string } | null; + visualTemplate: { + key: string; + version: string; + name: string; + supportedIndustryTemplates: BrandTemplateKey[]; + variants: Record; + } | null; + visualTemplateManifest?: { + schemaVersion: "1.0"; + key: string; + version: string; + name: string; + brandFirst: true; + tokens: { + colors: Record; + spacing: Record; + typography: Record; + radius: Record; + shadows?: Record; + }; + pages: Array<{ + key: string; + title: string; + modules: Array<{ + key: string; + type: string; + variant: string; + required: boolean; + dataSlots?: string[]; + assetSlots?: string[]; + capability?: string; + }>; + }>; + assets: Array>; + dataSlots: Array>; + capabilities: string[]; + }; + capabilities: RuntimeCapability[]; + offerings: RuntimeOffering[]; + inquiryForms: RuntimeInquiryForm[]; + trustItems: RuntimeTrustItem[]; + navigation: { tabs: Array<{ key: string; label: string; page: string }> }; + trustPresentation: Record; + theme: ThemeManifest; + layout?: { home: string[]; offerings: string[]; detail: string[]; profile: string[] }; + plugins?: Array<{ + key: string; + version: string; + displayName: string; + purpose: string; + requiredModules: string[]; + apiContract: string; + configSchema: string; + status: string; + }>; +} diff --git a/packages/api-client/test/exports.test.ts b/packages/api-client/test/exports.test.ts new file mode 100644 index 0000000..cb83eb1 --- /dev/null +++ b/packages/api-client/test/exports.test.ts @@ -0,0 +1,18 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import * as apiClientModule from "../src/index.js"; + +test("聚合导出保持既有公共契约", () => { + const expectedExports = [ + "ApiClient", + "ApiClientError", + "apiClientName", + "isTrustContentComplete", + "projectBrandAliases", + "projectTrustPresentation", + ]; + + for (const exportName of expectedExports) { + assert.ok(exportName in apiClientModule, `${exportName} 必须保留导出`); + } +}); From 466dc6690763e8608c302a192e723744462614c2 Mon Sep 17 00:00:00 2001 From: que01 Date: Mon, 12 Oct 2026 05:11:26 +0800 Subject: [PATCH 7/7] =?UTF-8?q?refactor:=20=E6=8B=86=E5=88=86=E4=B8=9A?= =?UTF-8?q?=E5=8A=A1=E3=80=81=E4=BF=A1=E4=BB=BB=E5=86=85=E5=AE=B9=E4=B8=8E?= =?UTF-8?q?=E5=85=AC=E5=85=B1=E5=B7=A5=E4=BD=9C=E5=8F=B0=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/components/RecordContentEditor.tsx | 120 +- .../src/components/record-content/types.ts | 14 + .../useRecordContentEditorState.ts | 117 + .../features/services/OfferingEditorModal.tsx | 181 + .../src/features/services/OfferingsTable.tsx | 113 + .../src/features/services/ServicesPage.tsx | 609 +--- .../src/features/services/offering-form.ts | 87 + .../src/features/services/offering-model.ts | 15 + .../src/features/services/offering-preview.ts | 104 + .../features/services/use-offering-data.ts | 91 + .../features/services/use-offering-editor.ts | 68 + .../trust-content/TrustContentPage.tsx | 437 +-- .../components/TrustContentEditorModal.tsx | 123 + .../components/TrustContentTable.tsx | 77 + .../components/TrustRequirementsList.tsx | 65 + .../domain/trust-content-domain.ts | 117 + .../hooks/useTrustContentEditor.ts | 56 + .../hooks/useTrustContentMutations.ts | 37 + .../hooks/useTrustContentQueries.ts | 17 + .../public/public-workspace.controller.ts | 377 +- .../public/public-workspace.runtime-mapper.ts | 162 + .../public-workspace.snapshot-assembler.ts | 213 ++ eslint.config.mjs | 2 +- packages/config/package.json | 5 +- .../src/generated-template-packages.d.ts | 3 - .../config/src/generated-template-packages.js | 3125 ----------------- .../config/src/generated-template-packages.ts | 3067 ++++++++++++++++ .../config/src/template-package-manifest.ts | 28 +- .../config/src/template-sample-content.ts | 1 + packages/config/tsconfig.json | 5 +- .../test/editability.test.mjs | 5 +- .../template-contract/test/manifest.test.mjs | 2 +- scripts/generate-template-catalog.cjs | 7 +- 33 files changed, 4950 insertions(+), 4500 deletions(-) create mode 100644 apps/admin/src/components/record-content/types.ts create mode 100644 apps/admin/src/components/record-content/useRecordContentEditorState.ts create mode 100644 apps/admin/src/features/services/OfferingEditorModal.tsx create mode 100644 apps/admin/src/features/services/OfferingsTable.tsx create mode 100644 apps/admin/src/features/services/offering-form.ts create mode 100644 apps/admin/src/features/services/offering-model.ts create mode 100644 apps/admin/src/features/services/offering-preview.ts create mode 100644 apps/admin/src/features/services/use-offering-data.ts create mode 100644 apps/admin/src/features/services/use-offering-editor.ts create mode 100644 apps/admin/src/features/trust-content/components/TrustContentEditorModal.tsx create mode 100644 apps/admin/src/features/trust-content/components/TrustContentTable.tsx create mode 100644 apps/admin/src/features/trust-content/components/TrustRequirementsList.tsx create mode 100644 apps/admin/src/features/trust-content/domain/trust-content-domain.ts create mode 100644 apps/admin/src/features/trust-content/hooks/useTrustContentEditor.ts create mode 100644 apps/admin/src/features/trust-content/hooks/useTrustContentMutations.ts create mode 100644 apps/admin/src/features/trust-content/hooks/useTrustContentQueries.ts create mode 100644 apps/api/src/modules/public/public-workspace.runtime-mapper.ts create mode 100644 apps/api/src/modules/public/public-workspace.snapshot-assembler.ts delete mode 100644 packages/config/src/generated-template-packages.d.ts delete mode 100644 packages/config/src/generated-template-packages.js create mode 100644 packages/config/src/generated-template-packages.ts diff --git a/apps/admin/src/components/RecordContentEditor.tsx b/apps/admin/src/components/RecordContentEditor.tsx index 66cfe8f..59dd01a 100644 --- a/apps/admin/src/components/RecordContentEditor.tsx +++ b/apps/admin/src/components/RecordContentEditor.tsx @@ -1,31 +1,14 @@ -import { Alert, Button, Col, Form, Row, Space, Typography, message } from "antd"; -import { useMutation, useQueryClient } from "@tanstack/react-query"; -import { useEffect, useMemo, useState } from "react"; +import { Alert, Button, Col, Form, Row, Space, Typography } from "antd"; import { useNavigate } from "react-router-dom"; -import type { Offering, TemplateAdminSection, TrustContent } from "@personal-brand/api-client"; -import { createApiClient } from "../lib/api.js"; +import type { TemplateAdminSection } from "@personal-brand/api-client"; import { TemplateListField } from "./TemplateListField.js"; import { TemplateFieldRenderer } from "./TemplateFieldRenderer.js"; import { MutationError } from "./QueryState.js"; -import { - applyPresentationValues, - applyStandardEntityValues, - presentationFieldName, - readPresentationValue, - type PresentationValues, -} from "../features/brand/presentation-bindings.js"; +import { presentationFieldName } from "../features/brand/presentation-bindings.js"; +import { useRecordContentEditorState } from "./record-content/useRecordContentEditorState.js"; +import type { RecordContentEditorProps, RecordContentSource } from "./record-content/types.js"; -export type RecordContentSource = "offering" | "trust"; - -export interface RecordContentEditorProps { - source: RecordContentSource; - record: Offering | TrustContent; - section: TemplateAdminSection; - context: "visual" | "services"; - onDraft?: (values: PresentationValues) => void; - onSaved?: () => void; - visualSelection?: { targetKey: string; page: string }; -} +export type { RecordContentEditorProps, RecordContentSource }; export function RecordContentFields({ section, @@ -72,95 +55,22 @@ export function RecordContentEditor({ visualSelection, }: RecordContentEditorProps) { const navigate = useNavigate(); - const [form] = Form.useForm(); - const queryClient = useQueryClient(); const recordName = "name" in record ? record.name : record.title; - const [draftValues, setDraftValues] = useState(() => - Object.fromEntries( - section.fields.map((field) => [ - presentationFieldName(section.key, field.key), - readPresentationValue( - record.config, - field.binding, - field, - record as unknown as Record, - ), - ]), - ), - ); - const initialValues = useMemo( - () => - Object.fromEntries( - section.fields.map((field) => [ - presentationFieldName(section.key, field.key), - readPresentationValue( - record.config, - field.binding, - field, - record as unknown as Record, - ), - ]), - ), - [record, section], - ); - useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]); - const save = useMutation({ - mutationFn: async (values: PresentationValues): Promise => { - const config = applyPresentationValues(record.config, [section], values); - const standard = applyStandardEntityValues( - record as unknown as Record, - source, - [section], - values, - ); - const changed = Object.fromEntries( - Object.entries(standard).filter( - ([key, value]) => - key !== "config" && - (key in (record as unknown as Record) || - value !== (record as unknown as Record)[key]), - ), - ); - const client = createApiClient(); - if (source === "offering") - await client.updateAdminOffering(record.id, { ...changed, config }); - else await client.updateAdminTrustContent(record.id, { ...changed, config }); - }, - onSuccess: () => { - message.success("已保存内容草稿,发布后访客才会看到更新"); - onSaved?.(); - void queryClient.invalidateQueries({ - queryKey: [source === "offering" ? "admin-offerings" : "trust-content"], - }); - void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); - void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] }); - if (source === "offering") - void queryClient.invalidateQueries({ queryKey: ["admin-workspace-offering-fields"] }); - }, + const { form, handleValuesChange, initialValues, save, submit } = useRecordContentEditorState({ + source, + record, + section, + ...(onDraft ? { onDraft } : {}), + ...(onSaved ? { onSaved } : {}), }); + return (
{ - const currentValues = form.getFieldsValue(true) as PresentationValues; - const next = { - ...draftValues, - ...values, - ...currentValues, - }; - setDraftValues(next); - onDraft?.(next); - }} - onFinish={(values) => { - const currentValues = form.getFieldsValue(true) as PresentationValues; - save.mutate({ - ...draftValues, - ...values, - ...currentValues, - }); - }} + onValuesChange={handleValuesChange} + onFinish={submit} style={{ minHeight: 0, display: "flex", flexDirection: "column" }} > void; + onSaved?: () => void; + visualSelection?: { targetKey: string; page: string }; +} diff --git a/apps/admin/src/components/record-content/useRecordContentEditorState.ts b/apps/admin/src/components/record-content/useRecordContentEditorState.ts new file mode 100644 index 0000000..b90a141 --- /dev/null +++ b/apps/admin/src/components/record-content/useRecordContentEditorState.ts @@ -0,0 +1,117 @@ +import { Form, message } from "antd"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { useEffect, useMemo, useState } from "react"; +import type { TemplateAdminSection } from "@personal-brand/api-client"; +import type { Offering, TrustContent } from "@personal-brand/api-client"; +import { createApiClient } from "../../lib/api.js"; +import { + applyPresentationValues, + applyStandardEntityValues, + presentationFieldName, + readPresentationValue, + type PresentationValues, +} from "../../features/brand/presentation-bindings.js"; +import type { RecordContentSource } from "./types.js"; + +function createInitialValues( + record: Offering | TrustContent, + section: TemplateAdminSection, +): PresentationValues { + return Object.fromEntries( + section.fields.map((field) => [ + presentationFieldName(section.key, field.key), + readPresentationValue( + record.config, + field.binding, + field, + record as unknown as Record, + ), + ]), + ); +} + +function createChangedStandardValues( + record: Offering | TrustContent, + source: RecordContentSource, + section: TemplateAdminSection, + values: PresentationValues, +) { + const entity = record as unknown as Record; + const standard = applyStandardEntityValues(entity, source, [section], values); + + return Object.fromEntries( + Object.entries(standard).filter( + ([key, value]) => key !== "config" && (key in entity || value !== entity[key]), + ), + ); +} + +export function useRecordContentEditorState({ + source, + record, + section, + onDraft, + onSaved, +}: { + source: RecordContentSource; + record: Offering | TrustContent; + section: TemplateAdminSection; + onDraft?: ((values: PresentationValues) => void) | undefined; + onSaved?: (() => void) | undefined; +}) { + const [form] = Form.useForm(); + const queryClient = useQueryClient(); + const [draftValues, setDraftValues] = useState(() => + createInitialValues(record, section), + ); + const initialValues = useMemo(() => createInitialValues(record, section), [record, section]); + + useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]); + + const save = useMutation({ + mutationFn: async (values: PresentationValues): Promise => { + const config = applyPresentationValues(record.config, [section], values); + const changed = createChangedStandardValues(record, source, section, values); + const client = createApiClient(); + + if (source === "offering") { + await client.updateAdminOffering(record.id, { ...changed, config }); + } else { + await client.updateAdminTrustContent(record.id, { ...changed, config }); + } + }, + onSuccess: () => { + message.success("已保存内容草稿,发布后访客才会看到更新"); + onSaved?.(); + void queryClient.invalidateQueries({ + queryKey: [source === "offering" ? "admin-offerings" : "trust-content"], + }); + void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); + void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] }); + if (source === "offering") { + void queryClient.invalidateQueries({ queryKey: ["admin-workspace-offering-fields"] }); + } + }, + }); + + const submit = (values: PresentationValues) => { + const currentValues = form.getFieldsValue(true) as PresentationValues; + save.mutate({ ...draftValues, ...values, ...currentValues }); + }; + + const handleValuesChange = (_values: PresentationValues) => { + const currentValues = form.getFieldsValue(true) as PresentationValues; + const next = { ...draftValues, ..._values, ...currentValues }; + setDraftValues(next); + onDraft?.(next); + }; + + return { + draftValues, + form, + handleValuesChange, + initialValues, + save, + submit, + }; +} diff --git a/apps/admin/src/features/services/OfferingEditorModal.tsx b/apps/admin/src/features/services/OfferingEditorModal.tsx new file mode 100644 index 0000000..e0a5d17 --- /dev/null +++ b/apps/admin/src/features/services/OfferingEditorModal.tsx @@ -0,0 +1,181 @@ +import { Alert, Button, Form, Input, Modal, Segmented, Select, Typography } from "antd"; +import type { + Offering, + RuntimeWorkspace, + TemplateAdminField, + TemplateAdminSection, +} from "@personal-brand/api-client"; +import { ImageUrlField } from "../../components/ImageUrlField.js"; +import { RecordContentFields } from "../../components/RecordContentEditor.js"; +import { ComponentTemplatePreview } from "../brand/ComponentTemplatePreview.js"; +import type { PreviewTarget } from "../brand/preview-selection.js"; +import type { FormInstance } from "antd"; +import "./ServicesPage.css"; + +type OfferingEditorModalProps = { + open: boolean; + editingOffering: Offering | null; + form: FormInstance>; + previewPage: "offerings" | "detail"; + previewWorkspace: RuntimeWorkspace | undefined; + previewTargets: Record<"offerings" | "detail", PreviewTarget[]>; + activeTemplateFields: TemplateAdminField[]; + templateFieldSection: TemplateAdminSection; + hasTemplateDetailCopy: boolean; + listTarget: PreviewTarget; + detailTarget: PreviewTarget | undefined; + saving: boolean; + onClose: () => void; + onPreviewPageChange: (page: "offerings" | "detail") => void; + onValuesChange: (values: Record) => void; + onFinish: (values: Record) => void; + onEditInBrand: () => void; +}; + +export function OfferingEditorModal({ + open, + editingOffering, + form, + previewPage, + previewWorkspace, + previewTargets, + activeTemplateFields, + templateFieldSection, + hasTemplateDetailCopy, + listTarget, + detailTarget, + saving, + onClose, + onPreviewPageChange, + onValuesChange, + onFinish, + onEditInBrand, +}: OfferingEditorModalProps) { + return ( + form.submit()} + confirmLoading={saving} + > +
+ {editingOffering && previewWorkspace ? ( +
+ + + {}} + /> +
+ ) : null} + onValuesChange(allValues)} + onFinish={onFinish} + > +
+ 基础信息 + + + + + + + {!hasTemplateDetailCopy ? ( + + + + ) : null} + + + + + + + + + + + - - - - - - - - {!hasTemplateDetailCopy ? ( - - - - ) : null} - - - - - - - - - - - ({ value: item.type, label: item.label }))} - /> - - {selectedTypeMeta?.pages?.length ? ( - - 这类内容会显示在: - {selectedTypeMeta.pages.map(pageLabel).join("、")} - - ) : null} - - - - {!selectedTypeMeta?.hideStandardFields?.includes("summary") && ( - - - - )} - {!selectedTypeMeta?.hideStandardFields?.includes("content") && ( - - - - )} - {selectedTypeMeta?.configFields?.map((field) => - field.input === "list" ? ( - - ) : ( - - {field.input === "textarea" ? : } - - ), - )} - - - - - ({ value: item.type, label: item.label }))} + /> + + {selectedTypeMeta?.pages?.length ? ( + + 这类内容会显示在:{selectedTypeMeta.pages.map(pageLabel).join("、")} + + ) : null} + + + + {!selectedTypeMeta?.hideStandardFields?.includes("summary") && ( + + + + )} + {!selectedTypeMeta?.hideStandardFields?.includes("content") && ( + + + + )} + {selectedTypeMeta?.configFields?.map((field) => + field.input === "list" ? ( + + ) : ( + + {field.input === "textarea" ? : } + + ), + )} + + + + +