Files
persionalBrand/apps/admin/src/main.tsx
T

584 lines
18 KiB
TypeScript

import React, { useState } from "react";
import { createRoot } from "react-dom/client";
import {
QueryClient,
QueryClientProvider,
useMutation,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import {
App,
Button,
Card,
Form,
Input,
Layout,
Menu,
Select,
Space,
Typography,
message,
Table,
Tag,
Popconfirm,
Modal,
Badge,
} from "antd";
import { createApiClient } from "./lib/api.js";
import { InquiriesPage as FeatureInquiriesPage } from "./features/inquiries/InquiriesPage.js";
import { BrowserRouter, Navigate, Route, Routes, useLocation, useNavigate } from "react-router-dom";
import type {
BrandProfile,
PublicService,
TrustContent,
TrustContentInput,
} from "@personal-brand/api-client";
import "antd/dist/reset.css";
const queryClient = new QueryClient();
const api = createApiClient;
function Login({ onLogin }: { onLogin: () => void }) {
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
async function submit(values: { username: string; password: string }) {
setLoading(true);
try {
const result = await api().loginAdmin(values.username, values.password);
localStorage.setItem("adminToken", result.token);
onLogin();
} catch (error) {
message.error(error instanceof Error ? error.message : "登录失败");
} finally {
setLoading(false);
}
}
return (
<Card title="个人品牌后台" style={{ maxWidth: 420, margin: "120px auto" }}>
<Form form={form} layout="vertical" onFinish={submit}>
<Form.Item name="username" label="账号" initialValue="admin" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="password" label="密码" rules={[{ required: true }]}>
<Input.Password />
</Form.Item>
<Button type="primary" htmlType="submit" loading={loading} block>
登录
</Button>
</Form>
</Card>
);
}
function BrandPage() {
const client = api();
const queryClientHook = useQueryClient();
const [form] = Form.useForm<BrandProfile>();
const brand = useQuery({ queryKey: ["admin-brand"], queryFn: () => client.getAdminBrand() });
const save = useMutation({
mutationFn: (values: Partial<BrandProfile>) => client.updateAdminBrand(values),
onSuccess: () => {
message.success("品牌配置已保存");
void queryClientHook.invalidateQueries({ queryKey: ["admin-brand"] });
},
});
if (brand.isLoading) return <Card loading />;
if (brand.isError || !brand.data) return <Card>品牌配置加载失败</Card>;
return (
<Card title="品牌信任配置">
<Form
form={form}
layout="vertical"
initialValues={brand.data}
onFinish={(values) => save.mutate(values)}
>
<Form.Item name="templateKey" label="行业模板">
<Select
options={[
{ value: "personal", label: "个人品牌" },
{ value: "food", label: "餐饮模板" },
]}
/>
</Form.Item>
<Form.Item name="name" label="品牌名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="tagline" label="一句话定位">
<Input />
</Form.Item>
<Form.Item name="description" label="品牌简介">
<Input.TextArea rows={5} />
</Form.Item>
<Form.Item name="hours" label="服务时间">
<Input />
</Form.Item>
<Form.Item name="address" label="所在位置">
<Input />
</Form.Item>
<Form.Item name="contactPhone" label="联系电话">
<Input />
</Form.Item>
<Form.Item name="contactWechat" label="微信号">
<Input />
</Form.Item>
<Button type="primary" htmlType="submit" loading={save.isPending}>
保存配置
</Button>
</Form>
</Card>
);
}
function TrustContentPage() {
const client = api();
const queryClientHook = useQueryClient();
const [editing, setEditing] = useState<TrustContent | null>(null);
const [modalOpen, setModalOpen] = useState(false);
const [form] = Form.useForm<TrustContentInput>();
const query = useQuery({
queryKey: ["trust-content"],
queryFn: () => client.listAdminTrustContent(),
});
const save = useMutation({
mutationFn: (values: TrustContentInput) =>
editing
? client.updateAdminTrustContent(editing.id, values)
: client.createAdminTrustContent(values),
onSuccess: () => {
message.success("信任内容已保存");
setModalOpen(false);
setEditing(null);
form.resetFields();
void queryClientHook.invalidateQueries({ queryKey: ["trust-content"] });
},
});
const remove = useMutation({
mutationFn: (id: string) => client.deleteAdminTrustContent(id),
onSuccess: () => {
message.success("内容已删除");
void queryClientHook.invalidateQueries({ queryKey: ["trust-content"] });
},
});
function open(item?: TrustContent) {
setEditing(item ?? null);
setModalOpen(true);
form.setFieldsValue(
item
? {
type: item.type,
title: item.title,
summary: item.summary ?? undefined,
content: item.content,
sortOrder: item.sortOrder,
isPublished: item.isPublished,
}
: { type: "profile", isPublished: true },
);
}
return (
<Card
title="信任内容"
extra={
<Button type="primary" onClick={() => open()}>
新增内容
</Button>
}
>
<Table
rowKey="id"
loading={query.isLoading}
dataSource={query.data ?? []}
columns={[
{ title: "类型", dataIndex: "type", render: (value) => <Tag>{value}</Tag> },
{ title: "标题", dataIndex: "title" },
{
title: "状态",
dataIndex: "isPublished",
render: (value) => (value ? "已发布" : "草稿"),
},
{
title: "操作",
render: (_: unknown, item: TrustContent) => (
<Space>
<Button size="small" onClick={() => open(item)}>
编辑
</Button>
<Popconfirm title="确认删除?" onConfirm={() => remove.mutate(item.id)}>
<Button size="small" danger>
删除
</Button>
</Popconfirm>
</Space>
),
},
]}
/>{" "}
<Modal
open={modalOpen}
title={editing ? "编辑信任内容" : "新增信任内容"}
onCancel={() => {
setModalOpen(false);
setEditing(null);
form.resetFields();
}}
onOk={() => form.submit()}
confirmLoading={save.isPending}
>
<Form form={form} layout="vertical" onFinish={(values) => save.mutate(values)}>
<Form.Item name="type" label="内容类型" rules={[{ required: true }]}>
<Select
options={[
"profile",
"experience",
"credential",
"portfolio",
"process",
"testimonial",
].map((value) => ({ value, label: value }))}
/>
</Form.Item>
<Form.Item name="title" label="标题" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="summary" label="摘要">
<Input />
</Form.Item>
<Form.Item name="content" label="内容" rules={[{ required: true }]}>
<Input.TextArea rows={7} />
</Form.Item>
<Form.Item name="isPublished" label="发布状态">
<Select
options={[
{ value: true, label: "已发布" },
{ value: false, label: "草稿" },
]}
/>
</Form.Item>
</Form>
</Modal>
</Card>
);
}
function ServicesPage() {
const client = api();
const queryClientHook = useQueryClient();
const [editing, setEditing] = useState<PublicService | null>(null);
const [modalOpen, setModalOpen] = useState(false);
const [form] = Form.useForm();
const query = useQuery({
queryKey: ["admin-services"],
queryFn: () => client.listAdminServices(),
});
const save = useMutation({
mutationFn: (values: Record<string, unknown>) =>
editing
? client.updateAdminService(editing.id, values)
: client.createAdminService(values as { name: string; description: string }),
onSuccess: () => {
message.success("服务已保存");
setModalOpen(false);
setEditing(null);
form.resetFields();
void queryClientHook.invalidateQueries({ queryKey: ["admin-services"] });
},
});
const remove = useMutation({
mutationFn: (item: PublicService) =>
client.updateAdminService(item.id, { isEnabled: !item.isEnabled }),
onSuccess: () => {
message.success("服务状态已更新");
void queryClientHook.invalidateQueries({ queryKey: ["admin-services"] });
},
});
function open(item?: PublicService) {
setEditing(item ?? null);
setModalOpen(true);
form.setFieldsValue(
item ?? { categoryKey: "standard", bookingEnabled: true, isEnabled: true, sortOrder: 0 },
);
}
return (
<Card
title="服务与合作"
extra={
<Button type="primary" onClick={() => open()}>
新增服务
</Button>
}
>
<Table
rowKey="id"
loading={query.isLoading}
dataSource={query.data ?? []}
columns={[
{ title: "服务名称", dataIndex: "name" },
{ title: "分类", dataIndex: "categoryKey", render: (value) => <Tag>{value}</Tag> },
{ title: "价格展示", dataIndex: "priceText" },
{
title: "状态",
dataIndex: "isEnabled",
render: (value) => (value ? "已上架" : "已下架"),
},
{
title: "操作",
render: (_: unknown, item: PublicService) => (
<Space>
<Button size="small" onClick={() => open(item)}>
编辑
</Button>
<Button size="small" onClick={() => remove.mutate(item)}>
{item.isEnabled ? "下架" : "上架"}
</Button>
</Space>
),
},
]}
/>
<Modal
open={modalOpen}
title={editing ? "编辑服务" : "新增服务"}
onCancel={() => {
setModalOpen(false);
setEditing(null);
form.resetFields();
}}
onOk={() => form.submit()}
confirmLoading={save.isPending}
>
<Form form={form} layout="vertical" onFinish={(values) => save.mutate(values)}>
<Form.Item name="name" label="服务名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="description" label="服务描述" rules={[{ required: true }]}>
<Input.TextArea rows={4} />
</Form.Item>
<Form.Item name="categoryKey" label="服务分类" rules={[{ required: true }]}>
<Input placeholder="例如:standard、consulting、food-package" />
</Form.Item>
<Form.Item name="priceText" label="价格展示">
<Input placeholder="例如:¥ 1,500 起 / 沟通报价" />
</Form.Item>
<Form.Item name="sortOrder" label="排序">
<Input type="number" />
</Form.Item>
<Form.Item name="bookingEnabled" label="允许提交需求">
<Select
options={[
{ value: true, label: "允许" },
{ value: false, label: "暂不接受" },
]}
/>
</Form.Item>
<Form.Item name="isEnabled" label="公开状态">
<Select
options={[
{ value: true, label: "已上架" },
{ value: false, label: "已下架" },
]}
/>
</Form.Item>
</Form>
</Modal>
</Card>
);
}
const bookingStatusOptions = [
"received",
"contacting",
"confirmed",
"completed",
"cancelled",
] as const;
const bookingStatusLabels: Record<string, string> = {
received: "待处理",
contacting: "沟通中",
confirmed: "已确认",
completed: "已完成",
cancelled: "已取消",
};
function InquiriesPage() {
const client = api();
const queryClientHook = useQueryClient();
const [status, setStatus] = useState<string | undefined>();
const query = useQuery({
queryKey: ["admin-bookings", status],
queryFn: () => client.listAdminBookings(status ? { status: status as never } : {}),
});
const update = useMutation({
mutationFn: ({ id, nextStatus, note }: { id: string; nextStatus: never; note?: string }) =>
client.updateAdminBookingStatus(id, nextStatus, note),
onSuccess: () => {
message.success("咨询状态已更新");
void queryClientHook.invalidateQueries({ queryKey: ["admin-bookings"] });
},
});
const markRead = useMutation({
mutationFn: (id: string) => client.markAdminBookingRead(id),
onSuccess: () => void queryClientHook.invalidateQueries({ queryKey: ["admin-bookings"] }),
});
return (
<Card
title="咨询记录"
extra={
<Space>
<Select
allowClear
placeholder="全部状态"
style={{ width: 130 }}
value={status}
onChange={setStatus}
options={bookingStatusOptions.map((value) => ({
value,
label: bookingStatusLabels[value],
}))}
/>
<Badge
count={
query.data?.filter((item) => !(item as AdminBooking & { isRead?: boolean }).isRead)
.length ?? 0
}
showZero
/>
</Space>
}
>
<Table
rowKey="id"
loading={query.isLoading}
dataSource={query.data ?? []}
columns={[
{ title: "编号", dataIndex: "bookingNo" },
{
title: "类型",
render: (_: unknown, item: AdminBooking & { requestType?: string }) =>
item.requestType === "inquiry"
? "品牌咨询"
: item.requestType === "private_chef"
? "定制服务"
: "服务预约",
},
{ title: "联系人", dataIndex: "customerName" },
{
title: "提交时间",
dataIndex: "createdAt",
render: (value: string) => new Date(value).toLocaleString("zh-CN"),
},
{
title: "状态",
dataIndex: "status",
render: (value: string) => (
<Tag color={value === "cancelled" ? "default" : "processing"}>
{bookingStatusLabels[value] ?? value}
</Tag>
),
},
{
title: "操作",
render: (_: unknown, item: AdminBooking) => (
<Space>
<Select
size="small"
value={item.status}
onChange={(nextStatus) =>
update.mutate({ id: item.id, nextStatus: nextStatus as never })
}
options={bookingStatusOptions.map((value) => ({
value,
label: bookingStatusLabels[value],
}))}
/>
<Button size="small" onClick={() => markRead.mutate(item.id)}>
标记已读
</Button>
</Space>
),
},
]}
/>
</Card>
);
}
function Dashboard({ onLogout }: { onLogout: () => void }) {
const navigate = useNavigate();
const location = useLocation();
const page = location.pathname.split("/")[2] || "brand";
const items = [
{ key: "brand", label: "品牌信任" },
{ key: "trust", label: "信任内容" },
{ key: "services", label: "服务与合作" },
{ key: "inquiries", label: "咨询记录" },
];
return (
<Layout style={{ minHeight: "100vh" }}>
<Layout.Sider>
<Typography.Title level={4} style={{ color: "white", padding: 20 }}>
个人品牌
</Typography.Title>
<Menu
theme="dark"
selectedKeys={[page]}
onClick={({ key }) => navigate(`/admin/${key}`)}
items={items}
/>
</Layout.Sider>
<Layout>
<Layout.Header
style={{
background: "white",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Space>品牌管理后台</Space>
<Button type="text" onClick={onLogout}>
退出登录
</Button>
</Layout.Header>
<Layout.Content style={{ padding: 24 }}>
<Routes>
<Route path="brand" element={<BrandPage />} />
<Route path="trust" element={<TrustContentPage />} />
<Route path="services" element={<ServicesPage />} />
<Route path="inquiries" element={<FeatureInquiriesPage />} />
<Route path="*" element={<Navigate to="/admin/brand" replace />} />
</Routes>
</Layout.Content>
</Layout>
</Layout>
);
}
function Root() {
const [loggedIn, setLoggedIn] = useState(Boolean(localStorage.getItem("adminToken")));
React.useEffect(() => {
const expire = () => {
message.warning("登录状态已失效,请重新登录");
setLoggedIn(false);
};
window.addEventListener("admin-auth-expired", expire);
return () => window.removeEventListener("admin-auth-expired", expire);
}, []);
const logout = () => {
localStorage.removeItem("adminToken");
setLoggedIn(false);
};
return loggedIn ? <Dashboard onLogout={logout} /> : <Login onLogin={() => setLoggedIn(true)} />;
}
createRoot(document.getElementById("app")!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App>
<BrowserRouter>
<Root />
</BrowserRouter>
</App>
</QueryClientProvider>
</React.StrictMode>,
);