refactor: 拆分业务、信任内容与公共工作台模块
This commit is contained in:
1 parent
357f271639
commit
466dc66907
33 files changed
+4950
-4500
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(
|
source,
|
||||||
section.fields.map((field) => [
|
record,
|
||||||
presentationFieldName(section.key, field.key),
|
section,
|
||||||
readPresentationValue(
|
...(onDraft ? { onDraft } : {}),
|
||||||
record.config,
|
...(onSaved ? { onSaved } : {}),
|
||||||
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,
|
|
||||||
[section],
|
|
||||||
values,
|
|
||||||
);
|
|
||||||
const changed = Object.fromEntries(
|
|
||||||
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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>
|
loading={offerings.isLoading}
|
||||||
{detailSections.length ? (
|
saveError={mutations.saveOffering.error}
|
||||||
<Typography.Paragraph type="secondary">
|
toggleOffering={mutations.toggleOffering}
|
||||||
编辑单项详情时,附加字段将用于:
|
deleteOffering={mutations.deleteOffering}
|
||||||
{detailSections.map((section) => section.title).join("、")}
|
onEdit={(item: Offering) => editor.beginOffering(item)}
|
||||||
。列表中的名称、说明、价格和封面也会显示在业务展示页。
|
/>
|
||||||
</Typography.Paragraph>
|
<OfferingEditorModal
|
||||||
) : null}
|
open={editor.offeringOpen}
|
||||||
<Table
|
editingOffering={editor.editingOffering}
|
||||||
scroll={{ x: 760 }}
|
form={editor.offeringForm}
|
||||||
rowKey="id"
|
previewPage={editor.previewPage}
|
||||||
loading={offerings.isLoading}
|
previewWorkspace={previewWorkspaceDraft}
|
||||||
dataSource={offerings.data ?? []}
|
previewTargets={previewTargets}
|
||||||
columns={[
|
activeTemplateFields={activeTemplateFields}
|
||||||
{ title: "名称", dataIndex: "name" },
|
templateFieldSection={editor.templateFieldSection}
|
||||||
{
|
hasTemplateDetailCopy={hasTemplateDetailCopy(templateFields)}
|
||||||
title: "业务类型",
|
listTarget={listTarget}
|
||||||
dataIndex: "kind",
|
detailTarget={detailTarget}
|
||||||
render: (value) => (
|
saving={mutations.saveOffering.isPending}
|
||||||
<Tag>
|
onClose={editor.closeOffering}
|
||||||
{(
|
onPreviewPageChange={(page: PreviewPage) => editor.setPreviewPage(page)}
|
||||||
{
|
onValuesChange={(values) => editor.handleValuesChange(null, values)}
|
||||||
service: "服务",
|
onFinish={(values) => mutations.saveOffering.mutate(values)}
|
||||||
product: "定制产品",
|
onEditInBrand={navigateToBrand}
|
||||||
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 && (
|
|
||||||
<Typography.Paragraph type="secondary">
|
|
||||||
还没有公开业务提供项。创建后,小程序服务页会优先读取这些内容。
|
|
||||||
</Typography.Paragraph>
|
|
||||||
)}
|
|
||||||
<MutationError error={saveOffering.error} />
|
|
||||||
<MutationError error={toggleOffering.error} />
|
|
||||||
<MutationError error={deleteOffering.error} />
|
|
||||||
</section>
|
|
||||||
<Modal
|
|
||||||
open={offeringOpen}
|
|
||||||
title={editingOffering ? "编辑业务提供项" : "新增业务提供项"}
|
|
||||||
width={960}
|
|
||||||
onCancel={() => {
|
|
||||||
setOfferingOpen(false);
|
|
||||||
setEditingOffering(null);
|
|
||||||
offeringForm.resetFields();
|
|
||||||
}}
|
|
||||||
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",
|
<TrustContentEditorModal
|
||||||
render: (value) => (
|
availableTypes={availableTypes}
|
||||||
<Tag>{availableTypes.find((item) => item.type === value)?.label ?? value}</Tag>
|
editing={editing}
|
||||||
),
|
form={editorForm}
|
||||||
},
|
|
||||||
{ 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} />
|
|
||||||
</section>
|
|
||||||
<Modal
|
|
||||||
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,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,
|
||||||
|
};
|
||||||
|
}
|
||||||
+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,
|
||||||
|
|||||||
@@ -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"
|
||||||
|
|||||||
@@ -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
@@ -20,8 +20,8 @@ export interface TemplatePackageManifest {
|
|||||||
iconPath?: string;
|
iconPath?: string;
|
||||||
selectedIconPath?: string;
|
selectedIconPath?: string;
|
||||||
}[];
|
}[];
|
||||||
renderers: Readonly<Record<string, string>>;
|
renderers?: Readonly<Record<string, string>>;
|
||||||
runtimeOwnedPages: readonly string[];
|
runtimeOwnedPages?: readonly string[];
|
||||||
dataSlots: readonly {
|
dataSlots: readonly {
|
||||||
key: string;
|
key: string;
|
||||||
source: string;
|
source: string;
|
||||||
@@ -39,6 +39,7 @@ export interface TemplatePackageManifest {
|
|||||||
itemValueKey?: string;
|
itemValueKey?: string;
|
||||||
required?: boolean;
|
required?: boolean;
|
||||||
maxLength?: number;
|
maxLength?: number;
|
||||||
|
previewTarget?: string;
|
||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
options?: readonly { value: string; label: string }[];
|
options?: readonly { value: string; label: string }[];
|
||||||
}[];
|
}[];
|
||||||
@@ -49,7 +50,18 @@ export interface TemplatePackageManifest {
|
|||||||
label: string;
|
label: string;
|
||||||
help: string;
|
help: string;
|
||||||
required: boolean;
|
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: {
|
admin: {
|
||||||
sections: readonly {
|
sections: readonly {
|
||||||
key: string;
|
key: string;
|
||||||
@@ -71,11 +83,12 @@ export interface TemplatePackageManifest {
|
|||||||
help?: string;
|
help?: string;
|
||||||
required?: boolean;
|
required?: boolean;
|
||||||
itemFields?: readonly { key: string; label: string; input?: string; required?: boolean }[];
|
itemFields?: readonly { key: string; label: string; input?: string; required?: boolean }[];
|
||||||
|
kind?: string;
|
||||||
itemValueKey?: string;
|
itemValueKey?: string;
|
||||||
maxLength?: number;
|
maxLength?: number;
|
||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
options?: readonly { value: string; label: string }[];
|
|
||||||
previewTarget?: string;
|
previewTarget?: string;
|
||||||
|
options?: readonly { value: string; label: string }[];
|
||||||
}[];
|
}[];
|
||||||
}[];
|
}[];
|
||||||
};
|
};
|
||||||
@@ -91,9 +104,15 @@ export interface TemplatePackageManifest {
|
|||||||
};
|
};
|
||||||
help?: string;
|
help?: string;
|
||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
|
previewTargets?: readonly {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
page?: string;
|
||||||
|
}[];
|
||||||
required?: boolean;
|
required?: boolean;
|
||||||
maxPublishedItems?: number;
|
maxPublishedItems?: number;
|
||||||
hideStandardFields?: readonly ("summary" | "content")[];
|
hideStandardFields?: readonly ("summary" | "content")[];
|
||||||
|
pages?: readonly string[];
|
||||||
configFields?: readonly {
|
configFields?: readonly {
|
||||||
key: string;
|
key: string;
|
||||||
binding: string;
|
binding: string;
|
||||||
@@ -101,8 +120,11 @@ export interface TemplatePackageManifest {
|
|||||||
input: string;
|
input: string;
|
||||||
itemFields?: readonly { key: string; label: string; input?: string; required?: boolean }[];
|
itemFields?: readonly { key: string; label: string; input?: string; required?: boolean }[];
|
||||||
itemValueKey?: string;
|
itemValueKey?: string;
|
||||||
|
placeholder?: string;
|
||||||
|
previewTarget?: string;
|
||||||
required?: boolean;
|
required?: boolean;
|
||||||
}[];
|
}[];
|
||||||
}[];
|
}[];
|
||||||
|
overrides?: readonly string[];
|
||||||
sampleContent?: Partial<Record<BrandTemplateKey, TemplateSampleContent>>;
|
sampleContent?: Partial<Record<BrandTemplateKey, TemplateSampleContent>>;
|
||||||
}
|
}
|
||||||
@@ -23,6 +23,7 @@ export interface TemplateSampleContent {
|
|||||||
type: string;
|
type: string;
|
||||||
required: boolean;
|
required: boolean;
|
||||||
options?: Array<{ label: string; value: string }>;
|
options?: Array<{ label: string; value: string }>;
|
||||||
|
placeholder?: string;
|
||||||
}>;
|
}>;
|
||||||
capabilityKey: string;
|
capabilityKey: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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