feat: 增加多品牌切换并继续拆分控制器
This commit is contained in:
1 parent
f4a93bba23
commit
045472035b
7 files changed
+126
-3
No files matched your search
@@ -3,7 +3,7 @@
|
|||||||
- 任务:多品牌后台与 API 架构收口
|
- 任务:多品牌后台与 API 架构收口
|
||||||
- 形态:epic
|
- 形态:epic
|
||||||
- 进度:1/3
|
- 进度:1/3
|
||||||
- 当前:API Controller 拆分(已完成 session 模块第一批迁移,继续拆分中)
|
- 当前:API Controller 拆分(已完成 session、customer booking、admin booking;继续拆分 public 和 admin config)
|
||||||
- 真相文件:`SUBTASKS.csv`
|
- 真相文件:`SUBTASKS.csv`
|
||||||
|
|
||||||
## 已完成
|
## 已完成
|
||||||
@@ -14,3 +14,4 @@
|
|||||||
- `CustomerSessionController` 和 `AdminSessionController` 已迁移到 `modules/session/session.controller.ts`。
|
- `CustomerSessionController` 和 `AdminSessionController` 已迁移到 `modules/session/session.controller.ts`。
|
||||||
- `AdminBookingController` 已迁移到 `modules/admin/admin-booking.controller.ts`。
|
- `AdminBookingController` 已迁移到 `modules/admin/admin-booking.controller.ts`。
|
||||||
- `CustomerBookingController` 已迁移到 `modules/customer/customer-booking.controller.ts`。
|
- `CustomerBookingController` 已迁移到 `modules/customer/customer-booking.controller.ts`。
|
||||||
|
- 新增 `GET /admin/brands` 和 `POST /admin/brands/:brandId/switch`,切换由 membership 服务端校验。
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes
|
id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes
|
||||||
1,当前品牌工作区语义,single-full,,DONE,tasks/admin-context,后台明确当前品牌并保持 membership 隔离,pnpm --filter @personal-brand/admin build && pnpm --filter @personal-brand/api test:integration,已完成
|
1,当前品牌工作区语义,single-full,,DONE,tasks/admin-context,后台明确当前品牌并保持 membership 隔离,pnpm --filter @personal-brand/admin build && pnpm --filter @personal-brand/api test:integration,已完成
|
||||||
2,API Controller 拆分,single-full,1,TODO,tasks/api-split,main.ts 仅保留装配和跨模块基础代码,pnpm --filter @personal-brand/api typecheck && pnpm --filter @personal-brand/api test:integration,
|
2,API Controller 拆分,single-full,1,IN_PROGRESS,tasks/api-split,main.ts 仅保留装配和跨模块基础代码,pnpm --filter @personal-brand/api typecheck && pnpm --filter @personal-brand/api test:integration,已拆分 session、customer booking、admin booking;public 和 admin config 仍待拆分
|
||||||
3,架构回归收口,single-full,2,TODO,tasks/regression,Admin 和 miniapp 回归全部通过,pnpm --filter @personal-brand/admin build && pnpm --filter @personal-brand/miniapp test:fixture,
|
3,架构回归收口,single-full,2,TODO,tasks/regression,Admin 和 miniapp 回归全部通过,pnpm --filter @personal-brand/admin build && pnpm --filter @personal-brand/miniapp test:fixture,
|
||||||
|
+36
-1
@@ -2,7 +2,19 @@ import React, { Suspense, useState } from "react";
|
|||||||
import { createRoot } from "react-dom/client";
|
import { createRoot } from "react-dom/client";
|
||||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { App, Button, Card, Form, Input, Layout, Menu, Space, Typography, message } from "antd";
|
import {
|
||||||
|
App,
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
Layout,
|
||||||
|
Menu,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Typography,
|
||||||
|
message,
|
||||||
|
} from "antd";
|
||||||
import { createApiClient } from "./lib/api.js";
|
import { createApiClient } from "./lib/api.js";
|
||||||
const FeatureInquiriesPage = React.lazy(() =>
|
const FeatureInquiriesPage = React.lazy(() =>
|
||||||
import("./features/inquiries/InquiriesPage.js").then((module) => ({
|
import("./features/inquiries/InquiriesPage.js").then((module) => ({
|
||||||
@@ -82,6 +94,19 @@ function Dashboard({ onLogout }: { onLogout: () => void }) {
|
|||||||
queryKey: ["admin-shell-brand"],
|
queryKey: ["admin-shell-brand"],
|
||||||
queryFn: () => createApiClient().getAdminBrand(),
|
queryFn: () => createApiClient().getAdminBrand(),
|
||||||
});
|
});
|
||||||
|
const memberships = useQuery({
|
||||||
|
queryKey: ["admin-brand-memberships"],
|
||||||
|
queryFn: () => createApiClient().listAdminBrands(),
|
||||||
|
});
|
||||||
|
const switchBrand = async (brandId: string) => {
|
||||||
|
try {
|
||||||
|
const result = await createApiClient().switchAdminBrand(brandId);
|
||||||
|
localStorage.setItem("adminToken", result.token);
|
||||||
|
window.location.reload();
|
||||||
|
} catch (error) {
|
||||||
|
message.error(error instanceof Error ? error.message : "品牌切换失败");
|
||||||
|
}
|
||||||
|
};
|
||||||
const page = location.pathname.split("/")[2] || "overview";
|
const page = location.pathname.split("/")[2] || "overview";
|
||||||
const items = [
|
const items = [
|
||||||
{ key: "overview", label: "当前品牌概览" },
|
{ key: "overview", label: "当前品牌概览" },
|
||||||
@@ -117,6 +142,16 @@ function Dashboard({ onLogout }: { onLogout: () => void }) {
|
|||||||
<Space>
|
<Space>
|
||||||
<Typography.Text strong>{brand.data?.name || "当前品牌"}</Typography.Text>
|
<Typography.Text strong>{brand.data?.name || "当前品牌"}</Typography.Text>
|
||||||
<Typography.Text type="secondary">品牌工作区</Typography.Text>
|
<Typography.Text type="secondary">品牌工作区</Typography.Text>
|
||||||
|
<Select
|
||||||
|
size="small"
|
||||||
|
value={brand.data?.id}
|
||||||
|
loading={memberships.isLoading}
|
||||||
|
onChange={(value) => void switchBrand(value)}
|
||||||
|
options={(memberships.data ?? []).map((item) => ({
|
||||||
|
value: item.brand.id,
|
||||||
|
label: item.brand.name,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
</Space>
|
</Space>
|
||||||
<Button type="text" onClick={onLogout}>
|
<Button type="text" onClick={onLogout}>
|
||||||
退出登录
|
退出登录
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ import {
|
|||||||
} from "./modules/session/session.controller.js";
|
} from "./modules/session/session.controller.js";
|
||||||
import { AdminBookingController } from "./modules/admin/admin-booking.controller.js";
|
import { AdminBookingController } from "./modules/admin/admin-booking.controller.js";
|
||||||
import { CustomerBookingController } from "./modules/customer/customer-booking.controller.js";
|
import { CustomerBookingController } from "./modules/customer/customer-booking.controller.js";
|
||||||
|
import { TenantController } from "./modules/tenant/tenant.controller.js";
|
||||||
import type {
|
import type {
|
||||||
RuntimeInquiryField,
|
RuntimeInquiryField,
|
||||||
RuntimeOffering,
|
RuntimeOffering,
|
||||||
@@ -830,6 +831,7 @@ export class AdminConfigController {
|
|||||||
CustomerSessionController,
|
CustomerSessionController,
|
||||||
AdminSessionController,
|
AdminSessionController,
|
||||||
CustomerBookingController,
|
CustomerBookingController,
|
||||||
|
TenantController,
|
||||||
AdminBookingController,
|
AdminBookingController,
|
||||||
AdminConfigController,
|
AdminConfigController,
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
ForbiddenException,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Req,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import type { FastifyRequest } from "fastify";
|
||||||
|
import { PrismaService } from "../../prisma.service.js";
|
||||||
|
import { readIdentity, signIdentity } from "../../auth.js";
|
||||||
|
|
||||||
|
@Controller("admin/brands")
|
||||||
|
export class TenantController {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
async list(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
|
const identity = this.adminIdentity(request);
|
||||||
|
return this.prisma.brandMembership.findMany({
|
||||||
|
where: { adminUserId: identity.subject, isEnabled: true },
|
||||||
|
include: { brand: { select: { id: true, slug: true, name: true, templateKey: true } } },
|
||||||
|
orderBy: { createdAt: "asc" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post(":brandId/switch")
|
||||||
|
async switchBrand(
|
||||||
|
@Req() request: FastifyRequest,
|
||||||
|
@Param("brandId") brandId: string,
|
||||||
|
): Promise<{ token: string; brand: unknown }> {
|
||||||
|
const identity = this.adminIdentity(request);
|
||||||
|
const membership = await this.prisma.brandMembership.findFirst({
|
||||||
|
where: { adminUserId: identity.subject, brandId, isEnabled: true },
|
||||||
|
include: { brand: { select: { id: true, slug: true, name: true, templateKey: true } } },
|
||||||
|
});
|
||||||
|
if (!membership) throw new ForbiddenException("没有该品牌的管理权限");
|
||||||
|
return {
|
||||||
|
token: signIdentity({ subject: identity.subject, brandId, role: "admin" }),
|
||||||
|
brand: membership.brand,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private adminIdentity(request: FastifyRequest) {
|
||||||
|
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||||
|
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||||
|
const identity = readIdentity(token);
|
||||||
|
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||||
|
return identity;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -769,6 +769,25 @@ test("admin login validates credentials", async () => {
|
|||||||
assert.equal(response.statusCode, 401);
|
assert.equal(response.statusCode, 401);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("admin can list and switch only enabled brand memberships", 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;
|
||||||
|
const brands = await request("/admin/brands", {
|
||||||
|
headers: { authorization: `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
assert.equal(brands.statusCode, 200);
|
||||||
|
const memberships = JSON.parse(brands.body);
|
||||||
|
assert.ok(memberships.some((item) => item.brand.id === brandId));
|
||||||
|
const denied = await request("/admin/brands/00000000-0000-0000-0000-000000000000/switch", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { authorization: `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
assert.equal(denied.statusCode, 403);
|
||||||
|
});
|
||||||
|
|
||||||
test("disabled brand membership blocks existing admin token", async () => {
|
test("disabled brand membership blocks existing admin token", async () => {
|
||||||
const login = await request("/admin/session/login", {
|
const login = await request("/admin/session/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
|||||||
@@ -25,6 +25,11 @@ export interface BrandProfile {
|
|||||||
contactWechat: string | null;
|
contactWechat: string | null;
|
||||||
config?: Record<string, unknown> | null;
|
config?: Record<string, unknown> | null;
|
||||||
}
|
}
|
||||||
|
export interface AdminBrandMembership {
|
||||||
|
id: string;
|
||||||
|
role: string;
|
||||||
|
brand: Pick<BrandProfile, "id" | "name" | "templateKey"> & { slug?: string };
|
||||||
|
}
|
||||||
export type BrandUpdate = Partial<Omit<BrandProfile, "id">>;
|
export type BrandUpdate = Partial<Omit<BrandProfile, "id">>;
|
||||||
export interface OfferingUpdate {
|
export interface OfferingUpdate {
|
||||||
name?: string;
|
name?: string;
|
||||||
@@ -398,6 +403,14 @@ export class ApiClient {
|
|||||||
getAdminBrand(): Promise<BrandProfile> {
|
getAdminBrand(): Promise<BrandProfile> {
|
||||||
return this.request("/admin/config/brand");
|
return this.request("/admin/config/brand");
|
||||||
}
|
}
|
||||||
|
listAdminBrands(): Promise<AdminBrandMembership[]> {
|
||||||
|
return this.request("/admin/brands");
|
||||||
|
}
|
||||||
|
switchAdminBrand(
|
||||||
|
brandId: string,
|
||||||
|
): Promise<{ token: string; brand: AdminBrandMembership["brand"] }> {
|
||||||
|
return this.request(`/admin/brands/${encodeURIComponent(brandId)}/switch`, { method: "POST" });
|
||||||
|
}
|
||||||
getAdminVisualTemplatePreview(): Promise<{
|
getAdminVisualTemplatePreview(): Promise<{
|
||||||
current: {
|
current: {
|
||||||
key: string;
|
key: string;
|
||||||
|
|||||||
Reference in new issue
Block a user