背景:
- A1 只实现了部门树读取与新建 / 改名接口,没有部门管理入口,
负责人、排序、停用状态都无法维护;
- 用户必须关联部门,部门无法维护会让 A2 的数据范围缺少组织基础。
改动:
- shared:DepartmentNode 增加 status / sortOrder / directMemberCount;
新增 createDepartmentInput / updateDepartmentInput / departmentTreeQuery 契约;
- api:GET /departments/tree?include_disabled;POST/PATCH /departments
(名称 / 负责人 / 排序);POST /departments/{id}/disable|enable;
只停用不删除,有在职成员 / 启用子部门 / 下级在职成员时禁止停用;
新建 / 编辑用户校验部门必须启用;@Audit 与 OpenAPI 同步;
- web:管理中心新增「部门管理」/system/departments,左两级组织树 +
右详情 / 内联编辑 + 新建部门/小组 + 停用启用二次确认;显示已停用、
?id= 选中可恢复、无 user:manage 只读;用户页部门选择仍只取启用部门;
- 测试:shared 契约、api 单测 + int、web 树/表单/接口单测同步。
影响面:
- 新增部门写接口与页面;GET tree 默认仍只返回启用部门,对用户页无破坏;
- 权限复用 user:view / user:manage,不新增权限点;
- 无数据库迁移(status / leader_user_id / sort_order 列已存在)。
回滚方式:
- 回滚本提交即移除部门管理页与写接口,保留原只读树;数据库无需回滚。
验证证据:
- pnpm format:check / lint / typecheck 全绿;
- pnpm test:shared 121 / api 90 / web 120;test:int 4 files / 33 tests;
- pnpm openapi:diff:无破坏性变更;
- 真实 API + 浏览器(jiang.lan):新建一级部门 / 小组、改名、停用空小组、
重名 40903、树/详情/停用确认均正常;
截图 design/a1-ui-v1/shots/impl/70-departments.png。
This commit is contained in:
1 parent
f4da1f3c02
commit
6661c42e84
33 files changed
+3237
-125
No files matched your search
@@ -0,0 +1,127 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { useAuthStore } from '@/stores/auth-store';
|
||||
|
||||
import {
|
||||
createDepartment,
|
||||
disableDepartment,
|
||||
enableDepartment,
|
||||
fetchDepartments,
|
||||
updateDepartment,
|
||||
} from './identity';
|
||||
|
||||
const USER_ID = '01HZZZZZZZZZZZZZZZZZZZZZZ1';
|
||||
const ROOT_ID = '01HZZZZZZZZZZZZZZZZZZZZZZ2';
|
||||
const CHILD_ID = '01HZZZZZZZZZZZZZZZZZZZZZZ3';
|
||||
|
||||
const jsonResponse = (body: unknown, status = 200): Response =>
|
||||
new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
const root = {
|
||||
id: ROOT_ID,
|
||||
name: '内容生产中心',
|
||||
parentId: null,
|
||||
leader: { id: USER_ID, name: '陈默' },
|
||||
status: 'active',
|
||||
sortOrder: 1,
|
||||
memberCount: 19,
|
||||
directMemberCount: 4,
|
||||
createdAt: '2026-11-01T00:00:00.000Z',
|
||||
children: [
|
||||
{
|
||||
id: CHILD_ID,
|
||||
name: '素材一组',
|
||||
parentId: ROOT_ID,
|
||||
leader: null,
|
||||
status: 'disabled',
|
||||
sortOrder: 2,
|
||||
memberCount: 9,
|
||||
directMemberCount: 9,
|
||||
createdAt: '2026-11-01T00:00:00.000Z',
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function calls(): { url: string; init: RequestInit | undefined }[] {
|
||||
return vi.mocked(globalThis.fetch).mock.calls.map((call) => {
|
||||
const input = call[0];
|
||||
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
|
||||
return { url, init: call[1] };
|
||||
});
|
||||
}
|
||||
|
||||
function lastBody(): unknown {
|
||||
const body = calls().at(-1)?.init?.body;
|
||||
return typeof body === 'string' ? (JSON.parse(body) as unknown) : undefined;
|
||||
}
|
||||
|
||||
describe('部门接口', () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
window.localStorage.clear();
|
||||
useAuthStore.getState().clearSession();
|
||||
useAuthStore.getState().setSession({
|
||||
accessToken: 'token',
|
||||
user: { id: USER_ID, name: '陈默', account: 'chen.mo' },
|
||||
permissions: ['user:view', 'user:manage'],
|
||||
});
|
||||
});
|
||||
|
||||
it('部门树默认只取启用部门,includeDisabled 时带 query', async () => {
|
||||
const fetchMock = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(jsonResponse({ items: [root] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ items: [root] }));
|
||||
const activeOnly = await fetchDepartments();
|
||||
expect(String(calls()[0]?.url)).toContain('/departments/tree?include_disabled=false');
|
||||
expect(activeOnly.map((node) => node.name)).toEqual(['内容生产中心', '素材一组']);
|
||||
expect(activeOnly[1]?.status).toBe('disabled');
|
||||
await fetchDepartments(true);
|
||||
expect(String(calls()[1]?.url)).toContain('/departments/tree?include_disabled=true');
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('新建返回部门 id,请求走 POST /departments', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(jsonResponse({ id: CHILD_ID }));
|
||||
await expect(
|
||||
createDepartment({
|
||||
name: '设计组',
|
||||
parentId: ROOT_ID,
|
||||
leaderUserId: null,
|
||||
sortOrder: 3,
|
||||
}),
|
||||
).resolves.toBe(CHILD_ID);
|
||||
expect(calls()[0]?.init?.method).toBe('POST');
|
||||
expect(String(calls()[0]?.url)).toContain('/departments');
|
||||
expect(lastBody()).toEqual({
|
||||
name: '设计组',
|
||||
parentId: ROOT_ID,
|
||||
leaderUserId: null,
|
||||
sortOrder: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it('更新 / 停用 / 启用使用约定方法与路径', async () => {
|
||||
vi.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValueOnce(new Response(null, { status: 204 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 204 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 204 }));
|
||||
await updateDepartment(CHILD_ID, { name: '设计组', leaderUserId: null });
|
||||
await disableDepartment(CHILD_ID);
|
||||
await enableDepartment(CHILD_ID);
|
||||
const requestLines = calls().map((call) => {
|
||||
const url = new URL(call.url);
|
||||
return `${call.init?.method ?? 'GET'} ${url.pathname.replace('/api/v1', '')}`;
|
||||
});
|
||||
expect(requestLines).toEqual([
|
||||
`PATCH /departments/${CHILD_ID}`,
|
||||
`POST /departments/${CHILD_ID}/disable`,
|
||||
`POST /departments/${CHILD_ID}/enable`,
|
||||
]);
|
||||
expect(lastBody()).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -19,6 +19,12 @@ export const ENDPOINTS = {
|
||||
userTransferCustomers: (userId: string): string =>
|
||||
`${USERS}/${encodeURIComponent(userId)}/transfer-customers`,
|
||||
departments: '/departments/tree',
|
||||
departmentsRoot: '/departments',
|
||||
department: (departmentId: string): string => `/departments/${encodeURIComponent(departmentId)}`,
|
||||
departmentDisable: (departmentId: string): string =>
|
||||
`/departments/${encodeURIComponent(departmentId)}/disable`,
|
||||
departmentEnable: (departmentId: string): string =>
|
||||
`/departments/${encodeURIComponent(departmentId)}/enable`,
|
||||
roles: '/roles',
|
||||
role: (roleId: string): string => `/roles/${encodeURIComponent(roleId)}`,
|
||||
permissions: '/permissions',
|
||||
|
||||
@@ -110,7 +110,10 @@ describe('identity 接口封装', () => {
|
||||
name: '内容生产中心',
|
||||
parentId: null,
|
||||
leader: null,
|
||||
status: 'active',
|
||||
sortOrder: 1,
|
||||
memberCount: 19,
|
||||
directMemberCount: 4,
|
||||
createdAt: '2026-09-01T00:00:00.000Z',
|
||||
children: [
|
||||
{
|
||||
@@ -118,7 +121,10 @@ describe('identity 接口封装', () => {
|
||||
name: '素材一组',
|
||||
parentId: GROUP_ID,
|
||||
leader: null,
|
||||
status: 'active',
|
||||
sortOrder: 1,
|
||||
memberCount: 9,
|
||||
directMemberCount: 9,
|
||||
createdAt: '2026-09-01T00:00:00.000Z',
|
||||
children: [],
|
||||
},
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import {
|
||||
type ChangePasswordInput,
|
||||
changePasswordInputSchema,
|
||||
type CreateDepartmentInput,
|
||||
createDepartmentInputSchema,
|
||||
type CreateUserInput,
|
||||
createUserInputSchema,
|
||||
type DepartmentNode,
|
||||
@@ -17,6 +19,8 @@ import {
|
||||
roleSummarySchema,
|
||||
type TransferCustomersInput,
|
||||
transferCustomersInputSchema,
|
||||
type UpdateDepartmentInput,
|
||||
updateDepartmentInputSchema,
|
||||
type UpdateUserInput,
|
||||
updateUserInputSchema,
|
||||
} from '@lingxi/shared';
|
||||
@@ -32,7 +36,7 @@ export interface CustomerSummary {
|
||||
}
|
||||
|
||||
const customerSummarySchema = z.object({ id: z.string().min(1), name: z.string().min(1) });
|
||||
const createdUserSchema = z.object({ id: z.string().min(1) }).passthrough();
|
||||
const createdIdSchema = z.object({ id: z.string().min(1) }).passthrough();
|
||||
|
||||
/** 兼容 `T[]` 与 `{ items: T[] }` 两种列表返回,逐项用共享 schema 校验 */
|
||||
function parseList<T>(payload: unknown, itemSchema: z.ZodType<T>): T[] {
|
||||
@@ -69,9 +73,13 @@ export async function fetchMe(): Promise<MeResponse> {
|
||||
return meResponseSchema.parse(payload);
|
||||
}
|
||||
|
||||
/** 部门树(后端返回两级嵌套 children),前端拍平成列表供下拉与筛选使用 */
|
||||
export async function fetchDepartments(): Promise<DepartmentNode[]> {
|
||||
const payload: unknown = await request(ENDPOINTS.departments);
|
||||
/**
|
||||
* 部门树(后端返回两级嵌套 children),前端拍平成列表供下拉与筛选使用。
|
||||
* includeDisabled=true 时包含已停用部门(部门管理页需要),默认只看启用。
|
||||
*/
|
||||
export async function fetchDepartments(includeDisabled = false): Promise<DepartmentNode[]> {
|
||||
const search = includeDisabled ? '?include_disabled=true' : '?include_disabled=false';
|
||||
const payload: unknown = await request(`${ENDPOINTS.departments}${search}`);
|
||||
const raw: unknown = isRecord(payload) && Array.isArray(payload.items) ? payload.items : payload;
|
||||
if (!Array.isArray(raw)) {
|
||||
return [];
|
||||
@@ -93,6 +101,32 @@ export async function fetchDepartments(): Promise<DepartmentNode[]> {
|
||||
return flat;
|
||||
}
|
||||
|
||||
export async function createDepartment(input: CreateDepartmentInput): Promise<string> {
|
||||
const body = createDepartmentInputSchema.parse(input);
|
||||
const payload: unknown = await request(ENDPOINTS.departmentsRoot, { method: 'POST', body });
|
||||
const parsed = createdIdSchema.safeParse(payload);
|
||||
if (!parsed.success) {
|
||||
throw new Error('部门创建成功但未返回部门 ID');
|
||||
}
|
||||
return parsed.data.id;
|
||||
}
|
||||
|
||||
export async function updateDepartment(
|
||||
departmentId: string,
|
||||
input: UpdateDepartmentInput,
|
||||
): Promise<void> {
|
||||
const body = updateDepartmentInputSchema.parse(input);
|
||||
await request<unknown>(ENDPOINTS.department(departmentId), { method: 'PATCH', body });
|
||||
}
|
||||
|
||||
export async function disableDepartment(departmentId: string): Promise<void> {
|
||||
await request<unknown>(ENDPOINTS.departmentDisable(departmentId), { method: 'POST' });
|
||||
}
|
||||
|
||||
export async function enableDepartment(departmentId: string): Promise<void> {
|
||||
await request<unknown>(ENDPOINTS.departmentEnable(departmentId), { method: 'POST' });
|
||||
}
|
||||
|
||||
export async function fetchRoles(): Promise<RoleSummary[]> {
|
||||
const payload: unknown = await request(ENDPOINTS.roles);
|
||||
return parseList(payload, roleSummarySchema);
|
||||
@@ -102,7 +136,7 @@ export async function fetchRoles(): Promise<RoleSummary[]> {
|
||||
export async function createUser(input: CreateUserInput): Promise<string | null> {
|
||||
const body = createUserInputSchema.parse(input);
|
||||
const payload: unknown = await request(ENDPOINTS.users, { method: 'POST', body });
|
||||
const parsed = createdUserSchema.safeParse(payload);
|
||||
const parsed = createdIdSchema.safeParse(payload);
|
||||
return parsed.success ? parsed.data.id : null;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ export const queryKeys = {
|
||||
userList: (query: UserListQueryInput) => ['users', 'list', query] as const,
|
||||
user: (userId: string) => ['users', 'detail', userId] as const,
|
||||
userCustomers: (userId: string) => ['users', 'customers', userId] as const,
|
||||
departments: ['departments'] as const,
|
||||
departments: (includeDisabled: boolean) => ['departments', { includeDisabled }] as const,
|
||||
roles: ['roles'] as const,
|
||||
roleList: (query: RoleListQueryInput) => ['roles', 'management', query] as const,
|
||||
role: (roleId: string) => ['roles', 'detail', roleId] as const,
|
||||
|
||||
Reference in new issue
Block a user