R38: 完成员工管理筛选与部门树试跑

这个提交包含在:
2026-03-28 13:15:32 +08:00
父节点 debef078f6
当前提交 f33431fdb8
共修改 9 个文件,包含 474 行新增和 60 行删除
+224 -24
查看文件
@@ -7,10 +7,21 @@ import {
archiveDepartment,
createDepartment,
fetchDepartments,
updateDepartment,
type DepartmentItem,
type DepartmentTreeNode,
} from "../api/departments";
import { StatusBadge } from "../components/common/StatusBadge";
import { PageHeader } from "../components/common/PageHeader";
import { Button } from "../components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "../components/ui/dialog";
import { Input } from "../components/ui/input";
import { Label } from "../components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../components/ui/table";
@@ -18,6 +29,73 @@ import { toast } from "sonner";
import { TableSkeleton } from "../components/common/TableSkeleton";
import { ConfirmDialog } from "../components/common/ConfirmDialog";
function mapDepartmentErrorMessage(error: unknown, fallback: string) {
if (!isApiError(error)) {
return error instanceof Error ? error.message : fallback;
}
if (error.code === "VALID_001") {
if (error.details?.parentId === "not_found") {
return `${error.code}: 上级部门不存在。`;
}
if (error.details?.parentId === "archived") {
return `${error.code}: 上级部门已归档,无法继续使用。`;
}
if (error.details?.parentId === "self_not_allowed") {
return `${error.code}: 上级部门不能选择自身。`;
}
if (error.details?.parentId === "cycle_not_allowed") {
return `${error.code}: 上级部门不能形成循环层级。`;
}
if (error.details?.status === "archived") {
return `${error.code}: 已归档部门不可编辑。`;
}
if (error.details?.department === "has_children") {
return `${error.code}: 当前部门存在下级节点,无法归档。`;
}
if (error.details?.department === "has_active_employees") {
return `${error.code}: 当前部门仍有在职员工,无法归档。`;
}
}
return `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`;
}
function flattenDepartmentTree(nodes: DepartmentTreeNode[], depth = 0): Array<{ id: string; label: string }> {
const items: Array<{ id: string; label: string }> = [];
for (const node of nodes) {
items.push({ id: node.id, label: `${" ".repeat(depth)}${node.name}` });
items.push(...flattenDepartmentTree(node.children, depth + 1));
}
return items;
}
function DepartmentTreeView({ nodes, depth = 0 }: { nodes: DepartmentTreeNode[]; depth?: number }) {
if (!nodes.length) {
return null;
}
return (
<div className="space-y-3">
{nodes.map((node) => (
<div key={node.id} className="space-y-3">
<div
className="flex items-center gap-3 rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-2"
style={{ marginLeft: `${depth * 20}px` }}
>
<div className="min-w-0 flex-1">
<div className="font-medium text-zinc-900">{node.name}</div>
<div className="text-xs text-zinc-500 font-mono">{node.id}</div>
</div>
{node.archivedAt ? <StatusBadge status="archived" /> : null}
</div>
{node.children.length ? <DepartmentTreeView nodes={node.children} depth={depth + 1} /> : null}
</div>
))}
</div>
);
}
export function DepartmentsPage() {
const queryClient = useQueryClient();
const [searchParams, setSearchParams] = useSearchParams();
@@ -29,6 +107,9 @@ export function DepartmentsPage() {
const [parentId, setParentId] = useState<string>("");
const [error, setError] = useState("");
const [confirmArchive, setConfirmArchive] = useState<{ id: string; name: string } | null>(null);
const [editDepartment, setEditDepartment] = useState<DepartmentItem | null>(null);
const [editName, setEditName] = useState("");
const [editParentId, setEditParentId] = useState("");
const listQuery = useQuery({
queryKey: ["departments", includeArchived],
@@ -36,6 +117,7 @@ export function DepartmentsPage() {
});
const departments = listQuery.data?.items ?? [];
const departmentTree = listQuery.data?.tree ?? [];
const departmentById = useMemo(() => {
const map = new Map<string, DepartmentItem>();
@@ -45,6 +127,11 @@ export function DepartmentsPage() {
return map;
}, [departments]);
const departmentOptions = useMemo(
() => flattenDepartmentTree(departmentTree).filter((item) => !departmentById.get(item.id)?.archivedAt),
[departmentById, departmentTree],
);
const createMutation = useMutation({
mutationFn: () =>
createDepartment({
@@ -59,9 +146,32 @@ export function DepartmentsPage() {
toast.success("部门已创建");
},
onError: (err) => {
const msg = isApiError(err)
? `${err.code}: ${mapApiErrorMessage(err.code, err.details, err.message)}`
: err instanceof Error ? err.message : "创建部门失败";
const msg = mapDepartmentErrorMessage(err, "创建部门失败");
setError(msg);
toast.error(msg);
},
});
const editMutation = useMutation({
mutationFn: () => {
if (!editDepartment) {
throw new Error("未选择待编辑部门");
}
return updateDepartment(editDepartment.id, {
name: editName.trim(),
parentId: editParentId ? editParentId : null,
});
},
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["departments"] });
setEditDepartment(null);
setEditName("");
setEditParentId("");
setError("");
toast.success("部门已更新");
},
onError: (err) => {
const msg = mapDepartmentErrorMessage(err, "更新部门失败");
setError(msg);
toast.error(msg);
},
@@ -75,9 +185,7 @@ export function DepartmentsPage() {
toast.success("已归档");
},
onError: (err) => {
const msg = isApiError(err)
? `${err.code}: ${mapApiErrorMessage(err.code, err.details, err.message)}`
: err instanceof Error ? err.message : "归档部门失败";
const msg = mapDepartmentErrorMessage(err, "归档部门失败");
setError(msg);
toast.error(msg);
},
@@ -140,13 +248,11 @@ export function DepartmentsPage() {
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>
))}
{departmentOptions.map((item) => (
<option key={item.id} value={item.id}>
{item.label}
</option>
))}
</select>
</div>
@@ -163,6 +269,18 @@ export function DepartmentsPage() {
</div>
</div>
<div className="card-std p-6 space-y-4">
<h3 className="text-base font-semibold text-zinc-900">部门树形视图</h3>
{listQuery.isLoading ? <TableSkeleton columns={1} rows={4} /> : null}
{!listQuery.isLoading && !listQuery.isError ? (
departmentTree.length ? (
<DepartmentTreeView nodes={departmentTree} />
) : (
<p className="text-sm text-zinc-500">暂无部门层级</p>
)
) : null}
</div>
<div className="card-std p-6 space-y-4">
<h3 className="text-base font-semibold text-zinc-900">部门列表</h3>
@@ -207,16 +325,30 @@ export function DepartmentsPage() {
</TableCell>
<TableCell>
{!item.archivedAt ? (
<Button
data-testid="department-archive"
size="sm"
variant="secondary"
type="button"
disabled={archiveMutation.isPending}
onClick={() => setConfirmArchive({ id: item.id, name: item.name })}
>
归档
</Button>
<div className="flex flex-wrap gap-2">
<Button
size="sm"
variant="secondary"
type="button"
onClick={() => {
setEditDepartment(item);
setEditName(item.name);
setEditParentId(item.parentId ?? "");
}}
>
编辑
</Button>
<Button
data-testid="department-archive"
size="sm"
variant="secondary"
type="button"
disabled={archiveMutation.isPending}
onClick={() => setConfirmArchive({ id: item.id, name: item.name })}
>
归档
</Button>
</div>
) : (
<span className="text-xs text-zinc-500">已归档</span>
)}
@@ -247,7 +379,75 @@ export function DepartmentsPage() {
}}
onOpenChange={(open) => { if (!open) setConfirmArchive(null); }}
/>
<Dialog
open={Boolean(editDepartment)}
onOpenChange={(open) => {
if (!open) {
setEditDepartment(null);
setEditName("");
setEditParentId("");
}
}}
>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>编辑部门</DialogTitle>
<DialogDescription>修改部门名称或上级部门,保存后列表和树形视图会同步刷新。</DialogDescription>
</DialogHeader>
<div className="grid gap-4">
<div className="space-y-1">
<Label htmlFor="editDeptName">部门名称</Label>
<Input
id="editDeptName"
value={editName}
onChange={(event) => setEditName(event.target.value)}
/>
</div>
<div className="space-y-1">
<Label htmlFor="editDeptParent">上级部门</Label>
<select
id="editDeptParent"
className="select-std"
value={editParentId}
onChange={(event) => setEditParentId(event.target.value)}
>
<option value="">无</option>
{departmentOptions
.filter((item) => item.id !== editDepartment?.id)
.map((item) => (
<option key={item.id} value={item.id}>
{item.label}
</option>
))}
</select>
</div>
</div>
<DialogFooter>
<Button
variant="secondary"
type="button"
onClick={() => {
setEditDepartment(null);
setEditName("");
setEditParentId("");
}}
>
取消
</Button>
<Button
type="button"
disabled={editMutation.isPending || !editDepartment || !editName.trim()}
onClick={() => editMutation.mutate()}
>
{editMutation.isPending ? "保存中..." : "保存"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}