454 行
16 KiB
TypeScript
454 行
16 KiB
TypeScript
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,
|
||
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";
|
||
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();
|
||
|
||
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 [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],
|
||
queryFn: () => fetchDepartments({ includeArchived }),
|
||
});
|
||
|
||
const departments = listQuery.data?.items ?? [];
|
||
const departmentTree = listQuery.data?.tree ?? [];
|
||
|
||
const departmentById = useMemo(() => {
|
||
const map = new Map<string, DepartmentItem>();
|
||
for (const dept of departments) {
|
||
map.set(dept.id, dept);
|
||
}
|
||
return map;
|
||
}, [departments]);
|
||
|
||
const departmentOptions = useMemo(
|
||
() => flattenDepartmentTree(departmentTree).filter((item) => !departmentById.get(item.id)?.archivedAt),
|
||
[departmentById, departmentTree],
|
||
);
|
||
|
||
const createMutation = useMutation({
|
||
mutationFn: () =>
|
||
createDepartment({
|
||
name: name.trim(),
|
||
parentId: parentId ? parentId : null,
|
||
}),
|
||
onSuccess: async () => {
|
||
await queryClient.invalidateQueries({ queryKey: ["departments"] });
|
||
setName("");
|
||
setParentId("");
|
||
setError("");
|
||
toast.success("部门已创建");
|
||
},
|
||
onError: (err) => {
|
||
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);
|
||
},
|
||
});
|
||
|
||
const archiveMutation = useMutation({
|
||
mutationFn: (departmentId: string) => archiveDepartment(departmentId),
|
||
onSuccess: async () => {
|
||
await queryClient.invalidateQueries({ queryKey: ["departments"] });
|
||
setError("");
|
||
toast.success("已归档");
|
||
},
|
||
onError: (err) => {
|
||
const msg = mapDepartmentErrorMessage(err, "归档部门失败");
|
||
setError(msg);
|
||
toast.error(msg);
|
||
},
|
||
});
|
||
|
||
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}
|
||
|
||
<div className="card-std p-6 space-y-4">
|
||
<div className="flex items-center justify-between gap-3">
|
||
<h3 className="text-base font-semibold text-zinc-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="select-std"
|
||
value={parentId}
|
||
onChange={(event) => setParentId(event.target.value)}
|
||
>
|
||
<option value="">无</option>
|
||
{departmentOptions.map((item) => (
|
||
<option key={item.id} value={item.id}>
|
||
{item.label}
|
||
</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>
|
||
</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>
|
||
|
||
{listQuery.isLoading ? <TableSkeleton columns={4} rows={4} /> : 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-zinc-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-zinc-900">{item.name}</div>
|
||
<div className="text-xs text-zinc-500 font-mono">{item.id}</div>
|
||
</TableCell>
|
||
<TableCell>{parentName}</TableCell>
|
||
<TableCell className="text-xs text-zinc-600">
|
||
{item.archivedAt ? item.archivedAt.slice(0, 19).replace("T", " ") : "-"}
|
||
</TableCell>
|
||
<TableCell>
|
||
{!item.archivedAt ? (
|
||
<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>
|
||
)}
|
||
</TableCell>
|
||
</TableRow>
|
||
);
|
||
})
|
||
) : (
|
||
<TableRow>
|
||
<TableCell className="py-3 text-zinc-500" colSpan={4}>
|
||
暂无部门
|
||
</TableCell>
|
||
</TableRow>
|
||
)}
|
||
</TableBody>
|
||
</Table>
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
|
||
<ConfirmDialog
|
||
open={Boolean(confirmArchive)}
|
||
title="确认归档"
|
||
description={`确认归档部门「${confirmArchive?.name ?? ""}」?归档后不可用于新员工。`}
|
||
variant="destructive"
|
||
onConfirm={async () => {
|
||
if (confirmArchive) archiveMutation.mutate(confirmArchive.id);
|
||
}}
|
||
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>
|
||
);
|
||
}
|