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 { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Alert, Button, Col, Form, Row, Space, Typography } from "antd";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import type { Offering, TemplateAdminSection, TrustContent } from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../lib/api.js";
|
||||
import type { TemplateAdminSection } from "@personal-brand/api-client";
|
||||
import { TemplateListField } from "./TemplateListField.js";
|
||||
import { TemplateFieldRenderer } from "./TemplateFieldRenderer.js";
|
||||
import { MutationError } from "./QueryState.js";
|
||||
import {
|
||||
applyPresentationValues,
|
||||
applyStandardEntityValues,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
type PresentationValues,
|
||||
} from "../features/brand/presentation-bindings.js";
|
||||
import { presentationFieldName } from "../features/brand/presentation-bindings.js";
|
||||
import { useRecordContentEditorState } from "./record-content/useRecordContentEditorState.js";
|
||||
import type { RecordContentEditorProps, RecordContentSource } from "./record-content/types.js";
|
||||
|
||||
export type RecordContentSource = "offering" | "trust";
|
||||
|
||||
export interface RecordContentEditorProps {
|
||||
source: RecordContentSource;
|
||||
record: Offering | TrustContent;
|
||||
section: TemplateAdminSection;
|
||||
context: "visual" | "services";
|
||||
onDraft?: (values: PresentationValues) => void;
|
||||
onSaved?: () => void;
|
||||
visualSelection?: { targetKey: string; page: string };
|
||||
}
|
||||
export type { RecordContentEditorProps, RecordContentSource };
|
||||
|
||||
export function RecordContentFields({
|
||||
section,
|
||||
@@ -72,95 +55,22 @@ export function RecordContentEditor({
|
||||
visualSelection,
|
||||
}: RecordContentEditorProps) {
|
||||
const navigate = useNavigate();
|
||||
const [form] = Form.useForm<PresentationValues>();
|
||||
const queryClient = useQueryClient();
|
||||
const recordName = "name" in record ? record.name : record.title;
|
||||
const [draftValues, setDraftValues] = useState<PresentationValues>(() =>
|
||||
Object.fromEntries(
|
||||
section.fields.map((field) => [
|
||||
presentationFieldName(section.key, field.key),
|
||||
readPresentationValue(
|
||||
record.config,
|
||||
field.binding,
|
||||
field,
|
||||
record as unknown as Record<string, unknown>,
|
||||
),
|
||||
]),
|
||||
),
|
||||
);
|
||||
const initialValues = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
section.fields.map((field) => [
|
||||
presentationFieldName(section.key, field.key),
|
||||
readPresentationValue(
|
||||
record.config,
|
||||
field.binding,
|
||||
field,
|
||||
record as unknown as Record<string, unknown>,
|
||||
),
|
||||
]),
|
||||
),
|
||||
[record, section],
|
||||
);
|
||||
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
|
||||
const save = useMutation({
|
||||
mutationFn: async (values: PresentationValues): Promise<void> => {
|
||||
const config = applyPresentationValues(record.config, [section], values);
|
||||
const standard = applyStandardEntityValues(
|
||||
record as unknown as Record<string, unknown>,
|
||||
source,
|
||||
[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"] });
|
||||
},
|
||||
const { form, handleValuesChange, initialValues, save, submit } = useRecordContentEditorState({
|
||||
source,
|
||||
record,
|
||||
section,
|
||||
...(onDraft ? { onDraft } : {}),
|
||||
...(onSaved ? { onSaved } : {}),
|
||||
});
|
||||
|
||||
return (
|
||||
<Form
|
||||
form={form}
|
||||
layout="vertical"
|
||||
initialValues={initialValues}
|
||||
onValuesChange={(_, values) => {
|
||||
const currentValues = form.getFieldsValue(true) as PresentationValues;
|
||||
const next = {
|
||||
...draftValues,
|
||||
...values,
|
||||
...currentValues,
|
||||
};
|
||||
setDraftValues(next);
|
||||
onDraft?.(next);
|
||||
}}
|
||||
onFinish={(values) => {
|
||||
const currentValues = form.getFieldsValue(true) as PresentationValues;
|
||||
save.mutate({
|
||||
...draftValues,
|
||||
...values,
|
||||
...currentValues,
|
||||
});
|
||||
}}
|
||||
onValuesChange={handleValuesChange}
|
||||
onFinish={submit}
|
||||
style={{ minHeight: 0, display: "flex", flexDirection: "column" }}
|
||||
>
|
||||
<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 {
|
||||
Alert,
|
||||
Button,
|
||||
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 { Button } from "antd";
|
||||
import type { Offering, TemplateAdminField } from "@personal-brand/api-client";
|
||||
import { useMemo } from "react";
|
||||
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() {
|
||||
const navigate = useNavigate();
|
||||
const client = createApiClient();
|
||||
const queryClient = useQueryClient();
|
||||
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<"offerings" | "detail">("detail");
|
||||
const [formValues, setFormValues] = useState<Record<string, unknown>>({});
|
||||
const offerings = useQuery({
|
||||
queryKey: ["admin-offerings"],
|
||||
queryFn: () => client.listAdminOfferings(),
|
||||
refetchOnMount: "always",
|
||||
const { offerings, workspace, previewWorkspace, templateFields, retry } = useOfferingQueries();
|
||||
const editor = useOfferingEditor(templateFields);
|
||||
const mutations = useOfferingMutations({
|
||||
editingOffering: editor.editingOffering,
|
||||
templateFields,
|
||||
onSuccess: () => {
|
||||
editor.closeOffering();
|
||||
editor.offeringForm.resetFields();
|
||||
},
|
||||
});
|
||||
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: 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)) ?? {
|
||||
|
||||
const sections = workspace.data?.templateContent?.admin.sections ?? [];
|
||||
const previewTargets = useMemo(() => previewTargetsByPage(sections), [sections]);
|
||||
const listTarget = previewTargets.offerings.find((target) =>
|
||||
templateFields.some((field) => field.previewTarget === target.key),
|
||||
) ?? {
|
||||
key: "linjing-editorial.offerings.item",
|
||||
label: "业务卡片",
|
||||
page: "offerings",
|
||||
source: "offering",
|
||||
};
|
||||
const hasTemplateDetailCopy = templateFields.some(
|
||||
(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 detailTarget = previewTargets.detail.find((target) => target.source === "offering");
|
||||
const listFields = useMemo(
|
||||
() => templateFields.filter((field) => field.previewTarget === visualOfferingTarget.key),
|
||||
[templateFields, visualOfferingTarget.key],
|
||||
() => templateFields.filter((field) => field.previewTarget === listTarget.key),
|
||||
[templateFields, listTarget.key],
|
||||
);
|
||||
const detailTarget = previewTargets.detail?.find((target) => target.source === "offering");
|
||||
const detailFields = useMemo(
|
||||
() => templateFields.filter((field) => field.previewTarget === detailTarget?.key),
|
||||
[templateFields, detailTarget?.key],
|
||||
@@ -134,426 +52,85 @@ export function ServicesPage() {
|
||||
),
|
||||
[templateFields, listFields, detailFields],
|
||||
);
|
||||
const activeTemplateFields =
|
||||
previewPage === "offerings"
|
||||
const activeTemplateFields: TemplateAdminField[] =
|
||||
editor.previewPage === "offerings"
|
||||
? [...listFields, ...otherFields.filter((field) => field.page === "offerings")]
|
||||
: [...detailFields, ...otherFields.filter((field) => field.page === "detail")];
|
||||
const previewWorkspaceDraft = useMemo<RuntimeWorkspace | undefined>(() => {
|
||||
if (!previewWorkspace.data || !editingOffering) return undefined;
|
||||
const values: Record<string, unknown> = Object.keys(formValues).length
|
||||
? formValues
|
||||
: (offeringForm.getFieldsValue(true) as Record<string, unknown>);
|
||||
const config = applyPresentationValues(
|
||||
editingOffering.config,
|
||||
[{ 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,
|
||||
};
|
||||
const previewWorkspaceDraft = useMemo(() => {
|
||||
if (!previewWorkspace.data || !editor.editingOffering) return undefined;
|
||||
return buildOfferingPreviewWorkspace({
|
||||
previewWorkspace: previewWorkspace.data,
|
||||
editingOffering: editor.editingOffering,
|
||||
templateFields,
|
||||
formValues: editor.formValues,
|
||||
});
|
||||
}, [
|
||||
previewWorkspace.data,
|
||||
editingOffering,
|
||||
editor.editingOffering,
|
||||
templateFields,
|
||||
formValues,
|
||||
offeringDraftVersion,
|
||||
offeringForm,
|
||||
editor.formValues,
|
||||
editor.offeringDraftVersion,
|
||||
]);
|
||||
const saveOffering = useMutation({
|
||||
mutationFn: (values: Record<string, unknown>) => {
|
||||
const fields = Object.fromEntries(
|
||||
Object.entries(values).filter(([key]) => key !== "config" && !key.startsWith("offering:")),
|
||||
);
|
||||
const config = applyPresentationValues(
|
||||
editingOffering?.config,
|
||||
[{ key: "offering", fields: templateFields }],
|
||||
values,
|
||||
);
|
||||
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>);
|
||||
|
||||
const navigateToBrand = () => {
|
||||
if (!editor.editingOffering) return;
|
||||
void navigate("/admin/brand", {
|
||||
state: {
|
||||
targetKey:
|
||||
editor.previewPage === "offerings"
|
||||
? listTarget.key
|
||||
: (detailTarget?.key ?? listTarget.key),
|
||||
recordId: editor.editingOffering.id,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<QueryState
|
||||
loading={offerings.isLoading || workspace.isLoading}
|
||||
error={offerings.error || workspace.error}
|
||||
onRetry={() => {
|
||||
void offerings.refetch();
|
||||
void workspace.refetch();
|
||||
}}
|
||||
onRetry={retry}
|
||||
>
|
||||
<AdminPageHeader
|
||||
title="小程序内容:业务展示与详情"
|
||||
description={`在「${offeringPageLabel}」管理访客能选择的服务、产品或案例;每项内容的补充资料会显示在对应的「${detailPageLabel}」。`}
|
||||
description={`在「${offeringPageLabel(workspace.data?.templateContent ?? undefined)}」管理访客能选择的服务、产品或案例;每项内容的补充资料会显示在对应的「${detailPageLabel(workspace.data?.templateContent ?? undefined)}」。`}
|
||||
extra={
|
||||
<Button type="primary" onClick={() => beginOffering()}>
|
||||
<Button type="primary" onClick={() => editor.beginOffering()}>
|
||||
新增业务提供项
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<section aria-label="业务提供项列表">
|
||||
<Space wrap style={{ marginBottom: 16 }}>
|
||||
<Typography.Title level={5} style={{ margin: 0 }}>
|
||||
{offeringPageLabel}中的内容
|
||||
</Typography.Title>
|
||||
<Tag color="blue">已启用的项目会公开展示</Tag>
|
||||
</Space>
|
||||
{detailSections.length ? (
|
||||
<Typography.Paragraph type="secondary">
|
||||
编辑单项详情时,附加字段将用于:
|
||||
{detailSections.map((section) => section.title).join("、")}
|
||||
。列表中的名称、说明、价格和封面也会显示在业务展示页。
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
<Table
|
||||
scroll={{ x: 760 }}
|
||||
rowKey="id"
|
||||
loading={offerings.isLoading}
|
||||
dataSource={offerings.data ?? []}
|
||||
columns={[
|
||||
{ title: "名称", dataIndex: "name" },
|
||||
{
|
||||
title: "业务类型",
|
||||
dataIndex: "kind",
|
||||
render: (value) => (
|
||||
<Tag>
|
||||
{(
|
||||
{
|
||||
service: "服务",
|
||||
product: "定制产品",
|
||||
package: "套餐",
|
||||
subscription: "订阅",
|
||||
} as Record<string, string>
|
||||
)[String(value)] ?? String(value)}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{ title: "价格", dataIndex: "priceText" },
|
||||
{
|
||||
title: "状态",
|
||||
dataIndex: "isEnabled",
|
||||
render: (value) => (value ? "已启用" : "已停用"),
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
render: (_: unknown, item: Offering) => (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => beginOffering(item)}>
|
||||
编辑详情
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
loading={toggleOffering.isPending && toggleOffering.variables?.id === item.id}
|
||||
onClick={() =>
|
||||
toggleOffering.mutate({ id: item.id, isEnabled: !item.isEnabled })
|
||||
}
|
||||
>
|
||||
{item.isEnabled ? "禁用" : "启用"}
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="确认删除这项业务提供项?"
|
||||
description="如果它已经关联咨询表单,系统会阻止删除。"
|
||||
onConfirm={() => deleteOffering.mutate(item.id)}
|
||||
okText="删除"
|
||||
cancelText="取消"
|
||||
>
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
loading={deleteOffering.isPending && deleteOffering.variables === item.id}
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
{offerings.data?.length === 0 && (
|
||||
<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>
|
||||
<OfferingsTable
|
||||
pageLabel={offeringPageLabel(workspace.data?.templateContent ?? undefined)}
|
||||
detailSectionTitles={sections
|
||||
.filter((section) => section.target === "offering" && section.page === "detail")
|
||||
.map((section) => section.title)}
|
||||
items={offerings.data ?? []}
|
||||
loading={offerings.isLoading}
|
||||
saveError={mutations.saveOffering.error}
|
||||
toggleOffering={mutations.toggleOffering}
|
||||
deleteOffering={mutations.deleteOffering}
|
||||
onEdit={(item: Offering) => editor.beginOffering(item)}
|
||||
/>
|
||||
<OfferingEditorModal
|
||||
open={editor.offeringOpen}
|
||||
editingOffering={editor.editingOffering}
|
||||
form={editor.offeringForm}
|
||||
previewPage={editor.previewPage}
|
||||
previewWorkspace={previewWorkspaceDraft}
|
||||
previewTargets={previewTargets}
|
||||
activeTemplateFields={activeTemplateFields}
|
||||
templateFieldSection={editor.templateFieldSection}
|
||||
hasTemplateDetailCopy={hasTemplateDetailCopy(templateFields)}
|
||||
listTarget={listTarget}
|
||||
detailTarget={detailTarget}
|
||||
saving={mutations.saveOffering.isPending}
|
||||
onClose={editor.closeOffering}
|
||||
onPreviewPageChange={(page: PreviewPage) => editor.setPreviewPage(page)}
|
||||
onValuesChange={(values) => editor.handleValuesChange(null, values)}
|
||||
onFinish={(values) => mutations.saveOffering.mutate(values)}
|
||||
onEditInBrand={navigateToBrand}
|
||||
/>
|
||||
</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 {
|
||||
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 { Button, Divider, Form, Typography } from "antd";
|
||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
||||
import { TemplateListField } from "../../components/TemplateListField.js";
|
||||
import { MutationError, QueryState } from "../../components/QueryState.js";
|
||||
|
||||
const types = [
|
||||
{
|
||||
value: "schedule",
|
||||
label: "时间与服务安排",
|
||||
help: "说明你通常什么时候提供服务、接受预约或处理订单。多项内容可以分行填写。",
|
||||
},
|
||||
{
|
||||
value: "coverage",
|
||||
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,
|
||||
}));
|
||||
import { QueryState } from "../../components/QueryState.js";
|
||||
import { TrustContentEditorModal } from "./components/TrustContentEditorModal.js";
|
||||
import { TrustContentTable } from "./components/TrustContentTable.js";
|
||||
import { TrustRequirementsList } from "./components/TrustRequirementsList.js";
|
||||
import type { TrustTypeOption } from "./domain/trust-content-domain.js";
|
||||
import {
|
||||
createTrustPageLabelResolver,
|
||||
groupTrustContentByType,
|
||||
selectTrustTypeOptions,
|
||||
} from "./domain/trust-content-domain.js";
|
||||
import { useTrustContentEditor } from "./hooks/useTrustContentEditor.js";
|
||||
import { useTrustContentQueries } from "./hooks/useTrustContentQueries.js";
|
||||
|
||||
export function TrustContentPage() {
|
||||
const client = createApiClient();
|
||||
const queryClient = useQueryClient();
|
||||
const [editing, setEditing] = useState<TrustContent | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [form] = Form.useForm<TrustContentInput>();
|
||||
const [searchParams] = useSearchParams();
|
||||
const selectedType = Form.useWatch("type", form);
|
||||
const query = useQuery({
|
||||
queryKey: ["trust-content"],
|
||||
queryFn: () => client.listAdminTrustContent(),
|
||||
const { query, workspace } = useTrustContentQueries();
|
||||
const availableTypes = selectTrustTypeOptions(workspace.data?.templateContent?.trustContentTypes);
|
||||
const pageLabel = createTrustPageLabelResolver(workspace.data?.templateContent?.navigation);
|
||||
const contentByType = groupTrustContentByType(query.data ?? []);
|
||||
const firstMissingRequiredType =
|
||||
availableTypes.find((item) => item.required && !contentByType.has(item.type))?.type ??
|
||||
availableTypes[0]?.type ??
|
||||
"credential";
|
||||
const {
|
||||
begin,
|
||||
closeEditor,
|
||||
editing,
|
||||
form: editorForm,
|
||||
open,
|
||||
remove,
|
||||
save,
|
||||
} = useTrustContentEditor({
|
||||
availableTypes,
|
||||
contentByType,
|
||||
firstMissingRequiredType,
|
||||
});
|
||||
const workspace = useQuery({
|
||||
queryKey: ["admin-workspace-trust-types"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
});
|
||||
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 selectedType = Form.useWatch("type", editorForm);
|
||||
const selectedTypeMeta: TrustTypeOption | undefined = availableTypes.find(
|
||||
(item) => item.type === selectedType,
|
||||
);
|
||||
const trustPageLabels = [
|
||||
...new Set(availableTypes.flatMap((item) => item.pages ?? []).map(pageLabel)),
|
||||
];
|
||||
const trustPlacement = trustPageLabels.length
|
||||
? `小程序的${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 (
|
||||
<QueryState
|
||||
loading={query.isLoading || workspace.isLoading}
|
||||
@@ -202,213 +68,34 @@ export function TrustContentPage() {
|
||||
<Typography.Paragraph type="secondary">
|
||||
标记为“发布必填”的项目需要填写完整后,才能发布小程序。
|
||||
</Typography.Paragraph>
|
||||
<List
|
||||
size="small"
|
||||
dataSource={availableTypes}
|
||||
renderItem={(item) => {
|
||||
const content = contentByType.get(item.type);
|
||||
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>
|
||||
);
|
||||
}}
|
||||
<TrustRequirementsList
|
||||
availableTypes={availableTypes}
|
||||
contentByType={contentByType}
|
||||
items={query.data ?? []}
|
||||
onEdit={begin}
|
||||
/>
|
||||
</section>
|
||||
<Divider />
|
||||
<section aria-label="已配置的品牌内容">
|
||||
<Table
|
||||
rowKey="id"
|
||||
dataSource={query.data ?? []}
|
||||
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) => {
|
||||
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
|
||||
<TrustContentTable
|
||||
availableTypes={availableTypes}
|
||||
items={query.data ?? []}
|
||||
removeError={remove.error}
|
||||
removePending={remove.isPending}
|
||||
onEdit={(item) => begin(item)}
|
||||
onDelete={(id) => remove.mutate(id)}
|
||||
/>
|
||||
<TrustContentEditorModal
|
||||
availableTypes={availableTypes}
|
||||
editing={editing}
|
||||
form={editorForm}
|
||||
open={open}
|
||||
title={editing ? "编辑品牌内容" : "添加品牌内容"}
|
||||
onCancel={() => {
|
||||
setOpen(false);
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
}}
|
||||
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>
|
||||
pageLabel={pageLabel}
|
||||
saveError={save.error}
|
||||
savePending={save.isPending}
|
||||
selectedTypeMeta={selectedTypeMeta}
|
||||
onCancel={closeEditor}
|
||||
onFinish={(values) => save.mutate(values)}
|
||||
/>
|
||||
</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(),
|
||||
}),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user