merge: 合并代码结构标准重构
This commit is contained in:
commit
f87b26b201
79 files changed
+8033
-6814
No files matched your search
@@ -1,31 +1,14 @@
|
|||||||
import { Alert, Button, Col, Form, Row, Space, Typography, message } from "antd";
|
import { Alert, Button, Col, Form, Row, Space, Typography } from "antd";
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import { useEffect, useMemo, useState } from "react";
|
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import type { Offering, TemplateAdminSection, TrustContent } from "@personal-brand/api-client";
|
import type { TemplateAdminSection } from "@personal-brand/api-client";
|
||||||
import { createApiClient } from "../lib/api.js";
|
|
||||||
import { TemplateListField } from "./TemplateListField.js";
|
import { TemplateListField } from "./TemplateListField.js";
|
||||||
import { TemplateFieldRenderer } from "./TemplateFieldRenderer.js";
|
import { TemplateFieldRenderer } from "./TemplateFieldRenderer.js";
|
||||||
import { MutationError } from "./QueryState.js";
|
import { MutationError } from "./QueryState.js";
|
||||||
import {
|
import { presentationFieldName } from "../features/brand/presentation-bindings.js";
|
||||||
applyPresentationValues,
|
import { useRecordContentEditorState } from "./record-content/useRecordContentEditorState.js";
|
||||||
applyStandardEntityValues,
|
import type { RecordContentEditorProps, RecordContentSource } from "./record-content/types.js";
|
||||||
presentationFieldName,
|
|
||||||
readPresentationValue,
|
|
||||||
type PresentationValues,
|
|
||||||
} from "../features/brand/presentation-bindings.js";
|
|
||||||
|
|
||||||
export type RecordContentSource = "offering" | "trust";
|
export type { RecordContentEditorProps, RecordContentSource };
|
||||||
|
|
||||||
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 function RecordContentFields({
|
export function RecordContentFields({
|
||||||
section,
|
section,
|
||||||
@@ -72,95 +55,22 @@ export function RecordContentEditor({
|
|||||||
visualSelection,
|
visualSelection,
|
||||||
}: RecordContentEditorProps) {
|
}: RecordContentEditorProps) {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [form] = Form.useForm<PresentationValues>();
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const recordName = "name" in record ? record.name : record.title;
|
const recordName = "name" in record ? record.name : record.title;
|
||||||
const [draftValues, setDraftValues] = useState<PresentationValues>(() =>
|
const { form, handleValuesChange, initialValues, save, submit } = useRecordContentEditorState({
|
||||||
Object.fromEntries(
|
|
||||||
section.fields.map((field) => [
|
|
||||||
presentationFieldName(section.key, field.key),
|
|
||||||
readPresentationValue(
|
|
||||||
record.config,
|
|
||||||
field.binding,
|
|
||||||
field,
|
|
||||||
record as unknown as Record<string, unknown>,
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
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<string, unknown>,
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
[record, section],
|
|
||||||
);
|
|
||||||
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
|
|
||||||
const save = useMutation({
|
|
||||||
mutationFn: async (values: PresentationValues): Promise<void> => {
|
|
||||||
const config = applyPresentationValues(record.config, [section], values);
|
|
||||||
const standard = applyStandardEntityValues(
|
|
||||||
record as unknown as Record<string, unknown>,
|
|
||||||
source,
|
source,
|
||||||
[section],
|
record,
|
||||||
values,
|
section,
|
||||||
);
|
...(onDraft ? { onDraft } : {}),
|
||||||
const changed = Object.fromEntries(
|
...(onSaved ? { onSaved } : {}),
|
||||||
Object.entries(standard).filter(
|
|
||||||
([key, value]) =>
|
|
||||||
key !== "config" &&
|
|
||||||
(key in (record as unknown as Record<string, unknown>) ||
|
|
||||||
value !== (record as unknown as Record<string, unknown>)[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"] });
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Form
|
<Form
|
||||||
form={form}
|
form={form}
|
||||||
layout="vertical"
|
layout="vertical"
|
||||||
initialValues={initialValues}
|
initialValues={initialValues}
|
||||||
onValuesChange={(_, values) => {
|
onValuesChange={handleValuesChange}
|
||||||
const currentValues = form.getFieldsValue(true) as PresentationValues;
|
onFinish={submit}
|
||||||
const next = {
|
|
||||||
...draftValues,
|
|
||||||
...values,
|
|
||||||
...currentValues,
|
|
||||||
};
|
|
||||||
setDraftValues(next);
|
|
||||||
onDraft?.(next);
|
|
||||||
}}
|
|
||||||
onFinish={(values) => {
|
|
||||||
const currentValues = form.getFieldsValue(true) as PresentationValues;
|
|
||||||
save.mutate({
|
|
||||||
...draftValues,
|
|
||||||
...values,
|
|
||||||
...currentValues,
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
style={{ minHeight: 0, display: "flex", flexDirection: "column" }}
|
style={{ minHeight: 0, display: "flex", flexDirection: "column" }}
|
||||||
>
|
>
|
||||||
<Alert
|
<Alert
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import type { Offering, TemplateAdminSection, TrustContent } from "@personal-brand/api-client";
|
||||||
|
import type { PresentationValues } from "../../features/brand/presentation-bindings.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 };
|
||||||
|
}
|
||||||
@@ -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<string, unknown>,
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createChangedStandardValues(
|
||||||
|
record: Offering | TrustContent,
|
||||||
|
source: RecordContentSource,
|
||||||
|
section: TemplateAdminSection,
|
||||||
|
values: PresentationValues,
|
||||||
|
) {
|
||||||
|
const entity = record as unknown as Record<string, unknown>;
|
||||||
|
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<PresentationValues>();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [draftValues, setDraftValues] = useState<PresentationValues>(() =>
|
||||||
|
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<void> => {
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -11,9 +11,8 @@ import {
|
|||||||
Space,
|
Space,
|
||||||
Tag,
|
Tag,
|
||||||
Typography,
|
Typography,
|
||||||
message,
|
|
||||||
} from "antd";
|
} from "antd";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import type {
|
import type {
|
||||||
@@ -24,7 +23,6 @@ import type {
|
|||||||
} from "@personal-brand/api-client";
|
} from "@personal-brand/api-client";
|
||||||
import type { BrandProfile } from "@personal-brand/api-client";
|
import type { BrandProfile } from "@personal-brand/api-client";
|
||||||
import { projectBrandAliases, projectTrustPresentation } 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 { TemplateListField } from "../../components/TemplateListField.js";
|
||||||
import { TemplateFieldRenderer } from "../../components/TemplateFieldRenderer.js";
|
import { TemplateFieldRenderer } from "../../components/TemplateFieldRenderer.js";
|
||||||
import { MutationError } from "../../components/QueryState.js";
|
import { MutationError } from "../../components/QueryState.js";
|
||||||
@@ -38,17 +36,20 @@ import {
|
|||||||
type PreviewTarget,
|
type PreviewTarget,
|
||||||
} from "./preview-selection.js";
|
} from "./preview-selection.js";
|
||||||
import {
|
import {
|
||||||
applyBrandPreviewValues,
|
|
||||||
applyStandardBrandValues,
|
|
||||||
applyStandardEntityValues,
|
|
||||||
applyPresentationValues,
|
|
||||||
filterSectionsForPreviewTarget,
|
filterSectionsForPreviewTarget,
|
||||||
presentationFieldName,
|
presentationFieldName,
|
||||||
readPresentationValue,
|
|
||||||
type PresentationValues,
|
type PresentationValues,
|
||||||
} from "./presentation-bindings.js";
|
} from "./presentation-bindings.js";
|
||||||
import "./PresentationEditor.css";
|
import "./PresentationEditor.css";
|
||||||
import { useEditorDraft } from "./use-editor-draft.js";
|
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 {
|
interface PresentationEditorProps {
|
||||||
templateContent: AdminTemplateContent | null | undefined;
|
templateContent: AdminTemplateContent | null | undefined;
|
||||||
@@ -136,7 +137,6 @@ export function PresentationEditor({
|
|||||||
error,
|
error,
|
||||||
initialSelection,
|
initialSelection,
|
||||||
}: PresentationEditorProps) {
|
}: PresentationEditorProps) {
|
||||||
const [form] = Form.useForm<PresentationValues>();
|
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const breakpoints = Grid.useBreakpoint();
|
const breakpoints = Grid.useBreakpoint();
|
||||||
@@ -149,45 +149,12 @@ export function PresentationEditor({
|
|||||||
id: string;
|
id: string;
|
||||||
values: PresentationValues;
|
values: PresentationValues;
|
||||||
}>();
|
}>();
|
||||||
const [previewConfig, setPreviewConfig] = useState(config ?? {});
|
|
||||||
const [previewBrandValues, setPreviewBrandValues] = useState<Record<string, unknown>>({});
|
|
||||||
const [inquiryDraft, setInquiryDraft] =
|
const [inquiryDraft, setInquiryDraft] =
|
||||||
useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>();
|
useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>();
|
||||||
const [brandDirty, setBrandDirty] = useState(false);
|
const [brandDirty, setBrandDirty] = useState(false);
|
||||||
const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft);
|
const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft);
|
||||||
const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand");
|
const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand");
|
||||||
const sections = useMemo(() => {
|
const sections = useBrandPresentationSections(templateContent);
|
||||||
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 pageOptions = useMemo(() => {
|
const pageOptions = useMemo(() => {
|
||||||
const pages = new Map<string, string>();
|
const pages = new Map<string, string>();
|
||||||
for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label);
|
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 === "offering" || selectedTarget?.source === "trust"
|
||||||
? selectedTarget.source
|
? selectedTarget.source
|
||||||
: undefined;
|
: undefined;
|
||||||
const offeringsQuery = useQuery({
|
const { offeringsQuery, trustQuery, selectedRecord } = usePresentationRecordQueries(
|
||||||
queryKey: ["admin-offerings"],
|
selectedRecordSource,
|
||||||
queryFn: () => createApiClient().listAdminOfferings(),
|
selection?.recordId,
|
||||||
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 editableSections = filterSectionsForPreviewTarget(
|
const editableSections = filterSectionsForPreviewTarget(
|
||||||
visibleSections.filter((section) =>
|
visibleSections.filter((section) =>
|
||||||
section.fields.some((field) => field.binding.startsWith("brand.")),
|
section.fields.some((field) => field.binding.startsWith("brand.")),
|
||||||
@@ -342,58 +296,9 @@ export function PresentationEditor({
|
|||||||
return item.target === selectedSection.target;
|
return item.target === selectedSection.target;
|
||||||
})
|
})
|
||||||
: pageLinks;
|
: pageLinks;
|
||||||
const initialValues = useMemo(() => {
|
const formState = useBrandPresentationForm({ brand, config, sections });
|
||||||
const values: PresentationValues = {};
|
const { form, initialValues } = formState;
|
||||||
for (const section of sections) {
|
const save = useBrandSaveMutation({ ...formState, brand, config, sections, queryClient });
|
||||||
for (const field of section.fields) {
|
|
||||||
values[presentationFieldName(section.key, field.key)] = readPresentationValue(
|
|
||||||
config,
|
|
||||||
field.binding,
|
|
||||||
field,
|
|
||||||
brand as unknown as Record<string, unknown>,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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<string, unknown>,
|
|
||||||
sections,
|
|
||||||
values,
|
|
||||||
);
|
|
||||||
const changed = Object.fromEntries(
|
|
||||||
Object.entries(standard).filter(
|
|
||||||
([key, value]) =>
|
|
||||||
key !== "config" && value !== (brand as unknown as Record<string, unknown>)[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]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const initialPage =
|
const initialPage =
|
||||||
@@ -453,62 +358,16 @@ export function PresentationEditor({
|
|||||||
() => setRecordDraft(undefined),
|
() => setRecordDraft(undefined),
|
||||||
[selection?.targetKey, selection?.recordId, selectedPage],
|
[selection?.targetKey, selection?.recordId, selectedPage],
|
||||||
);
|
);
|
||||||
useEffect(() => {
|
const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({
|
||||||
setPreviewConfig(config ?? {});
|
brand,
|
||||||
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<string, unknown>,
|
|
||||||
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<string, unknown>,
|
|
||||||
config,
|
config,
|
||||||
sections,
|
sections,
|
||||||
synchronized,
|
form,
|
||||||
);
|
onDirty: () => setBrandDirty(true),
|
||||||
setPreviewConfig((next.config as Record<string, unknown>) ?? {});
|
});
|
||||||
setPreviewBrandValues(next);
|
const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection });
|
||||||
},
|
useEffect(() => resetPreview(), [config, initialValues, resetPreview]);
|
||||||
[brand, config, sections, form],
|
const previewConfig = previewBrand.config;
|
||||||
);
|
|
||||||
const draftWorkspace = useMemo(() => {
|
const draftWorkspace = useMemo(() => {
|
||||||
if (!previewWorkspace) return undefined;
|
if (!previewWorkspace) return undefined;
|
||||||
const next: RuntimeWorkspace = {
|
const next: RuntimeWorkspace = {
|
||||||
@@ -652,8 +511,7 @@ export function PresentationEditor({
|
|||||||
guardDraft(() => {
|
guardDraft(() => {
|
||||||
setBrandDirty(false);
|
setBrandDirty(false);
|
||||||
form.setFieldsValue(initialValues);
|
form.setFieldsValue(initialValues);
|
||||||
setPreviewConfig(config ?? {});
|
resetPreview();
|
||||||
setPreviewBrandValues({});
|
|
||||||
setRecordDraft(undefined);
|
setRecordDraft(undefined);
|
||||||
setInquiryDraft(undefined);
|
setInquiryDraft(undefined);
|
||||||
setActivePage(value);
|
setActivePage(value);
|
||||||
@@ -669,8 +527,7 @@ export function PresentationEditor({
|
|||||||
guardDraft(() => {
|
guardDraft(() => {
|
||||||
setBrandDirty(false);
|
setBrandDirty(false);
|
||||||
form.setFieldsValue(initialValues);
|
form.setFieldsValue(initialValues);
|
||||||
setPreviewConfig(config ?? {});
|
resetPreview();
|
||||||
setPreviewBrandValues({});
|
|
||||||
setRecordDraft(undefined);
|
setRecordDraft(undefined);
|
||||||
setInquiryDraft(undefined);
|
setInquiryDraft(undefined);
|
||||||
setActivePage(String(value));
|
setActivePage(String(value));
|
||||||
|
|||||||
@@ -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<string, unknown>,
|
||||||
|
recordDraft.source,
|
||||||
|
[recordSection],
|
||||||
|
recordDraft.values,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}, [recordDraft, selectedRecord, recordSection]);
|
||||||
|
}
|
||||||
@@ -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<PresentationValues>;
|
||||||
|
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<string, unknown> | null | undefined;
|
||||||
|
sections: TemplateAdminSection[];
|
||||||
|
}): BrandPresentationFormState {
|
||||||
|
const [form] = Form.useForm<PresentationValues>();
|
||||||
|
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<string, unknown>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return values;
|
||||||
|
}, [brand, config, sections]);
|
||||||
|
|
||||||
|
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
|
||||||
|
return { form, initialValues };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BrandSaveMutationOptions extends BrandPresentationFormState {
|
||||||
|
brand: BrandProfile;
|
||||||
|
config: Record<string, unknown> | 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<string, unknown>,
|
||||||
|
sections,
|
||||||
|
values,
|
||||||
|
);
|
||||||
|
const changed = Object.fromEntries(
|
||||||
|
Object.entries(standard).filter(
|
||||||
|
([key, value]) =>
|
||||||
|
key !== "config" && value !== (brand as unknown as Record<string, unknown>)[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<string, unknown> | null | undefined;
|
||||||
|
sections: TemplateAdminSection[];
|
||||||
|
form: BrandPresentationFormState["form"];
|
||||||
|
onDirty: () => void;
|
||||||
|
}) {
|
||||||
|
const [previewConfig, setPreviewConfig] = useState(config ?? {});
|
||||||
|
const [previewBrandValues, setPreviewBrandValues] = useState<Record<string, unknown>>({});
|
||||||
|
|
||||||
|
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<string, unknown>,
|
||||||
|
config,
|
||||||
|
sections,
|
||||||
|
synchronized,
|
||||||
|
);
|
||||||
|
setPreviewConfig((next.config as Record<string, unknown>) ?? {});
|
||||||
|
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 };
|
||||||
|
}
|
||||||
@@ -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<Record<string, unknown>>;
|
||||||
|
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<string, unknown>) => void;
|
||||||
|
onFinish: (values: Record<string, unknown>) => 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 (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
title={editingOffering ? "编辑业务提供项" : "新增业务提供项"}
|
||||||
|
width={960}
|
||||||
|
onCancel={onClose}
|
||||||
|
onOk={() => form.submit()}
|
||||||
|
confirmLoading={saving}
|
||||||
|
>
|
||||||
|
<div className="service-offering-editor">
|
||||||
|
{editingOffering && previewWorkspace ? (
|
||||||
|
<div className="service-offering-editor__preview">
|
||||||
|
<Segmented
|
||||||
|
className="service-offering-editor__view"
|
||||||
|
value={previewPage}
|
||||||
|
options={[
|
||||||
|
{ value: "offerings", label: "列表卡片" },
|
||||||
|
{ value: "detail", label: "详情内容" },
|
||||||
|
]}
|
||||||
|
onChange={onPreviewPageChange}
|
||||||
|
/>
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
message={previewPage === "offerings" ? "正在核对列表展示" : "正在核对详情展示"}
|
||||||
|
description={
|
||||||
|
previewPage === "offerings"
|
||||||
|
? "右侧「列表展示」字段修改后,会实时反映在当前卡片。"
|
||||||
|
: "右侧「详情展示」字段修改后,会实时反映在当前详情内容。"
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<ComponentTemplatePreview
|
||||||
|
workspace={previewWorkspace}
|
||||||
|
page={previewPage}
|
||||||
|
offeringId={editingOffering.id}
|
||||||
|
targets={previewTargets[previewPage]}
|
||||||
|
selection={{
|
||||||
|
targetKey: previewPage === "offerings" ? listTarget.key : (detailTarget?.key ?? ""),
|
||||||
|
recordId: editingOffering.id,
|
||||||
|
}}
|
||||||
|
onTargetSelected={() => {}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<Form
|
||||||
|
className="service-offering-editor__form"
|
||||||
|
form={form}
|
||||||
|
layout="vertical"
|
||||||
|
onValuesChange={(_, allValues) => onValuesChange(allValues)}
|
||||||
|
onFinish={onFinish}
|
||||||
|
>
|
||||||
|
<div className="service-offering-editor__form-scroll">
|
||||||
|
<Typography.Title level={5}>基础信息</Typography.Title>
|
||||||
|
<Form.Item name="kind" label="类型" rules={[{ required: true }]}>
|
||||||
|
<Select
|
||||||
|
options={[
|
||||||
|
{ value: "service", label: "服务" },
|
||||||
|
{ value: "product", label: "定制产品" },
|
||||||
|
{ value: "package", label: "套餐" },
|
||||||
|
{ value: "subscription", label: "订阅" },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
|
||||||
|
<Input />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="summary" label="一句话说明">
|
||||||
|
<Input />
|
||||||
|
</Form.Item>
|
||||||
|
{!hasTemplateDetailCopy ? (
|
||||||
|
<Form.Item name="description" label="详细介绍">
|
||||||
|
<Input.TextArea rows={5} />
|
||||||
|
</Form.Item>
|
||||||
|
) : null}
|
||||||
|
<Form.Item name="priceText" label="价格展示">
|
||||||
|
<Input placeholder="例如:按现场评估报价 / ¥ 2,800 起" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="coverUrl"
|
||||||
|
label="封面图片地址"
|
||||||
|
help="点击上传,或粘贴服务/产品封面图片地址。"
|
||||||
|
>
|
||||||
|
<ImageUrlField placeholder="粘贴服务或产品封面图片地址" scope="offering" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="sortOrder"
|
||||||
|
label="展示顺序"
|
||||||
|
help="数字越小越靠前,不确定时填写 0。"
|
||||||
|
rules={[{ type: "number", min: 0, max: 9999 }]}
|
||||||
|
>
|
||||||
|
<Input type="number" min={0} max={9999} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="isEnabled" label="公开状态">
|
||||||
|
<Select
|
||||||
|
options={[
|
||||||
|
{ value: true, label: "已启用" },
|
||||||
|
{ value: false, label: "已停用" },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
{activeTemplateFields.length ? (
|
||||||
|
<div>
|
||||||
|
<Typography.Title level={5}>
|
||||||
|
{previewPage === "offerings" ? "列表展示字段" : "详情展示字段"}
|
||||||
|
</Typography.Title>
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
这里只编辑左侧预览对应的字段;它们与小程序页面编辑的是同一份业务数据。
|
||||||
|
</Typography.Paragraph>
|
||||||
|
<RecordContentFields
|
||||||
|
section={{
|
||||||
|
...templateFieldSection,
|
||||||
|
fields: activeTemplateFields,
|
||||||
|
}}
|
||||||
|
sectionKey="offering"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{editingOffering ? (
|
||||||
|
<Button htmlType="button" onClick={onEditInBrand}>
|
||||||
|
在小程序页面编辑
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</Form>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import { Button, Popconfirm, Space, Table, Tag, Typography } from "antd";
|
||||||
|
import type { Offering } from "@personal-brand/api-client";
|
||||||
|
import { MutationError } from "../../components/QueryState.js";
|
||||||
|
import type { useOfferingMutations } from "./use-offering-data.js";
|
||||||
|
|
||||||
|
type OfferingsTableProps = {
|
||||||
|
pageLabel: string;
|
||||||
|
detailSectionTitles: string[];
|
||||||
|
items: Offering[];
|
||||||
|
loading: boolean;
|
||||||
|
saveError: unknown;
|
||||||
|
toggleOffering: ReturnType<typeof useOfferingMutations>["toggleOffering"];
|
||||||
|
deleteOffering: ReturnType<typeof useOfferingMutations>["deleteOffering"];
|
||||||
|
onEdit: (item: Offering) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const offeringKindLabels: Record<string, string> = {
|
||||||
|
service: "服务",
|
||||||
|
product: "定制产品",
|
||||||
|
package: "套餐",
|
||||||
|
subscription: "订阅",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function OfferingsTable({
|
||||||
|
pageLabel,
|
||||||
|
detailSectionTitles,
|
||||||
|
items,
|
||||||
|
loading,
|
||||||
|
saveError,
|
||||||
|
toggleOffering,
|
||||||
|
deleteOffering,
|
||||||
|
onEdit,
|
||||||
|
}: OfferingsTableProps) {
|
||||||
|
const columns = [
|
||||||
|
{ title: "名称", dataIndex: "name" },
|
||||||
|
{
|
||||||
|
title: "业务类型",
|
||||||
|
dataIndex: "kind",
|
||||||
|
render: (value: unknown) => <Tag>{offeringKindLabels[String(value)] ?? String(value)}</Tag>,
|
||||||
|
},
|
||||||
|
{ title: "价格", dataIndex: "priceText" },
|
||||||
|
{
|
||||||
|
title: "状态",
|
||||||
|
dataIndex: "isEnabled",
|
||||||
|
render: (value: boolean) => (value ? "已启用" : "已停用"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "操作",
|
||||||
|
render: (_: unknown, item: Offering) => (
|
||||||
|
<Space>
|
||||||
|
<Button size="small" onClick={() => onEdit(item)}>
|
||||||
|
编辑详情
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
loading={toggleOffering.isPending && toggleOffering.variables?.id === item.id}
|
||||||
|
onClick={() => toggleOffering.mutate({ id: item.id, isEnabled: !item.isEnabled })}
|
||||||
|
>
|
||||||
|
{item.isEnabled ? "禁用" : "启用"}
|
||||||
|
</Button>
|
||||||
|
<Popconfirm
|
||||||
|
title="确认删除这项业务提供项?"
|
||||||
|
description="如果它已经关联咨询表单,系统会阻止删除。"
|
||||||
|
onConfirm={() => deleteOffering.mutate(item.id)}
|
||||||
|
okText="删除"
|
||||||
|
cancelText="取消"
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
danger
|
||||||
|
size="small"
|
||||||
|
loading={deleteOffering.isPending && deleteOffering.variables === item.id}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section aria-label="业务提供项列表">
|
||||||
|
<Space wrap style={{ marginBottom: 16 }}>
|
||||||
|
<Typography.Title level={5} style={{ margin: 0 }}>
|
||||||
|
{pageLabel}中的内容
|
||||||
|
</Typography.Title>
|
||||||
|
<Tag color="blue">已启用的项目会公开展示</Tag>
|
||||||
|
</Space>
|
||||||
|
{detailSectionTitles.length ? (
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
编辑单项详情时,附加字段将用于:
|
||||||
|
{detailSectionTitles.join("、")}
|
||||||
|
。列表中的名称、说明、价格和封面也会显示在业务展示页。
|
||||||
|
</Typography.Paragraph>
|
||||||
|
) : null}
|
||||||
|
<Table
|
||||||
|
scroll={{ x: 760 }}
|
||||||
|
rowKey="id"
|
||||||
|
loading={loading}
|
||||||
|
dataSource={items}
|
||||||
|
columns={columns}
|
||||||
|
/>
|
||||||
|
{items.length === 0 && (
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
还没有公开业务提供项。创建后,小程序服务页会优先读取这些内容。
|
||||||
|
</Typography.Paragraph>
|
||||||
|
)}
|
||||||
|
<MutationError error={saveError} />
|
||||||
|
<MutationError error={toggleOffering.error} />
|
||||||
|
<MutationError error={deleteOffering.error} />
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,128 +1,46 @@
|
|||||||
import {
|
import { Button } from "antd";
|
||||||
Alert,
|
import type { Offering, TemplateAdminField } from "@personal-brand/api-client";
|
||||||
Button,
|
import { useMemo } from "react";
|
||||||
Form,
|
|
||||||
Input,
|
|
||||||
Modal,
|
|
||||||
Popconfirm,
|
|
||||||
Segmented,
|
|
||||||
Select,
|
|
||||||
Space,
|
|
||||||
Table,
|
|
||||||
Tag,
|
|
||||||
Typography,
|
|
||||||
message,
|
|
||||||
} from "antd";
|
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import type {
|
|
||||||
Offering,
|
|
||||||
RuntimeWorkspace,
|
|
||||||
TemplateAdminField,
|
|
||||||
TemplateAdminSection,
|
|
||||||
} from "@personal-brand/api-client";
|
|
||||||
import { useMemo, useState } from "react";
|
|
||||||
import { createApiClient } from "../../lib/api.js";
|
|
||||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
|
||||||
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 {
|
|
||||||
applyPresentationValues,
|
|
||||||
presentationFieldName,
|
|
||||||
readPresentationValue,
|
|
||||||
} from "../brand/presentation-bindings.js";
|
|
||||||
import { MutationError, QueryState } from "../../components/QueryState.js";
|
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import "./ServicesPage.css";
|
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||||
|
import { QueryState } from "../../components/QueryState.js";
|
||||||
|
import { OfferingEditorModal } from "./OfferingEditorModal.js";
|
||||||
|
import { OfferingsTable } from "./OfferingsTable.js";
|
||||||
|
import { detailPageLabel, hasTemplateDetailCopy, offeringPageLabel } from "./offering-model.js";
|
||||||
|
import { buildOfferingPreviewWorkspace, previewTargetsByPage } from "./offering-preview.js";
|
||||||
|
import { useOfferingEditor } from "./use-offering-editor.js";
|
||||||
|
import { useOfferingMutations, useOfferingQueries } from "./use-offering-data.js";
|
||||||
|
|
||||||
|
type PreviewPage = "offerings" | "detail";
|
||||||
|
|
||||||
export function ServicesPage() {
|
export function ServicesPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const client = createApiClient();
|
const { offerings, workspace, previewWorkspace, templateFields, retry } = useOfferingQueries();
|
||||||
const queryClient = useQueryClient();
|
const editor = useOfferingEditor(templateFields);
|
||||||
const [offeringForm] = Form.useForm();
|
const mutations = useOfferingMutations({
|
||||||
const [offeringOpen, setOfferingOpen] = useState(false);
|
editingOffering: editor.editingOffering,
|
||||||
const [editingOffering, setEditingOffering] = useState<Offering | null>(null);
|
templateFields,
|
||||||
const [offeringDraftVersion, setOfferingDraftVersion] = useState(0);
|
onSuccess: () => {
|
||||||
const [previewPage, setPreviewPage] = useState<"offerings" | "detail">("detail");
|
editor.closeOffering();
|
||||||
const [formValues, setFormValues] = useState<Record<string, unknown>>({});
|
editor.offeringForm.resetFields();
|
||||||
const offerings = useQuery({
|
},
|
||||||
queryKey: ["admin-offerings"],
|
|
||||||
queryFn: () => client.listAdminOfferings(),
|
|
||||||
refetchOnMount: "always",
|
|
||||||
});
|
});
|
||||||
const workspace = useQuery({
|
|
||||||
queryKey: ["admin-workspace-offering-fields"],
|
const sections = workspace.data?.templateContent?.admin.sections ?? [];
|
||||||
queryFn: () => client.getAdminWorkspace(),
|
const previewTargets = useMemo(() => previewTargetsByPage(sections), [sections]);
|
||||||
});
|
const listTarget = previewTargets.offerings.find((target) =>
|
||||||
const previewWorkspace = useQuery({
|
templateFields.some((field) => field.previewTarget === target.key),
|
||||||
queryKey: ["admin-preview-workspace-services"],
|
) ?? {
|
||||||
queryFn: () => client.getAdminPreviewWorkspace(),
|
|
||||||
refetchOnMount: "always",
|
|
||||||
});
|
|
||||||
const templateFields: TemplateAdminField[] = (
|
|
||||||
workspace.data?.templateContent?.admin.sections ?? []
|
|
||||||
)
|
|
||||||
.filter((section) => section.target === "offering")
|
|
||||||
.flatMap((section) =>
|
|
||||||
section.fields.filter((field) => field.binding.startsWith("offering.config.")),
|
|
||||||
);
|
|
||||||
const templateFieldSection = useMemo<TemplateAdminSection>(
|
|
||||||
() => ({
|
|
||||||
key: "offering",
|
|
||||||
title: "模板内容",
|
|
||||||
description: "",
|
|
||||||
page: "detail",
|
|
||||||
target: "offering",
|
|
||||||
fields: templateFields,
|
|
||||||
}),
|
|
||||||
[templateFields],
|
|
||||||
);
|
|
||||||
const offeringPageLabel =
|
|
||||||
workspace.data?.templateContent?.navigation.find((item) => item.page === "offerings")?.label ??
|
|
||||||
"业务展示页";
|
|
||||||
const detailPageLabel =
|
|
||||||
workspace.data?.templateContent?.navigation.find((item) => item.page === "detail")?.label ??
|
|
||||||
"详情页";
|
|
||||||
const detailSections = (workspace.data?.templateContent?.admin.sections ?? []).filter(
|
|
||||||
(section) => section.target === "offering" && section.page === "detail",
|
|
||||||
);
|
|
||||||
const visualOfferingTarget = (workspace.data?.templateContent?.admin.sections ?? [])
|
|
||||||
.filter((section) => section.target === "offering" && section.page === "offerings")
|
|
||||||
.flatMap((section) => section.previewTargets ?? [])
|
|
||||||
.find((target) => templateFields.some((field) => field.previewTarget === target.key)) ?? {
|
|
||||||
key: "linjing-editorial.offerings.item",
|
key: "linjing-editorial.offerings.item",
|
||||||
label: "业务卡片",
|
label: "业务卡片",
|
||||||
|
page: "offerings",
|
||||||
|
source: "offering",
|
||||||
};
|
};
|
||||||
const hasTemplateDetailCopy = templateFields.some(
|
const detailTarget = previewTargets.detail.find((target) => target.source === "offering");
|
||||||
(field) => field.binding === "offering.config.details.background",
|
|
||||||
);
|
|
||||||
const previewTargets = useMemo<Record<string, PreviewTarget[]>>(
|
|
||||||
() =>
|
|
||||||
["offerings", "detail"].reduce<Record<string, PreviewTarget[]>>((result, page) => {
|
|
||||||
result[page] = (workspace.data?.templateContent?.admin.sections ?? [])
|
|
||||||
.filter((section) => section.page === page)
|
|
||||||
.flatMap((section) =>
|
|
||||||
(section.previewTargets ?? []).map((target) => ({
|
|
||||||
...target,
|
|
||||||
page: section.page,
|
|
||||||
source: section.fields.some(
|
|
||||||
(field) =>
|
|
||||||
field.binding.startsWith("offering.") && field.previewTarget === target.key,
|
|
||||||
)
|
|
||||||
? "offering"
|
|
||||||
: section.target,
|
|
||||||
})),
|
|
||||||
);
|
|
||||||
return result;
|
|
||||||
}, {}),
|
|
||||||
[workspace.data?.templateContent],
|
|
||||||
);
|
|
||||||
const listFields = useMemo(
|
const listFields = useMemo(
|
||||||
() => templateFields.filter((field) => field.previewTarget === visualOfferingTarget.key),
|
() => templateFields.filter((field) => field.previewTarget === listTarget.key),
|
||||||
[templateFields, visualOfferingTarget.key],
|
[templateFields, listTarget.key],
|
||||||
);
|
);
|
||||||
const detailTarget = previewTargets.detail?.find((target) => target.source === "offering");
|
|
||||||
const detailFields = useMemo(
|
const detailFields = useMemo(
|
||||||
() => templateFields.filter((field) => field.previewTarget === detailTarget?.key),
|
() => templateFields.filter((field) => field.previewTarget === detailTarget?.key),
|
||||||
[templateFields, detailTarget?.key],
|
[templateFields, detailTarget?.key],
|
||||||
@@ -134,426 +52,85 @@ export function ServicesPage() {
|
|||||||
),
|
),
|
||||||
[templateFields, listFields, detailFields],
|
[templateFields, listFields, detailFields],
|
||||||
);
|
);
|
||||||
const activeTemplateFields =
|
const activeTemplateFields: TemplateAdminField[] =
|
||||||
previewPage === "offerings"
|
editor.previewPage === "offerings"
|
||||||
? [...listFields, ...otherFields.filter((field) => field.page === "offerings")]
|
? [...listFields, ...otherFields.filter((field) => field.page === "offerings")]
|
||||||
: [...detailFields, ...otherFields.filter((field) => field.page === "detail")];
|
: [...detailFields, ...otherFields.filter((field) => field.page === "detail")];
|
||||||
const previewWorkspaceDraft = useMemo<RuntimeWorkspace | undefined>(() => {
|
const previewWorkspaceDraft = useMemo(() => {
|
||||||
if (!previewWorkspace.data || !editingOffering) return undefined;
|
if (!previewWorkspace.data || !editor.editingOffering) return undefined;
|
||||||
const values: Record<string, unknown> = Object.keys(formValues).length
|
return buildOfferingPreviewWorkspace({
|
||||||
? formValues
|
previewWorkspace: previewWorkspace.data,
|
||||||
: (offeringForm.getFieldsValue(true) as Record<string, unknown>);
|
editingOffering: editor.editingOffering,
|
||||||
const config = applyPresentationValues(
|
templateFields,
|
||||||
editingOffering.config,
|
formValues: editor.formValues,
|
||||||
[{ key: "offering", fields: templateFields }],
|
});
|
||||||
values,
|
|
||||||
);
|
|
||||||
const offeringValues = {
|
|
||||||
name: values.name,
|
|
||||||
summary: values.summary,
|
|
||||||
description: values.description,
|
|
||||||
priceText: values.priceText,
|
|
||||||
coverUrl: values.coverUrl,
|
|
||||||
};
|
|
||||||
return {
|
|
||||||
...previewWorkspace.data,
|
|
||||||
offerings: previewWorkspace.data.offerings.map((item) =>
|
|
||||||
item.id === editingOffering.id
|
|
||||||
? {
|
|
||||||
...item,
|
|
||||||
name:
|
|
||||||
typeof offeringValues.name === "string" && offeringValues.name.trim()
|
|
||||||
? offeringValues.name
|
|
||||||
: item.name,
|
|
||||||
summary:
|
|
||||||
typeof offeringValues.summary === "string" ? offeringValues.summary : item.summary,
|
|
||||||
priceText:
|
|
||||||
typeof offeringValues.priceText === "string"
|
|
||||||
? offeringValues.priceText
|
|
||||||
: item.priceText,
|
|
||||||
coverUrl:
|
|
||||||
typeof offeringValues.coverUrl === "string" && offeringValues.coverUrl.trim()
|
|
||||||
? offeringValues.coverUrl
|
|
||||||
: item.coverUrl,
|
|
||||||
config,
|
|
||||||
presentation: {
|
|
||||||
...item.presentation,
|
|
||||||
...config,
|
|
||||||
...(config.presentation && typeof config.presentation === "object"
|
|
||||||
? (config.presentation as Record<string, unknown>)
|
|
||||||
: {}),
|
|
||||||
...(typeof config.area === "string" ? { area: config.area } : {}),
|
|
||||||
...(typeof config.series === "string" ? { series: config.series } : {}),
|
|
||||||
...(typeof config.spaceType === "string" ? { spaceType: config.spaceType } : {}),
|
|
||||||
heroImage:
|
|
||||||
typeof config.detailHero === "string"
|
|
||||||
? config.detailHero
|
|
||||||
: typeof offeringValues.coverUrl === "string" && offeringValues.coverUrl.trim()
|
|
||||||
? offeringValues.coverUrl
|
|
||||||
: (item.coverUrl ?? null),
|
|
||||||
details: {
|
|
||||||
...item.presentation.details,
|
|
||||||
...(config.details && typeof config.details === "object"
|
|
||||||
? {
|
|
||||||
...item.presentation.details,
|
|
||||||
...(config.details as Record<string, unknown>),
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
: item,
|
|
||||||
),
|
|
||||||
brand: previewWorkspace.data.brand,
|
|
||||||
};
|
|
||||||
}, [
|
}, [
|
||||||
previewWorkspace.data,
|
previewWorkspace.data,
|
||||||
editingOffering,
|
editor.editingOffering,
|
||||||
templateFields,
|
templateFields,
|
||||||
formValues,
|
editor.formValues,
|
||||||
offeringDraftVersion,
|
editor.offeringDraftVersion,
|
||||||
offeringForm,
|
|
||||||
]);
|
]);
|
||||||
const saveOffering = useMutation({
|
|
||||||
mutationFn: (values: Record<string, unknown>) => {
|
const navigateToBrand = () => {
|
||||||
const fields = Object.fromEntries(
|
if (!editor.editingOffering) return;
|
||||||
Object.entries(values).filter(([key]) => key !== "config" && !key.startsWith("offering:")),
|
void navigate("/admin/brand", {
|
||||||
);
|
state: {
|
||||||
const config = applyPresentationValues(
|
targetKey:
|
||||||
editingOffering?.config,
|
editor.previewPage === "offerings"
|
||||||
[{ key: "offering", fields: templateFields }],
|
? listTarget.key
|
||||||
values,
|
: (detailTarget?.key ?? listTarget.key),
|
||||||
);
|
recordId: editor.editingOffering.id,
|
||||||
const body = { ...fields, config };
|
|
||||||
return editingOffering
|
|
||||||
? client.updateAdminOffering(editingOffering.id, body)
|
|
||||||
: client.createAdminOffering(body as Omit<Offering, "id" | "brandId">);
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
|
||||||
message.success("业务提供项已保存");
|
|
||||||
setOfferingOpen(false);
|
|
||||||
setEditingOffering(null);
|
|
||||||
offeringForm.resetFields();
|
|
||||||
offeringForm.setFieldsValue({});
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace-offering-fields"] });
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace-services"] });
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const deleteOffering = useMutation({
|
|
||||||
mutationFn: (id: string) => client.deleteAdminOffering(id),
|
|
||||||
onSuccess: () => {
|
|
||||||
message.success("业务提供项已删除");
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const toggleOffering = useMutation({
|
|
||||||
mutationFn: ({ id, isEnabled }: { id: string; isEnabled: boolean }) =>
|
|
||||||
client.updateAdminOffering(id, { isEnabled }),
|
|
||||||
onSuccess: () => {
|
|
||||||
message.success("业务提供项状态已更新");
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const beginOffering = (item?: Offering) => {
|
|
||||||
setEditingOffering(item ?? null);
|
|
||||||
setPreviewPage("detail");
|
|
||||||
setOfferingOpen(true);
|
|
||||||
offeringForm.setFieldsValue(
|
|
||||||
item
|
|
||||||
? {
|
|
||||||
kind: item.kind,
|
|
||||||
name: item.name,
|
|
||||||
summary: item.summary ?? "",
|
|
||||||
description: item.description ?? "",
|
|
||||||
priceText: item.priceText ?? "",
|
|
||||||
coverUrl: item.coverUrl ?? "",
|
|
||||||
sortOrder: item.sortOrder,
|
|
||||||
isEnabled: item.isEnabled,
|
|
||||||
...Object.fromEntries(
|
|
||||||
templateFields.map((field) => {
|
|
||||||
const value = readPresentationValue(item.config, field.binding, field);
|
|
||||||
return [
|
|
||||||
presentationFieldName("offering", field.key),
|
|
||||||
value === undefined || value === null || value === ""
|
|
||||||
? field.input === "select"
|
|
||||||
? field.options?.[0]?.value
|
|
||||||
: field.input === "list"
|
|
||||||
? []
|
|
||||||
: undefined
|
|
||||||
: value,
|
|
||||||
];
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
: {
|
|
||||||
kind: "service",
|
|
||||||
isEnabled: true,
|
|
||||||
sortOrder: 0,
|
|
||||||
...Object.fromEntries(
|
|
||||||
templateFields.map((field) => [
|
|
||||||
presentationFieldName("offering", field.key),
|
|
||||||
field.input === "list" ? [] : undefined,
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
setFormValues(offeringForm.getFieldsValue(true) as Record<string, unknown>);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<QueryState
|
<QueryState
|
||||||
loading={offerings.isLoading || workspace.isLoading}
|
loading={offerings.isLoading || workspace.isLoading}
|
||||||
error={offerings.error || workspace.error}
|
error={offerings.error || workspace.error}
|
||||||
onRetry={() => {
|
onRetry={retry}
|
||||||
void offerings.refetch();
|
|
||||||
void workspace.refetch();
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<AdminPageHeader
|
<AdminPageHeader
|
||||||
title="小程序内容:业务展示与详情"
|
title="小程序内容:业务展示与详情"
|
||||||
description={`在「${offeringPageLabel}」管理访客能选择的服务、产品或案例;每项内容的补充资料会显示在对应的「${detailPageLabel}」。`}
|
description={`在「${offeringPageLabel(workspace.data?.templateContent ?? undefined)}」管理访客能选择的服务、产品或案例;每项内容的补充资料会显示在对应的「${detailPageLabel(workspace.data?.templateContent ?? undefined)}」。`}
|
||||||
extra={
|
extra={
|
||||||
<Button type="primary" onClick={() => beginOffering()}>
|
<Button type="primary" onClick={() => editor.beginOffering()}>
|
||||||
新增业务提供项
|
新增业务提供项
|
||||||
</Button>
|
</Button>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<section aria-label="业务提供项列表">
|
<OfferingsTable
|
||||||
<Space wrap style={{ marginBottom: 16 }}>
|
pageLabel={offeringPageLabel(workspace.data?.templateContent ?? undefined)}
|
||||||
<Typography.Title level={5} style={{ margin: 0 }}>
|
detailSectionTitles={sections
|
||||||
{offeringPageLabel}中的内容
|
.filter((section) => section.target === "offering" && section.page === "detail")
|
||||||
</Typography.Title>
|
.map((section) => section.title)}
|
||||||
<Tag color="blue">已启用的项目会公开展示</Tag>
|
items={offerings.data ?? []}
|
||||||
</Space>
|
|
||||||
{detailSections.length ? (
|
|
||||||
<Typography.Paragraph type="secondary">
|
|
||||||
编辑单项详情时,附加字段将用于:
|
|
||||||
{detailSections.map((section) => section.title).join("、")}
|
|
||||||
。列表中的名称、说明、价格和封面也会显示在业务展示页。
|
|
||||||
</Typography.Paragraph>
|
|
||||||
) : null}
|
|
||||||
<Table
|
|
||||||
scroll={{ x: 760 }}
|
|
||||||
rowKey="id"
|
|
||||||
loading={offerings.isLoading}
|
loading={offerings.isLoading}
|
||||||
dataSource={offerings.data ?? []}
|
saveError={mutations.saveOffering.error}
|
||||||
columns={[
|
toggleOffering={mutations.toggleOffering}
|
||||||
{ title: "名称", dataIndex: "name" },
|
deleteOffering={mutations.deleteOffering}
|
||||||
{
|
onEdit={(item: Offering) => editor.beginOffering(item)}
|
||||||
title: "业务类型",
|
|
||||||
dataIndex: "kind",
|
|
||||||
render: (value) => (
|
|
||||||
<Tag>
|
|
||||||
{(
|
|
||||||
{
|
|
||||||
service: "服务",
|
|
||||||
product: "定制产品",
|
|
||||||
package: "套餐",
|
|
||||||
subscription: "订阅",
|
|
||||||
} as Record<string, string>
|
|
||||||
)[String(value)] ?? String(value)}
|
|
||||||
</Tag>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{ title: "价格", dataIndex: "priceText" },
|
|
||||||
{
|
|
||||||
title: "状态",
|
|
||||||
dataIndex: "isEnabled",
|
|
||||||
render: (value) => (value ? "已启用" : "已停用"),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: "操作",
|
|
||||||
render: (_: unknown, item: Offering) => (
|
|
||||||
<Space>
|
|
||||||
<Button size="small" onClick={() => beginOffering(item)}>
|
|
||||||
编辑详情
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
size="small"
|
|
||||||
loading={toggleOffering.isPending && toggleOffering.variables?.id === item.id}
|
|
||||||
onClick={() =>
|
|
||||||
toggleOffering.mutate({ id: item.id, isEnabled: !item.isEnabled })
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{item.isEnabled ? "禁用" : "启用"}
|
|
||||||
</Button>
|
|
||||||
<Popconfirm
|
|
||||||
title="确认删除这项业务提供项?"
|
|
||||||
description="如果它已经关联咨询表单,系统会阻止删除。"
|
|
||||||
onConfirm={() => deleteOffering.mutate(item.id)}
|
|
||||||
okText="删除"
|
|
||||||
cancelText="取消"
|
|
||||||
>
|
|
||||||
<Button
|
|
||||||
danger
|
|
||||||
size="small"
|
|
||||||
loading={deleteOffering.isPending && deleteOffering.variables === item.id}
|
|
||||||
>
|
|
||||||
删除
|
|
||||||
</Button>
|
|
||||||
</Popconfirm>
|
|
||||||
</Space>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
]}
|
|
||||||
/>
|
/>
|
||||||
{offerings.data?.length === 0 && (
|
<OfferingEditorModal
|
||||||
<Typography.Paragraph type="secondary">
|
open={editor.offeringOpen}
|
||||||
还没有公开业务提供项。创建后,小程序服务页会优先读取这些内容。
|
editingOffering={editor.editingOffering}
|
||||||
</Typography.Paragraph>
|
form={editor.offeringForm}
|
||||||
)}
|
previewPage={editor.previewPage}
|
||||||
<MutationError error={saveOffering.error} />
|
previewWorkspace={previewWorkspaceDraft}
|
||||||
<MutationError error={toggleOffering.error} />
|
previewTargets={previewTargets}
|
||||||
<MutationError error={deleteOffering.error} />
|
activeTemplateFields={activeTemplateFields}
|
||||||
</section>
|
templateFieldSection={editor.templateFieldSection}
|
||||||
<Modal
|
hasTemplateDetailCopy={hasTemplateDetailCopy(templateFields)}
|
||||||
open={offeringOpen}
|
listTarget={listTarget}
|
||||||
title={editingOffering ? "编辑业务提供项" : "新增业务提供项"}
|
detailTarget={detailTarget}
|
||||||
width={960}
|
saving={mutations.saveOffering.isPending}
|
||||||
onCancel={() => {
|
onClose={editor.closeOffering}
|
||||||
setOfferingOpen(false);
|
onPreviewPageChange={(page: PreviewPage) => editor.setPreviewPage(page)}
|
||||||
setEditingOffering(null);
|
onValuesChange={(values) => editor.handleValuesChange(null, values)}
|
||||||
offeringForm.resetFields();
|
onFinish={(values) => mutations.saveOffering.mutate(values)}
|
||||||
}}
|
onEditInBrand={navigateToBrand}
|
||||||
onOk={() => offeringForm.submit()}
|
|
||||||
confirmLoading={saveOffering.isPending}
|
|
||||||
>
|
|
||||||
<div className="service-offering-editor">
|
|
||||||
{editingOffering && previewWorkspaceDraft ? (
|
|
||||||
<div className="service-offering-editor__preview">
|
|
||||||
<Segmented
|
|
||||||
className="service-offering-editor__view"
|
|
||||||
value={previewPage}
|
|
||||||
options={[
|
|
||||||
{ value: "offerings", label: "列表卡片" },
|
|
||||||
{ value: "detail", label: "详情内容" },
|
|
||||||
]}
|
|
||||||
onChange={(value) => setPreviewPage(value as "offerings" | "detail")}
|
|
||||||
/>
|
/>
|
||||||
<Alert
|
|
||||||
type="info"
|
|
||||||
showIcon
|
|
||||||
message={previewPage === "offerings" ? "正在核对列表展示" : "正在核对详情展示"}
|
|
||||||
description={
|
|
||||||
previewPage === "offerings"
|
|
||||||
? "右侧「列表展示」字段修改后,会实时反映在当前卡片。"
|
|
||||||
: "右侧「详情展示」字段修改后,会实时反映在当前详情内容。"
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<ComponentTemplatePreview
|
|
||||||
workspace={previewWorkspaceDraft}
|
|
||||||
page={previewPage}
|
|
||||||
offeringId={editingOffering.id}
|
|
||||||
targets={previewTargets[previewPage] ?? []}
|
|
||||||
selection={{
|
|
||||||
targetKey:
|
|
||||||
previewPage === "offerings"
|
|
||||||
? visualOfferingTarget.key
|
|
||||||
: (detailTarget?.key ?? ""),
|
|
||||||
recordId: editingOffering.id,
|
|
||||||
}}
|
|
||||||
onTargetSelected={() => {}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
<Form
|
|
||||||
className="service-offering-editor__form"
|
|
||||||
form={offeringForm}
|
|
||||||
layout="vertical"
|
|
||||||
onValuesChange={(_, allValues) => {
|
|
||||||
setFormValues(allValues as Record<string, unknown>);
|
|
||||||
setOfferingDraftVersion((version) => version + 1);
|
|
||||||
}}
|
|
||||||
onFinish={(values) => saveOffering.mutate(values as Record<string, unknown>)}
|
|
||||||
>
|
|
||||||
<div className="service-offering-editor__form-scroll">
|
|
||||||
<Typography.Title level={5}>基础信息</Typography.Title>
|
|
||||||
<Form.Item name="kind" label="类型" rules={[{ required: true }]}>
|
|
||||||
<Select
|
|
||||||
options={[
|
|
||||||
{ value: "service", label: "服务" },
|
|
||||||
{ value: "product", label: "定制产品" },
|
|
||||||
{ value: "package", label: "套餐" },
|
|
||||||
{ value: "subscription", label: "订阅" },
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
|
|
||||||
<Input />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="summary" label="一句话说明">
|
|
||||||
<Input />
|
|
||||||
</Form.Item>
|
|
||||||
{!hasTemplateDetailCopy ? (
|
|
||||||
<Form.Item name="description" label="详细介绍">
|
|
||||||
<Input.TextArea rows={5} />
|
|
||||||
</Form.Item>
|
|
||||||
) : null}
|
|
||||||
<Form.Item name="priceText" label="价格展示">
|
|
||||||
<Input placeholder="例如:按现场评估报价 / ¥ 2,800 起" />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item
|
|
||||||
name="coverUrl"
|
|
||||||
label="封面图片地址"
|
|
||||||
help="点击上传,或粘贴服务/产品封面图片地址。"
|
|
||||||
>
|
|
||||||
<ImageUrlField placeholder="粘贴服务或产品封面图片地址" scope="offering" />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item
|
|
||||||
name="sortOrder"
|
|
||||||
label="展示顺序"
|
|
||||||
help="数字越小越靠前,不确定时填写 0。"
|
|
||||||
rules={[{ type: "number", min: 0, max: 9999 }]}
|
|
||||||
>
|
|
||||||
<Input type="number" min={0} max={9999} />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="isEnabled" label="公开状态">
|
|
||||||
<Select
|
|
||||||
options={[
|
|
||||||
{ value: true, label: "已启用" },
|
|
||||||
{ value: false, label: "已停用" },
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
{activeTemplateFields.length ? (
|
|
||||||
<div>
|
|
||||||
<Typography.Title level={5}>
|
|
||||||
{previewPage === "offerings" ? "列表展示字段" : "详情展示字段"}
|
|
||||||
</Typography.Title>
|
|
||||||
<Typography.Paragraph type="secondary">
|
|
||||||
这里只编辑左侧预览对应的字段;它们与小程序页面编辑的是同一份业务数据。
|
|
||||||
</Typography.Paragraph>
|
|
||||||
<RecordContentFields
|
|
||||||
section={{
|
|
||||||
...templateFieldSection,
|
|
||||||
fields: activeTemplateFields,
|
|
||||||
}}
|
|
||||||
sectionKey="offering"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
{editingOffering ? (
|
|
||||||
<Button
|
|
||||||
htmlType="button"
|
|
||||||
onClick={() =>
|
|
||||||
navigate("/admin/brand", {
|
|
||||||
state: {
|
|
||||||
targetKey:
|
|
||||||
previewPage === "offerings"
|
|
||||||
? visualOfferingTarget.key
|
|
||||||
: (detailTarget?.key ?? visualOfferingTarget.key),
|
|
||||||
recordId: editingOffering.id,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
>
|
|
||||||
在小程序页面编辑
|
|
||||||
</Button>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
</Form>
|
|
||||||
</div>
|
|
||||||
</Modal>
|
|
||||||
</QueryState>
|
</QueryState>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import type {
|
||||||
|
AdminTemplateContent,
|
||||||
|
Offering,
|
||||||
|
TemplateAdminField,
|
||||||
|
} from "@personal-brand/api-client";
|
||||||
|
import {
|
||||||
|
applyPresentationValues,
|
||||||
|
presentationFieldName,
|
||||||
|
readPresentationValue,
|
||||||
|
} from "../brand/presentation-bindings.js";
|
||||||
|
|
||||||
|
export type OfferingFormValues = Record<string, unknown>;
|
||||||
|
|
||||||
|
export function offeringTemplateFields(
|
||||||
|
sections: AdminTemplateContent["admin"]["sections"],
|
||||||
|
): TemplateAdminField[] {
|
||||||
|
return sections
|
||||||
|
.filter((section) => section.target === "offering")
|
||||||
|
.flatMap((section) =>
|
||||||
|
section.fields.filter((field) => field.binding.startsWith("offering.config.")),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function offeringDefaultFormValues(
|
||||||
|
templateFields: TemplateAdminField[],
|
||||||
|
): OfferingFormValues {
|
||||||
|
return {
|
||||||
|
kind: "service",
|
||||||
|
isEnabled: true,
|
||||||
|
sortOrder: 0,
|
||||||
|
...Object.fromEntries(
|
||||||
|
templateFields.map((field) => [
|
||||||
|
presentationFieldName("offering", field.key),
|
||||||
|
field.input === "list" ? [] : undefined,
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function offeringEditFormValues(
|
||||||
|
item: Offering,
|
||||||
|
templateFields: TemplateAdminField[],
|
||||||
|
): OfferingFormValues {
|
||||||
|
return {
|
||||||
|
kind: item.kind,
|
||||||
|
name: item.name,
|
||||||
|
summary: item.summary ?? "",
|
||||||
|
description: item.description ?? "",
|
||||||
|
priceText: item.priceText ?? "",
|
||||||
|
coverUrl: item.coverUrl ?? "",
|
||||||
|
sortOrder: item.sortOrder,
|
||||||
|
isEnabled: item.isEnabled,
|
||||||
|
...Object.fromEntries(
|
||||||
|
templateFields.map((field) => {
|
||||||
|
const value = readPresentationValue(item.config, field.binding, field);
|
||||||
|
return [
|
||||||
|
presentationFieldName("offering", field.key),
|
||||||
|
value === undefined || value === null || value === ""
|
||||||
|
? field.input === "select"
|
||||||
|
? field.options?.[0]?.value
|
||||||
|
: field.input === "list"
|
||||||
|
? []
|
||||||
|
: undefined
|
||||||
|
: value,
|
||||||
|
];
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildOfferingRequestBody(
|
||||||
|
values: OfferingFormValues,
|
||||||
|
editingOffering: Offering | null,
|
||||||
|
templateFields: TemplateAdminField[],
|
||||||
|
): Record<string, unknown> {
|
||||||
|
const fields = Object.fromEntries(
|
||||||
|
Object.entries(values).filter(([key]) => key !== "config" && !key.startsWith("offering:")),
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
...fields,
|
||||||
|
config: applyPresentationValues(
|
||||||
|
editingOffering?.config,
|
||||||
|
[{ key: "offering", fields: templateFields }],
|
||||||
|
values,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import type { AdminTemplateContent, TemplateAdminField } from "@personal-brand/api-client";
|
||||||
|
|
||||||
|
export function offeringPageLabel(templateContent?: AdminTemplateContent): string {
|
||||||
|
return (
|
||||||
|
templateContent?.navigation.find((item) => item.page === "offerings")?.label ?? "业务展示页"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function detailPageLabel(templateContent?: AdminTemplateContent): string {
|
||||||
|
return templateContent?.navigation.find((item) => item.page === "detail")?.label ?? "详情页";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasTemplateDetailCopy(templateFields: TemplateAdminField[]): boolean {
|
||||||
|
return templateFields.some((field) => field.binding === "offering.config.details.background");
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import type {
|
||||||
|
AdminTemplateContent,
|
||||||
|
Offering,
|
||||||
|
RuntimeWorkspace,
|
||||||
|
TemplateAdminField,
|
||||||
|
} from "@personal-brand/api-client";
|
||||||
|
import type { PreviewTarget } from "../brand/preview-selection.js";
|
||||||
|
import { applyPresentationValues } from "../brand/presentation-bindings.js";
|
||||||
|
|
||||||
|
export function previewTargetsByPage(
|
||||||
|
sections: AdminTemplateContent["admin"]["sections"],
|
||||||
|
): Record<"offerings" | "detail", PreviewTarget[]> {
|
||||||
|
const result: Record<"offerings" | "detail", PreviewTarget[]> = {
|
||||||
|
offerings: [],
|
||||||
|
detail: [],
|
||||||
|
};
|
||||||
|
for (const page of ["offerings", "detail"] as const) {
|
||||||
|
result[page] = sections
|
||||||
|
.filter((section) => section.page === page)
|
||||||
|
.flatMap((section) =>
|
||||||
|
(section.previewTargets ?? []).map((target) => ({
|
||||||
|
...target,
|
||||||
|
page: section.page,
|
||||||
|
source: section.fields.some(
|
||||||
|
(field) => field.binding.startsWith("offering.") && field.previewTarget === target.key,
|
||||||
|
)
|
||||||
|
? "offering"
|
||||||
|
: section.target,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildOfferingPreviewWorkspace(options: {
|
||||||
|
previewWorkspace: RuntimeWorkspace;
|
||||||
|
editingOffering: Offering;
|
||||||
|
templateFields: TemplateAdminField[];
|
||||||
|
formValues: Record<string, unknown>;
|
||||||
|
}): RuntimeWorkspace {
|
||||||
|
const { previewWorkspace, editingOffering, templateFields, formValues } = options;
|
||||||
|
const config = applyPresentationValues(
|
||||||
|
editingOffering.config,
|
||||||
|
[{ key: "offering", fields: templateFields }],
|
||||||
|
formValues,
|
||||||
|
);
|
||||||
|
const offeringValues = {
|
||||||
|
name: formValues.name,
|
||||||
|
summary: formValues.summary,
|
||||||
|
description: formValues.description,
|
||||||
|
priceText: formValues.priceText,
|
||||||
|
coverUrl: formValues.coverUrl,
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
...previewWorkspace,
|
||||||
|
offerings: previewWorkspace.offerings.map((item) =>
|
||||||
|
item.id === editingOffering.id
|
||||||
|
? {
|
||||||
|
...item,
|
||||||
|
name:
|
||||||
|
typeof offeringValues.name === "string" && offeringValues.name.trim()
|
||||||
|
? offeringValues.name
|
||||||
|
: item.name,
|
||||||
|
summary:
|
||||||
|
typeof offeringValues.summary === "string" ? offeringValues.summary : item.summary,
|
||||||
|
priceText:
|
||||||
|
typeof offeringValues.priceText === "string"
|
||||||
|
? offeringValues.priceText
|
||||||
|
: item.priceText,
|
||||||
|
coverUrl:
|
||||||
|
typeof offeringValues.coverUrl === "string" && offeringValues.coverUrl.trim()
|
||||||
|
? offeringValues.coverUrl
|
||||||
|
: item.coverUrl,
|
||||||
|
config,
|
||||||
|
presentation: {
|
||||||
|
...item.presentation,
|
||||||
|
...config,
|
||||||
|
...(config.presentation && typeof config.presentation === "object"
|
||||||
|
? (config.presentation as Record<string, unknown>)
|
||||||
|
: {}),
|
||||||
|
...(typeof config.area === "string" ? { area: config.area } : {}),
|
||||||
|
...(typeof config.series === "string" ? { series: config.series } : {}),
|
||||||
|
...(typeof config.spaceType === "string" ? { spaceType: config.spaceType } : {}),
|
||||||
|
heroImage:
|
||||||
|
typeof config.detailHero === "string"
|
||||||
|
? config.detailHero
|
||||||
|
: typeof offeringValues.coverUrl === "string" && offeringValues.coverUrl.trim()
|
||||||
|
? offeringValues.coverUrl
|
||||||
|
: (item.coverUrl ?? null),
|
||||||
|
details: {
|
||||||
|
...item.presentation.details,
|
||||||
|
...(config.details && typeof config.details === "object"
|
||||||
|
? {
|
||||||
|
...item.presentation.details,
|
||||||
|
...(config.details as Record<string, unknown>),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: item,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import type { Offering } from "@personal-brand/api-client";
|
||||||
|
import { message } from "antd";
|
||||||
|
import { useMemo } from "react";
|
||||||
|
import { createApiClient } from "../../lib/api.js";
|
||||||
|
import {
|
||||||
|
buildOfferingRequestBody,
|
||||||
|
offeringTemplateFields,
|
||||||
|
type OfferingFormValues,
|
||||||
|
} from "./offering-form.js";
|
||||||
|
|
||||||
|
export function useOfferingQueries() {
|
||||||
|
const client = createApiClient();
|
||||||
|
const offerings = useQuery({
|
||||||
|
queryKey: ["admin-offerings"],
|
||||||
|
queryFn: () => client.listAdminOfferings(),
|
||||||
|
refetchOnMount: "always",
|
||||||
|
});
|
||||||
|
const workspace = useQuery({
|
||||||
|
queryKey: ["admin-workspace-offering-fields"],
|
||||||
|
queryFn: () => client.getAdminWorkspace(),
|
||||||
|
});
|
||||||
|
const previewWorkspace = useQuery({
|
||||||
|
queryKey: ["admin-preview-workspace-services"],
|
||||||
|
queryFn: () => client.getAdminPreviewWorkspace(),
|
||||||
|
refetchOnMount: "always",
|
||||||
|
});
|
||||||
|
const templateFields = useMemo(
|
||||||
|
() => offeringTemplateFields(workspace.data?.templateContent?.admin.sections ?? []),
|
||||||
|
[workspace.data?.templateContent?.admin.sections],
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
offerings,
|
||||||
|
workspace,
|
||||||
|
previewWorkspace,
|
||||||
|
templateFields,
|
||||||
|
retry: () => {
|
||||||
|
void offerings.refetch();
|
||||||
|
void workspace.refetch();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useOfferingMutations(options: {
|
||||||
|
editingOffering: Offering | null;
|
||||||
|
templateFields: ReturnType<typeof offeringTemplateFields>;
|
||||||
|
onSuccess: () => void;
|
||||||
|
}) {
|
||||||
|
const client = createApiClient();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const invalidateAfterSave = () => {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["admin-workspace-offering-fields"] });
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace-services"] });
|
||||||
|
};
|
||||||
|
const saveOffering = useMutation({
|
||||||
|
mutationFn: (values: OfferingFormValues) =>
|
||||||
|
options.editingOffering
|
||||||
|
? client.updateAdminOffering(
|
||||||
|
options.editingOffering.id,
|
||||||
|
buildOfferingRequestBody(values, options.editingOffering, options.templateFields),
|
||||||
|
)
|
||||||
|
: client.createAdminOffering(
|
||||||
|
buildOfferingRequestBody(values, null, options.templateFields) as Omit<
|
||||||
|
Offering,
|
||||||
|
"id" | "brandId"
|
||||||
|
>,
|
||||||
|
),
|
||||||
|
onSuccess: () => {
|
||||||
|
message.success("业务提供项已保存");
|
||||||
|
invalidateAfterSave();
|
||||||
|
options.onSuccess();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const deleteOffering = useMutation({
|
||||||
|
mutationFn: (id: string) => client.deleteAdminOffering(id),
|
||||||
|
onSuccess: () => {
|
||||||
|
message.success("业务提供项已删除");
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const toggleOffering = useMutation({
|
||||||
|
mutationFn: ({ id, isEnabled }: { id: string; isEnabled: boolean }) =>
|
||||||
|
client.updateAdminOffering(id, { isEnabled }),
|
||||||
|
onSuccess: () => {
|
||||||
|
message.success("业务提供项状态已更新");
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return { saveOffering, deleteOffering, toggleOffering };
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import { Form } from "antd";
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import type {
|
||||||
|
Offering,
|
||||||
|
TemplateAdminField,
|
||||||
|
TemplateAdminSection,
|
||||||
|
} from "@personal-brand/api-client";
|
||||||
|
import { offeringDefaultFormValues, offeringEditFormValues } from "./offering-form.js";
|
||||||
|
|
||||||
|
export type OfferingPreviewPage = "offerings" | "detail";
|
||||||
|
|
||||||
|
export function useOfferingEditor(templateFields: TemplateAdminField[]) {
|
||||||
|
const [offeringForm] = Form.useForm();
|
||||||
|
const [offeringOpen, setOfferingOpen] = useState(false);
|
||||||
|
const [editingOffering, setEditingOffering] = useState<Offering | null>(null);
|
||||||
|
const [offeringDraftVersion, setOfferingDraftVersion] = useState(0);
|
||||||
|
const [previewPage, setPreviewPage] = useState<OfferingPreviewPage>("detail");
|
||||||
|
const [formValues, setFormValues] = useState<Record<string, unknown>>({});
|
||||||
|
|
||||||
|
const templateFieldSection = useMemo<TemplateAdminSection>(
|
||||||
|
() => ({
|
||||||
|
key: "offering",
|
||||||
|
title: "模板内容",
|
||||||
|
description: "",
|
||||||
|
page: "detail",
|
||||||
|
target: "offering",
|
||||||
|
fields: templateFields,
|
||||||
|
}),
|
||||||
|
[templateFields],
|
||||||
|
);
|
||||||
|
|
||||||
|
const beginOffering = (item?: Offering) => {
|
||||||
|
setEditingOffering(item ?? null);
|
||||||
|
setPreviewPage("detail");
|
||||||
|
setOfferingOpen(true);
|
||||||
|
offeringForm.setFieldsValue(
|
||||||
|
item
|
||||||
|
? offeringEditFormValues(item, templateFields)
|
||||||
|
: offeringDefaultFormValues(templateFields),
|
||||||
|
);
|
||||||
|
setFormValues(offeringForm.getFieldsValue(true) as Record<string, unknown>);
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeOffering = () => {
|
||||||
|
setOfferingOpen(false);
|
||||||
|
setEditingOffering(null);
|
||||||
|
offeringForm.resetFields();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleValuesChange = (_: unknown, allValues: Record<string, unknown>) => {
|
||||||
|
setFormValues(allValues);
|
||||||
|
setOfferingDraftVersion((version) => version + 1);
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
offeringForm,
|
||||||
|
offeringOpen,
|
||||||
|
editingOffering,
|
||||||
|
previewPage,
|
||||||
|
templateFieldSection,
|
||||||
|
formValues,
|
||||||
|
offeringDraftVersion,
|
||||||
|
setPreviewPage,
|
||||||
|
beginOffering,
|
||||||
|
closeOffering,
|
||||||
|
handleValuesChange,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,185 +1,51 @@
|
|||||||
import {
|
import { Button, Divider, Form, Typography } from "antd";
|
||||||
Button,
|
|
||||||
Divider,
|
|
||||||
Form,
|
|
||||||
Input,
|
|
||||||
List,
|
|
||||||
Modal,
|
|
||||||
Popconfirm,
|
|
||||||
Select,
|
|
||||||
Space,
|
|
||||||
Table,
|
|
||||||
Tag,
|
|
||||||
Typography,
|
|
||||||
message,
|
|
||||||
} from "antd";
|
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import { isTrustContentComplete } from "@personal-brand/api-client";
|
|
||||||
import type {
|
|
||||||
TemplateAdminField,
|
|
||||||
TrustContent,
|
|
||||||
TrustContentInput,
|
|
||||||
} from "@personal-brand/api-client";
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { useSearchParams } from "react-router-dom";
|
|
||||||
import { createApiClient } from "../../lib/api.js";
|
|
||||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
import { QueryState } from "../../components/QueryState.js";
|
||||||
import { TemplateListField } from "../../components/TemplateListField.js";
|
import { TrustContentEditorModal } from "./components/TrustContentEditorModal.js";
|
||||||
import { MutationError, QueryState } from "../../components/QueryState.js";
|
import { TrustContentTable } from "./components/TrustContentTable.js";
|
||||||
|
import { TrustRequirementsList } from "./components/TrustRequirementsList.js";
|
||||||
const types = [
|
import type { TrustTypeOption } from "./domain/trust-content-domain.js";
|
||||||
{
|
import {
|
||||||
value: "schedule",
|
createTrustPageLabelResolver,
|
||||||
label: "时间与服务安排",
|
groupTrustContentByType,
|
||||||
help: "说明你通常什么时候提供服务、接受预约或处理订单。多项内容可以分行填写。",
|
selectTrustTypeOptions,
|
||||||
},
|
} from "./domain/trust-content-domain.js";
|
||||||
{
|
import { useTrustContentEditor } from "./hooks/useTrustContentEditor.js";
|
||||||
value: "coverage",
|
import { useTrustContentQueries } from "./hooks/useTrustContentQueries.js";
|
||||||
label: "服务范围与方式",
|
|
||||||
help: "说明服务地点、覆盖范围、适用对象或承接边界。多项内容可以分行填写。",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
value: "process",
|
|
||||||
label: "合作流程",
|
|
||||||
help: "说明客户从提出需求到完成合作会经历哪些步骤,每行写一步。",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
value: "credential",
|
|
||||||
label: "资质与专业证明",
|
|
||||||
help: "说明资质、经验、制作标准或让客户放心的专业依据。",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
value: "case",
|
|
||||||
label: "案例与客户反馈",
|
|
||||||
help: "写代表性案例、服务结果或客户评价,多条内容可以分行填写。",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
value: "promise",
|
|
||||||
label: "服务承诺与响应说明",
|
|
||||||
help: "说明回复时间、交付承诺、售后方式或合作预期。",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
type TrustTypeOption = {
|
|
||||||
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[];
|
|
||||||
hideStandardFields?: Array<"summary" | "content">;
|
|
||||||
maxPublishedItems?: number;
|
|
||||||
};
|
|
||||||
const fallbackTypes: TrustTypeOption[] = types.map(({ value, label, help }) => ({
|
|
||||||
type: value,
|
|
||||||
label,
|
|
||||||
adminFields: { title: "标题", summary: "摘要", content: "详细内容" },
|
|
||||||
help,
|
|
||||||
}));
|
|
||||||
|
|
||||||
export function TrustContentPage() {
|
export function TrustContentPage() {
|
||||||
const client = createApiClient();
|
const { query, workspace } = useTrustContentQueries();
|
||||||
const queryClient = useQueryClient();
|
const availableTypes = selectTrustTypeOptions(workspace.data?.templateContent?.trustContentTypes);
|
||||||
const [editing, setEditing] = useState<TrustContent | null>(null);
|
const pageLabel = createTrustPageLabelResolver(workspace.data?.templateContent?.navigation);
|
||||||
const [open, setOpen] = useState(false);
|
const contentByType = groupTrustContentByType(query.data ?? []);
|
||||||
const [form] = Form.useForm<TrustContentInput>();
|
const firstMissingRequiredType =
|
||||||
const [searchParams] = useSearchParams();
|
availableTypes.find((item) => item.required && !contentByType.has(item.type))?.type ??
|
||||||
const selectedType = Form.useWatch("type", form);
|
availableTypes[0]?.type ??
|
||||||
const query = useQuery({
|
"credential";
|
||||||
queryKey: ["trust-content"],
|
const {
|
||||||
queryFn: () => client.listAdminTrustContent(),
|
begin,
|
||||||
|
closeEditor,
|
||||||
|
editing,
|
||||||
|
form: editorForm,
|
||||||
|
open,
|
||||||
|
remove,
|
||||||
|
save,
|
||||||
|
} = useTrustContentEditor({
|
||||||
|
availableTypes,
|
||||||
|
contentByType,
|
||||||
|
firstMissingRequiredType,
|
||||||
});
|
});
|
||||||
const workspace = useQuery({
|
const selectedType = Form.useWatch("type", editorForm);
|
||||||
queryKey: ["admin-workspace-trust-types"],
|
const selectedTypeMeta: TrustTypeOption | undefined = availableTypes.find(
|
||||||
queryFn: () => client.getAdminWorkspace(),
|
(item) => item.type === selectedType,
|
||||||
});
|
);
|
||||||
const availableTypes: TrustTypeOption[] = workspace.data?.templateContent?.trustContentTypes
|
|
||||||
?.length
|
|
||||||
? workspace.data.templateContent.trustContentTypes
|
|
||||||
: fallbackTypes;
|
|
||||||
const pageLabel = (page: string) =>
|
|
||||||
workspace.data?.templateContent?.navigation.find((item) => item.page === page)?.label ??
|
|
||||||
(
|
|
||||||
{ home: "首页", offerings: "业务展示页", detail: "详情页", profile: "主理人页" } as Record<
|
|
||||||
string,
|
|
||||||
string
|
|
||||||
>
|
|
||||||
)[page] ??
|
|
||||||
page;
|
|
||||||
const trustPageLabels = [
|
const trustPageLabels = [
|
||||||
...new Set(availableTypes.flatMap((item) => item.pages ?? []).map(pageLabel)),
|
...new Set(availableTypes.flatMap((item) => item.pages ?? []).map(pageLabel)),
|
||||||
];
|
];
|
||||||
const trustPlacement = trustPageLabels.length
|
const trustPlacement = trustPageLabels.length
|
||||||
? `小程序的${trustPageLabels.join("、")}中`
|
? `小程序的${trustPageLabels.join("、")}中`
|
||||||
: "小程序对应的信任展示区域中";
|
: "小程序对应的信任展示区域中";
|
||||||
const selectedTypeMeta = availableTypes.find((item) => item.type === selectedType);
|
|
||||||
const contentByType = new Map<string, TrustContent>();
|
|
||||||
for (const item of query.data ?? []) {
|
|
||||||
const current = contentByType.get(item.type);
|
|
||||||
const hasConfig = Object.keys(item.config ?? {}).length > 0;
|
|
||||||
const currentHasConfig = Object.keys(current?.config ?? {}).length > 0;
|
|
||||||
if (
|
|
||||||
!current ||
|
|
||||||
(item.isPublished && !current.isPublished) ||
|
|
||||||
(item.isPublished === current.isPublished && hasConfig && !currentHasConfig)
|
|
||||||
) {
|
|
||||||
contentByType.set(item.type, item);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const firstMissingRequiredType =
|
|
||||||
availableTypes.find((item) => item.required && !contentByType.has(item.type))?.type ??
|
|
||||||
availableTypes[0]?.type ??
|
|
||||||
"credential";
|
|
||||||
const requestedType = searchParams.get("type");
|
|
||||||
const save = useMutation({
|
|
||||||
mutationFn: (values: TrustContentInput) =>
|
|
||||||
editing
|
|
||||||
? client.updateAdminTrustContent(editing.id, values)
|
|
||||||
: client.createAdminTrustContent(values),
|
|
||||||
onSuccess: () => {
|
|
||||||
message.success("品牌内容已保存为草稿,发布后小程序才会更新");
|
|
||||||
setOpen(false);
|
|
||||||
setEditing(null);
|
|
||||||
form.resetFields();
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const remove = useMutation({
|
|
||||||
mutationFn: (id: string) => client.deleteAdminTrustContent(id),
|
|
||||||
onSuccess: () => {
|
|
||||||
message.success("品牌内容已删除");
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const begin = (item?: TrustContent, type?: string) => {
|
|
||||||
setEditing(item ?? null);
|
|
||||||
setOpen(true);
|
|
||||||
form.setFieldsValue(
|
|
||||||
item
|
|
||||||
? {
|
|
||||||
type: item.type,
|
|
||||||
title: item.title,
|
|
||||||
...(item.summary ? { summary: item.summary } : {}),
|
|
||||||
content: item.content,
|
|
||||||
config: item.config ?? {},
|
|
||||||
...(item.coverUrl ? { coverUrl: item.coverUrl } : {}),
|
|
||||||
isPublished: item.isPublished,
|
|
||||||
}
|
|
||||||
: { type: type ?? firstMissingRequiredType, isPublished: false, config: {} },
|
|
||||||
);
|
|
||||||
};
|
|
||||||
useEffect(() => {
|
|
||||||
if (!requestedType || !availableTypes.some((item) => item.type === requestedType)) return;
|
|
||||||
begin(contentByType.get(requestedType), requestedType);
|
|
||||||
}, [requestedType, availableTypes.length]);
|
|
||||||
return (
|
return (
|
||||||
<QueryState
|
<QueryState
|
||||||
loading={query.isLoading || workspace.isLoading}
|
loading={query.isLoading || workspace.isLoading}
|
||||||
@@ -202,213 +68,34 @@ export function TrustContentPage() {
|
|||||||
<Typography.Paragraph type="secondary">
|
<Typography.Paragraph type="secondary">
|
||||||
标记为“发布必填”的项目需要填写完整后,才能发布小程序。
|
标记为“发布必填”的项目需要填写完整后,才能发布小程序。
|
||||||
</Typography.Paragraph>
|
</Typography.Paragraph>
|
||||||
<List
|
<TrustRequirementsList
|
||||||
size="small"
|
availableTypes={availableTypes}
|
||||||
dataSource={availableTypes}
|
contentByType={contentByType}
|
||||||
renderItem={(item) => {
|
items={query.data ?? []}
|
||||||
const content = contentByType.get(item.type);
|
onEdit={begin}
|
||||||
const publishedCount = (query.data ?? []).filter(
|
|
||||||
(record) => record.type === item.type && record.isPublished,
|
|
||||||
).length;
|
|
||||||
const tooMany =
|
|
||||||
item.maxPublishedItems !== undefined && publishedCount > item.maxPublishedItems;
|
|
||||||
const complete = Boolean(content && isTrustContentComplete(content, item) && !tooMany);
|
|
||||||
return (
|
|
||||||
<List.Item
|
|
||||||
actions={[
|
|
||||||
<Button
|
|
||||||
key={item.type}
|
|
||||||
type="link"
|
|
||||||
size="small"
|
|
||||||
onClick={() => (content ? begin(content) : begin(undefined, item.type))}
|
|
||||||
>
|
|
||||||
{content ? "编辑" : "新增"}
|
|
||||||
</Button>,
|
|
||||||
]}
|
|
||||||
>
|
|
||||||
<Space wrap>
|
|
||||||
<Typography.Text strong>{item.label}</Typography.Text>
|
|
||||||
{item.required && <Tag color="orange">发布必填</Tag>}
|
|
||||||
{(item.pages ?? []).map((page) => (
|
|
||||||
<Tag key={page}>{pageLabel(page)}</Tag>
|
|
||||||
))}
|
|
||||||
<Tag color={complete ? "success" : "default"}>
|
|
||||||
{tooMany
|
|
||||||
? `公开内容过多(${publishedCount} 条)`
|
|
||||||
: complete
|
|
||||||
? "内容完整"
|
|
||||||
: content
|
|
||||||
? "需要完善"
|
|
||||||
: "尚未填写"}
|
|
||||||
</Tag>
|
|
||||||
{item.help && <Typography.Text type="secondary">{item.help}</Typography.Text>}
|
|
||||||
</Space>
|
|
||||||
</List.Item>
|
|
||||||
);
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
<Divider />
|
<Divider />
|
||||||
<section aria-label="已配置的品牌内容">
|
<TrustContentTable
|
||||||
<Table
|
availableTypes={availableTypes}
|
||||||
rowKey="id"
|
items={query.data ?? []}
|
||||||
dataSource={query.data ?? []}
|
removeError={remove.error}
|
||||||
locale={{ emptyText: "还没有品牌内容,请先按上方模板要求添加。" }}
|
removePending={remove.isPending}
|
||||||
columns={[
|
onEdit={(item) => begin(item)}
|
||||||
{
|
onDelete={(id) => remove.mutate(id)}
|
||||||
title: "内容类型",
|
|
||||||
dataIndex: "type",
|
|
||||||
render: (value) => (
|
|
||||||
<Tag>{availableTypes.find((item) => item.type === value)?.label ?? value}</Tag>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{ title: "标题", dataIndex: "title" },
|
|
||||||
{
|
|
||||||
title: "内容预览",
|
|
||||||
ellipsis: { showTitle: true },
|
|
||||||
render: (_value: unknown, item: TrustContent) => {
|
|
||||||
const meta = availableTypes.find((type) => type.type === item.type);
|
|
||||||
if (meta?.hideStandardFields?.includes("content")) {
|
|
||||||
return (
|
|
||||||
meta.configFields
|
|
||||||
?.flatMap((field) => {
|
|
||||||
const value = item.config?.[field.key];
|
|
||||||
if (Array.isArray(value))
|
|
||||||
return value.length ? [`${field.label}:${value.length} 项`] : [];
|
|
||||||
return typeof value === "string" && value.trim()
|
|
||||||
? [`${field.label}:${value}`]
|
|
||||||
: [];
|
|
||||||
})
|
|
||||||
.join(";") || "尚未填写区块内容"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return item.summary || item.content || "未填写";
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: "发布状态",
|
|
||||||
dataIndex: "isPublished",
|
|
||||||
render: (value) => (
|
|
||||||
<Tag color={value ? "success" : "default"}>{value ? "随发布展示" : "草稿"}</Tag>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: "操作",
|
|
||||||
render: (_: unknown, item: TrustContent) => (
|
|
||||||
<Space>
|
|
||||||
<Button size="small" onClick={() => begin(item)}>
|
|
||||||
编辑
|
|
||||||
</Button>
|
|
||||||
<Popconfirm
|
|
||||||
title="确认删除这条信任内容?"
|
|
||||||
description="删除后需发布品牌,才会更新小程序展示。"
|
|
||||||
onConfirm={() => remove.mutate(item.id)}
|
|
||||||
>
|
|
||||||
<Button size="small" danger loading={remove.isPending}>
|
|
||||||
删除
|
|
||||||
</Button>
|
|
||||||
</Popconfirm>
|
|
||||||
</Space>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
]}
|
|
||||||
/>
|
/>
|
||||||
<MutationError error={remove.error} />
|
<TrustContentEditorModal
|
||||||
</section>
|
availableTypes={availableTypes}
|
||||||
<Modal
|
editing={editing}
|
||||||
|
form={editorForm}
|
||||||
open={open}
|
open={open}
|
||||||
title={editing ? "编辑品牌内容" : "添加品牌内容"}
|
pageLabel={pageLabel}
|
||||||
onCancel={() => {
|
saveError={save.error}
|
||||||
setOpen(false);
|
savePending={save.isPending}
|
||||||
setEditing(null);
|
selectedTypeMeta={selectedTypeMeta}
|
||||||
form.resetFields();
|
onCancel={closeEditor}
|
||||||
}}
|
onFinish={(values) => save.mutate(values)}
|
||||||
onOk={() => form.submit()}
|
|
||||||
confirmLoading={save.isPending}
|
|
||||||
destroyOnClose
|
|
||||||
>
|
|
||||||
<Form
|
|
||||||
form={form}
|
|
||||||
layout="vertical"
|
|
||||||
onFinish={(values) => save.mutate({ ...values, content: values.content ?? "" })}
|
|
||||||
>
|
|
||||||
<Form.Item name="type" label="内容类型" rules={[{ required: true }]}>
|
|
||||||
<Select
|
|
||||||
options={availableTypes.map((item) => ({ value: item.type, label: item.label }))}
|
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
|
||||||
{selectedTypeMeta?.pages?.length ? (
|
|
||||||
<Typography.Paragraph type="secondary">
|
|
||||||
这类内容会显示在:
|
|
||||||
{selectedTypeMeta.pages.map(pageLabel).join("、")}
|
|
||||||
</Typography.Paragraph>
|
|
||||||
) : null}
|
|
||||||
<Form.Item
|
|
||||||
name="title"
|
|
||||||
label={selectedTypeMeta?.adminFields.title ?? "标题"}
|
|
||||||
rules={[{ required: true }]}
|
|
||||||
>
|
|
||||||
<Input placeholder="例如:服务过 30+ 位独立创作者" />
|
|
||||||
</Form.Item>
|
|
||||||
{!selectedTypeMeta?.hideStandardFields?.includes("summary") && (
|
|
||||||
<Form.Item
|
|
||||||
name="summary"
|
|
||||||
label={selectedTypeMeta?.adminFields.summary ?? "摘要"}
|
|
||||||
help={selectedTypeMeta?.adminFields.summaryHelp}
|
|
||||||
>
|
|
||||||
<Input placeholder={selectedTypeMeta?.adminFields.summaryPlaceholder} />
|
|
||||||
</Form.Item>
|
|
||||||
)}
|
|
||||||
{!selectedTypeMeta?.hideStandardFields?.includes("content") && (
|
|
||||||
<Form.Item
|
|
||||||
name="content"
|
|
||||||
label={selectedTypeMeta?.adminFields.content ?? "详细内容"}
|
|
||||||
help={
|
|
||||||
selectedTypeMeta?.help ?? "每行写一项,页面会按模板样式展示。不要填写 HTML 或代码。"
|
|
||||||
}
|
|
||||||
rules={[{ required: true }]}
|
|
||||||
>
|
|
||||||
<Input.TextArea
|
|
||||||
rows={8}
|
|
||||||
showCount
|
|
||||||
maxLength={2000}
|
|
||||||
placeholder={selectedTypeMeta?.placeholder ?? "例如:\n第一项内容\n第二项内容"}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
)}
|
|
||||||
{selectedTypeMeta?.configFields?.map((field) =>
|
|
||||||
field.input === "list" ? (
|
|
||||||
<TemplateListField key={field.key} field={field} name={["config", field.key]} />
|
|
||||||
) : (
|
|
||||||
<Form.Item
|
|
||||||
key={field.key}
|
|
||||||
name={["config", field.key]}
|
|
||||||
label={field.label}
|
|
||||||
help={field.help}
|
|
||||||
rules={[{ required: field.required === true }]}
|
|
||||||
>
|
|
||||||
{field.input === "textarea" ? <Input.TextArea rows={3} /> : <Input />}
|
|
||||||
</Form.Item>
|
|
||||||
),
|
|
||||||
)}
|
|
||||||
<Form.Item
|
|
||||||
name="coverUrl"
|
|
||||||
label="配图地址"
|
|
||||||
help="粘贴一张可公开访问的图片地址,保存前会显示预览。"
|
|
||||||
>
|
|
||||||
<ImageUrlField placeholder="粘贴案例或经历配图地址" scope="trust" />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="isPublished" label="公开状态">
|
|
||||||
<Select
|
|
||||||
options={[
|
|
||||||
{ value: true, label: "随品牌发布展示" },
|
|
||||||
{ value: false, label: "保存为草稿" },
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
<MutationError error={save.error} />
|
|
||||||
</Form>
|
|
||||||
</Modal>
|
|
||||||
</QueryState>
|
</QueryState>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import { Form, Input, Modal, Select, Typography } from "antd";
|
||||||
|
import type { FormInstance } from "antd";
|
||||||
|
import type { TrustContent, TrustContentInput } from "@personal-brand/api-client";
|
||||||
|
import { ImageUrlField } from "../../../components/ImageUrlField.js";
|
||||||
|
import { TemplateListField } from "../../../components/TemplateListField.js";
|
||||||
|
import { MutationError } from "../../../components/QueryState.js";
|
||||||
|
import type { TrustTypeOption } from "../domain/trust-content-domain.js";
|
||||||
|
|
||||||
|
export function TrustContentEditorModal({
|
||||||
|
availableTypes,
|
||||||
|
editing,
|
||||||
|
form,
|
||||||
|
open,
|
||||||
|
pageLabel,
|
||||||
|
saveError,
|
||||||
|
savePending,
|
||||||
|
selectedTypeMeta,
|
||||||
|
onCancel,
|
||||||
|
onFinish,
|
||||||
|
}: {
|
||||||
|
availableTypes: TrustTypeOption[];
|
||||||
|
editing: TrustContent | null;
|
||||||
|
form: FormInstance<TrustContentInput>;
|
||||||
|
open: boolean;
|
||||||
|
pageLabel: (page: string) => string;
|
||||||
|
saveError: unknown;
|
||||||
|
savePending: boolean;
|
||||||
|
selectedTypeMeta?: TrustTypeOption | undefined;
|
||||||
|
onCancel: () => void;
|
||||||
|
onFinish: (values: TrustContentInput) => void;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
title={editing ? "编辑品牌内容" : "添加品牌内容"}
|
||||||
|
onCancel={onCancel}
|
||||||
|
onOk={() => form.submit()}
|
||||||
|
confirmLoading={savePending}
|
||||||
|
destroyOnClose
|
||||||
|
>
|
||||||
|
<Form
|
||||||
|
form={form}
|
||||||
|
layout="vertical"
|
||||||
|
onFinish={(values) => onFinish({ ...values, content: values.content ?? "" })}
|
||||||
|
>
|
||||||
|
<Form.Item name="type" label="内容类型" rules={[{ required: true }]}>
|
||||||
|
<Select
|
||||||
|
options={availableTypes.map((item) => ({ value: item.type, label: item.label }))}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
{selectedTypeMeta?.pages?.length ? (
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
这类内容会显示在:{selectedTypeMeta.pages.map(pageLabel).join("、")}
|
||||||
|
</Typography.Paragraph>
|
||||||
|
) : null}
|
||||||
|
<Form.Item
|
||||||
|
name="title"
|
||||||
|
label={selectedTypeMeta?.adminFields.title ?? "标题"}
|
||||||
|
rules={[{ required: true }]}
|
||||||
|
>
|
||||||
|
<Input placeholder="例如:服务过 30+ 位独立创作者" />
|
||||||
|
</Form.Item>
|
||||||
|
{!selectedTypeMeta?.hideStandardFields?.includes("summary") && (
|
||||||
|
<Form.Item
|
||||||
|
name="summary"
|
||||||
|
label={selectedTypeMeta?.adminFields.summary ?? "摘要"}
|
||||||
|
help={selectedTypeMeta?.adminFields.summaryHelp}
|
||||||
|
>
|
||||||
|
<Input placeholder={selectedTypeMeta?.adminFields.summaryPlaceholder} />
|
||||||
|
</Form.Item>
|
||||||
|
)}
|
||||||
|
{!selectedTypeMeta?.hideStandardFields?.includes("content") && (
|
||||||
|
<Form.Item
|
||||||
|
name="content"
|
||||||
|
label={selectedTypeMeta?.adminFields.content ?? "详细内容"}
|
||||||
|
help={
|
||||||
|
selectedTypeMeta?.help ?? "每行写一项,页面会按模板样式展示。不要填写 HTML 或代码。"
|
||||||
|
}
|
||||||
|
rules={[{ required: true }]}
|
||||||
|
>
|
||||||
|
<Input.TextArea
|
||||||
|
rows={8}
|
||||||
|
showCount
|
||||||
|
maxLength={2000}
|
||||||
|
placeholder={selectedTypeMeta?.placeholder ?? "例如:\n第一项内容\n第二项内容"}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
)}
|
||||||
|
{selectedTypeMeta?.configFields?.map((field) =>
|
||||||
|
field.input === "list" ? (
|
||||||
|
<TemplateListField key={field.key} field={field} name={["config", field.key]} />
|
||||||
|
) : (
|
||||||
|
<Form.Item
|
||||||
|
key={field.key}
|
||||||
|
name={["config", field.key]}
|
||||||
|
label={field.label}
|
||||||
|
help={field.help}
|
||||||
|
rules={[{ required: field.required === true }]}
|
||||||
|
>
|
||||||
|
{field.input === "textarea" ? <Input.TextArea rows={3} /> : <Input />}
|
||||||
|
</Form.Item>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
<Form.Item
|
||||||
|
name="coverUrl"
|
||||||
|
label="配图地址"
|
||||||
|
help="粘贴一张可公开访问的图片地址,保存前会显示预览。"
|
||||||
|
>
|
||||||
|
<ImageUrlField placeholder="粘贴案例或经历配图地址" scope="trust" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="isPublished" label="公开状态">
|
||||||
|
<Select
|
||||||
|
options={[
|
||||||
|
{ value: true, label: "随品牌发布展示" },
|
||||||
|
{ value: false, label: "保存为草稿" },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<MutationError error={saveError} />
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import { Button, Popconfirm, Space, Table, Tag } from "antd";
|
||||||
|
import type { TrustContent } from "@personal-brand/api-client";
|
||||||
|
import type { TrustTypeOption } from "../domain/trust-content-domain.js";
|
||||||
|
import { getTrustContentPreview } from "../domain/trust-content-domain.js";
|
||||||
|
import { MutationError } from "../../../components/QueryState.js";
|
||||||
|
|
||||||
|
export function TrustContentTable({
|
||||||
|
availableTypes,
|
||||||
|
items,
|
||||||
|
removeError,
|
||||||
|
removePending,
|
||||||
|
onEdit,
|
||||||
|
onDelete,
|
||||||
|
}: {
|
||||||
|
availableTypes: TrustTypeOption[];
|
||||||
|
items: TrustContent[];
|
||||||
|
removeError: unknown;
|
||||||
|
removePending: boolean;
|
||||||
|
onEdit: (item: TrustContent) => void;
|
||||||
|
onDelete: (id: string) => void;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<section aria-label="已配置的品牌内容">
|
||||||
|
<Table
|
||||||
|
rowKey="id"
|
||||||
|
dataSource={items}
|
||||||
|
locale={{ emptyText: "还没有品牌内容,请先按上方模板要求添加。" }}
|
||||||
|
columns={[
|
||||||
|
{
|
||||||
|
title: "内容类型",
|
||||||
|
dataIndex: "type",
|
||||||
|
render: (value) => (
|
||||||
|
<Tag>{availableTypes.find((item) => item.type === value)?.label ?? value}</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{ title: "标题", dataIndex: "title" },
|
||||||
|
{
|
||||||
|
title: "内容预览",
|
||||||
|
ellipsis: { showTitle: true },
|
||||||
|
render: (_value: unknown, item: TrustContent) =>
|
||||||
|
getTrustContentPreview(
|
||||||
|
item,
|
||||||
|
availableTypes.find((type) => type.type === item.type),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "发布状态",
|
||||||
|
dataIndex: "isPublished",
|
||||||
|
render: (value) => (
|
||||||
|
<Tag color={value ? "success" : "default"}>{value ? "随发布展示" : "草稿"}</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "操作",
|
||||||
|
render: (_: unknown, item: TrustContent) => (
|
||||||
|
<Space>
|
||||||
|
<Button size="small" onClick={() => onEdit(item)}>
|
||||||
|
编辑
|
||||||
|
</Button>
|
||||||
|
<Popconfirm
|
||||||
|
title="确认删除这条信任内容?"
|
||||||
|
description="删除后需发布品牌,才会更新小程序展示。"
|
||||||
|
onConfirm={() => onDelete(item.id)}
|
||||||
|
>
|
||||||
|
<Button size="small" danger loading={removePending}>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
<MutationError error={removeError} />
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import { Button, List, Space, Tag, Typography } from "antd";
|
||||||
|
import { isTrustContentComplete } from "@personal-brand/api-client";
|
||||||
|
import type { TrustContent } from "@personal-brand/api-client";
|
||||||
|
import type { TrustTypeOption } from "../domain/trust-content-domain.js";
|
||||||
|
|
||||||
|
export function TrustRequirementsList({
|
||||||
|
availableTypes,
|
||||||
|
contentByType,
|
||||||
|
items,
|
||||||
|
onEdit,
|
||||||
|
}: {
|
||||||
|
availableTypes: TrustTypeOption[];
|
||||||
|
contentByType: Map<string, TrustContent>;
|
||||||
|
items: TrustContent[];
|
||||||
|
onEdit: (item?: TrustContent, type?: string) => void;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<List
|
||||||
|
size="small"
|
||||||
|
dataSource={availableTypes}
|
||||||
|
renderItem={(item) => {
|
||||||
|
const content = contentByType.get(item.type);
|
||||||
|
const publishedCount = items.filter(
|
||||||
|
(record) => record.type === item.type && record.isPublished,
|
||||||
|
).length;
|
||||||
|
const tooMany =
|
||||||
|
item.maxPublishedItems !== undefined && publishedCount > item.maxPublishedItems;
|
||||||
|
const complete = Boolean(content && isTrustContentComplete(content, item) && !tooMany);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<List.Item
|
||||||
|
actions={[
|
||||||
|
<Button
|
||||||
|
key={item.type}
|
||||||
|
type="link"
|
||||||
|
size="small"
|
||||||
|
onClick={() => (content ? onEdit(content) : onEdit(undefined, item.type))}
|
||||||
|
>
|
||||||
|
{content ? "编辑" : "新增"}
|
||||||
|
</Button>,
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Space wrap>
|
||||||
|
<Typography.Text strong>{item.label}</Typography.Text>
|
||||||
|
{item.required && <Tag color="orange">发布必填</Tag>}
|
||||||
|
{(item.pages ?? []).map((page) => (
|
||||||
|
<Tag key={page}>{page}</Tag>
|
||||||
|
))}
|
||||||
|
<Tag color={complete ? "success" : "default"}>
|
||||||
|
{tooMany
|
||||||
|
? `公开内容过多(${publishedCount} 条)`
|
||||||
|
: complete
|
||||||
|
? "内容完整"
|
||||||
|
: content
|
||||||
|
? "需要完善"
|
||||||
|
: "尚未填写"}
|
||||||
|
</Tag>
|
||||||
|
{item.help && <Typography.Text type="secondary">{item.help}</Typography.Text>}
|
||||||
|
</Space>
|
||||||
|
</List.Item>
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import type { TemplateAdminField } from "@personal-brand/api-client";
|
||||||
|
import type { TrustContent } from "@personal-brand/api-client";
|
||||||
|
|
||||||
|
export type TrustTypeOption = {
|
||||||
|
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[];
|
||||||
|
hideStandardFields?: Array<"summary" | "content">;
|
||||||
|
maxPublishedItems?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
const fallbackTypeSeeds = [
|
||||||
|
{
|
||||||
|
value: "schedule",
|
||||||
|
label: "时间与服务安排",
|
||||||
|
help: "说明你通常什么时候提供服务、接受预约或处理订单。多项内容可以分行填写。",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: "coverage",
|
||||||
|
label: "服务范围与方式",
|
||||||
|
help: "说明服务地点、覆盖范围、适用对象或承接边界。多项内容可以分行填写。",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: "process",
|
||||||
|
label: "合作流程",
|
||||||
|
help: "说明客户从提出需求到完成合作会经历哪些步骤,每行写一步。",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: "credential",
|
||||||
|
label: "资质与专业证明",
|
||||||
|
help: "说明资质、经验、制作标准或让客户放心的专业依据。",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: "case",
|
||||||
|
label: "案例与客户反馈",
|
||||||
|
help: "写代表性案例、服务结果或客户评价,多条内容可以分行填写。",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: "promise",
|
||||||
|
label: "服务承诺与响应说明",
|
||||||
|
help: "说明回复时间、交付承诺、售后方式或合作预期。",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export const fallbackTrustTypes: TrustTypeOption[] = fallbackTypeSeeds.map(
|
||||||
|
({ value, label, help }) => ({
|
||||||
|
type: value,
|
||||||
|
label,
|
||||||
|
adminFields: { title: "标题", summary: "摘要", content: "详细内容" },
|
||||||
|
help,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const pageLabels: Record<string, string> = {
|
||||||
|
home: "首页",
|
||||||
|
offerings: "业务展示页",
|
||||||
|
detail: "详情页",
|
||||||
|
profile: "主理人页",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createTrustPageLabelResolver(navigation?: Array<{ page: string; label: string }>) {
|
||||||
|
return (page: string) =>
|
||||||
|
navigation?.find((item) => item.page === page)?.label ?? pageLabels[page] ?? page;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function selectTrustTypeOptions(workspaceTypes?: TrustTypeOption[]): TrustTypeOption[] {
|
||||||
|
return workspaceTypes?.length ? workspaceTypes : fallbackTrustTypes;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function groupTrustContentByType(items: TrustContent[]) {
|
||||||
|
const contentByType = new Map<string, TrustContent>();
|
||||||
|
|
||||||
|
for (const item of items) {
|
||||||
|
const current = contentByType.get(item.type);
|
||||||
|
const hasConfig = Object.keys(item.config ?? {}).length > 0;
|
||||||
|
const currentHasConfig = Object.keys(current?.config ?? {}).length > 0;
|
||||||
|
|
||||||
|
if (
|
||||||
|
!current ||
|
||||||
|
(item.isPublished && !current.isPublished) ||
|
||||||
|
(item.isPublished === current.isPublished && hasConfig && !currentHasConfig)
|
||||||
|
) {
|
||||||
|
contentByType.set(item.type, item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return contentByType;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTrustContentPreview(item: TrustContent, typeMeta?: TrustTypeOption): string {
|
||||||
|
if (typeMeta?.hideStandardFields?.includes("content")) {
|
||||||
|
return (
|
||||||
|
typeMeta.configFields
|
||||||
|
?.flatMap((field) => {
|
||||||
|
const value = item.config?.[field.key];
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.length ? [`${field.label}:${value.length} 项`] : [];
|
||||||
|
}
|
||||||
|
return typeof value === "string" && value.trim() ? [`${field.label}:${value}`] : [];
|
||||||
|
})
|
||||||
|
.join(";") || "尚未填写区块内容"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return item.summary || item.content || "未填写";
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useSearchParams } from "react-router-dom";
|
||||||
|
import { Form } from "antd";
|
||||||
|
import type { TrustContent, TrustContentInput } from "@personal-brand/api-client";
|
||||||
|
import type { TrustTypeOption } from "../domain/trust-content-domain.js";
|
||||||
|
import { useTrustContentMutations } from "./useTrustContentMutations.js";
|
||||||
|
|
||||||
|
export function useTrustContentEditor({
|
||||||
|
availableTypes,
|
||||||
|
contentByType,
|
||||||
|
firstMissingRequiredType,
|
||||||
|
}: {
|
||||||
|
availableTypes: TrustTypeOption[];
|
||||||
|
contentByType: Map<string, TrustContent>;
|
||||||
|
firstMissingRequiredType: string;
|
||||||
|
}) {
|
||||||
|
const [editing, setEditing] = useState<TrustContent | null>(null);
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [form] = Form.useForm<TrustContentInput>();
|
||||||
|
const [searchParams] = useSearchParams();
|
||||||
|
|
||||||
|
const closeEditor = () => {
|
||||||
|
setOpen(false);
|
||||||
|
setEditing(null);
|
||||||
|
form.resetFields();
|
||||||
|
};
|
||||||
|
|
||||||
|
const { save, remove } = useTrustContentMutations({ editing, closeEditor });
|
||||||
|
|
||||||
|
const begin = (item?: TrustContent, type?: string) => {
|
||||||
|
setEditing(item ?? null);
|
||||||
|
setOpen(true);
|
||||||
|
form.setFieldsValue(
|
||||||
|
item
|
||||||
|
? {
|
||||||
|
type: item.type,
|
||||||
|
title: item.title,
|
||||||
|
...(item.summary ? { summary: item.summary } : {}),
|
||||||
|
content: item.content,
|
||||||
|
config: item.config ?? {},
|
||||||
|
...(item.coverUrl ? { coverUrl: item.coverUrl } : {}),
|
||||||
|
isPublished: item.isPublished,
|
||||||
|
}
|
||||||
|
: { type: type ?? firstMissingRequiredType, isPublished: false, config: {} },
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const requestedType = searchParams.get("type");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!requestedType || !availableTypes.some((item) => item.type === requestedType)) return;
|
||||||
|
begin(contentByType.get(requestedType), requestedType);
|
||||||
|
}, [requestedType, availableTypes.length]);
|
||||||
|
|
||||||
|
return { begin, closeEditor, editing, form, open, remove, save };
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { message } from "antd";
|
||||||
|
import type { TrustContent, TrustContentInput } from "@personal-brand/api-client";
|
||||||
|
import { createApiClient } from "../../../lib/api.js";
|
||||||
|
|
||||||
|
export function useTrustContentMutations({
|
||||||
|
editing,
|
||||||
|
closeEditor,
|
||||||
|
}: {
|
||||||
|
editing: TrustContent | null;
|
||||||
|
closeEditor: () => void;
|
||||||
|
}) {
|
||||||
|
const client = createApiClient();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
const save = useMutation({
|
||||||
|
mutationFn: (values: TrustContentInput) =>
|
||||||
|
editing
|
||||||
|
? client.updateAdminTrustContent(editing.id, values)
|
||||||
|
: client.createAdminTrustContent(values),
|
||||||
|
onSuccess: () => {
|
||||||
|
message.success("品牌内容已保存为草稿,发布后小程序才会更新");
|
||||||
|
closeEditor();
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const remove = useMutation({
|
||||||
|
mutationFn: (id: string) => client.deleteAdminTrustContent(id),
|
||||||
|
onSuccess: () => {
|
||||||
|
message.success("品牌内容已删除");
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return { save, remove };
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { createApiClient } from "../../../lib/api.js";
|
||||||
|
|
||||||
|
export function useTrustContentQueries() {
|
||||||
|
const client = createApiClient();
|
||||||
|
|
||||||
|
return {
|
||||||
|
query: useQuery({
|
||||||
|
queryKey: ["trust-content"],
|
||||||
|
queryFn: () => client.listAdminTrustContent(),
|
||||||
|
}),
|
||||||
|
workspace: useQuery({
|
||||||
|
queryKey: ["admin-workspace-trust-types"],
|
||||||
|
queryFn: () => client.getAdminWorkspace(),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,30 +1,25 @@
|
|||||||
import {
|
import { Button, Card, Form, Input, Modal, Select, Space, Table, Tag, Typography } from "antd";
|
||||||
Button,
|
|
||||||
Card,
|
|
||||||
Form,
|
|
||||||
Input,
|
|
||||||
Modal,
|
|
||||||
Select,
|
|
||||||
Space,
|
|
||||||
Table,
|
|
||||||
Tag,
|
|
||||||
Typography,
|
|
||||||
message,
|
|
||||||
} from "antd";
|
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { createApiClient } from "../../lib/api.js";
|
|
||||||
import { ApiClientError } from "@personal-brand/api-client";
|
import { ApiClientError } from "@personal-brand/api-client";
|
||||||
|
import { createApiClient } from "../../lib/api.js";
|
||||||
import type {
|
import type {
|
||||||
BrandFieldDefinition,
|
BrandFieldDefinition,
|
||||||
BrandTemplateKey,
|
BrandTemplateKey,
|
||||||
InquiryForm,
|
InquiryForm,
|
||||||
} from "@personal-brand/api-client";
|
} from "@personal-brand/api-client";
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { useState } from "react";
|
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 { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||||
import { MutationError } from "../../components/QueryState.js";
|
import { MutationError } from "../../components/QueryState.js";
|
||||||
|
|
||||||
const inquiryFieldTypes = [
|
export const inquiryFieldTypes = [
|
||||||
{ value: "text", label: "简短文字" },
|
{ value: "text", label: "简短文字" },
|
||||||
{ value: "textarea", label: "详细说明" },
|
{ value: "textarea", label: "详细说明" },
|
||||||
{ value: "phone", label: "联系电话" },
|
{ value: "phone", label: "联系电话" },
|
||||||
@@ -36,42 +31,26 @@ const inquiryFieldTypes = [
|
|||||||
{ value: "multi-select", label: "多项选择" },
|
{ value: "multi-select", label: "多项选择" },
|
||||||
];
|
];
|
||||||
|
|
||||||
function readOptionLabel(option: unknown): string {
|
export function readOptionLabel(option: unknown): string {
|
||||||
const value = option as { label?: unknown } | null | undefined;
|
const value = option as { label?: unknown } | null | undefined;
|
||||||
return typeof value?.label === "string" ? value.label : "";
|
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 : [])
|
return (Array.isArray(options) ? options : [])
|
||||||
.map(readOptionLabel)
|
.map(readOptionLabel)
|
||||||
.filter((label) => label.trim())
|
.filter((label) => label.trim())
|
||||||
.map((label) => ({ label, value: label }));
|
.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() {
|
export function WorkspacePage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const client = createApiClient();
|
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const [fieldOpen, setFieldOpen] = useState(false);
|
const [fieldOpen, setFieldOpen] = useState(false);
|
||||||
const [formOpen, setFormOpen] = useState(false);
|
const [formOpen, setFormOpen] = useState(false);
|
||||||
const [editingForm, setEditingForm] = useState<InquiryForm | null>(null);
|
const [editingForm, setEditingForm] = useState<InquiryForm | null>(null);
|
||||||
const [visualTarget, setVisualTarget] = useState<string | null>(null);
|
const [visualTarget, setVisualTarget] = useState<string | null>(null);
|
||||||
const [industryTarget, setIndustryTarget] = useState<{
|
const [industryTarget, setIndustryTarget] = useState<IndustryTarget | null>(null);
|
||||||
key: "personal" | "food" | "doors";
|
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
capabilities: string[];
|
|
||||||
} | null>(null);
|
|
||||||
const [previewIndustry, setPreviewIndustry] = useState<BrandTemplateKey>("personal");
|
const [previewIndustry, setPreviewIndustry] = useState<BrandTemplateKey>("personal");
|
||||||
const [previewVisual, setPreviewVisual] = useState("linjing-editorial");
|
const [previewVisual, setPreviewVisual] = useState("linjing-editorial");
|
||||||
const [form] = Form.useForm<Record<string, unknown>>();
|
const [form] = Form.useForm<Record<string, unknown>>();
|
||||||
@@ -89,126 +68,35 @@ export function WorkspacePage() {
|
|||||||
});
|
});
|
||||||
setFormOpen(true);
|
setFormOpen(true);
|
||||||
};
|
};
|
||||||
const query = useQuery({
|
const { query, runtimeQuery, templateCatalog, forms, templatePreview } = useWorkspaceQueries();
|
||||||
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 combinationPreview = useQuery({
|
const combinationPreview = useQuery({
|
||||||
queryKey: ["template-combination-preview", previewIndustry, previewVisual],
|
queryKey: ["template-combination-preview", previewIndustry, previewVisual],
|
||||||
queryFn: () => client.previewPublicTemplateCombination(previewIndustry, previewVisual),
|
queryFn: () =>
|
||||||
|
createApiClient().previewPublicTemplateCombination(previewIndustry, previewVisual),
|
||||||
enabled: Boolean(templateCatalog.data),
|
enabled: Boolean(templateCatalog.data),
|
||||||
});
|
});
|
||||||
const compatibleVisuals = (templateCatalog.data?.visuals ?? []).filter((visual) =>
|
const compatibleVisuals = (templateCatalog.data?.visuals ?? []).filter((visual) =>
|
||||||
supportsIndustry(visual, query.data?.brand?.templateKey ?? "personal"),
|
supportsIndustry(visual, query.data?.brand?.templateKey ?? "personal"),
|
||||||
);
|
);
|
||||||
const visualTemplate = useMutation({
|
const { visualTemplate, rollbackVisual, install, upgrade, rollback } = useTemplateMutations({
|
||||||
mutationFn: (key: string) =>
|
runtimeConfig: runtimeQuery.data?.brand?.config ?? undefined,
|
||||||
client.updateAdminBrand({
|
queryClient,
|
||||||
config: { ...(runtimeQuery.data?.brand?.config ?? {}), visualTemplateKey: key },
|
|
||||||
}),
|
|
||||||
onSuccess: () => {
|
|
||||||
message.success("视觉模板已切换");
|
|
||||||
void runtimeQuery.refetch();
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
const visualHistory = useQuery({
|
const visualHistory = useQuery({
|
||||||
queryKey: ["visual-template-history"],
|
queryKey: ["visual-template-history"],
|
||||||
queryFn: () => client.getAdminVisualTemplateHistory(),
|
queryFn: () => createApiClient().getAdminVisualTemplateHistory(),
|
||||||
});
|
});
|
||||||
const rollbackVisual = useMutation({
|
const { createField, removeField } = useFieldMutations({
|
||||||
mutationFn: () => client.rollbackAdminVisualTemplate(),
|
form,
|
||||||
onSuccess: () => {
|
queryClient,
|
||||||
message.success("视觉模板已回滚");
|
onClose: () => setFieldOpen(false),
|
||||||
void runtimeQuery.refetch();
|
|
||||||
void visualHistory.refetch();
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
const install = useMutation({
|
const { createForm, updateForm } = useInquiryFormMutations({
|
||||||
mutationFn: (key: "personal" | "food" | "doors") => client.installAdminTemplate(key),
|
form: inquiryForm,
|
||||||
onSuccess: () => {
|
queryClient,
|
||||||
message.success("模板已安装");
|
onClose: () => {
|
||||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const createField = useMutation({
|
|
||||||
mutationFn: (values: Omit<BrandFieldDefinition, "id" | "source">) =>
|
|
||||||
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<InquiryForm> }) =>
|
|
||||||
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("咨询表单已更新");
|
|
||||||
setFormOpen(false);
|
setFormOpen(false);
|
||||||
setEditingForm(null);
|
setEditingForm(null);
|
||||||
inquiryForm.resetFields();
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-forms"] });
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (query.isLoading) return <Card loading />;
|
if (query.isLoading) return <Card loading />;
|
||||||
|
|||||||
@@ -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<typeof createApiClient>;
|
||||||
|
runtimeConfig: Record<string, unknown> | undefined;
|
||||||
|
queryClient: {
|
||||||
|
invalidateQueries: (options: { queryKey: readonly unknown[] }) => Promise<void>;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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<typeof createApiClient>;
|
||||||
|
form: FormInstance<Record<string, unknown>>;
|
||||||
|
queryClient: {
|
||||||
|
invalidateQueries: (options: { queryKey: readonly unknown[] }) => Promise<void>;
|
||||||
|
};
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useFieldMutations({
|
||||||
|
client = createApiClient(),
|
||||||
|
form,
|
||||||
|
queryClient,
|
||||||
|
onClose,
|
||||||
|
}: FieldMutationOptions) {
|
||||||
|
const createField = useMutation({
|
||||||
|
mutationFn: (values: Omit<BrandFieldDefinition, "id" | "source">) =>
|
||||||
|
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<typeof createApiClient>;
|
||||||
|
form: FormInstance<Record<string, unknown>>;
|
||||||
|
queryClient: {
|
||||||
|
invalidateQueries: (options: { queryKey: readonly unknown[] }) => Promise<void>;
|
||||||
|
};
|
||||||
|
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<InquiryForm> }) =>
|
||||||
|
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 };
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
import {
|
import {
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
UnauthorizedException,
|
|
||||||
ForbiddenException,
|
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Delete,
|
Delete,
|
||||||
@@ -14,7 +12,6 @@ import {
|
|||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
import type { FastifyRequest } from "fastify";
|
import type { FastifyRequest } from "fastify";
|
||||||
import { PrismaService } from "./prisma.service.js";
|
import { PrismaService } from "./prisma.service.js";
|
||||||
import { readIdentity } from "./auth.js";
|
|
||||||
import {
|
import {
|
||||||
InstallTemplateDto,
|
InstallTemplateDto,
|
||||||
CreateOfferingDto,
|
CreateOfferingDto,
|
||||||
@@ -27,44 +24,30 @@ import {
|
|||||||
UpdateCapabilityInstallationDto,
|
UpdateCapabilityInstallationDto,
|
||||||
} from "./admin.dto.js";
|
} from "./admin.dto.js";
|
||||||
import {
|
import {
|
||||||
|
capabilityRegistry,
|
||||||
capabilityPlugins,
|
capabilityPlugins,
|
||||||
getBrandTemplate,
|
getBrandTemplate,
|
||||||
getTemplateSampleContent,
|
getTemplateSampleContent,
|
||||||
getTemplatePackageManifestForVisualKey,
|
|
||||||
getDefaultVisualTemplateKey,
|
|
||||||
resolveCapabilities,
|
|
||||||
} from "@personal-brand/config";
|
} from "@personal-brand/config";
|
||||||
import { TemplateWorkspaceService } from "./template-workspace.service.js";
|
import { TemplateWorkspaceService } from "./template-workspace.service.js";
|
||||||
import { validateFieldSnapshot, validateOfferingConfig } from "@personal-brand/validation";
|
import { validateFieldSnapshot } from "@personal-brand/validation";
|
||||||
import { PublicWorkspaceService } from "./modules/public/public-workspace.controller.js";
|
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")
|
@Controller("admin/workspace")
|
||||||
class AdminWorkspaceController {
|
class AdminWorkspaceController {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
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")
|
@Get("offerings")
|
||||||
async listOfferings(@Req() request: FastifyRequest): Promise<unknown> {
|
listOfferings(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
const brandId = this.requireAdmin(request).brandId;
|
const brandId = requireAdminIdentity(request).brandId;
|
||||||
const items = await this.prisma.offering.findMany({
|
return this.offeringService.list(brandId);
|
||||||
where: { brandId },
|
|
||||||
orderBy: { sortOrder: "asc" },
|
|
||||||
});
|
|
||||||
return items.map((item) => {
|
|
||||||
const config = (item.config ?? {}) as Record<string, unknown>;
|
|
||||||
return {
|
|
||||||
...item,
|
|
||||||
sections: config.sections ?? [],
|
|
||||||
media: config.media ?? [],
|
|
||||||
cta: config.cta ?? null,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post("offerings")
|
@Post("offerings")
|
||||||
@@ -72,23 +55,8 @@ class AdminWorkspaceController {
|
|||||||
@Req() request: FastifyRequest,
|
@Req() request: FastifyRequest,
|
||||||
@Body() body: CreateOfferingDto,
|
@Body() body: CreateOfferingDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const brandId = this.requireAdmin(request).brandId;
|
const brandId = requireAdminIdentity(request).brandId;
|
||||||
const { config, sections, media, cta, ...fields } = body;
|
return this.offeringService.create(brandId, 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,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch("offerings/:id")
|
@Patch("offerings/:id")
|
||||||
@@ -97,134 +65,46 @@ class AdminWorkspaceController {
|
|||||||
@Param("id") id: string,
|
@Param("id") id: string,
|
||||||
@Body() body: UpdateOfferingDto,
|
@Body() body: UpdateOfferingDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const brandId = this.requireAdmin(request).brandId;
|
const brandId = requireAdminIdentity(request).brandId;
|
||||||
const item = await this.prisma.offering.findFirst({ where: { id, brandId } });
|
return this.offeringService.update(brandId, id, body);
|
||||||
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,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Delete("offerings/:id")
|
@Delete("offerings/:id")
|
||||||
async deleteOffering(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
async deleteOffering(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||||
const brandId = this.requireAdmin(request).brandId;
|
const brandId = requireAdminIdentity(request).brandId;
|
||||||
const item = await this.prisma.offering.findFirst({ where: { id, brandId } });
|
return this.offeringService.delete(brandId, id);
|
||||||
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" };
|
|
||||||
}
|
}
|
||||||
@Get()
|
@Get()
|
||||||
async get(@Req() request: FastifyRequest): Promise<unknown> {
|
get(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
const brandId = this.requireAdmin(request).brandId;
|
const brandId = requireAdminIdentity(request).brandId;
|
||||||
const [brand, installations, fields, offerings, forms] = await Promise.all([
|
return this.workspaceService.get(brandId);
|
||||||
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("preview")
|
@Get("preview")
|
||||||
async getPreviewWorkspace(@Req() request: FastifyRequest): Promise<unknown> {
|
async getPreviewWorkspace(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
const { brandId } = this.requireAdmin(request);
|
const { brandId } = requireAdminIdentity(request);
|
||||||
return this.publicWorkspace.getForBrandId(brandId, true);
|
return this.workspaceService.getPreview(brandId);
|
||||||
}
|
|
||||||
private jsonObject(value: unknown): Record<string, unknown> {
|
|
||||||
return value && typeof value === "object" && !Array.isArray(value)
|
|
||||||
? (value as Record<string, unknown>)
|
|
||||||
: {};
|
|
||||||
}
|
}
|
||||||
@Post("install")
|
@Post("install")
|
||||||
async install(
|
async install(
|
||||||
@Req() request: FastifyRequest,
|
@Req() request: FastifyRequest,
|
||||||
@Body() body: InstallTemplateDto,
|
@Body() body: InstallTemplateDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
this.requireAdmin(request);
|
const { brandId } = requireAdminIdentity(request);
|
||||||
return this.templateWorkspace.install(this.requireAdmin(request).brandId, body.templateKey);
|
return this.templateWorkspace.install(brandId, body.templateKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get("capabilities")
|
@Get("capabilities")
|
||||||
async listCapabilities(@Req() request: FastifyRequest): Promise<unknown> {
|
async listCapabilities(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
const brandId = this.requireAdmin(request).brandId;
|
const brandId = requireAdminIdentity(request).brandId;
|
||||||
const [templateKey, installations] = await Promise.all([
|
const [templateKey, installations] = await Promise.all([
|
||||||
this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
||||||
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
|
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
|
||||||
]);
|
]);
|
||||||
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
|
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
|
||||||
const template = getBrandTemplate(templateKey);
|
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);
|
const item = installed.get(definition.key);
|
||||||
return {
|
return {
|
||||||
id: item?.id ?? null,
|
id: item?.id ?? null,
|
||||||
@@ -240,7 +120,7 @@ class AdminWorkspaceController {
|
|||||||
|
|
||||||
@Get("sample-content/preview")
|
@Get("sample-content/preview")
|
||||||
async previewSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
|
async previewSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
const brandId = this.requireAdmin(request).brandId;
|
const brandId = requireAdminIdentity(request).brandId;
|
||||||
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
||||||
const sample = getTemplateSampleContent(templateKey);
|
const sample = getTemplateSampleContent(templateKey);
|
||||||
if (!sample) throw new BadRequestException("模板示例内容不存在");
|
if (!sample) throw new BadRequestException("模板示例内容不存在");
|
||||||
@@ -265,7 +145,7 @@ class AdminWorkspaceController {
|
|||||||
|
|
||||||
@Post("sample-content/import")
|
@Post("sample-content/import")
|
||||||
async importSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
|
async importSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
const identity = this.requireAdmin(request);
|
const identity = requireAdminIdentity(request);
|
||||||
const brandId = identity.brandId;
|
const brandId = identity.brandId;
|
||||||
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
||||||
const sample = getTemplateSampleContent(templateKey);
|
const sample = getTemplateSampleContent(templateKey);
|
||||||
@@ -359,7 +239,7 @@ class AdminWorkspaceController {
|
|||||||
@Param("key") key: string,
|
@Param("key") key: string,
|
||||||
@Body() body: UpdateCapabilityInstallationDto,
|
@Body() body: UpdateCapabilityInstallationDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = this.requireAdmin(request);
|
const identity = requireAdminIdentity(request);
|
||||||
const brandId = identity.brandId;
|
const brandId = identity.brandId;
|
||||||
const template = getBrandTemplate(
|
const template = getBrandTemplate(
|
||||||
await this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
await this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
||||||
@@ -402,20 +282,20 @@ class AdminWorkspaceController {
|
|||||||
|
|
||||||
@Get("template/preview")
|
@Get("template/preview")
|
||||||
async previewTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
async previewTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
this.requireAdmin(request);
|
const { brandId } = requireAdminIdentity(request);
|
||||||
return this.templateWorkspace.preview(this.requireAdmin(request).brandId);
|
return this.templateWorkspace.preview(brandId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post("template/upgrade")
|
@Post("template/upgrade")
|
||||||
async upgradeTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
async upgradeTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
this.requireAdmin(request);
|
const { brandId } = requireAdminIdentity(request);
|
||||||
return this.templateWorkspace.upgrade(this.requireAdmin(request).brandId);
|
return this.templateWorkspace.upgrade(brandId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post("template/rollback")
|
@Post("template/rollback")
|
||||||
async rollbackTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
async rollbackTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
this.requireAdmin(request);
|
const { brandId } = requireAdminIdentity(request);
|
||||||
return this.templateWorkspace.rollback(this.requireAdmin(request).brandId);
|
return this.templateWorkspace.rollback(brandId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post("fields")
|
@Post("fields")
|
||||||
@@ -423,7 +303,7 @@ class AdminWorkspaceController {
|
|||||||
@Req() request: FastifyRequest,
|
@Req() request: FastifyRequest,
|
||||||
@Body() body: CreateFieldDefinitionDto,
|
@Body() body: CreateFieldDefinitionDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const brandId = this.requireAdmin(request).brandId;
|
const brandId = requireAdminIdentity(request).brandId;
|
||||||
return this.prisma.brandFieldDefinition.create({
|
return this.prisma.brandFieldDefinition.create({
|
||||||
data: {
|
data: {
|
||||||
...body,
|
...body,
|
||||||
@@ -441,7 +321,7 @@ class AdminWorkspaceController {
|
|||||||
@Param("id") id: string,
|
@Param("id") id: string,
|
||||||
@Body() body: UpdateFieldDefinitionDto,
|
@Body() body: UpdateFieldDefinitionDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const brandId = this.requireAdmin(request).brandId;
|
const brandId = requireAdminIdentity(request).brandId;
|
||||||
const item = await this.prisma.brandFieldDefinition.findFirst({
|
const item = await this.prisma.brandFieldDefinition.findFirst({
|
||||||
where: { id, brandId },
|
where: { id, brandId },
|
||||||
});
|
});
|
||||||
@@ -459,7 +339,7 @@ class AdminWorkspaceController {
|
|||||||
|
|
||||||
@Delete("fields/:id")
|
@Delete("fields/:id")
|
||||||
async deleteField(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
async deleteField(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||||
const brandId = this.requireAdmin(request).brandId;
|
const brandId = requireAdminIdentity(request).brandId;
|
||||||
const item = await this.prisma.brandFieldDefinition.findFirst({
|
const item = await this.prisma.brandFieldDefinition.findFirst({
|
||||||
where: { id, brandId, source: "custom" },
|
where: { id, brandId, source: "custom" },
|
||||||
});
|
});
|
||||||
@@ -470,7 +350,7 @@ class AdminWorkspaceController {
|
|||||||
|
|
||||||
@Get("forms")
|
@Get("forms")
|
||||||
listForms(@Req() request: FastifyRequest): Promise<unknown> {
|
listForms(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
const brandId = this.requireAdmin(request).brandId;
|
const brandId = requireAdminIdentity(request).brandId;
|
||||||
return this.prisma.inquiryForm.findMany({
|
return this.prisma.inquiryForm.findMany({
|
||||||
where: { brandId },
|
where: { brandId },
|
||||||
orderBy: { updatedAt: "desc" },
|
orderBy: { updatedAt: "desc" },
|
||||||
@@ -479,7 +359,7 @@ class AdminWorkspaceController {
|
|||||||
|
|
||||||
@Get("submissions")
|
@Get("submissions")
|
||||||
listSubmissions(@Req() request: FastifyRequest): Promise<unknown> {
|
listSubmissions(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
const brandId = this.requireAdmin(request).brandId;
|
const brandId = requireAdminIdentity(request).brandId;
|
||||||
return this.prisma.inquirySubmission.findMany({
|
return this.prisma.inquirySubmission.findMany({
|
||||||
where: { brandId },
|
where: { brandId },
|
||||||
include: {
|
include: {
|
||||||
@@ -496,7 +376,7 @@ class AdminWorkspaceController {
|
|||||||
@Param("id") id: string,
|
@Param("id") id: string,
|
||||||
@Body() body: UpdateInquirySubmissionDto,
|
@Body() body: UpdateInquirySubmissionDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const brandId = this.requireAdmin(request).brandId;
|
const brandId = requireAdminIdentity(request).brandId;
|
||||||
const item = await this.prisma.inquirySubmission.findFirst({
|
const item = await this.prisma.inquirySubmission.findFirst({
|
||||||
where: { id, brandId },
|
where: { id, brandId },
|
||||||
});
|
});
|
||||||
@@ -525,7 +405,7 @@ class AdminWorkspaceController {
|
|||||||
|
|
||||||
@Post("forms")
|
@Post("forms")
|
||||||
createForm(@Req() request: FastifyRequest, @Body() body: CreateInquiryFormDto): Promise<unknown> {
|
createForm(@Req() request: FastifyRequest, @Body() body: CreateInquiryFormDto): Promise<unknown> {
|
||||||
const brandId = this.requireAdmin(request).brandId;
|
const brandId = requireAdminIdentity(request).brandId;
|
||||||
if (validateFieldSnapshot(body.fieldsSnapshot).length)
|
if (validateFieldSnapshot(body.fieldsSnapshot).length)
|
||||||
throw new BadRequestException("咨询表单字段定义无效");
|
throw new BadRequestException("咨询表单字段定义无效");
|
||||||
return this.prisma.inquiryForm.create({
|
return this.prisma.inquiryForm.create({
|
||||||
@@ -544,7 +424,7 @@ class AdminWorkspaceController {
|
|||||||
@Param("id") id: string,
|
@Param("id") id: string,
|
||||||
@Body() body: UpdateInquiryFormDto,
|
@Body() body: UpdateInquiryFormDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const brandId = this.requireAdmin(request).brandId;
|
const brandId = requireAdminIdentity(request).brandId;
|
||||||
const item = await this.prisma.inquiryForm.findFirst({
|
const item = await this.prisma.inquiryForm.findFirst({
|
||||||
where: { id, brandId },
|
where: { id, brandId },
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ import {
|
|||||||
PublicWorkspaceService,
|
PublicWorkspaceService,
|
||||||
} from "./modules/public/public-workspace.controller.js";
|
} from "./modules/public/public-workspace.controller.js";
|
||||||
import { PublicBrandContextService } from "./modules/public/public-brand-context.service.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 { AdminConfigController } from "./modules/admin/admin-config.controller.js";
|
||||||
import { AdminUploadController } from "./modules/admin/admin-upload.controller.js";
|
import { AdminUploadController } from "./modules/admin/admin-upload.controller.js";
|
||||||
import { AdminLocalUploadController } from "./modules/admin/admin-local-upload.controller.js";
|
import { AdminLocalUploadController } from "./modules/admin/admin-local-upload.controller.js";
|
||||||
@@ -78,6 +80,8 @@ export class HealthController {
|
|||||||
BrandReleaseApiService,
|
BrandReleaseApiService,
|
||||||
PublicBrandContextService,
|
PublicBrandContextService,
|
||||||
PublicWorkspaceService,
|
PublicWorkspaceService,
|
||||||
|
AdminOfferingService,
|
||||||
|
AdminWorkspaceService,
|
||||||
],
|
],
|
||||||
exports: [PrismaService, WechatAuthService],
|
exports: [PrismaService, WechatAuthService],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,31 +1,14 @@
|
|||||||
import { Controller, Get, Injectable, Query } from "@nestjs/common";
|
import { Controller, Get, Injectable, Query } from "@nestjs/common";
|
||||||
import { Prisma } from "@prisma/client";
|
|
||||||
import { PrismaService } from "../../prisma.service.js";
|
import { PrismaService } from "../../prisma.service.js";
|
||||||
|
import {
|
||||||
|
buildBrandReleaseSnapshot,
|
||||||
|
type BrandReleaseSnapshot,
|
||||||
|
} from "../../brand-release.service.js";
|
||||||
import { PublicBrandContextService } from "./public-brand-context.service.js";
|
import { PublicBrandContextService } from "./public-brand-context.service.js";
|
||||||
import type { BrandReleaseSnapshot } from "../../brand-release.service.js";
|
|
||||||
import {
|
import {
|
||||||
getBrandTemplate,
|
assemblePublicWorkspace,
|
||||||
getVisualTemplate,
|
createUnpublishedWorkspace,
|
||||||
getVisualTemplateManifest,
|
} from "./public-workspace.snapshot-assembler.js";
|
||||||
resolveCapabilities,
|
|
||||||
capabilityPlugins,
|
|
||||||
getDefaultVisualTemplateKey,
|
|
||||||
getTemplatePackageManifestForVisualKey,
|
|
||||||
} from "@personal-brand/config";
|
|
||||||
import type {
|
|
||||||
RuntimeInquiryField,
|
|
||||||
RuntimeOffering,
|
|
||||||
RuntimeTrustItem,
|
|
||||||
RuntimeWorkspace,
|
|
||||||
} from "@personal-brand/types";
|
|
||||||
import { buildBrandReleaseSnapshot } from "../../brand-release.service.js";
|
|
||||||
import {
|
|
||||||
projectBrandAliases,
|
|
||||||
projectOfferingDetails,
|
|
||||||
projectTemplateData,
|
|
||||||
projectTrustItem,
|
|
||||||
projectTrustPresentation,
|
|
||||||
} from "@personal-brand/types";
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class PublicWorkspaceService {
|
export class PublicWorkspaceService {
|
||||||
@@ -38,345 +21,15 @@ export class PublicWorkspaceService {
|
|||||||
select: { version: true, createdAt: true, snapshot: true },
|
select: { version: true, createdAt: true, snapshot: true },
|
||||||
});
|
});
|
||||||
const draftSnapshot = draft ? await buildBrandReleaseSnapshot(this.prisma, brandId) : null;
|
const draftSnapshot = draft ? await buildBrandReleaseSnapshot(this.prisma, brandId) : null;
|
||||||
const sourceSnapshot = draftSnapshot ?? release?.snapshot;
|
if (!release && !draftSnapshot) return createUnpublishedWorkspace();
|
||||||
const releaseSnapshot = this.jsonObject(sourceSnapshot) as unknown as BrandReleaseSnapshot;
|
|
||||||
if (!release && !draftSnapshot) {
|
const sourceSnapshot = draftSnapshot ?? (release?.snapshot as BrandReleaseSnapshot | null);
|
||||||
return {
|
const snapshot = sourceSnapshot as BrandReleaseSnapshot;
|
||||||
contractVersion: "1.0",
|
return assemblePublicWorkspace({
|
||||||
schemaVersion: "1.0.0",
|
release: release ? { version: release.version, createdAt: release.createdAt } : null,
|
||||||
publication: { status: "unpublished", version: null },
|
snapshot,
|
||||||
brand: null,
|
draftSnapshot,
|
||||||
template: null,
|
|
||||||
visualTemplate: null,
|
|
||||||
offerings: [],
|
|
||||||
inquiryForms: [],
|
|
||||||
trustItems: [],
|
|
||||||
capabilities: [],
|
|
||||||
trustPresentation: {},
|
|
||||||
navigation: { tabs: [] },
|
|
||||||
plugins: [],
|
|
||||||
theme: { colors: {} },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
const brandData = this.jsonObject(releaseSnapshot.brand);
|
|
||||||
const offeringsData = this.jsonArray(releaseSnapshot.offerings).filter(
|
|
||||||
(item) => this.jsonObject(item).isEnabled === true,
|
|
||||||
) as Array<Record<string, unknown>>;
|
|
||||||
const enabledOfferingIds = new Set(offeringsData.map((item) => item.id));
|
|
||||||
const formsData = this.jsonArray(releaseSnapshot.forms).filter((item) => {
|
|
||||||
const form = this.jsonObject(item);
|
|
||||||
return (
|
|
||||||
form.isEnabled === true &&
|
|
||||||
(form.offeringId === null || enabledOfferingIds.has(form.offeringId))
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
const trustData = this.jsonArray(releaseSnapshot.trustContents).filter(
|
|
||||||
(item) => this.jsonObject(item).isPublished === true,
|
|
||||||
) as Array<Record<string, unknown>>;
|
|
||||||
const installationData = this.jsonObject(releaseSnapshot.installation);
|
|
||||||
const templateKeyFromSnapshot =
|
|
||||||
typeof releaseSnapshot.templateKey === "string" ? releaseSnapshot.templateKey : undefined;
|
|
||||||
const templateKey =
|
|
||||||
templateKeyFromSnapshot ??
|
|
||||||
(typeof installationData.templateKey === "string"
|
|
||||||
? installationData.templateKey
|
|
||||||
: undefined) ??
|
|
||||||
(typeof brandData.templateKey === "string" ? brandData.templateKey : "personal");
|
|
||||||
const template = releaseSnapshot.templateDefinition ?? getBrandTemplate(templateKey);
|
|
||||||
const capabilityData = this.jsonArray(releaseSnapshot.capabilities) as Array<
|
|
||||||
Record<string, unknown>
|
|
||||||
>;
|
|
||||||
const runtimeCapabilities = capabilityData.length
|
|
||||||
? capabilityData.map((item) => ({
|
|
||||||
key: this.string(item.capabilityKey),
|
|
||||||
version: this.string(item.capabilityVersion, "1.0.0"),
|
|
||||||
status: this.capabilityStatus(item.status),
|
|
||||||
config:
|
|
||||||
item.config && typeof item.config === "object" && !Array.isArray(item.config)
|
|
||||||
? (item.config as Record<string, unknown>)
|
|
||||||
: {},
|
|
||||||
}))
|
|
||||||
: template
|
|
||||||
? resolveCapabilities(template.capabilities).map((item) => ({
|
|
||||||
key: item.key,
|
|
||||||
version: item.version,
|
|
||||||
status: "enabled" as const,
|
|
||||||
config: {},
|
|
||||||
}))
|
|
||||||
: [];
|
|
||||||
const brandConfig =
|
|
||||||
brandData.config && typeof brandData.config === "object" && !Array.isArray(brandData.config)
|
|
||||||
? (brandData.config as Record<string, unknown>)
|
|
||||||
: {};
|
|
||||||
const visualTemplateKey =
|
|
||||||
typeof brandConfig.visualTemplateKey === "string"
|
|
||||||
? brandConfig.visualTemplateKey
|
|
||||||
: getDefaultVisualTemplateKey(templateKey);
|
|
||||||
const visualTemplate =
|
|
||||||
releaseSnapshot.visualTemplateDefinition ?? getVisualTemplate(visualTemplateKey);
|
|
||||||
const visualTemplateManifest =
|
|
||||||
releaseSnapshot.visualTemplateManifest ?? getVisualTemplateManifest(visualTemplateKey);
|
|
||||||
const templatePackageManifest =
|
|
||||||
releaseSnapshot.templatePackageManifest ??
|
|
||||||
getTemplatePackageManifestForVisualKey(visualTemplateKey);
|
|
||||||
const categoryOptions = new Map(
|
|
||||||
(templatePackageManifest?.admin.sections ?? [])
|
|
||||||
.filter((section) => section.target === "offering")
|
|
||||||
.flatMap((section) => section.fields)
|
|
||||||
.filter((field) => field.binding === "offering.config.categoryKey")
|
|
||||||
.flatMap((field) => field.options ?? [])
|
|
||||||
.map((option) => [option.value, option.label]),
|
|
||||||
);
|
|
||||||
// 标准 BrandProfile 字段优先,兼容旧模板仍使用的 config 字段。
|
|
||||||
// 这样后台编辑 description/contactPhone 等标准字段后,旧模板也会立即读取新值。
|
|
||||||
const runtimeBrand = projectBrandAliases(brandData, brandConfig);
|
|
||||||
const declaredTemplateFields = templatePackageManifest?.templateFields ?? [];
|
|
||||||
const templateData = projectTemplateData(
|
|
||||||
brandConfig,
|
|
||||||
declaredTemplateFields.map((field) => field.key),
|
|
||||||
);
|
|
||||||
const runtimeOfferings: RuntimeOffering[] = offeringsData.map((raw) => {
|
|
||||||
const item = raw;
|
|
||||||
const config = this.jsonObject(item.config);
|
|
||||||
const sections = Array.isArray(config.sections) ? config.sections : [];
|
|
||||||
const details = projectOfferingDetails(config);
|
|
||||||
const media = Array.isArray(config.media)
|
|
||||||
? config.media.flatMap((entry) => {
|
|
||||||
const value = this.jsonObject(entry);
|
|
||||||
return typeof value.url === "string"
|
|
||||||
? [
|
|
||||||
{
|
|
||||||
url: value.url,
|
|
||||||
alt:
|
|
||||||
typeof value.alt === "string"
|
|
||||||
? value.alt
|
|
||||||
: this.string(item.name, "业务提供项"),
|
|
||||||
type: "image" as const,
|
|
||||||
},
|
|
||||||
]
|
|
||||||
: [];
|
|
||||||
})
|
|
||||||
: [];
|
|
||||||
return {
|
|
||||||
id: this.string(item.id),
|
|
||||||
name: this.string(item.name),
|
|
||||||
summary: typeof item.summary === "string" ? item.summary : this.string(item.description),
|
|
||||||
enabled: item.isEnabled !== false,
|
|
||||||
kind: this.offeringKind(this.string(item.kind, "service")),
|
|
||||||
coverUrl: typeof item.coverUrl === "string" ? item.coverUrl : null,
|
|
||||||
priceText: typeof item.priceText === "string" ? item.priceText : null,
|
|
||||||
priceAmount: typeof item.priceAmount === "number" ? item.priceAmount : null,
|
|
||||||
schemaKey: typeof config.schemaKey === "string" ? config.schemaKey : "offering.default",
|
|
||||||
schemaVersion: typeof config.schemaVersion === "string" ? config.schemaVersion : "1.0.0",
|
|
||||||
presentation: {
|
|
||||||
...Object.fromEntries(
|
|
||||||
Object.entries(config).filter(
|
|
||||||
([key]) =>
|
|
||||||
![
|
|
||||||
"schemaKey",
|
|
||||||
"schemaVersion",
|
|
||||||
"details",
|
|
||||||
"sections",
|
|
||||||
"media",
|
|
||||||
"presentation",
|
|
||||||
].includes(key),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
...this.jsonObject(config.presentation),
|
|
||||||
categoryKey: typeof config.categoryKey === "string" ? config.categoryKey : "custom",
|
|
||||||
categoryLabel:
|
|
||||||
categoryOptions.get(
|
|
||||||
typeof config.categoryKey === "string" ? config.categoryKey : "custom",
|
|
||||||
) ?? "",
|
|
||||||
heroImage:
|
|
||||||
typeof config.detailHero === "string"
|
|
||||||
? config.detailHero
|
|
||||||
: typeof item.coverUrl === "string"
|
|
||||||
? item.coverUrl
|
|
||||||
: null,
|
|
||||||
keywords: Array.isArray(config.keywords)
|
|
||||||
? config.keywords.filter((keyword): keyword is string => typeof keyword === "string")
|
|
||||||
: [],
|
|
||||||
media,
|
|
||||||
details: {
|
|
||||||
background: details.background,
|
|
||||||
designConcept: details.designConcept,
|
|
||||||
crafts: details.crafts,
|
|
||||||
materialsList: details.materialsList,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
sections: sections
|
|
||||||
.filter((section): section is Record<string, unknown> =>
|
|
||||||
Boolean(section && typeof section === "object"),
|
|
||||||
)
|
|
||||||
.map((section) => ({
|
|
||||||
key: typeof section.key === "string" ? section.key : "section",
|
|
||||||
type: this.sectionType(section.type),
|
|
||||||
config: this.jsonObject(section.config),
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
const toInquiryFields = (snapshot: Prisma.JsonValue): RuntimeInquiryField[] =>
|
|
||||||
this.jsonArray(snapshot).flatMap((field) => {
|
|
||||||
if (!field || typeof field !== "object") return [];
|
|
||||||
const value = field as Record<string, unknown>;
|
|
||||||
if (typeof value.key !== "string" || typeof value.label !== "string") return [];
|
|
||||||
const sourceType = this.string(value.type);
|
|
||||||
const type =
|
|
||||||
sourceType === "phone"
|
|
||||||
? "tel"
|
|
||||||
: sourceType === "multi-select"
|
|
||||||
? "checkbox"
|
|
||||||
: [
|
|
||||||
"text",
|
|
||||||
"tel",
|
|
||||||
"number",
|
|
||||||
"select",
|
|
||||||
"radio",
|
|
||||||
"checkbox",
|
|
||||||
"checkbox",
|
|
||||||
"textarea",
|
|
||||||
"date",
|
|
||||||
].includes(sourceType)
|
|
||||||
? (sourceType as RuntimeInquiryField["type"])
|
|
||||||
: "text";
|
|
||||||
const options = Array.isArray(value.options)
|
|
||||||
? value.options.flatMap((option) => {
|
|
||||||
if (typeof option === "string") return [{ label: option, value: option }];
|
|
||||||
if (!option || typeof option !== "object") return [];
|
|
||||||
const item = option as Record<string, unknown>;
|
|
||||||
return typeof item.label === "string" && typeof item.value === "string"
|
|
||||||
? [{ label: item.label, value: item.value }]
|
|
||||||
: [];
|
|
||||||
})
|
|
||||||
: undefined;
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
key: value.key,
|
|
||||||
label: value.label,
|
|
||||||
type,
|
|
||||||
required: value.required === true,
|
|
||||||
...(options?.length ? { options } : {}),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
});
|
|
||||||
const trustDeclarations = templatePackageManifest?.trustContentTypes ?? [];
|
|
||||||
const trustItems: RuntimeTrustItem[] = trustData.flatMap((raw) => {
|
|
||||||
const item = projectTrustItem(this.jsonObject(raw));
|
|
||||||
return item && trustDeclarations.some((declaration) => declaration.type === item.type)
|
|
||||||
? [item]
|
|
||||||
: [];
|
|
||||||
});
|
|
||||||
const trustPresentation = projectTrustPresentation(trustItems, trustDeclarations);
|
|
||||||
const runtimeWorkspace: RuntimeWorkspace = {
|
|
||||||
schemaVersion: "1.0.0",
|
|
||||||
publication: {
|
|
||||||
status: draftSnapshot ? "draft" : "published",
|
|
||||||
version: draftSnapshot ? null : (release?.version ?? null),
|
|
||||||
...(!draftSnapshot && release ? { publishedAt: release.createdAt.toISOString() } : {}),
|
|
||||||
},
|
|
||||||
brand: runtimeBrand,
|
|
||||||
templateData,
|
|
||||||
navigation: {
|
|
||||||
tabs:
|
|
||||||
templatePackageManifest?.navigation.map((tab) => ({
|
|
||||||
key: tab.key,
|
|
||||||
label: tab.label,
|
|
||||||
page: templatePackageManifest.entrypoints[tab.page] ?? tab.page,
|
|
||||||
})) ?? [],
|
|
||||||
},
|
|
||||||
offerings: runtimeOfferings,
|
|
||||||
inquiryForms: formsData.map((raw) => {
|
|
||||||
const form = this.jsonObject(raw);
|
|
||||||
return {
|
|
||||||
key: this.string(form.id),
|
|
||||||
version:
|
|
||||||
typeof form.version === "number"
|
|
||||||
? String(form.version)
|
|
||||||
: this.string(form.version, "1"),
|
|
||||||
purpose: this.formPurpose(this.string(form.purpose, "inquiry")),
|
|
||||||
target: form.targetType === "offering" ? "offering" : "brand",
|
|
||||||
...(typeof form.offeringId === "string" ? { targetId: form.offeringId } : {}),
|
|
||||||
submissionAction: this.submissionAction(
|
|
||||||
this.string(form.submissionAction, "create-inquiry"),
|
|
||||||
),
|
|
||||||
fields: toInquiryFields(form.fieldsSnapshot as Prisma.JsonValue),
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
trustItems,
|
|
||||||
trustPresentation,
|
|
||||||
capabilities: runtimeCapabilities,
|
|
||||||
plugins: runtimeCapabilities
|
|
||||||
.filter((capability) => capability.status === "enabled")
|
|
||||||
.map((capability) => capability.key)
|
|
||||||
.map((key) => capabilityPlugins[key as keyof typeof capabilityPlugins])
|
|
||||||
.filter(Boolean)
|
|
||||||
.map((plugin) => ({ ...plugin, status: "enabled" as const, config: {} })),
|
|
||||||
theme: visualTemplate?.theme ?? {
|
|
||||||
colors: { background: "#F7F5F1", foreground: "#252525", accent: "#8A6846" },
|
|
||||||
},
|
|
||||||
...(visualTemplate?.layout ? { layout: visualTemplate.layout } : {}),
|
|
||||||
};
|
|
||||||
const response = {
|
|
||||||
...runtimeWorkspace,
|
|
||||||
contractVersion: "1.0",
|
|
||||||
brand: runtimeBrand,
|
|
||||||
template: template
|
|
||||||
? {
|
|
||||||
key: template.key,
|
|
||||||
version:
|
|
||||||
typeof installationData.templateVersion === "string"
|
|
||||||
? installationData.templateVersion
|
|
||||||
: template.version,
|
|
||||||
name: template.name,
|
|
||||||
}
|
|
||||||
: null,
|
|
||||||
visualTemplate: visualTemplate
|
|
||||||
? {
|
|
||||||
key: visualTemplate.key,
|
|
||||||
version: visualTemplate.version,
|
|
||||||
name: visualTemplate.name,
|
|
||||||
supportedIndustryTemplates: visualTemplate.supportedIndustryTemplates,
|
|
||||||
variants: visualTemplate.variants,
|
|
||||||
}
|
|
||||||
: null,
|
|
||||||
visualTemplateManifest,
|
|
||||||
};
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
private jsonObject(value: unknown): Record<string, unknown> {
|
|
||||||
return value && typeof value === "object" && !Array.isArray(value)
|
|
||||||
? (value as Record<string, unknown>)
|
|
||||||
: {};
|
|
||||||
}
|
|
||||||
private string(value: unknown, fallback = ""): string {
|
|
||||||
return typeof value === "string" ? value : fallback;
|
|
||||||
}
|
|
||||||
private capabilityStatus(value: unknown): "enabled" | "disabled" | "degraded" {
|
|
||||||
return value === "disabled" || value === "degraded" ? value : "enabled";
|
|
||||||
}
|
|
||||||
private jsonArray(value: unknown): Prisma.JsonValue[] {
|
|
||||||
return Array.isArray(value) ? (value as Prisma.JsonValue[]) : [];
|
|
||||||
}
|
|
||||||
private sectionType(value: unknown): RuntimeOffering["sections"][number]["type"] {
|
|
||||||
const known = ["text", "image-list", "timeline", "faq", "specification"] as const;
|
|
||||||
return known.includes(value as (typeof known)[number])
|
|
||||||
? (value as (typeof known)[number])
|
|
||||||
: "text";
|
|
||||||
}
|
|
||||||
private offeringKind(value: string): RuntimeOffering["kind"] {
|
|
||||||
const known: RuntimeOffering["kind"][] = ["service", "product", "package", "subscription"];
|
|
||||||
return known.includes(value as RuntimeOffering["kind"])
|
|
||||||
? (value as RuntimeOffering["kind"])
|
|
||||||
: "service";
|
|
||||||
}
|
|
||||||
private formPurpose(value: string): RuntimeWorkspace["inquiryForms"][number]["purpose"] {
|
|
||||||
return value === "booking" || value === "quote-request" ? value : "inquiry";
|
|
||||||
}
|
|
||||||
private submissionAction(
|
|
||||||
value: string,
|
|
||||||
): RuntimeWorkspace["inquiryForms"][number]["submissionAction"] {
|
|
||||||
return value === "create-booking" || value === "create-quote" ? value : "create-inquiry";
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,162 @@
|
|||||||
|
import type { Prisma } from "@prisma/client";
|
||||||
|
import type { RuntimeInquiryField, RuntimeOffering, RuntimeWorkspace } from "@personal-brand/types";
|
||||||
|
import { projectOfferingDetails } from "@personal-brand/types";
|
||||||
|
|
||||||
|
export function asRecord(value: unknown): Record<string, unknown> {
|
||||||
|
return value && typeof value === "object" && !Array.isArray(value)
|
||||||
|
? (value as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function asArray(value: unknown): unknown[] {
|
||||||
|
return Array.isArray(value) ? value : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function asString(value: unknown, fallback = ""): string {
|
||||||
|
return typeof value === "string" ? value : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function offeringKind(value: string): RuntimeOffering["kind"] {
|
||||||
|
const known: RuntimeOffering["kind"][] = ["service", "product", "package", "subscription"];
|
||||||
|
return known.find((item) => item === value) ?? "service";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sectionType(value: unknown): RuntimeOffering["sections"][number]["type"] {
|
||||||
|
const known = ["text", "image-list", "timeline", "faq", "specification"] as const;
|
||||||
|
return known.includes(value as (typeof known)[number])
|
||||||
|
? (value as (typeof known)[number])
|
||||||
|
: "text";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function capabilityStatus(value: unknown): "enabled" | "disabled" | "degraded" {
|
||||||
|
return value === "disabled" || value === "degraded" ? value : "enabled";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formPurpose(value: string): RuntimeWorkspace["inquiryForms"][number]["purpose"] {
|
||||||
|
return value === "booking" || value === "quote-request" ? value : "inquiry";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function submissionAction(
|
||||||
|
value: string,
|
||||||
|
): RuntimeWorkspace["inquiryForms"][number]["submissionAction"] {
|
||||||
|
return value === "create-booking" || value === "create-quote" ? value : "create-inquiry";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toRuntimeOffering(
|
||||||
|
item: Record<string, unknown>,
|
||||||
|
categoryOptions: Map<string, string>,
|
||||||
|
): RuntimeOffering {
|
||||||
|
const config = asRecord(item.config);
|
||||||
|
const sections = asArray(config.sections).filter((section): section is Record<string, unknown> =>
|
||||||
|
Boolean(section && typeof section === "object"),
|
||||||
|
);
|
||||||
|
const details = projectOfferingDetails(config);
|
||||||
|
const media = asArray(config.media).flatMap((entry) => {
|
||||||
|
const value = asRecord(entry);
|
||||||
|
return typeof value.url === "string"
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
url: value.url,
|
||||||
|
alt: asString(value.alt, asString(item.name, "业务提供项")),
|
||||||
|
type: "image" as const,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [];
|
||||||
|
});
|
||||||
|
const categoryKey = typeof config.categoryKey === "string" ? config.categoryKey : "custom";
|
||||||
|
return {
|
||||||
|
id: asString(item.id),
|
||||||
|
name: asString(item.name),
|
||||||
|
summary: typeof item.summary === "string" ? item.summary : asString(item.description),
|
||||||
|
enabled: item.isEnabled !== false,
|
||||||
|
kind: offeringKind(asString(item.kind, "service")),
|
||||||
|
coverUrl: typeof item.coverUrl === "string" ? item.coverUrl : null,
|
||||||
|
priceText: typeof item.priceText === "string" ? item.priceText : null,
|
||||||
|
priceAmount: typeof item.priceAmount === "number" ? item.priceAmount : null,
|
||||||
|
schemaKey: asString(config.schemaKey, "offering.default"),
|
||||||
|
schemaVersion: asString(config.schemaVersion, "1.0.0"),
|
||||||
|
presentation: {
|
||||||
|
...Object.fromEntries(
|
||||||
|
Object.entries(config).filter(
|
||||||
|
([key]) =>
|
||||||
|
![
|
||||||
|
"schemaKey",
|
||||||
|
"schemaVersion",
|
||||||
|
"details",
|
||||||
|
"sections",
|
||||||
|
"media",
|
||||||
|
"presentation",
|
||||||
|
].includes(key),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
...asRecord(config.presentation),
|
||||||
|
categoryKey,
|
||||||
|
categoryLabel: categoryOptions.get(categoryKey) ?? "",
|
||||||
|
heroImage:
|
||||||
|
typeof config.detailHero === "string"
|
||||||
|
? config.detailHero
|
||||||
|
: typeof item.coverUrl === "string"
|
||||||
|
? item.coverUrl
|
||||||
|
: null,
|
||||||
|
keywords: asArray(config.keywords).filter(
|
||||||
|
(keyword): keyword is string => typeof keyword === "string",
|
||||||
|
),
|
||||||
|
media,
|
||||||
|
details: {
|
||||||
|
background: details.background,
|
||||||
|
designConcept: details.designConcept,
|
||||||
|
crafts: details.crafts,
|
||||||
|
materialsList: details.materialsList,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
sections: sections.map((section) => ({
|
||||||
|
key: asString(section.key, "section"),
|
||||||
|
type: sectionType(section.type),
|
||||||
|
config: asRecord(section.config),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toRuntimeInquiryFields(snapshot: Prisma.JsonValue): RuntimeInquiryField[] {
|
||||||
|
return asArray(snapshot).flatMap((field) => {
|
||||||
|
if (!field || typeof field !== "object") return [];
|
||||||
|
const value = field as Record<string, unknown>;
|
||||||
|
if (typeof value.key !== "string" || typeof value.label !== "string") return [];
|
||||||
|
const sourceType = asString(value.type);
|
||||||
|
const type =
|
||||||
|
sourceType === "phone"
|
||||||
|
? "tel"
|
||||||
|
: sourceType === "multi-select"
|
||||||
|
? "checkbox"
|
||||||
|
: [
|
||||||
|
"text",
|
||||||
|
"tel",
|
||||||
|
"number",
|
||||||
|
"select",
|
||||||
|
"radio",
|
||||||
|
"checkbox",
|
||||||
|
"checkbox",
|
||||||
|
"textarea",
|
||||||
|
"date",
|
||||||
|
].includes(sourceType)
|
||||||
|
? (sourceType as RuntimeInquiryField["type"])
|
||||||
|
: "text";
|
||||||
|
const options = asArray(value.options).flatMap((option) => {
|
||||||
|
if (typeof option === "string") return [{ label: option, value: option }];
|
||||||
|
if (!option || typeof option !== "object") return [];
|
||||||
|
const item = option as Record<string, unknown>;
|
||||||
|
return typeof item.label === "string" && typeof item.value === "string"
|
||||||
|
? [{ label: item.label, value: item.value }]
|
||||||
|
: [];
|
||||||
|
});
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
key: value.key,
|
||||||
|
label: value.label,
|
||||||
|
type,
|
||||||
|
required: value.required === true,
|
||||||
|
...(options.length ? { options } : {}),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
import type { BrandReleaseSnapshot } from "../../brand-release.service.js";
|
||||||
|
import type { Prisma } from "@prisma/client";
|
||||||
|
import {
|
||||||
|
capabilityPlugins,
|
||||||
|
type BrandTemplateKey,
|
||||||
|
getBrandTemplate,
|
||||||
|
getDefaultVisualTemplateKey,
|
||||||
|
getTemplatePackageManifestForVisualKey,
|
||||||
|
getVisualTemplate,
|
||||||
|
getVisualTemplateManifest,
|
||||||
|
resolveCapabilities,
|
||||||
|
} from "@personal-brand/config";
|
||||||
|
import type { RuntimeTrustItem, RuntimeWorkspace } from "@personal-brand/types";
|
||||||
|
import {
|
||||||
|
projectBrandAliases,
|
||||||
|
projectTemplateData,
|
||||||
|
projectTrustItem,
|
||||||
|
projectTrustPresentation,
|
||||||
|
} from "@personal-brand/types";
|
||||||
|
import {
|
||||||
|
asArray,
|
||||||
|
asRecord,
|
||||||
|
asString,
|
||||||
|
capabilityStatus,
|
||||||
|
formPurpose,
|
||||||
|
submissionAction,
|
||||||
|
toRuntimeInquiryFields,
|
||||||
|
toRuntimeOffering,
|
||||||
|
} from "./public-workspace.runtime-mapper.js";
|
||||||
|
|
||||||
|
type ReleaseMetadata = { version: number; createdAt: Date };
|
||||||
|
|
||||||
|
type PublicWorkspaceResponse = Omit<RuntimeWorkspace, "brand"> & {
|
||||||
|
contractVersion: string;
|
||||||
|
brand: Record<string, unknown> | null;
|
||||||
|
template: {
|
||||||
|
key: string;
|
||||||
|
version: string;
|
||||||
|
name: string;
|
||||||
|
} | null;
|
||||||
|
visualTemplate: {
|
||||||
|
key: string;
|
||||||
|
version: string;
|
||||||
|
name: string;
|
||||||
|
supportedIndustryTemplates: BrandTemplateKey[];
|
||||||
|
variants: Record<string, string>;
|
||||||
|
} | null;
|
||||||
|
visualTemplateManifest: BrandReleaseSnapshot["visualTemplateManifest"];
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createUnpublishedWorkspace(): PublicWorkspaceResponse {
|
||||||
|
return {
|
||||||
|
contractVersion: "1.0",
|
||||||
|
schemaVersion: "1.0.0",
|
||||||
|
publication: { status: "unpublished", version: null },
|
||||||
|
brand: null,
|
||||||
|
template: null,
|
||||||
|
visualTemplate: null,
|
||||||
|
visualTemplateManifest: null,
|
||||||
|
offerings: [],
|
||||||
|
inquiryForms: [],
|
||||||
|
trustItems: [],
|
||||||
|
capabilities: [],
|
||||||
|
trustPresentation: {},
|
||||||
|
navigation: { tabs: [] },
|
||||||
|
templateData: {},
|
||||||
|
plugins: [],
|
||||||
|
theme: { colors: {} },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assemblePublicWorkspace(input: {
|
||||||
|
release: ReleaseMetadata | null;
|
||||||
|
snapshot: BrandReleaseSnapshot;
|
||||||
|
draftSnapshot: BrandReleaseSnapshot | null;
|
||||||
|
}): PublicWorkspaceResponse {
|
||||||
|
const { release, snapshot, draftSnapshot } = input;
|
||||||
|
const releaseSnapshot = snapshot;
|
||||||
|
const brandData = asRecord(releaseSnapshot.brand);
|
||||||
|
const offeringsData = asArray(releaseSnapshot.offerings).filter(
|
||||||
|
(item) => asRecord(item).isEnabled === true,
|
||||||
|
) as Array<Record<string, unknown>>;
|
||||||
|
const enabledOfferingIds = new Set(offeringsData.map((item) => item.id));
|
||||||
|
const formsData = asArray(releaseSnapshot.forms).filter((item) => {
|
||||||
|
const form = asRecord(item);
|
||||||
|
return (
|
||||||
|
form.isEnabled === true &&
|
||||||
|
(form.offeringId === null || enabledOfferingIds.has(form.offeringId))
|
||||||
|
);
|
||||||
|
}) as Array<Record<string, unknown>>;
|
||||||
|
const trustData = asArray(releaseSnapshot.trustContents).filter(
|
||||||
|
(item) => asRecord(item).isPublished === true,
|
||||||
|
) as Array<Record<string, unknown>>;
|
||||||
|
const installationData = asRecord(releaseSnapshot.installation);
|
||||||
|
const templateKey =
|
||||||
|
asString(releaseSnapshot.templateKey) ||
|
||||||
|
asString(installationData.templateKey) ||
|
||||||
|
asString(brandData.templateKey) ||
|
||||||
|
"personal";
|
||||||
|
const template = releaseSnapshot.templateDefinition ?? getBrandTemplate(templateKey);
|
||||||
|
const capabilityData = asArray(releaseSnapshot.capabilities) as Array<Record<string, unknown>>;
|
||||||
|
const capabilities = capabilityData.length
|
||||||
|
? capabilityData.map((item) => ({
|
||||||
|
key: asString(item.capabilityKey),
|
||||||
|
version: asString(item.capabilityVersion, "1.0.0"),
|
||||||
|
status: capabilityStatus(item.status),
|
||||||
|
config: asRecord(item.config),
|
||||||
|
}))
|
||||||
|
: template
|
||||||
|
? resolveCapabilities(template.capabilities).map((item) => ({
|
||||||
|
key: item.key,
|
||||||
|
version: item.version,
|
||||||
|
status: "enabled" as const,
|
||||||
|
config: {},
|
||||||
|
}))
|
||||||
|
: [];
|
||||||
|
const brandConfig = asRecord(brandData.config);
|
||||||
|
const visualTemplateKey =
|
||||||
|
asString(brandConfig.visualTemplateKey) || getDefaultVisualTemplateKey(templateKey);
|
||||||
|
const visualTemplate =
|
||||||
|
releaseSnapshot.visualTemplateDefinition ?? getVisualTemplate(visualTemplateKey);
|
||||||
|
const visualTemplateManifest =
|
||||||
|
releaseSnapshot.visualTemplateManifest ?? getVisualTemplateManifest(visualTemplateKey);
|
||||||
|
const templatePackageManifest =
|
||||||
|
releaseSnapshot.templatePackageManifest ??
|
||||||
|
getTemplatePackageManifestForVisualKey(visualTemplateKey);
|
||||||
|
const categoryOptions = new Map(
|
||||||
|
(templatePackageManifest?.admin.sections ?? [])
|
||||||
|
.filter((section) => section.target === "offering")
|
||||||
|
.flatMap((section) => section.fields)
|
||||||
|
.filter((field) => field.binding === "offering.config.categoryKey")
|
||||||
|
.flatMap((field) => field.options ?? [])
|
||||||
|
.map((option) => [option.value, option.label]),
|
||||||
|
);
|
||||||
|
const runtimeBrand = projectBrandAliases(brandData, brandConfig);
|
||||||
|
const templateData = projectTemplateData(
|
||||||
|
brandConfig,
|
||||||
|
(templatePackageManifest?.templateFields ?? []).map((field) => field.key),
|
||||||
|
);
|
||||||
|
const trustDeclarations = templatePackageManifest?.trustContentTypes ?? [];
|
||||||
|
const trustItems: RuntimeTrustItem[] = trustData.flatMap((raw) => {
|
||||||
|
const item = projectTrustItem(asRecord(raw));
|
||||||
|
return item && trustDeclarations.some((declaration) => declaration.type === item.type)
|
||||||
|
? [item]
|
||||||
|
: [];
|
||||||
|
});
|
||||||
|
const runtimeWorkspace: RuntimeWorkspace = {
|
||||||
|
schemaVersion: "1.0.0",
|
||||||
|
publication: {
|
||||||
|
status: draftSnapshot ? "draft" : "published",
|
||||||
|
version: draftSnapshot ? null : (release?.version ?? null),
|
||||||
|
...(!draftSnapshot && release ? { publishedAt: release.createdAt.toISOString() } : {}),
|
||||||
|
},
|
||||||
|
brand: runtimeBrand,
|
||||||
|
templateData,
|
||||||
|
navigation: {
|
||||||
|
tabs:
|
||||||
|
templatePackageManifest?.navigation.map((tab) => ({
|
||||||
|
key: tab.key,
|
||||||
|
label: tab.label,
|
||||||
|
page: templatePackageManifest.entrypoints[tab.page] ?? tab.page,
|
||||||
|
})) ?? [],
|
||||||
|
},
|
||||||
|
offerings: offeringsData.map((item) => toRuntimeOffering(item, categoryOptions)),
|
||||||
|
inquiryForms: formsData.map((raw) => {
|
||||||
|
const form = asRecord(raw);
|
||||||
|
return {
|
||||||
|
key: asString(form.id),
|
||||||
|
version:
|
||||||
|
typeof form.version === "number" ? String(form.version) : asString(form.version, "1"),
|
||||||
|
purpose: formPurpose(asString(form.purpose, "inquiry")),
|
||||||
|
target: form.targetType === "offering" ? "offering" : "brand",
|
||||||
|
...(typeof form.offeringId === "string" ? { targetId: form.offeringId } : {}),
|
||||||
|
submissionAction: submissionAction(asString(form.submissionAction, "create-inquiry")),
|
||||||
|
fields: toRuntimeInquiryFields(form.fieldsSnapshot as Prisma.JsonValue),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
trustItems,
|
||||||
|
trustPresentation: projectTrustPresentation(trustItems, trustDeclarations),
|
||||||
|
capabilities,
|
||||||
|
plugins: capabilities
|
||||||
|
.filter((capability) => capability.status === "enabled")
|
||||||
|
.map((capability) => capabilityPlugins[capability.key as keyof typeof capabilityPlugins])
|
||||||
|
.filter(Boolean)
|
||||||
|
.map((plugin) => ({ ...plugin, status: "enabled" as const, config: {} })),
|
||||||
|
theme: visualTemplate?.theme ?? {
|
||||||
|
colors: { background: "#F7F5F1", foreground: "#252525", accent: "#8A6846" },
|
||||||
|
},
|
||||||
|
...(visualTemplate?.layout ? { layout: visualTemplate.layout } : {}),
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
...runtimeWorkspace,
|
||||||
|
contractVersion: "1.0",
|
||||||
|
brand: runtimeBrand,
|
||||||
|
template: template
|
||||||
|
? {
|
||||||
|
key: template.key,
|
||||||
|
version: asString(installationData.templateVersion, template.version),
|
||||||
|
name: template.name,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
visualTemplate: visualTemplate
|
||||||
|
? {
|
||||||
|
key: visualTemplate.key,
|
||||||
|
version: visualTemplate.version,
|
||||||
|
name: visualTemplate.name,
|
||||||
|
supportedIndustryTemplates: [...visualTemplate.supportedIndustryTemplates],
|
||||||
|
variants: visualTemplate.variants,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
visualTemplateManifest,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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<string, unknown> {
|
||||||
|
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<unknown> {
|
||||||
|
const items = await this.prisma.offering.findMany({
|
||||||
|
where: { brandId },
|
||||||
|
orderBy: { sortOrder: "asc" },
|
||||||
|
});
|
||||||
|
return items.map((item) => {
|
||||||
|
const config = (item.config ?? {}) as Record<string, unknown>;
|
||||||
|
return {
|
||||||
|
...item,
|
||||||
|
sections: config.sections ?? [],
|
||||||
|
media: config.media ?? [],
|
||||||
|
cta: config.cta ?? null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(brandId: string, body: CreateOfferingDto): Promise<unknown> {
|
||||||
|
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<unknown> {
|
||||||
|
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<unknown> {
|
||||||
|
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 };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<unknown> {
|
||||||
|
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<unknown> {
|
||||||
|
return this.publicWorkspace.getForBrandId(brandId, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private jsonObject(value: unknown): Record<string, unknown> {
|
||||||
|
return value && typeof value === "object" && !Array.isArray(value)
|
||||||
|
? (value as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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`。
|
||||||
@@ -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<T>`、`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`。
|
||||||
+1
-1
@@ -19,7 +19,7 @@ export default tseslint.config(
|
|||||||
"apps/miniapp/pages/**/*.js",
|
"apps/miniapp/pages/**/*.js",
|
||||||
"apps/miniapp/app.js",
|
"apps/miniapp/app.js",
|
||||||
"apps/admin/vite.config.ts",
|
"apps/admin/vite.config.ts",
|
||||||
"packages/config/src/generated-template-packages.js",
|
"packages/config/src/generated-template-packages.ts",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
eslint.configs.recommended,
|
eslint.configs.recommended,
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import type { ApiErrorBody } from "../types/common.js";
|
||||||
|
|
||||||
|
export interface FetchResponse {
|
||||||
|
readonly status: number;
|
||||||
|
readonly ok: boolean;
|
||||||
|
json(): Promise<unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type FetchLike = (
|
||||||
|
input: string,
|
||||||
|
init?: { method?: string; headers?: Record<string, string>; body?: string },
|
||||||
|
) => Promise<FetchResponse>;
|
||||||
|
|
||||||
|
export interface ApiClientOptions {
|
||||||
|
baseUrl: string;
|
||||||
|
fetcher: FetchLike;
|
||||||
|
token?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type RequestFn = <T>(
|
||||||
|
path: string,
|
||||||
|
options?: { method?: string; body?: unknown },
|
||||||
|
) => Promise<T>;
|
||||||
|
|
||||||
|
export async function request<T>(
|
||||||
|
state: { baseUrl: string; fetcher: FetchLike; token?: string | undefined },
|
||||||
|
path: string,
|
||||||
|
options: { method?: string; body?: unknown } = {},
|
||||||
|
): Promise<T> {
|
||||||
|
const headers: Record<string, string> = { 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+272
-905
File diff suppressed because it is too large.
Load diff
@@ -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<Booking[]>;
|
||||||
|
createCustomerBooking(input: CreateBookingInput): Promise<BookingSummary>;
|
||||||
|
cancelCustomerBooking(id: string): Promise<Booking>;
|
||||||
|
listAdminBookings(filters?: {
|
||||||
|
status?: BookingStatus;
|
||||||
|
unreadOnly?: boolean;
|
||||||
|
tagId?: string;
|
||||||
|
}): Promise<AdminBooking[]>;
|
||||||
|
getAdminBooking(id: string): Promise<AdminBooking>;
|
||||||
|
getAdminUnreadCount(): Promise<{ count: number }>;
|
||||||
|
updateAdminBookingStatus(id: string, status: BookingStatus, adminNote?: string): Promise<Booking>;
|
||||||
|
markAdminBookingRead(id: string): Promise<Booking>;
|
||||||
|
listAdminTags(): Promise<BookingTag[]>;
|
||||||
|
createAdminTag(name: string): Promise<BookingTag>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 } }),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<BrandProfile>;
|
||||||
|
listAdminBrands(): Promise<AdminBrandMembership[]>;
|
||||||
|
switchAdminBrand(
|
||||||
|
brandId: string,
|
||||||
|
): Promise<{ token: string; brand: AdminBrandMembership["brand"] }>;
|
||||||
|
listAdminMembers(): Promise<AdminBrandMember[]>;
|
||||||
|
createAdminMember(body: {
|
||||||
|
username: string;
|
||||||
|
displayName: string;
|
||||||
|
password: string;
|
||||||
|
role: "owner" | "editor";
|
||||||
|
}): Promise<AdminBrandMember>;
|
||||||
|
updateAdminMember(
|
||||||
|
id: string,
|
||||||
|
body: Partial<Pick<AdminBrandMember, "role" | "isEnabled">>,
|
||||||
|
): Promise<AdminBrandMember>;
|
||||||
|
getAdminVisualTemplatePreview(): Promise<{
|
||||||
|
current: {
|
||||||
|
key: string;
|
||||||
|
version: string;
|
||||||
|
name: string;
|
||||||
|
theme: { colors: Record<string, string> };
|
||||||
|
variants: Record<string, string>;
|
||||||
|
} | null;
|
||||||
|
available: string[];
|
||||||
|
}>;
|
||||||
|
getAdminVisualTemplateHistory(): Promise<{
|
||||||
|
history: Array<{ visualTemplateKey: string; savedAt: string }>;
|
||||||
|
}>;
|
||||||
|
rollbackAdminVisualTemplate(): Promise<{ visualTemplateKey: string; rolledBack: boolean }>;
|
||||||
|
updateAdminBrand(body: BrandUpdate): Promise<BrandProfile>;
|
||||||
|
updateAdminBrandPresentation(body: BrandPresentationUpdate): Promise<{
|
||||||
|
visualPresentation: Record<string, Record<string, string>>;
|
||||||
|
}>;
|
||||||
|
listAdminReleases(): Promise<BrandReleaseSummary[]>;
|
||||||
|
getAdminReleaseReadiness(): Promise<{
|
||||||
|
ready: boolean;
|
||||||
|
checks: Array<{
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
passed: boolean;
|
||||||
|
help?: string;
|
||||||
|
destination?: string;
|
||||||
|
}>;
|
||||||
|
}>;
|
||||||
|
publishAdminRelease(note?: string): Promise<BrandReleaseSummary>;
|
||||||
|
rollbackAdminRelease(version: number, note?: string): Promise<BrandReleaseSummary>;
|
||||||
|
revokeAdminRelease(): Promise<
|
||||||
|
Pick<BrandReleaseSummary, "id" | "version" | "status" | "revokedAt">
|
||||||
|
>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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" }),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<BrandFieldDefinition, "id" | "source">,
|
||||||
|
): Promise<BrandFieldDefinition>;
|
||||||
|
deleteAdminField(id: string): Promise<{ deleted: boolean }>;
|
||||||
|
listAdminInquiryForms(): Promise<InquiryForm[]>;
|
||||||
|
listAdminInquirySubmissions(): Promise<InquirySubmission[]>;
|
||||||
|
updateAdminInquirySubmission(
|
||||||
|
id: string,
|
||||||
|
body: { status: InquirySubmission["status"]; adminNote?: string },
|
||||||
|
): Promise<InquirySubmission>;
|
||||||
|
createAdminInquiryForm(body: {
|
||||||
|
name: string;
|
||||||
|
offeringId?: string;
|
||||||
|
fieldsSnapshot: unknown[];
|
||||||
|
isEnabled?: boolean;
|
||||||
|
purpose?: InquiryForm["purpose"];
|
||||||
|
targetType?: InquiryForm["targetType"];
|
||||||
|
submissionAction?: InquiryForm["submissionAction"];
|
||||||
|
}): Promise<InquiryForm>;
|
||||||
|
updateAdminInquiryForm(
|
||||||
|
id: string,
|
||||||
|
body: Partial<{
|
||||||
|
name: string;
|
||||||
|
offeringId: string;
|
||||||
|
fieldsSnapshot: unknown[];
|
||||||
|
isEnabled: boolean;
|
||||||
|
purpose?: InquiryForm["purpose"];
|
||||||
|
targetType?: InquiryForm["targetType"];
|
||||||
|
submissionAction?: InquiryForm["submissionAction"];
|
||||||
|
}>,
|
||||||
|
): Promise<InquiryForm>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import type { RequestFn } from "../client/request.js";
|
||||||
|
import type { PresignedUpload, UploadConfig } from "../types/media.js";
|
||||||
|
|
||||||
|
export interface MediaMethods {
|
||||||
|
getUploadConfig(): Promise<UploadConfig>;
|
||||||
|
createPresignedUpload(body: {
|
||||||
|
fileName: string;
|
||||||
|
contentType: string;
|
||||||
|
scope?: "brand" | "offering" | "trust";
|
||||||
|
}): Promise<PresignedUpload>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mediaMethods({ request }: { request: RequestFn }): MediaMethods {
|
||||||
|
return {
|
||||||
|
getUploadConfig: () => request("/admin/uploads/config"),
|
||||||
|
createPresignedUpload: (body) => request("/admin/uploads/presign", { method: "POST", body }),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<Offering>;
|
||||||
|
listPublicOfferings(): Promise<Offering[]>;
|
||||||
|
listAdminOfferings(): Promise<Offering[]>;
|
||||||
|
createAdminOffering(body: Omit<Offering, "id" | "brandId">): Promise<Offering>;
|
||||||
|
updateAdminOffering(
|
||||||
|
id: string,
|
||||||
|
body: Partial<Omit<Offering, "id" | "brandId">>,
|
||||||
|
): Promise<Offering>;
|
||||||
|
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",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<BrandProfile>;
|
||||||
|
listOfferings(): Promise<PublicOffering[]>;
|
||||||
|
getPublicWorkspace(): Promise<PublicWorkspace>;
|
||||||
|
getPublicInquiryForm(id: string): Promise<InquiryForm>;
|
||||||
|
createCustomerInquirySubmission(
|
||||||
|
formId: string,
|
||||||
|
values: Record<string, unknown>,
|
||||||
|
): Promise<InquirySubmission>;
|
||||||
|
listCustomerInquirySubmissions(): Promise<InquirySubmission[]>;
|
||||||
|
getCustomerInquirySubmission(id: string): Promise<InquirySubmission>;
|
||||||
|
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 } }),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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 },
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<BrandTemplateDefinition>;
|
||||||
|
listPublicTemplates(): Promise<{
|
||||||
|
industries: BrandTemplateDefinition[];
|
||||||
|
visuals: Array<{
|
||||||
|
key: string;
|
||||||
|
version: string;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
supportedIndustryTemplates: BrandTemplateKey[];
|
||||||
|
variants: Record<string, string>;
|
||||||
|
theme: { colors: Record<string, string> };
|
||||||
|
}>;
|
||||||
|
}>;
|
||||||
|
previewPublicTemplateCombination(
|
||||||
|
industry: string,
|
||||||
|
visual: string,
|
||||||
|
): Promise<{
|
||||||
|
industry: BrandTemplateDefinition;
|
||||||
|
visual: {
|
||||||
|
key: string;
|
||||||
|
version: string;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
supportedIndustryTemplates: BrandTemplateKey[];
|
||||||
|
variants: Record<string, string>;
|
||||||
|
theme: { colors: Record<string, string> };
|
||||||
|
};
|
||||||
|
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<string, string>;
|
||||||
|
} | null;
|
||||||
|
installations: Array<{ id: string; templateKey: BrandTemplateKey; templateVersion: string }>;
|
||||||
|
fields: BrandFieldDefinition[];
|
||||||
|
offerings: Offering[];
|
||||||
|
forms: unknown[];
|
||||||
|
templateContent: AdminTemplateContent | null;
|
||||||
|
}>;
|
||||||
|
getAdminPreviewWorkspace(): Promise<RuntimeWorkspace>;
|
||||||
|
installAdminTemplate(templateKey: "personal" | "food" | "doors"): Promise<unknown>;
|
||||||
|
listAdminCapabilities(): Promise<CapabilityInstallation[]>;
|
||||||
|
updateAdminCapability(
|
||||||
|
key: string,
|
||||||
|
body: {
|
||||||
|
capabilityVersion: string;
|
||||||
|
status: CapabilityInstallation["status"];
|
||||||
|
config?: Record<string, unknown>;
|
||||||
|
},
|
||||||
|
): Promise<CapabilityInstallation>;
|
||||||
|
previewAdminSampleContent(): Promise<{
|
||||||
|
templateKey: string;
|
||||||
|
alreadyImported: boolean;
|
||||||
|
counts: Record<string, number>;
|
||||||
|
willCreateInquiryForm: boolean;
|
||||||
|
}>;
|
||||||
|
importAdminSampleContent(): Promise<{ imported: boolean; counts: Record<string, number> }>;
|
||||||
|
getAdminTemplateUpgradePreview(): Promise<{
|
||||||
|
currentVersion: string;
|
||||||
|
latestVersion: string;
|
||||||
|
canUpgrade: boolean;
|
||||||
|
canRollback: boolean;
|
||||||
|
missingModules: unknown[];
|
||||||
|
missingFields: unknown[];
|
||||||
|
}>;
|
||||||
|
upgradeAdminTemplate(): Promise<unknown>;
|
||||||
|
rollbackAdminTemplate(): Promise<unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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<string, string>)
|
||||||
|
: {},
|
||||||
|
theme:
|
||||||
|
visual.theme && typeof visual.theme === "object"
|
||||||
|
? (visual.theme as { colors: Record<string, string> })
|
||||||
|
: { 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" }),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import type { RequestFn } from "../client/request.js";
|
||||||
|
import type { TrustContent, TrustContentInput } from "../types/trust.js";
|
||||||
|
|
||||||
|
export interface TrustMethods {
|
||||||
|
listAdminTrustContent(): Promise<TrustContent[]>;
|
||||||
|
createAdminTrustContent(body: TrustContentInput): Promise<TrustContent>;
|
||||||
|
updateAdminTrustContent(id: string, body: Partial<TrustContentInput>): Promise<TrustContent>;
|
||||||
|
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",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<string, unknown>;
|
||||||
|
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 }>;
|
||||||
|
}
|
||||||
@@ -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<string, unknown> | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminBrandMembership {
|
||||||
|
id: string;
|
||||||
|
role: string;
|
||||||
|
brand: Pick<BrandProfile, "id" | "name" | "templateKey"> & { slug?: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminBrandMember {
|
||||||
|
id: string;
|
||||||
|
role: string;
|
||||||
|
isEnabled: boolean;
|
||||||
|
adminUser: {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
displayName: string;
|
||||||
|
isEnabled: boolean;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BrandUpdate = Partial<Omit<BrandProfile, "id">>;
|
||||||
|
|
||||||
|
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<string, string>
|
||||||
|
>
|
||||||
|
>;
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
export interface CapabilityInstallation {
|
||||||
|
id: string | null;
|
||||||
|
capabilityKey: string;
|
||||||
|
capabilityVersion: string;
|
||||||
|
status: "enabled" | "disabled" | "degraded";
|
||||||
|
config?: Record<string, unknown> | null;
|
||||||
|
updatedAt: string | null;
|
||||||
|
source?: "template" | "brand";
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
export interface ApiErrorBody {
|
||||||
|
data: null;
|
||||||
|
error: { code: string; message: string };
|
||||||
|
requestId: string | null;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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<string, unknown>;
|
||||||
|
activeFields: Record<string, boolean>;
|
||||||
|
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;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
export interface UploadConfig {
|
||||||
|
configured: boolean;
|
||||||
|
status: "ok" | "unavailable" | "unconfigured";
|
||||||
|
bucket?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PresignedUpload {
|
||||||
|
uploadUrl: string;
|
||||||
|
key: string;
|
||||||
|
publicUrl: string;
|
||||||
|
}
|
||||||
@@ -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<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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<string, unknown> | null;
|
||||||
|
sections?: OfferingSection[];
|
||||||
|
media?: OfferingMedia[];
|
||||||
|
cta?: OfferingCta;
|
||||||
|
inquiryForms?: Array<Pick<InquiryForm, "id" | "name" | "purpose" | "targetType" | "version">>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OfferingUpdate {
|
||||||
|
name?: string;
|
||||||
|
description?: string;
|
||||||
|
coverUrl?: string;
|
||||||
|
priceText?: string;
|
||||||
|
priceAmount?: number;
|
||||||
|
sortOrder?: number;
|
||||||
|
bookingEnabled?: boolean;
|
||||||
|
isEnabled?: boolean;
|
||||||
|
categoryKey?: string;
|
||||||
|
config?: Record<string, unknown>;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
@@ -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<string, unknown> | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TrustContentInput {
|
||||||
|
type: string;
|
||||||
|
title: string;
|
||||||
|
summary?: string;
|
||||||
|
content: string;
|
||||||
|
coverUrl?: string;
|
||||||
|
sortOrder?: number;
|
||||||
|
isPublished?: boolean;
|
||||||
|
config?: Record<string, unknown>;
|
||||||
|
}
|
||||||
@@ -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<string, unknown>) | null;
|
||||||
|
template: { key: BrandTemplateKey; version: string; name: string } | null;
|
||||||
|
visualTemplate: {
|
||||||
|
key: string;
|
||||||
|
version: string;
|
||||||
|
name: string;
|
||||||
|
supportedIndustryTemplates: BrandTemplateKey[];
|
||||||
|
variants: Record<string, string>;
|
||||||
|
} | null;
|
||||||
|
visualTemplateManifest?: {
|
||||||
|
schemaVersion: "1.0";
|
||||||
|
key: string;
|
||||||
|
version: string;
|
||||||
|
name: string;
|
||||||
|
brandFirst: true;
|
||||||
|
tokens: {
|
||||||
|
colors: Record<string, string>;
|
||||||
|
spacing: Record<string, string>;
|
||||||
|
typography: Record<string, string>;
|
||||||
|
radius: Record<string, string>;
|
||||||
|
shadows?: Record<string, string>;
|
||||||
|
};
|
||||||
|
pages: Array<{
|
||||||
|
key: string;
|
||||||
|
title: string;
|
||||||
|
modules: Array<{
|
||||||
|
key: string;
|
||||||
|
type: string;
|
||||||
|
variant: string;
|
||||||
|
required: boolean;
|
||||||
|
dataSlots?: string[];
|
||||||
|
assetSlots?: string[];
|
||||||
|
capability?: string;
|
||||||
|
}>;
|
||||||
|
}>;
|
||||||
|
assets: Array<Record<string, unknown>>;
|
||||||
|
dataSlots: Array<Record<string, unknown>>;
|
||||||
|
capabilities: string[];
|
||||||
|
};
|
||||||
|
capabilities: RuntimeCapability[];
|
||||||
|
offerings: RuntimeOffering[];
|
||||||
|
inquiryForms: RuntimeInquiryForm[];
|
||||||
|
trustItems: RuntimeTrustItem[];
|
||||||
|
navigation: { tabs: Array<{ key: string; label: string; page: string }> };
|
||||||
|
trustPresentation: Record<string, unknown>;
|
||||||
|
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;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
@@ -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} 必须保留导出`);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -4,11 +4,12 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": {
|
".": {
|
||||||
"types": "./src/index.ts",
|
"types": "./dist/index.d.ts",
|
||||||
"import": "./src/index.ts"
|
"import": "./dist/index.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
"build": "tsc -p tsconfig.json",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||||
"clean": "rimraf dist"
|
"clean": "rimraf dist"
|
||||||
|
|||||||
@@ -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<string, string>;
|
||||||
|
theme: { colors: Record<string, string>; radius: Record<string, string> };
|
||||||
|
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<string, string>;
|
||||||
|
spacing: Record<string, string>;
|
||||||
|
typography: Record<string, string>;
|
||||||
|
radius: Record<string, string>;
|
||||||
|
shadows?: Record<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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<string, unknown>;
|
||||||
|
forms: Record<string, unknown>[];
|
||||||
|
capabilityConfig: Record<string, unknown>;
|
||||||
|
fixtures: {
|
||||||
|
runtime: Record<string, unknown>;
|
||||||
|
visual: Record<string, unknown>;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<BrandTemplateKey, BrandTemplateDefinition>;
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import type { CapabilityKey } from "./template-keys.js";
|
||||||
|
|
||||||
|
export interface WorkflowDefinition {
|
||||||
|
key: string;
|
||||||
|
version: string;
|
||||||
|
initialState: string;
|
||||||
|
transitions: Record<string, readonly string[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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<string, WorkflowDefinition>;
|
||||||
|
|
||||||
|
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<CapabilityKey, CapabilityDefinition>;
|
||||||
|
|
||||||
|
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;
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
import type { TemplatePackageManifest } from "./index.js";
|
|
||||||
export declare const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[];
|
|
||||||
export declare const generatedTemplatePackageRegistryHash: string;
|
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+11
-945
@@ -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";
|
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<string, readonly string[]>;
|
|
||||||
}
|
|
||||||
|
|
||||||
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<string, WorkflowDefinition>;
|
|
||||||
|
|
||||||
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<CapabilityKey, CapabilityDefinition>;
|
|
||||||
|
|
||||||
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<string, string>;
|
|
||||||
theme: { colors: Record<string, string>; radius: Record<string, string> };
|
|
||||||
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<string, string>;
|
|
||||||
spacing: Record<string, string>;
|
|
||||||
typography: Record<string, string>;
|
|
||||||
radius: Record<string, string>;
|
|
||||||
shadows?: Record<string, string>;
|
|
||||||
}
|
|
||||||
|
|
||||||
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<string, unknown>;
|
|
||||||
forms: Record<string, unknown>[];
|
|
||||||
capabilityConfig: Record<string, unknown>;
|
|
||||||
fixtures: {
|
|
||||||
runtime: Record<string, unknown>;
|
|
||||||
visual: Record<string, unknown>;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TemplatePackageManifest {
|
|
||||||
packageKey: string;
|
|
||||||
version: string;
|
|
||||||
displayName: string;
|
|
||||||
visualTemplateKey: VisualTemplateKey;
|
|
||||||
runtimeContract: "1.0";
|
|
||||||
supportedIndustryTemplates: readonly BrandTemplateKey[];
|
|
||||||
entrypoints: Readonly<Record<string, string>>;
|
|
||||||
requiredCapabilities: readonly CapabilityKey[];
|
|
||||||
defaultBrandSlug: string;
|
|
||||||
navigation: readonly {
|
|
||||||
key: string;
|
|
||||||
label: string;
|
|
||||||
page: string;
|
|
||||||
iconPath?: string;
|
|
||||||
selectedIconPath?: string;
|
|
||||||
}[];
|
|
||||||
renderers: Readonly<Record<string, string>>;
|
|
||||||
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<Record<BrandTemplateKey, TemplateSampleContent>>;
|
|
||||||
}
|
|
||||||
|
|
||||||
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<string, unknown>;
|
|
||||||
}>;
|
|
||||||
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<BrandTemplateKey, TemplateSampleContent> = {
|
|
||||||
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<VisualTemplateKey, VisualTemplateManifest> = {
|
|
||||||
"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<VisualTemplateKey, VisualTemplateDefinition> = {
|
|
||||||
"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<BrandTemplateKey, BrandTemplateDefinition>;
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
@@ -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";
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
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<Record<string, string>>;
|
||||||
|
requiredCapabilities: readonly CapabilityKey[];
|
||||||
|
defaultBrandSlug: string;
|
||||||
|
navigation: readonly {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
page: string;
|
||||||
|
iconPath?: string;
|
||||||
|
selectedIconPath?: string;
|
||||||
|
}[];
|
||||||
|
renderers?: Readonly<Record<string, string>>;
|
||||||
|
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;
|
||||||
|
previewTarget?: string;
|
||||||
|
placeholder?: string;
|
||||||
|
options?: readonly { value: string; label: string }[];
|
||||||
|
}[];
|
||||||
|
assetSlots: readonly {
|
||||||
|
key: string;
|
||||||
|
binding: string;
|
||||||
|
target: "brand" | "offering" | "trust";
|
||||||
|
label: string;
|
||||||
|
help: string;
|
||||||
|
required: boolean;
|
||||||
|
kind?: string;
|
||||||
|
aspectRatio?: string;
|
||||||
|
}[];
|
||||||
|
inquiryFormFields?: readonly {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
type: string;
|
||||||
|
required: boolean;
|
||||||
|
placeholder?: string;
|
||||||
|
options?: readonly { label: string; value: string }[];
|
||||||
|
}[];
|
||||||
|
pages: readonly string[];
|
||||||
|
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 }[];
|
||||||
|
kind?: string;
|
||||||
|
itemValueKey?: string;
|
||||||
|
maxLength?: number;
|
||||||
|
placeholder?: string;
|
||||||
|
previewTarget?: string;
|
||||||
|
options?: readonly { value: string; label: string }[];
|
||||||
|
}[];
|
||||||
|
}[];
|
||||||
|
};
|
||||||
|
trustContentTypes?: readonly {
|
||||||
|
type: string;
|
||||||
|
label: string;
|
||||||
|
adminFields: {
|
||||||
|
title: string;
|
||||||
|
summary: string;
|
||||||
|
content: string;
|
||||||
|
summaryHelp?: string;
|
||||||
|
summaryPlaceholder?: string;
|
||||||
|
};
|
||||||
|
help?: string;
|
||||||
|
placeholder?: string;
|
||||||
|
previewTargets?: readonly {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
page?: string;
|
||||||
|
}[];
|
||||||
|
required?: boolean;
|
||||||
|
maxPublishedItems?: number;
|
||||||
|
hideStandardFields?: readonly ("summary" | "content")[];
|
||||||
|
pages?: readonly string[];
|
||||||
|
configFields?: readonly {
|
||||||
|
key: string;
|
||||||
|
binding: string;
|
||||||
|
label: string;
|
||||||
|
input: string;
|
||||||
|
itemFields?: readonly { key: string; label: string; input?: string; required?: boolean }[];
|
||||||
|
itemValueKey?: string;
|
||||||
|
placeholder?: string;
|
||||||
|
previewTarget?: string;
|
||||||
|
required?: boolean;
|
||||||
|
}[];
|
||||||
|
}[];
|
||||||
|
overrides?: readonly string[];
|
||||||
|
sampleContent?: Partial<Record<BrandTemplateKey, TemplateSampleContent>>;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
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<string, unknown>;
|
||||||
|
}>;
|
||||||
|
fields: Array<{
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
type: string;
|
||||||
|
required: boolean;
|
||||||
|
options?: Array<{ label: string; value: string }>;
|
||||||
|
placeholder?: 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<BrandTemplateKey, TemplateSampleContent> = {
|
||||||
|
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];
|
||||||
|
}
|
||||||
@@ -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<VisualTemplateKey, VisualTemplateManifest> = {
|
||||||
|
"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,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<VisualTemplateKey, VisualTemplateDefinition> = {
|
||||||
|
"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"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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]);
|
||||||
|
}
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
{
|
{
|
||||||
"extends": "../../tsconfig.base.json",
|
"extends": "../../tsconfig.base.json",
|
||||||
"compilerOptions": { "noEmit": true },
|
"compilerOptions": {
|
||||||
|
"outDir": "dist",
|
||||||
|
"rootDir": "src"
|
||||||
|
},
|
||||||
"include": ["src/**/*.ts"]
|
"include": ["src/**/*.ts"]
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,10 @@ import test from "node:test";
|
|||||||
const packagesRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
|
const packagesRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
|
||||||
const runtimeRoot = path.resolve(packagesRoot, "../apps/miniapp");
|
const runtimeRoot = path.resolve(packagesRoot, "../apps/miniapp");
|
||||||
const adminTrustEditor = fs.readFileSync(
|
const adminTrustEditor = fs.readFileSync(
|
||||||
path.resolve(packagesRoot, "../apps/admin/src/features/trust-content/TrustContentPage.tsx"),
|
path.resolve(
|
||||||
|
packagesRoot,
|
||||||
|
"../apps/admin/src/features/trust-content/components/TrustContentEditorModal.tsx",
|
||||||
|
),
|
||||||
"utf8",
|
"utf8",
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -191,7 +191,7 @@ test("shared brand facts have one editor and template-specific offering detail b
|
|||||||
);
|
);
|
||||||
assert.match(runtimeRenderer, /item\.details\.background\s*\|\|\s*item\.desc/);
|
assert.match(runtimeRenderer, /item\.details\.background\s*\|\|\s*item\.desc/);
|
||||||
const runtimeProjection = fs.readFileSync(
|
const runtimeProjection = fs.readFileSync(
|
||||||
path.resolve(packageRoot, "../apps/api/src/modules/public/public-workspace.controller.ts"),
|
path.resolve(packageRoot, "../apps/api/src/modules/public/public-workspace.runtime-mapper.ts"),
|
||||||
"utf8",
|
"utf8",
|
||||||
);
|
);
|
||||||
assert.match(runtimeProjection, /projectOfferingDetails\(config\)/);
|
assert.match(runtimeProjection, /projectOfferingDetails\(config\)/);
|
||||||
|
|||||||
@@ -4,8 +4,7 @@ const crypto = require("node:crypto");
|
|||||||
|
|
||||||
const root = path.resolve(__dirname, "..");
|
const root = path.resolve(__dirname, "..");
|
||||||
const packageRoot = path.join(root, "packages");
|
const packageRoot = path.join(root, "packages");
|
||||||
const outputPath = path.join(root, "packages/config/src/generated-template-packages.js");
|
const outputPath = path.join(root, "packages/config/src/generated-template-packages.ts");
|
||||||
const declarationPath = path.join(root, "packages/config/src/generated-template-packages.d.ts");
|
|
||||||
const templates = fs
|
const templates = fs
|
||||||
.readdirSync(packageRoot, { withFileTypes: true })
|
.readdirSync(packageRoot, { withFileTypes: true })
|
||||||
.filter(
|
.filter(
|
||||||
@@ -35,12 +34,10 @@ const fingerprint = crypto
|
|||||||
.createHash("sha256")
|
.createHash("sha256")
|
||||||
.update(JSON.stringify(canonical(templates)))
|
.update(JSON.stringify(canonical(templates)))
|
||||||
.digest("hex");
|
.digest("hex");
|
||||||
const content = `// prettier-ignore\nexport const generatedTemplatePackageRegistry = ${JSON.stringify(templates, null, 2)};\nexport const generatedTemplatePackageRegistryHash =\n "${fingerprint}";\n`;
|
const content = `// prettier-ignore\nimport type { TemplatePackageManifest } from "./index.js";\n\nexport const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[] = ${JSON.stringify(templates, null, 2)};\nexport const generatedTemplatePackageRegistryHash =\n "${fingerprint}";\n`;
|
||||||
const declaration = `import type { TemplatePackageManifest } from "./index.js";\nexport declare const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[];\nexport declare const generatedTemplatePackageRegistryHash: string;\n`;
|
|
||||||
const write = process.argv.includes("--write");
|
const write = process.argv.includes("--write");
|
||||||
if (write) {
|
if (write) {
|
||||||
fs.writeFileSync(outputPath, content);
|
fs.writeFileSync(outputPath, content);
|
||||||
fs.writeFileSync(declarationPath, declaration);
|
|
||||||
} else {
|
} else {
|
||||||
const current = fs.existsSync(outputPath) ? fs.readFileSync(outputPath, "utf8") : "";
|
const current = fs.existsSync(outputPath) ? fs.readFileSync(outputPath, "utf8") : "";
|
||||||
const generatedHash = current.match(
|
const generatedHash = current.match(
|
||||||
|
|||||||
Reference in new issue
Block a user