diff --git a/apps/admin/src/entry.ts b/apps/admin/src/entry.ts index 06fda3c..d85f9f5 100644 --- a/apps/admin/src/entry.ts +++ b/apps/admin/src/entry.ts @@ -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); } diff --git a/apps/admin/src/main.ts b/apps/admin/src/main.ts index 5b44bbd..78c7671 100644 --- a/apps/admin/src/main.ts +++ b/apps/admin/src/main.ts @@ -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 { 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 = `

品牌后台

未读订单:${unread.count}

品牌配置

服务配置

选择订单查看详情
`; 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("[data-service-save]").forEach((item) => item.addEventListener("click", () => void this.saveService(item.dataset.serviceSave))); - root.querySelectorAll("[data-id]").forEach((item) => item.addEventListener("click", () => this.select(item.dataset.id))); + root + .querySelectorAll("[data-service-save]") + .forEach((item) => + item.addEventListener("click", () => void this.saveService(item.dataset.serviceSave)), + ); + root + .querySelectorAll("[data-id]") + .forEach((item) => item.addEventListener("click", () => this.select(item.dataset.id))); } - private listHtml(): string { return this.bookings.map((item) => `
  • `).join("") || "
  • 暂无订单
  • "; } - private async filter(): Promise { 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 = `

    ${this.selected.bookingNo}

    客户:${this.selected.customerName}

    `; detail.querySelector("#save")?.addEventListener("click", () => void this.save()); } - private async save(): Promise { 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 { 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 { 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) => + `
  • `, + ) + .join("") || "
  • 暂无订单
  • " + ); + } + private async filter(): Promise { + 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 = `

    ${this.selected.bookingNo}

    客户:${this.selected.customerName}

    `; + detail.querySelector("#save")?.addEventListener("click", () => void this.save()); + } + private async save(): Promise { + 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 { + 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 { + 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; diff --git a/apps/admin/src/main.tsx b/apps/admin/src/main.tsx index b029670..0e3e67a 100644 --- a/apps/admin/src/main.tsx +++ b/apps/admin/src/main.tsx @@ -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
    ; + 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 ( + +
    + + + + + + + +
    +
    + ); } function BrandPage() { - const client = api(); const queryClientHook = useQueryClient(); const [form] = Form.useForm(); + const client = api(); + const queryClientHook = useQueryClient(); + const [form] = Form.useForm(); const brand = useQuery({ queryKey: ["admin-brand"], queryFn: () => client.getAdminBrand() }); - const save = useMutation({ mutationFn: (values: Partial) => client.updateAdminBrand(values), onSuccess: () => { message.success("品牌配置已保存"); void queryClientHook.invalidateQueries({ queryKey: ["admin-brand"] }); } }); + const save = useMutation({ + mutationFn: (values: Partial) => client.updateAdminBrand(values), + onSuccess: () => { + message.success("品牌配置已保存"); + void queryClientHook.invalidateQueries({ queryKey: ["admin-brand"] }); + }, + }); if (brand.isLoading) return ; if (brand.isError || !brand.data) return 品牌配置加载失败; - return
    save.mutate(values)}>
    ; + return ( + +
    save.mutate(values)} + > + + + + + + + + + + + + + + + + + + + + + + +
    +
    + ); } function TrustContentPage() { - const client = api(); const queryClientHook = useQueryClient(); const [editing, setEditing] = useState(null); const [modalOpen, setModalOpen] = useState(false); const [form] = Form.useForm(); - 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 open()}>新增内容}>{value} }, { title: "标题", dataIndex: "title" }, { title: "状态", dataIndex: "isPublished", render: (value) => value ? "已发布" : "草稿" }, { title: "操作", render: (_: unknown, item: TrustContent) => remove.mutate(item.id)}> }]} /> { setModalOpen(false); setEditing(null); form.resetFields(); }} onOk={() => form.submit()} confirmLoading={save.isPending}>
    save.mutate(values)}>
    {value} }, + { title: "标题", dataIndex: "title" }, + { + title: "状态", + dataIndex: "isPublished", + render: (value) => (value ? "已发布" : "草稿"), + }, + { + title: "操作", + render: (_: unknown, item: TrustContent) => ( + + + remove.mutate(item.id)}> + + + + ), + }, + ]} + />{" "} + { + setModalOpen(false); + setEditing(null); + form.resetFields(); + }} + onOk={() => form.submit()} + confirmLoading={save.isPending} + > + save.mutate(values)}> + + + + + + + + + + +
    {value} }, { title: "价格展示", dataIndex: "priceText" }, { title: "状态", dataIndex: "isEnabled", render: (value) => value ? "已上架" : "已下架" }, { title: "操作", render: (_: unknown, item: PublicService) => }]} /> { setModalOpen(false); setEditing(null); form.resetFields(); }} onOk={() => form.submit()} confirmLoading={save.isPending}> save.mutate(values)}>; + const client = api(); + const queryClientHook = useQueryClient(); + const [editing, setEditing] = useState(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) => + 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 ( + open()}> + 新增服务 + + } + > +
    {value} }, + { title: "价格展示", dataIndex: "priceText" }, + { + title: "状态", + dataIndex: "isEnabled", + render: (value) => (value ? "已上架" : "已下架"), + }, + { + title: "操作", + render: (_: unknown, item: PublicService) => ( + + + + + ), + }, + ]} + /> + { + setModalOpen(false); + setEditing(null); + form.resetFields(); + }} + onOk={() => form.submit()} + confirmLoading={save.isPending} + > +
    save.mutate(values)}> + + + + + + + + + + + + + + + + + + + +
    + + ); } -const bookingStatusOptions = ["received", "contacting", "confirmed", "completed", "cancelled"] as const; -const bookingStatusLabels: Record = { received: "待处理", contacting: "沟通中", confirmed: "已确认", completed: "已完成", cancelled: "已取消" }; +const bookingStatusOptions = [ + "received", + "contacting", + "confirmed", + "completed", + "cancelled", +] as const; +const bookingStatusLabels: Record = { + received: "待处理", + contacting: "沟通中", + confirmed: "已确认", + completed: "已完成", + cancelled: "已取消", +}; function InquiriesPage() { - const client = api(); const queryClientHook = useQueryClient(); + const client = api(); + const queryClientHook = useQueryClient(); const [status, setStatus] = useState(); - 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
    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) => {bookingStatusLabels[value] ?? value} }, { title: "操作", render: (_: unknown, item: AdminBooking) => ({ + value, + label: bookingStatusLabels[value], + }))} + /> + !(item as AdminBooking & { isRead?: boolean }).isRead) + .length ?? 0 + } + showZero + /> + + } + > +
    + 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) => ( + + {bookingStatusLabels[value] ?? value} + + ), + }, + { + title: "操作", + render: (_: unknown, item: AdminBooking) => ( + +