refactor: 拆分业务、信任内容与公共工作台模块

This commit is contained in:
que01 committed 2026-10-12 05:11:26 +08:00
1 parent 357f271639
commit 466dc66907
33 files changed
+4950 -4500

No files matched your search

@@ -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(),
}),
};
}