fix: 修复后台配置接口与管理后台高优先级问题

This commit is contained in:
que01 committed 2026-09-19 18:20:51 +08:00
1 parent 69bbeb1b1b
commit c393a5231e
6 files changed
+53 -14

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@ 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: "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);
}
+3 -3
View File
@@ -6,7 +6,7 @@ import { ApiClient } from "@personal-brand/api-client";
import type { BrandProfile, PublicService, TrustContent, TrustContentInput } from "@personal-brand/api-client";
import "antd/dist/reset.css";
const apiBaseUrl = "http://localhost:3001";
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL ?? "http://localhost:3001";
const queryClient = new QueryClient();
const api = () => new ApiClient({ baseUrl: apiBaseUrl, token: localStorage.getItem("adminToken") ?? undefined, fetcher: (input, init) => fetch(input, init) });
@@ -29,10 +29,10 @@ function BrandPage() {
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("信任内容已保存"); setEditing(null); form.resetFields(); void queryClientHook.invalidateQueries({ queryKey: ["trust-content"] }); } });
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); setModalOpen(false); }}><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>;
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() {
+7
View File
@@ -0,0 +1,7 @@
interface ImportMetaEnv {
readonly VITE_API_BASE_URL?: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
+11
View File
@@ -51,6 +51,17 @@ export class CreateTrustContentDto {
@IsOptional() config?: Record<string, unknown>;
}
export class UpdateTrustContentDto {
@IsOptional() @IsIn(["profile", "experience", "credential", "portfolio", "process", "testimonial"]) type?: string;
@IsOptional() @IsString() title?: string;
@IsOptional() @IsString() summary?: string;
@IsOptional() @IsString() content?: string;
@IsOptional() @IsString() coverUrl?: string;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() @IsBoolean() isPublished?: boolean;
@IsOptional() config?: Record<string, unknown>;
}
export class UpdateBookingStatusDto {
@IsIn(["received", "contacting", "confirmed", "completed", "cancelled"])
status!: "received" | "contacting" | "confirmed" | "completed" | "cancelled";
+20 -7
View File
@@ -1,6 +1,8 @@
import "reflect-metadata";
import {
BadRequestException,
UnauthorizedException,
ForbiddenException,
Body,
Controller,
Delete,
@@ -21,7 +23,7 @@ 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 } 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";
@@ -83,6 +85,13 @@ export class PublicController {
}
}
@Controller("public/trust-content")
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" }] }); }
}
@Controller("customer/session")
export class CustomerSessionController {
constructor(
@@ -278,9 +287,10 @@ export class AdminBookingController {
private requireAdmin(request: FastifyRequest): void {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new BadRequestException("缺少管理员登录态");
const identity = readIdentity(token);
if (identity.role !== "admin") throw new BadRequestException("无管理员权限");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
try { identity = readIdentity(token); } catch { throw new UnauthorizedException("管理员登录态无效或已过期"); }
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
}
}
@@ -290,8 +300,10 @@ export class AdminConfigController {
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 BadRequestException("缺少管理员登录态");
if (readIdentity(token).role !== "admin") throw new BadRequestException("无管理员权限");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
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() } }); }
@@ -302,7 +314,7 @@ export class AdminConfigController {
@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 }) } }); }
@Patch("trust-content/:id")
async updateTrustContent(@Req() request: FastifyRequest, @Param("id") id: string, @Body() body: Partial<CreateTrustContentDto>): 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 }; }
@Get("services")
@@ -323,6 +335,7 @@ export class AdminConfigController {
controllers: [
HealthController,
PublicController,
PublicTrustContentController,
CustomerSessionController,
AdminSessionController,
CustomerBookingController,
+11 -3
View File
@@ -45,7 +45,7 @@ test("health and public content are available without authentication", async ()
test("admin booking endpoints reject missing or customer credentials", async () => {
const missing = await request("/admin/bookings");
assert.equal(missing.statusCode, 400);
assert.equal(missing.statusCode, 401);
const customer = await request("/admin/bookings", {
headers: { authorization: "Bearer invalid-token" },
@@ -92,7 +92,7 @@ test("admin can read and update brand and service configuration", async () => {
assert.ok(adminToken);
const unauthorized = await request("/admin/config/brand");
assert.equal(unauthorized.statusCode, 400);
assert.equal(unauthorized.statusCode, 401);
const brandBefore = await prisma.brandProfile.findUnique({ where: { id: brandId } });
assert.ok(brandBefore);
@@ -145,10 +145,17 @@ test("admin can read and update brand and service configuration", async () => {
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 token = JSON.parse(login.body).token;
assert.equal((await request("/admin/config/trust-content")).statusCode, 400);
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: "测试摘要" } });
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 } });
assert.equal(draft.statusCode, 201);
const publicContent = await request("/public/trust-content");
assert.equal(publicContent.statusCode, 200);
const publicItems = JSON.parse(publicContent.body);
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}` } });
assert.equal(list.statusCode, 200);
@@ -158,6 +165,7 @@ test("admin can manage trust content", async () => {
} finally {
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 } });
}
});