414 行
15 KiB
TypeScript
414 行
15 KiB
TypeScript
import { resolveErrorMessage as resolveUserErrorMessage } from "../lib/resolveErrorMessage";
|
|
import { useState } from "react";
|
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
import { fetchDepartments } from "../api/departments";
|
|
import { fetchEmployees } from "../api/employees";
|
|
import {
|
|
createUser,
|
|
disableUser,
|
|
enableUser,
|
|
fetchUsers,
|
|
resetUserPassword,
|
|
setUserRoles,
|
|
type UserStatus,
|
|
type UserSummary,
|
|
} from "../api/users";
|
|
import { ListWorkspace, WorkspaceHeader } from "../components/patterns/ListWorkspace";
|
|
import { Button } from "../components/ui/button";
|
|
import { Input } from "../components/ui/input";
|
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../components/ui/table";
|
|
import { toast } from "sonner";
|
|
import { TableSkeleton } from "../components/common/TableSkeleton";
|
|
import { StatusBadge } from "../components/common/StatusBadge";
|
|
import { Pagination } from "../components/common/Pagination";
|
|
import { CreateUserDialog, type CreateUserFormData } from "./user-management/CreateUserDialog";
|
|
import { UserImportDialog } from "./user-management/UserImportDialog";
|
|
import { UserRoleDialog } from "./user-management/UserRoleDialog";
|
|
import { useAuth } from "../auth/AuthContext";
|
|
|
|
const PAGE_SIZE = 20;
|
|
|
|
const ROLE_LABELS: Record<string, string> = {
|
|
employee: "员工",
|
|
manager: "直属经理",
|
|
ceo: "公司负责人",
|
|
finance: "财务",
|
|
system_admin: "OA 系统管理员",
|
|
finance_mgr: "财务负责人(兼容)",
|
|
administration: "行政(兼容)",
|
|
hr: "人事(兼容)",
|
|
admin: "应急超级管理员",
|
|
};
|
|
|
|
const ORDINARY_ROLE_OPTIONS = [
|
|
"employee",
|
|
"manager",
|
|
"ceo",
|
|
"finance",
|
|
"system_admin",
|
|
"finance_mgr",
|
|
"administration",
|
|
"hr",
|
|
] as const;
|
|
|
|
function formatRoleCodes(roleCodes: string[]) {
|
|
return roleCodes.length ? roleCodes.map((roleCode) => ROLE_LABELS[roleCode] ?? roleCode).join("、") : "-";
|
|
}
|
|
|
|
function isProtectedUserAccount(user: UserSummary) {
|
|
return user.roleCodes.some((roleCode) => roleCode === "admin" || roleCode === "system_admin");
|
|
}
|
|
|
|
export function UserManagementPage() {
|
|
const { me } = useAuth();
|
|
const queryClient = useQueryClient();
|
|
const isEmergencyAdmin = (me?.roleCodes ?? []).includes("admin");
|
|
const roleOptions = ORDINARY_ROLE_OPTIONS.map((code) => ({
|
|
code,
|
|
label: ROLE_LABELS[code],
|
|
disabled: code === "system_admin" && !isEmergencyAdmin,
|
|
}));
|
|
const [status, setStatus] = useState<UserStatus | "">("");
|
|
const [q, setQ] = useState("");
|
|
const [page, setPage] = useState(1);
|
|
const [error, setError] = useState("");
|
|
const [credentialResult, setCredentialResult] = useState<{
|
|
mode: "create" | "reset";
|
|
userId: string;
|
|
employeeNo?: string;
|
|
password: string;
|
|
} | null>(null);
|
|
|
|
const [createOpen, setCreateOpen] = useState(false);
|
|
const [importOpen, setImportOpen] = useState(false);
|
|
const [roleDialogUser, setRoleDialogUser] = useState<UserSummary | null>(null);
|
|
|
|
const listQuery = useQuery({
|
|
queryKey: ["users", "list", status, q, page],
|
|
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 users = listQuery.data?.items ?? [];
|
|
const userStats = {
|
|
total: listQuery.data?.total ?? 0,
|
|
active: users.filter((item) => item.status === "active").length,
|
|
archived: users.filter((item) => item.status === "archived").length,
|
|
roles: new Set(users.flatMap((item) => item.roleCodes)).size,
|
|
};
|
|
|
|
const createMutation = useMutation({
|
|
mutationFn: (payload: CreateUserFormData) => createUser(payload),
|
|
onSuccess: async (data) => {
|
|
await queryClient.invalidateQueries({ queryKey: ["users"] });
|
|
setCreateOpen(false);
|
|
setError("");
|
|
setCredentialResult({
|
|
mode: "create",
|
|
userId: data.id,
|
|
employeeNo: data.employeeNo,
|
|
password: data.oneTimePassword,
|
|
});
|
|
toast.success("用户已创建");
|
|
},
|
|
onError: (err) => {
|
|
const msg = resolveUserErrorMessage(err, "创建用户失败");
|
|
setError(msg);
|
|
toast.error(msg);
|
|
},
|
|
});
|
|
|
|
const toggleMutation = useMutation({
|
|
mutationFn: async (item: UserSummary) => {
|
|
if (item.status === "active") {
|
|
return disableUser(item.id);
|
|
}
|
|
return enableUser(item.id);
|
|
},
|
|
onSuccess: async () => {
|
|
await queryClient.invalidateQueries({ queryKey: ["users"] });
|
|
setError("");
|
|
toast.success("状态已更新");
|
|
},
|
|
onError: (err) => {
|
|
const msg = resolveUserErrorMessage(err, "更新用户状态失败");
|
|
setError(msg);
|
|
toast.error(msg);
|
|
},
|
|
});
|
|
|
|
const resetMutation = useMutation({
|
|
mutationFn: async (item: UserSummary) => resetUserPassword(item.id),
|
|
onSuccess: async (data) => {
|
|
setCredentialResult({ mode: "reset", userId: data.id, password: data.oneTimePassword });
|
|
await queryClient.invalidateQueries({ queryKey: ["users"] });
|
|
setError("");
|
|
toast.success("密码已重置");
|
|
},
|
|
onError: (err) => {
|
|
const msg = resolveUserErrorMessage(err, "重置密码失败");
|
|
setError(msg);
|
|
toast.error(msg);
|
|
},
|
|
});
|
|
|
|
const rolesMutation = useMutation({
|
|
mutationFn: async ({ userId, roles }: { userId: string; roles: string[] }) => {
|
|
return setUserRoles(userId, roles);
|
|
},
|
|
onSuccess: async () => {
|
|
await queryClient.invalidateQueries({ queryKey: ["users"] });
|
|
setRoleDialogUser(null);
|
|
setError("");
|
|
toast.success("角色已更新");
|
|
},
|
|
onError: (err) => {
|
|
const msg = resolveUserErrorMessage(err, "更新角色失败");
|
|
setError(msg);
|
|
toast.error(msg);
|
|
},
|
|
});
|
|
|
|
return (
|
|
<ListWorkspace>
|
|
<WorkspaceHeader
|
|
title="系统用户管理"
|
|
subtitle="账号开通、停用、角色和一次性口令集中处理。"
|
|
actions={
|
|
<div className="flex gap-2">
|
|
<UserImportDialog
|
|
open={importOpen}
|
|
onOpenChange={setImportOpen}
|
|
onImported={async () => {
|
|
await Promise.all([
|
|
queryClient.invalidateQueries({ queryKey: ["users"] }),
|
|
queryClient.invalidateQueries({ queryKey: ["employees"] }),
|
|
]);
|
|
}}
|
|
/>
|
|
<CreateUserDialog
|
|
open={createOpen}
|
|
onOpenChange={setCreateOpen}
|
|
onSubmit={(data) => createMutation.mutate(data)}
|
|
isPending={createMutation.isPending}
|
|
departments={{
|
|
isLoading: departmentsQuery.isLoading,
|
|
items: departmentsQuery.data?.items ?? [],
|
|
}}
|
|
managers={{
|
|
isLoading: managersQuery.isLoading,
|
|
items: (managersQuery.data?.items ?? []).map((item) => ({
|
|
id: item.id,
|
|
name: item.name,
|
|
employeeNo: item.employeeNo,
|
|
})),
|
|
}}
|
|
roleOptions={roleOptions}
|
|
/>
|
|
</div>
|
|
}
|
|
/>
|
|
|
|
{error ? (
|
|
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600" data-testid="users-error">
|
|
{error}
|
|
</p>
|
|
) : null}
|
|
|
|
{credentialResult ? (
|
|
<p className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800" data-testid="users-reset-result">
|
|
{credentialResult.mode === "create"
|
|
? (
|
|
<>
|
|
已创建用户(user={credentialResult.userId}
|
|
{credentialResult.employeeNo ? `,工号=${credentialResult.employeeNo}` : ""}
|
|
),一次性口令:<span className="font-mono">{credentialResult.password}</span>
|
|
</>
|
|
)
|
|
: (
|
|
<>
|
|
已重置密码(user={credentialResult.userId}),一次性口令:<span className="font-mono">{credentialResult.password}</span>
|
|
</>
|
|
)}
|
|
</p>
|
|
) : null}
|
|
|
|
<div className="finance-status-strip" data-testid="users-summary">
|
|
<div className="finance-metric-card"><div className="finance-metric-card__label">用户总数</div><div className="finance-metric-card__value">{userStats.total}</div></div>
|
|
<div className="finance-metric-card"><div className="finance-metric-card__label">当前页生效</div><div className="finance-metric-card__value">{userStats.active}</div></div>
|
|
<div className="finance-metric-card"><div className="finance-metric-card__label">当前页停用</div><div className="finance-metric-card__value">{userStats.archived}</div></div>
|
|
<div className="finance-metric-card"><div className="finance-metric-card__label">当前页角色</div><div className="finance-metric-card__value">{userStats.roles}</div></div>
|
|
<div className="finance-metric-card"><div className="finance-metric-card__label">当前页</div><div className="finance-metric-card__value">{page}</div></div>
|
|
</div>
|
|
|
|
<div className="admin-command-panel space-y-4">
|
|
<div className="ops-command-bar__row">
|
|
<Input
|
|
data-testid="users-search"
|
|
value={q}
|
|
onChange={(e) => {
|
|
setQ(e.target.value);
|
|
setPage(1);
|
|
}}
|
|
placeholder="搜索工号/姓名/手机号/邮箱"
|
|
/>
|
|
<select
|
|
className="select-std w-auto"
|
|
data-testid="users-status-filter"
|
|
value={status}
|
|
onChange={(e) => {
|
|
setStatus(e.target.value as UserStatus | "");
|
|
setPage(1);
|
|
}}
|
|
>
|
|
<option value="">全部状态</option>
|
|
<option value="active">生效中</option>
|
|
<option value="archived">已停用</option>
|
|
</select>
|
|
</div>
|
|
|
|
{listQuery.isLoading ? <TableSkeleton columns={5} rows={5} /> : null}
|
|
{listQuery.isError ? (
|
|
<p className="text-sm text-red-600">
|
|
{resolveUserErrorMessage(listQuery.error, "加载用户列表失败")}
|
|
</p>
|
|
) : null}
|
|
|
|
<div className="ops-table-focus overflow-x-auto">
|
|
<Table data-testid="users-table">
|
|
<TableHeader>
|
|
<tr>
|
|
<TableHead>工号/姓名</TableHead>
|
|
<TableHead>联系方式</TableHead>
|
|
<TableHead>状态</TableHead>
|
|
<TableHead>角色</TableHead>
|
|
<TableHead className="w-56">操作</TableHead>
|
|
</tr>
|
|
</TableHeader>
|
|
<TableBody>
|
|
{users.length ? (
|
|
users.map((item) => {
|
|
const protectedAccount = isProtectedUserAccount(item);
|
|
const canManageAccount = isEmergencyAdmin || !protectedAccount;
|
|
const isCurrentAccount = item.id === me?.id;
|
|
const canToggleAccount = canManageAccount && !isCurrentAccount;
|
|
const canResetPassword = canManageAccount;
|
|
const canEditRoles = canManageAccount && !isCurrentAccount;
|
|
|
|
return (
|
|
<TableRow data-testid="users-row" key={item.id}>
|
|
<TableCell>
|
|
<div className="font-medium text-zinc-900">
|
|
{item.employeeNo} / {item.name}
|
|
</div>
|
|
<div className="text-xs text-zinc-500 font-mono">{item.id}</div>
|
|
</TableCell>
|
|
<TableCell className="text-sm">
|
|
<div>{item.email}</div>
|
|
<div className="text-zinc-500">{item.phone ?? "手机号未填写"}</div>
|
|
</TableCell>
|
|
<TableCell><StatusBadge status={item.status} /></TableCell>
|
|
<TableCell className="text-xs">{formatRoleCodes(item.roleCodes)}</TableCell>
|
|
<TableCell>
|
|
<div className="flex flex-wrap gap-2">
|
|
{canToggleAccount ? (
|
|
<Button
|
|
data-testid="users-toggle"
|
|
size="sm"
|
|
variant="secondary"
|
|
disabled={toggleMutation.isPending}
|
|
onClick={() => toggleMutation.mutate(item)}
|
|
type="button"
|
|
>
|
|
{item.status === "active" ? "禁用" : "启用"}
|
|
</Button>
|
|
) : null}
|
|
|
|
{canResetPassword ? (
|
|
<Button
|
|
data-testid="users-reset-password"
|
|
size="sm"
|
|
variant="secondary"
|
|
disabled={resetMutation.isPending}
|
|
onClick={() => resetMutation.mutate(item)}
|
|
type="button"
|
|
>
|
|
重置密码
|
|
</Button>
|
|
) : null}
|
|
|
|
{canEditRoles ? (
|
|
<Button
|
|
data-testid="users-edit-roles"
|
|
size="sm"
|
|
variant="secondary"
|
|
disabled={rolesMutation.isPending}
|
|
onClick={() => setRoleDialogUser(item)}
|
|
type="button"
|
|
>
|
|
{item.roleCodes.includes("admin") ? "应急账号" : "角色"}
|
|
</Button>
|
|
) : null}
|
|
|
|
{protectedAccount && !isEmergencyAdmin ? (
|
|
<span
|
|
className="inline-flex items-center text-xs text-zinc-500"
|
|
data-testid="users-protected-account"
|
|
>
|
|
受保护账号
|
|
</span>
|
|
) : null}
|
|
</div>
|
|
</TableCell>
|
|
</TableRow>
|
|
);
|
|
})
|
|
) : (
|
|
<TableRow>
|
|
<TableCell colSpan={5} className="py-3 text-zinc-500">
|
|
暂无数据
|
|
</TableCell>
|
|
</TableRow>
|
|
)}
|
|
</TableBody>
|
|
</Table>
|
|
</div>
|
|
|
|
<Pagination
|
|
page={page}
|
|
totalPages={totalPages}
|
|
onPageChange={setPage}
|
|
testIdPrefix="users"
|
|
/>
|
|
</div>
|
|
|
|
<UserRoleDialog
|
|
open={Boolean(roleDialogUser)}
|
|
onOpenChange={(open) => {
|
|
if (!open) {
|
|
setRoleDialogUser(null);
|
|
}
|
|
}}
|
|
user={roleDialogUser}
|
|
roleOptions={roleOptions}
|
|
onSubmit={(roles) => {
|
|
if (roleDialogUser) {
|
|
rolesMutation.mutate({ userId: roleDialogUser.id, roles });
|
|
}
|
|
}}
|
|
isPending={rolesMutation.isPending}
|
|
/>
|
|
</ListWorkspace>
|
|
);
|
|
}
|