page.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. "use client";
  2. import { useCallback, useEffect, useState } from "react";
  3. import { useRouter } from "next/navigation";
  4. import { useAuth } from "@/features/agent/hooks/useAuth";
  5. import { ResponsiveLayout } from "@/components/layout";
  6. import {
  7. fetchUsers,
  8. createUser,
  9. updateUser,
  10. deleteUser,
  11. updateUserPassword,
  12. type UserSummary,
  13. type CreateUserRequest,
  14. type UpdateUserRequest,
  15. type UpdatePasswordRequest,
  16. } from "@/features/agent/services/userApi";
  17. import { Button } from "@/components/ui/button";
  18. import { Input } from "@/components/ui/input";
  19. import {
  20. Dialog,
  21. DialogContent,
  22. DialogHeader,
  23. DialogTitle,
  24. } from "@/components/ui/dialog";
  25. import { Badge } from "@/components/ui/badge";
  26. import { Card } from "@/components/ui/card";
  27. import { Label } from "@/components/ui/label";
  28. import {
  29. Plus,
  30. Edit,
  31. Trash2,
  32. Lock,
  33. Search,
  34. UserPlus,
  35. Save,
  36. X,
  37. } from "lucide-react";
  38. export default function UsersPage(props: any = {}) {
  39. const { embedded = false } = props;
  40. const router = useRouter();
  41. const { agent } = useAuth();
  42. const [users, setUsers] = useState<UserSummary[]>([]);
  43. const [loading, setLoading] = useState(true);
  44. const [searchQuery, setSearchQuery] = useState("");
  45. const [createDialogOpen, setCreateDialogOpen] = useState(false);
  46. const [editDialogOpen, setEditDialogOpen] = useState(false);
  47. const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);
  48. const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  49. const [selectedUser, setSelectedUser] = useState<UserSummary | null>(null);
  50. const [submitting, setSubmitting] = useState(false);
  51. // 创建用户表单
  52. const [createForm, setCreateForm] = useState<CreateUserRequest>({
  53. username: "",
  54. password: "",
  55. role: "agent",
  56. nickname: "",
  57. email: "",
  58. });
  59. // 编辑用户表单
  60. const [editForm, setEditForm] = useState<UpdateUserRequest>({
  61. role: "agent",
  62. nickname: "",
  63. email: "",
  64. receive_ai_conversations: true,
  65. });
  66. // 修改密码表单
  67. const [passwordForm, setPasswordForm] = useState<UpdatePasswordRequest>({
  68. old_password: "",
  69. new_password: "",
  70. });
  71. // 检查权限
  72. useEffect(() => {
  73. if (agent && agent.role !== "admin") {
  74. router.push("/agent/dashboard");
  75. }
  76. }, [agent, router]);
  77. // 加载用户列表
  78. const loadUsers = useCallback(async () => {
  79. if (!agent?.id) {
  80. return;
  81. }
  82. setLoading(true);
  83. try {
  84. const data = await fetchUsers(agent.id);
  85. setUsers(data);
  86. } catch (error) {
  87. console.error("加载用户列表失败:", error);
  88. alert((error as Error).message || "加载用户列表失败");
  89. } finally {
  90. setLoading(false);
  91. }
  92. }, [agent?.id]);
  93. // 初始加载
  94. useEffect(() => {
  95. loadUsers();
  96. }, [loadUsers]);
  97. // 过滤用户列表
  98. const filteredUsers = users.filter((user) => {
  99. if (!searchQuery.trim()) {
  100. return true;
  101. }
  102. const query = searchQuery.toLowerCase();
  103. return (
  104. user.username.toLowerCase().includes(query) ||
  105. (user.nickname && user.nickname.toLowerCase().includes(query)) ||
  106. (user.email && user.email.toLowerCase().includes(query))
  107. );
  108. });
  109. // 打开创建对话框
  110. const handleOpenCreate = () => {
  111. setCreateForm({
  112. username: "",
  113. password: "",
  114. role: "agent",
  115. nickname: "",
  116. email: "",
  117. });
  118. setCreateDialogOpen(true);
  119. };
  120. // 创建用户
  121. const handleCreate = async () => {
  122. if (!agent?.id) {
  123. return;
  124. }
  125. if (!createForm.username.trim() || !createForm.password.trim()) {
  126. alert("用户名和密码不能为空");
  127. return;
  128. }
  129. setSubmitting(true);
  130. try {
  131. await createUser(createForm, agent.id);
  132. setCreateDialogOpen(false);
  133. await loadUsers();
  134. alert("创建成功");
  135. } catch (error) {
  136. alert((error as Error).message || "创建用户失败");
  137. } finally {
  138. setSubmitting(false);
  139. }
  140. };
  141. // 打开编辑对话框
  142. const handleOpenEdit = (user: UserSummary) => {
  143. setSelectedUser(user);
  144. setEditForm({
  145. role: user.role as "admin" | "agent",
  146. nickname: user.nickname || "",
  147. email: user.email || "",
  148. receive_ai_conversations: user.receive_ai_conversations,
  149. });
  150. setEditDialogOpen(true);
  151. };
  152. // 更新用户
  153. const handleUpdate = async () => {
  154. if (!agent?.id || !selectedUser) {
  155. return;
  156. }
  157. setSubmitting(true);
  158. try {
  159. await updateUser(selectedUser.id, editForm, agent.id);
  160. setEditDialogOpen(false);
  161. setSelectedUser(null);
  162. await loadUsers();
  163. alert("更新成功");
  164. } catch (error) {
  165. alert((error as Error).message || "更新用户失败");
  166. } finally {
  167. setSubmitting(false);
  168. }
  169. };
  170. // 打开修改密码对话框
  171. const handleOpenPassword = (user: UserSummary) => {
  172. setSelectedUser(user);
  173. setPasswordForm({
  174. old_password: "",
  175. new_password: "",
  176. });
  177. setPasswordDialogOpen(true);
  178. };
  179. // 更新密码
  180. const handleUpdatePassword = async () => {
  181. if (!agent?.id || !selectedUser) {
  182. return;
  183. }
  184. if (!passwordForm.new_password.trim()) {
  185. alert("新密码不能为空");
  186. return;
  187. }
  188. // 如果修改的是当前用户,需要旧密码;如果是其他用户,不需要旧密码
  189. const isCurrentUser = selectedUser.id === agent.id;
  190. if (isCurrentUser && !passwordForm.old_password?.trim()) {
  191. alert("修改自己的密码需要提供旧密码");
  192. return;
  193. }
  194. setSubmitting(true);
  195. try {
  196. await updateUserPassword(
  197. selectedUser.id,
  198. isCurrentUser ? passwordForm : { new_password: passwordForm.new_password },
  199. agent.id
  200. );
  201. setPasswordDialogOpen(false);
  202. setSelectedUser(null);
  203. setPasswordForm({ old_password: "", new_password: "" });
  204. alert("密码更新成功");
  205. } catch (error) {
  206. alert((error as Error).message || "更新密码失败");
  207. } finally {
  208. setSubmitting(false);
  209. }
  210. };
  211. // 打开删除对话框
  212. const handleOpenDelete = (user: UserSummary) => {
  213. setSelectedUser(user);
  214. setDeleteDialogOpen(true);
  215. };
  216. // 删除用户
  217. const handleDelete = async () => {
  218. if (!agent?.id || !selectedUser) {
  219. return;
  220. }
  221. setSubmitting(true);
  222. try {
  223. await deleteUser(selectedUser.id, agent.id);
  224. setDeleteDialogOpen(false);
  225. setSelectedUser(null);
  226. await loadUsers();
  227. alert("删除成功");
  228. } catch (error) {
  229. alert((error as Error).message || "删除用户失败");
  230. } finally {
  231. setSubmitting(false);
  232. }
  233. };
  234. // 格式化时间
  235. const formatTime = (dateStr: string) => {
  236. const date = new Date(dateStr);
  237. return date.toLocaleString("zh-CN", {
  238. year: "numeric",
  239. month: "2-digit",
  240. day: "2-digit",
  241. hour: "2-digit",
  242. minute: "2-digit",
  243. });
  244. };
  245. if (!agent || agent.role !== "admin") {
  246. return null; // 或者显示"权限不足"页面
  247. }
  248. // 构建头部内容
  249. const headerContent = (
  250. <div className="bg-card border-b p-4 shadow-sm">
  251. <div className="flex items-center justify-between mb-4">
  252. <h1 className="text-xl font-bold text-foreground">用户管理</h1>
  253. {!embedded && (
  254. <Button
  255. variant="ghost"
  256. size="sm"
  257. onClick={() => router.push("/agent/dashboard")}
  258. >
  259. 返回
  260. </Button>
  261. )}
  262. </div>
  263. {/* 搜索和操作栏 */}
  264. <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2">
  265. <div className="flex-1 relative">
  266. <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
  267. <Input
  268. type="text"
  269. placeholder="搜索用户(用户名、昵称、邮箱)..."
  270. value={searchQuery}
  271. onChange={(e) => setSearchQuery(e.target.value)}
  272. className="pl-10"
  273. />
  274. </div>
  275. <Button
  276. onClick={handleOpenCreate}
  277. className="w-full sm:w-auto"
  278. >
  279. <UserPlus className="w-4 h-4 mr-2" />
  280. 创建用户
  281. </Button>
  282. </div>
  283. </div>
  284. );
  285. // 构建主内容区
  286. const mainContent = (
  287. <div className="flex-1 overflow-y-auto p-4 scrollbar-auto">
  288. {loading ? (
  289. <div className="flex items-center justify-center h-full">
  290. <span className="text-muted-foreground">加载中...</span>
  291. </div>
  292. ) : filteredUsers.length === 0 ? (
  293. <div className="flex items-center justify-center h-full">
  294. <span className="text-muted-foreground">
  295. {searchQuery ? "没有找到匹配的用户" : "暂无用户"}
  296. </span>
  297. </div>
  298. ) : (
  299. <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
  300. {filteredUsers.map((user) => (
  301. <Card key={user.id} className="p-4 flex flex-col">
  302. <div className="mb-3 flex-1">
  303. <div className="flex items-center gap-2 mb-2">
  304. <span className="font-medium text-foreground">
  305. {user.nickname || user.username}
  306. </span>
  307. <Badge
  308. variant={user.role === "admin" ? "default" : "secondary"}
  309. >
  310. {user.role === "admin" ? "管理员" : "客服"}
  311. </Badge>
  312. </div>
  313. <div className="text-sm text-muted-foreground space-y-1 mb-2">
  314. <div>用户名: {user.username}</div>
  315. {user.email && <div>邮箱: {user.email}</div>}
  316. </div>
  317. <div className="text-xs text-muted-foreground">
  318. 创建时间: {formatTime(user.created_at)}
  319. </div>
  320. </div>
  321. <div className="flex items-center gap-2 mt-auto pt-3 border-t">
  322. <Button
  323. variant="outline"
  324. size="sm"
  325. onClick={() => handleOpenEdit(user)}
  326. className="flex-1"
  327. >
  328. <Edit className="w-4 h-4 mr-1" />
  329. 编辑
  330. </Button>
  331. <Button
  332. variant="outline"
  333. size="sm"
  334. onClick={() => handleOpenPassword(user)}
  335. className="flex-1"
  336. >
  337. <Lock className="w-4 h-4 mr-1" />
  338. 密码
  339. </Button>
  340. <Button
  341. variant="destructive"
  342. size="sm"
  343. onClick={() => handleOpenDelete(user)}
  344. disabled={user.id === agent.id}
  345. title={user.id === agent.id ? "不能删除当前登录用户" : ""}
  346. >
  347. <Trash2 className="w-4 h-4" />
  348. </Button>
  349. </div>
  350. </Card>
  351. ))}
  352. </div>
  353. )}
  354. </div>
  355. );
  356. // 如果是嵌入模式,只返回内容,不包含 ResponsiveLayout
  357. if (embedded) {
  358. return (
  359. <>
  360. <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
  361. {headerContent}
  362. {mainContent}
  363. </div>
  364. {/* 对话框 */}
  365. {/* 创建用户对话框 */}
  366. <Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
  367. <DialogContent>
  368. <DialogHeader>
  369. <DialogTitle>创建新用户</DialogTitle>
  370. </DialogHeader>
  371. <div className="space-y-4">
  372. <div>
  373. <Label htmlFor="create-username">用户名 *</Label>
  374. <Input
  375. id="create-username"
  376. value={createForm.username}
  377. onChange={(e) =>
  378. setCreateForm({ ...createForm, username: e.target.value })
  379. }
  380. placeholder="请输入用户名"
  381. />
  382. </div>
  383. <div>
  384. <Label htmlFor="create-password">密码 *</Label>
  385. <Input
  386. id="create-password"
  387. type="password"
  388. value={createForm.password}
  389. onChange={(e) =>
  390. setCreateForm({ ...createForm, password: e.target.value })
  391. }
  392. placeholder="请输入密码"
  393. />
  394. </div>
  395. <div>
  396. <Label htmlFor="create-role">角色 *</Label>
  397. <select
  398. id="create-role"
  399. value={createForm.role}
  400. onChange={(e) =>
  401. setCreateForm({
  402. ...createForm,
  403. role: e.target.value as "admin" | "agent",
  404. })
  405. }
  406. className="w-full px-3 py-2 border border-border rounded-md bg-background"
  407. >
  408. <option value="agent">客服</option>
  409. <option value="admin">管理员</option>
  410. </select>
  411. </div>
  412. <div>
  413. <Label htmlFor="create-nickname">昵称</Label>
  414. <Input
  415. id="create-nickname"
  416. value={createForm.nickname}
  417. onChange={(e) =>
  418. setCreateForm({ ...createForm, nickname: e.target.value })
  419. }
  420. placeholder="请输入昵称(可选)"
  421. />
  422. </div>
  423. <div>
  424. <Label htmlFor="create-email">邮箱</Label>
  425. <Input
  426. id="create-email"
  427. type="email"
  428. value={createForm.email}
  429. onChange={(e) =>
  430. setCreateForm({ ...createForm, email: e.target.value })
  431. }
  432. placeholder="请输入邮箱(可选)"
  433. />
  434. </div>
  435. <div className="flex justify-end gap-2">
  436. <Button
  437. variant="outline"
  438. onClick={() => setCreateDialogOpen(false)}
  439. disabled={submitting}
  440. >
  441. 取消
  442. </Button>
  443. <Button onClick={handleCreate} disabled={submitting}>
  444. {submitting ? "创建中..." : "创建"}
  445. </Button>
  446. </div>
  447. </div>
  448. </DialogContent>
  449. </Dialog>
  450. {/* 编辑用户对话框 */}
  451. <Dialog open={editDialogOpen} onOpenChange={setEditDialogOpen}>
  452. <DialogContent>
  453. <DialogHeader>
  454. <DialogTitle>编辑用户</DialogTitle>
  455. </DialogHeader>
  456. {selectedUser && (
  457. <div className="space-y-4">
  458. <div>
  459. <Label>用户名</Label>
  460. <Input value={selectedUser.username} disabled />
  461. <p className="text-xs text-muted-foreground mt-1">
  462. 用户名不能修改
  463. </p>
  464. </div>
  465. <div>
  466. <Label htmlFor="edit-role">角色 *</Label>
  467. <select
  468. id="edit-role"
  469. value={editForm.role}
  470. onChange={(e) =>
  471. setEditForm({
  472. ...editForm,
  473. role: e.target.value as "admin" | "agent",
  474. })
  475. }
  476. className="w-full px-3 py-2 border border-border rounded-md bg-background"
  477. >
  478. <option value="agent">客服</option>
  479. <option value="admin">管理员</option>
  480. </select>
  481. </div>
  482. <div>
  483. <Label htmlFor="edit-nickname">昵称</Label>
  484. <Input
  485. id="edit-nickname"
  486. value={editForm.nickname || ""}
  487. onChange={(e) =>
  488. setEditForm({ ...editForm, nickname: e.target.value })
  489. }
  490. placeholder="请输入昵称"
  491. />
  492. </div>
  493. <div>
  494. <Label htmlFor="edit-email">邮箱</Label>
  495. <Input
  496. id="edit-email"
  497. type="email"
  498. value={editForm.email || ""}
  499. onChange={(e) =>
  500. setEditForm({ ...editForm, email: e.target.value })
  501. }
  502. placeholder="请输入邮箱"
  503. />
  504. </div>
  505. <div className="flex items-center gap-2">
  506. <input
  507. type="checkbox"
  508. id="edit-receive-ai"
  509. checked={editForm.receive_ai_conversations ?? true}
  510. onChange={(e) =>
  511. setEditForm({
  512. ...editForm,
  513. receive_ai_conversations: e.target.checked,
  514. })
  515. }
  516. className="w-4 h-4"
  517. />
  518. <Label htmlFor="edit-receive-ai" className="cursor-pointer">
  519. 接收 AI 对话
  520. </Label>
  521. </div>
  522. <div className="flex justify-end gap-2">
  523. <Button
  524. variant="outline"
  525. onClick={() => setEditDialogOpen(false)}
  526. disabled={submitting}
  527. >
  528. 取消
  529. </Button>
  530. <Button onClick={handleUpdate} disabled={submitting}>
  531. {submitting ? "更新中..." : "更新"}
  532. </Button>
  533. </div>
  534. </div>
  535. )}
  536. </DialogContent>
  537. </Dialog>
  538. {/* 修改密码对话框 */}
  539. <Dialog open={passwordDialogOpen} onOpenChange={setPasswordDialogOpen}>
  540. <DialogContent>
  541. <DialogHeader>
  542. <DialogTitle>修改密码</DialogTitle>
  543. </DialogHeader>
  544. {selectedUser && (
  545. <div className="space-y-4">
  546. <div>
  547. <Label>用户名</Label>
  548. <Input value={selectedUser.username} disabled />
  549. </div>
  550. {selectedUser.id === agent?.id && (
  551. <div>
  552. <Label htmlFor="password-old">旧密码 *</Label>
  553. <Input
  554. id="password-old"
  555. type="password"
  556. value={passwordForm.old_password || ""}
  557. onChange={(e) =>
  558. setPasswordForm({
  559. ...passwordForm,
  560. old_password: e.target.value,
  561. })
  562. }
  563. placeholder="请输入旧密码"
  564. />
  565. </div>
  566. )}
  567. <div>
  568. <Label htmlFor="password-new">新密码 *</Label>
  569. <Input
  570. id="password-new"
  571. type="password"
  572. value={passwordForm.new_password}
  573. onChange={(e) =>
  574. setPasswordForm({
  575. ...passwordForm,
  576. new_password: e.target.value,
  577. })
  578. }
  579. placeholder="请输入新密码"
  580. />
  581. </div>
  582. <div className="flex justify-end gap-2">
  583. <Button
  584. variant="outline"
  585. onClick={() => setPasswordDialogOpen(false)}
  586. disabled={submitting}
  587. >
  588. 取消
  589. </Button>
  590. <Button onClick={handleUpdatePassword} disabled={submitting}>
  591. {submitting ? "更新中..." : "更新"}
  592. </Button>
  593. </div>
  594. </div>
  595. )}
  596. </DialogContent>
  597. </Dialog>
  598. {/* 删除确认对话框 */}
  599. <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
  600. <DialogContent>
  601. <DialogHeader>
  602. <DialogTitle>删除用户</DialogTitle>
  603. </DialogHeader>
  604. {selectedUser && (
  605. <div className="space-y-4">
  606. <p className="text-foreground">
  607. 确定要删除用户 <strong>{selectedUser.username}</strong> 吗?
  608. </p>
  609. <p className="text-sm text-muted-foreground">
  610. 此操作不可恢复,请谨慎操作。
  611. </p>
  612. <div className="flex justify-end gap-2">
  613. <Button
  614. variant="outline"
  615. onClick={() => setDeleteDialogOpen(false)}
  616. disabled={submitting}
  617. >
  618. 取消
  619. </Button>
  620. <Button
  621. variant="destructive"
  622. onClick={handleDelete}
  623. disabled={submitting}
  624. >
  625. {submitting ? "删除中..." : "删除"}
  626. </Button>
  627. </div>
  628. </div>
  629. )}
  630. </DialogContent>
  631. </Dialog>
  632. </>
  633. );
  634. }
  635. return (
  636. <ResponsiveLayout
  637. main={mainContent}
  638. header={headerContent}
  639. />
  640. );
  641. }