feat(client): 部门管理与员工创建增强(F32)

- 新增部门管理页:列表/创建/归档
- 用户创建支持选择部门与直属上级
- 补齐 departments/employees API 封装与导航入口
这个提交包含在:
2026-02-09 18:24:07 +08:00
父节点 1a5d3b1d52
当前提交 efa4a3d3f6
共修改 7 个文件,包含 411 行新增和 3 行删除
+52
查看文件
@@ -0,0 +1,52 @@
import { apiRequestData } from "./http";
export type DepartmentItem = {
id: string;
name: string;
parentId: string | null;
archivedAt: string | null;
createdAt: string | null;
updatedAt: string | null;
};
export type DepartmentTreeNode = DepartmentItem & {
children: DepartmentTreeNode[];
};
export type DepartmentListResponse = {
includeArchived: boolean;
items: DepartmentItem[];
tree: DepartmentTreeNode[];
};
export async function fetchDepartments(params: { includeArchived?: boolean } = {}) {
const search = new URLSearchParams();
if (params.includeArchived != null) {
search.set("includeArchived", params.includeArchived ? "1" : "0");
}
const qs = search.toString();
return apiRequestData<DepartmentListResponse>(`/api/departments${qs ? `?${qs}` : ""}`);
}
export async function createDepartment(payload: { name: string; parentId?: string | null }) {
return apiRequestData<DepartmentItem>("/api/departments", {
method: "POST",
body: JSON.stringify(payload),
});
}
export async function updateDepartment(departmentId: string, payload: { name?: string; parentId?: string | null }) {
return apiRequestData<DepartmentItem>(`/api/departments/${departmentId}`, {
method: "PATCH",
body: JSON.stringify(payload),
});
}
export async function archiveDepartment(departmentId: string) {
return apiRequestData<DepartmentItem>(`/api/departments/${departmentId}/archive`, {
method: "POST",
body: JSON.stringify({}),
});
}
+41
查看文件
@@ -0,0 +1,41 @@
import { apiRequestData } from "./http";
export type EmployeeStatus = "active" | "archived";
export type EmployeeSummary = {
id: string;
employeeNo: string;
name: string;
phone: string;
email: string;
status: EmployeeStatus;
departmentId: string;
directManagerId: string | null;
title: string;
roleCodes: string[];
createdAt: string | null;
updatedAt: string | null;
};
export type EmployeeListResponse = {
page: number;
pageSize: number;
total: number;
items: EmployeeSummary[];
};
export async function fetchEmployees(params: {
page: number;
pageSize: number;
status?: EmployeeStatus;
q?: string;
}) {
const search = new URLSearchParams();
search.set("page", String(params.page));
search.set("pageSize", String(params.pageSize));
if (params.status) search.set("status", params.status);
if (params.q) search.set("q", params.q);
return apiRequestData<EmployeeListResponse>(`/api/employees?${search.toString()}`);
}
+2 -1
查看文件
@@ -44,6 +44,8 @@ export async function createUser(payload: {
phone: string;
email: string;
password: string;
departmentId?: string;
directManagerId?: string | null;
roles: string[];
}) {
return apiRequestData<UserSummary>("/api/users", {
@@ -80,4 +82,3 @@ export async function setUserRoles(userId: string, roles: string[]) {
body: JSON.stringify({ roles }),
});
}
@@ -41,6 +41,11 @@ export const NAV_ITEMS: NavItem[] = [
label: "用户管理",
anyOf: ["system.users"],
},
{
to: "/system/departments",
label: "部门管理",
anyOf: ["system.users"],
},
{ to: "/settings/profile", label: "个人设置" },
];
+242
查看文件
@@ -0,0 +1,242 @@
import { useMemo, useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { mapApiErrorMessage } from "../api/errorMessages";
import { isApiError } from "../api/types";
import {
archiveDepartment,
createDepartment,
fetchDepartments,
type DepartmentItem,
} from "../api/departments";
import { PageHeader } from "../components/common/PageHeader";
import { Button } from "../components/ui/button";
import { Card } from "../components/ui/card";
import { Input } from "../components/ui/input";
import { Label } from "../components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../components/ui/table";
export function DepartmentsPage() {
const queryClient = useQueryClient();
const [searchParams, setSearchParams] = useSearchParams();
const includeArchivedRaw = searchParams.get("includeArchived") ?? "0";
const includeArchived = includeArchivedRaw === "1" || includeArchivedRaw === "true";
const [name, setName] = useState("");
const [parentId, setParentId] = useState<string>("");
const [error, setError] = useState("");
const listQuery = useQuery({
queryKey: ["departments", includeArchived],
queryFn: () => fetchDepartments({ includeArchived }),
});
const departments = listQuery.data?.items ?? [];
const departmentById = useMemo(() => {
const map = new Map<string, DepartmentItem>();
for (const dept of departments) {
map.set(dept.id, dept);
}
return map;
}, [departments]);
const createMutation = useMutation({
mutationFn: () =>
createDepartment({
name: name.trim(),
parentId: parentId ? parentId : null,
}),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["departments"] });
setName("");
setParentId("");
setError("");
},
onError: (err) => {
if (isApiError(err)) {
setError(`${err.code}: ${mapApiErrorMessage(err.code, err.details, err.message)}`);
return;
}
setError(err instanceof Error ? err.message : "创建部门失败");
},
});
const archiveMutation = useMutation({
mutationFn: (departmentId: string) => archiveDepartment(departmentId),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["departments"] });
setError("");
},
onError: (err) => {
if (isApiError(err)) {
setError(`${err.code}: ${mapApiErrorMessage(err.code, err.details, err.message)}`);
return;
}
setError(err instanceof Error ? err.message : "归档部门失败");
},
});
return (
<div className="space-y-6">
<PageHeader
title="部门管理"
subtitle="维护部门层级,用于员工归属与审批链路解析。"
actions={
<Button asChild variant="secondary" data-testid="departments-back">
<Link to="/system/users">返回用户管理</Link>
</Button>
}
/>
{error ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
{error}
</p>
) : null}
<Card className="space-y-4 p-6">
<div className="flex items-center justify-between gap-3">
<h3 className="text-base font-semibold text-slate-900">新建部门</h3>
<Button
data-testid="departments-toggle-archived"
variant="secondary"
type="button"
onClick={() =>
setSearchParams({
includeArchived: includeArchived ? "0" : "1",
})
}
>
{includeArchived ? "隐藏归档" : "显示归档"}
</Button>
</div>
<div className="grid gap-3 md:grid-cols-3">
<div className="space-y-1">
<Label htmlFor="deptName">部门名称</Label>
<Input
id="deptName"
data-testid="departments-create-name"
placeholder="研发部"
value={name}
onChange={(event) => setName(event.target.value)}
/>
</div>
<div className="space-y-1">
<Label htmlFor="deptParent">上级部门(可选)</Label>
<select
id="deptParent"
data-testid="departments-create-parent"
className="h-11 w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm"
value={parentId}
onChange={(event) => setParentId(event.target.value)}
>
<option value="">无</option>
{departments
.filter((item) => !item.archivedAt)
.map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</div>
<div className="flex items-end">
<Button
data-testid="departments-create-submit"
disabled={createMutation.isPending || !name.trim()}
onClick={() => createMutation.mutate()}
type="button"
>
{createMutation.isPending ? "创建中..." : "创建"}
</Button>
</div>
</div>
</Card>
<Card className="space-y-4 p-6">
<h3 className="text-base font-semibold text-slate-900">部门列表</h3>
{listQuery.isLoading ? <p className="text-sm text-slate-500">加载中...</p> : null}
{listQuery.isError ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
{isApiError(listQuery.error)
? `${listQuery.error.code}: ${mapApiErrorMessage(
listQuery.error.code,
listQuery.error.details,
listQuery.error.message,
)}`
: "加载部门列表失败"}
</p>
) : null}
{!listQuery.isLoading && !listQuery.isError ? (
<div className="rounded-lg border border-slate-200">
<Table data-testid="departments-table">
<TableHeader>
<tr>
<TableHead>名称</TableHead>
<TableHead>上级部门</TableHead>
<TableHead>归档时间</TableHead>
<TableHead className="w-32">操作</TableHead>
</tr>
</TableHeader>
<TableBody>
{departments.length ? (
departments.map((item) => {
const parentName = item.parentId ? departmentById.get(item.parentId)?.name ?? "-" : "-";
return (
<TableRow data-testid="department-row" key={item.id}>
<TableCell>
<div className="font-medium text-slate-900">{item.name}</div>
<div className="text-xs text-slate-500 font-mono">{item.id}</div>
</TableCell>
<TableCell>{parentName}</TableCell>
<TableCell className="text-xs text-slate-600">
{item.archivedAt ? item.archivedAt.slice(0, 19).replace("T", " ") : "-"}
</TableCell>
<TableCell>
{!item.archivedAt ? (
<Button
data-testid="department-archive"
size="sm"
variant="secondary"
type="button"
disabled={archiveMutation.isPending}
onClick={() => {
if (!window.confirm(`确认归档部门「${item.name}」?归档后不可用于新员工。`)) {
return;
}
archiveMutation.mutate(item.id);
}}
>
归档
</Button>
) : (
<span className="text-xs text-slate-500">已归档</span>
)}
</TableCell>
</TableRow>
);
})
) : (
<TableRow>
<TableCell className="py-3 text-slate-500" colSpan={4}>
暂无部门
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
) : null}
</Card>
</div>
);
}
+59 -2
查看文件
@@ -2,6 +2,8 @@ import { useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { mapApiErrorMessage } from "../api/errorMessages";
import { isApiError } from "../api/types";
import { fetchDepartments } from "../api/departments";
import { fetchEmployees } from "../api/employees";
import {
createUser,
disableUser,
@@ -51,6 +53,8 @@ export function UserManagementPage() {
const [phone, setPhone] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [departmentId, setDepartmentId] = useState("");
const [directManagerId, setDirectManagerId] = useState("");
const [createRoles, setCreateRoles] = useState<Set<string>>(() => new Set(["employee"]));
const [roleDialogUser, setRoleDialogUser] = useState<UserSummary | null>(null);
@@ -61,6 +65,16 @@ export function UserManagementPage() {
queryFn: () => fetchUsers({ page, pageSize: PAGE_SIZE, status: status || undefined, q: q || undefined }),
});
const departmentsQuery = useQuery({
queryKey: ["departments", "active"],
queryFn: () => fetchDepartments({ includeArchived: false }),
});
const managersQuery = useQuery({
queryKey: ["employees", "active"],
queryFn: () => fetchEmployees({ page: 1, pageSize: 200, status: "active" }),
});
const totalPages = Math.max(1, Math.ceil((listQuery.data?.total ?? 0) / PAGE_SIZE));
const createPayload = useMemo(() => {
@@ -70,9 +84,11 @@ export function UserManagementPage() {
phone: phone.trim(),
email: email.trim(),
password: password,
departmentId: departmentId || undefined,
directManagerId: directManagerId ? directManagerId : null,
roles: Array.from(createRoles),
};
}, [createRoles, email, employeeNo, name, password, phone]);
}, [createRoles, departmentId, directManagerId, email, employeeNo, name, password, phone]);
const createMutation = useMutation({
mutationFn: () => createUser(createPayload),
@@ -84,6 +100,8 @@ export function UserManagementPage() {
setPhone("");
setEmail("");
setPassword("");
setDepartmentId("");
setDirectManagerId("");
setCreateRoles(new Set(["employee"]));
setError("");
},
@@ -225,6 +243,46 @@ export function UserManagementPage() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor="departmentId">部门(可选)</Label>
<select
id="departmentId"
data-testid="users-create-department"
className="h-11 w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm"
value={departmentId}
onChange={(event) => setDepartmentId(event.target.value)}
>
<option value="">
{departmentsQuery.isLoading ? "加载中..." : "默认(与当前管理员一致)"}
</option>
{(departmentsQuery.data?.items ?? []).map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</div>
<div className="grid gap-2">
<Label htmlFor="directManagerId">直属上级(可选)</Label>
<select
id="directManagerId"
data-testid="users-create-direct-manager"
className="h-11 w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm"
value={directManagerId}
onChange={(event) => setDirectManagerId(event.target.value)}
>
<option value="">
{managersQuery.isLoading ? "加载中..." : "无"}
</option>
{(managersQuery.data?.items ?? []).map((item) => (
<option key={item.id} value={item.id}>
{item.name} ({item.employeeNo})
</option>
))}
</select>
</div>
<div className="grid gap-2">
<Label>角色</Label>
<div className="flex flex-wrap gap-3 text-sm">
@@ -500,4 +558,3 @@ export function UserManagementPage() {
</div>
);
}
+10
查看文件
@@ -4,6 +4,7 @@ import { AuthLayout } from "../layouts/AuthLayout";
import { AuditLogsPage } from "../pages/AuditLogsPage";
import { ChangePasswordPage } from "../pages/ChangePasswordPage";
import { DashboardPage } from "../pages/DashboardPage";
import { DepartmentsPage } from "../pages/DepartmentsPage";
import { DelegationsPage } from "../pages/DelegationsPage";
import { ForbiddenPage } from "../pages/ForbiddenPage";
import { InvoicePoolPage } from "../pages/InvoicePoolPage";
@@ -128,6 +129,15 @@ export function AppRouter() {
}
/>
<Route
path="system/departments"
element={
<RequirePermission anyOf={["system.users"]}>
<DepartmentsPage />
</RequirePermission>
}
/>
<Route path="settings/profile" element={<ProfilePage />} />
</Route>