style: 统一项目代码格式

This commit is contained in:
que01 committed 2026-09-19 18:37:00 +08:00
1 parent f0836ec056
commit 718d357d88
8 files changed
+1012 -117

No files matched your search

+11 -1
View File
@@ -10,7 +10,17 @@ if (root) {
event.preventDefault();
const username = (root.querySelector("#username") as HTMLInputElement).value;
const password = (root.querySelector("#password") as HTMLInputElement).value;
try { const client = new ApiClient({ baseUrl: import.meta.env.VITE_API_BASE_URL ?? "http://localhost:3001", fetcher: (input, init) => fetch(input, init) }); const result = await client.loginAdmin(username, password); localStorage.setItem("adminToken", result.token); location.reload(); } catch (error) { alert(error instanceof Error ? error.message : "登录失败"); }
try {
const client = new ApiClient({
baseUrl: import.meta.env.VITE_API_BASE_URL ?? "http://localhost:3001",
fetcher: (input, init) => fetch(input, init),
});
const result = await client.loginAdmin(username, password);
localStorage.setItem("adminToken", result.token);
location.reload();
} catch (error) {
alert(error instanceof Error ? error.message : "登录失败");
}
});
} else bootstrapAdmin(root);
}
+84 -12
View File
@@ -1,6 +1,9 @@
import { ApiClient, type AdminBooking, type BookingStatus } from "@personal-brand/api-client";
export interface AdminDashboardOptions { client: ApiClient; root: HTMLElement }
export interface AdminDashboardOptions {
client: ApiClient;
root: HTMLElement;
}
export class AdminDashboard {
private bookings: AdminBooking[] = [];
@@ -9,29 +12,98 @@ export class AdminDashboard {
async load(): Promise<void> {
const { root, client } = this.options;
const [bookings, unread, brand, services] = await Promise.all([client.listAdminBookings(), client.getAdminUnreadCount(), client.getAdminBrand(), client.listServices()]);
const [bookings, unread, brand, services] = await Promise.all([
client.listAdminBookings(),
client.getAdminUnreadCount(),
client.getAdminBrand(),
client.listServices(),
]);
this.bookings = bookings;
root.innerHTML = `<h1>品牌后台</h1><p>未读订单:${unread.count}</p><section><h2>品牌配置</h2><label>行业模板 <select id="brand-template"><option value="food" ${brand.templateKey === "food" ? "selected" : ""}>餐饮</option><option value="personal" ${brand.templateKey === "personal" ? "selected" : ""}>个人品牌</option></select></label><label>品牌名 <input id="brand-name" value="${brand.name}"></label><label>品牌简介 <textarea id="brand-description">${brand.description ?? ""}</textarea></label><label>联系电话 <input id="brand-phone" value="${brand.contactPhone ?? ""}"></label><label>微信号 <input id="brand-wechat" value="${brand.contactWechat ?? ""}"></label><button id="save-brand">保存品牌配置</button></section><section><h2>服务配置</h2><ul id="services">${services.map((item) => `<li><input data-service-name="${item.id}" value="${item.name}"><input data-service-price="${item.id}" value="${item.priceText ?? ""}"><button data-service-save="${item.id}">保存</button></li>`).join("")}</ul></section><label>状态 <select id="status"><option value="">全部</option><option>received</option><option>contacting</option><option>confirmed</option><option>completed</option><option>cancelled</option></select></label><button id="refresh">刷新</button><ul id="bookings">${this.listHtml()}</ul><section id="detail">选择订单查看详情</section>`;
root.querySelector("#refresh")?.addEventListener("click", () => void this.load());
root.querySelector("#status")?.addEventListener("change", () => void this.filter());
root.querySelector("#save-brand")?.addEventListener("click", () => void this.saveBrand());
root.querySelectorAll<HTMLElement>("[data-service-save]").forEach((item) => item.addEventListener("click", () => void this.saveService(item.dataset.serviceSave)));
root.querySelectorAll<HTMLElement>("[data-id]").forEach((item) => item.addEventListener("click", () => this.select(item.dataset.id)));
root
.querySelectorAll<HTMLElement>("[data-service-save]")
.forEach((item) =>
item.addEventListener("click", () => void this.saveService(item.dataset.serviceSave)),
);
root
.querySelectorAll<HTMLElement>("[data-id]")
.forEach((item) => item.addEventListener("click", () => this.select(item.dataset.id)));
}
private listHtml(): string { return this.bookings.map((item) => `<li><button data-id="${item.id}">${item.bookingNo} · ${item.customerName} · ${item.status}</button></li>`).join("") || "<li>暂无订单</li>"; }
private async filter(): Promise<void> { const status = (this.options.root.querySelector("#status") as HTMLSelectElement).value as BookingStatus | ""; this.bookings = await this.options.client.listAdminBookings(status ? { status } : {}); const list = this.options.root.querySelector("#bookings"); if (list) list.innerHTML = this.listHtml(); }
private select(id: string | undefined): void { this.selected = this.bookings.find((item) => item.id === id); if (!this.selected) return; const detail = this.options.root.querySelector("#detail"); if (!detail) return; detail.innerHTML = `<h2>${this.selected.bookingNo}</h2><p>客户:${this.selected.customerName}</p><select id="detail-status"><option>received</option><option>contacting</option><option>confirmed</option><option>completed</option><option>cancelled</option></select><textarea id="note" placeholder="内部备注">${this.selected.adminNote ?? ""}</textarea><button id="save">保存</button>`; detail.querySelector("#save")?.addEventListener("click", () => void this.save()); }
private async save(): Promise<void> { if (!this.selected) return; const detail = this.options.root.querySelector("#detail")!; const status = (detail.querySelector("#detail-status") as HTMLSelectElement).value as BookingStatus; const note = (detail.querySelector("#note") as HTMLTextAreaElement).value; this.selected = await this.options.client.updateAdminBookingStatus(this.selected.id, status, note); await this.load(); }
private async saveBrand(): Promise<void> { const root = this.options.root; await this.options.client.updateAdminBrand({ templateKey: (root.querySelector("#brand-template") as HTMLSelectElement).value as "food" | "personal", name: (root.querySelector("#brand-name") as HTMLInputElement).value, description: (root.querySelector("#brand-description") as HTMLTextAreaElement).value, contactPhone: (root.querySelector("#brand-phone") as HTMLInputElement).value, contactWechat: (root.querySelector("#brand-wechat") as HTMLInputElement).value }); }
private async saveService(id: string | undefined): Promise<void> { if (!id) return; const root = this.options.root; await this.options.client.updateAdminService(id, { name: (root.querySelector(`[data-service-name="${id}"]`) as HTMLInputElement).value, priceText: (root.querySelector(`[data-service-price="${id}"]`) as HTMLInputElement).value }); }
private listHtml(): string {
return (
this.bookings
.map(
(item) =>
`<li><button data-id="${item.id}">${item.bookingNo} · ${item.customerName} · ${item.status}</button></li>`,
)
.join("") || "<li>暂无订单</li>"
);
}
private async filter(): Promise<void> {
const status = (this.options.root.querySelector("#status") as HTMLSelectElement).value as
BookingStatus | "";
this.bookings = await this.options.client.listAdminBookings(status ? { status } : {});
const list = this.options.root.querySelector("#bookings");
if (list) list.innerHTML = this.listHtml();
}
private select(id: string | undefined): void {
this.selected = this.bookings.find((item) => item.id === id);
if (!this.selected) return;
const detail = this.options.root.querySelector("#detail");
if (!detail) return;
detail.innerHTML = `<h2>${this.selected.bookingNo}</h2><p>客户:${this.selected.customerName}</p><select id="detail-status"><option>received</option><option>contacting</option><option>confirmed</option><option>completed</option><option>cancelled</option></select><textarea id="note" placeholder="内部备注">${this.selected.adminNote ?? ""}</textarea><button id="save">保存</button>`;
detail.querySelector("#save")?.addEventListener("click", () => void this.save());
}
private async save(): Promise<void> {
if (!this.selected) return;
const detail = this.options.root.querySelector("#detail")!;
const status = (detail.querySelector("#detail-status") as HTMLSelectElement)
.value as BookingStatus;
const note = (detail.querySelector("#note") as HTMLTextAreaElement).value;
this.selected = await this.options.client.updateAdminBookingStatus(
this.selected.id,
status,
note,
);
await this.load();
}
private async saveBrand(): Promise<void> {
const root = this.options.root;
await this.options.client.updateAdminBrand({
templateKey: (root.querySelector("#brand-template") as HTMLSelectElement).value as
"food" | "personal",
name: (root.querySelector("#brand-name") as HTMLInputElement).value,
description: (root.querySelector("#brand-description") as HTMLTextAreaElement).value,
contactPhone: (root.querySelector("#brand-phone") as HTMLInputElement).value,
contactWechat: (root.querySelector("#brand-wechat") as HTMLInputElement).value,
});
}
private async saveService(id: string | undefined): Promise<void> {
if (!id) return;
const root = this.options.root;
await this.options.client.updateAdminService(id, {
name: (root.querySelector(`[data-service-name="${id}"]`) as HTMLInputElement).value,
priceText: (root.querySelector(`[data-service-price="${id}"]`) as HTMLInputElement).value,
});
}
}
export const adminAppName = "personal-brand-admin";
export function bootstrapAdmin(root: HTMLElement, baseUrl = "http://localhost:3001"): AdminDashboard {
export function bootstrapAdmin(
root: HTMLElement,
baseUrl = "http://localhost:3001",
): AdminDashboard {
const token = localStorage.getItem("adminToken");
const client = new ApiClient({ baseUrl, fetcher: (input, init) => fetch(input, init), ...(token ? { token } : {}) });
const client = new ApiClient({
baseUrl,
fetcher: (input, init) => fetch(input, init),
...(token ? { token } : {}),
});
const dashboard = new AdminDashboard({ client, root });
void dashboard.load();
return dashboard;
+556 -31
View File
@@ -1,10 +1,38 @@
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 {
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 { ApiClient } from "@personal-brand/api-client";
import { BrowserRouter, Navigate, Route, Routes, useLocation, useNavigate } from "react-router-dom";
import type { BrandProfile, PublicService, TrustContent, TrustContentInput } from "@personal-brand/api-client";
import type {
BrandProfile,
PublicService,
TrustContent,
TrustContentInput,
} from "@personal-brand/api-client";
import "antd/dist/reset.css";
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL ?? "http://localhost:3001";
@@ -17,55 +45,552 @@ async function authenticatedFetch(input: RequestInfo | URL, init?: RequestInit):
}
return response;
}
const api = () => new ApiClient({ baseUrl: apiBaseUrl, token: localStorage.getItem("adminToken") ?? undefined, fetcher: authenticatedFetch });
const api = () =>
new ApiClient({
baseUrl: apiBaseUrl,
token: localStorage.getItem("adminToken") ?? undefined,
fetcher: authenticatedFetch,
});
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>;
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 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"] }); } });
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>;
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>;
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 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: "已取消" };
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 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>;
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={<InquiriesPage />} /><Route path="*" element={<Navigate to="/admin/brand" replace />} /></Routes></Layout.Content></Layout></Layout>; }
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={<InquiriesPage />} />
<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>);
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>,
);