style: 统一项目代码格式
This commit is contained in:
1 parent
f0836ec056
commit
718d357d88
8 files changed
+1012
-117
No files matched your search
+11
-1
@@ -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
@@ -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
@@ -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>,
|
||||
);
|
||||
@@ -41,7 +41,8 @@ export class CreateServiceDto {
|
||||
}
|
||||
|
||||
export class CreateTrustContentDto {
|
||||
@IsIn(["profile", "experience", "credential", "portfolio", "process", "testimonial"]) type!: string;
|
||||
@IsIn(["profile", "experience", "credential", "portfolio", "process", "testimonial"])
|
||||
type!: string;
|
||||
@IsString() title!: string;
|
||||
@IsOptional() @IsString() summary?: string;
|
||||
@IsString() content!: string;
|
||||
@@ -52,7 +53,9 @@ export class CreateTrustContentDto {
|
||||
}
|
||||
|
||||
export class UpdateTrustContentDto {
|
||||
@IsOptional() @IsIn(["profile", "experience", "credential", "portfolio", "process", "testimonial"]) type?: string;
|
||||
@IsOptional()
|
||||
@IsIn(["profile", "experience", "credential", "portfolio", "process", "testimonial"])
|
||||
type?: string;
|
||||
@IsOptional() @IsString() title?: string;
|
||||
@IsOptional() @IsString() summary?: string;
|
||||
@IsOptional() @IsString() content?: string;
|
||||
|
||||
+124
-19
@@ -23,7 +23,16 @@ import { PrismaService } from "./prisma.service.js";
|
||||
import { WechatAuthService } from "./wechat-auth.js";
|
||||
import { BookingService } from "./booking.service.js";
|
||||
import { CreateBookingDto } from "./booking.dto.js";
|
||||
import { CreateServiceDto, CreateTagDto, CreateTrustContentDto, UpdateBookingStatusDto, UpdateBookingTagsDto, UpdateBrandDto, UpdateServiceDto, UpdateTrustContentDto } from "./admin.dto.js";
|
||||
import {
|
||||
CreateServiceDto,
|
||||
CreateTagDto,
|
||||
CreateTrustContentDto,
|
||||
UpdateBookingStatusDto,
|
||||
UpdateBookingTagsDto,
|
||||
UpdateBrandDto,
|
||||
UpdateServiceDto,
|
||||
UpdateTrustContentDto,
|
||||
} from "./admin.dto.js";
|
||||
import { AdminAuthService } from "./admin-auth.service.js";
|
||||
import { AdminLoginDto } from "./admin-auth.dto.js";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
@@ -89,7 +98,15 @@ export class PublicController {
|
||||
export class PublicTrustContentController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
@Get()
|
||||
list(): Promise<unknown> { return this.prisma.trustContent.findMany({ where: { brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001", isPublished: true }, orderBy: [{ type: "asc" }, { sortOrder: "asc" }] }); }
|
||||
list(): Promise<unknown> {
|
||||
return this.prisma.trustContent.findMany({
|
||||
where: {
|
||||
brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
||||
isPublished: true,
|
||||
},
|
||||
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Controller("customer/session")
|
||||
@@ -202,10 +219,7 @@ export class CustomerBookingController {
|
||||
export class AdminBookingController {
|
||||
constructor(private readonly bookings: BookingService) {}
|
||||
@Get()
|
||||
list(
|
||||
@Req() request: FastifyRequest,
|
||||
@Query() query: AdminBookingQueryDto,
|
||||
): Promise<unknown> {
|
||||
list(@Req() request: FastifyRequest, @Query() query: AdminBookingQueryDto): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.bookings.listForAdmin(
|
||||
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
|
||||
@@ -289,7 +303,11 @@ export class AdminBookingController {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
let identity;
|
||||
try { identity = readIdentity(token); } catch { throw new UnauthorizedException("管理员登录态无效或已过期"); }
|
||||
try {
|
||||
identity = readIdentity(token);
|
||||
} catch {
|
||||
throw new UnauthorizedException("管理员登录态无效或已过期");
|
||||
}
|
||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||
}
|
||||
}
|
||||
@@ -297,37 +315,124 @@ export class AdminBookingController {
|
||||
@Controller("admin/config")
|
||||
export class AdminConfigController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
private brandId(): string { return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001"; }
|
||||
private brandId(): string {
|
||||
return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
|
||||
}
|
||||
private requireAdmin(request: FastifyRequest): void {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
let identity;
|
||||
try { identity = readIdentity(token); } catch { throw new UnauthorizedException("管理员登录态无效或已过期"); }
|
||||
try {
|
||||
identity = readIdentity(token);
|
||||
} catch {
|
||||
throw new UnauthorizedException("管理员登录态无效或已过期");
|
||||
}
|
||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||
}
|
||||
@Get("brand")
|
||||
getBrand(@Req() request: FastifyRequest): Promise<unknown> { this.requireAdmin(request); return this.prisma.brandProfile.findUnique({ where: { id: this.brandId() } }); }
|
||||
getBrand(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.prisma.brandProfile.findUnique({ where: { id: this.brandId() } });
|
||||
}
|
||||
@Patch("brand")
|
||||
updateBrand(@Req() request: FastifyRequest, @Body() body: UpdateBrandDto): Promise<unknown> { this.requireAdmin(request); return this.prisma.brandProfile.update({ where: { id: this.brandId() }, data: body }); }
|
||||
updateBrand(@Req() request: FastifyRequest, @Body() body: UpdateBrandDto): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.prisma.brandProfile.update({ where: { id: this.brandId() }, data: body });
|
||||
}
|
||||
@Get("trust-content")
|
||||
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> { this.requireAdmin(request); return this.prisma.trustContent.findMany({ where: { brandId: this.brandId() }, orderBy: [{ type: "asc" }, { sortOrder: "asc" }] }); }
|
||||
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.prisma.trustContent.findMany({
|
||||
where: { brandId: this.brandId() },
|
||||
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
|
||||
});
|
||||
}
|
||||
@Post("trust-content")
|
||||
createTrustContent(@Req() request: FastifyRequest, @Body() body: CreateTrustContentDto): Promise<unknown> { this.requireAdmin(request); const { config, ...fields } = body; return this.prisma.trustContent.create({ data: { ...fields, brandId: this.brandId(), ...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }) } }); }
|
||||
createTrustContent(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: CreateTrustContentDto,
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const { config, ...fields } = body;
|
||||
return this.prisma.trustContent.create({
|
||||
data: {
|
||||
...fields,
|
||||
brandId: this.brandId(),
|
||||
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
||||
},
|
||||
});
|
||||
}
|
||||
@Patch("trust-content/:id")
|
||||
async updateTrustContent(@Req() request: FastifyRequest, @Param("id") id: string, @Body() body: UpdateTrustContentDto): Promise<unknown> { this.requireAdmin(request); const item = await this.prisma.trustContent.findFirst({ where: { id, brandId: this.brandId() } }); if (!item) throw new BadRequestException("信任内容不存在"); const { config, ...fields } = body; return this.prisma.trustContent.update({ where: { id }, data: { ...fields, ...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }) } }); }
|
||||
async updateTrustContent(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("id") id: string,
|
||||
@Body() body: UpdateTrustContentDto,
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const item = await this.prisma.trustContent.findFirst({
|
||||
where: { id, brandId: this.brandId() },
|
||||
});
|
||||
if (!item) throw new BadRequestException("信任内容不存在");
|
||||
const { config, ...fields } = body;
|
||||
return this.prisma.trustContent.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...fields,
|
||||
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
||||
},
|
||||
});
|
||||
}
|
||||
@Delete("trust-content/:id")
|
||||
async deleteTrustContent(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> { this.requireAdmin(request); const item = await this.prisma.trustContent.findFirst({ where: { id, brandId: this.brandId() } }); if (!item) throw new BadRequestException("信任内容不存在"); await this.prisma.trustContent.delete({ where: { id } }); return { deleted: true }; }
|
||||
async deleteTrustContent(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("id") id: string,
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const item = await this.prisma.trustContent.findFirst({
|
||||
where: { id, brandId: this.brandId() },
|
||||
});
|
||||
if (!item) throw new BadRequestException("信任内容不存在");
|
||||
await this.prisma.trustContent.delete({ where: { id } });
|
||||
return { deleted: true };
|
||||
}
|
||||
@Get("services")
|
||||
listServices(@Req() request: FastifyRequest): Promise<unknown> { this.requireAdmin(request); return this.prisma.service.findMany({ where: { brandId: this.brandId() }, orderBy: { sortOrder: "asc" } }); }
|
||||
listServices(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.prisma.service.findMany({
|
||||
where: { brandId: this.brandId() },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
});
|
||||
}
|
||||
@Post("services")
|
||||
createService(@Req() request: FastifyRequest, @Body() body: CreateServiceDto): Promise<unknown> { this.requireAdmin(request); const { config, ...fields } = body; return this.prisma.service.create({ data: { ...fields, brandId: this.brandId(), categoryKey: body.categoryKey ?? "standard", ...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }) } }); }
|
||||
createService(@Req() request: FastifyRequest, @Body() body: CreateServiceDto): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const { config, ...fields } = body;
|
||||
return this.prisma.service.create({
|
||||
data: {
|
||||
...fields,
|
||||
brandId: this.brandId(),
|
||||
categoryKey: body.categoryKey ?? "standard",
|
||||
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
||||
},
|
||||
});
|
||||
}
|
||||
@Patch("services/:id")
|
||||
async updateService(@Req() request: FastifyRequest, @Param("id") id: string, @Body() body: UpdateServiceDto): Promise<unknown> {
|
||||
async updateService(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("id") id: string,
|
||||
@Body() body: UpdateServiceDto,
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
const service = await this.prisma.service.findFirst({ where: { id, brandId: this.brandId() } });
|
||||
if (!service) throw new BadRequestException("服务不存在");
|
||||
const { config, ...fields } = body;
|
||||
return this.prisma.service.update({ where: { id }, data: { ...fields, ...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }) } });
|
||||
return this.prisma.service.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...fields,
|
||||
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,10 @@ after(async () => {
|
||||
});
|
||||
|
||||
async function request(url, options = {}) {
|
||||
return app.getHttpAdapter().getInstance().inject({ method: "GET", url, ...options });
|
||||
return app
|
||||
.getHttpAdapter()
|
||||
.getInstance()
|
||||
.inject({ method: "GET", url, ...options });
|
||||
}
|
||||
|
||||
test("health and public content are available without authentication", async () => {
|
||||
@@ -101,14 +104,20 @@ test("admin can read and update brand and service configuration", async () => {
|
||||
let createdServiceId;
|
||||
|
||||
try {
|
||||
const brand = await request("/admin/config/brand", { headers: { authorization: `Bearer ${adminToken}` } });
|
||||
const brand = await request("/admin/config/brand", {
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
assert.equal(brand.statusCode, 200);
|
||||
assert.equal(JSON.parse(brand.body).id, brandId);
|
||||
|
||||
const updatedBrand = await request("/admin/config/brand", {
|
||||
method: "PATCH",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { description: "集成测试品牌简介", contactPhone: "13800000000", templateKey: "personal" },
|
||||
payload: {
|
||||
description: "集成测试品牌简介",
|
||||
contactPhone: "13800000000",
|
||||
templateKey: "personal",
|
||||
},
|
||||
});
|
||||
assert.equal(updatedBrand.statusCode, 200);
|
||||
assert.equal(JSON.parse(updatedBrand.body).description, "集成测试品牌简介");
|
||||
@@ -123,33 +132,61 @@ test("admin can read and update brand and service configuration", async () => {
|
||||
assert.equal(JSON.parse(updatedService.body).priceText, "集成测试价格");
|
||||
assert.equal(JSON.parse(updatedService.body).sortOrder, 99);
|
||||
|
||||
const listedServices = await request("/admin/config/services", { headers: { authorization: `Bearer ${adminToken}` } });
|
||||
const listedServices = await request("/admin/config/services", {
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
assert.equal(listedServices.statusCode, 200);
|
||||
assert.ok(JSON.parse(listedServices.body).some((item) => item.id === serviceBefore.id));
|
||||
|
||||
const createdService = await request("/admin/config/services", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "集成测试通用服务", description: "通用品牌服务", categoryKey: "consulting", config: { duration: 60 } },
|
||||
payload: {
|
||||
name: "集成测试通用服务",
|
||||
description: "通用品牌服务",
|
||||
categoryKey: "consulting",
|
||||
config: { duration: 60 },
|
||||
},
|
||||
});
|
||||
assert.equal(createdService.statusCode, 201);
|
||||
createdServiceId = JSON.parse(createdService.body).id;
|
||||
assert.equal(JSON.parse(createdService.body).categoryKey, "consulting");
|
||||
} finally {
|
||||
await prisma.brandProfile.update({ where: { id: brandId }, data: { description: brandBefore.description, contactPhone: brandBefore.contactPhone, templateKey: brandBefore.templateKey } });
|
||||
await prisma.service.update({ where: { id: serviceBefore.id }, data: { priceText: serviceBefore.priceText, sortOrder: serviceBefore.sortOrder } });
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: brandId },
|
||||
data: {
|
||||
description: brandBefore.description,
|
||||
contactPhone: brandBefore.contactPhone,
|
||||
templateKey: brandBefore.templateKey,
|
||||
},
|
||||
});
|
||||
await prisma.service.update({
|
||||
where: { id: serviceBefore.id },
|
||||
data: { priceText: serviceBefore.priceText, sortOrder: serviceBefore.sortOrder },
|
||||
});
|
||||
if (createdServiceId) await prisma.service.delete({ where: { id: createdServiceId } });
|
||||
}
|
||||
});
|
||||
|
||||
test("admin can manage trust content", async () => {
|
||||
const login = await request("/admin/session/login", { method: "POST", payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD } });
|
||||
const login = await request("/admin/session/login", {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
assert.equal((await request("/admin/config/trust-content")).statusCode, 401);
|
||||
const created = await request("/admin/config/trust-content", { method: "POST", headers: { authorization: `Bearer ${token}` }, payload: { type: "profile", title: "关于我", content: "集成测试内容", summary: "测试摘要" } });
|
||||
const created = await request("/admin/config/trust-content", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { type: "profile", title: "关于我", content: "集成测试内容", summary: "测试摘要" },
|
||||
});
|
||||
assert.equal(created.statusCode, 201);
|
||||
const id = JSON.parse(created.body).id;
|
||||
const draft = await request("/admin/config/trust-content", { method: "POST", headers: { authorization: `Bearer ${token}` }, payload: { type: "experience", title: "草稿", content: "不应公开", isPublished: false } });
|
||||
const draft = await request("/admin/config/trust-content", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { type: "experience", title: "草稿", content: "不应公开", isPublished: false },
|
||||
});
|
||||
assert.equal(draft.statusCode, 201);
|
||||
const publicContent = await request("/public/trust-content");
|
||||
assert.equal(publicContent.statusCode, 200);
|
||||
@@ -157,13 +194,22 @@ test("admin can manage trust content", async () => {
|
||||
assert.ok(publicItems.some((item) => item.id === id));
|
||||
assert.ok(!publicItems.some((item) => item.id === JSON.parse(draft.body).id));
|
||||
try {
|
||||
const list = await request("/admin/config/trust-content", { headers: { authorization: `Bearer ${token}` } });
|
||||
const list = await request("/admin/config/trust-content", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(list.statusCode, 200);
|
||||
const updated = await request(`/admin/config/trust-content/${id}`, { method: "PATCH", headers: { authorization: `Bearer ${token}` }, payload: { content: "更新后的内容" } });
|
||||
const updated = await request(`/admin/config/trust-content/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { content: "更新后的内容" },
|
||||
});
|
||||
assert.equal(updated.statusCode, 200);
|
||||
assert.equal(JSON.parse(updated.body).content, "更新后的内容");
|
||||
} finally {
|
||||
const deleted = await request(`/admin/config/trust-content/${id}`, { method: "DELETE", headers: { authorization: `Bearer ${token}` } });
|
||||
const deleted = await request(`/admin/config/trust-content/${id}`, {
|
||||
method: "DELETE",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(deleted.statusCode, 200);
|
||||
await prisma.trustContent.delete({ where: { id: JSON.parse(draft.body).id } });
|
||||
}
|
||||
@@ -216,7 +262,9 @@ test("customer can create a generic inquiry without food-specific fields", async
|
||||
});
|
||||
|
||||
test("customer can create and cancel a package booking", async () => {
|
||||
const service = await prisma.service.findFirst({ where: { brandId, isEnabled: true, priceAmount: { not: null } } });
|
||||
const service = await prisma.service.findFirst({
|
||||
where: { brandId, isEnabled: true, priceAmount: { not: null } },
|
||||
});
|
||||
assert.ok(service);
|
||||
const created = await request("/customer/bookings", {
|
||||
method: "POST",
|
||||
@@ -245,7 +293,9 @@ test("customer can create and cancel a package booking", async () => {
|
||||
});
|
||||
|
||||
test("admin can advance booking status but cannot skip the state machine", async () => {
|
||||
const service = await prisma.service.findFirst({ where: { brandId, isEnabled: true, priceAmount: { not: null } } });
|
||||
const service = await prisma.service.findFirst({
|
||||
where: { brandId, isEnabled: true, priceAmount: { not: null } },
|
||||
});
|
||||
assert.ok(service);
|
||||
const created = await request("/customer/bookings", {
|
||||
method: "POST",
|
||||
@@ -258,7 +308,9 @@ test("admin can advance booking status but cannot skip the state machine", async
|
||||
items: [{ serviceId: service.id, quantity: 1 }],
|
||||
},
|
||||
});
|
||||
const booking = await prisma.booking.findUnique({ where: { bookingNo: JSON.parse(created.body).bookingNo } });
|
||||
const booking = await prisma.booking.findUnique({
|
||||
where: { bookingNo: JSON.parse(created.body).bookingNo },
|
||||
});
|
||||
assert.ok(booking);
|
||||
createdBookingIds.push(booking.id);
|
||||
|
||||
|
||||
@@ -23,11 +23,44 @@ export interface BrandProfile {
|
||||
contactWechat: string | null;
|
||||
}
|
||||
export type BrandUpdate = Partial<Omit<BrandProfile, "id">>;
|
||||
export interface ServiceUpdate { name?: string; description?: string; coverUrl?: string; priceText?: string; priceAmount?: number; sortOrder?: number; bookingEnabled?: boolean; isEnabled?: boolean; categoryKey?: string; config?: Record<string, unknown> }
|
||||
export interface TrustContent { id: string; type: string; title: string; summary?: string | null; content: string; coverUrl?: string | null; sortOrder: number; isPublished: boolean; config?: Record<string, unknown> | null }
|
||||
export interface TrustContentInput { type: string; title: string; summary?: string; content: string; coverUrl?: string; sortOrder?: number; isPublished?: boolean; config?: Record<string, unknown> }
|
||||
export interface ServiceUpdate {
|
||||
name?: string;
|
||||
description?: string;
|
||||
coverUrl?: string;
|
||||
priceText?: string;
|
||||
priceAmount?: number;
|
||||
sortOrder?: number;
|
||||
bookingEnabled?: boolean;
|
||||
isEnabled?: boolean;
|
||||
categoryKey?: string;
|
||||
config?: Record<string, unknown>;
|
||||
}
|
||||
export interface TrustContent {
|
||||
id: string;
|
||||
type: string;
|
||||
title: string;
|
||||
summary?: string | null;
|
||||
content: string;
|
||||
coverUrl?: string | null;
|
||||
sortOrder: number;
|
||||
isPublished: boolean;
|
||||
config?: Record<string, unknown> | null;
|
||||
}
|
||||
export interface TrustContentInput {
|
||||
type: string;
|
||||
title: string;
|
||||
summary?: string;
|
||||
content: string;
|
||||
coverUrl?: string;
|
||||
sortOrder?: number;
|
||||
isPublished?: boolean;
|
||||
config?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BookingItemInput { serviceId: string; quantity: number }
|
||||
export interface BookingItemInput {
|
||||
serviceId: string;
|
||||
quantity: number;
|
||||
}
|
||||
export interface CreateBookingInput {
|
||||
requestType: BookingRequestType;
|
||||
customerName: string;
|
||||
@@ -43,24 +76,62 @@ export interface CreateBookingInput {
|
||||
extraData?: Record<string, unknown>;
|
||||
items: BookingItemInput[];
|
||||
}
|
||||
export interface BookingSummary { bookingNo: string; status: BookingStatus; estimatedAmount: number | null; createdAt: string }
|
||||
export interface Booking extends BookingSummary { id: string; customerName: string; adminNote?: string | null }
|
||||
export interface BookingTag { id: string; name: string; isPreset: boolean; isEnabled: boolean }
|
||||
export interface AdminBooking extends Booking { tags?: Array<{ tag: BookingTag }> }
|
||||
export interface ApiErrorBody { data: null; error: { code: string; message: string }; requestId: string | null }
|
||||
export interface BookingSummary {
|
||||
bookingNo: string;
|
||||
status: BookingStatus;
|
||||
estimatedAmount: number | null;
|
||||
createdAt: string;
|
||||
}
|
||||
export interface Booking extends BookingSummary {
|
||||
id: string;
|
||||
customerName: string;
|
||||
adminNote?: string | null;
|
||||
}
|
||||
export interface BookingTag {
|
||||
id: string;
|
||||
name: string;
|
||||
isPreset: boolean;
|
||||
isEnabled: boolean;
|
||||
}
|
||||
export interface AdminBooking extends Booking {
|
||||
tags?: Array<{ tag: BookingTag }>;
|
||||
}
|
||||
export interface ApiErrorBody {
|
||||
data: null;
|
||||
error: { code: string; message: string };
|
||||
requestId: string | null;
|
||||
}
|
||||
|
||||
export class ApiClientError extends Error {
|
||||
constructor(readonly status: number, readonly body: ApiErrorBody) {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly body: ApiErrorBody,
|
||||
) {
|
||||
super(body.error.message);
|
||||
this.name = "ApiClientError";
|
||||
}
|
||||
get code(): string { return this.body.error.code; }
|
||||
get requestId(): string | null { return this.body.requestId; }
|
||||
get code(): string {
|
||||
return this.body.error.code;
|
||||
}
|
||||
get requestId(): string | null {
|
||||
return this.body.requestId;
|
||||
}
|
||||
}
|
||||
|
||||
export interface FetchResponse { readonly status: number; readonly ok: boolean; json(): Promise<unknown> }
|
||||
export type FetchLike = (input: string, init?: { method?: string; headers?: Record<string, string>; body?: string }) => Promise<FetchResponse>;
|
||||
export interface ApiClientOptions { baseUrl: string; fetcher: FetchLike; token?: string }
|
||||
export interface FetchResponse {
|
||||
readonly status: number;
|
||||
readonly ok: boolean;
|
||||
json(): Promise<unknown>;
|
||||
}
|
||||
export type FetchLike = (
|
||||
input: string,
|
||||
init?: { method?: string; headers?: Record<string, string>; body?: string },
|
||||
) => Promise<FetchResponse>;
|
||||
export interface ApiClientOptions {
|
||||
baseUrl: string;
|
||||
fetcher: FetchLike;
|
||||
token?: string;
|
||||
}
|
||||
|
||||
export class ApiClient {
|
||||
private readonly baseUrl: string;
|
||||
@@ -72,13 +143,21 @@ export class ApiClient {
|
||||
this.fetcher = options.fetcher;
|
||||
this.token = options.token;
|
||||
}
|
||||
setToken(token: string | undefined): void { this.token = token; }
|
||||
getBrand(): Promise<BrandProfile> { return this.request("/public/brand"); }
|
||||
listServices(): Promise<PublicService[]> { return this.request("/public/services"); }
|
||||
setToken(token: string | undefined): void {
|
||||
this.token = token;
|
||||
}
|
||||
getBrand(): Promise<BrandProfile> {
|
||||
return this.request("/public/brand");
|
||||
}
|
||||
listServices(): Promise<PublicService[]> {
|
||||
return this.request("/public/services");
|
||||
}
|
||||
createCustomerSession(code: string): Promise<{ token: string }> {
|
||||
return this.request("/customer/session/wechat", { method: "POST", body: { code } });
|
||||
}
|
||||
listCustomerBookings(): Promise<Booking[]> { return this.request("/customer/bookings"); }
|
||||
listCustomerBookings(): Promise<Booking[]> {
|
||||
return this.request("/customer/bookings");
|
||||
}
|
||||
createCustomerBooking(input: CreateBookingInput): Promise<BookingSummary> {
|
||||
return this.request("/customer/bookings", { method: "POST", body: input });
|
||||
}
|
||||
@@ -88,7 +167,9 @@ export class ApiClient {
|
||||
loginAdmin(username: string, password: string): Promise<{ token: string; displayName: string }> {
|
||||
return this.request("/admin/session/login", { method: "POST", body: { username, password } });
|
||||
}
|
||||
listAdminBookings(filters: { status?: BookingStatus; unreadOnly?: boolean; tagId?: string } = {}): Promise<AdminBooking[]> {
|
||||
listAdminBookings(
|
||||
filters: { status?: BookingStatus; unreadOnly?: boolean; tagId?: string } = {},
|
||||
): Promise<AdminBooking[]> {
|
||||
const params: string[] = [];
|
||||
if (filters.status) params.push(`status=${encodeURIComponent(filters.status)}`);
|
||||
if (filters.unreadOnly !== undefined) params.push(`unreadOnly=${filters.unreadOnly}`);
|
||||
@@ -96,28 +177,72 @@ export class ApiClient {
|
||||
const query = params.join("&");
|
||||
return this.request(`/admin/bookings${query ? `?${query}` : ""}`);
|
||||
}
|
||||
getAdminBooking(id: string): Promise<AdminBooking> { return this.request(`/admin/bookings/${encodeURIComponent(id)}`); }
|
||||
getAdminUnreadCount(): Promise<{ count: number }> { return this.request("/admin/bookings/unread-count"); }
|
||||
updateAdminBookingStatus(id: string, status: BookingStatus, adminNote?: string): Promise<Booking> {
|
||||
return this.request(`/admin/bookings/${encodeURIComponent(id)}/status`, { method: "POST", body: { status, ...(adminNote === undefined ? {} : { adminNote }) } });
|
||||
getAdminBooking(id: string): Promise<AdminBooking> {
|
||||
return this.request(`/admin/bookings/${encodeURIComponent(id)}`);
|
||||
}
|
||||
getAdminUnreadCount(): Promise<{ count: number }> {
|
||||
return this.request("/admin/bookings/unread-count");
|
||||
}
|
||||
updateAdminBookingStatus(
|
||||
id: string,
|
||||
status: BookingStatus,
|
||||
adminNote?: string,
|
||||
): Promise<Booking> {
|
||||
return this.request(`/admin/bookings/${encodeURIComponent(id)}/status`, {
|
||||
method: "POST",
|
||||
body: { status, ...(adminNote === undefined ? {} : { adminNote }) },
|
||||
});
|
||||
}
|
||||
markAdminBookingRead(id: string): Promise<Booking> {
|
||||
return this.request(`/admin/bookings/${encodeURIComponent(id)}/read`, { method: "POST" });
|
||||
}
|
||||
listAdminTags(): Promise<BookingTag[]> { return this.request("/admin/bookings/tags"); }
|
||||
listAdminTags(): Promise<BookingTag[]> {
|
||||
return this.request("/admin/bookings/tags");
|
||||
}
|
||||
createAdminTag(name: string): Promise<BookingTag> {
|
||||
return this.request("/admin/bookings/tags", { method: "POST", body: { name } });
|
||||
}
|
||||
getAdminBrand(): Promise<BrandProfile> { return this.request("/admin/config/brand"); }
|
||||
updateAdminBrand(body: BrandUpdate): Promise<BrandProfile> { return this.request("/admin/config/brand", { method: "PATCH", body }); }
|
||||
updateAdminService(id: string, body: ServiceUpdate): Promise<PublicService> { return this.request(`/admin/config/services/${encodeURIComponent(id)}`, { method: "PATCH", body }); }
|
||||
listAdminServices(): Promise<PublicService[]> { return this.request("/admin/config/services"); }
|
||||
createAdminService(body: ServiceUpdate & { name: string; description: string }): Promise<PublicService> { return this.request("/admin/config/services", { method: "POST", body }); }
|
||||
listAdminTrustContent(): Promise<TrustContent[]> { return this.request("/admin/config/trust-content"); }
|
||||
createAdminTrustContent(body: TrustContentInput): Promise<TrustContent> { return this.request("/admin/config/trust-content", { method: "POST", body }); }
|
||||
updateAdminTrustContent(id: string, body: Partial<TrustContentInput>): Promise<TrustContent> { return this.request(`/admin/config/trust-content/${encodeURIComponent(id)}`, { method: "PATCH", body }); }
|
||||
deleteAdminTrustContent(id: string): Promise<{ deleted: boolean }> { return this.request(`/admin/config/trust-content/${encodeURIComponent(id)}`, { method: "DELETE" }); }
|
||||
private async request<T>(path: string, options: { method?: string; body?: unknown } = {}): Promise<T> {
|
||||
getAdminBrand(): Promise<BrandProfile> {
|
||||
return this.request("/admin/config/brand");
|
||||
}
|
||||
updateAdminBrand(body: BrandUpdate): Promise<BrandProfile> {
|
||||
return this.request("/admin/config/brand", { method: "PATCH", body });
|
||||
}
|
||||
updateAdminService(id: string, body: ServiceUpdate): Promise<PublicService> {
|
||||
return this.request(`/admin/config/services/${encodeURIComponent(id)}`, {
|
||||
method: "PATCH",
|
||||
body,
|
||||
});
|
||||
}
|
||||
listAdminServices(): Promise<PublicService[]> {
|
||||
return this.request("/admin/config/services");
|
||||
}
|
||||
createAdminService(
|
||||
body: ServiceUpdate & { name: string; description: string },
|
||||
): Promise<PublicService> {
|
||||
return this.request("/admin/config/services", { method: "POST", body });
|
||||
}
|
||||
listAdminTrustContent(): Promise<TrustContent[]> {
|
||||
return this.request("/admin/config/trust-content");
|
||||
}
|
||||
createAdminTrustContent(body: TrustContentInput): Promise<TrustContent> {
|
||||
return this.request("/admin/config/trust-content", { method: "POST", body });
|
||||
}
|
||||
updateAdminTrustContent(id: string, body: Partial<TrustContentInput>): Promise<TrustContent> {
|
||||
return this.request(`/admin/config/trust-content/${encodeURIComponent(id)}`, {
|
||||
method: "PATCH",
|
||||
body,
|
||||
});
|
||||
}
|
||||
deleteAdminTrustContent(id: string): Promise<{ deleted: boolean }> {
|
||||
return this.request(`/admin/config/trust-content/${encodeURIComponent(id)}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
}
|
||||
private async request<T>(
|
||||
path: string,
|
||||
options: { method?: string; body?: unknown } = {},
|
||||
): Promise<T> {
|
||||
const headers: Record<string, string> = { accept: "application/json" };
|
||||
if (options.body !== undefined) headers["content-type"] = "application/json";
|
||||
if (this.token) headers.authorization = `Bearer ${this.token}`;
|
||||
|
||||
@@ -4,7 +4,10 @@ export type ContactPreference = "wechat" | "phone" | "none";
|
||||
export type FulfillmentType = "pickup" | "delivery";
|
||||
export type OrderStatus = BookingStatus;
|
||||
export type BrandTemplateKey = "food" | "personal";
|
||||
export const BRAND_TEMPLATE = { FOOD: "food", PERSONAL: "personal" } as const satisfies Record<Uppercase<BrandTemplateKey>, BrandTemplateKey>;
|
||||
export const BRAND_TEMPLATE = { FOOD: "food", PERSONAL: "personal" } as const satisfies Record<
|
||||
Uppercase<BrandTemplateKey>,
|
||||
BrandTemplateKey
|
||||
>;
|
||||
|
||||
export const HTTP_STATUS = {
|
||||
OK: 200,
|
||||
|
||||
Reference in new issue
Block a user