179 Commits

Author SHA1 Message Date
095eccea76 feat: 支持考试批量归档与恢复 2026-07-25 09:45:58 +08:00
0ef86e65ce feat: 为批量归档补充批量恢复 2026-07-25 09:34:03 +08:00
1da763109b Merge pull request 'Remove name field from ClassTeacher and derive teacher name from user' (#55) from xiongyuxing/gongxue-base:main into main
Reviewed-on: wangziqi/gongxue-base#55
2026-07-24 09:37:06 +00:00
4d77848bf7 Remove name field from ClassTeacher and derive teacher name from user
lookup
2026-07-24 17:36:35 +08:00
1d656a80e7 Merge pull request '修复班级教师姓名显示' (#54) from xiongyuxing/gongxue-base:main into main
Reviewed-on: wangziqi/gongxue-base#54
2026-07-24 09:20:25 +00:00
c1bb05502e 修复班级教师姓名显示 2026-07-24 17:19:18 +08:00
3bd72596c9 Merge pull request 'Update data.sql' (#53) from update-data-sql into main 2026-07-24 08:57:21 +00:00
4fc77aec07 Update data.sql 2026-07-24 16:57:15 +08:00
6dcb2bc28a Merge pull request 'Clean up data.sql: remove unused entries' (#52) from cleanup-data-sql into main 2026-07-24 08:48:06 +00:00
d5a1d23037 Clean up data.sql: remove unused entries 2026-07-24 16:47:54 +08:00
1f198d48ea Merge pull request 'Refactor AI chat: streaming, tool calls, UI polish' (#51) from refactor-ai-chat-streaming into main 2026-07-24 08:28:10 +00:00
5cf68e3f8a Merge pull request 'main' (#50) from xiongyuxing/gongxue-base:main into main 2026-07-24 08:28:07 +00:00
8656394b9b Refactor AI chat: streaming, tool calls, UI polish 2026-07-24 16:27:50 +08:00
3573351f59 新增考试归档与恢复功能 2026-07-24 16:18:35 +08:00
4046e29e33 Remove manual code-splitting config for React, ECharts, and Antd 2026-07-24 16:06:57 +08:00
525bbd1a56 Add seed data for 2025 summer school schedule
Drop unused KeyOutlined import and refactor init.sql to drop all tables
safely
2026-07-24 15:28:19 +08:00
f53934c67d 新增暑期班课表数据库初始化脚本 2026-07-24 15:02:08 +08:00
e605586fc9 Merge pull request 'Refactor AI config to step-based wizard with DeepSeek defaults' (#49) from refactor-ai-config-wizard into main 2026-07-24 06:35:16 +00:00
150e6ecff0 Refactor AI config to step-based wizard with DeepSeek defaults 2026-07-24 14:34:32 +08:00
065dfd9a38 Merge pull request '修复管理员班级可见范围、 修复班级归档查询参数转换、 移除账号启用状态统一使用归档' (#48) from xiongyuxing/gongxue-base:main into main
Reviewed-on: wangziqi/gongxue-base#48
2026-07-24 06:32:55 +00:00
a272403f27 修复班级归档查询参数转换 2026-07-24 10:05:36 +08:00
13ef357448 移除账号启用状态统一使用归档 2026-07-24 09:53:04 +08:00
a9c6578569 修复管理员班级可见范围 2026-07-24 09:41:37 +08:00
106c30683f Merge pull request 'fix: 修复 CI — 安装 AI 依赖 + 移除 lucide-react + 删除 docs' (#47) from fix/ci-deps-and-cleanup into main 2026-07-23 07:38:53 +00:00
3a2b3f1239 fix: add AI deps, remove lucide-react; chore: remove docs 2026-07-23 15:25:20 +08:00
b8d5927a16 Merge branch 'review-pr44' 2026-07-23 15:21:51 +08:00
fb787c3e0d Merge pull request '集成 AI 对话与只读查询工具' (#44) from xiongyuxing/gongxue-base:main into main 2026-07-23 07:15:07 +00:00
176f098923 chore: add @ant-design/x deps for AI chat feature 2026-07-23 15:08:57 +08:00
c401766bc5 fix: replace lucide-react Sparkles with RobotOutlined to avoid extra dependency 2026-07-23 15:02:36 +08:00
2a20b1fc97 Merge pull request 'fix: 权限按钮可见性与Modal/Popconfirm撤权一致性修复' (#45) from worktree-audit-permission-ui into main 2026-07-23 06:40:18 +00:00
6f29220257 test: 跳过外部考勤工作流集成测试 2026-07-23 14:35:38 +08:00
446c6bcc91 fix: harden permission-gated UI — minimum-org endpoint, modal/Popconfirm fail-closed on revocation 2026-07-23 14:28:58 +08:00
a7a7af1667 fix: close permission review gaps
fix: harden permission-gated UI — minimum-org endpoint, modal/Popconfirm fail-closed on revocation
2026-07-23 14:28:58 +08:00
9f54fec972 Merge remote-tracking branch 'origin/main' 2026-07-23 14:25:15 +08:00
f3b59935d6 feat: 集成 AI 对话与只读查询工具 2026-07-23 14:24:40 +08:00
c98d37307e fix: align permission-gated UI actions 2026-07-23 12:34:37 +08:00
adf738288f Merge pull request 'chore: 修复 npm 高危依赖漏洞' (#43) from worktree-npm-security-updates into main 2026-07-23 04:12:10 +00:00
585e955720 Merge pull request 'test: cover end-to-end attendance workflow' (#41) from worktree-working-session into main 2026-07-23 04:10:31 +00:00
eaca56617c chore: patch vulnerable npm dependencies 2026-07-23 12:02:20 +08:00
0bdc8a067b fix: satisfy attendance workflow lint 2026-07-23 11:48:50 +08:00
490a337446 Merge remote-tracking branch 'origin/main' into fix/pr41-ci 2026-07-23 11:47:30 +08:00
302dbe0621 Merge pull request 'fix: 避免 PR #40 触屏双击时缩放页面' (#42) from fix/pr40-touch-action into main 2026-07-23 03:32:57 +00:00
5bd63846d1 fix: prevent touch double-tap zoom 2026-07-23 11:27:41 +08:00
301064dbf6 Merge pull request '修复手机端双击编辑单元格' (#40) from xiongyuxing/gongxue-base:main into main 2026-07-23 03:26:42 +00:00
fa7ed8e128 feat:移除表格内部的滚动 2026-07-23 11:22:31 +08:00
099cff7f00 test: cover end-to-end attendance workflow 2026-07-23 10:31:23 +08:00
a267238e7c merge upstream 2026-07-23 01:44:00 +00:00
d93f6cb0b9 修复手机端双击编辑单元格 2026-07-23 09:42:33 +08:00
0ce8f58adb chore: remove dead code and tune frontend chunks
Remove unused production symbols, starter assets, and stale browser tooling; reduce frontend chunk fragmentation.
2026-07-23 01:26:41 +00:00
43ca5a6e36 Merge pull request 'fix: UI优化 + 钉钉考勤已结算课程刷新 + dev脚本改进' (#38) from fix/ux-improvements-20260722 into main 2026-07-22 09:52:03 +00:00
90cc321221 fix: UI improvements and DingTalk attendance refresh for completed sessions
- DatePicker editors open immediately on double-click
- Student archive drawer hides empty studentNo parentheses
- Student add/edit form uses 2-column grid layout
- Table horizontal scrollbars show only on hover/focus
- Remove fake 近7日趋势 stats from attendance student detail
- Allow DingTalk refresh to update completed attendance sessions
  (late-arriving punches can now change absent → present)
- Switch dev command from concurrently to turbo run dev
- Remove concurrently/wait-on dependencies
2026-07-22 17:50:59 +08:00
d33c37b4b0 Merge pull request '修复学习记录实体未注册问题' (#37) from xiongyuxing/gongxue-base:main into main 2026-07-22 09:38:45 +00:00
bf867eedaa Merge branch 'main' of https://git.gongxue100.com/xiongyuxing/gongxue-base 2026-07-22 17:22:11 +08:00
6286864df0 修复学习记录实体未注册问题 2026-07-22 17:19:20 +08:00
5b10e80d3a Merge pull request '修正换宿当天查寝归属、修复 SQLite 钱包调账锁异常' (#36) from xiongyuxing/gongxue-base:main into main 2026-07-22 08:59:43 +00:00
a9009f86fb fix: 修正换宿当天查寝归属 2026-07-22 15:18:12 +08:00
7ffc573d2e 修复 SQLite 钱包调账锁异常 2026-07-22 15:03:06 +08:00
cd1996f281 Merge pull request '增加金数据学生同步与匹配规则' (#35) from feature/jinshuju-student-sync into main 2026-07-22 04:30:03 +00:00
e1bc3a6b2c ci: remove cache steps that add overhead 2026-07-22 12:27:51 +08:00
6052b03fc6 ci: cache npm and Turbo artifacts 2026-07-22 11:50:53 +08:00
67fdf093e5 perf: split oversized admin bundles 2026-07-22 11:45:35 +08:00
393ee62168 feat: add Jinshuju student sync 2026-07-22 11:41:50 +08:00
1dc13274de Merge pull request '增加宿舍查寝功能' (#34) from xiongyuxing/gongxue-base:main into main 2026-07-22 03:33:32 +00:00
576dab0d41 fix: 修复测试文件日期比较逻辑 2026-07-22 11:25:13 +08:00
22a4431ba3 Merge branch 'main' of https://git.gongxue100.com/xiongyuxing/gongxue-base 2026-07-22 11:18:04 +08:00
da023759a1 fix: 修复后端 CI 检查与测试 2026-07-22 11:17:39 +08:00
f2cae27575 merge upstream 2026-07-22 02:58:11 +00:00
257c39db90 feat: 优化 CI 工作流,简化依赖安装和类型检查步骤 2026-07-22 10:57:46 +08:00
54e283b687 feat: 增加宿舍查寝功能 2026-07-22 10:55:48 +08:00
e27d8b512e Merge pull request '修复学生余额多选充值一次性最高只能选15个' (#33) from xiongyuxing/gongxue-base:main into main 2026-07-22 02:23:09 +00:00
c888dce065 feat: 更新 CI 工作流,优化依赖安装步骤 2026-07-22 10:13:31 +08:00
d4fb55a20c feat: 更新 CI 工作流,添加 checkout 步骤的配置 2026-07-22 09:49:12 +08:00
8f1ff5970d feat: 更新学生余额页面的分页设置,增加页面大小选择功能 2026-07-22 09:43:54 +08:00
25760a4ec7 Merge pull request '学生信息导入' (#32) from xiongyuxing/gongxue-base:main into main 2026-07-22 01:05:47 +00:00
4fdf190d69 feat: 优化 CI 工作流,简化步骤并更新环境配置 2026-07-21 17:35:16 +08:00
04082820b0 feat: 重构 CI 工作流,合并 lint、类型检查和测试步骤 2026-07-21 17:31:44 +08:00
cbc04fea4f feat: add exam score management 2026-07-21 16:04:17 +08:00
37ef6f9dd7 feat: add college archive fields 2026-07-21 15:35:35 +08:00
2626d5f460 Merge branch 'main' of https://git.gongxue100.com/xiongyuxing/gongxue-base 2026-07-21 15:12:24 +08:00
90cc0c10b2 feat: expand student archive import template 2026-07-21 15:11:52 +08:00
6a35e406d5 Merge pull request '添加可拖拽的路由停靠组件,支持动态标签管理,支持侧边栏多项同时展开' (#31) from xiongyuxing/gongxue-base:main into main 2026-07-21 06:37:33 +00:00
a585fd42d5 feat: 支持表格单元格快捷编辑 2026-07-21 14:17:08 +08:00
fe0b71a0a9 feat:调整登陆页面输入框布局 2026-07-21 10:43:07 +08:00
a9961d1a99 feat: 更新系统名称为学生管理系统,修改相关页面标题和生成的账单信息 2026-07-21 10:32:21 +08:00
29c55ebff1 feat: 添加可拖拽的路由停靠组件,支持动态标签管理 2026-07-21 10:13:47 +08:00
5e1ba70e59 功能:支持侧边栏多项同时展开 2026-07-21 09:59:17 +08:00
d306de48e4 修复:兼容 SQLite 开发环境启动 2026-07-21 09:57:19 +08:00
b32dc33e8b Merge pull request 'feat: 移除 Docker 部署,添加 Gitea CI/CD + PM2 手动部署' (#30) from worktree-ci-cd-pm2-deploy into main 2026-07-20 07:46:18 +00:00
151ef06ec2 refactor: 精简部署流程,移除 MySQL 管理
MySQL 已在服务器运行,部署只需三步:
1. 本地构建 → rsync 同步
2. npm ci(首次)+ migration:run
3. pm2 startOrReload
2026-07-20 15:35:45 +08:00
a87f26a915 feat: 移除 Docker 部署,添加 Gitea CI/CD workflows
- 删除 docker-compose.yml、Dockerfile、.dockerignore、docker/ 目录
- 更新 deploy.sh:移除 Docker Compose MySQL 启动,改为 systemd 检查
- 新增 .gitea/workflows/deploy.yml:手动触发、rsync + SSH + PM2 部署
- 新增 .gitea/workflows/ci.yml:PR lint + typecheck + test 自动检查
2026-07-20 15:33:46 +08:00
ad62b8595c Merge pull request 'test: 为边界条件修复添加测试用例' (#29) from test/boundary-conditions into main 2026-07-20 07:31:36 +00:00
2c0be0f033 test: 为边界条件修复添加测试用例
- rooms: parseRoomNumber 未知格式、楼层0、capacity ?? 测试
- occupancies: capacity undefined/null/0 fail-closed 防守测试
- schedules: startTime > endTime 拒绝测试
- attendance: 重叠检查按时间排序、raw[index] 移除测试
- expenses: 金额零/负/NaN 拒绝、period反转校验测试

5 modules, 40 tests, all passing
2026-07-20 15:30:41 +08:00
bbd700369c Merge pull request 'fix: 修复多处边界条件问题' (#27) from fix/boundary-conditions into main 2026-07-20 06:50:21 +00:00
00e9c5e45a fix: 修复多处边界条件问题
- rooms: parseRoomNumber 未知格式返回默认 capacity=4,防止 undefined 绕过入住容量检查
- rooms: 修复 parseInt() || undefined 导致楼层 0 被吞掉
- rooms: batchImport 中 capacity 使用 ?? 代替 ||,显式 0 不被覆盖
- occupancies: 所有 capacity 比较加 ?? 0 防守兜底,fail closed
- schedules: assertValidScheduleRange 增加 startTime > endTime 校验
- attendance: 时段重叠检查改为按 startTime 排序后再比较,消除漏检
- attendance: 移除 getScheduleOptionsForAttendance 中不可靠的 raw[index] fallback
- expenses: 个人附加费批量导入增加 assertPositiveAmount 校验
- expenses: 水电费导入增加 periodEnd >= periodStart 校验
2026-07-20 14:45:53 +08:00
990c0c16e6 feat: Docker Compose deployment + auto migration on startup
- docker-compose.yml: 移除 MySQL 容器,连宿主机 MySQL
- main.ts: 启动前通过独立 DataSource 执行 runMigrations
- migration-runner.ts: 独立 migration 执行器
- app.module.ts: TypeORM 配置增加 migrations
- 修复 InitialSchema 中 room_expenses 和 financial_operations 重复索引
2026-07-20 12:43:13 +08:00
4c2192d85e feat: switch to Docker Compose + auto-migration
- docker-compose.yml: 移除 MySQL 容器,后端连宿主机 MySQL
- main.ts: 启动时自动 runMigrations
- 前端 Nginx 反代 /api/ → backend:3000 不变
2026-07-20 12:24:51 +08:00
2d7c30eb30 Merge pull request 'feat: add TypeORM CLI migration support' (#26) from feat/migration-setup into main 2026-07-20 04:16:59 +00:00
2ee8bd47e2 feat: add TypeORM CLI migration support
- 新增 datasource.ts 支持 mysql/sqlite 双模式
- 新增 migration 脚本: generate/create/run/revert/show
- 生成 InitialSchema migration (35 张表全量建表)
2026-07-20 12:16:48 +08:00
a871bb3f96 Merge pull request 'fix: 修正档案报告品牌名 工学云 → 恭学教育' (#25) from fix/brand-name into main 2026-07-20 04:00:17 +00:00
ed428c8aa3 fix: 修正档案报告品牌名 工学云 → 恭学教育 2026-07-20 11:59:51 +08:00
62a5f817ae Merge pull request 'feat: 拆分学号/身份证字段 + 考勤教师展示 + 代码优化' (#24) from feat/split-student-id-number into main 2026-07-20 03:54:21 +00:00
c7ba2799b9 feat: 拆分学号/身份证字段 + 考勤教师展示 + 代码优化
- 入住导入模板:学号和身份证号拆为独立字段,前后端对齐
- 排课查询关联教师,考勤归档页展示教师姓名
- 抽查时段增加 IsIn 校验
- 抽取 withPessimisticWriteLock 去重悲观锁查询
- import 增加文件空 buffer 校验
- 测试 mock 补全,适配事务 manager
- MySQL init.sql VALUES() 语法兼容修复
2026-07-20 11:54:01 +08:00
375c7ec60b feat: refine admin forms, attendance and finance workflows
Squash merge PR #23.

Included changes:
- complete occupancy check-in required fields/default payload
- improve responsive admin management pages
- fix attendance edge cases and attendance period config
- refine wallet/finance-related workflow handling

Checks:
- npm run typecheck -w apps/admin
- npm run typecheck -w apps/server
2026-07-18 12:54:10 +00:00
92d303ed01 Merge pull request #22: financial safety and attendance workspace 2026-07-18 07:35:49 +00:00
295debee33 Merge teacher attendance workspace 2026-07-18 15:34:36 +08:00
a8da6de235 Merge financial safety fixes 2026-07-18 15:34:36 +08:00
98d335b889 feat: redesign teacher attendance workspace 2026-07-18 15:34:02 +08:00
5836b421d8 fix: harden financial transaction boundaries 2026-07-18 15:33:41 +08:00
4af7acbeaa Merge pull request #21: harden DingTalk student synchronization 2026-07-18 06:52:33 +00:00
c11f6bb614 fix: harden DingTalk student synchronization 2026-07-18 14:51:53 +08:00
d25e451b61 Merge pull request #20: refine deposit workflows and RBAC permissions 2026-07-18 06:07:19 +00:00
7edb4ff853 fix: prune unused RBAC permissions 2026-07-17 17:43:45 +08:00
b3d0bafc22 feat: refine deposit room type workflows 2026-07-17 17:36:04 +08:00
a5bda6f093 Merge pull request 'fix: 归档删除改为软删除' (#19)
fix: 归档删除改为软删除
2026-07-17 06:18:38 +00:00
f7328d670d fix: 归档删除改为软删除 2026-07-17 14:13:17 +08:00
3131d2e141 Merge pull request 'fix:修复无法导出账单pdf' (#18) 2026-07-16 03:47:38 +00:00
2beedc22af fix:修复无法导出账单pdf 2026-07-16 11:25:59 +08:00
fa086e4c1c Merge pull request '修复考勤服务测试 mock' (#17) 2026-07-16 03:01:59 +00:00
4fbcde48b1 test: update attendance service mocks 2026-07-16 11:01:24 +08:00
c93ac986aa Merge pull request '移除删除账号功能' (#15) 2026-07-16 02:55:22 +00:00
ab7f7c725a Merge pull request '添加考勤设备 SN 教室绑定' (#16) 2026-07-16 02:49:30 +00:00
200d2e423b 调整归档操作入口 2026-07-16 10:44:21 +08:00
559b8a56e9 feat: add attendance device SN classroom bindings 2026-07-16 10:22:23 +08:00
d037787346 feat: support batch wallet balance changes 2026-07-16 10:22:23 +08:00
8ba51f48c0 fix: map expense type sort order column 2026-07-16 10:22:23 +08:00
7a62d8962a chore: update production deployment config 2026-07-16 10:21:40 +08:00
1737563516 移除删除账号功能 2026-07-16 10:16:56 +08:00
6a43f33f7a Merge pull request '优化管理端移动端适配与班级教师候选人' (#14)
Merge PR #14
2026-07-15 05:57:32 +00:00
d582d641c0 feat: improve admin responsive pages and teacher candidates 2026-07-15 13:56:58 +08:00
fb9697bd05 Merge pull request '完善全业务边界校验与回归测试' (#12)
Merge PR #12
2026-07-15 05:53:46 +00:00
bc49d1016a feat: filter rooms by rental category 2026-07-15 13:52:39 +08:00
8bd445df5a fix student import and profile labels 2026-07-15 10:52:43 +08:00
fcde6caaaa fix: defer attendance settlement until lesson end 2026-07-15 09:39:21 +08:00
b1f35f9d1a test: harden business boundary conditions 2026-07-15 00:03:55 +08:00
17a5046ea0 Merge pull request '完善考勤排课与接口校验' (#11) from wangziqi/gongxue-base:codex/wzq into main
完善考勤排课、钉钉同步与接口参数校验
2026-07-14 15:13:12 +00:00
e45da7f998 feat: improve attendance scheduling and API validation 2026-07-14 23:12:14 +08:00
c75a08affe feat: add student wallet utility billing 2026-07-14 20:42:21 +08:00
b480070e69 Merge pull request '修复账单生成时未计算分摊费用' (#10) from xiongyuxing/gongxue-base:main into main
Reviewed-on: wangziqi/gongxue-base#10
2026-07-14 08:41:13 +00:00
598b4e8acd feat: link deposits to bill payment 2026-07-14 16:38:38 +08:00
eac336a54a fix: include contained room expenses in bill generation 2026-07-14 14:53:07 +08:00
ce5fd1c6cb fix: 修复批量更新账单状态功能 2026-07-14 14:24:19 +08:00
05a936bbc2 Merge pull request 'feat: 优化入住办理与名单导入' (#9) from codex/wzq into main 2026-07-14 04:26:53 +00:00
3adf4933d8 Merge pull request '修复pdf导出' (#8) from xiongyuxing/gongxue-base:main into main 2026-07-14 04:26:34 +00:00
d84f37e98f feat: streamline occupancy check-in and imports 2026-07-14 12:23:53 +08:00
16b56ffcd5 merge upstream 2026-07-14 04:09:42 +00:00
718c58589f Merge PR #7: improve attendance and occupancy workflows 2026-07-14 03:22:19 +00:00
aaf49d5580 fix: guard bill generation submission 2026-07-14 11:20:42 +08:00
5cf6aede1e feat: improve occupancy import template 2026-07-14 11:20:41 +08:00
811e7ce826 feat: show DingTalk punch device details 2026-07-14 11:20:41 +08:00
79fa472b78 merge upstream 2026-07-14 03:20:00 +00:00
029af37f3a fix: render bill pdf from frontend print view 2026-07-14 11:18:49 +08:00
d572e984d2 Merge PR #6: keep room capacity and beds consistent 2026-07-14 02:58:01 +00:00
a93ba657a8 fix: keep room capacity and beds consistent 2026-07-14 10:57:13 +08:00
77714642a5 Merge PR #5: main 2026-07-14 02:56:04 +00:00
e7aa202603 fix: 修改 PDFDocument 导入方式以符合 ES6 模块规范 2026-07-14 10:45:27 +08:00
xyx
013b3f4afe fix: 押金页添加批量构建学生选项的功能以简化学生数据处理 2026-07-13 17:18:35 +08:00
xyx
7bfd30b513 fix: 添加表单验证错误处理逻辑以改善错误提示 2026-07-13 16:50:47 +08:00
xyx
ceb0e2bf14 fix: 添加默认床位生成逻辑并优化床位添加验证 2026-07-13 16:50:47 +08:00
xyx
acb11b87a3 fix: enhance pagination settings across multiple pages with default size and options 2026-07-13 16:49:21 +08:00
b9e4caae99 Merge PR #4: align forms, contracts, and lifecycle models
Reviewed and validated across admin/server builds, typechecks, migrations, and full test suites.
2026-07-13 08:31:24 +00:00
f98c0ccaa8 refactor(rooms): remove dorm gender restrictions 2026-07-13 16:12:57 +08:00
aa1ed7db56 refactor: resolve remaining field audit issues 2026-07-13 16:12:57 +08:00
0533c30ece refactor(classes): preserve student membership history 2026-07-13 16:12:57 +08:00
1f32d1285b refactor(deposits): remove refund approval remnants 2026-07-13 16:12:56 +08:00
7b08560aef fix(deposits): show student numbers in lookup 2026-07-13 16:12:56 +08:00
04ef5c42d9 refactor(deposits): remove inline installment creation 2026-07-13 16:12:22 +08:00
0515e6ed27 fix(integration): simplify manual DingTalk sync setup 2026-07-13 16:12:22 +08:00
effa34434b refactor(students): remove obsolete class id input 2026-07-13 16:12:22 +08:00
0377acd33b refactor: remove residual campus and department fields 2026-07-13 16:12:22 +08:00
6396d3e934 fix(schedules): support editable schedule notes 2026-07-13 16:12:21 +08:00
dfd3cf6772 fix(archive): align aggregate result field 2026-07-13 16:12:21 +08:00
2874ab7bee fix(occupancies): assign room resources during transfers 2026-07-13 16:12:21 +08:00
8cadf8970e fix(admin): restore teacher profile form values 2026-07-13 16:12:20 +08:00
337d25e370 Merge PR #3: validated codex/xyx fixes
Includes PR #2 changes and DingTalk token cache test fixture updates.
2026-07-13 08:08:19 +00:00
7860703672 test: update DingTalk token cache fixtures 2026-07-13 16:04:05 +08:00
xyx
ebce2463f0 fix: remove sensitive data masking from student options label 2026-07-13 15:27:17 +08:00
xyx
910a4263f6 fix: refactor notification display logic and add format function 2026-07-13 14:52:03 +08:00
xyx
6d42241918 fix: enhance emergency contact phone display with masking and view option 2026-07-13 14:29:01 +08:00
xyx
70283d9dfe fix: enhance 401 error handling to exclude login requests 2026-07-13 14:22:22 +08:00
438 changed files with 40307 additions and 29609 deletions

View File

@@ -1,21 +0,0 @@
node_modules
npm-debug.log
Dockerfile
.dockerignore
.git
.gitignore
README.md
*.md
dist
build
.env
.env.local
.env.*.local
coverage
.nyc_output
.DS_Store
.vscode
.idea
*.swp
*.swo
*~

View File

@@ -8,11 +8,15 @@ MYSQL_ROOT_PASSWORD=change-me-to-a-strong-password
DB_HOST=127.0.0.1
DB_PORT=3306
DB_USERNAME=root
DB_DATABASE=gongxue
DB_DATABASE=dorm_billing_v2
DB_SYNCHRONIZE=false
JWT_SECRET=change-me-to-a-random-string-at-least-32-chars
JWT_EXPIRES_IN=24h
PORT=3000
# 初始管理员 admin 密码(仅首次创建 admin 用户时生效)
ADMIN_PASSWORD=change-me-admin-password
PORT=3002
# ---- AI 模型配置 ----
# AES-256-GCM 加密主密钥,用于加密存储 API Key

43
.gitea/workflows/ci.yml Normal file
View File

@@ -0,0 +1,43 @@
name: CI
env:
NPM_CONFIG_REGISTRY: https://registry.npmmirror.com
NPM_CONFIG_AUDIT: "false"
NPM_CONFIG_FUND: "false"
NPM_CONFIG_REPLACE_REGISTRY_HOST: always
CI: "true"
on:
pull_request:
branches: [main]
workflow_dispatch:
jobs:
check:
runs-on: ubuntu-latest
container: node:22.22.0-bookworm
timeout-minutes: 30
steps:
- name: Checkout
uses: https://gitee.com/mirrors_actions/checkout@v4
with:
github-server-url: https://git.gongxue100.com
fetch-depth: 1
- name: Install dependencies
run: npm ci
- name: Lint
run: |
npm run lint -w @gongxue/admin
npm run lint -w @gongxue/server -- --quiet
- name: Type check
run: npm run typecheck
- name: Build frontend
run: npm run build -w @gongxue/admin
- name: Run backend tests
run: npm run test -w @gongxue/server -- --runInBand --forceExit

View File

@@ -0,0 +1,80 @@
# PM2 手动部署工作流
# 手动触发 → 构建 → rsync → 安装依赖 → 数据库迁移 → PM2 重载
#
# 前置准备:
# 1. 服务器 MySQL 已在运行
# 2. 服务器已安装 PM2: npm i -g pm2
# 3. Gitea 仓库 Settings → Secrets 配置:
# - SSH_PRIVATE_KEY : 部署用 SSH 私钥
# - SSH_HOST : 服务器地址
# - SSH_USER : SSH 用户名
# - SSH_PORT : SSH 端口(默认 22可选
# - REMOTE_DIR : 服务器项目目录,如 /opt/gongxue
name: PM2 部署
on:
workflow_dispatch:
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: 检出代码
uses: actions/checkout@v4
- name: 安装 Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: 安装依赖 & 构建
run: |
npm ci
npm run build -w @gongxue/server
npm run build -w @gongxue/admin
- name: 配置 SSH
run: |
mkdir -p ~/.ssh
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
cat >> ~/.ssh/config <<'EOF'
Host deploy-server
HostName ${{ secrets.SSH_HOST }}
User ${{ secrets.SSH_USER }}
Port ${{ secrets.SSH_PORT || '22' }}
IdentityFile ~/.ssh/deploy_key
StrictHostKeyChecking accept-new
EOF
- name: 同步代码到服务器
run: |
rsync -avz --delete \
--exclude='node_modules' \
--exclude='.git' \
--exclude='*.db' \
--exclude='.DS_Store' \
--exclude='logs/' \
--exclude='.turbo/' \
--exclude='.claude/' \
--exclude='.codegraph/' \
./ deploy-server:${{ secrets.REMOTE_DIR }}/
- name: 安装依赖 → 迁移 → PM2 重载
run: |
ssh deploy-server "
cd ${{ secrets.REMOTE_DIR }}
mkdir -p logs
if [ ! -d node_modules ]; then
echo '首次部署,安装生产依赖...'
npm ci --omit=dev
fi
echo '执行数据库迁移...'
npm run migration:run -w @gongxue/server
echo 'PM2 重载...'
pm2 startOrReload ecosystem.config.cjs --update-env
pm2 save
echo '=== PM2 状态 ==='
pm2 status
"

1
.gitignore vendored
View File

@@ -20,6 +20,7 @@ build/
# 上传文件合同PDF等敏感文件不入版本库和部署包
uploads/
backend/uploads/
data/ai-attachments/
# 日志
logs/

View File

@@ -8,3 +8,7 @@ In repositories indexed by CodeGraph (a `.codegraph/` directory exists at the re
If there is no `.codegraph/` directory, skip CodeGraph entirely — indexing is the user's decision.
<!-- CODEGRAPH_END -->
## Ant Design X
修改 AI 助手、SSE 消息、运行时技能、附件或 Agent 工具前,先读取 `docs/skills/ant-design-x/SKILL.md`,优先使用项目已安装的 Ant Design X 组件与 SDK。

View File

@@ -1,14 +0,0 @@
FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
COPY apps/admin/package.json ./apps/admin/package.json
COPY packages/typescript-config/package.json ./packages/typescript-config/package.json
RUN npm ci
COPY . .
RUN npm run build -w @gongxue/admin
FROM nginx:alpine
COPY --from=builder /app/apps/admin/dist /usr/share/nginx/html
COPY apps/admin/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

View File

@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>恭学教育基地管理系统</title>
<title>学生管理系统</title>
</head>
<body>
<div id="root"></div>

View File

@@ -14,11 +14,18 @@
},
"dependencies": {
"@ant-design/icons": "^6.1.1",
"@ant-design/x": "^2.8.0",
"@ant-design/x-markdown": "^2.8.0",
"@ant-design/x-sdk": "^2.8.0",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"antd": "^6.3.6",
"axios": "^1.15.1",
"dayjs": "^1.11.20",
"echarts": "^6.0.0",
"echarts-for-react": "^3.0.6",
"lucide-react": "^0.468.0",
"react": "^19.2.5",
"react-dom": "^19.2.5",
"react-router-dom": "^7.14.1",

View File

@@ -1,182 +0,0 @@
.counter {
font-size: 16px;
padding: 5px 10px;
border-radius: 5px;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.hero {
position: relative;
.base,
.framework,
.vite {
inset-inline: 0;
margin: 0 auto;
}
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg) scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg) scale(0.8);
}
}
#center {
display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
}
#next-steps {
display: flex;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
#next-steps ul {
list-style: none;
padding: 0;
display: flex;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center;
gap: 8px;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap;
justify-content: center;
li {
flex: 1 1 calc(50% - 8px);
}
a {
width: 100%;
justify-content: center;
box-sizing: border-box;
}
}
}
#spacer {
height: 88px;
border-top: 1px solid var(--border);
@media (max-width: 1024px) {
height: 48px;
}
}
.ticks {
position: relative;
width: 100%;
&::before,
&::after {
content: '';
position: absolute;
top: -4.5px;
border: 5px solid transparent;
}
&::before {
left: 0;
border-left-color: var(--border);
}
&::after {
right: 0;
border-right-color: var(--border);
}
}

View File

@@ -1,6 +1,8 @@
import React, { Suspense, lazy } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { ConfigProvider, App as AntdApp, Spin } from 'antd';
import { XProvider } from '@ant-design/x';
import xZhCN from '@ant-design/x/es/locale/zh_CN';
import zhCN from 'antd/es/locale/zh_CN';
import MainLayout from './layouts/MainLayout';
import PermissionRoute from './components/PermissionRoute';
@@ -14,6 +16,7 @@ const RoomsPage = lazy(() => import('./pages/Rooms'));
const OccupanciesPage = lazy(() => import('./pages/Occupancies'));
const ExpensesPage = lazy(() => import('./pages/Expenses'));
const BillsPage = lazy(() => import('./pages/Bills'));
const WalletsPage = lazy(() => import('./pages/Wallets'));
const RoomVisualPage = lazy(() => import('./pages/RoomVisual'));
const OperationLogsPage = lazy(() => import('./pages/OperationLogs'));
const UsersPage = lazy(() => import('./pages/Users'));
@@ -23,13 +26,16 @@ const TeachersPage = lazy(() => import('./pages/Teachers'));
const StudentProfilePage = lazy(() => import('./pages/StudentProfile'));
const ClassesPage = lazy(() => import('./pages/Classes'));
const ClassDetailPage = lazy(() => import('./pages/Classes/detail'));
const OrganizationsPage = lazy(() => import('./pages/Organizations'))
const ExamsPage = lazy(() => import('./pages/Exams'));
const ExamDetailPage = lazy(() => import('./pages/Exams/detail'));
const OrganizationsPage = lazy(() => import('./pages/Organizations'));
const ClassroomRentalsPage = lazy(() => import('./pages/ClassroomRentals'));
const ClassroomSchedulePage = lazy(() => import('./pages/ClassroomSchedule'));
const SchedulesPage = lazy(() => import('./pages/Schedules'));
const RolesPage = lazy(() => import('./pages/Roles'));
const PermissionsPage = lazy(() => import('./pages/Permissions'));
const AttendancePage = lazy(() => import('./pages/Attendance'));
const AttendanceDevicesPage = lazy(() => import('./pages/AttendanceDevices'));
const TeacherWorkspacePage = lazy(() => import('./pages/TeacherWorkspace'));
const NotificationsPage = lazy(() => import('./pages/Notifications'));
const IntegrationConfigPage = lazy(() => import('./pages/IntegrationConfig'));
@@ -54,242 +60,291 @@ const App: React.FC = () => {
},
}}
>
<AntdApp>
<AppMessageBridge />
<BrowserRouter>
<Suspense fallback={<div style={{ minHeight: '40vh', display: 'grid', placeItems: 'center' }}><Spin size="large" /></div>}>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route
path="/"
element={
<PrivateRoute>
<MainLayout />
</PrivateRoute>
}
>
<Route index element={<DefaultRoute />} />
<XProvider
locale={{ ...zhCN, ...xZhCN }}
theme={{
token: { colorPrimary: '#007AFF', borderRadius: 10 },
components: {
Sender: { colorBorder: '#d9d9de' },
Bubble: { colorBgContainer: '#f5f7fa' },
},
}}
>
<AntdApp>
<AppMessageBridge />
<BrowserRouter>
<Suspense
fallback={
<div style={{ minHeight: '40vh', display: 'grid', placeItems: 'center' }}>
<Spin size="large" />
</div>
}
>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route
path="dashboard"
path="/"
element={
<PermissionRoute permission="dashboard:view">
<DashboardPage />
</PermissionRoute>
<PrivateRoute>
<MainLayout />
</PrivateRoute>
}
/>
<Route
path="room-visual"
element={
<PermissionRoute permission="room:view">
<RoomVisualPage />
</PermissionRoute>
}
/>
<Route
path="students"
element={
<PermissionRoute permission="student:view">
<StudentsPage />
</PermissionRoute>
}
/>
>
<Route index element={<DefaultRoute />} />
<Route
path="dashboard"
element={
<PermissionRoute permission="dashboard:view">
<DashboardPage />
</PermissionRoute>
}
/>
<Route
path="room-visual"
element={
<PermissionRoute permission="room:view">
<RoomVisualPage />
</PermissionRoute>
}
/>
<Route
path="students"
element={
<PermissionRoute permission="student:view">
<StudentsPage />
</PermissionRoute>
}
/>
<Route
path="students/:id/profile"
element={
<PermissionRoute permission="student:view">
<StudentProfilePage />
</PermissionRoute>
}
/>
<Route
path="rooms"
element={
<PermissionRoute permission="room:view">
<RoomsPage />
</PermissionRoute>
}
/>
<Route
path="occupancies"
element={
<PermissionRoute permission="occupancy:view">
<OccupanciesPage />
</PermissionRoute>
}
/>
<Route
path="expenses"
element={
<PermissionRoute permission="expense:view">
<ExpensesPage />
</PermissionRoute>
}
/>
<Route
path="deposits"
element={
<PermissionRoute permission="deposit:view">
<DepositsPage />
</PermissionRoute>
}
/>
<Route
path="bills"
element={
<PermissionRoute permission="bill:view">
<BillsPage />
</PermissionRoute>
}
/>
<Route
path="classes"
element={
<PermissionRoute permission="class:view">
<ClassesPage />
</PermissionRoute>
}
/>
<Route
path="classes/:id"
element={
<PermissionRoute permission="class:view">
<ClassDetailPage />
</PermissionRoute>
}
/>
<Route
path="operation-logs"
element={
<PermissionRoute permission="log:view">
<OperationLogsPage />
</PermissionRoute>
}
/>
<Route
path="roles"
element={
<PermissionRoute permission="role:view">
<RolesPage />
</PermissionRoute>
}
/>
<Route
path="permissions"
element={
<PermissionRoute permission="role:view">
<PermissionsPage />
</PermissionRoute>
}
/>
<Route
path="users"
element={
<PermissionRoute permission="user:view">
<UsersPage />
</PermissionRoute>
}
/>
<Route
path="teachers"
element={
<PermissionRoute permission="teacher:view">
<TeachersPage />
</PermissionRoute>
}
/>
<Route
path="classrooms"
element={
<PermissionRoute permission="classroom:view">
<ClassroomsPage />
</PermissionRoute>
}
/>
<Route
path="organizations"
element={
<PermissionRoute permission="organization:view">
<OrganizationsPage />
</PermissionRoute>
}
/>
<Route
path="classroom-rentals"
element={
<PermissionRoute permission="rental:view">
<ClassroomRentalsPage />
</PermissionRoute>
}
/>
<Route
path="classroom-schedule"
element={
<PermissionRoute permission="rental:view">
<ClassroomSchedulePage />
</PermissionRoute>
}
/>
<Route
path="students/:id/profile"
element={
<PermissionRoute permission="student:view">
<StudentProfilePage />
</PermissionRoute>
}
/>
<Route
path="rooms"
element={
<PermissionRoute permission="room:view">
<RoomsPage />
</PermissionRoute>
}
/>
<Route
path="occupancies"
element={
<PermissionRoute permission="occupancy:view">
<OccupanciesPage />
</PermissionRoute>
}
/>
<Route
path="expenses"
element={
<PermissionRoute permission="expense:view">
<ExpensesPage />
</PermissionRoute>
}
/>
<Route
path="deposits"
element={
<PermissionRoute permission="deposit:view">
<DepositsPage />
</PermissionRoute>
}
/>
<Route
path="wallets"
element={
<PermissionRoute permission="wallet:view">
<WalletsPage />
</PermissionRoute>
}
/>
<Route
path="bills"
element={
<PermissionRoute permission="bill:view">
<BillsPage />
</PermissionRoute>
}
/>
<Route
path="classes"
element={
<PermissionRoute permission="class:view">
<ClassesPage />
</PermissionRoute>
}
/>
<Route
path="classes/:id"
element={
<PermissionRoute permission="class:view">
<ClassDetailPage />
</PermissionRoute>
}
/>
<Route
path="exams"
element={
<PermissionRoute permission="exam:view">
<ExamsPage />
</PermissionRoute>
}
/>
<Route
path="exams/:id"
element={
<PermissionRoute permission="exam:view">
<ExamDetailPage />
</PermissionRoute>
}
/>
<Route
path="operation-logs"
element={
<PermissionRoute permission="log:view">
<OperationLogsPage />
</PermissionRoute>
}
/>
<Route
path="roles"
element={
<PermissionRoute permission="role:view">
<RolesPage />
</PermissionRoute>
}
/>
<Route
path="permissions"
element={
<PermissionRoute permission="role:view">
<PermissionsPage />
</PermissionRoute>
}
/>
<Route
path="users"
element={
<PermissionRoute permission="user:view">
<UsersPage />
</PermissionRoute>
}
/>
<Route
path="teachers"
element={
<PermissionRoute permission="teacher:view">
<TeachersPage />
</PermissionRoute>
}
/>
<Route
path="classrooms"
element={
<PermissionRoute permission="classroom:view">
<ClassroomsPage />
</PermissionRoute>
}
/>
<Route
path="organizations"
element={
<PermissionRoute permission="organization:view">
<OrganizationsPage />
</PermissionRoute>
}
/>
<Route
path="classroom-rentals"
element={
<PermissionRoute permission="rental:view">
<ClassroomRentalsPage />
</PermissionRoute>
}
/>
<Route
path="classroom-schedule"
element={
<PermissionRoute permission="rental:view">
<ClassroomSchedulePage />
</PermissionRoute>
}
/>
<Route
path="attendance"
element={
<PermissionRoute permission="attendance:view">
<AttendancePage />
</PermissionRoute>
}
/>
<Route
path="attendance-devices"
element={
<PermissionRoute permission="classroom:view">
<AttendanceDevicesPage />
</PermissionRoute>
}
/>
<Route
path="schedules"
element={
<PermissionRoute permission="schedule:view">
<SchedulesPage />
</PermissionRoute>
}
/>
<Route
path="attendance"
element={
<PermissionRoute permission="attendance:view">
<AttendancePage />
</PermissionRoute>
}
/>
<Route
path="teacher-workspace"
element={
<PermissionRoute permission="teacher-workspace:view">
<TeacherWorkspacePage />
</PermissionRoute>
}
/>
<Route
path="schedules"
element={
<PermissionRoute permission="schedule:view">
<SchedulesPage />
</PermissionRoute>
}
/>
<Route
path="notifications"
element={
<PermissionRoute permission="notification:view">
<NotificationsPage />
</PermissionRoute>
}
/>
<Route
path="teacher-workspace"
element={
<PermissionRoute permission="teacher-workspace:view">
<TeacherWorkspacePage />
</PermissionRoute>
}
/>
<Route
path="notifications"
element={
<PermissionRoute permission="notification:view">
<NotificationsPage />
</PermissionRoute>
}
/>
<Route
path="integration-config"
element={
<PermissionRoute permission="integration:read">
<IntegrationConfigPage />
</PermissionRoute>
}
/>
<Route
path="integration-config"
element={
<PermissionRoute permission="integration:read">
<IntegrationConfigPage />
</PermissionRoute>
}
/>
<Route
path="ai-config"
element={
<PermissionRoute permission="ai:config:read">
<AiConfigPage />
</PermissionRoute>
}
/>
</Route>
</Routes>
<Route
path="ai-config"
element={
<PermissionRoute permission="ai:config:read">
<AiConfigPage />
</PermissionRoute>
}
/>
</Route>
</Routes>
</Suspense>
</BrowserRouter>
</AntdApp>
</BrowserRouter>
</AntdApp>
</XProvider>
</ConfigProvider>
);
};

View File

@@ -1,4 +1,5 @@
import axios, { type AxiosRequestConfig } from 'axios';
import { clearPermissions } from '../auth/permission-store';
const instance = axios.create({
baseURL: '/api',
@@ -16,10 +17,12 @@ instance.interceptors.request.use((config) => {
instance.interceptors.response.use(
(res) => res.data,
(err) => {
if (err.response?.status === 401) {
const isLoginRequest = err.config?.url === '/auth/login' || err.config?.url === 'auth/login';
if (err.response?.status === 401 && !isLoginRequest) {
localStorage.removeItem('token');
localStorage.removeItem('user');
localStorage.removeItem('permissions');
clearPermissions();
window.location.href = '/login';
}
if (err.response?.status === 403) {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

Before

Width:  |  Height:  |  Size: 4.0 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 8.5 KiB

View File

@@ -11,6 +11,7 @@ const academicPermissions = [
'dashboard:view',
'student:view',
'class:view',
'exam:view',
'teacher:view',
'schedule:view',
'attendance:view',
@@ -45,9 +46,7 @@ describe('role-aware menu policy', () => {
'/attendance',
'/notifications',
]);
expect(findRoleAwareLandingPath(['任课老师'], teacherPermissions)).toBe(
'/teacher-workspace',
);
expect(findRoleAwareLandingPath(['任课老师'], teacherPermissions)).toBe('/teacher-workspace');
});
it('places schedules and attendance only once in academic management', () => {
@@ -56,6 +55,7 @@ describe('role-aware menu policy', () => {
expect(menu.map((item) => item.label)).toEqual(['数据面板', '教务管理', '通知中心']);
expect(paths.filter((path) => path === '/schedules')).toHaveLength(1);
expect(paths.filter((path) => path === '/attendance')).toHaveLength(1);
expect(paths).toContain('/exams');
expect(paths).not.toContain('/teacher-workspace');
});

View File

@@ -43,7 +43,12 @@ const SECTIONS: MenuSection[] = [
icon: 'calendar',
roles: ['teacher'],
children: [
{ key: '/teacher-workspace', label: '今日教学', icon: 'workspace', permission: 'teacher-workspace:view' },
{
key: '/teacher-workspace',
label: '今日教学',
icon: 'workspace',
permission: 'teacher-workspace:view',
},
{ key: '/schedules', label: '我的排课', icon: 'calendar', permission: 'schedule:view' },
{ key: '/attendance', label: '课程考勤', icon: 'attendance', permission: 'attendance:view' },
],
@@ -56,6 +61,7 @@ const SECTIONS: MenuSection[] = [
children: [
{ key: '/students', label: '学生管理', icon: 'students', permission: 'student:view' },
{ key: '/classes', label: '班级管理', icon: 'classes', permission: 'class:view' },
{ key: '/exams', label: '考试管理', icon: 'exam', permission: 'exam:view' },
{ key: '/teachers', label: '教师管理', icon: 'teachers', permission: 'teacher:view' },
{ key: '/schedules', label: '排课管理', icon: 'calendar', permission: 'schedule:view' },
{ key: '/attendance', label: '历史考勤', icon: 'attendance', permission: 'attendance:view' },
@@ -73,6 +79,7 @@ const SECTIONS: MenuSection[] = [
{ key: '/occupancies', label: '入住管理', icon: 'occupancy', permission: 'occupancy:view' },
{ key: '/expenses', label: '费用管理', icon: 'expense', permission: 'expense:view' },
{ key: '/bills', label: '账单管理', icon: 'bill', permission: 'bill:view' },
{ key: '/wallets', label: '学生余额', icon: 'wallet', permission: 'wallet:view' },
{ key: '/deposits', label: '押金管理', icon: 'deposit', permission: 'deposit:view' },
],
},
@@ -82,10 +89,26 @@ const SECTIONS: MenuSection[] = [
icon: 'classroom',
roles: ['classroom', 'super'],
children: [
{ key: '/classroom-schedule', label: '教室排期', icon: 'calendar', permission: 'rental:view' },
{
key: '/classroom-schedule',
label: '教室排期',
icon: 'calendar',
permission: 'rental:view',
},
{ key: '/classrooms', label: '教室管理', icon: 'classroom', permission: 'classroom:view' },
{
key: '/attendance-devices',
label: '考勤机绑定',
icon: 'attendance',
permission: 'classroom:view',
},
{ key: '/classroom-rentals', label: '租赁订单', icon: 'rental', permission: 'rental:view' },
{ key: '/organizations', label: '机构管理', icon: 'organization', permission: 'organization:view' },
{
key: '/organizations',
label: '机构管理',
icon: 'organization',
permission: 'organization:view',
},
],
},
{
@@ -98,21 +121,30 @@ const SECTIONS: MenuSection[] = [
{ key: '/roles', label: '角色管理', icon: 'role', permission: 'role:view' },
{ key: '/permissions', label: '权限一览', icon: 'permission', permission: 'role:view' },
{ key: '/operation-logs', label: '操作日志', icon: 'log', permission: 'log:view' },
{ key: '/integration-config', label: '钉钉集成', icon: 'integration', permission: 'integration:read' },
{
key: '/integration-config',
label: '钉钉集成',
icon: 'integration',
permission: 'integration:read',
},
{ key: '/ai-config', label: 'AI 配置', icon: 'ai', permission: 'ai:config:read' },
],
},
];
export function getRoleDomains(roles: readonly string[], permissions: readonly string[]): Set<string> {
export function getRoleDomains(
roles: readonly string[],
permissions: readonly string[],
): Set<string> {
const normalized = new Set(roles.map((role) => ROLE_ALIASES[role]).filter(Boolean));
// 权限可以来自多个叠加角色,因此业务域按能力累加,而不是只选择一个。
if (permissions.includes('student:view') || permissions.includes('class:view')) {
normalized.add('academic');
}
if (
permissions.includes('room:view') &&
(permissions.includes('occupancy:view') || permissions.includes('expense:view'))
(permissions.includes('room:view') &&
(permissions.includes('occupancy:view') || permissions.includes('expense:view'))) ||
permissions.includes('wallet:view')
) {
normalized.add('accommodation');
}
@@ -164,7 +196,8 @@ export function buildMenu(roles: readonly string[], permissions: readonly string
const children = section.children
.filter((child) => permissionSet.has(child.permission))
.map(({ permission: _, ...child }) => child);
if (children.length > 0) sections.push({ ...section, children, roles: undefined } as AppMenuItem);
if (children.length > 0)
sections.push({ ...section, children, roles: undefined } as AppMenuItem);
}
if (permissionSet.has('notification:view')) {

View File

@@ -13,11 +13,7 @@ describe('permission navigation', () => {
it('lands teachers on the teacher workspace without global student or class access', () => {
expect(
findFirstAccessiblePath([
'teacher-workspace:view',
'schedule:view',
'attendance:view',
]),
findFirstAccessiblePath(['teacher-workspace:view', 'schedule:view', 'attendance:view']),
).toBe('/teacher-workspace');
expect(canAccessPath('/students', ['teacher-workspace:view'])).toBe(false);
expect(canAccessPath('/classes', ['teacher-workspace:view'])).toBe(false);
@@ -34,6 +30,7 @@ describe('permission navigation', () => {
it('keeps route permission lookup aligned for nested detail routes', () => {
expect(getRequiredPermission('/classes/12')).toBe('class:view');
expect(getRequiredPermission('/students/8/profile')).toBe('student:view');
expect(getRequiredPermission('/exams/8')).toBe('exam:view');
expect(canAccessPath('/ai-config', ['ai:config:read'])).toBe(true);
expect(canAccessPath('/ai-config', ['integration:read'])).toBe(false);
});

View File

@@ -14,12 +14,26 @@ export const PERMISSION_PAGES: readonly PermissionPage[] = [
{ path: '/rooms', permission: 'room:view' },
{ path: '/occupancies', permission: 'occupancy:view' },
{ path: '/teacher-workspace', permission: 'teacher-workspace:view' },
{ path: '/students', permission: 'student:view', matches: (p) => p === '/students' || /^\/students\/\d+\/profile$/.test(p) },
{ path: '/classes', permission: 'class:view', matches: (p) => p === '/classes' || /^\/classes\/\d+$/.test(p) },
{
path: '/students',
permission: 'student:view',
matches: (p) => p === '/students' || /^\/students\/\d+\/profile$/.test(p),
},
{
path: '/classes',
permission: 'class:view',
matches: (p) => p === '/classes' || /^\/classes\/\d+$/.test(p),
},
{
path: '/exams',
permission: 'exam:view',
matches: (p) => p === '/exams' || /^\/exams\/\d+$/.test(p),
},
{ path: '/attendance', permission: 'attendance:view' },
{ path: '/schedules', permission: 'schedule:view' },
{ path: '/classroom-schedule', permission: 'rental:view' },
{ path: '/classrooms', permission: 'classroom:view' },
{ path: '/attendance-devices', permission: 'classroom:view' },
{ path: '/classroom-rentals', permission: 'rental:view' },
{ path: '/organizations', permission: 'organization:view' },
{ path: '/expenses', permission: 'expense:view' },

View File

@@ -0,0 +1,65 @@
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, beforeAll, describe, expect, it } from 'vitest';
import PermissionButton from '../components/PermissionButton';
import {
beginPermissionVerification,
clearPermissions,
readPermissionState,
writePermissions,
} from './permission-store';
let container: HTMLDivElement | null = null;
let root: ReturnType<typeof createRoot> | null = null;
beforeAll(() => {
(
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
});
async function renderPermissionButton() {
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
await act(async () => {
root?.render(<PermissionButton permission="student:edit"></PermissionButton>);
});
}
afterEach(async () => {
if (root) await act(async () => root?.unmount());
container?.remove();
root = null;
container = null;
clearPermissions();
});
describe('permission state', () => {
it('ignores cached localStorage permissions until profile verification succeeds', async () => {
localStorage.setItem('permissions', JSON.stringify(['student:edit']));
beginPermissionVerification();
expect(readPermissionState()).toEqual({ permissions: [], status: 'loading' });
await renderPermissionButton();
expect(container?.textContent).not.toContain('编辑学生');
});
it('renders permission actions only after verified permissions are written', async () => {
beginPermissionVerification();
await renderPermissionButton();
expect(container?.textContent).not.toContain('编辑学生');
await act(async () => writePermissions(['student:edit']));
expect(container?.textContent).toContain('编辑学生');
});
it('stays fail-closed while profile verification is retried after a failure', async () => {
writePermissions(['student:edit']);
beginPermissionVerification();
expect(readPermissionState()).toEqual({ permissions: [], status: 'loading' });
await renderPermissionButton();
expect(container?.textContent).not.toContain('编辑学生');
});
});

View File

@@ -1,15 +1,40 @@
export const PERMISSIONS_UPDATED_EVENT = 'permissions-updated';
export type PermissionStatus = 'unknown' | 'loading' | 'ready';
export interface PermissionState {
permissions: string[];
status: PermissionStatus;
}
let permissionState: PermissionState = { permissions: [], status: 'unknown' };
function notifyPermissionStateChanged(): void {
window.dispatchEvent(new Event(PERMISSIONS_UPDATED_EVENT));
}
export function readPermissionState(): PermissionState {
return permissionState;
}
export function readPermissions(): string[] {
try {
const value = JSON.parse(localStorage.getItem('permissions') || '[]');
return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
} catch {
return [];
}
return permissionState.status === 'ready' ? permissionState.permissions : [];
}
export function beginPermissionVerification(): void {
permissionState = { permissions: [], status: 'loading' };
notifyPermissionStateChanged();
}
export function writePermissions(permissions: string[]): void {
localStorage.setItem('permissions', JSON.stringify([...new Set(permissions)]));
window.dispatchEvent(new Event(PERMISSIONS_UPDATED_EVENT));
const uniquePermissions = [...new Set(permissions)];
localStorage.setItem('permissions', JSON.stringify(uniquePermissions));
permissionState = { permissions: uniquePermissions, status: 'ready' };
notifyPermissionStateChanged();
}
export function clearPermissions(status: PermissionStatus = 'unknown'): void {
localStorage.removeItem('permissions');
permissionState = { permissions: [], status };
notifyPermissionStateChanged();
}

View File

@@ -0,0 +1,541 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
DeleteOutlined,
EditOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
PlusOutlined,
RobotOutlined,
} from '@ant-design/icons';
import {
Attachments,
Bubble,
Conversations,
Prompts,
Sender,
Welcome,
} from '@ant-design/x';
import type {
BubbleItemType,
BubbleListProps,
ConversationItemType,
PromptsItemType,
} from '@ant-design/x';
import type { Attachment } from '@ant-design/x/es/attachments';
import { useXChat, useXConversations, type MessageInfo } from '@ant-design/x-sdk';
import { Button, Drawer, Dropdown, Grid, Input, Modal, Spin, Tooltip, Typography } from 'antd';
import type { MenuProps, UploadFile, UploadProps } from 'antd';
import { message } from '../../ui/app-message';
import { aiChatApi, conversationStreamUrl } from './api';
import { AiMessageContent } from './AiMessageContent';
import { mapHistoryMessage } from './message-mappers';
import { GongxueAiChatProvider } from './provider';
import type {
AiAttachment,
AiChatInput,
AiChatMessage,
AiChatMessageStatus,
AiConversation,
AiSkill,
AiSseChunk,
} from './types';
import './style.css';
interface AiChatDrawerProps {
open: boolean;
onClose: () => void;
}
interface ConversationData extends AiConversation {
key: string;
label: string;
}
function sortConversations(items: AiConversation[]): AiConversation[] {
return [...items].sort((a, b) => {
const aTime = new Date(a.lastMessageAt || a.updatedAt).getTime();
const bTime = new Date(b.lastMessageAt || b.updatedAt).getTime();
return bTime - aTime;
});
}
function toConversationData(item: AiConversation): ConversationData {
return { ...item, key: String(item.id), label: item.title };
}
function toUploadFile(attachment: AiAttachment): Attachment<AiAttachment> {
return {
uid: String(attachment.id),
name: attachment.name,
size: attachment.size,
status: attachment.status === 'ready' ? 'done' : attachment.status === 'failed' ? 'error' : 'uploading',
url: attachment.url,
response: attachment,
description: attachment.error || undefined,
cardType: attachment.mimeType.startsWith('image/') ? 'image' : 'file',
};
}
function emptyAssistant(): AiChatMessage {
return {
role: 'assistant',
content: '',
reasoningContent: '',
toolRuns: [],
attachments: [],
};
}
export const aiBubbleRoles: BubbleListProps['role'] = {
user: { placement: 'end', variant: 'filled', shape: 'corner' },
assistant: { placement: 'start', variant: 'borderless' },
};
const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose }) => {
const screens = Grid.useBreakpoint();
const isMobile = !screens.sm;
const [loadingList, setLoadingList] = useState(false);
const [sidebarOpen, setSidebarOpen] = useState(!isMobile);
const [input, setInput] = useState('');
const [skills, setSkills] = useState<AiSkill[]>([]);
const [attachments, setAttachments] = useState<AiAttachment[]>([]);
const requestingRef = useRef(false);
const abortRef = useRef<() => void>(() => undefined);
const attachmentsRef = useRef<AiAttachment[]>([]);
const {
conversations,
activeConversationKey,
setActiveConversationKey,
addConversation,
removeConversation,
setConversation,
setConversations,
} = useXConversations({});
const activeConversation = useMemo(
() => conversations.find((item) => item.key === activeConversationKey) as ConversationData | undefined,
[activeConversationKey, conversations],
);
const activeId = activeConversation?.id ?? null;
const lockedSkill = skills.find((skill) => skill.key === activeConversation?.lockedSkillKey);
useEffect(() => setSidebarOpen(!isMobile), [isMobile]);
const refreshConversations = useCallback(async () => {
const items = sortConversations(await aiChatApi.listConversations()).map(toConversationData);
setConversations(items);
const current = activeConversationKey;
setActiveConversationKey(
current && items.some((item) => item.key === current) ? current : (items[0]?.key ?? ''),
);
}, [activeConversationKey, setActiveConversationKey, setConversations]);
const provider = useMemo(
() =>
activeId
? new GongxueAiChatProvider(conversationStreamUrl(activeId), () => {
void refreshConversations();
})
: undefined,
[activeId, refreshConversations],
);
const { messages, onRequest, onReload, isRequesting, abort, setMessage } = useXChat<
AiChatMessage,
AiChatMessage,
AiChatInput,
AiSseChunk
>({
provider,
conversationKey: activeConversationKey || 'no-conversation',
defaultMessages: async () => {
if (!activeId) return [];
const page = await aiChatApi.listMessages(activeId);
return page.items.map(mapHistoryMessage);
},
requestPlaceholder: emptyAssistant(),
requestFallback: (
params: Partial<AiChatInput>,
{ error, messageInfo }: { error: Error; messageInfo: MessageInfo<AiChatMessage> },
) => ({
...(params.reloadMessage || messageInfo?.message || emptyAssistant()),
error: error.name === 'AbortError' ? undefined : '连接中断,请稍后重试',
cancelled: error.name === 'AbortError',
}),
});
requestingRef.current = isRequesting;
abortRef.current = abort;
attachmentsRef.current = attachments;
const stopRequest = useCallback(() => {
if (requestingRef.current) abortRef.current();
}, []);
const discardPendingAttachments = useCallback(() => {
const pending = attachmentsRef.current;
attachmentsRef.current = [];
setAttachments([]);
for (const attachment of pending) {
void aiChatApi.deleteAttachment(attachment.id).catch(() => undefined);
}
}, []);
useEffect(() => {
if (!open) return;
let cancelled = false;
setLoadingList(true);
Promise.all([aiChatApi.listSkills(), aiChatApi.listConversations()])
.then(async ([skillItems, conversationItems]) => {
if (cancelled) return;
setSkills(skillItems);
let next = sortConversations(conversationItems);
if (!next.length) next = [await aiChatApi.createConversation()];
const data = next.map(toConversationData);
setConversations(data);
setActiveConversationKey(data[0]?.key ?? '');
})
.catch(() => message.error('加载 AI 助手失败'))
.finally(() => !cancelled && setLoadingList(false));
return () => {
cancelled = true;
};
}, [open, setActiveConversationKey, setConversations]);
useEffect(() => {
discardPendingAttachments();
if (isMobile) setSidebarOpen(false);
}, [activeConversationKey, discardPendingAttachments, isMobile]);
useEffect(() => () => stopRequest(), [stopRequest]);
const createConversation = useCallback(async () => {
try {
stopRequest();
const created = toConversationData(await aiChatApi.createConversation());
addConversation(created, 'prepend');
setActiveConversationKey(created.key);
if (isMobile) setSidebarOpen(false);
} catch {
message.error('新建会话失败');
}
}, [addConversation, isMobile, setActiveConversationKey, stopRequest]);
const renameConversation = useCallback(
(conversation: ConversationData) => {
let title = conversation.title;
Modal.confirm({
title: '重命名会话',
icon: <EditOutlined />,
content: <Input defaultValue={title} maxLength={100} onChange={(event) => (title = event.target.value)} />,
okText: '保存',
cancelText: '取消',
onOk: async () => {
const normalized = title.trim();
if (!normalized) throw new Error('请输入会话名称');
const updated = toConversationData(
await aiChatApi.updateConversation(conversation.id, { title: normalized }),
);
setConversation(conversation.key, updated);
},
});
},
[setConversation],
);
const deleteConversation = useCallback(
(conversation: ConversationData) => {
Modal.confirm({
title: '删除会话',
content: '该会话及全部历史消息将被永久删除。',
okText: '删除',
okButtonProps: { danger: true },
cancelText: '取消',
onOk: async () => {
if (conversation.id === activeId) stopRequest();
await aiChatApi.deleteConversation(conversation.id);
removeConversation(conversation.key);
const remaining = conversations.filter((item) => item.key !== conversation.key);
if (!remaining.length) {
const created = toConversationData(await aiChatApi.createConversation());
addConversation(created, 'prepend');
setActiveConversationKey(created.key);
} else if (conversation.id === activeId) {
setActiveConversationKey(remaining[0].key);
}
},
});
},
[activeId, addConversation, conversations, removeConversation, setActiveConversationKey, stopRequest],
);
const conversationMenu = useCallback(
(item: ConversationItemType): MenuProps => ({
items: [
{ key: 'rename', label: '重命名', icon: <EditOutlined /> },
{ key: 'delete', label: '删除', icon: <DeleteOutlined />, danger: true },
],
onClick: ({ key, domEvent }) => {
domEvent.stopPropagation();
const conversation = conversations.find((entry) => entry.key === item.key) as ConversationData;
if (key === 'rename') renameConversation(conversation);
if (key === 'delete') deleteConversation(conversation);
},
}),
[conversations, deleteConversation, renameConversation],
);
const setLockedSkill = useCallback(
async (skillKey: string | null) => {
if (!activeConversation) return;
try {
const updated = toConversationData(
await aiChatApi.updateConversation(activeConversation.id, { lockedSkillKey: skillKey }),
);
setConversation(activeConversation.key, updated);
} catch {
message.error('切换技能失败');
}
},
[activeConversation, setConversation],
);
const submit = useCallback(
(value: string) => {
const text = value.trim();
if (!text || !activeId || isRequesting) return;
const submittedAttachments = attachmentsRef.current;
attachmentsRef.current = [];
onRequest({
message: text,
attachmentIds: submittedAttachments.map((item) => item.id),
skillKey: activeConversation?.lockedSkillKey ?? null,
clientRequestId: crypto.randomUUID(),
localAttachments: submittedAttachments,
});
setInput('');
setAttachments([]);
}, [activeConversation?.lockedSkillKey, activeId, isRequesting, onRequest]);
const reloadMessage = useCallback(
(messageInfo: MessageInfo<AiChatMessage>) => {
if (!activeId || typeof messageInfo.message.id !== 'number') return;
onReload(messageInfo.id, {
message: '',
attachmentIds: [],
skillKey: activeConversation?.lockedSkillKey ?? null,
clientRequestId: crypto.randomUUID(),
regenerateMessageId: messageInfo.message.id,
reloadMessage: messageInfo.message,
});
},
[activeConversation?.lockedSkillKey, activeId, onReload],
);
const updateFeedback = useCallback(
async (messageInfo: MessageInfo<AiChatMessage>, feedback: 'like' | 'dislike' | null) => {
if (typeof messageInfo.message.id !== 'number') return;
try {
await aiChatApi.setFeedback(messageInfo.message.id, feedback);
setMessage(messageInfo.id, {
message: { ...messageInfo.message, feedback },
});
} catch {
message.error('提交反馈失败');
}
},
[setMessage],
);
const customUpload = useCallback<NonNullable<UploadProps['customRequest']>>(async (options) => {
const file = options.file as File;
if (attachmentsRef.current.length >= 5) {
const error = new Error('每条消息最多添加 5 个附件');
options.onError?.(error);
message.warning(error.message);
return;
}
try {
const uploaded = await aiChatApi.uploadAttachment(file);
setAttachments((items) => [...items, uploaded]);
options.onSuccess?.(uploaded, file);
} catch (error) {
options.onError?.(error instanceof Error ? error : new Error('附件上传失败'));
message.error('附件上传失败');
}
}, []);
const removeAttachment = useCallback(async (file: UploadFile<AiAttachment>) => {
const attachment = file.response;
if (!attachment) return true;
try {
await aiChatApi.deleteAttachment(attachment.id);
setAttachments((items) => items.filter((item) => item.id !== attachment.id));
return true;
} catch {
message.error('删除附件失败');
return false;
}
}, []);
const uploadItems = useMemo(() => attachments.map(toUploadFile), [attachments]);
const promptItems = useMemo<PromptsItemType[]>(
() =>
(lockedSkill ? [lockedSkill] : skills)
.flatMap((skill) => skill.examples.slice(0, lockedSkill ? 4 : 1).map((example) => ({ skill, example })))
.slice(0, 5)
.map(({ skill, example }) => ({
key: `${skill.key}-${example}`,
label: example,
description: skill.name,
})),
[lockedSkill, skills],
);
const bubbleItems = useMemo<BubbleItemType[]>(
() =>
messages.map((info) => ({
key: info.id,
role: info.message.role === 'assistant' ? 'assistant' : 'user',
status: info.status,
content: info.message,
contentRender: (content: AiChatMessage) => (
<AiMessageContent
message={content}
status={info.status as AiChatMessageStatus}
onReload={content.role === 'assistant' && info.status !== 'loading' ? () => reloadMessage(info) : undefined}
onFeedback={content.role === 'assistant' ? (feedback) => void updateFeedback(info, feedback) : undefined}
/>
),
})),
[messages, reloadMessage, updateFeedback],
);
const skillMenu: MenuProps = {
items: [
{ key: 'auto', label: '自动选择技能' },
{ type: 'divider' },
...skills.map((skill) => ({ key: skill.key, label: skill.name })),
],
selectedKeys: [activeConversation?.lockedSkillKey || 'auto'],
onClick: ({ key }) => void setLockedSkill(key === 'auto' ? null : key),
};
return (
<Drawer
title={<span className="ai-chat-title"><RobotOutlined /> AI </span>}
open={open}
onClose={() => {
stopRequest();
discardPendingAttachments();
onClose();
}}
width={isMobile ? '100%' : 'min(1040px, 92vw)'}
destroyOnHidden={false}
className="ai-chat-drawer"
styles={{ body: { padding: 0, height: '100%' } }}
>
<div className="ai-chat-layout">
<aside className={`ai-chat-sidebar${sidebarOpen ? ' is-open' : ''}`}>
<Conversations
items={conversations as ConversationItemType[]}
activeKey={activeConversationKey}
onActiveChange={(key) => {
stopRequest();
setActiveConversationKey(key);
}}
menu={conversationMenu}
creation={{ label: '新对话', icon: <PlusOutlined />, onClick: createConversation }}
/>
{loadingList && <Spin className="ai-chat-sidebar__loading" />}
</aside>
<main className="ai-chat-main">
<div className="ai-chat-toolbar">
<Tooltip title={sidebarOpen ? '收起会话' : '展开会话'}>
<Button
type="text"
icon={sidebarOpen ? <MenuFoldOutlined /> : <MenuUnfoldOutlined />}
onClick={() => setSidebarOpen((value) => !value)}
/>
</Tooltip>
<Typography.Text ellipsis>{activeConversation?.title || 'AI 助手'}</Typography.Text>
<Dropdown menu={skillMenu} trigger={['click']}>
<Button size="small">{lockedSkill?.name || '自动技能'}</Button>
</Dropdown>
</div>
<div className="ai-chat-messages">
{messages.length ? (
<Bubble.List items={bubbleItems} role={aiBubbleRoles} autoScroll />
) : (
<div className="ai-chat-welcome">
<Welcome
variant="borderless"
icon={<RobotOutlined />}
title="你好,我是功学 AI 助手"
description={lockedSkill?.description || '我会在你的权限范围内查询学生、考勤、宿舍、账单和经营数据。'}
/>
<Prompts
title="你可以这样问"
items={promptItems}
wrap
onItemClick={({ data }) => submit(String(data.label || ''))}
/>
</div>
)}
</div>
<div className="ai-chat-composer">
<Sender
value={input}
onChange={setInput}
loading={isRequesting}
onSubmit={submit}
onCancel={stopRequest}
autoSize={{ minRows: 1, maxRows: 6 }}
placeholder="询问学生、考勤、宿舍或账单数据"
skill={
lockedSkill
? {
title: lockedSkill.name,
value: lockedSkill.key,
closable: { onClose: () => void setLockedSkill(null) },
}
: undefined
}
header={
uploadItems.length ? (
<Attachments
items={uploadItems}
customRequest={customUpload}
onRemove={removeAttachment}
accept="image/jpeg,image/png,image/webp,application/pdf,.docx,.xlsx"
multiple
/>
) : false
}
prefix={
<Attachments
items={[]}
customRequest={customUpload}
onRemove={removeAttachment}
accept="image/jpeg,image/png,image/webp,application/pdf,.docx,.xlsx"
multiple
placeholder={{ title: '添加附件', description: '图片、PDF、Word、Excel单个不超过 10MB' }}
>
<Button type="text" size="small"></Button>
</Attachments>
}
/>
<Typography.Text type="secondary" className="ai-chat-disclaimer">
AI
</Typography.Text>
</div>
</main>
</div>
</Drawer>
);
};
export default AiChatDrawer;

View File

@@ -0,0 +1,195 @@
import React, { useMemo } from 'react';
import {
CheckCircleOutlined,
CloseCircleOutlined,
CopyOutlined,
DislikeFilled,
DislikeOutlined,
LikeFilled,
LikeOutlined,
LoadingOutlined,
ReloadOutlined,
} from '@ant-design/icons';
import { Actions, CodeHighlighter, FileCard, Think, ThoughtChain } from '@ant-design/x';
import type { ThoughtChainItemType } from '@ant-design/x';
import XMarkdown from '@ant-design/x-markdown';
import type { ComponentProps } from '@ant-design/x-markdown';
import { Alert, Flex, Space, Typography } from 'antd';
import type {
AiAttachment,
AiChatMessage,
AiChatMessageStatus,
AiMessageFeedback,
AiToolRun,
} from './types';
const toolLabels: Record<string, string> = {
search_students: '查询学生',
get_student_basic: '读取学生信息',
search_classes: '查询班级',
get_attendance_summary: '统计考勤',
search_rooms: '查询房间',
get_room_occupancy_summary: '统计入住',
search_bills: '查询账单',
get_dashboard_stats: '读取经营概览',
};
const markdownComponents = {
code: ({ children, lang, block }: ComponentProps) => {
const content = String(children ?? '').replace(/\n$/, '');
if (!block) return <code>{content}</code>;
return <CodeHighlighter lang={lang || 'text'}>{content}</CodeHighlighter>;
},
};
const markdownSanitizerConfig = {
ALLOW_UNKNOWN_PROTOCOLS: false,
FORBID_TAGS: ['script', 'style', 'iframe', 'object', 'embed', 'form'],
FORBID_ATTR: ['style'],
};
function attachmentIcon(attachment: AiAttachment) {
if (attachment.mimeType === 'application/pdf') return 'pdf' as const;
if (attachment.mimeType.includes('wordprocessingml')) return 'word' as const;
if (attachment.mimeType.includes('spreadsheetml')) return 'excel' as const;
if (attachment.mimeType.startsWith('image/')) return 'image' as const;
return 'default' as const;
}
async function openAttachment(attachment: AiAttachment): Promise<void> {
const token = localStorage.getItem('token');
const response = await fetch(attachment.url, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
});
if (!response.ok) throw new Error('附件打开失败');
const objectUrl = URL.createObjectURL(await response.blob());
window.open(objectUrl, '_blank', 'noopener,noreferrer');
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 60_000);
}
function ToolChain({ tools }: { tools: AiToolRun[] }) {
const items = useMemo<ThoughtChainItemType[]>(
() =>
tools.map((tool) => {
const running = tool.status === 'running';
const success = tool.status === 'success';
return {
key: tool.toolCallId,
title: toolLabels[tool.toolName] || tool.toolName,
description: tool.durationMs ? `${tool.durationMs}ms` : undefined,
content: tool.summary || (running ? '正在查询业务数据' : success ? '查询完成' : '查询失败'),
status: running ? 'loading' : success ? 'success' : 'error',
icon: running ? (
<LoadingOutlined spin />
) : success ? (
<CheckCircleOutlined />
) : (
<CloseCircleOutlined />
),
collapsible: Boolean(tool.summary),
};
}),
[tools],
);
return <ThoughtChain items={items} line="solid" />;
}
export interface AiMessageContentProps {
message: AiChatMessage;
status?: AiChatMessageStatus;
onReload?: () => void;
onFeedback?: (feedback: AiMessageFeedback) => void;
}
export const AiMessageContent: React.FC<AiMessageContentProps> = ({
message,
status,
onReload,
onFeedback,
}) => {
const streaming = status === 'loading' || status === 'updating';
const attachmentCards = message.attachments.map((attachment) => (
<FileCard
key={attachment.id}
name={attachment.name}
byte={attachment.size}
size="small"
icon={attachmentIcon(attachment)}
onClick={() => void openAttachment(attachment)}
/>
));
if (message.role === 'user') {
return (
<Space direction="vertical" size={8} className="ai-chat-user-content">
{attachmentCards.length > 0 && <Flex wrap gap={8}>{attachmentCards}</Flex>}
<div className="ai-chat-user-text">{message.content}</div>
</Space>
);
}
const actionItems = [
{
key: 'copy',
label: '复制',
icon: <CopyOutlined />,
onItemClick: () => void navigator.clipboard.writeText(message.content),
},
...(onReload
? [{ key: 'reload', label: '重新生成', icon: <ReloadOutlined />, onItemClick: onReload }]
: []),
...(onFeedback
? [
{
key: 'like',
label: '有帮助',
icon: message.feedback === 'like' ? <LikeFilled /> : <LikeOutlined />,
onItemClick: () => onFeedback(message.feedback === 'like' ? null : 'like'),
},
{
key: 'dislike',
label: '没帮助',
icon: message.feedback === 'dislike' ? <DislikeFilled /> : <DislikeOutlined />,
onItemClick: () => onFeedback(message.feedback === 'dislike' ? null : 'dislike'),
},
]
: []),
];
return (
<Space direction="vertical" size={10} className="ai-chat-answer">
{message.reasoningContent && (
<Think title={streaming ? '正在思考' : '思考过程'} loading={streaming} defaultExpanded={false}>
<XMarkdown
content={message.reasoningContent}
components={markdownComponents}
escapeRawHtml
openLinksInNewTab
dompurifyConfig={markdownSanitizerConfig}
streaming={{ hasNextChunk: streaming, tail: streaming }}
/>
</Think>
)}
{message.toolRuns.length > 0 && <ToolChain tools={message.toolRuns} />}
{attachmentCards.length > 0 && <Flex wrap gap={8}>{attachmentCards}</Flex>}
{message.content && (
<XMarkdown
content={message.content}
components={markdownComponents}
escapeRawHtml
openLinksInNewTab
dompurifyConfig={markdownSanitizerConfig}
streaming={{
hasNextChunk: streaming,
enableAnimation: true,
tail: streaming,
incompleteMarkdownComponentMap: { link: 'span', image: 'span', table: 'div' },
}}
/>
)}
{message.error && <Alert type="error" showIcon message={message.error} />}
{message.cancelled && <Typography.Text type="secondary"></Typography.Text>}
{!streaming && message.content && <Actions items={actionItems} fadeIn />}
</Space>
);
};

View File

@@ -0,0 +1,40 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import api from '../../api';
import { aiChatApi } from './api';
describe('AI chat API adapter', () => {
afterEach(() => vi.restoreAllMocks());
it('unwraps the backend success/data response', async () => {
vi.spyOn(api, 'get').mockResolvedValue({
success: true,
data: [
{
id: 1,
title: '会话',
lockedSkillKey: null,
createdAt: '2026-07-23T00:00:00.000Z',
updatedAt: '2026-07-23T00:00:00.000Z',
lastMessageAt: null,
},
],
});
await expect(aiChatApi.listConversations()).resolves.toMatchObject([{ id: 1, title: '会话' }]);
});
it('loads every history page in chronological page order', async () => {
vi.spyOn(api, 'get')
.mockResolvedValueOnce({
success: true,
data: { items: [{ id: 1 }], total: 101, page: 1, limit: 100 },
})
.mockResolvedValueOnce({
success: true,
data: { items: [{ id: 101 }], total: 101, page: 2, limit: 100 },
});
const page = await aiChatApi.listMessages(3);
expect(page.items.map((item) => item.id)).toEqual([1, 101]);
});
});

View File

@@ -0,0 +1,73 @@
import api from '../../api';
import type {
AiApiResponse,
AiAttachment,
AiConversation,
AiMessageFeedback,
AiMessagePage,
AiSkill,
} from './types';
const basePath = '/ai/chat/conversations';
export const aiChatApi = {
listSkills: async () => (await api.get<AiApiResponse<AiSkill[]>>('/ai/chat/skills')).data,
listConversations: async () =>
(await api.get<AiApiResponse<AiConversation[]>>(basePath)).data,
createConversation: async (input?: { title?: string; lockedSkillKey?: string | null }) =>
(await api.post<AiApiResponse<AiConversation>>(basePath, input ?? {})).data,
updateConversation: async (
id: number,
input: { title?: string; lockedSkillKey?: string | null },
) => (await api.patch<AiApiResponse<AiConversation>>(`${basePath}/${id}`, input)).data,
deleteConversation: (id: number) => api.delete<void>(`${basePath}/${id}`),
uploadAttachment: async (file: File): Promise<AiAttachment> => {
const form = new FormData();
form.append('file', file);
return (
await api.post<AiApiResponse<AiAttachment>>('/ai/chat/attachments', form, {
headers: { 'Content-Type': 'multipart/form-data' },
timeout: 120_000,
})
).data;
},
deleteAttachment: (id: number) => api.delete<void>(`/ai/chat/attachments/${id}`),
setFeedback: async (
messageId: number,
feedback: AiMessageFeedback,
reason?: string,
) =>
(
await api.patch<AiApiResponse<{ id: number; feedback: AiMessageFeedback }>>(
`/ai/chat/messages/${messageId}/feedback`,
{ feedback, reason },
)
).data,
listMessages: async (id: number): Promise<AiMessagePage> => {
const first = (
await api.get<AiApiResponse<AiMessagePage>>(`${basePath}/${id}/messages`, {
params: { page: 1, limit: 100 },
})
).data;
const pageCount = Math.ceil(first.total / first.limit);
if (pageCount <= 1) return first;
const rest = await Promise.all(
Array.from({ length: pageCount - 1 }, (_, index) =>
api
.get<AiApiResponse<AiMessagePage>>(`${basePath}/${id}/messages`, {
params: { page: index + 2, limit: first.limit },
})
.then((response) => response.data),
),
);
return { ...first, items: [first, ...rest].flatMap((page) => page.items) };
},
};
export function conversationStreamUrl(id: number): string {
return `/api${basePath}/${id}/stream`;
}
export function regenerateStreamUrl(conversationId: number, messageId: number): string {
return `/api${basePath}/${conversationId}/messages/${messageId}/regenerate/stream`;
}

View File

@@ -0,0 +1,42 @@
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { Bubble } from '@ant-design/x';
import { afterEach, describe, expect, it } from 'vitest';
import { aiBubbleRoles } from './AiChatDrawer';
import type { AiChatMessage } from './types';
let container: HTMLDivElement | null = null;
let root: ReturnType<typeof createRoot> | null = null;
afterEach(async () => {
if (root) await act(async () => root?.unmount());
container?.remove();
root = null;
container = null;
});
describe('AI chat bubble rendering', () => {
it('renders a structured user message instead of passing the object to React', async () => {
const message: AiChatMessage = {
role: 'user',
content: '查询今天的系统概览',
reasoningContent: '',
toolRuns: [],
attachments: [],
};
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
await act(async () => {
root?.render(
<Bubble.List
role={aiBubbleRoles}
items={[{ key: 'user-1', role: 'user', status: 'local', content: message }]}
/>,
);
});
expect(container.textContent).toContain('查询今天的系统概览');
});
});

View File

@@ -0,0 +1,55 @@
import { describe, expect, it } from 'vitest';
import { mapHistoryMessage } from './message-mappers';
describe('AI chat history mapper', () => {
it('restores reasoning, tool summaries and completed status', () => {
const mapped = mapHistoryMessage({
id: 3,
role: 'assistant',
content: '回答',
reasoningContent: '思考',
status: 'completed',
errorCode: null,
createdAt: '2026-07-23T00:00:00.000Z',
feedback: 'like',
attachments: [
{
id: 8,
name: '考勤.pdf',
mimeType: 'application/pdf',
size: 100,
status: 'ready',
url: '/api/ai/chat/attachments/8',
createdAt: '2026-07-24T00:00:00.000Z',
},
],
toolRuns: [
{
toolCallId: 'tool-1',
toolName: 'search_rooms',
status: 'success',
resultSummary: '共 4 间',
},
],
});
expect(mapped.status).toBe('success');
expect(mapped.message.reasoningContent).toBe('思考');
expect(mapped.message.toolRuns[0].summary).toBe('共 4 间');
expect(mapped.message.attachments).toHaveLength(1);
expect(mapped.message.feedback).toBe('like');
});
it('maps failed and cancelled history to X SDK statuses', () => {
const base = {
id: 4,
role: 'assistant' as const,
content: '',
reasoningContent: null,
errorCode: 'UPSTREAM_ERROR',
createdAt: '2026-07-23T00:00:00.000Z',
};
expect(mapHistoryMessage({ ...base, status: 'failed' }).status).toBe('error');
expect(mapHistoryMessage({ ...base, status: 'cancelled' }).status).toBe('abort');
});
});

View File

@@ -0,0 +1,38 @@
import type { MessageInfo } from '@ant-design/x-sdk';
import type { AiChatMessage, AiChatMessageStatus, AiMessageRecord, AiToolRun } from './types';
function mapStatus(record: AiMessageRecord): AiChatMessageStatus {
if (record.status === 'pending') return 'loading';
if (record.status === 'failed') return 'error';
if (record.status === 'cancelled') return 'abort';
return record.role === 'user' ? 'local' : 'success';
}
function normalizeToolRun(tool: AiToolRun): AiToolRun {
return {
...tool,
status: tool.status === 'error' ? 'failed' : tool.status,
summary: tool.resultSummary ?? tool.argumentsSummary ?? tool.summary,
};
}
export function mapHistoryMessage(record: AiMessageRecord): MessageInfo<AiChatMessage> {
return {
id: record.id,
status: mapStatus(record),
message: {
id: record.id,
role: record.role,
content: record.content || '',
reasoningContent: record.reasoningContent || '',
toolRuns: (record.toolRuns || []).map(normalizeToolRun),
attachments: record.attachments ?? [],
replyToMessageId: record.replyToMessageId,
feedback: record.feedback,
feedbackReason: record.feedbackReason,
metadata: record.metadata,
error: record.status === 'failed' ? record.errorCode || 'AI 回答生成失败' : undefined,
cancelled: record.status === 'cancelled',
},
};
}

View File

@@ -0,0 +1,129 @@
import { describe, expect, it } from 'vitest';
import { parseSsePayload, reduceAiSseMessage } from './provider';
describe('AI chat SSE message reducer', () => {
it('separates reasoning and answer deltas', () => {
let message = reduceAiSseMessage(undefined, {
event: 'reasoning.delta',
data: JSON.stringify({ messageId: 8, delta: '分析' }),
});
message = reduceAiSseMessage(message, {
event: 'content.delta',
data: JSON.stringify({ delta: '**答案**' }),
});
expect(message.reasoningContent).toBe('分析');
expect(message.content).toBe('**答案**');
});
it('tracks tool lifecycle without exposing raw payloads', () => {
let message = reduceAiSseMessage(undefined, {
event: 'tool.started',
data: JSON.stringify({
toolCallId: 'call-1',
toolName: 'search_students',
summary: '姓名条件',
}),
});
message = reduceAiSseMessage(message, {
event: 'tool.completed',
data: JSON.stringify({
toolCallId: 'call-1',
toolName: 'search_students',
status: 'success',
summary: '找到 1 条记录',
}),
});
expect(message.toolRuns).toHaveLength(1);
expect(message.toolRuns[0]).toMatchObject({ status: 'success', summary: '找到 1 条记录' });
});
it('tracks processed attachments and final feedback state', () => {
let message = reduceAiSseMessage(undefined, {
event: 'attachment.processed',
data: JSON.stringify({
attachment: {
id: 4,
name: '名单.xlsx',
mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
size: 1200,
status: 'ready',
url: '/api/ai/chat/attachments/4',
createdAt: '2026-07-24T00:00:00.000Z',
},
}),
});
message = reduceAiSseMessage(message, {
event: 'message.completed',
data: JSON.stringify({
message: {
id: 12,
content: '完成',
reasoningContent: null,
feedback: 'like',
attachments: message.attachments,
},
}),
});
expect(message.attachments).toHaveLength(1);
expect(message.feedback).toBe('like');
});
it('uses final content and records cancellation and errors', () => {
let message = reduceAiSseMessage(undefined, {
event: 'message.completed',
data: JSON.stringify({
message: {
id: 12,
content: '最终回答',
reasoningContent: '完成',
status: 'completed',
toolRuns: [
{
toolCallId: 'nested-tool',
toolName: 'search_rooms',
status: 'success',
resultSummary: '共 4 间',
},
],
},
}),
});
message = reduceAiSseMessage(message, {
event: 'error',
data: JSON.stringify({ message: '上游服务不可用' }),
});
message = reduceAiSseMessage(message, {
event: 'message.cancelled',
data: JSON.stringify({ messageId: 12 }),
});
expect(message).toMatchObject({
id: 12,
content: '最终回答',
reasoningContent: '完成',
error: '上游服务不可用',
cancelled: true,
});
expect(message.toolRuns[0]).toMatchObject({ toolCallId: 'nested-tool', status: 'success' });
});
it('reads nested assistant message from message.created', () => {
const message = reduceAiSseMessage(undefined, {
event: 'message.created',
data: JSON.stringify({
message: { id: 9, content: '', reasoningContent: null, status: 'pending' },
}),
});
expect(message.id).toBe(9);
});
it('tolerates non-JSON event data', () => {
expect(parseSsePayload({ event: 'content.delta', data: 'plain text' })).toEqual({
event: 'content.delta',
payload: { delta: 'plain text' },
});
});
});

View File

@@ -0,0 +1,249 @@
import {
AbstractChatProvider,
XRequest,
type TransformMessage,
type XRequestOptions,
} from '@ant-design/x-sdk';
import type {
AiAttachment,
AiChatInput,
AiChatMessage,
AiSseChunk,
AiToolRun,
} from './types';
interface AiSsePayload {
messageId?: number;
userMessageId?: number;
assistantMessageId?: number;
delta?: string;
content?: string;
reasoningContent?: string | null;
toolCallId?: string;
toolName?: string;
skillKey?: string | null;
status?: string;
summary?: string | null;
durationMs?: number | null;
attachment?: AiAttachment;
message?:
| string
| {
id?: number;
content?: string;
reasoningContent?: string | null;
status?: string;
toolRuns?: AiToolRun[];
attachments?: AiAttachment[];
replyToMessageId?: number | null;
feedback?: 'like' | 'dislike' | null;
feedbackReason?: string | null;
metadata?: Record<string, unknown> | null;
};
error?: string;
}
function emptyAssistant(): AiChatMessage {
return {
role: 'assistant',
content: '',
reasoningContent: '',
toolRuns: [],
attachments: [],
};
}
export function parseSsePayload(chunk?: AiSseChunk): {
event: string;
payload: AiSsePayload;
} {
if (!chunk) return { event: '', payload: {} };
const event = chunk.event?.trim() || 'message';
if (!chunk.data || chunk.data === '[DONE]') return { event, payload: {} };
try {
const parsed: unknown = JSON.parse(chunk.data);
return {
event,
payload: parsed && typeof parsed === 'object' ? (parsed as AiSsePayload) : {},
};
} catch {
return { event, payload: { delta: chunk.data } };
}
}
function upsertToolRun(
toolRuns: AiToolRun[],
payload: AiSsePayload,
fallbackStatus: AiToolRun['status'],
): AiToolRun[] {
const toolCallId = payload.toolCallId || `${payload.toolName || 'tool'}-${toolRuns.length}`;
const next: AiToolRun = {
toolCallId,
toolName: payload.toolName || '查询工具',
skillKey: payload.skillKey,
status: (payload.status as AiToolRun['status']) || fallbackStatus,
summary: payload.summary,
resultSummary: fallbackStatus === 'running' ? undefined : payload.summary,
argumentsSummary: fallbackStatus === 'running' ? payload.summary : undefined,
durationMs: payload.durationMs,
};
const index = toolRuns.findIndex((item) => item.toolCallId === toolCallId);
if (index === -1) return [...toolRuns, next];
return toolRuns.map((item, itemIndex) => (itemIndex === index ? { ...item, ...next } : item));
}
function normalizeToolRuns(toolRuns: AiToolRun[] | undefined, fallback: AiToolRun[]): AiToolRun[] {
if (!toolRuns) return fallback;
return toolRuns.map((tool) => ({
...tool,
status: tool.status === 'error' ? 'failed' : tool.status,
summary: tool.resultSummary ?? tool.argumentsSummary ?? tool.summary,
}));
}
export function reduceAiSseMessage(
originMessage: AiChatMessage | undefined,
chunk?: AiSseChunk,
): AiChatMessage {
const message = originMessage ? { ...originMessage } : emptyAssistant();
const { event, payload } = parseSsePayload(chunk);
if (event === 'message.created') {
const nested = typeof payload.message === 'object' ? payload.message : undefined;
message.id = nested?.id ?? payload.assistantMessageId ?? payload.messageId ?? message.id;
message.content = nested?.content ?? message.content;
message.reasoningContent = nested?.reasoningContent ?? message.reasoningContent;
message.toolRuns = normalizeToolRuns(nested?.toolRuns, message.toolRuns);
message.attachments = nested?.attachments ?? message.attachments;
message.replyToMessageId = nested?.replyToMessageId ?? message.replyToMessageId;
message.feedback = nested?.feedback ?? message.feedback;
message.feedbackReason = nested?.feedbackReason ?? message.feedbackReason;
message.metadata = nested?.metadata ?? message.metadata;
} else if (event === 'reasoning.delta') {
message.reasoningContent += payload.delta ?? payload.reasoningContent ?? '';
} else if (event === 'content.delta') {
message.content += payload.delta ?? payload.content ?? '';
} else if (event === 'tool.started') {
message.toolRuns = upsertToolRun(message.toolRuns, payload, 'running');
} else if (event === 'tool.completed') {
message.toolRuns = upsertToolRun(message.toolRuns, payload, 'success');
} else if (event === 'tool.failed') {
message.toolRuns = upsertToolRun(message.toolRuns, payload, 'failed');
} else if (event === 'attachment.processed' && payload.attachment) {
if (!message.attachments.some((item) => item.id === payload.attachment?.id)) {
message.attachments = [...message.attachments, payload.attachment];
}
} else if (event === 'message.completed') {
const nested = typeof payload.message === 'object' ? payload.message : undefined;
message.id = nested?.id ?? payload.messageId ?? message.id;
message.content = nested?.content ?? payload.content ?? message.content;
message.reasoningContent =
nested?.reasoningContent ?? payload.reasoningContent ?? message.reasoningContent;
message.toolRuns = normalizeToolRuns(nested?.toolRuns, message.toolRuns);
message.attachments = nested?.attachments ?? message.attachments;
message.replyToMessageId = nested?.replyToMessageId ?? message.replyToMessageId;
message.feedback = nested?.feedback ?? message.feedback;
message.feedbackReason = nested?.feedbackReason ?? message.feedbackReason;
message.metadata = nested?.metadata ?? message.metadata;
} else if (event === 'message.cancelled') {
message.id = payload.messageId ?? message.id;
message.cancelled = true;
} else if (event === 'error') {
message.error =
(typeof payload.message === 'string' ? payload.message : undefined) ||
payload.error ||
'AI 回答生成失败';
}
return message;
}
async function authenticatedFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
const headers = new Headers(init?.headers);
const token = localStorage.getItem('token');
if (token) headers.set('Authorization', `Bearer ${token}`);
headers.set('Accept', 'text/event-stream');
let requestInput = input;
let requestInit = init;
if (typeof init?.body === 'string') {
try {
const body = JSON.parse(init.body) as AiChatInput;
if (body.regenerateMessageId) {
requestInput = `${String(input).replace(/\/stream$/, '')}/messages/${body.regenerateMessageId}/regenerate/stream`;
requestInit = {
...init,
body: JSON.stringify({ clientRequestId: body.clientRequestId }),
};
} else {
const {
localAttachments: _localAttachments,
reloadMessage: _reloadMessage,
regenerateMessageId: _regenerateMessageId,
...payload
} = body;
requestInit = { ...init, body: JSON.stringify(payload) };
}
} catch {
requestInit = init;
}
}
const response = await fetch(requestInput, { ...requestInit, headers });
if (response.status === 401) {
localStorage.removeItem('token');
localStorage.removeItem('user');
localStorage.removeItem('permissions');
window.location.href = '/login';
}
return response;
}
export class GongxueAiChatProvider extends AbstractChatProvider<
AiChatMessage,
AiChatInput,
AiSseChunk
> {
constructor(url: string, onSettled?: () => void) {
super({
request: XRequest<AiChatInput, AiSseChunk, AiChatMessage>(url, {
manual: true,
fetch: authenticatedFetch,
timeout: 15_000,
streamTimeout: 120_000,
callbacks: {
onUpdate: () => undefined,
onSuccess: () => onSettled?.(),
onError: () => onSettled?.(),
},
}),
});
}
transformParams(
requestParams: Partial<AiChatInput>,
options: XRequestOptions<AiChatInput, AiSseChunk, AiChatMessage>,
): AiChatInput {
return {
...options.params,
message: requestParams.message?.trim() || '',
attachmentIds: requestParams.attachmentIds ?? [],
skillKey: requestParams.skillKey ?? null,
clientRequestId: requestParams.clientRequestId || crypto.randomUUID(),
localAttachments: requestParams.localAttachments,
regenerateMessageId: requestParams.regenerateMessageId,
reloadMessage: requestParams.reloadMessage,
};
}
transformLocalMessage(requestParams: Partial<AiChatInput>): AiChatMessage {
return {
role: 'user',
content: requestParams.message?.trim() || '',
reasoningContent: '',
toolRuns: [],
attachments: requestParams.localAttachments ?? [],
};
}
transformMessage(info: TransformMessage<AiChatMessage, AiSseChunk>): AiChatMessage {
return reduceAiSseMessage(info.originMessage, info.chunk);
}
}

View File

@@ -0,0 +1,193 @@
.ai-chat-drawer .ant-drawer-body {
overflow: hidden;
}
.ai-chat-title {
display: flex;
align-items: center;
gap: 8px;
}
.ai-chat-layout {
position: relative;
display: flex;
height: 100%;
min-height: 0;
background: #fff;
}
.ai-chat-sidebar {
position: relative;
flex: 0 0 0;
width: 0;
min-width: 0;
overflow: hidden;
background: #f7f7f8;
border-right: 1px solid #e5e5e7;
transition: flex-basis 180ms ease;
}
.ai-chat-sidebar.is-open {
flex-basis: 248px;
width: 248px;
padding: 12px 8px;
}
.ai-chat-sidebar .ant-conversations {
width: 232px;
height: 100%;
overflow-y: auto;
}
.ai-chat-sidebar .ant-conversations-creation {
margin-bottom: 8px;
}
.ai-chat-sidebar__loading {
position: absolute;
inset: 68px 0 auto;
}
.ai-chat-main {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-width: 0;
min-height: 0;
}
.ai-chat-toolbar {
display: flex;
flex: 0 0 48px;
align-items: center;
gap: 8px;
min-width: 0;
padding: 0 12px;
border-bottom: 1px solid #ededf0;
}
.ai-chat-toolbar .ant-typography {
flex: 1 1 auto;
min-width: 0;
font-weight: 600;
}
.ai-chat-welcome {
display: grid;
width: min(720px, 100%);
gap: 20px;
padding: 32px;
}
.ai-chat-welcome .ant-welcome-icon {
color: #007aff;
}
.ai-chat-messages {
display: flex;
flex: 1 1 auto;
align-items: center;
justify-content: center;
min-height: 0;
overflow: hidden;
}
.ai-chat-messages > .ant-bubble-list {
width: 100%;
height: 100%;
padding: 20px clamp(16px, 4vw, 48px);
}
.ai-chat-messages .ant-bubble-content {
max-width: min(100%, 680px);
}
.ai-chat-user-text {
max-width: 100%;
overflow-wrap: anywhere;
white-space: pre-wrap;
}
.ai-chat-user-content {
max-width: 100%;
}
.ai-chat-answer {
width: 100%;
min-width: 0;
}
.ai-chat-answer .ant-space-item,
.ai-chat-answer .ant-x-markdown {
min-width: 0;
max-width: 100%;
}
.ai-chat-answer pre,
.ai-chat-answer table {
max-width: 100%;
overflow-x: auto;
}
.ai-chat-answer .ant-thought-chain {
padding: 10px 12px;
background: #f7f8fa;
border: 1px solid #eceef2;
border-radius: 10px;
}
.ai-chat-composer {
flex: 0 0 auto;
padding: 12px clamp(12px, 3vw, 32px) 14px;
background: #fff;
border-top: 1px solid #ededf0;
}
.ai-chat-composer .ant-sender {
max-width: 820px;
margin: 0 auto;
}
.ai-chat-composer .ant-attachments {
max-width: 820px;
}
.ai-chat-composer .ant-sender-input:focus,
.ai-chat-composer .ant-sender-input:focus-visible,
.ai-chat-composer .ant-sender-input:focus-within {
outline: none;
box-shadow: none;
}
.ai-chat-disclaimer {
display: block;
margin-top: 6px;
font-size: 11px;
text-align: center;
}
@media (max-width: 575px) {
.ai-chat-sidebar {
position: absolute;
z-index: 2;
inset: 0 auto 0 0;
box-shadow: 8px 0 24px rgba(0, 0, 0, 0.08);
}
.ai-chat-sidebar.is-open {
width: min(82vw, 300px);
flex-basis: min(82vw, 300px);
}
.ai-chat-sidebar .ant-conversations {
width: calc(min(82vw, 300px) - 16px);
}
.ai-chat-messages > .ant-bubble-list {
padding: 14px 12px;
}
.ai-chat-messages .ant-bubble-content {
max-width: 92%;
}
}

View File

@@ -0,0 +1,117 @@
export interface AiConversation {
id: number;
title: string;
lockedSkillKey: string | null;
createdAt: string;
updatedAt: string;
lastMessageAt: string | null;
}
export interface AiSkillTool {
name: string;
description: string;
}
export interface AiSkill {
key: string;
name: string;
description: string;
examples: string[];
tools: AiSkillTool[];
}
export interface AiAttachment {
id: number;
name: string;
mimeType: string;
size: number;
status: 'processing' | 'ready' | 'failed';
error?: string | null;
url: string;
createdAt: string;
}
export type AiToolRunStatus =
| 'running'
| 'success'
| 'error'
| 'failed'
| 'denied'
| 'not_found';
export interface AiToolRun {
id?: number;
toolCallId: string;
toolName: string;
skillKey?: string | null;
status: AiToolRunStatus;
summary?: string | null;
argumentsSummary?: string | null;
resultSummary?: string | null;
durationMs?: number | null;
}
export type AiMessageRole = 'user' | 'assistant';
export type AiMessageFeedback = 'like' | 'dislike' | null;
export interface AiChatMessage {
id?: number | string;
role: AiMessageRole;
content: string;
reasoningContent: string;
toolRuns: AiToolRun[];
attachments: AiAttachment[];
replyToMessageId?: number | null;
feedback?: AiMessageFeedback;
feedbackReason?: string | null;
metadata?: Record<string, unknown> | null;
error?: string;
cancelled?: boolean;
}
export interface AiMessageRecord {
id: number;
role: AiMessageRole;
content: string;
reasoningContent: string | null;
status: 'pending' | 'completed' | 'failed' | 'cancelled';
errorCode: string | null;
replyToMessageId?: number | null;
feedback?: AiMessageFeedback;
feedbackReason?: string | null;
metadata?: Record<string, unknown> | null;
attachments?: AiAttachment[];
createdAt: string;
toolRuns?: AiToolRun[];
}
export interface AiMessagePage {
items: AiMessageRecord[];
total: number;
page: number;
limit: number;
}
export interface AiChatInput {
message: string;
attachmentIds: number[];
skillKey: string | null;
clientRequestId: string;
localAttachments?: AiAttachment[];
regenerateMessageId?: number;
reloadMessage?: AiChatMessage;
}
export type AiChatMessageStatus = 'local' | 'loading' | 'updating' | 'success' | 'error' | 'abort';
export interface AiApiResponse<T> {
success: boolean;
data: T;
message?: string;
}
export interface AiSseChunk {
event?: string;
data?: string;
id?: string;
}

View File

@@ -1,11 +1,14 @@
import React from 'react';
import { Navigate } from 'react-router-dom';
import { Result } from 'antd';
import { Result, Spin } from 'antd';
import { usePermission } from '../hooks/usePermission';
import { findRoleAwareLandingPath } from '../auth/menu-policy';
const DefaultRoute: React.FC = () => {
const { permissions } = usePermission();
const { permissions, permissionsReady } = usePermission();
if (!permissionsReady) {
return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;
}
const roles = (() => {
try {
return JSON.parse(localStorage.getItem('user') || '{}').roles || [];
@@ -15,7 +18,9 @@ const DefaultRoute: React.FC = () => {
})();
const firstPath = findRoleAwareLandingPath(roles, permissions);
if (firstPath) return <Navigate to={firstPath} replace />;
return <Result status="403" title="暂无可访问功能" subTitle="请联系管理员为当前账号分配功能权限" />;
return (
<Result status="403" title="暂无可访问功能" subTitle="请联系管理员为当前账号分配功能权限" />
);
};
export default DefaultRoute;

View File

@@ -0,0 +1,177 @@
import React, { act } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, describe, expect, it, vi } from 'vitest';
import dayjs from 'dayjs';
import EditableCell, {
editableValuesEqual,
normalizeEditableValue,
serializeEditableValue,
} from './index';
let container: HTMLDivElement | null = null;
let root: ReturnType<typeof createRoot> | null = null;
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
const dispatchPointer = (
target: Element,
type: 'pointerdown' | 'pointerup',
init: { pointerType: 'touch' | 'mouse'; pointerId?: number; clientX?: number; clientY?: number },
) => {
const event = new Event(type, { bubbles: true });
Object.defineProperties(event, {
pointerType: { value: init.pointerType },
pointerId: { value: init.pointerId ?? 1 },
clientX: { value: init.clientX ?? 0 },
clientY: { value: init.clientY ?? 0 },
});
target.dispatchEvent(event);
};
afterEach(async () => {
if (root) {
await act(async () => root?.unmount());
}
container?.remove();
root = null;
container = null;
});
describe('editable cell value mapping', () => {
it('normalizes and serializes date values', () => {
const value = normalizeEditableValue('2026-07-21', 'date');
expect(dayjs.isDayjs(value)).toBe(true);
expect(serializeEditableValue(value, 'date')).toBe('2026-07-21');
});
it('normalizes and serializes date ranges', () => {
const value = normalizeEditableValue(['2026-07-01', '2026-07-31'], 'date-range');
expect(serializeEditableValue(value, 'date-range')).toEqual(['2026-07-01', '2026-07-31']);
});
it('converts numeric input and preserves zero', () => {
expect(serializeEditableValue(normalizeEditableValue('12.50', 'money'), 'money')).toBe(12.5);
expect(serializeEditableValue(0, 'number')).toBe(0);
});
it('normalizes empty and multi-select values', () => {
expect(serializeEditableValue('', 'number')).toBeUndefined();
expect(normalizeEditableValue(undefined, 'multi-select')).toEqual([]);
});
it('compares structured values without reference equality', () => {
expect(editableValuesEqual([1, 2], [1, 2])).toBe(true);
expect(editableValuesEqual(' a ', 'a')).toBe(false);
});
});
describe('editable cell interactions', () => {
const renderTextCell = async () => {
const onSave = vi.fn(async () => undefined);
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
await act(async () => {
root?.render(
React.createElement(EditableCell, { value: '张三', onSave }, '张三'),
);
});
return container.querySelector('.editable-cell') as HTMLElement;
};
it('keeps a single touch tap read-only', async () => {
const cell = await renderTextCell();
await act(async () => {
dispatchPointer(cell, 'pointerdown', { pointerType: 'touch', clientX: 10, clientY: 10 });
dispatchPointer(cell, 'pointerup', { pointerType: 'touch', clientX: 12, clientY: 11 });
await flush();
});
expect(container?.querySelector('.editable-cell--editing')).toBeNull();
});
it('enters edit mode after two nearby touch taps', async () => {
const cell = await renderTextCell();
await act(async () => {
dispatchPointer(cell, 'pointerdown', { pointerType: 'touch', clientX: 10, clientY: 10 });
dispatchPointer(cell, 'pointerup', { pointerType: 'touch', clientX: 11, clientY: 10 });
dispatchPointer(cell, 'pointerdown', { pointerType: 'touch', clientX: 12, clientY: 11 });
dispatchPointer(cell, 'pointerup', { pointerType: 'touch', clientX: 12, clientY: 11 });
await flush();
});
expect(container?.querySelector('.editable-cell--editing')).toBeTruthy();
});
it('keeps mouse single-click behavior read-only', async () => {
const cell = await renderTextCell();
await act(async () => {
dispatchPointer(cell, 'pointerdown', { pointerType: 'mouse' });
dispatchPointer(cell, 'pointerup', { pointerType: 'mouse' });
await flush();
});
expect(container?.querySelector('.editable-cell--editing')).toBeNull();
});
it('does not edit when a touch gesture scrolls the table', async () => {
const cell = await renderTextCell();
await act(async () => {
dispatchPointer(cell, 'pointerdown', { pointerType: 'touch', clientX: 10, clientY: 10 });
dispatchPointer(cell, 'pointerup', { pointerType: 'touch', clientX: 30, clientY: 10 });
await flush();
});
expect(container?.querySelector('.editable-cell--editing')).toBeNull();
});
it('saves a single-select value immediately when an option is clicked', async () => {
const onSave = vi.fn(async () => undefined);
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
await act(async () => {
root?.render(
React.createElement(
EditableCell,
{
value: 'active',
editor: 'select',
options: [
{ value: 'active', label: '启用' },
{ value: 'disabled', label: '停用' },
],
onSave,
},
'启用',
),
);
});
await act(async () => {
container?.querySelector('.editable-cell')?.dispatchEvent(
new MouseEvent('dblclick', { bubbles: true }),
);
await flush();
});
const options = Array.from(document.querySelectorAll<HTMLElement>('.ant-select-item-option'));
const disabledOption = options.find((option) => option.textContent?.includes('停用'));
expect(disabledOption).toBeTruthy();
await act(async () => {
disabledOption?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
await flush();
});
expect(onSave).toHaveBeenCalledOnce();
expect(onSave).toHaveBeenCalledWith('disabled');
expect(container.querySelector('.editable-cell--editing')).toBeNull();
});
});

View File

@@ -0,0 +1,318 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { DatePicker, Input, InputNumber, Select, Spin, Tooltip } from 'antd';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import { usePermission } from '../../hooks/usePermission';
import { message } from '../../ui/app-message';
import './style.css';
export type EditableCellEditor =
| 'text'
| 'textarea'
| 'number'
| 'money'
| 'date'
| 'date-range'
| 'select'
| 'multi-select'
| 'tags';
export interface EditableCellOption {
label: React.ReactNode;
value: string | number | boolean;
}
export interface EditableCellProps<Value = unknown> {
value: Value;
children?: React.ReactNode;
editor?: EditableCellEditor;
options?: EditableCellOption[];
permission?: string;
disabled?: boolean;
required?: boolean;
min?: number;
max?: number;
placeholder?: string;
formatValue?: (value: Value) => unknown;
parseValue?: (value: unknown) => Value;
onSave: (value: Value) => Promise<void>;
}
let activeCell: { id: string; save: () => Promise<boolean> } | null = null;
let replayingOutsideAction = false;
export function normalizeEditableValue(value: unknown, editor: EditableCellEditor) {
if (editor === 'date') return value ? dayjs(value as string) : null;
if (editor === 'date-range')
return Array.isArray(value) ? value.map((item) => dayjs(item as string)) : null;
if (editor === 'number' || editor === 'money') {
return value === null || value === undefined || value === '' ? null : Number(value);
}
if (editor === 'multi-select' || editor === 'tags') return Array.isArray(value) ? value : [];
return value ?? '';
}
export function serializeEditableValue(value: unknown, editor: EditableCellEditor) {
if (editor === 'date') return value ? (value as Dayjs).format('YYYY-MM-DD') : undefined;
if (editor === 'date-range')
return Array.isArray(value)
? value.map((item) => (item as Dayjs).format('YYYY-MM-DD'))
: undefined;
if (editor === 'number' || editor === 'money') {
return value === null || value === undefined || value === '' ? undefined : Number(value);
}
if (typeof value === 'string') return value.trim();
return value;
}
export function editableValuesEqual(left: unknown, right: unknown) {
return JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
}
function isEditorOverlay(target: EventTarget | null) {
return (
target instanceof Element &&
!!target.closest('.ant-select-dropdown, .ant-picker-dropdown, .ant-tooltip, .ant-message')
);
}
const EditableCell = <Value,>({
value,
children,
editor = 'text',
options,
permission,
disabled,
required,
min,
max,
placeholder,
formatValue,
parseValue,
onSave,
}: EditableCellProps<Value>) => {
const { hasPermission } = usePermission();
const idRef = useRef(crypto.randomUUID());
const rootRef = useRef<HTMLDivElement>(null);
const touchStartRef = useRef<{ pointerId: number; x: number; y: number } | null>(null);
const lastTouchTapRef = useRef<{ time: number; x: number; y: number } | null>(null);
const [editing, setEditing] = useState(false);
const [saving, setSaving] = useState(false);
const [draft, setDraft] = useState<unknown>(() =>
normalizeEditableValue(formatValue ? formatValue(value) : value, editor),
);
const enabled = !disabled && (!permission || hasPermission(permission));
const original = useMemo(
() =>
serializeEditableValue(
normalizeEditableValue(formatValue ? formatValue(value) : value, editor),
editor,
),
[editor, formatValue, value],
);
useEffect(() => {
if (!editing) {
setDraft(normalizeEditableValue(formatValue ? formatValue(value) : value, editor));
}
}, [editing, editor, formatValue, value]);
const cancel = useCallback(() => {
setDraft(normalizeEditableValue(formatValue ? formatValue(value) : value, editor));
if (activeCell?.id === idRef.current) activeCell = null;
setEditing(false);
}, [editor, formatValue, value]);
const saveValue = useCallback(async (nextDraft: unknown) => {
if (saving) return false;
const serialized = serializeEditableValue(nextDraft, editor);
if (required && (serialized === '' || serialized === undefined || serialized === null)) {
message.error('该字段不能为空');
return false;
}
if (editableValuesEqual(serialized, original)) {
if (activeCell?.id === idRef.current) activeCell = null;
setEditing(false);
return true;
}
setSaving(true);
try {
await onSave(parseValue ? parseValue(serialized) : (serialized as Value));
if (activeCell?.id === idRef.current) activeCell = null;
setEditing(false);
return true;
} catch (error) {
message.error((error as { message?: string })?.message || '保存失败');
return false;
} finally {
setSaving(false);
}
}, [editor, onSave, original, parseValue, required, saving]);
const save = useCallback(() => saveValue(draft), [draft, saveValue]);
useEffect(() => {
const cellId = idRef.current;
if (editing && activeCell?.id === cellId) activeCell.save = save;
return () => {
if (activeCell?.id === cellId) activeCell = null;
};
}, [editing, save]);
useEffect(() => {
if (!editing) return;
const onPointerDown = (event: PointerEvent) => {
if (replayingOutsideAction) return;
if (rootRef.current?.contains(event.target as Node) || isEditorOverlay(event.target)) return;
const actionTarget =
event.target instanceof Element
? (event.target.closest(
'button, a, input, label, [role="button"], .ant-pagination-item, .ant-pagination-prev, .ant-pagination-next',
) as HTMLElement | null)
: null;
if (!actionTarget) {
void save();
return;
}
event.preventDefault();
event.stopPropagation();
void save().then((saved) => {
if (!saved) return;
replayingOutsideAction = true;
actionTarget.click();
queueMicrotask(() => {
replayingOutsideAction = false;
});
});
};
document.addEventListener('pointerdown', onPointerDown, true);
return () => {
document.removeEventListener('pointerdown', onPointerDown, true);
};
}, [editing, save]);
const beginEdit = async () => {
if (!enabled || saving) return;
if (activeCell && activeCell.id !== idRef.current) {
const saved = await activeCell.save();
if (!saved) return;
}
activeCell = { id: idRef.current, save };
setEditing(true);
};
const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
if (event.pointerType !== 'touch' || editing) return;
touchStartRef.current = {
pointerId: event.pointerId,
x: event.clientX,
y: event.clientY,
};
};
const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
const touchStart = touchStartRef.current;
touchStartRef.current = null;
if (!touchStart || event.pointerType !== 'touch' || event.pointerId !== touchStart.pointerId) {
return;
}
const moved = Math.hypot(event.clientX - touchStart.x, event.clientY - touchStart.y);
if (moved > 8) {
lastTouchTapRef.current = null;
return;
}
const now = Date.now();
const lastTap = lastTouchTapRef.current;
const isDoubleTap =
!!lastTap &&
now - lastTap.time <= 450 &&
Math.hypot(event.clientX - lastTap.x, event.clientY - lastTap.y) <= 24;
lastTouchTapRef.current = isDoubleTap
? null
: { time: now, x: event.clientX, y: event.clientY };
if (isDoubleTap) void beginEdit();
};
const onKeyDown = async (event: React.KeyboardEvent) => {
if (event.key === 'Escape') {
event.preventDefault();
cancel();
return;
}
if (event.key === 'Enter' && editor !== 'textarea') {
event.preventDefault();
await save();
return;
}
if (event.key === 'Tab') await save();
};
const commonProps = {
autoFocus: true,
value: draft as never,
placeholder,
disabled: saving,
onChange: (next: unknown) =>
setDraft(
next && typeof next === 'object' && 'target' in next
? (next as React.ChangeEvent<HTMLInputElement>).target.value
: next,
),
onKeyDown,
};
let control: React.ReactNode;
if (editor === 'select' || editor === 'multi-select' || editor === 'tags') {
control = (
<Select
{...commonProps}
onChange={(next) => {
setDraft(next);
if (editor === 'select') void saveValue(next);
}}
mode={editor === 'multi-select' ? 'multiple' : editor === 'tags' ? 'tags' : undefined}
options={options}
open
popupMatchSelectWidth={false}
popupClassName="editable-cell-dropdown"
/>
);
} else if (editor === 'date') {
control = <DatePicker {...commonProps} format="YYYY-MM-DD" open />;
} else if (editor === 'date-range') {
const { placeholder: _placeholder, ...rangeProps } = commonProps;
control = <DatePicker.RangePicker {...rangeProps} format="YYYY-MM-DD" open />;
} else if (editor === 'number' || editor === 'money') {
control = (
<InputNumber {...commonProps} min={min} max={max} precision={editor === 'money' ? 2 : 0} />
);
} else if (editor === 'textarea') {
control = <Input.TextArea {...commonProps} autoSize={{ minRows: 1, maxRows: 4 }} />;
} else {
control = <Input {...commonProps} />;
}
return (
<div
ref={rootRef}
className={`editable-cell${enabled ? ' editable-cell--enabled' : ''}${editing ? ' editable-cell--editing' : ''}`}
onDoubleClick={() => void beginEdit()}
onPointerDown={onPointerDown}
onPointerUp={onPointerUp}
onPointerCancel={() => {
touchStartRef.current = null;
lastTouchTapRef.current = null;
}}
>
{editing ? (
<Spin spinning={saving}>{control}</Spin>
) : (
<Tooltip title={enabled ? '双击编辑,触屏双击编辑' : undefined}>{children}</Tooltip>
)}
</div>
);
};
export default EditableCell;

View File

@@ -0,0 +1,47 @@
.editable-cell {
min-height: 30px;
min-width: 0;
display: flex;
align-items: center;
}
.editable-cell--enabled {
cursor: cell;
touch-action: manipulation;
padding: 4px 6px;
margin: -4px -6px;
border: 1px solid transparent;
border-radius: 4px;
}
.editable-cell--enabled:not(.editable-cell--editing):hover {
border-color: #91caff;
background: #e6f4ff;
}
.editable-cell--editing {
cursor: text;
padding: 0;
margin: -4px -6px;
border-color: transparent;
background: transparent;
min-width: 88px;
position: relative;
z-index: 2;
}
.editable-cell--editing .ant-spin-nested-loading,
.editable-cell--editing .ant-spin-container,
.editable-cell--editing .ant-input-number,
.editable-cell--editing .ant-picker,
.editable-cell--editing .ant-select {
width: 100%;
}
.editable-cell-dropdown {
min-width: 140px !important;
}
.editable-cell-dropdown .ant-select-item-option-content {
white-space: nowrap;
}

View File

@@ -0,0 +1,779 @@
import React, { useEffect, useRef, useState } from 'react';
import { Button, Form, Input, Modal, Popconfirm, Select, Spin, Steps, Tag, Typography } from 'antd';
import {
CloudUploadOutlined,
DeleteOutlined,
EditOutlined,
LinkOutlined,
PlusOutlined,
SaveOutlined,
SearchOutlined,
} from '@ant-design/icons';
import api from '../api';
import { message } from '../ui/app-message';
import { usePermission } from '../hooks/usePermission';
import PermissionButton from './PermissionButton';
const { Text } = Typography;
// ── Types ──
interface JinshujuEntryRow {
serialNumber: number;
name: string;
phone: string | null;
suggestedStudent: {
id: number;
name: string;
phone: string | null;
studentNo: string | null;
} | null;
}
interface StudentOption {
id: number;
name: string;
phone: string | null;
studentNo: string | null;
}
interface PreviewResponse {
success: boolean;
entries: JinshujuEntryRow[];
students: StudentOption[];
}
interface MatchRule {
id: number;
name: string;
formToken: string;
mappings: Record<string, string>;
createdAt: string;
}
interface JinshujuFormField {
key: string;
label: string;
type: string;
}
type MatchDecision =
| { action: 'match'; matchStudentId: number }
| { action: 'create'; createName: string; createPhone: string }
| { action: 'skip' };
// ── Constants ──
const ROW_HEIGHT = 72;
const LEFT_WIDTH = 260;
const GAP = 80;
const STUDENT_FIELDS = [
{ key: 'name', label: '姓名' },
{ key: 'phone', label: '手机号' },
{ key: 'idNumber', label: '身份证号' },
{ key: 'gender', label: '性别' },
{ key: 'ethnicity', label: '民族' },
{ key: 'emergencyContact', label: '紧急联系人' },
{ key: 'emergencyPhone', label: '紧急联系电话' },
{ key: 'studentNo', label: '学号' },
];
// ── MatchSelector sub-component ──
interface MatchSelectorProps {
entry: JinshujuEntryRow;
decision: MatchDecision | undefined;
studentOptions: StudentOption[];
onChange: (d: MatchDecision) => void;
}
const MatchSelector: React.FC<MatchSelectorProps> = ({
entry,
decision,
studentOptions,
onChange,
}) => {
const action = decision?.action ?? 'skip';
if (action === 'match') {
const matchD = decision as { action: 'match'; matchStudentId: number };
const matchedStudent = studentOptions.find((s) => s.id === matchD.matchStudentId);
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
<Tag color="blue" icon={<LinkOutlined />}>
</Tag>
<Text style={{ flex: 1 }}>
{matchedStudent?.name ?? '未知'}
{matchedStudent?.studentNo && (
<Text type="secondary" style={{ fontSize: 12, marginLeft: 4 }}>
({matchedStudent.studentNo})
</Text>
)}
</Text>
<Button size="small" type="link" danger onClick={() => onChange({ action: 'skip' })}>
</Button>
</div>
);
}
if (action === 'create') {
const createD = decision as { action: 'create'; createName: string; createPhone: string };
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
<Tag color="green" icon={<PlusOutlined />}>
</Tag>
<Input
size="small"
value={createD.createName}
placeholder="姓名"
style={{ width: 100 }}
onChange={(e) =>
onChange({
action: 'create',
createName: e.target.value,
createPhone: createD.createPhone,
})
}
/>
<Input
size="small"
value={createD.createPhone}
placeholder="手机号"
style={{ width: 120 }}
onChange={(e) =>
onChange({
action: 'create',
createName: createD.createName,
createPhone: e.target.value,
})
}
/>
<Button size="small" type="link" danger onClick={() => onChange({ action: 'skip' })}>
</Button>
</div>
);
}
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
<Select
showSearch
size="small"
placeholder="搜索学生…"
style={{ flex: 1 }}
value={undefined}
filterOption={(input, option) =>
((option?.label as string) || '').toLowerCase().includes(input.toLowerCase())
}
options={studentOptions.map((s) => ({
value: s.id,
label: `${s.name}${s.phone ? ` (${s.phone})` : ''}${s.studentNo ? ` [${s.studentNo}]` : ''}`,
}))}
onChange={(studentId: number) => onChange({ action: 'match', matchStudentId: studentId })}
/>
<Button
size="small"
type="dashed"
icon={<PlusOutlined />}
onClick={() =>
onChange({
action: 'create',
createName: entry.name || '',
createPhone: entry.phone || '',
})
}
>
</Button>
<Button size="small" type="link" onClick={() => onChange({ action: 'skip' })}>
</Button>
</div>
);
};
// ── Rule Editor sub-component ──
interface RuleEditorProps {
rule: MatchRule | null;
formToken: string;
fields: JinshujuFormField[];
onSave: () => void;
onDelete: (id: number) => void;
onCancel: () => void;
}
const RuleEditor: React.FC<RuleEditorProps> = ({
rule,
formToken,
fields,
onSave,
onDelete,
onCancel,
}) => {
const [name, setName] = useState(rule?.name ?? '');
const [mappings, setMappings] = useState<Record<string, string>>(
rule?.mappings ?? { name: 'field_1', phone: 'field_2' },
);
const [saving, setSaving] = useState(false);
const handleSave = async () => {
if (!name.trim()) {
message.warning('请输入规则名称');
return;
}
setSaving(true);
try {
if (rule) {
await api.put(`/sync/jinshuju/rules/${rule.id}`, { name, mappings });
} else {
await api.post('/sync/jinshuju/rules', { name, formToken, mappings });
}
message.success('规则已保存');
onSave();
} catch (e: unknown) {
const err = e as { message?: string };
if (err?.message) message.error(err.message);
} finally {
setSaving(false);
}
};
return (
<div style={{ padding: '12px 0' }}>
<Input
placeholder="规则名称"
value={name}
onChange={(e) => setName(e.target.value)}
style={{ marginBottom: 12 }}
/>
<Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
</Text>
{STUDENT_FIELDS.map((sf) => (
<div
key={sf.key}
style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}
>
<Text style={{ width: 100, textAlign: 'right', fontSize: 13 }}>{sf.label}</Text>
<Text type="secondary" style={{ fontSize: 12 }}>
</Text>
<Select
allowClear
showSearch
optionFilterProp="label"
placeholder="选择金数据字段"
value={mappings[sf.key]}
style={{ flex: 1 }}
options={fields.map((field) => ({
value: field.key,
label: `${field.label}${field.key}`,
}))}
onChange={(value) =>
setMappings((prev) => {
const next = { ...prev };
if (value) next[sf.key] = value;
else delete next[sf.key];
return next;
})
}
/>
</div>
))}
<div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
<Button type="primary" icon={<SaveOutlined />} loading={saving} onClick={handleSave}>
</Button>
{rule && (
<Popconfirm title="确定删除此规则?" onConfirm={() => onDelete(rule.id)}>
<Button danger icon={<DeleteOutlined />}>
</Button>
</Popconfirm>
)}
<Button onClick={onCancel}></Button>
</div>
</div>
);
};
// ── Main MatchModal ──
interface MatchModalProps {
open: boolean;
onClose: () => void;
onApplied: () => void;
}
const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplied }) => {
const { hasPermission, hasAllPermissions, permissionsReady } = usePermission();
const canTriggerSync = hasPermission('sync:trigger');
const canEnterModal = permissionsReady && hasAllPermissions('sync:read', 'sync:trigger');
const [step, setStep] = useState<'connection' | 'rule' | 'match' | 'applying'>('connection');
const [loading, setLoading] = useState(false);
const [selectedRuleId, setSelectedRuleId] = useState<number | undefined>();
const [rules, setRules] = useState<MatchRule[]>([]);
const [editingRule, setEditingRule] = useState<MatchRule | null>(null);
const [showRuleEditor, setShowRuleEditor] = useState(false);
const [credForm] = Form.useForm();
const formToken = Form.useWatch('formToken', credForm) ?? '';
const [entries, setEntries] = useState<JinshujuEntryRow[]>([]);
const [studentOptions, setStudentOptions] = useState<StudentOption[]>([]);
const [decisions, setDecisions] = useState<Map<number, MatchDecision>>(new Map());
const leftRef = useRef<HTMLDivElement>(null);
const rightRef = useRef<HTMLDivElement>(null);
const [formFields, setFormFields] = useState<JinshujuFormField[]>([]);
const [formName, setFormName] = useState('');
const [scrollTop, setScrollTop] = useState(0);
// Load rules on open
useEffect(() => {
if (open && canEnterModal) loadRules();
}, [open, canEnterModal]);
// Close and reset when permission is lost
const enteredRef = useRef(false);
useEffect(() => {
if (canEnterModal) {
enteredRef.current = true;
return;
}
if (enteredRef.current) {
enteredRef.current = false;
reset();
onClose();
}
}, [canEnterModal, onClose]);
const loadRules = async () => {
try {
const res = await api.get<{ success: boolean; data: MatchRule[] }>('/sync/jinshuju/rules');
if (res.success) setRules(res.data);
} catch {
/* ignore */
}
};
const handleConnectionNext = async () => {
if (!canTriggerSync) return;
try {
const values = await credForm.validateFields();
setLoading(true);
const response = await api.post<{
success: boolean;
data: { name: string; fields: JinshujuFormField[] };
}>('/sync/jinshuju/fields', values);
setFormFields(response.data.fields);
setFormName(response.data.name);
setStep('rule');
} catch (error: unknown) {
const apiError = error as { message?: string; errorFields?: unknown[] };
if (!apiError.errorFields && apiError.message) message.error(apiError.message);
} finally {
setLoading(false);
}
};
const handlePreview = async () => {
if (!canTriggerSync) return;
try {
const values = await credForm.validateFields();
setLoading(true);
const body: Record<string, unknown> = { ...values };
if (selectedRuleId) body.ruleId = selectedRuleId;
const res = await api.post<PreviewResponse>('/sync/jinshuju/preview', body);
if (!res.success) throw new Error('预览失败');
setEntries(res.entries);
setStudentOptions(res.students);
const initial = new Map<number, MatchDecision>();
for (const entry of res.entries) {
if (entry.suggestedStudent) {
initial.set(entry.serialNumber, {
action: 'match',
matchStudentId: entry.suggestedStudent.id,
});
}
}
setDecisions(initial);
setStep('match');
} catch (e: unknown) {
const err = e as { message?: string };
if (err?.message) message.error(err.message);
} finally {
setLoading(false);
}
};
const handleApply = async () => {
if (!canTriggerSync) return;
setLoading(true);
setStep('applying');
try {
const decisionList = [...decisions.entries()].map(([serialNumber, d]) => ({
serialNumber,
...d,
}));
const body: Record<string, unknown> = {
...credForm.getFieldsValue(),
decisions: decisionList,
};
if (selectedRuleId) body.ruleId = selectedRuleId;
const res = await api.post<{
success: boolean;
log: { recordsCount: number; message?: string };
}>('/sync/jinshuju/apply', body);
if (res.success) {
message.success(res.log.message || `处理 ${res.log.recordsCount} 条记录`);
onApplied();
reset();
}
} catch (e: unknown) {
const err = e as { message?: string };
if (err?.message) message.error(err.message);
setStep('match');
} finally {
setLoading(false);
}
};
const reset = () => {
setStep('connection');
setEntries([]);
setStudentOptions([]);
setDecisions(new Map());
setSelectedRuleId(undefined);
setFormFields([]);
setFormName('');
setShowRuleEditor(false);
credForm.resetFields();
};
const handleClose = () => {
reset();
onClose();
};
const handleScroll = (source: 'left' | 'right') => {
const el = source === 'left' ? leftRef.current : rightRef.current;
if (el) setScrollTop(el.scrollTop);
};
useEffect(() => {
if (leftRef.current) leftRef.current.scrollTop = scrollTop;
if (rightRef.current) rightRef.current.scrollTop = scrollTop;
}, [scrollTop]);
const getDecision = (serial: number): MatchDecision | undefined => decisions.get(serial);
const setDecision = (serial: number, d: MatchDecision) =>
setDecisions((prev) => new Map(prev).set(serial, d));
const total = entries.length;
const matched = [...decisions.values()].filter((d) => d.action !== 'skip').length;
const visibleRules = rules.filter((rule) => rule.formToken === formToken);
const selectedRule = visibleRules.find((rule) => rule.id === selectedRuleId) ?? null;
// ── Render ──
const renderConnectionStep = () => (
<Form form={credForm} layout="vertical" style={{ marginTop: 24 }}>
<Form.Item
name="apiKey"
label="API Key"
extra="金数据个人中心 → API 中获取"
rules={[{ required: true, message: '请输入 API Key' }]}
>
<Input placeholder="请输入 API Key" autoComplete="username" />
</Form.Item>
<Form.Item
name="apiSecret"
label="API Secret"
rules={[{ required: true, message: '请输入 API Secret' }]}
>
<Input.Password placeholder="请输入 API Secret" autoComplete="current-password" />
</Form.Item>
<Form.Item
name="formToken"
label="表单 Token"
extra="例如表单地址 /f/AbC123 中的 AbC123"
rules={[{ required: true, message: '请输入表单 Token' }]}
>
<Input placeholder="请输入表单 Token" />
</Form.Item>
</Form>
);
const renderRuleStep = () => (
<div style={{ marginTop: 24 }}>
<div style={{ marginBottom: 12 }}>
<Text strong></Text>
<Text type="secondary" style={{ display: 'block', marginTop: 4 }}>
{formName} {formFields.length}
</Text>
</div>
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<Select
style={{ flex: 1 }}
placeholder="默认规则field_1 → 姓名field_2 → 手机号"
allowClear
value={selectedRuleId}
onChange={(value) => setSelectedRuleId(value)}
options={visibleRules.map((rule) => ({ value: rule.id, label: rule.name }))}
/>
{canTriggerSync && selectedRule ? (
<Button
icon={<EditOutlined />}
onClick={() => {
setEditingRule(selectedRule);
setShowRuleEditor(true);
}}
>
</Button>
) : null}
{canTriggerSync ? (
<Button
icon={<PlusOutlined />}
onClick={() => {
setEditingRule(null);
setShowRuleEditor(true);
}}
>
</Button>
) : null}
</div>
{visibleRules.length === 0 && !showRuleEditor ? (
<Text type="secondary" style={{ display: 'block', marginTop: 12 }}>
</Text>
) : null}
{canTriggerSync && showRuleEditor ? (
<RuleEditor
rule={editingRule}
formToken={formToken}
fields={formFields}
onSave={() => {
setShowRuleEditor(false);
loadRules();
}}
onDelete={async (id) => {
await api.delete(`/sync/jinshuju/rules/${id}`);
message.success('规则已删除');
if (selectedRuleId === id) setSelectedRuleId(undefined);
setShowRuleEditor(false);
loadRules();
}}
onCancel={() => setShowRuleEditor(false)}
/>
) : null}
</div>
);
const renderMatchStep = () => {
const svgHeight = entries.length * ROW_HEIGHT;
const lines: React.ReactNode[] = [];
entries.forEach((entry, i) => {
const y = i * ROW_HEIGHT + ROW_HEIGHT / 2;
const d = getDecision(entry.serialNumber);
const isMatched = d?.action === 'match';
const color = isMatched ? '#1677ff' : '#d9d9d9';
lines.push(
<line
key={entry.serialNumber}
x1={LEFT_WIDTH}
y1={y}
x2={LEFT_WIDTH + GAP}
y2={y}
stroke={color}
strokeWidth={isMatched ? 2 : 1}
strokeDasharray={isMatched ? undefined : '4 4'}
opacity={isMatched ? 0.7 : 0.3}
/>,
);
});
return (
<div style={{ position: 'relative' }}>
<div
style={{
marginBottom: 12,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<Text type="secondary">
{total} {matched}
</Text>
<Button size="small" onClick={() => setDecisions(new Map())}>
</Button>
</div>
<div style={{ display: 'flex', position: 'relative' }}>
<svg
style={{
position: 'absolute',
top: 0,
left: 0,
width: LEFT_WIDTH + GAP,
height: svgHeight,
pointerEvents: 'none',
zIndex: 1,
}}
>
{lines}
</svg>
<div
ref={leftRef}
onScroll={() => handleScroll('left')}
style={{ width: LEFT_WIDTH, maxHeight: 480, overflowY: 'auto', flexShrink: 0 }}
>
{entries.map((entry, i) => {
const d = getDecision(entry.serialNumber);
const isMatched = d?.action === 'match';
return (
<div
key={entry.serialNumber}
style={{
height: ROW_HEIGHT,
padding: '8px 12px',
borderBottom: '1px solid #f0f0f0',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
background: isMatched ? '#f6ffed' : i % 2 === 0 ? '#fafafa' : '#fff',
borderLeft: isMatched ? '3px solid #1677ff' : '3px solid transparent',
}}
>
<Text strong style={{ fontSize: 13 }}>
{entry.name || <Text type="secondary"></Text>}
</Text>
{entry.phone && (
<Text type="secondary" style={{ fontSize: 12 }}>
{entry.phone}
</Text>
)}
<Text type="secondary" style={{ fontSize: 11 }}>
#{entry.serialNumber}
</Text>
</div>
);
})}
</div>
<div style={{ width: GAP, flexShrink: 0 }} />
<div
ref={rightRef}
onScroll={() => handleScroll('right')}
style={{ flex: 1, maxHeight: 480, overflowY: 'auto' }}
>
{entries.map((entry) => (
<div
key={entry.serialNumber}
style={{
height: ROW_HEIGHT,
padding: '8px 12px',
borderBottom: '1px solid #f0f0f0',
display: 'flex',
alignItems: 'center',
gap: 8,
}}
>
<MatchSelector
entry={entry}
decision={getDecision(entry.serialNumber)}
studentOptions={studentOptions}
onChange={(newD) => setDecision(entry.serialNumber, newD)}
/>
</div>
))}
</div>
</div>
</div>
);
};
const currentStep = step === 'connection' ? 0 : step === 'rule' ? 1 : 2;
return (
<Modal
title="同步金数据"
open={open && canEnterModal}
onCancel={handleClose}
width={step === 'match' || step === 'applying' ? 900 : 640}
maskClosable={false}
footer={
step === 'connection'
? [
<Button key="cancel" onClick={handleClose}>
</Button>,
<Button key="next" type="primary" onClick={handleConnectionNext}>
</Button>,
]
: step === 'rule'
? [
<Button key="back" onClick={() => setStep('connection')}>
</Button>,
<Button key="cancel" onClick={handleClose}>
</Button>,
<Button
key="next"
type="primary"
icon={<SearchOutlined />}
loading={loading}
onClick={handlePreview}
>
</Button>,
]
: step === 'match'
? [
<Button key="back" onClick={() => setStep('rule')}>
</Button>,
<Button key="cancel" onClick={handleClose}>
</Button>,
canTriggerSync ? (
<PermissionButton
key="apply"
permission="sync:trigger"
type="primary"
icon={<CloudUploadOutlined />}
loading={loading}
onClick={handleApply}
>
</PermissionButton>
) : null,
]
: null
}
>
<Steps
current={currentStep}
items={[{ title: '连接表单' }, { title: '匹配规则' }, { title: '确认匹配' }]}
/>
{step === 'connection' ? renderConnectionStep() : null}
{step === 'rule' ? renderRuleStep() : null}
{step === 'match' ? renderMatchStep() : null}
{step === 'applying' ? (
<Spin tip="正在同步..." style={{ display: 'block', margin: '48px auto' }} />
) : null}
</Modal>
);
};
export default JinshujuMatchModal;

View File

@@ -3,6 +3,7 @@ import { Badge, Popover, Button, List, Typography, Empty } from 'antd';
import { BellOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import api from '../api';
import { formatNotificationText, notificationTypeLabels } from '../utils/notification-display';
interface NotificationItem {
id: number;
@@ -14,18 +15,6 @@ interface NotificationItem {
createdAt: string;
}
const typeLabels: Record<string, string> = {
bill_generated: '账单',
bill_paid: '账单',
check_in: '入住',
check_out: '退宿',
deposit_due: '押金',
deposit_refunded: '押金',
class_change: '班级',
schedule_conflict: '排课',
announcement: '公告',
};
function timeAgo(dateStr: string): string {
const diff = Date.now() - new Date(dateStr).getTime();
const mins = Math.floor(diff / 60000);
@@ -45,16 +34,20 @@ const NotificationBell: React.FC = () => {
const fetchNotifications = async () => {
try {
const data = await api.get('/notifications?limit=20') as unknown as NotificationItem[];
const data = (await api.get('/notifications?limit=20')) as unknown as NotificationItem[];
setNotifications(data);
} catch { /* ignore */ }
} catch {
/* ignore */
}
};
const fetchUnread = async () => {
try {
const data = await api.get('/notifications/unread-count') as unknown as { count: number };
const data = (await api.get('/notifications/unread-count')) as unknown as { count: number };
setUnreadCount(data.count);
} catch { /* ignore */ }
} catch {
/* ignore */
}
};
const openRef = useRef(open);
openRef.current = open;
@@ -71,7 +64,9 @@ const NotificationBell: React.FC = () => {
JSON.parse(event.data);
setUnreadCount((c) => c + 1);
if (openRef.current) fetchNotifications();
} catch { /* ignore */ }
} catch {
/* ignore */
}
};
es.onerror = () => {
es.close();
@@ -95,7 +90,9 @@ const NotificationBell: React.FC = () => {
try {
await api.put(`/notifications/${item.id}/read`);
setUnreadCount((c) => Math.max(0, c - 1));
} catch { /* ignore */ }
} catch {
/* ignore */
}
}
setOpen(false);
if (item.link) navigate(item.link);
@@ -105,10 +102,10 @@ const NotificationBell: React.FC = () => {
try {
await api.put('/notifications/read-all');
setUnreadCount(0);
setNotifications((prev) =>
prev.map((n) => ({ ...n, isRead: true })),
);
} catch { /* ignore */ }
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
} catch {
/* ignore */
}
};
const content = (
@@ -159,18 +156,13 @@ const NotificationBell: React.FC = () => {
)
}
title={
<Typography.Text
strong={!item.isRead}
style={{ fontSize: 14 }}
>
[{typeLabels[item.type] || item.type}] {item.title}
<Typography.Text strong={!item.isRead} style={{ fontSize: 14 }}>
[{notificationTypeLabels[item.type] || item.type}]{' '}
{formatNotificationText(item.title)}
</Typography.Text>
}
description={
<Typography.Text
type="secondary"
style={{ fontSize: 12 }}
>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
{timeAgo(item.createdAt)}
</Typography.Text>
}

View File

@@ -1,5 +1,5 @@
import React from 'react';
import { Result, Button } from 'antd';
import { Result, Button, Spin } from 'antd';
import { useNavigate } from 'react-router-dom';
import { findRoleAwareLandingPath } from '../auth/menu-policy';
import { usePermission } from '../hooks/usePermission';
@@ -10,8 +10,11 @@ interface PermissionRouteProps {
}
const PermissionRoute: React.FC<PermissionRouteProps> = ({ permission, children }) => {
const { permissions, hasPermission } = usePermission();
const { permissions, permissionsReady, hasPermission } = usePermission();
const navigate = useNavigate();
if (!permissionsReady) {
return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;
}
if (!hasPermission(permission)) {
let roles: string[] = [];
try {
@@ -25,7 +28,13 @@ const PermissionRoute: React.FC<PermissionRouteProps> = ({ permission, children
status="403"
title="无权访问"
subTitle="您没有访问此页面的权限"
extra={firstPath ? <Button type="primary" onClick={() => navigate(firstPath, { replace: true })}>访</Button> : undefined}
extra={
firstPath ? (
<Button type="primary" onClick={() => navigate(firstPath, { replace: true })}>
访
</Button>
) : undefined
}
/>
);
}

View File

@@ -0,0 +1,196 @@
import React, { useEffect, useMemo, useState } from 'react';
import type { DragEndEvent } from '@dnd-kit/core';
import { closestCenter, DndContext, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import {
arrayMove,
horizontalListSortingStrategy,
SortableContext,
useSortable,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Tabs } from 'antd';
import type { TabsProps } from 'antd';
import type { Location } from 'react-router-dom';
import type { AppMenuItem } from '../../auth/menu-policy';
const STORAGE_KEY = 'gongxue-route-dock';
interface DockTab {
key: string;
label: string;
}
interface RouteDockProps {
location: Location;
menuItems: readonly AppMenuItem[];
onNavigate: (path: string) => void;
draggable: boolean;
}
interface DraggableTabNodeProps extends React.HTMLAttributes<HTMLDivElement> {
'data-node-key': string;
}
function findMenuLabel(items: readonly AppMenuItem[], pathname: string): string | undefined {
for (const item of items) {
if (item.key === pathname) return item.label;
if (item.children) {
const label = findMenuLabel(item.children, pathname);
if (label) return label;
}
}
return undefined;
}
function getRouteLabel(items: readonly AppMenuItem[], pathname: string): string {
const menuLabel = findMenuLabel(items, pathname);
if (menuLabel) return menuLabel;
if (/^\/students\/\d+\/profile$/.test(pathname)) return '学生档案';
if (/^\/classes\/\d+$/.test(pathname)) return '班级详情';
return pathname === '/' ? '首页' : '页面';
}
function readStoredTabs(): DockTab[] {
try {
const parsed = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
if (!Array.isArray(parsed)) return [];
return parsed.filter(
(tab): tab is DockTab =>
typeof tab?.key === 'string' && tab.key.startsWith('/') && typeof tab?.label === 'string',
);
} catch {
return [];
}
}
const DraggableTabNode: React.FC<Readonly<DraggableTabNodeProps>> = ({ ...props }) => {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: props['data-node-key'],
});
const child = props.children as React.ReactElement<{ style?: React.CSSProperties }>;
return React.cloneElement(child, {
ref: setNodeRef,
style: {
...child.props.style,
transform: CSS.Translate.toString(transform),
transition,
cursor: isDragging ? 'grabbing' : 'grab',
zIndex: isDragging ? 1 : undefined,
opacity: isDragging ? 0.92 : undefined,
boxShadow: isDragging ? '0 8px 20px rgba(29, 29, 31, 0.14)' : undefined,
},
...attributes,
...listeners,
} as React.HTMLAttributes<HTMLElement>);
};
const RouteDock: React.FC<RouteDockProps> = ({ location, menuItems, onNavigate, draggable }) => {
const activeKey = `${location.pathname}${location.search}`;
const [tabs, setTabs] = useState<DockTab[]>(() => {
const storedTabs = readStoredTabs();
if (location.pathname === '/') return storedTabs;
if (storedTabs.some((tab) => tab.key === activeKey)) return storedTabs;
return [...storedTabs, { key: activeKey, label: getRouteLabel(menuItems, location.pathname) }];
});
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }));
useEffect(() => {
if (location.pathname === '/') return;
setTabs((currentTabs) => {
const label = getRouteLabel(menuItems, location.pathname);
const existing = currentTabs.find((tab) => tab.key === activeKey);
if (!existing) return [...currentTabs, { key: activeKey, label }];
if (existing.label === label) return currentTabs;
return currentTabs.map((tab) => (tab.key === activeKey ? { ...tab, label } : tab));
});
}, [activeKey, location.pathname, menuItems]);
useEffect(() => {
localStorage.setItem(STORAGE_KEY, JSON.stringify(tabs));
}, [tabs]);
const tabItems = useMemo<NonNullable<TabsProps['items']>>(
() =>
tabs.map((tab) => ({
key: tab.key,
label: tab.label,
closable: tabs.length > 1,
})),
[tabs],
);
const closeTab = (targetKey: string) => {
const targetIndex = tabs.findIndex((tab) => tab.key === targetKey);
if (targetIndex < 0 || tabs.length === 1) return;
const nextTabs = tabs.filter((tab) => tab.key !== targetKey);
setTabs(nextTabs);
if (targetKey === activeKey) {
const nextActiveTab = nextTabs[Math.min(targetIndex, nextTabs.length - 1)];
if (nextActiveTab) onNavigate(nextActiveTab.key);
}
};
const handleDragEnd = ({ active, over }: DragEndEvent) => {
if (!over || active.id === over.id) return;
setTabs((currentTabs) => {
const activeIndex = currentTabs.findIndex((tab) => tab.key === active.id);
const overIndex = currentTabs.findIndex((tab) => tab.key === over.id);
return activeIndex < 0 || overIndex < 0
? currentTabs
: arrayMove(currentTabs, activeIndex, overIndex);
});
};
const renderTabBar: TabsProps['renderTabBar'] = (tabBarProps, DefaultTabBar) => {
const tabBar = (
<DefaultTabBar {...tabBarProps}>
{(node) => {
if (!draggable) return node;
return (
<DraggableTabNode
{...(node as React.ReactElement<DraggableTabNodeProps>).props}
key={node.key}
>
{node}
</DraggableTabNode>
);
}}
</DefaultTabBar>
);
if (!draggable) return tabBar;
return (
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext
items={tabs.map((tab) => tab.key)}
strategy={horizontalListSortingStrategy}
>
{tabBar}
</SortableContext>
</DndContext>
);
};
if (location.pathname === '/' || tabs.length === 0) return null;
return (
<nav className="route-dock" aria-label="已打开页面">
<Tabs
type="editable-card"
size="small"
hideAdd
activeKey={activeKey}
items={tabItems}
animated={false}
onChange={onNavigate}
onEdit={(targetKey, action) => {
if (action === 'remove') closeTab(String(targetKey));
}}
renderTabBar={renderTabBar}
/>
</nav>
);
};
export default RouteDock;

File diff suppressed because it is too large Load Diff

View File

@@ -1,31 +1,40 @@
import { useCallback, useEffect, useState } from 'react';
import { PERMISSIONS_UPDATED_EVENT, readPermissions } from '../auth/permission-store';
import { PERMISSIONS_UPDATED_EVENT, readPermissionState } from '../auth/permission-store';
export function usePermission() {
const [permissions, setPermissions] = useState<string[]>(readPermissions);
const [state, setState] = useState(readPermissionState);
useEffect(() => {
const refresh = () => setPermissions(readPermissions());
const refresh = () => setState(readPermissionState());
window.addEventListener(PERMISSIONS_UPDATED_EVENT, refresh);
window.addEventListener('storage', refresh);
return () => {
window.removeEventListener(PERMISSIONS_UPDATED_EVENT, refresh);
window.removeEventListener('storage', refresh);
};
}, []);
const permissions = state.permissions;
const permissionsReady = state.status === 'ready';
const hasPermission = useCallback(
(code: string): boolean => permissions.includes(code),
[permissions],
(code: string): boolean => permissionsReady && permissions.includes(code),
[permissions, permissionsReady],
);
const hasAnyPermission = useCallback(
(...codes: string[]): boolean => codes.some((code) => permissions.includes(code)),
[permissions],
(...codes: string[]): boolean =>
permissionsReady && codes.some((code) => permissions.includes(code)),
[permissions, permissionsReady],
);
const hasAllPermissions = useCallback(
(...codes: string[]): boolean => codes.every((code) => permissions.includes(code)),
[permissions],
(...codes: string[]): boolean =>
permissionsReady && codes.every((code) => permissions.includes(code)),
[permissions, permissionsReady],
);
return { permissions, hasPermission, hasAnyPermission, hasAllPermissions };
return {
permissions,
permissionStatus: state.status,
permissionsReady,
hasPermission,
hasAnyPermission,
hasAllPermissions,
};
}

View File

@@ -1,4 +1,4 @@
import { useCallback } from 'react';
import { useCallback, useEffect, useRef } from 'react';
import { Modal } from 'antd';
import api from '../api';
import { message } from '../ui/app-message';
@@ -9,16 +9,35 @@ import { message } from '../ui/app-message';
*
* @param studentId - The student whose data is being viewed
* @param module - Audit module label (e.g. '学生管理', '学生档案')
* @param canLog - Whether the current user has log:create; when false any
* already-open confirm modal is destroyed.
*/
export function useViewSensitive(studentId: number, module: string) {
export function useViewSensitive(studentId: number, module: string, canLog: boolean) {
const canLogRef = useRef(canLog);
const modalRef = useRef<ReturnType<typeof Modal.confirm> | null>(null);
canLogRef.current = canLog;
useEffect(() => {
if (!canLogRef.current && modalRef.current) {
modalRef.current.destroy();
modalRef.current = null;
}
return () => {
modalRef.current?.destroy();
modalRef.current = null;
};
}, []);
return useCallback(
(field: string, value: string) => {
Modal.confirm({
if (!canLogRef.current) return;
modalRef.current = Modal.confirm({
title: '查看敏感信息',
content: `您即将查看 "${field}" 的完整信息。此操作将被记录。`,
okText: '确认查看',
cancelText: '取消',
onOk: async () => {
if (!canLogRef.current) return;
try {
await api.post('/operation-logs/audit', {
module,
@@ -37,6 +56,9 @@ export function useViewSensitive(studentId: number, module: string) {
okText: '关闭',
});
},
afterClose: () => {
modalRef.current = null;
},
});
},
[studentId, module],

View File

@@ -4,7 +4,15 @@
box-sizing: border-box;
}
html {
min-width: 320px;
background: #f5f5f7;
}
body {
min-width: 320px;
overflow-x: hidden;
background: #f5f5f7;
font-family:
-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
-webkit-font-smoothing: antialiased;
@@ -15,10 +23,203 @@ body {
min-height: 100vh;
}
/* === 通用:表格容器横向滚动(防双重滚动条) === */
img,
svg,
canvas {
max-width: 100%;
}
.app-shell,
.app-main,
.app-content {
min-width: 0;
}
.app-sidebar {
flex: 0 0 auto;
}
.app-content > * {
min-width: 0;
max-width: 100%;
}
.ant-card,
.ant-card-body,
.ant-tabs,
.ant-tabs-content-holder,
.ant-tabs-content,
.ant-tabs-tabpane {
min-width: 0;
}
.app-header {
position: sticky;
top: 0;
z-index: 100;
}
.route-dock {
position: sticky;
top: 64px;
z-index: 90;
min-width: 0;
height: 44px;
padding: 6px 12px;
overflow: hidden;
background: #f5f5f7;
border-bottom: 1px solid #e5e5e7;
}
.route-dock .ant-tabs {
height: 32px;
}
.route-dock .ant-tabs-nav {
height: 32px;
margin: 0;
}
.route-dock .ant-tabs-nav::before {
border-bottom: 0;
}
.route-dock .ant-tabs-tab {
min-width: 112px;
max-width: 220px;
height: 32px;
margin: 0 6px 0 0 !important;
padding: 0 10px 0 12px !important;
overflow: hidden;
background: rgba(255, 255, 255, 0.58) !important;
border: 1px solid transparent !important;
border-radius: 7px !important;
transition:
background-color 160ms ease,
border-color 160ms ease,
box-shadow 160ms ease !important;
}
.route-dock .ant-tabs-tab:hover {
background: rgba(255, 255, 255, 0.9) !important;
border-color: #dedee2 !important;
}
.route-dock .ant-tabs-tab-active {
background: #fff !important;
border-color: #d8d8dc !important;
box-shadow:
inset 0 2px 0 #1677ff,
0 2px 7px rgba(29, 29, 31, 0.08);
}
.route-dock .ant-tabs-tab-btn {
min-width: 0;
overflow: hidden;
color: #4d4d4d;
text-overflow: ellipsis;
white-space: nowrap;
}
.route-dock .ant-tabs-tab-remove {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 20px;
height: 20px;
margin-left: 8px;
border-radius: 50%;
transition: background-color 140ms ease;
}
.route-dock .ant-tabs-tab-remove:hover {
background: #ededf0;
}
.route-dock .ant-tabs-content-holder {
display: none;
}
/* Shared responsive toolbar: add these classes to page filter/action rows. */
.responsive-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 16px;
}
.responsive-toolbar__group {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.student-form-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
column-gap: 20px;
}
.student-form-grid .ant-form-item {
min-width: 0;
}
@media (max-width: 575px) {
.student-form-grid {
grid-template-columns: 1fr;
}
}
.ant-drawer-content-wrapper {
max-width: 100vw !important;
}
.ant-pagination {
row-gap: 8px;
}
/* Data tables own their horizontal scroll instead of widening the page. */
.ant-table-wrapper {
overflow-x: auto;
overflow-y: hidden;
width: 100%;
min-width: 0;
max-width: 100%;
}
.ant-table-wrapper .ant-table-content {
overscroll-behavior-inline: contain;
-webkit-overflow-scrolling: touch;
}
/* Keep wide tables scrollable without showing a heavy bar on every table. */
.ant-table-wrapper .ant-table-content {
scrollbar-color: transparent transparent;
scrollbar-width: thin;
}
.ant-table-wrapper .ant-table-content::-webkit-scrollbar {
height: 6px;
}
.ant-table-wrapper .ant-table-content::-webkit-scrollbar-track {
background: transparent;
}
.ant-table-wrapper .ant-table-content::-webkit-scrollbar-thumb {
background: transparent;
border-radius: 999px;
}
.ant-table-wrapper:hover .ant-table-content,
.ant-table-wrapper:focus-within .ant-table-content {
scrollbar-color: #c8c8cc transparent;
}
.ant-table-wrapper:hover .ant-table-content::-webkit-scrollbar-thumb,
.ant-table-wrapper:focus-within .ant-table-content::-webkit-scrollbar-thumb {
background: #c8c8cc;
}
/* ── 表格单元格省略号截断(按需启用) ──
@@ -54,6 +255,75 @@ body {
/* === 手机 (< 576px) === */
@media (max-width: 575px) {
.app-header {
height: 56px;
padding-inline: 8px !important;
line-height: 56px;
}
.route-dock {
top: 56px;
height: 42px;
padding: 5px 8px;
}
.route-dock .ant-tabs-tab {
min-width: 104px;
}
.app-header .ant-btn {
width: 40px;
min-height: 40px;
padding-inline: 0;
}
.app-content {
min-height: calc(100dvh - 72px);
margin: 8px !important;
padding: 12px !important;
border-radius: 10px !important;
}
.app-navigation-drawer .ant-drawer-header {
padding-inline: 16px;
}
.responsive-toolbar {
align-items: stretch;
flex-direction: column;
margin-bottom: 12px;
}
.responsive-toolbar__group,
.responsive-toolbar > .ant-space {
width: 100%;
}
.responsive-toolbar__group > .ant-space-item,
.responsive-toolbar > .ant-space > .ant-space-item {
flex: 1 1 140px;
max-width: 100%;
}
.responsive-toolbar .ant-input,
.responsive-toolbar .ant-input-affix-wrapper,
.responsive-toolbar .ant-input-search,
.responsive-toolbar .ant-picker,
.responsive-toolbar .ant-select,
.responsive-toolbar .ant-upload,
.responsive-toolbar .ant-upload-wrapper,
.responsive-toolbar .ant-btn {
width: 100% !important;
}
.ant-btn:not(.ant-btn-sm),
.ant-input-affix-wrapper,
.ant-input-search-button,
.ant-picker,
.ant-select-single .ant-select-selector {
min-height: 40px;
}
.ant-table {
font-size: 13px;
}
@@ -65,12 +335,48 @@ body {
font-size: 13px;
}
.ant-modal {
max-width: calc(100vw - 24px) !important;
margin: 12px auto !important;
top: 12px;
max-width: calc(100vw - 16px) !important;
margin: 0 auto !important;
padding-bottom: 12px;
}
.ant-modal .ant-modal-content {
padding: 16px;
}
.ant-modal .ant-modal-body {
max-height: 60vh;
max-height: calc(100dvh - 180px);
overflow-y: auto;
overscroll-behavior: contain;
}
.ant-modal .ant-modal-footer {
display: flex;
}
.ant-modal .ant-modal-footer .ant-btn {
flex: 1;
min-height: 40px;
}
.ant-drawer .ant-drawer-header {
padding: 14px 16px;
}
.ant-drawer .ant-drawer-body {
padding: 16px;
overscroll-behavior: contain;
}
.ant-popover,
.ant-picker-dropdown {
max-width: calc(100vw - 16px);
}
.ant-pagination {
justify-content: center;
}
.ant-pagination .ant-pagination-options {
margin-inline-start: 0;
}
.ant-alert {
padding: 10px 12px;
}
h1 {
font-size: 22px !important;
}
h2 {
font-size: 18px !important;
@@ -78,9 +384,48 @@ body {
.ant-card {
margin-bottom: 8px;
}
.ant-space-item .ant-btn {
padding: 2px 6px;
font-size: 12px;
.ant-card .ant-card-body {
padding: 14px;
}
}
@media (max-width: 575px) {
.ant-card-head {
align-items: flex-start;
flex-direction: column;
gap: 8px;
padding-block: 12px;
}
.ant-card-head-wrapper {
width: 100%;
min-width: 0;
}
.ant-card-extra {
max-width: 100%;
margin-inline-start: 0;
}
.ant-card-extra > .ant-space {
flex-wrap: wrap;
}
.ant-form-item-control,
.ant-form-item-control-input,
.ant-form-item-control-input-content,
.ant-picker-range {
min-width: 0;
max-width: 100%;
}
.ant-statistic-content {
overflow-wrap: anywhere;
}
}
@media (max-width: 991px) {
.app-content {
overflow: hidden;
}
}
@@ -90,3 +435,82 @@ body {
max-width: calc(100vw - 48px) !important;
}
}
.notifications-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 16px;
}
.notifications-filter {
width: 100%;
margin-bottom: 12px;
}
@media (max-width: 575px) {
.notifications-layout,
.notifications-content {
min-width: 0;
}
.notifications-header {
margin-bottom: 12px;
}
.notifications-content .ant-list-item {
align-items: flex-start;
padding: 14px 6px !important;
}
.notifications-content .ant-list-item-meta-avatar {
margin-inline-end: 10px;
}
.notifications-content .ant-list-item-meta-title {
margin-bottom: 4px;
}
}
@media (max-width: 575px) {
.ant-table-wrapper::before {
content: '表格可左右滑动查看';
display: block;
margin-bottom: 6px;
color: #8c8c8c;
font-size: 11px;
text-align: right;
}
.ant-table-wrapper .ant-table-content {
scrollbar-width: thin;
}
.ant-table-wrapper .ant-table-cell-fix-left,
.ant-table-wrapper .ant-table-cell-fix-right {
box-shadow: 2px 0 5px rgb(0 0 0 / 5%);
}
}
.responsive-toolbar--single {
justify-content: flex-start;
}
@media (max-width: 575px) {
/* Input.Search is an internal compact group. Keep the text field flexible and
the search icon button fixed instead of applying toolbar full-width rules
to both children. */
.responsive-toolbar .ant-input-search > .ant-input-affix-wrapper {
flex: 1 1 auto;
width: auto !important;
min-width: 0;
}
.responsive-toolbar .ant-input-search > .ant-input-search-btn {
flex: 0 0 40px;
width: 40px !important;
min-width: 40px;
padding-inline: 0;
}
}

View File

@@ -1,6 +1,6 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { Layout, Menu, Button, Avatar, Dropdown, Drawer, Grid } from 'antd';
import { Layout, Menu, Button, Avatar, Dropdown, Drawer, Grid, Tooltip } from 'antd';
import {
DashboardOutlined,
TeamOutlined,
@@ -25,15 +25,23 @@ import {
CheckCircleOutlined,
LaptopOutlined,
BellOutlined,
TrophyOutlined,
ApiOutlined,
RobotOutlined,
} from '@ant-design/icons';
import { usePermission } from '../hooks/usePermission';
import api from '../api';
import { writePermissions } from '../auth/permission-store';
import {
beginPermissionVerification,
clearPermissions,
writePermissions,
} from '../auth/permission-store';
import NotificationBell from '../components/NotificationBell';
import RouteDock from '../components/RouteDock';
import { buildMenu, type AppMenuItem } from '../auth/menu-policy';
const AiChatDrawer = React.lazy(() => import('../components/AiChat/AiChatDrawer'));
const { Header, Sider, Content } = Layout;
const iconMap: Record<string, React.ReactNode> = {
@@ -45,12 +53,14 @@ const iconMap: Record<string, React.ReactNode> = {
students: <TeamOutlined />,
classes: <TeamOutlined />,
teachers: <UserOutlined />,
exam: <TrophyOutlined />,
home: <HomeOutlined />,
overview: <AppstoreOutlined />,
occupancy: <SwapOutlined />,
expense: <DollarOutlined />,
bill: <FileTextOutlined />,
deposit: <WalletOutlined />,
wallet: <WalletOutlined />,
classroom: <ReadOutlined />,
rental: <FileProtectOutlined />,
organization: <TagsOutlined />,
@@ -67,6 +77,7 @@ const iconMap: Record<string, React.ReactNode> = {
const MainLayout: React.FC = () => {
const [collapsed, setCollapsed] = useState(false);
const [drawerOpen, setDrawerOpen] = useState(false);
const [aiChatOpen, setAiChatOpen] = useState(false);
const [openKeys, setOpenKeys] = useState<string[]>([]);
const prevPathname = useRef('');
const navigate = useNavigate();
@@ -78,25 +89,65 @@ const MainLayout: React.FC = () => {
useEffect(() => {
let cancelled = false;
api.get<{ id: number; username: string; permissions: string[]; roles?: string[] }>('/auth/profile')
.then((profile) => {
if (cancelled) return;
writePermissions(profile.permissions || []);
const cachedUser = JSON.parse(localStorage.getItem('user') || '{}');
const nextUser = { ...cachedUser, ...profile };
localStorage.setItem('user', JSON.stringify(nextUser));
setUser(nextUser);
})
.catch(() => {
// The API interceptor handles expired/invalid sessions.
});
return () => { cancelled = true; };
let retryTimer: number | undefined;
let verificationInFlight = false;
const verifyPermissions = () => {
if (cancelled || verificationInFlight || !localStorage.getItem('token')) return;
if (retryTimer !== undefined) {
window.clearTimeout(retryTimer);
retryTimer = undefined;
}
verificationInFlight = true;
beginPermissionVerification();
api
.get<{ id: number; username: string; permissions: string[]; roles?: string[] }>(
'/auth/profile',
)
.then((profile) => {
if (cancelled) return;
verificationInFlight = false;
writePermissions(profile.permissions || []);
const cachedUser = JSON.parse(localStorage.getItem('user') || '{}');
const nextUser = { ...cachedUser, ...profile };
localStorage.setItem('user', JSON.stringify(nextUser));
setUser(nextUser);
})
.catch(() => {
verificationInFlight = false;
if (cancelled || !localStorage.getItem('token')) return;
retryTimer = window.setTimeout(verifyPermissions, 5_000);
});
};
const handleStorage = (event: StorageEvent) => {
if (event.key !== 'token' && event.key !== 'permissions') return;
beginPermissionVerification();
window.location.reload();
};
const handleOnline = () => verifyPermissions();
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible') verifyPermissions();
};
verifyPermissions();
window.addEventListener('storage', handleStorage);
window.addEventListener('online', handleOnline);
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
cancelled = true;
if (retryTimer !== undefined) window.clearTimeout(retryTimer);
window.removeEventListener('storage', handleStorage);
window.removeEventListener('online', handleOnline);
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, []);
const screens = Grid.useBreakpoint();
const isMobile = !screens.sm; // < 576px (仅 xs)
const isMobile = !screens.sm; // < 576px (仅 xs)
const isTablet = (screens.sm || screens.md) && !screens.lg; // 576-991px
const isDesktop = !!screens.lg; // >= 992px
const isDesktop = !!screens.lg; // >= 992px
const usesDrawer = !isDesktop;
const menuItems = useMemo(
() => buildMenu(user.roles ?? [], permissions),
@@ -106,14 +157,17 @@ const MainLayout: React.FC = () => {
const handleLogout = useCallback(() => {
localStorage.removeItem('token');
localStorage.removeItem('user');
localStorage.removeItem('permissions');
clearPermissions();
navigate('/login');
}, [navigate]);
const handleMenuClick = useCallback((key: string) => {
navigate(key);
if (isMobile) setDrawerOpen(false);
}, [navigate, isMobile]);
const handleMenuClick = useCallback(
(key: string) => {
navigate(key);
if (usesDrawer) setDrawerOpen(false);
},
[navigate, usesDrawer],
);
const findSelectedKeys = (items: AppMenuItem[], pathname: string): string[] => {
for (const item of items) {
@@ -129,7 +183,12 @@ const MainLayout: React.FC = () => {
const findOpenKeys = (items: AppMenuItem[], pathname: string): string[] => {
for (const item of items) {
if (item.children) {
if (item.children.some((c) => c.key === pathname || (c.children && c.children.some((gc) => gc.key === pathname)))) {
if (
item.children.some(
(c) =>
c.key === pathname || (c.children && c.children.some((gc) => gc.key === pathname)),
)
) {
return [item.key];
}
}
@@ -137,23 +196,23 @@ const MainLayout: React.FC = () => {
return [];
};
const selectedKeys = useMemo(() => findSelectedKeys(menuItems, location.pathname), [menuItems, location.pathname]);
const selectedKeys = useMemo(
() => findSelectedKeys(menuItems, location.pathname),
[menuItems, location.pathname],
);
// 路径变化时同步展开的菜单(不干扰用户手动展开/收起)
useEffect(() => {
if (location.pathname !== prevPathname.current) {
prevPathname.current = location.pathname;
setOpenKeys(findOpenKeys(menuItems, location.pathname));
const routeOpenKeys = findOpenKeys(menuItems, location.pathname);
setOpenKeys((currentKeys) => [...new Set([...currentKeys, ...routeOpenKeys])]);
}
}, [location.pathname, menuItems]);
const handleOpenChange = useCallback((keys: string[]) => {
// 只保留最新打开的一个子菜单
const latestKey = keys[keys.length - 1];
setOpenKeys(latestKey ? [latestKey] : []);
setOpenKeys(keys);
}, []);
const transformToMenuItems = (items: AppMenuItem[]): any[] => {
return items.map((item) => ({
key: item.key,
@@ -162,27 +221,31 @@ const MainLayout: React.FC = () => {
children: item.children ? transformToMenuItems(item.children) : undefined,
}));
};
const menuContent = useMemo(() => (
<Menu
theme="light"
mode="inline"
selectedKeys={selectedKeys}
openKeys={openKeys}
onOpenChange={handleOpenChange}
items={transformToMenuItems(menuItems)}
onClick={({ key }) => handleMenuClick(key)}
style={{ border: 'none' }}
/>
), [selectedKeys, openKeys, menuItems, handleMenuClick]);
const menuContent = useMemo(
() => (
<Menu
theme="light"
mode="inline"
selectedKeys={selectedKeys}
openKeys={openKeys}
onOpenChange={handleOpenChange}
items={transformToMenuItems(menuItems)}
onClick={({ key }) => handleMenuClick(key)}
style={{ border: 'none' }}
/>
),
[selectedKeys, openKeys, menuItems, handleMenuClick],
);
return (
<Layout style={{ minHeight: '100vh' }}>
{!isMobile && (
<Layout className="app-shell" style={{ minHeight: '100vh' }}>
{isDesktop && (
<Sider
trigger={null}
collapsible
collapsed={isTablet ? true : collapsed}
collapsed={collapsed}
theme="light"
className="app-sidebar"
style={{ background: '#fff', borderRight: '1px solid #e5e5e7' }}
>
<div
@@ -192,30 +255,32 @@ const MainLayout: React.FC = () => {
alignItems: 'center',
justifyContent: 'center',
color: '#1d1d1f',
fontSize: (isTablet || collapsed) ? 16 : 17,
fontSize: collapsed ? 16 : 17,
fontWeight: 600,
borderBottom: '1px solid #e5e5e7',
}}
>
{(isTablet || collapsed) ? '' : '恭学教育基地'}
{collapsed ? '' : '学生管理系统'}
</div>
{menuContent}
</Sider>
)}
{isMobile && (
{usesDrawer && (
<Drawer
placement="left"
open={drawerOpen}
onClose={() => setDrawerOpen(false)}
size={240}
styles={{ body: { padding: 0 } }}
title="恭学教育基地"
className="app-navigation-drawer"
title="学生管理系统"
>
{menuContent}
</Drawer>
)}
<Layout style={{ background: '#f5f5f7' }}>
<Layout className="app-main" style={{ background: '#f5f5f7' }}>
<Header
className="app-header"
style={{
padding: '0 16px',
background: '#fff',
@@ -228,9 +293,9 @@ const MainLayout: React.FC = () => {
>
<Button
type="text"
aria-label={isMobile || isTablet ? '打开菜单' : collapsed ? '展开侧边栏' : '收起侧边栏'}
aria-label={usesDrawer ? '打开菜单' : collapsed ? '展开侧边栏' : '收起侧边栏'}
icon={
isMobile || isTablet ? (
usesDrawer ? (
<MenuUnfoldOutlined />
) : collapsed ? (
<MenuUnfoldOutlined />
@@ -238,9 +303,19 @@ const MainLayout: React.FC = () => {
<MenuFoldOutlined />
)
}
onClick={() => (isMobile || isTablet ? setDrawerOpen(true) : setCollapsed(!collapsed))}
onClick={() => (usesDrawer ? setDrawerOpen(true) : setCollapsed(!collapsed))}
/>
<div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
{hasPermission('ai:chat:use') && (
<Tooltip title="AI 助理">
<Button
type="text"
aria-label="打开 AI 助理"
icon={<RobotOutlined style={{ fontSize: 17 }} />}
onClick={() => setAiChatOpen(true)}
/>
</Tooltip>
)}
{hasPermission('notification:view') && <NotificationBell />}
<Dropdown
menu={{
@@ -266,9 +341,16 @@ const MainLayout: React.FC = () => {
</Dropdown>
</div>
</Header>
<RouteDock
location={location}
menuItems={menuItems}
onNavigate={navigate}
draggable={isDesktop}
/>
<Content
className="app-content"
style={{
margin: isMobile ? 12 : isTablet ? 16 : 24,
margin: isMobile ? 8 : isTablet ? 16 : 24,
padding: isMobile ? 12 : isTablet ? 16 : 24,
background: '#fff',
borderRadius: 12,
@@ -277,6 +359,11 @@ const MainLayout: React.FC = () => {
<Outlet />
</Content>
</Layout>
{hasPermission('ai:chat:use') && aiChatOpen && (
<React.Suspense fallback={null}>
<AiChatDrawer open onClose={() => setAiChatOpen(false)} />
</React.Suspense>
)}
</Layout>
);
};

View File

@@ -17,11 +17,7 @@ describe('AiConfig helpers', () => {
});
it('swaps when current baseUrl matches previous provider default', () => {
const result = shouldAutoSwapBaseUrl(
'DEEPSEEK',
'https://api.openai.com/v1',
'OPENAI',
);
const result = shouldAutoSwapBaseUrl('DEEPSEEK', 'https://api.openai.com/v1', 'OPENAI');
expect(result.shouldSwap).toBe(true);
expect(result.baseUrl).toBe(PROVIDER_DEFAULTS.DEEPSEEK);
});
@@ -32,11 +28,7 @@ describe('AiConfig helpers', () => {
});
it('keeps custom baseUrl unchanged', () => {
const result = shouldAutoSwapBaseUrl(
'OPENAI',
'https://custom.api.com/v1',
'DEEPSEEK',
);
const result = shouldAutoSwapBaseUrl('OPENAI', 'https://custom.api.com/v1', 'DEEPSEEK');
expect(result.shouldSwap).toBe(false);
expect(result.baseUrl).toBe('https://custom.api.com/v1');
});

View File

@@ -5,8 +5,8 @@
export type AiProvider = 'OPENAI' | 'DEEPSEEK' | 'OPENAI_COMPATIBLE';
export const PROVIDER_OPTIONS: { value: AiProvider; label: string }[] = [
{ value: 'OPENAI', label: 'OpenAI' },
{ value: 'DEEPSEEK', label: 'DeepSeek' },
{ value: 'OPENAI', label: 'OpenAI' },
{ value: 'OPENAI_COMPATIBLE', label: 'OpenAI 兼容' },
];

View File

@@ -1,11 +1,11 @@
.container {
max-width: 1200px;
max-width: 900px;
margin: 0 auto;
padding: 16px;
}
.header {
margin-bottom: 16px;
margin-bottom: 20px;
}
.header h2 {
@@ -24,17 +24,13 @@
margin-top: 8px;
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
margin-bottom: 16px;
.steps {
margin-bottom: 24px;
}
@media (max-width: 768px) {
.grid {
grid-template-columns: 1fr;
}
.stepContent {
min-height: 320px;
margin-bottom: 16px;
}
.cardTitle {
@@ -42,10 +38,17 @@
font-weight: 600;
}
.actions {
.stepNav {
display: flex;
gap: 8px;
flex-wrap: wrap;
justify-content: space-between;
padding-top: 8px;
border-top: 1px solid #f0f0f0;
}
.modelFetchRow {
display: flex;
align-items: center;
gap: 12px;
}
.testResult {

View File

@@ -6,24 +6,27 @@ import {
Input,
Button,
Select,
Switch,
AutoComplete,
InputNumber,
Tag,
Descriptions,
Spin,
Alert,
Typography,
Tooltip,
Space,
Steps,
Switch,
} from 'antd';
import {
SaveOutlined,
ApiOutlined,
CheckCircleOutlined,
CloseCircleOutlined,
KeyOutlined,
DeleteOutlined,
WarningOutlined,
ReloadOutlined,
CloudServerOutlined,
SafetyOutlined,
RobotOutlined,
} from '@ant-design/icons';
import api from '../../api';
import { message } from '../../ui/app-message';
@@ -55,6 +58,7 @@ interface AiConfigData {
keySource: 'database' | 'environment' | 'none';
defaultModel: string | null;
enabled: boolean;
supportsVision: boolean;
timeoutMs: number;
verified: boolean;
lastTestedAt: string | null;
@@ -72,12 +76,51 @@ interface TestResult {
message: string;
}
interface FetchModelsResult {
success: boolean;
models: Array<{ id: string }>;
message?: string;
}
interface ApiResponse<T> {
success: boolean;
data: T;
message?: string;
}
// ---------------------------------------------------------------------------
// Form state — mirrors all form fields, survives Step unmounts
// ---------------------------------------------------------------------------
interface FormValues {
provider: AiProvider;
baseUrl: string;
apiKey: string;
defaultModel: string;
timeoutMs: number;
supportsVision: boolean;
}
const DEFAULT_FORM_VALUES: FormValues = {
provider: 'DEEPSEEK',
baseUrl: PROVIDER_DEFAULTS['DEEPSEEK'],
apiKey: '',
defaultModel: '',
timeoutMs: 30000,
supportsVision: false,
};
// ---------------------------------------------------------------------------
// Step definitions
// ---------------------------------------------------------------------------
const STEP_ITEMS = [
{ title: '服务商', description: '选择 AI 服务商' },
{ title: '密钥', description: '配置 API 密钥' },
{ title: '模型', description: '获取并选择模型' },
{ title: '完成', description: '保存并测试连接' },
];
// ---------------------------------------------------------------------------
// Page Component
// ---------------------------------------------------------------------------
@@ -87,20 +130,32 @@ const AiConfigPage: React.FC = () => {
const { modal } = App.useApp();
const [form] = Form.useForm();
const [currentStep, setCurrentStep] = useState(0);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const [fetchingModels, setFetchingModels] = useState(false);
const [config, setConfig] = useState<AiConfigData | null>(null);
const [testResult, setTestResult] = useState<TestResult | null>(null);
const [modelOptions, setModelOptions] = useState<Array<{ value: string; label: string }>>([]);
const [error, setError] = useState<string | null>(null);
// Central form state — survives Step transitions when Form.Items unmount
const [formValues, setFormValues] = useState<FormValues>(DEFAULT_FORM_VALUES);
const lastProviderRef = useRef<AiProvider | null>(null);
const canWrite = hasPermission('ai:config:write');
const canTest = hasPermission('ai:config:test');
const canRead = hasPermission('ai:config:read');
// ── Load config ──
// ── Sync form → state ──
const handleFormChange = useCallback((_changed: Partial<FormValues>, all: Partial<FormValues>) => {
setFormValues((prev) => ({ ...prev, ...all }));
}, []);
// ── Load config (full) — used on initial mount and after save ──
const loadConfig = useCallback(async () => {
setLoading(true);
@@ -108,14 +163,22 @@ const AiConfigPage: React.FC = () => {
try {
const res = await api.get<ApiResponse<AiConfigData>>('/ai/config');
setConfig(res.data);
form.setFieldsValue({
const initial: FormValues = {
provider: res.data.provider,
baseUrl: res.data.baseUrl,
defaultModel: res.data.defaultModel ?? undefined,
enabled: res.data.enabled,
apiKey: '',
defaultModel: res.data.defaultModel ?? '',
timeoutMs: res.data.timeoutMs,
});
supportsVision: res.data.supportsVision,
};
form.setFieldsValue(initial);
setFormValues(initial);
lastProviderRef.current = res.data.provider;
if (res.data.defaultModel) {
setModelOptions([{ value: res.data.defaultModel, label: res.data.defaultModel }]);
}
} catch (err: unknown) {
setError(extractErrorMessage(err, '加载配置失败'));
} finally {
@@ -123,6 +186,18 @@ const AiConfigPage: React.FC = () => {
}
}, [form]);
// ── Refresh config (light) — only updates the config info display,
// does NOT touch form values. Used after test/fetch-models. ──
const refreshConfig = useCallback(async () => {
try {
const res = await api.get<ApiResponse<AiConfigData>>('/ai/config');
setConfig(res.data);
} catch {
// silent — config display refresh is non-critical
}
}, []);
useEffect(() => {
loadConfig();
}, [loadConfig]);
@@ -131,55 +206,86 @@ const AiConfigPage: React.FC = () => {
const handleProviderChange = useCallback(
(provider: AiProvider) => {
const currentBaseUrl = form.getFieldValue('baseUrl') || '';
const result = shouldAutoSwapBaseUrl(provider, currentBaseUrl, lastProviderRef.current);
const result = shouldAutoSwapBaseUrl(provider, formValues.baseUrl, lastProviderRef.current);
if (result.shouldSwap) {
form.setFieldValue('baseUrl', result.baseUrl);
}
lastProviderRef.current = provider;
},
[form],
[form, formValues.baseUrl],
);
const currentProvider = Form.useWatch('provider', form) as AiProvider | undefined;
const isFixedProvider = currentProvider ? FIXED_PROVIDERS.includes(currentProvider) : false;
const currentProvider = formValues.provider;
const isFixedProvider = FIXED_PROVIDERS.includes(currentProvider);
// ── Fetch models from provider ──
const handleFetchModels = useCallback(async () => {
setFetchingModels(true);
try {
await form.validateFields(['provider', 'baseUrl']);
const { provider, baseUrl, apiKey: formKey } = formValues;
const body: Record<string, unknown> = { provider };
if (baseUrl) body.baseUrl = baseUrl;
if (formKey && formKey !== '••••') body.apiKey = formKey;
const res = await api.post<FetchModelsResult>('/ai/config/models', body);
if (res.success && res.models.length > 0) {
const options = res.models.map((m) => ({ value: m.id, label: m.id }));
setModelOptions(options);
message.success(`获取到 ${res.models.length} 个模型`);
} else {
message.warning(res.message || '未获取到可用模型');
}
} catch (err: unknown) {
message.error(extractErrorMessage(err, '获取模型列表失败'));
} finally {
setFetchingModels(false);
}
}, [form, formValues]);
// ── Save ──
const handleSave = useCallback(async () => {
try {
const values = await form.validateFields();
setSaving(true);
// Validate fields (for UI error display) — actual values come from state
await form.validateFields(['provider', 'baseUrl', 'timeoutMs']);
// Validate baseUrl for OPENAI_COMPATIBLE
if (values.provider === 'OPENAI_COMPATIBLE' && !values.baseUrl) {
const { provider, baseUrl, defaultModel, apiKey, timeoutMs, supportsVision } = formValues;
if (provider === 'OPENAI_COMPATIBLE' && !baseUrl) {
message.error('OPENAI_COMPATIBLE 模式必须填写 Base URL');
setSaving(false);
return;
}
setSaving(true);
const resolvedBaseUrl = baseUrl || PROVIDER_DEFAULTS[provider] || '';
const body: Record<string, unknown> = {
provider: values.provider,
baseUrl: values.baseUrl,
defaultModel: values.defaultModel || undefined,
enabled: values.enabled,
timeoutMs: values.timeoutMs,
provider,
baseUrl: resolvedBaseUrl,
defaultModel: defaultModel || undefined,
enabled: true,
supportsVision,
timeoutMs,
};
if (values.apiKey && values.apiKey !== '••••') {
body.apiKey = values.apiKey;
if (apiKey && apiKey !== '••••') {
body.apiKey = apiKey;
}
await api.put('/ai/config', body);
message.success('配置已保存');
form.setFieldValue('apiKey', '');
setFormValues((prev) => ({ ...prev, apiKey: '' }));
} catch (err: unknown) {
message.error(extractErrorMessage(err, '保存失败'));
setSaving(false);
return;
}
// Reload config from server (non-fatal if it fails)
try {
await loadConfig();
} catch (err: unknown) {
@@ -187,42 +293,30 @@ const AiConfigPage: React.FC = () => {
} finally {
setSaving(false);
}
}, [form, loadConfig]);
}, [formValues, form, loadConfig]);
// ── Test connection ──
const handleTest = useCallback(async () => {
try {
// Validated fields: compatible requires baseUrl
const fieldsToValidate = ['provider', 'timeoutMs'] as string[];
if (currentProvider === 'OPENAI_COMPATIBLE') {
fieldsToValidate.push('baseUrl');
}
const values = await form.validateFields(fieldsToValidate);
await form.validateFields(fieldsToValidate);
setTesting(true);
setTestResult(null);
const body: Record<string, unknown> = {
timeoutMs: values.timeoutMs,
};
// Always send provider if form has it
if (currentProvider) body.provider = currentProvider;
if (values.baseUrl) body.baseUrl = values.baseUrl;
// Include defaultModel so backend checks target model
const defaultModel = form.getFieldValue('defaultModel');
const { provider, baseUrl, defaultModel, apiKey, timeoutMs } = formValues;
const body: Record<string, unknown> = { provider, timeoutMs };
if (baseUrl) body.baseUrl = baseUrl;
if (defaultModel) body.defaultModel = defaultModel;
const typedKey = form.getFieldValue('apiKey');
if (typedKey && typedKey !== '••••') {
body.apiKey = typedKey;
}
if (apiKey && apiKey !== '••••') body.apiKey = apiKey;
const res = await api.post<TestResult>('/ai/config/test', body);
setTestResult(res);
await loadConfig();
await refreshConfig();
} catch (err: unknown) {
setTestResult({
success: false,
@@ -235,7 +329,7 @@ const AiConfigPage: React.FC = () => {
} finally {
setTesting(false);
}
}, [form, loadConfig, currentProvider]);
}, [formValues, form, loadConfig, currentProvider]);
// ── Clear key ──
@@ -261,6 +355,28 @@ const AiConfigPage: React.FC = () => {
});
}, [config, loadConfig, modal]);
// ── Step navigation ──
const goNext = useCallback(async () => {
// Validate current step fields before moving
try {
if (currentStep === 0) {
await form.validateFields(['provider', 'baseUrl', 'timeoutMs']);
} else if (currentStep === 1) {
// API key step — optional, no validation needed
} else if (currentStep === 2) {
await form.validateFields(['defaultModel']);
}
setCurrentStep((s) => Math.min(s + 1, STEP_ITEMS.length - 1));
} catch {
// Validation failed — form will show errors
}
}, [currentStep, form]);
const goPrev = useCallback(() => {
setCurrentStep((s) => Math.max(s - 1, 0));
}, []);
// ── No read permission ──
if (!canRead) {
@@ -287,41 +403,28 @@ const AiConfigPage: React.FC = () => {
);
}
// ── Render ──
// ── Render step content ──
return (
<div className={styles.container}>
<div className={styles.header}>
<h2>AI </h2>
<p className={styles.headerDesc}></p>
<div className={styles.statusRow}>
<Space size="small">
<Tag color={config?.enabled ? 'green' : 'default'}>
{config?.enabled ? '已启用' : '未启用'}
</Tag>
{config?.verified && <Tag color="blue"></Tag>}
{config?.hasApiKey && (
<Tag color={sourceColor(config?.keySource || 'none')}>
: {sourceLabel(config?.keySource || 'none')}
</Tag>
)}
</Space>
</div>
</div>
<Form form={form} layout="vertical" initialValues={{ timeoutMs: 30000, enabled: false }}>
<div className={styles.grid}>
{/* Left: 模型路由 */}
<Card title={<span className={styles.cardTitle}></span>} extra={<ApiOutlined />}>
const renderStepContent = () => {
switch (currentStep) {
// Step 0: Provider + Base URL + Timeout
case 0:
return (
<Card
title={<span className={styles.cardTitle}></span>}
extra={<CloudServerOutlined />}
>
<Form.Item
name="provider"
label="Provider"
rules={[{ required: true, message: '请选择 Provider' }]}
preserve
>
<Select
options={PROVIDER_OPTIONS}
onChange={handleProviderChange}
disabled={!canWrite}
size="large"
/>
</Form.Item>
@@ -332,36 +435,19 @@ const AiConfigPage: React.FC = () => {
{ required: true, message: '请输入 Base URL' },
{ type: 'url', message: '请输入合法的 URL' },
]}
preserve
>
<Input
placeholder={
config?.provider
? PROVIDER_DEFAULTS[config.provider]
: 'https://api.openai.com/v1'
: 'https://api.deepseek.com'
}
disabled={!canWrite || (isFixedProvider && canWrite)}
size="large"
/>
</Form.Item>
<Form.Item noStyle shouldUpdate={(prev, curr) => prev.enabled !== curr.enabled}>
{({ getFieldValue }) => {
const enabled = getFieldValue('enabled');
return (
<Form.Item
name="defaultModel"
label="默认模型"
rules={enabled ? [{ required: true, message: '启用时默认模型为必填项' }] : []}
>
<Input placeholder="例如: gpt-4, deepseek-chat" disabled={!canWrite} />
</Form.Item>
);
}}
</Form.Item>
<Form.Item name="enabled" label="启用" valuePropName="checked">
<Switch disabled={!canWrite} />
</Form.Item>
<Form.Item
name="timeoutMs"
label="请求超时 (毫秒)"
@@ -369,6 +455,7 @@ const AiConfigPage: React.FC = () => {
{ required: true, message: '请输入超时时间' },
{ type: 'number', min: 1000, max: 120000, message: '范围: 1000-120000' },
]}
preserve
>
<InputNumber
min={1000}
@@ -376,20 +463,25 @@ const AiConfigPage: React.FC = () => {
step={1000}
style={{ width: '100%' }}
disabled={!canWrite}
size="large"
/>
</Form.Item>
</Card>
);
{/* Right: 密钥保险库 */}
// Step 1: API Key
case 1:
return (
<Card
title={<span className={styles.cardTitle}></span>}
extra={<KeyOutlined />}
title={<span className={styles.cardTitle}></span>}
extra={<SafetyOutlined />}
>
<Form.Item name="apiKey" label="API Key">
<Form.Item name="apiKey" label="API Key" preserve>
<Input.Password
placeholder={config?.hasApiKey ? '已安全保存,留空则保持不变' : '请输入 API Key'}
disabled={!canWrite}
autoComplete="new-password"
size="large"
/>
</Form.Item>
@@ -418,7 +510,7 @@ const AiConfigPage: React.FC = () => {
{config?.hasDatabaseKey && canWrite && (
<div style={{ marginBottom: 8 }}>
<Button danger size="small" icon={<DeleteOutlined />} onClick={handleClearKey}>
<Button danger size="small" onClick={handleClearKey}>
</Button>
</div>
@@ -431,7 +523,7 @@ const AiConfigPage: React.FC = () => {
)}
<div className={styles.safetyNote}>
API Key 使 AES-256-GCM 使 IV HTTPS
API Key 使 AES-256-GCM 使 IV HTTPS
</div>
<div className={styles.safetyNoteKey}>
@@ -439,74 +531,243 @@ const AiConfigPage: React.FC = () => {
</div>
</Card>
</div>
);
{/* Actions */}
<div className={styles.actions}>
<Tooltip title={!canWrite ? '当前角色无写入权限' : undefined}>
<Button
type="primary"
icon={<SaveOutlined />}
onClick={handleSave}
loading={saving}
disabled={!canWrite}
// Step 2: Model selection
case 2:
return (
<Card
title={<span className={styles.cardTitle}></span>}
extra={<RobotOutlined />}
>
<div className={styles.modelFetchRow}>
<Button
icon={<ReloadOutlined />}
onClick={handleFetchModels}
loading={fetchingModels}
disabled={!canWrite}
>
</Button>
{modelOptions.length > 0 && (
<Tag color="blue">{modelOptions.length} </Tag>
)}
</div>
<Form.Item
name="defaultModel"
label="默认模型"
rules={[{ required: true, message: '请选择或输入默认模型' }]}
style={{ marginTop: 16 }}
preserve
>
</Button>
</Tooltip>
<Tooltip title={!canTest ? '当前角色无测试权限' : undefined}>
<Button
icon={<ApiOutlined />}
onClick={handleTest}
loading={testing}
disabled={!canTest}
<AutoComplete
options={modelOptions}
placeholder="选择或输入模型名称,如 deepseek-chat, gpt-4"
disabled={!canWrite}
size="large"
filterOption={(inputValue, option) =>
option?.value?.toLowerCase().includes(inputValue.toLowerCase()) ?? false
}
/>
</Form.Item>
<Form.Item
name="supportsVision"
label="图片理解"
valuePropName="checked"
extra="仅当所选模型确实支持图片输入时开启;关闭时 AI 助手会阻止发送图片。"
preserve
>
<Switch disabled={!canWrite} checkedChildren="已启用" unCheckedChildren="未启用" />
</Form.Item>
{config?.verified && (
<div style={{ marginTop: 8 }}>
<Tag icon={<CheckCircleOutlined />} color="success">
</Tag>
{config.lastTestLatencyMs != null && (
<span style={{ marginLeft: 8, fontSize: 12, color: '#999' }}>
: {config.lastTestLatencyMs}ms
</span>
)}
</div>
)}
</Card>
);
// Step 3: Save & Test
case 3:
return (
<Card
title={<span className={styles.cardTitle}></span>}
extra={<CheckCircleOutlined />}
>
<Alert
type="info"
message="配置预览"
description={
<Descriptions column={1} size="small" style={{ marginTop: 8 }}>
<Descriptions.Item label="服务商">
<Tag color="blue">
{PROVIDER_OPTIONS.find((o) => o.value === currentProvider)?.label ??
currentProvider ??
'-'}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="Base URL">
<Typography.Text code>
{formValues.baseUrl || '-'}
</Typography.Text>
</Descriptions.Item>
<Descriptions.Item label="默认模型">
<Tag>{formValues.defaultModel || '未设置'}</Tag>
</Descriptions.Item>
<Descriptions.Item label="密钥">
{(() => {
const hasFormKey = formValues.apiKey && formValues.apiKey !== '••••';
if (config?.hasApiKey) {
return <Tag color="green">{config.maskedApiKey || '••••'}</Tag>;
}
if (hasFormKey) {
return <Tag color="blue"></Tag>;
}
return <Tag color="red"></Tag>;
})()}
</Descriptions.Item>
<Descriptions.Item label="超时">
{formValues.timeoutMs}ms
</Descriptions.Item>
<Descriptions.Item label="图片理解">
<Tag color={formValues.supportsVision ? 'blue' : 'default'}>
{formValues.supportsVision ? '已启用' : '未启用'}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="状态">
<Tag color={config?.enabled ? 'green' : 'default'}>
{config?.enabled ? '已启用' : '未启用'}
</Tag>
</Descriptions.Item>
</Descriptions>
}
style={{ marginBottom: 16 }}
/>
<Space>
{canWrite && (
<Button type="primary" icon={<SaveOutlined />} onClick={handleSave} loading={saving} size="large">
</Button>
)}
{canTest && (
<Button icon={<ApiOutlined />} onClick={handleTest} loading={testing} size="large">
</Button>
)}
</Space>
{/* Test result */}
{testResult && (
<Card size="small" className={styles.testResult}>
<Descriptions column={{ xs: 1, sm: 2 }} size="small">
<Descriptions.Item label="结果">
{testResult.success ? (
testResult.modelAvailable ? (
<Tag icon={<CheckCircleOutlined />} color="success">
</Tag>
) : (
<Tag icon={<WarningOutlined />} color="warning">
</Tag>
)
) : (
<Tag icon={<CloseCircleOutlined />} color="error">
</Tag>
)}
</Descriptions.Item>
<Descriptions.Item label="延迟">
{testResult.latencyMs != null ? `${testResult.latencyMs} ms` : '-'}
</Descriptions.Item>
<Descriptions.Item label="模型数量">
{testResult.modelCount != null ? testResult.modelCount : '-'}
</Descriptions.Item>
<Descriptions.Item label="测试时间">
{formatDateTime(testResult.testedAt)}
</Descriptions.Item>
</Descriptions>
<Alert
type={
testResult.success
? testResult.modelAvailable
? 'success'
: 'warning'
: 'error'
}
title={testResult.message}
style={{ marginTop: 8 }}
/>
</Card>
)}
</Card>
);
default:
return null;
}
};
// ── Render ──
return (
<div className={styles.container}>
<div className={styles.header}>
<h2>AI </h2>
<p className={styles.headerDesc}></p>
<div className={styles.statusRow}>
<Space size="small">
<Tag color={config?.enabled ? 'green' : 'default'}>
{config?.enabled ? '已启用' : '未启用'}
</Tag>
{config?.verified && <Tag color="blue"></Tag>}
{config?.hasApiKey && (
<Tag color={sourceColor(config?.keySource || 'none')}>
: {sourceLabel(config?.keySource || 'none')}
</Tag>
)}
</Space>
</div>
</div>
<Steps
current={currentStep}
items={STEP_ITEMS}
onChange={setCurrentStep}
className={styles.steps}
size="small"
/>
<Form
form={form}
layout="vertical"
initialValues={{ timeoutMs: 30000 }}
onValuesChange={handleFormChange}
>
<div className={styles.stepContent}>{renderStepContent()}</div>
<div className={styles.stepNav}>
<Button onClick={goPrev} disabled={currentStep === 0} icon={<span></span>}>
</Button>
{currentStep < STEP_ITEMS.length - 1 ? (
<Button type="primary" onClick={goNext} icon={<span></span>}>
</Button>
</Tooltip>
) : null}
</div>
</Form>
{/* Test result */}
{testResult && (
<Card size="small" className={styles.testResult}>
<Descriptions column={{ xs: 1, sm: 2 }} size="small">
<Descriptions.Item label="结果">
{testResult.success ? (
testResult.modelAvailable ? (
<Tag icon={<CheckCircleOutlined />} color="success">
</Tag>
) : (
<Tag icon={<WarningOutlined />} color="warning">
</Tag>
)
) : (
<Tag icon={<CloseCircleOutlined />} color="error">
</Tag>
)}
</Descriptions.Item>
<Descriptions.Item label="延迟">
{testResult.latencyMs != null ? `${testResult.latencyMs} ms` : '-'}
</Descriptions.Item>
<Descriptions.Item label="模型数量">
{testResult.modelCount != null ? testResult.modelCount : '-'}
</Descriptions.Item>
<Descriptions.Item label="测试时间">
{formatDateTime(testResult.testedAt)}
</Descriptions.Item>
</Descriptions>
<Alert
type={
testResult.success ? (testResult.modelAvailable ? 'success' : 'warning') : 'error'
}
title={testResult.message}
style={{ marginTop: 8 }}
/>
</Card>
)}
</div>
);
};

View File

@@ -0,0 +1,276 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Alert, Avatar, Button, Drawer, Empty, Input, Progress, Select, Table, Tag } from 'antd';
import dayjs from 'dayjs';
import api from '../../api';
import { message } from '../../ui/app-message';
import {
filterLessonAttendanceRecords,
getPunchDisplayInfo,
summarizeLessonCheckins,
type LessonAttendanceFilter,
} from './attendance-workspace';
import type { LessonAttendanceRecord, LessonAttendanceSchedule } from './types';
import { usePermission } from '../../hooks/usePermission';
interface LessonAttendanceSession {
id: number;
scheduleId: number;
classId: number;
lessonDate: string;
status: 'in_progress' | 'completed';
}
interface LessonAttendanceResponse {
schedule: LessonAttendanceSchedule;
session: LessonAttendanceSession | null;
records: LessonAttendanceRecord[];
}
interface LessonAttendanceDetailProps {
schedule: LessonAttendanceSchedule | null;
className: string;
onClose: () => void;
}
function AttendanceStatus({ status }: { status: string }) {
const checkedIn = status === 'present' || status === 'late';
return (
<span className={`attendance-status ${checkedIn ? 'is-present' : 'is-absent'}`}>
<span className="attendance-status__dot" />
{checkedIn ? '出勤' : '缺勤'}
</span>
);
}
function LessonSummary({ records }: { records: readonly LessonAttendanceRecord[] }) {
const summary = summarizeLessonCheckins(records);
const rate = summary.total > 0 ? Math.round((summary.checkedIn / summary.total) * 100) : 0;
return (
<div className="attendance-summary-strip lesson-summary-strip">
<div className="attendance-rate">
<Progress type="circle" percent={rate} size={64} strokeWidth={9} />
<div>
<span></span>
<strong>{summary.total} </strong>
</div>
</div>
<div className="attendance-summary-cell">
<span className="attendance-summary-icon is-present"></span>
<div>
<strong>{summary.checkedIn}</strong>
<span></span>
</div>
</div>
<div className="attendance-summary-cell">
<span className="attendance-summary-icon is-absent"></span>
<div>
<strong>{summary.notCheckedIn}</strong>
<span></span>
</div>
</div>
</div>
);
}
const LessonAttendanceDetail: React.FC<LessonAttendanceDetailProps> = ({
schedule,
className,
onClose,
}) => {
const { hasAnyPermission } = usePermission();
const canEditAttendance = hasAnyPermission('attendance:edit', 'attendance:self-edit');
const [loadedSchedule, setLoadedSchedule] = useState<LessonAttendanceSchedule | null>(null);
const [session, setSession] = useState<LessonAttendanceSession | null>(null);
const [records, setRecords] = useState<LessonAttendanceRecord[]>([]);
const [loading, setLoading] = useState(false);
const [keyword, setKeyword] = useState('');
const [filter, setFilter] = useState<LessonAttendanceFilter>('all');
useEffect(() => {
if (!schedule) return;
let cancelled = false;
setLoadedSchedule(schedule);
setSession(null);
setRecords([]);
setKeyword('');
setFilter('all');
setLoading(true);
const date = dayjs().format('YYYY-MM-DD');
void api
.post<LessonAttendanceResponse>(`/attendance-lessons/schedules/${schedule.id}/pull`, {
date,
})
.then((data) => {
if (cancelled) return;
setLoadedSchedule(data.schedule);
setSession(data.session);
setRecords(data.records);
message.success('钉钉打卡已更新;课程截止后系统将自动结算');
})
.catch((error: unknown) => {
if (cancelled) return;
message.error((error as { message?: string })?.message || '加载本节课考勤失败');
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [schedule]);
const updateRecord = useCallback(async (record: LessonAttendanceRecord, status: string) => {
const previous = record.status;
setRecords((items) =>
items.map((item) => (item.id === record.id ? { ...item, status } : item)),
);
try {
await api.put(`/attendance-records/${record.id}`, { status });
} catch (error: unknown) {
setRecords((items) =>
items.map((item) => (item.id === record.id ? { ...item, status: previous } : item)),
);
message.error((error as { message?: string })?.message || '更新考勤失败');
}
}, []);
const filteredRecords = useMemo(
() => filterLessonAttendanceRecords(records, keyword, filter),
[filter, keyword, records],
);
const completed = session?.status === 'completed';
const displayedSchedule = loadedSchedule ?? schedule;
return (
<Drawer
open={schedule !== null}
onClose={onClose}
size={960}
title={null}
className="attendance-drawer"
destroyOnHidden
>
<div className="lesson-record-header">
<span className="attendance-eyebrow">LESSON ATTENDANCE</span>
<h2>{displayedSchedule?.subject || '课程考勤'}</h2>
<p>
{className} · {displayedSchedule?.startTime}{displayedSchedule?.endTime} ·{' '}
{dayjs().format('YYYY-MM-DD')}
</p>
</div>
{session && (
<Alert
type={completed ? 'success' : 'info'}
showIcon
title={completed ? '本节课考勤已结算' : '当前打卡结果;课程截止后将自动做最终结算'}
style={{ marginBottom: 16 }}
/>
)}
<LessonSummary records={records} />
<div className="lesson-record-filters">
<Input.Search
allowClear
value={keyword}
placeholder="搜索学生姓名"
onChange={(event) => setKeyword(event.target.value)}
className="lesson-record-search"
/>
<Select<LessonAttendanceFilter>
value={filter}
onChange={setFilter}
options={[
{ value: 'all', label: '全部学生' },
{ value: 'checked_in', label: '已打卡' },
{ value: 'not_checked_in', label: '未打卡' },
]}
className="lesson-record-filter-select"
/>
<span className="lesson-record-filter-count">
{filteredRecords.length} / {records.length}
</span>
</div>
<Table<LessonAttendanceRecord>
rowKey="id"
loading={loading}
dataSource={filteredRecords}
pagination={false}
locale={{
emptyText: (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={records.length === 0 ? '本节课尚未开始点名' : '没有符合条件的学生'}
/>
),
}}
columns={[
{
title: '学生',
dataIndex: ['student', 'name'],
render: (name: string) => (
<div className="student-cell">
<Avatar size={32}>{name?.slice(0, 1)}</Avatar>
<strong>{name || '-'}</strong>
</div>
),
},
{
title: '考勤结果',
dataIndex: 'status',
width: 230,
render: (value: string, record) => {
if (!canEditAttendance) return <AttendanceStatus status={value} />;
const checkedIn = value === 'present' || value === 'late';
return (
<div className="attendance-marking-actions">
<Button
size="small"
type={checkedIn ? 'primary' : 'default'}
onClick={() => void updateRecord(record, 'present')}
>
</Button>
<Button
size="small"
type={!checkedIn ? 'primary' : 'default'}
danger={!checkedIn}
onClick={() => void updateRecord(record, 'absent')}
>
</Button>
</div>
);
},
},
{
title: '当前状态',
dataIndex: 'status',
width: 105,
render: (value: string) => <AttendanceStatus status={value} />,
},
{
title: '打卡设备',
width: 220,
render: (_: unknown, record) => {
const info = getPunchDisplayInfo(record);
if (!info) return <span className="muted-text"></span>;
return (
<div className="punch-device-cell">
<Tag color={info.machine ? 'green' : 'blue'}>{info.label}</Tag>
{info.detail && <strong>{info.detail}</strong>}
{info.time && <span>{dayjs(info.time).format('HH:mm:ss')}</span>}
</div>
);
},
},
{
title: '备注',
dataIndex: 'remark',
render: (value: string | null) => value || <span className="muted-text"></span>,
},
]}
/>
</Drawer>
);
};
export default LessonAttendanceDetail;

View File

@@ -1,7 +1,9 @@
import { describe, expect, it } from 'vitest';
import {
canPullAttendance,
filterLessonAttendanceRecords,
getAttendanceExperience,
getPunchDisplayInfo,
getSchedulePhase,
summarizeAttendance,
summarizeLessonCheckins,
@@ -65,3 +67,60 @@ describe('lesson check-in summary', () => {
).toEqual({ total: 4, checkedIn: 2, notCheckedIn: 2 });
});
});
describe('lesson attendance filters', () => {
const records = [
{ id: 1, student: { name: '张三' }, status: 'present' },
{ id: 2, student: { name: '李四' }, status: 'late' },
{ id: 3, student: { name: '王五' }, status: 'pending' },
{ id: 4, student: { name: '赵六' }, status: 'absent' },
];
it('searches students by name and ignores surrounding whitespace', () => {
expect(filterLessonAttendanceRecords(records, ' 张 ', 'all').map((item) => item.id)).toEqual([
1,
]);
});
it('groups present and late as checked in', () => {
expect(filterLessonAttendanceRecords(records, '', 'checked_in').map((item) => item.id)).toEqual(
[1, 2],
);
});
it('groups pending and absent as not checked in and combines with search', () => {
expect(
filterLessonAttendanceRecords(records, '王', 'not_checked_in').map((item) => item.id),
).toEqual([3]);
});
});
describe('lesson punch device display', () => {
it('labels attendance machine punches with the machine name and id', () => {
expect(
getPunchDisplayInfo({
status: 'present',
source: 'dingtalk',
punchSource: 'ATM',
punchDeviceName: '东门考勤机',
punchDeviceId: 'ATM-01',
punchTime: '2026-07-11T00:55:00.000Z',
}),
).toEqual({
label: '考勤机打卡',
machine: true,
detail: '东门考勤机ATM-01',
time: '2026-07-11T00:55:00.000Z',
});
});
it('distinguishes mobile punches and manual teacher markings', () => {
expect(
getPunchDisplayInfo({ status: 'present', source: 'dingtalk', punchSource: 'USER' }),
).toEqual({ label: '手机打卡', machine: false, detail: undefined, time: undefined });
expect(getPunchDisplayInfo({ status: 'present', source: 'manual' })).toEqual({
label: '老师手动标记',
machine: false,
});
});
});

View File

@@ -8,11 +8,7 @@ export function getAttendanceExperience(
roles: readonly string[],
): AttendanceExperience {
const domains = getRoleDomains(roles, permissions);
if (
permissions.includes('attendance:manage') ||
domains.has('academic') ||
domains.has('super')
) {
if (permissions.includes('attendance:edit') || domains.has('academic') || domains.has('super')) {
return 'admin';
}
return 'teacher';
@@ -82,3 +78,79 @@ export function summarizeLessonCheckins(
notCheckedIn: records.length - checkedIn,
};
}
export type LessonAttendanceFilter = 'all' | 'checked_in' | 'not_checked_in';
export interface LessonAttendanceFilterRecord {
student: { name: string };
status: string;
}
export function filterLessonAttendanceRecords<T extends LessonAttendanceFilterRecord>(
records: readonly T[],
keyword: string,
filter: LessonAttendanceFilter,
): T[] {
const normalizedKeyword = keyword.trim().toLocaleLowerCase('zh-CN');
return records.filter((record) => {
const matchesKeyword =
!normalizedKeyword ||
record.student.name.toLocaleLowerCase('zh-CN').includes(normalizedKeyword);
if (!matchesKeyword || filter === 'all') return matchesKeyword;
const checkedIn = record.status === 'present' || record.status === 'late';
return filter === 'checked_in' ? checkedIn : !checkedIn;
});
}
export interface PunchDisplayRecord {
status: string;
source?: string;
punchTime?: string | null;
punchSource?: string | null;
punchDeviceName?: string | null;
punchDeviceId?: string | null;
}
export interface PunchDisplayInfo {
label: string;
machine: boolean;
detail?: string;
time?: string;
}
export function getPunchDisplayInfo(record: PunchDisplayRecord): PunchDisplayInfo | null {
if (record.status !== 'present' && record.status !== 'late') return null;
if (record.source === 'manual') return { label: '老师手动标记', machine: false };
const source = (record.punchSource || '').trim().toUpperCase();
const machine = ['ATM', 'ATTENDANCE_MACHINE', 'MACHINE', 'DEVICE'].some(
(value) => source === value || source.includes(value),
);
const label = machine
? '考勤机打卡'
: source === 'USER'
? '手机打卡'
: source.includes('BEACON') || source.includes('BLE')
? '蓝牙打卡'
: source.includes('WIFI')
? 'Wi-Fi 打卡'
: source.includes('APPROVE')
? '审批补卡'
: source
? `其他打卡(${record.punchSource}`
: '打卡来源未知';
const device = record.punchDeviceName?.trim();
const deviceId = record.punchDeviceId?.trim();
const detail = device
? deviceId && deviceId !== device
? `${device}${deviceId}`
: device
: deviceId || undefined;
return {
label,
machine,
detail,
time: record.punchTime || undefined,
};
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,28 @@
export interface LessonAttendanceSchedule {
id: number;
classId: number;
classroomId: number;
startTime: string;
endTime: string;
subject: string;
}
export interface LessonAttendanceRecord {
id: number;
studentId: number;
classId: number | null;
attendanceDate: string;
session: string;
status: string;
source?: string;
remark: string | null;
createdAt: string;
student: { id: number; name: string; studentNo?: string | null };
class: { id: number; name: string } | null;
scheduleId?: number | null;
attendanceSessionId?: number | null;
punchTime?: string | null;
punchSource?: string | null;
punchDeviceName?: string | null;
punchDeviceId?: string | null;
}

View File

@@ -0,0 +1,353 @@
import React, { useEffect, useMemo, useState } from 'react';
import { Empty, Form, Input, Modal, Popconfirm, Select, Space, Table, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { PlusOutlined } from '@ant-design/icons';
import api from '../api';
import PermissionButton from '../components/PermissionButton';
import EditableCell from '../components/EditableCell';
import { message } from '../ui/app-message';
interface ClassroomOption {
id: number;
name: string;
building?: string | null;
}
interface AttendanceDeviceRow {
id: number;
deviceSn: string;
deviceName: string;
classroomId: number;
classroom?: ClassroomOption | null;
status: 'active' | 'disabled';
location?: string | null;
notes?: string | null;
}
const statusMeta = {
active: { text: '启用', color: 'green' },
disabled: { text: '停用', color: 'default' },
} as const;
const AttendanceDevicesPage: React.FC = () => {
const [data, setData] = useState<AttendanceDeviceRow[]>([]);
const [classrooms, setClassrooms] = useState<ClassroomOption[]>([]);
const [loading, setLoading] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
const [editing, setEditing] = useState<AttendanceDeviceRow | null>(null);
const [saving, setSaving] = useState(false);
const [keyword, setKeyword] = useState('');
const [form] = Form.useForm();
const loadData = async () => {
setLoading(true);
try {
const [devices, classroomList] = await Promise.all([
api.get<AttendanceDeviceRow[]>('/attendance-devices'),
api.get<ClassroomOption[]>('/classrooms'),
]);
setData(devices);
setClassrooms(classroomList.filter((item: any) => item.status !== 'archived'));
} catch (error: any) {
message.error(error?.message || '加载考勤机绑定失败');
} finally {
setLoading(false);
}
};
useEffect(() => {
void loadData();
}, []);
const classroomOptions = useMemo(
() =>
classrooms.map((item) => ({
value: item.id,
label: item.building ? `${item.name}${item.building}` : item.name,
})),
[classrooms],
);
const filteredData = useMemo(() => {
const text = keyword.trim().toLocaleLowerCase('zh-CN');
if (!text) return data;
return data.filter((item) =>
[item.deviceSn, item.deviceName, item.classroom?.name, item.location].some((value) =>
(value || '').toLocaleLowerCase('zh-CN').includes(text),
),
);
}, [data, keyword]);
const openCreate = () => {
setEditing(null);
form.resetFields();
form.setFieldsValue({ status: 'active' });
setModalOpen(true);
};
const openEdit = (record: AttendanceDeviceRow) => {
setEditing(record);
form.setFieldsValue({
deviceSn: record.deviceSn,
deviceName: record.deviceName,
classroomId: record.classroomId,
status: record.status,
location: record.location,
notes: record.notes,
});
setModalOpen(true);
};
const handleSave = async () => {
const values = await form.validateFields();
setSaving(true);
try {
if (editing) {
await api.put(`/attendance-devices/${editing.id}`, values);
message.success('考勤机绑定已更新');
} else {
await api.post('/attendance-devices', values);
message.success('考勤机绑定已创建');
}
setModalOpen(false);
setEditing(null);
form.resetFields();
await loadData();
} catch (error: any) {
message.error(error?.message || '保存失败');
} finally {
setSaving(false);
}
};
const saveCell = async (record: AttendanceDeviceRow, field: string, value: unknown) => {
await api.put(`/attendance-devices/${record.id}`, { [field]: value });
message.success('已保存');
await loadData();
};
const handleDelete = async (id: number) => {
try {
await api.delete(`/attendance-devices/${id}`);
message.success('已停用绑定');
await loadData();
} catch (error: any) {
message.error(error?.message || '停用失败');
}
};
const columns: ColumnsType<AttendanceDeviceRow> = [
{
title: '设备名称',
dataIndex: 'deviceName',
width: 180,
render: (value: string, record) => (
<EditableCell
value={value}
required
permission="classroom:edit"
onSave={(next) => saveCell(record, 'deviceName', next)}
>
{value}
</EditableCell>
),
},
{
title: 'SN 码',
dataIndex: 'deviceSn',
width: 220,
render: (value, record) => (
<EditableCell
value={value}
required
permission="classroom:edit"
onSave={(next) => saveCell(record, 'deviceSn', next)}
>
<span style={{ fontFamily: 'monospace' }}>{value}</span>
</EditableCell>
),
},
{
title: '绑定教室',
dataIndex: ['classroom', 'name'],
width: 160,
render: (_value, record) => (
<EditableCell
value={record.classroomId}
editor="select"
options={classrooms.map((item) => ({
value: item.id,
label: item.building ? `${item.building} · ${item.name}` : item.name,
}))}
permission="classroom:edit"
required
onSave={(next) => saveCell(record, 'classroomId', next)}
>
{record.classroom?.name || `教室 ${record.classroomId}`}
</EditableCell>
),
},
{
title: '位置',
dataIndex: 'location',
render: (value, record) => (
<EditableCell
value={value}
permission="classroom:edit"
onSave={(next) => saveCell(record, 'location', next)}
>
{value || <span style={{ color: '#999' }}></span>}
</EditableCell>
),
},
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (value: keyof typeof statusMeta, record) => (
<EditableCell
value={value}
editor="select"
options={[
{ value: 'active', label: '启用' },
{ value: 'disabled', label: '停用' },
]}
permission="classroom:edit"
onSave={(next) => saveCell(record, 'status', next)}
>
<Tag color={statusMeta[value]?.color}>{statusMeta[value]?.text || value}</Tag>
</EditableCell>
),
},
{
title: '备注',
dataIndex: 'notes',
ellipsis: true,
render: (value, record) => (
<EditableCell
value={value}
editor="textarea"
permission="classroom:edit"
onSave={(next) => saveCell(record, 'notes', next)}
>
{value || <span style={{ color: '#999' }}></span>}
</EditableCell>
),
},
{
title: '操作',
width: 150,
render: (_, record) => (
<Space>
<PermissionButton
permission="classroom:edit"
size="small"
type="link"
onClick={() => openEdit(record)}
>
</PermissionButton>
<Popconfirm title="确定停用此考勤机绑定?" onConfirm={() => handleDelete(record.id)}>
<PermissionButton permission="classroom:edit" size="small" danger>
</PermissionButton>
</Popconfirm>
</Space>
),
},
];
return (
<div>
<div
style={{
marginBottom: 16,
display: 'flex',
justifyContent: 'space-between',
flexWrap: 'wrap',
gap: 8,
}}
>
<Input.Search
allowClear
placeholder="搜索设备/SN/教室"
style={{ width: 260 }}
value={keyword}
onChange={(event) => setKeyword(event.target.value)}
/>
<PermissionButton
permission="classroom:edit"
type="primary"
icon={<PlusOutlined />}
onClick={openCreate}
>
</PermissionButton>
</div>
<Table<AttendanceDeviceRow>
rowKey="id"
columns={columns}
dataSource={filteredData}
loading={loading}
locale={{ emptyText: <Empty description="暂无考勤机绑定" /> }}
pagination={{ defaultPageSize: 20, showSizeChanger: true }}
/>
<Modal
title={editing ? '编辑考勤机绑定' : '添加考勤机绑定'}
open={modalOpen}
onOk={handleSave}
onCancel={() => {
setModalOpen(false);
setEditing(null);
}}
confirmLoading={saving}
okText="保存"
>
<Form form={form} layout="vertical">
<Form.Item
name="deviceName"
label="设备名称"
rules={[{ required: true, message: '请输入设备名称' }]}
>
<Input placeholder="如彼岸游境_N1604" />
</Form.Item>
<Form.Item
name="deviceSn"
label="SN 码"
rules={[{ required: true, message: '请输入钉钉返回的 deviceSN' }]}
>
<Input placeholder="如300419260325WN1604" />
</Form.Item>
<Form.Item
name="classroomId"
label="绑定教室"
rules={[{ required: true, message: '请选择绑定教室' }]}
>
<Select
showSearch
optionFilterProp="label"
options={classroomOptions}
placeholder="选择教室"
/>
</Form.Item>
<Form.Item name="status" label="状态" initialValue="active">
<Select
options={[
{ value: 'active', label: '启用' },
{ value: 'disabled', label: '停用' },
]}
/>
</Form.Item>
<Form.Item name="location" label="位置">
<Input placeholder="如:教学楼一楼东侧" />
</Form.Item>
<Form.Item name="notes" label="备注">
<Input.TextArea rows={2} />
</Form.Item>
</Form>
</Modal>
</div>
);
};
export default AttendanceDevicesPage;

View File

@@ -0,0 +1,110 @@
interface BillPrintItem {
expenseType?: string | null;
description?: string | null;
days?: number | null;
totalRoomDays?: number | null;
studentAmount?: number | string | null;
}
export interface BillPrintData {
id: number;
student?: { name?: string | null } | null;
periodStart?: string | null;
periodEnd?: string | null;
status?: string | null;
sharedAmount?: number | string | null;
personalAmount?: number | string | null;
totalAmount?: number | string | null;
paidAmount?: number | string | null;
outstandingAmount?: number | string | null;
items?: BillPrintItem[] | null;
}
const statusLabels: Record<string, string> = {
unpaid: '待支付',
partially_paid: '部分支付',
paid: '已结清',
cancelled: '已取消',
};
const escapeHtml = (value: unknown) =>
String(value ?? '')
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#039;');
const money = (value: unknown) => `¥${Number(value || 0).toFixed(2)}`;
export const buildBillPrintHtml = (bill: BillPrintData) => {
const rows = (bill.items ?? [])
.map(
(item) => `
<tr>
<td>${escapeHtml(item.expenseType || '')}</td>
<td>${escapeHtml(item.description || '')}</td>
<td>${Number(item.days || 0)}</td>
<td>${Number(item.totalRoomDays || 0)}</td>
<td>${Number(item.studentAmount || 0).toFixed(2)}</td>
</tr>`,
)
.join('');
return `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>账单_${bill.id}</title>
<style>
@page { size: A4; margin: 50pt; }
* { box-sizing: border-box; }
body {
margin: 0;
color: #000;
font-family: "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
font-size: 12px;
line-height: 1.5;
}
h1 { margin: 0; font-size: 20px; font-weight: 600; text-align: center; }
h2 { margin: 20px 0 6px; font-size: 14px; text-decoration: underline; }
p { margin: 2px 0; }
.generated { margin: 6px 0 18px; color: #666; font-size: 10px; text-align: center; }
.total { color: #007aff; font-size: 14px; font-weight: 600; }
.paid { color: #389e0d; font-size: 11px; }
.outstanding { color: ${Number(bill.outstandingAmount || 0) > 0 ? '#ff3b30' : '#389e0d'}; font-size: 14px; font-weight: 600; }
table { width: 100%; border-collapse: collapse; table-layout: fixed; font-size: 9px; }
th, td { padding: 4px 0; text-align: left; vertical-align: top; word-break: break-word; }
th { color: #333; font-size: 10px; font-weight: 400; border-bottom: 1px solid #ccc; }
th:nth-child(1) { width: 24%; }
th:nth-child(2) { width: 36%; }
th:nth-child(3), th:nth-child(4) { width: 12%; }
th:nth-child(5) { width: 16%; }
.empty { padding: 12px 0; color: #999; text-align: center; }
.footer { margin-top: 34px; color: #999; font-size: 8px; text-align: center; }
</style>
</head>
<body>
<h1>恭学教育基地水电费账单</h1>
<div class="generated">生成时间: ${escapeHtml(new Date().toLocaleString('zh-CN'))}</div>
<p>学生姓名: ${escapeHtml(bill.student?.name || '-')}</p>
<p>计费周期: ${escapeHtml(bill.periodStart || '-')} ~ ${escapeHtml(bill.periodEnd || '-')}</p>
<p>账单状态: ${escapeHtml(statusLabels[bill.status || ''] || bill.status || '-')}</p>
<h2>费用汇总</h2>
<p>分摊费用: ${money(bill.sharedAmount)}</p>
<p>个人费用: ${money(bill.personalAmount)}</p>
<p class="total">应付总额: ${money(bill.totalAmount)}</p>
<p class="paid">已扣余额: ${money(bill.paidAmount)}</p>
<p class="outstanding">待补缴: ${money(bill.outstandingAmount)}</p>
<h2>费用明细</h2>
<table>
<thead><tr><th>费用类型</th><th>说明</th><th>天数</th><th>总人天</th><th>金额(元)</th></tr></thead>
<tbody>${rows || '<tr><td class="empty" colspan="5">暂无费用明细</td></tr>'}</tbody>
</table>
<div class="footer">本账单由学生管理系统自动生成</div>
<script>window.addEventListener('load', function () { setTimeout(function () { window.print(); }, 100); });</script>
</body>
</html>`;
};

View File

@@ -10,13 +10,12 @@ import {
Popconfirm,
Input,
Select,
Tooltip,
Spin,
Empty,
} from 'antd';
import {
FileTextOutlined,
DeleteOutlined,
InboxOutlined,
DownloadOutlined,
FilePdfOutlined,
} from '@ant-design/icons';
@@ -25,13 +24,14 @@ import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
import { downloadBlob } from '../../utils/download';
import { message } from '../../ui/app-message';
const { RangePicker } = DatePicker;
import { buildBillPrintHtml, type BillPrintData } from './bill-print';
import { newOperationId } from '../../utils/operation-id';
const statusMap: Record<string, { text: string; color: string }> = {
draft: { text: '草稿', color: 'default' },
confirmed: { text: '已确认', color: 'blue' },
unpaid: { text: '待支付', color: 'orange' },
partially_paid: { text: '部分支付', color: 'gold' },
paid: { text: '已支付', color: 'green' },
cancelled: { text: '已取消', color: 'default' },
};
const typeMap: Record<string, string> = {
@@ -63,7 +63,7 @@ const BillsPage: React.FC = () => {
const params: Record<string, string | undefined> = {};
if (filterStatus) params.status = filterStatus;
if (filterExpenseType) params.expenseType = filterExpenseType;
const res = await api.get('/bills', { params }) as unknown[];
const res = (await api.get('/bills', { params })) as unknown[];
setBills(res);
} catch (e: any) {
message.error(e?.message || '加载失败,请稍后重试');
@@ -93,8 +93,8 @@ const BillsPage: React.FC = () => {
const values = await generateForm.validateFields();
try {
const res: any = await api.post('/bills/generate', {
periodStart: values.period[0].format('YYYY-MM-DD'),
periodEnd: values.period[1].format('YYYY-MM-DD'),
operationId: newOperationId(),
billingMonth: values.billingMonth.format('YYYY-MM'),
});
message.success(res.message || '生成成功');
setGenerateModal(false);
@@ -119,52 +119,53 @@ const BillsPage: React.FC = () => {
}
};
const updateStatus = async (id: number, status: string) => {
try {
await api.put(`/bills/${id}/status`, { status });
message.success('状态更新成功');
fetchData();
if (detailModal?.id === id) {
setDetailModal({ ...detailModal, status });
}
} catch (e: any) {
message.error(e?.message || '操作失败');
}
const handleCancel = async (id: number) => {
let reason = '';
Modal.confirm({
title: '取消账单并退回已扣余额',
content: (
<Input.TextArea
placeholder="请输入取消原因"
maxLength={300}
onChange={(event) => {
reason = event.target.value;
}}
/>
),
okText: '确认取消',
cancelText: '返回',
onOk: async () => {
if (!reason.trim()) {
message.error('请输入取消原因');
throw new Error('reason required');
}
await api.post(`/bills/${id}/cancel`, {
operationId: newOperationId(),
reason: reason.trim(),
});
message.success('账单已取消,已扣余额已冲正退回');
fetchData();
},
});
};
const batchUpdateStatus = async (status: string) => {
if (selectedRows.length === 0) return message.warning('请先选择账单');
if (batchLoading) return;
setBatchLoading(true);
try {
await api.put('/bills/batch/status', { ids: selectedRows, status });
message.success(`已批量更新 ${selectedRows.length} 条账单`);
setSelectedRows([]);
fetchData();
} catch (e: any) {
message.error(e?.message || '操作失败');
} finally {
setBatchLoading(false);
}
};
const handleDelete = async (id: number) => {
const handleArchive = async (id: number) => {
try {
await api.delete(`/bills/${id}`);
message.success('账单已删除');
message.success('账单已归档');
fetchData();
} catch (e: any) {
message.error(e?.message || '删除失败');
} catch (error: any) {
message.error(error?.message || '归档失败');
}
};
const batchDelete = async () => {
const batchArchive = async () => {
if (selectedRows.length === 0) return message.warning('请先选择账单');
if (batchLoading) return;
setBatchLoading(true);
try {
await api.post('/bills/batch/delete', { ids: selectedRows });
message.success(`删除 ${selectedRows.length} 条账单`);
message.success(`归档 ${selectedRows.length} 条账单`);
setSelectedRows([]);
fetchData();
} catch (e: any) {
@@ -181,142 +182,151 @@ const BillsPage: React.FC = () => {
);
};
const handleExportPdf = (billId: number) => {
downloadBlob(`/bills/export/pdf/${billId}`, `账单_${billId}.pdf`).catch(() =>
message.error('导出失败'),
const handleExportPdf = async (billId: number) => {
const printWindow = window.open('', '_blank');
if (!printWindow) {
message.error('浏览器阻止了打印窗口,请允许弹出窗口后重试');
return;
}
printWindow.document.write(
'<p style="font-family:sans-serif;padding:24px">正在加载账单...</p>',
);
try {
const bill = await api.get<BillPrintData>(`/bills/${billId}`);
printWindow.document.open();
printWindow.document.write(buildBillPrintHtml(bill));
printWindow.document.close();
} catch (error: any) {
printWindow.close();
message.error(error?.message || '账单加载失败');
}
};
const columns = useMemo(() => [
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
{ title: '账单周期', width: 200, render: (_: any, r: any) => `${r.periodStart} ~ ${r.periodEnd}` },
{
title: '分摊费用',
dataIndex: 'sharedAmount',
width: 120,
align: 'right' as const,
render: (v: number) => `¥${Number(v).toFixed(2)}`,
},
{
title: '个人费用',
dataIndex: 'personalAmount',
width: 120,
align: 'right' as const,
render: (v: number) => `¥${Number(v).toFixed(2)}`,
},
{
title: '总计',
dataIndex: 'totalAmount',
width: 100,
align: 'right' as const,
render: (v: number) => <strong>¥{Number(v).toFixed(2)}</strong>,
},
{
title: '可用押金',
dataIndex: 'availableDeposit',
width: 120,
render: (v: number) =>
v > 0 ? (
<span style={{ color: '#52c41a' }}>¥{Number(v).toFixed(2)}</span>
) : (
<span style={{ color: '#999' }}>-</span>
),
},
{
title: '抵扣后应付',
dataIndex: 'amountAfterDeposit',
width: 130,
render: (v: number, r: any) => {
const has = Number(r.availableDeposit || 0) > 0;
if (!has) return <span style={{ color: '#999' }}>-</span>;
const after = Number(v ?? r.totalAmount).toFixed(2);
const applied = Number(r.depositApplied || 0).toFixed(2);
return (
<Tooltip title={`已抵扣押金 ¥${applied}`}>
<strong style={{ color: '#fa541c' }}>¥{after}</strong>
</Tooltip>
);
const columns = useMemo(
() => [
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
{
title: '账单周期',
width: 200,
render: (_: any, r: any) => `${r.periodStart} ~ ${r.periodEnd}`,
},
},
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text}</Tag>,
},
{
title: '生成时间',
dataIndex: 'generatedAt',
width: 160,
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
},
{
title: '操作',
width: 320,
render: (_: any, record: any) => (
<Space>
<PermissionButton
permission="bill:view"
size="small"
type="link"
onClick={() => showDetail(record.id)}
>
</PermissionButton>
{record.status === 'draft' && (
{
title: '分摊费用',
dataIndex: 'sharedAmount',
width: 120,
align: 'right' as const,
render: (v: number) => `¥${Number(v).toFixed(2)}`,
},
{
title: '个人费用',
dataIndex: 'personalAmount',
width: 120,
align: 'right' as const,
render: (v: number) => `¥${Number(v).toFixed(2)}`,
},
{
title: '总计',
dataIndex: 'totalAmount',
width: 100,
align: 'right' as const,
render: (v: number) => <strong>¥{Number(v).toFixed(2)}</strong>,
},
{
title: '已扣余额',
dataIndex: 'paidAmount',
width: 110,
render: (value: number) => (
<span style={{ color: '#389e0d' }}>¥{Number(value || 0).toFixed(2)}</span>
),
},
{
title: '待补缴',
dataIndex: 'outstandingAmount',
width: 110,
render: (value: number) => (
<strong style={{ color: Number(value) > 0 ? '#cf1322' : '#389e0d' }}>
¥{Number(value || 0).toFixed(2)}
</strong>
),
},
{
title: '钱包余额',
dataIndex: 'walletBalance',
width: 110,
render: (value: number) => `¥${Number(value || 0).toFixed(2)}`,
},
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text}</Tag>,
},
{
title: '生成时间',
dataIndex: 'generatedAt',
width: 160,
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
},
{
title: '操作',
width: 320,
render: (_: any, record: any) => (
<Space>
<PermissionButton
permission="bill:confirm"
permission="bill:view"
size="small"
onClick={() => updateStatus(record.id, 'confirmed')}
type="link"
onClick={() => showDetail(record.id)}
>
</PermissionButton>
)}
{record.status === 'confirmed' && (
<PermissionButton
permission="bill:confirm"
permission="bill:export-pdf"
size="small"
type="primary"
onClick={() => updateStatus(record.id, 'paid')}
icon={<FilePdfOutlined />}
onClick={() => handleExportPdf(record.id)}
>
PDF
</PermissionButton>
)}
<PermissionButton
permission="bill:export-pdf"
size="small"
icon={<FilePdfOutlined />}
onClick={() => handleExportPdf(record.id)}
>
PDF
</PermissionButton>
<Popconfirm
title="确定删除此账单?"
onConfirm={() => handleDelete(record.id)}
okText="删除"
cancelText="取消"
>
<PermissionButton permission="bill:delete" size="small" danger icon={<DeleteOutlined />}>
</PermissionButton>
</Popconfirm>
</Space>
),
},
], [showDetail, updateStatus, handleDelete, handleExportPdf]);
{record.status !== 'cancelled' && (
<PermissionButton
permission="bill:delete"
size="small"
danger
onClick={() => handleCancel(record.id)}
>
</PermissionButton>
)}
{Number(record.paidAmount || 0) === 0 && record.status !== 'cancelled' && (
<Popconfirm
title="确定归档此未支付账单?"
onConfirm={() => handleArchive(record.id)}
okText="归档"
cancelText="取消"
>
<PermissionButton
permission="bill:delete"
size="small"
danger
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
)}
</Space>
),
},
],
[showDetail, handleArchive, handleCancel, handleExportPdf],
);
return (
<div>
<div
style={{
marginBottom: 16,
display: 'flex',
justifyContent: 'space-between',
flexWrap: 'wrap',
gap: 8,
}}
>
<Space wrap>
<div className="responsive-toolbar">
<Space wrap className="responsive-toolbar__group">
<Input.Search
placeholder="搜索学生姓名或账单周期"
allowClear
@@ -333,32 +343,30 @@ const BillsPage: React.FC = () => {
value={filterStatus}
onChange={(v) => setFilterStatus(v)}
options={[
{ value: 'draft', label: '草稿' },
{ value: 'confirmed', label: '已确认' },
{ value: 'unpaid', label: '待支付' },
{ value: 'partially_paid', label: '部分支付' },
{ value: 'paid', label: '已支付' },
{ value: 'cancelled', label: '已取消' },
]}
/>
<Select
placeholder="费用类型"
allowClear
style={{ width: 120 }}
value={filterExpenseType}
onChange={setFilterExpenseType}
options={[
{ value: 'water', label: '水费' },
{ value: 'electricity', label: '电费' },
{ value: 'cleaning', label: '保洁费' },
{ value: 'rent', label: '租金' },
{ value: 'other', label: '其他' },
]}
/>
<Select placeholder="费用类型" allowClear style={{ width: 120 }} value={filterExpenseType} onChange={setFilterExpenseType}
options={[{value:'water',label:'水费'},{value:'electricity',label:'电费'},{value:'cleaning',label:'保洁费'},{value:'rent',label:'租金'},{value:'other',label:'其他'}]} />
<PermissionButton
permission="bill:confirm"
onClick={() => batchUpdateStatus('confirmed')}
disabled={selectedRows.length === 0}
>
</PermissionButton>
<PermissionButton
permission="bill:confirm"
type="primary"
onClick={() => batchUpdateStatus('paid')}
disabled={selectedRows.length === 0}
>
</PermissionButton>
<Popconfirm
title={`确定删除选中的 ${selectedRows.length} 条账单?`}
onConfirm={batchDelete}
okText="删除"
title={`确定归档选中的 ${selectedRows.length} 条账单?`}
onConfirm={batchArchive}
okText="归档"
cancelText="取消"
disabled={selectedRows.length === 0}
>
@@ -366,13 +374,13 @@ const BillsPage: React.FC = () => {
permission="bill:delete"
danger
disabled={selectedRows.length === 0}
icon={<DeleteOutlined />}
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
</Space>
<Space>
<Space wrap className="responsive-toolbar__group">
<PermissionButton
permission="bill:generate"
type="primary"
@@ -417,15 +425,19 @@ const BillsPage: React.FC = () => {
>
<Form form={generateForm} layout="vertical">
<Form.Item
name="period"
label="账单周期"
rules={[{ required: true, message: '请选择账单周期' }]}
extra="选择费用对应的时间段,系统将自动计算每个学生的分摊费用"
name="billingMonth"
label="账单月份"
rules={[{ required: true, message: '请选择账单月份' }]}
extra="只能选择已结束月份,每个月只能生成一次账单"
>
<RangePicker
<DatePicker
style={{ width: '100%' }}
placeholder={['开始日期', '结束日期']}
format="YYYY-MM-DD"
picker="month"
placeholder="选择月份"
format="YYYY-MM"
disabledDate={(current) =>
!!current && !current.endOf('month').isBefore(dayjs(), 'day')
}
/>
</Form.Item>
</Form>
@@ -465,42 +477,17 @@ const BillsPage: React.FC = () => {
</strong>
</Descriptions.Item>
</Descriptions>
{Number(detailModal.availableDeposit || 0) > 0 && (
<div
style={{
marginBottom: 16,
padding: 12,
background: '#f6ffed',
border: '1px solid #b7eb8f',
borderRadius: 8,
}}
>
<div style={{ fontSize: 13, color: '#666', marginBottom: 6 }}>
</div>
<Space size={24} wrap>
<span>
<strong style={{ color: '#52c41a' }}>
¥{Number(detailModal.availableDeposit).toFixed(2)}
</strong>
</span>
<span>
<strong style={{ color: '#fa8c16' }}>
-¥{Number(detailModal.depositApplied || 0).toFixed(2)}
</strong>
</span>
<span>
<strong style={{ color: '#fa541c', fontSize: 16 }}>
¥
{Number(detailModal.amountAfterDeposit ?? detailModal.totalAmount).toFixed(2)}
</strong>
</span>
</Space>
</div>
)}
<Descriptions bordered size="small" column={3} style={{ marginBottom: 16 }}>
<Descriptions.Item label="已扣余额">
¥{Number(detailModal.paidAmount || 0).toFixed(2)}
</Descriptions.Item>
<Descriptions.Item label="待补缴">
¥{Number(detailModal.outstandingAmount || 0).toFixed(2)}
</Descriptions.Item>
<Descriptions.Item label="当前钱包余额">
¥{Number(detailModal.walletBalance || 0).toFixed(2)}
</Descriptions.Item>
</Descriptions>
<h4></h4>
<Table
scroll={{ x: 700 }}

View File

@@ -1,8 +1,23 @@
import React, { useEffect, useState, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
Card, Tabs, Descriptions, Table, Button, Space, Select, Modal, Tag,
Popconfirm, Form, Input, DatePicker, InputNumber, Row, Col, Statistic,
Card,
Tabs,
Descriptions,
Table,
Button,
Space,
Select,
Modal,
Tag,
Popconfirm,
Form,
Input,
DatePicker,
InputNumber,
Row,
Col,
Statistic,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { ArrowLeftOutlined, PlusOutlined, DownloadOutlined } from '@ant-design/icons';
@@ -10,6 +25,7 @@ import dayjs from 'dayjs';
import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
import { message } from '../../ui/app-message';
import { buildTeacherCandidateOptions, type TeacherCandidateUser } from './teacher-candidate';
// ---- Types ----
@@ -19,6 +35,7 @@ interface ClassStudent {
studentName: string;
studentNo: string;
joinDate: string;
leaveDate: string | null;
status: string;
}
@@ -38,6 +55,7 @@ interface ClassScheduleItem {
weekDay: number;
startTime: string;
endTime: string;
attendanceAdvanceMinutes: number;
startDate: string;
endDate: string;
subject: string;
@@ -82,10 +100,7 @@ interface StudentItem {
studentNo?: string;
}
interface UserItem {
id: number;
username: string;
}
type UserItem = TeacherCandidateUser;
// ---- Constants ----
@@ -111,7 +126,13 @@ const ROLE_MAP: Record<string, string> = {
};
const WEEK_DAY_MAP: Record<number, string> = {
1: '周一', 2: '周二', 3: '周三', 4: '周四', 5: '周五', 6: '周六', 7: '周日',
1: '周一',
2: '周二',
3: '周三',
4: '周四',
5: '周五',
6: '周六',
7: '周日',
};
const SCHEDULE_TYPE_MAP: Record<string, string> = {
@@ -145,14 +166,18 @@ const ClassDetailPage: React.FC = () => {
// Schedule & attendance state
const [schedules, setSchedules] = useState<ClassScheduleItem[]>([]);
const [scheduleDateRange, setScheduleDateRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null]>([null, null]);
const [scheduleDateRange, setScheduleDateRange] = useState<
[dayjs.Dayjs | null, dayjs.Dayjs | null]
>([null, null]);
const [attendanceSummary, setAttendanceSummary] = useState<AttendanceSummary | null>(null);
const [attendanceDateRange, setAttendanceDateRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null]>([null, null]);
const [attendanceDateRange, setAttendanceDateRange] = useState<
[dayjs.Dayjs | null, dayjs.Dayjs | null]
>([null, null]);
const fetchDetail = useCallback(async () => {
setLoading(true);
try {
const res = await api.get(`/classes/${id}`) as ClassDetail;
const res = (await api.get(`/classes/${id}`)) as ClassDetail;
setDetail(res);
setStudents(res.students || []);
setTeachers(res.teachers || []);
@@ -164,7 +189,19 @@ const ClassDetailPage: React.FC = () => {
}
}, [id]);
useEffect(() => { fetchDetail(); }, [fetchDetail]);
const fetchUsers = useCallback(async () => {
try {
const res = (await api.get('/rbac/users')) as UserItem[];
setAllUsers(res || []);
} catch {
setAllUsers([]);
}
}, []);
useEffect(() => {
fetchDetail();
fetchUsers();
}, [fetchDetail, fetchUsers]);
const fetchSchedules = useCallback(async () => {
if (!id) return;
@@ -180,7 +217,9 @@ const ClassDetailPage: React.FC = () => {
}
}, [id, scheduleDateRange]);
useEffect(() => { fetchSchedules(); }, [fetchSchedules]);
useEffect(() => {
fetchSchedules();
}, [fetchSchedules]);
const fetchAttendanceSummary = useCallback(async () => {
if (!id) return;
@@ -196,7 +235,9 @@ const ClassDetailPage: React.FC = () => {
}
}, [id, attendanceDateRange]);
useEffect(() => { fetchAttendanceSummary(); }, [fetchAttendanceSummary]);
useEffect(() => {
fetchAttendanceSummary();
}, [fetchAttendanceSummary]);
const handleSaveInfo = async () => {
try {
@@ -275,7 +316,9 @@ const ClassDetailPage: React.FC = () => {
const openStudentModal = async () => {
try {
const res = await api.get('/students', { params: { includeArchived: 'false' } }) as StudentItem[];
const res = (await api.get('/students', {
params: { includeArchived: 'false' },
})) as StudentItem[];
setAllStudents(res || []);
setSelectedStudentIds([]);
setStudentModalOpen(true);
@@ -287,8 +330,7 @@ const ClassDetailPage: React.FC = () => {
const openTeacherModal = async () => {
try {
const res = await api.get('/rbac/users') as UserItem[];
setAllUsers(res || []);
await fetchUsers();
setTeacherUserId(undefined);
setTeacherRole('subject_teacher');
setTeacherSubject('');
@@ -299,33 +341,38 @@ const ClassDetailPage: React.FC = () => {
}
};
const getTeacherName = (teacher: ClassTeacher) =>
allUsers.find((user) => user.id === teacher.userId)?.name?.trim() || '-';
if (!detail) return null;
const studentColumns: ColumnsType<ClassStudent> = [
{ title: '姓名', dataIndex: 'studentName' },
{ title: '学号', dataIndex: 'studentNo' },
{ title: '加入日期', dataIndex: 'joinDate' },
{ title: '离班日期', dataIndex: 'leaveDate', render: (v: string | null) => v || '-' },
{
title: '状态',
dataIndex: 'status',
render: (v: string) => (
<Tag color={v === 'active' ? 'green' : 'default'}>
{v === 'active' ? '在读' : '已离班'}
</Tag>
<Tag color={v === 'active' ? 'green' : 'default'}>{v === 'active' ? '在读' : '已离班'}</Tag>
),
},
{
title: '操作',
render: (_: unknown, r: ClassStudent) => (
<Popconfirm title="确认移除?" onConfirm={() => handleRemoveStudent(r.studentId)}>
<PermissionButton permission="class:edit" size="small" danger></PermissionButton>
</Popconfirm>
),
render: (_: unknown, r: ClassStudent) =>
r.status === 'active' ? (
<Popconfirm title="确认移除?" onConfirm={() => handleRemoveStudent(r.studentId)}>
<PermissionButton permission="class:edit" size="small" danger>
</PermissionButton>
</Popconfirm>
) : null,
},
];
const teacherColumns: ColumnsType<ClassTeacher> = [
{ title: '姓名', dataIndex: 'username' },
{ title: '姓名', render: (_: unknown, teacher) => getTeacherName(teacher) },
{
title: '角色',
dataIndex: 'roleType',
@@ -340,7 +387,9 @@ const ClassDetailPage: React.FC = () => {
title: '操作',
render: (_: unknown, r: ClassTeacher) => (
<Popconfirm title="确认移除?" onConfirm={() => handleRemoveTeacher(r.userId)}>
<PermissionButton permission="class:edit" size="small" danger></PermissionButton>
<PermissionButton permission="class:edit" size="small" danger>
</PermissionButton>
</Popconfirm>
),
},
@@ -349,14 +398,27 @@ const ClassDetailPage: React.FC = () => {
const scheduleColumns: ColumnsType<ClassScheduleItem> = [
{ title: '教室', dataIndex: 'classroomName', render: (v: string | null) => v || '-' },
{ title: '星期', dataIndex: 'weekDay', render: (v: number) => WEEK_DAY_MAP[v] || v },
{ title: '时间', render: (_: unknown, r: ClassScheduleItem) => `${r.startTime} - ${r.endTime}` },
{ title: '日期范围', render: (_: unknown, r: ClassScheduleItem) => `${r.startDate} ~ ${r.endDate}` },
{
title: '时间',
render: (_: unknown, r: ClassScheduleItem) => `${r.startTime} - ${r.endTime}`,
},
{
title: '签到窗口',
render: (_: unknown, r: ClassScheduleItem) =>
`课前 ${r.attendanceAdvanceMinutes ?? 30} 分钟至下课`,
},
{
title: '日期范围',
render: (_: unknown, r: ClassScheduleItem) => `${r.startDate} ~ ${r.endDate}`,
},
{ title: '科目', dataIndex: 'subject' },
{ title: '类型', dataIndex: 'scheduleType', render: (v: string) => SCHEDULE_TYPE_MAP[v] || v },
{
title: '状态',
dataIndex: 'status',
render: (v: string) => <Tag color={v === 'active' ? 'green' : 'default'}>{v === 'active' ? '启用' : v}</Tag>,
render: (v: string) => (
<Tag color={v === 'active' ? 'green' : 'default'}>{v === 'active' ? '启用' : v}</Tag>
),
},
];
@@ -365,7 +427,9 @@ const ClassDetailPage: React.FC = () => {
title={
<Space>
<Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/classes')} />
<span>{detail.name} ({detail.code})</span>
<span>
{detail.name} ({detail.code})
</span>
<Tag color={STATUS_MAP[detail.status]?.color}>{STATUS_MAP[detail.status]?.text}</Tag>
</Space>
}
@@ -431,7 +495,11 @@ const ClassDetailPage: React.FC = () => {
<Input.TextArea rows={3} />
</Form.Item>
<Space>
<PermissionButton permission="class:edit" type="primary" onClick={handleSaveInfo}>
<PermissionButton
permission="class:edit"
type="primary"
onClick={handleSaveInfo}
>
</PermissionButton>
<Button onClick={() => setEditingInfo(false)}></Button>
@@ -453,11 +521,14 @@ const ClassDetailPage: React.FC = () => {
{detail.studentCount}/{detail.maxStudents || '-'}
</Descriptions.Item>
<Descriptions.Item label="班主任">
{teachers.find((t) => t.roleType === 'head_teacher')?.username || '-'}
</Descriptions.Item>
<Descriptions.Item label="备注">
{detail.notes || '-'}
{(() => {
const headTeacher = teachers.find(
(teacher) => teacher.roleType === 'head_teacher',
);
return headTeacher ? getTeacherName(headTeacher) : '-';
})()}
</Descriptions.Item>
<Descriptions.Item label="备注">{detail.notes || '-'}</Descriptions.Item>
</Descriptions>
<PermissionButton
permission="class:edit"
@@ -527,7 +598,11 @@ const ClassDetailPage: React.FC = () => {
columns={studentColumns}
dataSource={students}
rowKey="id"
pagination={{ pageSize: 20 }}
pagination={{
defaultPageSize: 20,
showSizeChanger: true,
pageSizeOptions: [20, 50, 100],
}}
/>
<Modal
title="添加学员"
@@ -571,7 +646,11 @@ const ClassDetailPage: React.FC = () => {
columns={teacherColumns}
dataSource={teachers}
rowKey="id"
pagination={{ pageSize: 20 }}
pagination={{
defaultPageSize: 20,
showSizeChanger: true,
pageSizeOptions: [20, 50, 100],
}}
/>
<Modal
title="添加教师"
@@ -582,16 +661,13 @@ const ClassDetailPage: React.FC = () => {
<Space direction="vertical" style={{ width: '100%' }}>
<Select
style={{ width: '100%' }}
placeholder="选择教师"
showSearch
optionFilterProp="label"
placeholder="搜索姓名、用户名、角色或学科"
value={teacherUserId}
onChange={setTeacherUserId}
options={allUsers.map((u) => ({
value: u.id,
label: u.username,
}))}
filterOption={(input, option) =>
(option?.label as string)?.toLowerCase().includes(input.toLowerCase())
}
options={buildTeacherCandidateOptions(allUsers)}
notFoundContent="没有可分配的工作人员账号"
/>
<Select
style={{ width: '100%' }}
@@ -619,10 +695,12 @@ const ClassDetailPage: React.FC = () => {
label: '课表',
children: (
<div>
<Space style={{ marginBottom: 16 }}>
<Space style={{ marginBottom: 16, maxWidth: '100%' }} wrap>
<DatePicker.RangePicker
value={scheduleDateRange}
onChange={(dates) => setScheduleDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])}
onChange={(dates) =>
setScheduleDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])
}
placeholder={['开始日期', '结束日期']}
/>
</Space>
@@ -630,7 +708,12 @@ const ClassDetailPage: React.FC = () => {
columns={scheduleColumns}
dataSource={schedules}
rowKey="id"
pagination={{ pageSize: 20 }}
scroll={{ x: 'max-content' }}
pagination={{
defaultPageSize: 20,
showSizeChanger: true,
pageSizeOptions: [20, 50, 100],
}}
/>
</div>
),
@@ -640,31 +723,37 @@ const ClassDetailPage: React.FC = () => {
label: '出勤汇总',
children: (
<div>
<Space style={{ marginBottom: 16 }}>
<Space style={{ marginBottom: 16, maxWidth: '100%' }} wrap>
<DatePicker.RangePicker
value={attendanceDateRange}
onChange={(dates) => setAttendanceDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])}
onChange={(dates) =>
setAttendanceDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])
}
placeholder={['开始日期', '结束日期']}
/>
</Space>
{attendanceSummary && (
<Row gutter={16}>
<Col span={6}>
<Row gutter={[16, 16]}>
<Col xs={12} md={6}>
<Card bordered={false}>
<Statistic title="总记录" value={attendanceSummary.total} />
</Card>
</Col>
<Col span={6}>
<Col xs={12} md={6}>
<Card bordered={false}>
<Statistic title="出勤率" value={attendanceSummary.presentRate} suffix="%" />
<Statistic
title="出勤率"
value={attendanceSummary.presentRate}
suffix="%"
/>
</Card>
</Col>
<Col span={6}>
<Col xs={12} md={6}>
<Card bordered={false}>
<Statistic title="缺勤率" value={attendanceSummary.absentRate} suffix="%" />
</Card>
</Col>
<Col span={6}>
<Col xs={12} md={6}>
<Card bordered={false}>
<Statistic title="迟到率" value={attendanceSummary.lateRate} suffix="%" />
</Card>

View File

@@ -1,7 +1,19 @@
import React, { useEffect, useState, useMemo, useCallback } from 'react';
import {
Table, Button, Input, Select, Space, Tag, Modal, Form, InputNumber,
DatePicker, Popconfirm, Card, Switch, Empty,
Table,
Button,
Input,
Select,
Space,
Tag,
Modal,
Form,
InputNumber,
DatePicker,
Popconfirm,
Card,
Switch,
Empty,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { PlusOutlined, SearchOutlined, TeamOutlined, InboxOutlined } from '@ant-design/icons';
@@ -9,6 +21,7 @@ import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell';
import { message } from '../../ui/app-message';
// ---- Types ----
@@ -96,13 +109,14 @@ const ClassesPage: React.FC = () => {
setData(res);
} catch (e: any) {
message.error(e?.message || '加载失败,请稍后重试');
}
finally {
} finally {
setLoading(false);
}
}, [filterStatus, filterType, showArchived]);
useEffect(() => { fetchData(); }, [fetchData]);
useEffect(() => {
fetchData();
}, [fetchData]);
const filtered = useMemo(() => {
if (!searchText) return data;
@@ -154,73 +168,165 @@ const ClassesPage: React.FC = () => {
}
};
const handleDelete = async (id: number) => {
try {
await api.delete(`/classes/${id}`);
message.success('已删除');
fetchData();
} catch (e: any) {
message.error(e?.message || '删除失败');
}
};
const saveCell = useCallback(
async (record: ClassItem, field: string, value: unknown) => {
await api.put(`/classes/${record.id}`, { [field]: value });
message.success('已保存');
await fetchData();
},
[fetchData],
);
const columns: ColumnsType<ClassItem> = useMemo(() => [
{
title: '班级名称', dataIndex: 'name', width: 120,
sorter: (a, b) => a.name.localeCompare(b.name),
},
{ title: '编码', dataIndex: 'code', width: 140 },
{
title: '班型', dataIndex: 'classType', width: 100,
render: (v: string) => <Tag>{TYPE_MAP[v] || v}</Tag>,
},
{
title: '开班日期', dataIndex: 'startDate', width: 110,
render: (v: string | null) => v || '-',
},
{
title: '学员', width: 100,
render: (_: unknown, r: ClassItem) => `${r.studentCount || 0}/${r.maxStudents || '-'}`,
},
{
title: '状态', dataIndex: 'status', width: 100,
render: (v: string) => {
const cfg = STATUS_MAP[v] || { color: 'default', text: v };
return <Tag color={cfg.color}>{cfg.text}</Tag>;
const columns: ColumnsType<ClassItem> = useMemo(
() => [
{
title: '班级名称',
dataIndex: 'name',
width: 120,
sorter: (a, b) => a.name.localeCompare(b.name),
render: (v: string, r: ClassItem) => (
<EditableCell
value={v}
required
permission="class:edit"
disabled={r.isArchived}
onSave={(next) => saveCell(r, 'name', next)}
>
{v}
</EditableCell>
),
},
},
{
title: '操作', width: 280,
render: (_: unknown, r: ClassItem) => (
<Space>
<Button size="small" icon={<TeamOutlined />} onClick={() => navigate(`/classes/${r.id}`)}>
</Button>
<PermissionButton permission="class:edit" size="small" onClick={() => handleEdit(r)}>
</PermissionButton>
{r.isArchived ? (
<Popconfirm title="确认恢复?" onConfirm={() => handleArchive(r.id, false)}>
<PermissionButton permission="class:edit" size="small"></PermissionButton>
</Popconfirm>
) : (
<Popconfirm title="归档后可恢复,确认归档?" onConfirm={() => handleArchive(r.id, true)}>
<PermissionButton permission="class:edit" size="small"></PermissionButton>
</Popconfirm>
)}
<Popconfirm title="确认删除?" onConfirm={() => handleDelete(r.id)}>
<PermissionButton permission="class:delete" size="small" danger>
{
title: '编码',
dataIndex: 'code',
width: 140,
render: (v: string, r: ClassItem) => (
<EditableCell
value={v}
required
permission="class:edit"
disabled={r.isArchived}
onSave={(next) => saveCell(r, 'code', next)}
>
{v}
</EditableCell>
),
},
{
title: '班型',
dataIndex: 'classType',
width: 100,
render: (v: string, r: ClassItem) => (
<EditableCell
value={v}
editor="select"
options={Object.entries(TYPE_MAP).map(([value, label]) => ({ value, label }))}
permission="class:edit"
disabled={r.isArchived}
onSave={(next) => saveCell(r, 'classType', next)}
>
<Tag>{TYPE_MAP[v] || v}</Tag>
</EditableCell>
),
},
{
title: '开班日期',
dataIndex: 'startDate',
width: 110,
render: (v: string | null, r: ClassItem) => (
<EditableCell
value={v}
editor="date"
permission="class:edit"
disabled={r.isArchived}
onSave={(next) => saveCell(r, 'startDate', next)}
>
{v || '-'}
</EditableCell>
),
},
{
title: '学员',
width: 100,
render: (_: unknown, r: ClassItem) => (
<EditableCell
value={r.maxStudents}
editor="number"
min={0}
permission="class:edit"
disabled={r.isArchived}
onSave={(next) => saveCell(r, 'maxStudents', next)}
>{`${r.studentCount || 0}/${r.maxStudents || '-'}`}</EditableCell>
),
},
{
title: '状态',
dataIndex: 'status',
width: 100,
render: (v: string, r: ClassItem) => (
<EditableCell
value={v}
editor="select"
options={Object.entries(STATUS_MAP).map(([value, item]) => ({
value,
label: item.text,
}))}
permission="class:edit"
disabled={r.isArchived}
onSave={(next) => saveCell(r, 'status', next)}
>
{(() => {
const cfg = STATUS_MAP[v] || { color: 'default', text: v };
return <Tag color={cfg.color}>{cfg.text}</Tag>;
})()}
</EditableCell>
),
},
{
title: '操作',
width: 280,
render: (_: unknown, r: ClassItem) => (
<Space>
<Button
size="small"
icon={<TeamOutlined />}
onClick={() => navigate(`/classes/${r.id}`)}
>
</Button>
<PermissionButton permission="class:edit" size="small" onClick={() => handleEdit(r)}>
</PermissionButton>
</Popconfirm>
</Space>
),
},
], []);
{r.isArchived ? (
<Popconfirm title="确认恢复?" onConfirm={() => handleArchive(r.id, false)}>
<PermissionButton permission="class:edit" size="small">
</PermissionButton>
</Popconfirm>
) : (
<Popconfirm
title="归档后可恢复,确认归档?"
onConfirm={() => handleArchive(r.id, true)}
>
<PermissionButton permission="class:edit" size="small">
</PermissionButton>
</Popconfirm>
)}
</Space>
),
},
],
[saveCell],
);
return (
<Card>
<Space style={{ marginBottom: 16 }} wrap>
<Space
style={{ marginBottom: 16 }}
wrap
className="responsive-toolbar responsive-toolbar--single"
>
<Input
placeholder="搜索名称/编码"
prefix={<SearchOutlined />}
@@ -244,7 +350,12 @@ const ClassesPage: React.FC = () => {
onChange={setFilterStatus}
options={Object.entries(STATUS_MAP).map(([k, v]) => ({ value: k, label: v.text }))}
/>
<PermissionButton permission="class:create" type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
<PermissionButton
permission="class:create"
type="primary"
icon={<PlusOutlined />}
onClick={handleCreate}
>
</PermissionButton>
<span style={{ marginLeft: 8 }}>
@@ -264,7 +375,11 @@ const ClassesPage: React.FC = () => {
rowKey="id"
loading={loading}
locale={{ emptyText: <Empty description="暂无数据" /> }}
pagination={{ pageSize: 20 }}
pagination={{
defaultPageSize: 20,
showSizeChanger: true,
pageSizeOptions: [20, 50, 100],
}}
scroll={{ x: 1100 }}
/>
@@ -298,7 +413,9 @@ const ClassesPage: React.FC = () => {
</Form.Item>
</Space>
<Form.Item name="status" label="状态" initialValue="enrolling">
<Select options={Object.entries(STATUS_MAP).map(([k, v]) => ({ value: k, label: v.text }))} />
<Select
options={Object.entries(STATUS_MAP).map(([k, v]) => ({ value: k, label: v.text }))}
/>
</Form.Item>
<Form.Item name="notes" label="备注">
<Input.TextArea rows={3} />

View File

@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest';
import {
buildTeacherCandidateLabel,
buildTeacherCandidateOptions,
isTeacherCandidate,
type TeacherCandidateUser,
} from './teacher-candidate';
const baseUser = (overrides: Partial<TeacherCandidateUser> = {}): TeacherCandidateUser => ({
id: 1,
username: 'teacher',
name: '测试老师',
isArchived: false,
studentStatus: null,
roles: [{ code: 'teacher', name: '任课老师' }],
profile: { subjects: ['数学', '物理'] },
...overrides,
});
describe('class teacher candidates', () => {
it('keeps non-teacher staff roles because class duty is selected separately', () => {
expect(
isTeacherCandidate(baseUser({ roles: [{ code: 'academic', name: '教务管理员' }] })),
).toBe(true);
});
it('keeps staff-linked accounts so they can serve as head or life teachers', () => {
expect(isTeacherCandidate(baseUser({ studentStatus: 'staff' }))).toBe(true);
});
it('excludes active students, archived, and super-admin accounts', () => {
const users = [
baseUser({ id: 1, studentStatus: 'active' }),
baseUser({ id: 2, isArchived: true }),
baseUser({
id: 3,
roles: [{ code: 'super_admin', name: '超级管理员' }],
}),
];
expect(buildTeacherCandidateOptions(users)).toEqual([]);
});
it('shows real name, username, system role, and teaching subjects', () => {
expect(buildTeacherCandidateLabel(baseUser())).toBe(
'测试老师teacher · 任课老师 · 数学/物理',
);
});
});

View File

@@ -0,0 +1,43 @@
export interface TeacherCandidateRole {
code?: string | null;
name: string;
}
export interface TeacherCandidateUser {
id: number;
username: string;
name?: string | null;
isArchived: boolean;
studentStatus?: string | null;
roles?: TeacherCandidateRole[];
profile?: { subjects?: string[] } | null;
}
const isSuperAdminRole = (role: TeacherCandidateRole) =>
role.code === 'super_admin' || role.name === '超级管理员' || role.name === '超管';
export const isTeacherCandidate = (user: TeacherCandidateUser) => {
if (user.isArchived) return false;
if (user.studentStatus && user.studentStatus !== 'staff') return false;
return !(user.roles || []).some(isSuperAdminRole);
};
export const buildTeacherCandidateLabel = (user: TeacherCandidateUser) => {
const displayName = user.name?.trim();
const identity =
displayName && displayName !== user.username
? `${displayName}${user.username}`
: user.username;
const roleNames = [...new Set((user.roles || []).map((role) => role.name).filter(Boolean))];
const subjects = [
...new Set((user.profile?.subjects || []).map((subject) => subject.trim()).filter(Boolean)),
];
return [identity, roleNames.join('/'), subjects.join('/')].filter(Boolean).join(' · ');
};
export const buildTeacherCandidateOptions = (users: TeacherCandidateUser[]) =>
users.filter(isTeacherCandidate).map((user) => ({
value: user.id,
label: buildTeacherCandidateLabel(user),
}));

View File

@@ -15,11 +15,18 @@ import {
Tooltip,
Empty,
} from 'antd';
import { PlusOutlined, UploadOutlined, DeleteOutlined, FileTextOutlined } from '@ant-design/icons';
import {
PlusOutlined,
UploadOutlined,
FileTextOutlined,
StopOutlined,
CheckOutlined,
} from '@ant-design/icons';
import dayjs, { Dayjs } from 'dayjs';
import api from '../../api';
import { downloadBlob } from '../../utils/download';
import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell';
import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
@@ -30,7 +37,7 @@ export const unavailableDatesCacheKey = (classroomId: number, date: Dayjs) =>
`${classroomId}:${date.format('YYYY-MM')}`;
const ClassroomRentalsPage: React.FC = () => {
const { hasAnyPermission } = usePermission();
const { hasPermission, hasAnyPermission } = usePermission();
const [data, setData] = useState<any[]>([]);
const [classrooms, setClassrooms] = useState<any[]>([]);
const [organizations, setOrganizations] = useState<any[]>([]);
@@ -39,6 +46,7 @@ const ClassroomRentalsPage: React.FC = () => {
const [editing, setEditing] = useState<any>(null);
const [form] = Form.useForm();
const [filterMonth, setFilterMonth] = useState<Dayjs | null>(null);
const [filterStatus, setFilterStatus] = useState<string | undefined>();
const [searchText, setSearchText] = useState('');
const [saving, setSaving] = useState(false);
const [unavailableDates, setUnavailableDates] = useState<Set<string>>(new Set());
@@ -48,20 +56,22 @@ const ClassroomRentalsPage: React.FC = () => {
const selectedClassroomId = Form.useWatch('classroomId', form);
const filteredData = useMemo(() => {
if (!searchText) return data;
const s = searchText.toLowerCase();
return data.filter((r: any) => {
if (filterStatus && r.effectiveStatus !== filterStatus) return false;
if (!searchText) return true;
const s = searchText.toLowerCase();
const matchClassroom = r.classroom?.name?.toLowerCase().includes(s);
const matchOrganization = r.lesseeOrganization?.name?.toLowerCase().includes(s);
return matchClassroom || matchOrganization;
});
}, [data, searchText]);
}, [data, searchText, filterStatus]);
const fetchData = async () => {
setLoading(true);
try {
const params: any = {};
if (filterMonth) params.month = filterMonth.format('YYYY-MM');
params.includeEnded = true;
const res: any = await api.get('/classroom-rentals', { params });
setData(res);
} catch (e: any) {
@@ -205,13 +215,29 @@ const ClassroomRentalsPage: React.FC = () => {
}
};
const saveCell = async (record: any, field: string, value: unknown) => {
await api.put(`/classroom-rentals/${record.id}`, { [field]: value });
message.success('已保存');
await fetchData();
};
const handleDelete = async (id: number) => {
try {
await api.delete(`/classroom-rentals/${id}`);
message.success('已删除');
message.success('已归档');
fetchData();
} catch (e: any) {
message.error(e?.message || '删除失败');
message.error(e?.message || '归档失败');
}
};
const handleRentalAction = async (id: number, action: 'cancel' | 'end') => {
try {
await api.put(`/classroom-rentals/${id}/${action}`);
message.success(action === 'cancel' ? '租赁已取消' : '租赁已结束');
fetchData();
} catch (e: any) {
message.error(e?.message || '操作失败');
}
};
@@ -226,10 +252,10 @@ const ClassroomRentalsPage: React.FC = () => {
const handleDeleteContract = async (id: number) => {
try {
await api.delete(`/classroom-rentals/${id}/contract`);
message.success('合同已除');
message.success('合同已除');
fetchData();
} catch (e: any) {
message.error(e?.message || '除失败');
message.error(e?.message || '除失败');
}
};
@@ -260,34 +286,95 @@ const ClassroomRentalsPage: React.FC = () => {
title: '教室',
width: 120,
dataIndex: 'classroom',
render: (c: any) =>
c ? (
<span>
{c.building ? `${c.building} · ` : ''}
{c.name}
</span>
) : (
'-'
),
render: (c: any, r: any) => (
<EditableCell
value={r.classroomId}
editor="select"
options={classrooms
.filter((item) => item.status !== 'archived')
.map((item) => ({
value: item.id,
label: item.building ? `${item.building} · ${item.name}` : item.name,
}))}
permission="rental:edit"
disabled={r.effectiveStatus !== 'active'}
required
onSave={(next) => saveCell(r, 'classroomId', next)}
>
{c ? (
<span>
{c.building ? `${c.building} · ` : ''}
{c.name}
</span>
) : (
'-'
)}
</EditableCell>
),
},
{
title: '承租机构',
width: 100,
dataIndex: 'lesseeOrganization',
render: (t: any) =>
t ? (
<Tag
color={t.color}
style={{ background: t.color, color: '#fff', borderColor: t.color }}
>
{t.name}
</Tag>
) : (
'-'
),
render: (t: any, r: any) => (
<EditableCell
value={r.lesseeOrganizationId}
editor="select"
options={organizations
.filter((item) => item.status !== 'archived')
.map((item) => ({ value: item.id, label: item.name }))}
permission="rental:edit"
disabled={r.effectiveStatus !== 'active'}
required
onSave={(next) => saveCell(r, 'lesseeOrganizationId', next)}
>
{t ? (
<Tag
color={t.color}
style={{ background: t.color, color: '#fff', borderColor: t.color }}
>
{t.name}
</Tag>
) : (
'-'
)}
</EditableCell>
),
},
{
title: '开始日期',
dataIndex: 'startDate',
width: 110,
render: (v: string, r: any) => (
<EditableCell
value={v}
editor="date"
permission="rental:edit"
disabled={r.effectiveStatus !== 'active'}
required
onSave={(next) => saveCell(r, 'startDate', next)}
>
{v}
</EditableCell>
),
},
{
title: '结束日期',
dataIndex: 'endDate',
width: 110,
render: (v: string, r: any) => (
<EditableCell
value={v}
editor="date"
permission="rental:edit"
disabled={r.effectiveStatus !== 'active'}
required
onSave={(next) => saveCell(r, 'endDate', next)}
>
{v}
</EditableCell>
),
},
{ title: '开始日期', dataIndex: 'startDate', width: 110 },
{ title: '结束日期', dataIndex: 'endDate', width: 110 },
{
title: '时长',
width: 80,
@@ -300,13 +387,48 @@ const ClassroomRentalsPage: React.FC = () => {
title: '日租金',
dataIndex: 'dailyRate',
width: 100,
render: (v: any) => (v ? `¥${v}` : '-'),
render: (v: any, r: any) => (
<EditableCell
value={v}
editor="money"
min={0.01}
permission="rental:edit"
disabled={r.effectiveStatus !== 'active'}
onSave={(next) => saveCell(r, 'dailyRate', next)}
>
{v ? `¥${v}` : '-'}
</EditableCell>
),
},
{
title: '总额',
dataIndex: 'totalAmount',
width: 100,
render: (v: any) => (v ? `¥${v}` : '-'),
render: (v: any, r: any) => (
<EditableCell
value={v}
editor="money"
min={0.01}
permission="rental:edit"
disabled={r.effectiveStatus !== 'active'}
onSave={(next) => saveCell(r, 'totalAmount', next)}
>
{v ? `¥${v}` : '-'}
</EditableCell>
),
},
{
title: '状态',
dataIndex: 'effectiveStatus',
width: 90,
render: (status: string) => {
const config: Record<string, { text: string; color: string }> = {
active: { text: '进行中', color: 'green' },
ended: { text: '已结束', color: 'default' },
cancelled: { text: '已取消', color: 'red' },
};
return <Tag color={config[status]?.color}>{config[status]?.text || status}</Tag>;
},
},
{
title: '合同',
@@ -324,11 +446,13 @@ const ClassroomRentalsPage: React.FC = () => {
</Button>
</Tooltip>
<Popconfirm title="删除合同文件?" onConfirm={() => handleDeleteContract(r.id)}>
<Button size="small" danger icon={<DeleteOutlined />} aria-label="删除合同文件" />
</Popconfirm>
{hasPermission('rental:edit') ? (
<Popconfirm title="移除合同文件?" onConfirm={() => handleDeleteContract(r.id)}>
<Button size="small" danger icon={<StopOutlined />} aria-label="移除合同文件" />
</Popconfirm>
) : null}
</Space>
) : (
) : hasPermission('rental:edit') ? (
<Upload
accept="application/pdf"
showUploadList={false}
@@ -357,6 +481,8 @@ const ClassroomRentalsPage: React.FC = () => {
PDF
</Button>
</Upload>
) : (
'-'
),
},
{
@@ -364,26 +490,59 @@ const ClassroomRentalsPage: React.FC = () => {
width: 150,
render: (_: any, record: any) => (
<Space>
<PermissionButton
permission="rental:edit"
size="small"
onClick={() => openEdit(record)}
>
</PermissionButton>
<Popconfirm
title="确定删除该租赁订单?合同文件将一并删除。"
onConfirm={() => handleDelete(record.id)}
>
<PermissionButton permission="rental:delete" size="small" danger>
</PermissionButton>
</Popconfirm>
{record.effectiveStatus === 'active' && (
<>
<PermissionButton
permission="rental:edit"
size="small"
onClick={() => openEdit(record)}
>
</PermissionButton>
<Popconfirm
title="确定取消该租赁?"
onConfirm={() => handleRentalAction(record.id, 'cancel')}
>
<PermissionButton
permission="rental:edit"
size="small"
danger
icon={<StopOutlined />}
>
</PermissionButton>
</Popconfirm>
{!dayjs(record.startDate).isAfter(dayjs(), 'day') && (
<Popconfirm
title="确定今天结束该租赁?"
onConfirm={() => handleRentalAction(record.id, 'end')}
>
<PermissionButton
permission="rental:edit"
size="small"
icon={<CheckOutlined />}
>
</PermissionButton>
</Popconfirm>
)}
</>
)}
{record.effectiveStatus !== 'active' && (
<Popconfirm
title="确定归档该租赁订单?合同文件会保留。"
onConfirm={() => handleDelete(record.id)}
>
<PermissionButton permission="rental:delete" size="small" danger>
</PermissionButton>
</Popconfirm>
)}
</Space>
),
},
],
[],
[classrooms, organizations, hasPermission],
);
return (
@@ -415,6 +574,18 @@ const ClassroomRentalsPage: React.FC = () => {
allowClear
format="YYYY-MM"
/>
<Select
placeholder="状态"
allowClear
style={{ width: 110 }}
value={filterStatus}
onChange={setFilterStatus}
options={[
{ value: 'active', label: '进行中' },
{ value: 'ended', label: '已结束' },
{ value: 'cancelled', label: '已取消' },
]}
/>
</Space>
<PermissionButton
permission="rental:create"
@@ -436,7 +607,12 @@ const ClassroomRentalsPage: React.FC = () => {
rowKey="id"
loading={loading}
locale={{ emptyText: <Empty description="暂无数据" /> }}
pagination={{ pageSize: 15, showTotal: (total) => `${total}` }}
pagination={{
defaultPageSize: 15,
showSizeChanger: true,
pageSizeOptions: [15, 30, 50, 100],
showTotal: (total) => `${total}`,
}}
scroll={{ x: 1200 }}
/>
<Modal
@@ -459,10 +635,12 @@ const ClassroomRentalsPage: React.FC = () => {
optionFilterProp="label"
placeholder="选择教室"
onChange={handleClassroomChange}
options={classrooms.map((c) => ({
value: c.id,
label: `${c.building ? c.building + ' · ' : ''}${c.name}${c.roomType}`,
}))}
options={classrooms
.filter((c) => c.status === 'available')
.map((c) => ({
value: c.id,
label: `${c.building ? c.building + ' · ' : ''}${c.name}${c.roomType}`,
}))}
/>
</Form.Item>
<Form.Item name="lessorOrganizationId" label="出租机构" tooltip="默认由本机构出租">
@@ -507,10 +685,10 @@ const ClassroomRentalsPage: React.FC = () => {
/>
</Form.Item>
<Form.Item name="dailyRate" label="日租金(可选)">
<InputNumber min={0} precision={2} style={{ width: '100%' }} prefix="¥" />
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} prefix="¥" />
</Form.Item>
<Form.Item name="totalAmount" label="合同总额(可选)">
<InputNumber min={0} precision={2} style={{ width: '100%' }} prefix="¥" />
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} prefix="¥" />
</Form.Item>
<Form.Item name="notes" label="备注">
<Input.TextArea rows={2} />

View File

@@ -1,16 +0,0 @@
import { describe, expect, it } from 'vitest';
import { CLASSROOM_VISIBLE_FIELDS } from './classroom-fields';
describe('classroom visible fields', () => {
it('excludes obsolete course and supervisor metadata', () => {
expect(CLASSROOM_VISIBLE_FIELDS).toEqual([
'name',
'building',
'floor',
'roomType',
'capacity',
'status',
'notes',
]);
});
});

View File

@@ -1,9 +0,0 @@
export const CLASSROOM_VISIBLE_FIELDS = [
'name',
'building',
'floor',
'roomType',
'capacity',
'status',
'notes',
] as const;

View File

@@ -23,7 +23,9 @@ import {
} from '@ant-design/icons';
import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell';
import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
const statusMap: Record<string, { text: string; color: string }> = {
available: { text: '可用', color: 'green' },
@@ -47,6 +49,7 @@ const typeColor: Record<string, string> = {
};
const ClassroomsPage: React.FC = () => {
const { hasPermission } = usePermission();
const [data, setData] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
@@ -60,8 +63,16 @@ const ClassroomsPage: React.FC = () => {
const filteredData = useMemo(() => {
let result = data;
if (searchText) { const s = searchText.toLowerCase(); result = result.filter((d: Record<string, unknown>) => (typeof d.name === 'string' && d.name.toLowerCase().includes(s)) || (typeof d.building === 'string' && d.building.toLowerCase().includes(s))); }
if (filterStatus) result = result.filter((d: Record<string, unknown>) => d.status === filterStatus);
if (searchText) {
const s = searchText.toLowerCase();
result = result.filter(
(d: Record<string, unknown>) =>
(typeof d.name === 'string' && d.name.toLowerCase().includes(s)) ||
(typeof d.building === 'string' && d.building.toLowerCase().includes(s)),
);
}
if (filterStatus)
result = result.filter((d: Record<string, unknown>) => d.effectiveStatus === filterStatus);
return result;
}, [data, searchText, filterStatus]);
@@ -102,6 +113,12 @@ const ClassroomsPage: React.FC = () => {
}
};
const saveCell = async (record: any, field: string, value: unknown) => {
await api.put(`/classrooms/${record.id}`, { [field]: value });
message.success('已保存');
await fetchData();
};
const handleArchive = async (id: number) => {
try {
await api.delete(`/classrooms/${id}`);
@@ -140,72 +157,177 @@ const ClassroomsPage: React.FC = () => {
.catch(() => message.error('下载失败'));
};
const columns = useMemo(() => [
{
title: '教室名', width: 120,
dataIndex: 'name',
sorter: (a: any, b: any) => a.name.localeCompare(b.name),
},
{ title: '楼栋', dataIndex: 'building', width: 80 },
{ title: '楼层', dataIndex: 'floor', width: 80 },
{
title: '类型', width: 90,
dataIndex: 'roomType',
render: (v: string) => <Tag color={typeColor[v] || 'default'}>{v || '-'}</Tag>,
},
{ title: '容量', dataIndex: 'capacity', width: 80 },
{
title: '状态', width: 100,
dataIndex: 'status',
render: (s: string, record: { currentUsage?: CurrentUsage | null }) => {
const effectiveStatus = record.currentUsage ? 'in_use' : s;
return (
<Tooltip title={record.currentUsage ? `${record.currentUsage.title} (${record.currentUsage.startTime}-${record.currentUsage.endTime})` : undefined}>
<Tag color={statusMap[effectiveStatus]?.color}>{statusMap[effectiveStatus]?.text || s}</Tag>
</Tooltip>
);
const columns = useMemo(
() => [
{
title: '教室名',
width: 120,
dataIndex: 'name',
sorter: (a: any, b: any) => a.name.localeCompare(b.name),
render: (v: string, r: any) => (
<EditableCell
value={v}
required
permission="classroom:edit"
disabled={r.status === 'archived'}
onSave={(next) => saveCell(r, 'name', next)}
>
{v}
</EditableCell>
),
},
},
{
title: '操作',
width: 180,
render: (_: any, record: any) => (
<Space>
{record.status === 'archived' ? (
<Popconfirm title="确定恢复此教室?" onConfirm={() => handleRestore(record.id)}>
<PermissionButton permission="classroom:edit" size="small" icon={<UndoOutlined />} type="link">
</PermissionButton>
</Popconfirm>
) : (
<>
<PermissionButton
permission="classroom:edit"
size="small"
onClick={() => {
setEditing(record);
form.setFieldsValue(record);
setModalOpen(true);
}}
{
title: '楼栋',
dataIndex: 'building',
width: 80,
render: (v: string, r: any) => (
<EditableCell
value={v}
permission="classroom:edit"
disabled={r.status === 'archived'}
onSave={(next) => saveCell(r, 'building', next)}
>
{v || '-'}
</EditableCell>
),
},
{
title: '楼层',
dataIndex: 'floor',
width: 80,
render: (v: number, r: any) => (
<EditableCell
value={v}
editor="number"
permission="classroom:edit"
disabled={r.status === 'archived'}
onSave={(next) => saveCell(r, 'floor', next)}
>
{v ?? '-'}
</EditableCell>
),
},
{
title: '类型',
width: 90,
dataIndex: 'roomType',
render: (v: string, r: any) => (
<EditableCell
value={v}
editor="select"
options={['大', '次大', '小'].map((value) => ({ value, label: value }))}
permission="classroom:edit"
disabled={r.status === 'archived'}
onSave={(next) => saveCell(r, 'roomType', next)}
>
<Tag color={typeColor[v] || 'default'}>{v || '-'}</Tag>
</EditableCell>
),
},
{
title: '容量',
dataIndex: 'capacity',
width: 80,
render: (v: number, r: any) => (
<EditableCell
value={v}
editor="number"
min={0}
permission="classroom:edit"
disabled={r.status === 'archived'}
onSave={(next) => saveCell(r, 'capacity', next)}
>
{v ?? '-'}
</EditableCell>
),
},
{
title: '状态',
width: 100,
dataIndex: 'status',
render: (
_s: string,
record: { effectiveStatus?: string; status: string; currentUsage?: CurrentUsage | null },
) => {
const effectiveStatus = record.effectiveStatus || record.status;
return (
<EditableCell
value={record.status}
editor="select"
options={[
{ value: 'available', label: '可用' },
{ value: 'maintenance', label: '维护中' },
]}
permission="classroom:edit"
disabled={record.status === 'archived'}
onSave={(next) => saveCell(record, 'status', next)}
>
<Tooltip
title={
record.currentUsage
? `${record.currentUsage.title} (${record.currentUsage.startTime}-${record.currentUsage.endTime})`
: undefined
}
>
</PermissionButton>
<Popconfirm
title="归档后数据保留,可随时恢复。存在进行中的租赁将无法归档。"
onConfirm={() => handleArchive(record.id)}
okText="归档"
cancelText="取消"
>
<PermissionButton permission="classroom:delete" size="small" icon={<InboxOutlined />}>
<Tag color={statusMap[effectiveStatus]?.color}>
{statusMap[effectiveStatus]?.text || effectiveStatus}
</Tag>
</Tooltip>
</EditableCell>
);
},
},
{
title: '操作',
width: 180,
render: (_: any, record: any) => (
<Space>
{record.status === 'archived' ? (
<Popconfirm title="确定恢复此教室?" onConfirm={() => handleRestore(record.id)}>
<PermissionButton
permission="classroom:edit"
size="small"
icon={<UndoOutlined />}
type="link"
>
</PermissionButton>
</Popconfirm>
</>
)}
</Space>
),
},
], []);
) : (
<>
<PermissionButton
permission="classroom:edit"
size="small"
onClick={() => {
setEditing(record);
form.setFieldsValue(record);
setModalOpen(true);
}}
>
</PermissionButton>
<Popconfirm
title="归档后数据保留,可随时恢复。存在进行中的租赁将无法归档。"
onConfirm={() => handleArchive(record.id)}
okText="归档"
cancelText="取消"
>
<PermissionButton
permission="classroom:delete"
size="small"
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
</>
)}
</Space>
),
},
],
[],
);
return (
<div>
@@ -228,7 +350,20 @@ const ClassroomsPage: React.FC = () => {
if (!e.target.value) setSearchText('');
}}
/>
<Select placeholder="状态" allowClear style={{ width: 110 }} value={filterStatus} onChange={setFilterStatus} options={[{value:'available',label:'可用'},{value:'in_use',label:'使用中'},{value:'reserved',label:'已预留'},{value:'maintenance',label:'维护中'}]} />
<Select
placeholder="状态"
allowClear
style={{ width: 110 }}
value={filterStatus}
onChange={setFilterStatus}
options={[
{ value: 'available', label: '可用' },
{ value: 'in_use', label: '使用中' },
{ value: 'reserved', label: '已预留' },
{ value: 'maintenance', label: '维护中' },
{ value: 'archived', label: '已归档' },
]}
/>
<Button
type={showArchived ? 'primary' : 'default'}
onClick={() => setShowArchived(!showArchived)}
@@ -249,28 +384,49 @@ const ClassroomsPage: React.FC = () => {
>
</PermissionButton>
<PermissionButton permission="classroom:view" icon={<DownloadOutlined />} onClick={() => { const baseURL = '/api'; const token = localStorage.getItem('token'); fetch(`${baseURL}/classrooms/export`, { headers: { Authorization: `Bearer ${token}` } }).then(r => r.blob()).then(b => { const a = document.createElement('a'); a.href = URL.createObjectURL(b); a.download = '教室使用报表.xlsx'; a.click(); }); }}></PermissionButton>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }: any) => {
const formData = new FormData();
formData.append('file', file);
try {
const res: any = await api.post('/classrooms/import', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
<PermissionButton
permission="classroom:view"
icon={<DownloadOutlined />}
onClick={() => {
const baseURL = '/api';
const token = localStorage.getItem('token');
fetch(`${baseURL}/classrooms/export`, {
headers: { Authorization: `Bearer ${token}` },
})
.then((r) => r.blob())
.then((b) => {
const a = document.createElement('a');
a.href = URL.createObjectURL(b);
a.download = '教室使用报表.xlsx';
a.click();
});
message.success(res.message);
onSuccess?.(res);
fetchData();
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
}}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
</PermissionButton>
{hasPermission('classroom:create') ? (
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }: any) => {
const formData = new FormData();
formData.append('file', file);
try {
const res: any = await api.post('/classrooms/import', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
message.success(res.message);
onSuccess?.(res);
fetchData();
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
}}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
) : null}
<PermissionButton
permission="classroom:view"
icon={<DownloadOutlined />}
@@ -287,7 +443,12 @@ const ClassroomsPage: React.FC = () => {
rowKey="id"
loading={loading}
locale={{ emptyText: <Empty description="暂无数据" /> }}
pagination={{ pageSize: 20, showTotal: (total) => `${total}` }}
pagination={{
defaultPageSize: 20,
showSizeChanger: true,
pageSizeOptions: [20, 50, 100],
showTotal: (total) => `${total}`,
}}
/>
<Modal
title={editing ? '编辑教室' : '添加教室'}
@@ -323,6 +484,16 @@ const ClassroomsPage: React.FC = () => {
<Form.Item name="capacity" label="容量">
<InputNumber min={1} max={500} style={{ width: '100%' }} />
</Form.Item>
{editing && (
<Form.Item name="status" label="基础状态">
<Select
options={[
{ value: 'available', label: '可用' },
{ value: 'maintenance', label: '维护中' },
]}
/>
</Form.Item>
)}
<Form.Item name="notes" label="备注">
<Input.TextArea rows={2} />
</Form.Item>

View File

@@ -0,0 +1,41 @@
import { describe, expect, it } from 'vitest';
import { buildDepositStudentOption, buildDepositStudentOptions } from './deposit-student-option';
describe('deposit student option', () => {
it('uses the student number as the non-sensitive identifier', () => {
expect(buildDepositStudentOption({ id: 23, name: '张三', studentNo: 'S2026001' })).toEqual({
value: 23,
label: '张三 (S2026001)',
});
});
it('falls back to the internal id when the student number is missing', () => {
expect(buildDepositStudentOption({ id: 23, name: '张三', studentNo: null })).toEqual({
value: 23,
label: '张三 (#23)',
});
});
it('uses lookup rows without requiring a status field', () => {
expect(buildDepositStudentOptions([{ id: 23, name: '张三', studentNo: 'S2026001' }])).toEqual([
{
value: 23,
label: '张三 (S2026001)',
},
]);
});
it('includes room type when available', () => {
expect(
buildDepositStudentOption({
id: 23,
name: '张三',
studentNo: 'S2026001',
roomType: '四人间',
}),
).toEqual({
value: 23,
label: '张三 (S2026001) - 四人间',
});
});
});

View File

@@ -0,0 +1,14 @@
export interface DepositStudentLookup {
id: number;
name: string;
studentNo?: string | null;
roomType?: string | null;
}
export const buildDepositStudentOption = (student: DepositStudentLookup) => ({
value: student.id,
label: `${student.name} (${student.studentNo || `#${student.id}`})${student.roomType ? ` - ${student.roomType}` : ''}`,
});
export const buildDepositStudentOptions = (students: DepositStudentLookup[]) =>
students.map(buildDepositStudentOption);

View File

@@ -1,4 +1,4 @@
import React, { useEffect, useState, useMemo } from 'react';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
Table,
Modal,
@@ -10,29 +10,21 @@ import {
Space,
Tag,
Popconfirm,
List,
Card,
Empty,
} from 'antd';
import { PlusOutlined, DeleteOutlined, DollarOutlined } from '@ant-design/icons';
import { PlusOutlined, InboxOutlined, DollarOutlined, TeamOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import api from '../../api';
import { maskPhone, maskIdNumber } from '../../utils/sensitive';
import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell';
import { message } from '../../ui/app-message';
import { buildDepositStudentOptions, type DepositStudentLookup } from './deposit-student-option';
const statusMap: Record<string, { text: string; color: string }> = {
paid: { text: '已缴', color: 'green' },
paid: { text: '有余额', color: 'green' },
refunded: { text: '已全退', color: 'blue' },
partial_refund: { text: '部分退还', color: 'orange' },
deducted: { text: '已全扣', color: 'red' },
};
const refundStatusMap: Record<string, { text: string; color: string }> = {
pending: { text: '历史退款处理中', color: 'orange' },
head_teacher_approved: { text: '历史退款处理中', color: 'blue' },
finance_approved: { text: '已退款', color: 'green' },
refunded: { text: '已退款', color: 'green' },
depleted: { text: '已扣完', color: 'red' },
};
const installmentStatusMap: Record<string, { text: string; color: string }> = {
@@ -40,45 +32,152 @@ const installmentStatusMap: Record<string, { text: string; color: string }> = {
paid: { text: '已缴', color: 'green' },
};
const roomTypeOptions = [
{ value: '单人间', label: '单人间' },
{ value: '四人间', label: '四人间' },
];
const suggestedDepositByRoomType: Record<string, number> = {
单人间: 200,
四人间: 100,
};
interface DepositRecord {
id: number;
studentId: number;
amount: number;
status: string;
paidDate: string;
refundDate?: string | null;
notes?: string | null;
installments?: Array<{
id: number;
amount: number;
dueDate: string;
paidDate?: string | null;
status: string;
}>;
student?: DepositStudentLookup;
}
interface EligibleStudent {
studentId: number;
studentName: string;
studentNo?: string | null;
roomId: number;
roomNumber: string;
building?: string | null;
roomType?: string | null;
capacity: number;
depositAmount: number;
}
const isFormValidationError = (error: unknown) =>
typeof error === 'object' &&
error !== null &&
Array.isArray((error as { errorFields?: unknown }).errorFields);
const DepositsPage: React.FC = () => {
const [data, setData] = useState<any[]>([]);
const [students, setStudents] = useState<any[]>([]);
const [data, setData] = useState<DepositRecord[]>([]);
const [students, setStudents] = useState<DepositStudentLookup[]>([]);
const [eligibleStudents, setEligibleStudents] = useState<EligibleStudent[]>([]);
const [selectedEligibleStudentIds, setSelectedEligibleStudentIds] = useState<number[]>([]);
const [loading, setLoading] = useState(false);
const [eligibleLoading, setEligibleLoading] = useState(false);
const [createModal, setCreateModal] = useState(false);
const [refundModal, setRefundModal] = useState<any>(null);
const [detailModal, setDetailModal] = useState<any>(null);
const [batchModal, setBatchModal] = useState(false);
const [refundModal, setRefundModal] = useState<DepositRecord | null>(null);
const [detailModal, setDetailModal] = useState<DepositRecord | null>(null);
const [installmentModal, setInstallmentModal] = useState<number | null>(null);
const [createForm] = Form.useForm();
const [batchForm] = Form.useForm();
const [refundForm] = Form.useForm();
const [installmentForm] = Form.useForm();
const [searchText, setSearchText] = useState('');
const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
const [filterRoomType, setFilterRoomType] = useState<string | undefined>(undefined);
const [batchRoomType, setBatchRoomType] = useState<string>('四人间');
const [saving, setSaving] = useState(false);
const fetchData = async () => {
const fetchData = useCallback(async () => {
setLoading(true);
try {
const [d, s]: any[] = await Promise.all([
api.get('/deposits'),
api.get('/deposits/student-lookups'),
const [d, s] = await Promise.all([
api.get<DepositRecord[]>('/deposits'),
api.get<DepositStudentLookup[]>('/deposits/student-lookups'),
]);
setData(d);
setStudents(s);
} catch (e: any) {
message.error(e?.message || '加载失败,请稍后重试');
} finally {
setLoading(false);
}
setLoading(false);
};
}, []);
const fetchEligibleStudents = useCallback(async (roomType?: string) => {
setEligibleLoading(true);
try {
const params = roomType ? `?roomType=${encodeURIComponent(roomType)}` : '';
const rows = await api.get<EligibleStudent[]>(`/deposits/eligible-students${params}`);
setEligibleStudents(rows);
setSelectedEligibleStudentIds(rows.map((item) => item.studentId));
} catch (e: any) {
message.error(e?.message || '加载在住人员失败');
} finally {
setEligibleLoading(false);
}
}, []);
useEffect(() => {
fetchData();
}, []);
}, [fetchData]);
useEffect(() => {
fetchEligibleStudents(filterRoomType);
}, [fetchEligibleStudents, filterRoomType]);
const depositByStudentId = useMemo(() => {
const map = new Map<number, DepositRecord>();
data.forEach((item) => map.set(item.studentId, item));
return map;
}, [data]);
const filteredData = useMemo(() => {
return data.filter((d: any) => {
if (filterRoomType) {
const s = searchText.trim().toLowerCase();
return eligibleStudents
.filter(
(item) =>
!s ||
item.studentName.toLowerCase().includes(s) ||
item.studentNo?.toLowerCase().includes(s),
)
.map((item) => {
const deposit = depositByStudentId.get(item.studentId);
return {
id: deposit?.id ?? `eligible-${item.studentId}`,
studentId: item.studentId,
amount: deposit?.amount ?? item.depositAmount ?? 0,
status: deposit?.status ?? 'unpaid',
paidDate: deposit?.paidDate ?? '',
refundDate: deposit?.refundDate,
notes: deposit?.notes,
installments: deposit?.installments ?? [],
student: {
id: item.studentId,
name: item.studentName,
studentNo: item.studentNo,
roomType: item.roomType,
},
roomNumber: item.roomNumber,
building: item.building,
roomType: item.roomType,
};
});
}
return data.filter((d) => {
if (searchText) {
const s = searchText.toLowerCase();
if (!d.student?.name?.toLowerCase().includes(s)) return false;
@@ -86,56 +185,98 @@ const DepositsPage: React.FC = () => {
if (filterStatus && d.status !== filterStatus) return false;
return true;
});
}, [data, searchText, filterStatus]);
}, [data, depositByStudentId, eligibleStudents, filterRoomType, filterStatus, searchText]);
const studentOptions = useMemo(
() =>
students
.filter((s: any) => s.status === 'active')
.map((s: any) => ({
value: s.id,
label: `${s.name} (${s.idNumber ? maskIdNumber(s.idNumber) : (s.phone ? maskPhone(s.phone) : '')})`,
})),
[students],
);
const studentOptions = useMemo(() => buildDepositStudentOptions(students), [students]);
const openBatchModal = (roomType = filterRoomType || '四人间') => {
const amount = suggestedDepositByRoomType[roomType] ?? 100;
setBatchRoomType(roomType);
batchForm.resetFields();
batchForm.setFieldsValue({ roomType, amount, paidDate: dayjs() });
setBatchModal(true);
fetchEligibleStudents(roomType);
};
const handleBatchRoomTypeChange = (roomType: string) => {
setBatchRoomType(roomType);
batchForm.setFieldsValue({
amount: suggestedDepositByRoomType[roomType] ?? batchForm.getFieldValue('amount') ?? 100,
});
fetchEligibleStudents(roomType);
};
const handleCreate = async () => {
setSaving(true);
const values = await createForm.validateFields();
try {
const values = await createForm.validateFields();
await api.post('/deposits', {
studentId: values.studentId,
amount: values.amount,
paidDate: values.paidDate.format('YYYY-MM-DD'),
notes: values.notes,
});
message.success('押金记录已创建');
message.success('押金金额已增加');
setCreateModal(false);
createForm.resetFields();
fetchData();
fetchEligibleStudents(filterRoomType);
} catch (e: any) {
message.error(e?.message || '操作失败');
if (!isFormValidationError(e)) {
message.error(e?.message || '操作失败');
}
} finally {
setSaving(false);
}
};
const handleBatchCreate = async () => {
if (selectedEligibleStudentIds.length === 0) {
message.warning('请选择至少一名学生');
return;
}
setSaving(true);
try {
const values = await batchForm.validateFields();
await api.post('/deposits/batch', {
studentIds: selectedEligibleStudentIds,
amount: values.amount,
paidDate: values.paidDate.format('YYYY-MM-DD'),
notes: values.notes,
roomType: values.roomType,
});
message.success(`已为 ${selectedEligibleStudentIds.length} 人批量收取押金`);
setBatchModal(false);
batchForm.resetFields();
await fetchData();
fetchEligibleStudents(filterRoomType);
} catch (e: any) {
if (!isFormValidationError(e)) {
message.error(e?.message || '操作失败');
}
} finally {
setSaving(false);
}
};
const handleRefund = async () => {
if (!refundModal) return;
setSaving(true);
const values = await refundForm.validateFields();
try {
const values = await refundForm.validateFields();
await api.put(`/deposits/${refundModal.id}/refund`, {
refundDate: values.refundDate.format('YYYY-MM-DD'),
deductionAmount: values.deductionAmount || 0,
deductionReason: values.deductionReason,
notes: values.notes,
});
message.success('退还操作完成');
setRefundModal(null);
refundForm.resetFields();
fetchData();
fetchEligibleStudents(filterRoomType);
} catch (e: any) {
message.error(e?.message || '操作失败');
if (!isFormValidationError(e)) {
message.error(e?.message || '操作失败');
}
} finally {
setSaving(false);
}
@@ -143,8 +284,8 @@ const DepositsPage: React.FC = () => {
const handleAddInstallment = async () => {
if (installmentModal == null) return;
const values = await installmentForm.validateFields();
try {
const values = await installmentForm.validateFields();
await api.post(`/deposits/${installmentModal}/installments`, {
amount: values.amount,
dueDate: values.dueDate.format('YYYY-MM-DD'),
@@ -154,7 +295,9 @@ const DepositsPage: React.FC = () => {
installmentForm.resetFields();
fetchData();
} catch (e: any) {
message.error(e?.message || '操作失败');
if (!isFormValidationError(e)) {
message.error(e?.message || '操作失败');
}
}
};
@@ -171,158 +314,286 @@ const DepositsPage: React.FC = () => {
}
};
const saveInstallmentCell = async (
installmentId: number,
field: 'status' | 'paidDate',
value: unknown,
) => {
await api.put(`/deposits/installments/${installmentId}`, { [field]: value });
message.success('分期记录已保存');
if (detailModal) {
const refreshed = await api.get<DepositRecord>(`/deposits/${detailModal.id}`);
setDetailModal(refreshed);
}
await fetchData();
};
const handleDeleteInstallment = async (installmentId: number) => {
try {
await api.delete(`/deposits/installments/${installmentId}`);
message.success('分期已删除');
message.success('分期已归档');
fetchData();
} catch (e: any) {
message.error(e?.message || '操作失败');
}
};
const columns = useMemo(() => [
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
{ title: '押金金额', dataIndex: 'amount', width: 110, render: (v: number) => `¥${Number(v).toFixed(2)}` },
{ title: '缴纳日期', dataIndex: 'paidDate', width: 110 },
{
title: '状态',
dataIndex: 'status',
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>,
},
{
title: '退款状态',
dataIndex: 'refundStatus',
render: (s: string) =>
s ? <Tag color={refundStatusMap[s]?.color}>{refundStatusMap[s]?.text || s}</Tag> : '-',
},
{
title: '退还金额',
dataIndex: 'refundAmount',
render: (v: any) => (v != null ? `¥${Number(v).toFixed(2)}` : '-'),
},
{
title: '扣除金额',
dataIndex: 'deductionAmount',
render: (v: any) => (v > 0 ? `¥${Number(v).toFixed(2)}` : '-'),
},
{ title: '扣除原因', dataIndex: 'deductionReason', width: 120, render: (v: any) => v || '-' },
{ title: '退还日期', dataIndex: 'refundDate', width: 110, render: (v: any) => v || '-' },
{ title: '备注', dataIndex: 'notes', width: 120, render: (v: any) => v || '-' },
{
title: '操作',
width: 240,
render: (_: any, record: any) => (
<Space>
<PermissionButton
permission="deposit:view"
size="small"
onClick={() => {
setDetailModal(record);
}}
>
</PermissionButton>
{record.status === 'paid' && !record.refundStatus && (
<>
<PermissionButton
permission="deposit:refund"
size="small"
type="primary"
onClick={() => {
setRefundModal(record);
refundForm.setFieldsValue({ refundDate: dayjs(), deductionAmount: 0 });
}}
>
退
</PermissionButton>
</>
)}
<Popconfirm
title="确定删除?"
onConfirm={async () => {
try {
await api.delete(`/deposits/${record.id}`);
message.success('删除成功');
fetchData();
} catch (e: any) {
message.error(e?.message || '删除失败');
}
}}
>
<PermissionButton
permission="deposit:delete"
size="small"
danger
icon={<DeleteOutlined />}
>
</PermissionButton>
</Popconfirm>
</Space>
),
},
], [fetchData]);
const columns = useMemo(
() => [
{ title: '学生', width: 120, render: (_: unknown, r: any) => r.student?.name || '-' },
{
title: '当前可用押金',
dataIndex: 'amount',
width: 130,
render: (v: number) => `¥${Number(v || 0).toFixed(2)}`,
},
{
title: '房间',
width: 120,
render: (_: unknown, r: any) =>
r.roomNumber ? `${r.building ? `${r.building}-` : ''}${r.roomNumber}` : '-',
},
{ title: '房型', dataIndex: 'roomType', width: 100, render: (v: string) => v || '-' },
{ title: '最近收取日期', dataIndex: 'paidDate', width: 120, render: (v: string) => v || '-' },
{
title: '状态',
dataIndex: 'status',
render: (s: string) =>
s === 'unpaid' ? (
<Tag color="default"></Tag>
) : (
<Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>
),
},
{ title: '退还日期', dataIndex: 'refundDate', width: 110, render: (v: unknown) => v || '-' },
{ title: '备注', dataIndex: 'notes', width: 120, render: (v: unknown) => v || '-' },
{
title: '操作',
width: 240,
render: (_: unknown, record: any) => {
const hasDeposit = typeof record.id === 'number';
return (
<Space>
{hasDeposit && (
<PermissionButton
permission="deposit:view"
size="small"
onClick={() => {
setDetailModal(record);
}}
>
</PermissionButton>
)}
{record.status === 'paid' && hasDeposit && (
<PermissionButton
permission="deposit:refund"
size="small"
type="primary"
onClick={() => {
setRefundModal(record);
refundForm.setFieldsValue({ refundDate: dayjs() });
}}
>
退
</PermissionButton>
)}
{hasDeposit && (
<Popconfirm
title="确定归档?"
onConfirm={async () => {
try {
await api.delete(`/deposits/${record.id}`);
message.success('归档成功');
fetchData();
fetchEligibleStudents(filterRoomType);
} catch (e: any) {
message.error(e?.message || '归档失败');
}
}}
>
<PermissionButton
permission="deposit:delete"
size="small"
danger
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
)}
</Space>
);
},
},
],
[fetchData, fetchEligibleStudents, filterRoomType, refundForm],
);
const eligibleColumns = [
{
title: '学生',
render: (_: unknown, r: EligibleStudent) =>
`${r.studentName} (${r.studentNo || `#${r.studentId}`})`,
},
{
title: '房间',
render: (_: unknown, r: EligibleStudent) =>
`${r.building ? `${r.building}-` : ''}${r.roomNumber}`,
},
{ title: '房型', dataIndex: 'roomType' },
{
title: '当前押金',
dataIndex: 'depositAmount',
render: (v: number) => `¥${Number(v || 0).toFixed(2)}`,
},
];
return (
<div>
<div
style={{
marginBottom: 16,
display: 'flex',
justifyContent: 'space-between',
flexWrap: 'wrap',
gap: 8,
}}
>
<Space wrap>
<Input.Search
placeholder="搜索学生姓名"
allowClear
style={{ width: 180 }}
onSearch={(v) => setSearchText(v)}
onChange={(e) => {
if (!e.target.value) setSearchText('');
style={{
marginBottom: 16,
display: 'flex',
justifyContent: 'space-between',
flexWrap: 'wrap',
gap: 8,
}}
>
<Space wrap>
<Input.Search
placeholder="搜索学生姓名/学号"
allowClear
style={{ width: 180 }}
onSearch={(v) => setSearchText(v)}
onChange={(e) => {
setSearchText(e.target.value);
}}
/>
<Select
placeholder="房型筛选"
allowClear
style={{ width: 130 }}
value={filterRoomType}
onChange={(v) => setFilterRoomType(v)}
options={roomTypeOptions}
/>
<Select
placeholder="状态筛选"
allowClear
style={{ width: 120 }}
value={filterStatus}
disabled={!!filterRoomType}
onChange={(v) => setFilterStatus(v)}
options={[
{ value: 'paid', label: '有余额' },
{ value: 'refunded', label: '已全退' },
{ value: 'depleted', label: '已扣完' },
]}
/>
</Space>
<Space wrap>
<PermissionButton
permission="deposit:create"
icon={<TeamOutlined />}
onClick={() => openBatchModal()}
>
</PermissionButton>
<PermissionButton
permission="deposit:create"
type="primary"
icon={<PlusOutlined />}
onClick={() => {
createForm.resetFields();
createForm.setFieldsValue({ amount: 500, paidDate: dayjs() });
setCreateModal(true);
}}
>
</PermissionButton>
</Space>
</div>
<Table
columns={columns}
dataSource={filteredData}
rowKey="id"
loading={loading || (!!filterRoomType && eligibleLoading)}
scroll={{ x: 1200 }}
pagination={{
defaultPageSize: 15,
showSizeChanger: true,
pageSizeOptions: [15, 30, 50, 100],
showTotal: (total) => `${total}`,
}}
locale={{ emptyText: <Empty description="暂无数据" /> }}
/>
<Select
placeholder="状态筛选"
allowClear
style={{ width: 120 }}
value={filterStatus}
onChange={(v) => setFilterStatus(v)}
options={[
{ value: 'paid', label: '已缴' },
{ value: 'refunded', label: '已全退' },
{ value: 'partial_refund', label: '部分退还' },
{ value: 'deducted', label: '已全扣' },
]}
/>
</Space>
<PermissionButton
permission="deposit:create"
type="primary"
icon={<PlusOutlined />}
onClick={() => {
createForm.resetFields();
createForm.setFieldsValue({ amount: 500, paidDate: dayjs() });
setCreateModal(true);
}}
>
</PermissionButton>
</div>
<Table
columns={columns}
dataSource={filteredData}
rowKey="id"
loading={loading}
scroll={{ x: 1200 }}
pagination={{ pageSize: 15, showTotal: (total) => `${total}` }}
locale={{ emptyText: <Empty description="暂无数据" /> }}
/>
{/* Batch Create Modal */}
<Modal
title="按房型批量收取押金"
open={batchModal}
onOk={handleBatchCreate}
onCancel={() => setBatchModal(false)}
okText="确认批量收取"
confirmLoading={saving}
okButtonProps={{ disabled: selectedEligibleStudentIds.length === 0 }}
width={760}
>
<Form form={batchForm} layout="vertical">
<Space style={{ width: '100%' }} align="start" wrap>
<Form.Item
name="roomType"
label="房型"
rules={[{ required: true, message: '请选择房型' }]}
>
<Select
style={{ width: 140 }}
options={roomTypeOptions}
onChange={handleBatchRoomTypeChange}
/>
</Form.Item>
<Form.Item
name="amount"
label="每人收取金额(元)"
rules={[{ required: true, message: '请输入金额' }]}
>
<InputNumber min={0.01} precision={2} style={{ width: 180 }} />
</Form.Item>
<Form.Item
name="paidDate"
label="收取日期"
rules={[{ required: true, message: '请选择日期' }]}
>
<DatePicker style={{ width: 180 }} placeholder="选择收取日期" format="YYYY-MM-DD" />
</Form.Item>
</Space>
<Form.Item name="notes" label="备注">
<Input.TextArea rows={2} placeholder={`${batchRoomType}押金`} />
</Form.Item>
</Form>
<div style={{ marginBottom: 8 }}>
<strong>{selectedEligibleStudentIds.length}</strong> / {eligibleStudents.length}
{suggestedDepositByRoomType[batchRoomType] && (
<span style={{ color: '#999', marginLeft: 8 }}>
¥{suggestedDepositByRoomType[batchRoomType]}
</span>
)}
</div>
<Table
size="small"
columns={eligibleColumns}
dataSource={eligibleStudents}
rowKey="studentId"
loading={eligibleLoading}
locale={{ emptyText: <Empty description="暂无符合条件的在住人员" /> }}
pagination={{ pageSize: 6, showSizeChanger: false }}
rowSelection={{
selectedRowKeys: selectedEligibleStudentIds,
onChange: (keys) => setSelectedEligibleStudentIds(keys as number[]),
}}
/>
</Modal>
{/* Create Modal */}
<Modal
@@ -346,11 +617,11 @@ const DepositsPage: React.FC = () => {
options={studentOptions}
/>
</Form.Item>
<Form.Item name="amount" label="押金金额(元)" rules={[{ required: true }]}>
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
<Form.Item name="amount" label="本次收取金额(元)" rules={[{ required: true }]}>
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="paidDate" label="缴纳日期" rules={[{ required: true }]}>
<DatePicker style={{ width: '100%' }} placeholder="选择缴纳日期" format="YYYY-MM-DD" />
<Form.Item name="paidDate" label="收取日期" rules={[{ required: true }]}>
<DatePicker style={{ width: '100%' }} placeholder="选择收取日期" format="YYYY-MM-DD" />
</Form.Item>
<Form.Item name="notes" label="备注">
<Input.TextArea rows={2} />
@@ -369,22 +640,11 @@ const DepositsPage: React.FC = () => {
>
<Form form={refundForm} layout="vertical">
<div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 8 }}>
: <strong>¥{Number(refundModal?.amount || 0).toFixed(2)}</strong>
: <strong>¥{Number(refundModal?.amount || 0).toFixed(2)}</strong>
</div>
<Form.Item name="refundDate" label="退还日期" rules={[{ required: true }]}>
<DatePicker style={{ width: '100%' }} placeholder="选择退还日期" format="YYYY-MM-DD" />
</Form.Item>
<Form.Item name="deductionAmount" label="扣除金额(元)" extra="如无扣除填0">
<InputNumber
min={0}
max={Number(refundModal?.amount || 500)}
precision={2}
style={{ width: '100%' }}
/>
</Form.Item>
<Form.Item name="deductionReason" label="扣除原因">
<Input placeholder="如:房间损坏赔偿" />
</Form.Item>
<Form.Item name="notes" label="备注">
<Input.TextArea rows={2} />
</Form.Item>
@@ -402,27 +662,34 @@ const DepositsPage: React.FC = () => {
{detailModal && (
<div>
<Card size="small" style={{ marginBottom: 16 }}>
<p><strong>:</strong> ¥{Number(detailModal.amount).toFixed(2)}</p>
<p><strong>:</strong> {detailModal.paidDate}</p>
<p>
<strong>:</strong> ¥{Number(detailModal.amount).toFixed(2)}
</p>
<p>
<strong>:</strong> {detailModal.paidDate}
</p>
<p>
<strong>:</strong>{' '}
<Tag color={statusMap[detailModal.status]?.color}>
{statusMap[detailModal.status]?.text || detailModal.status}
</Tag>
</p>
{detailModal.refundStatus && (
{detailModal.notes && (
<p>
<strong>退:</strong>{' '}
<Tag color={refundStatusMap[detailModal.refundStatus]?.color}>
{refundStatusMap[detailModal.refundStatus]?.text || detailModal.refundStatus}
</Tag>
<strong>:</strong> {detailModal.notes}
</p>
)}
{detailModal.notes && <p><strong>:</strong> {detailModal.notes}</p>}
</Card>
{/* Installments Section */}
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 8,
}}
>
<h4 style={{ margin: 0 }}></h4>
<PermissionButton
permission="deposit:edit"
@@ -437,43 +704,86 @@ const DepositsPage: React.FC = () => {
</PermissionButton>
</div>
{detailModal.installments?.length > 0 ? (
<List
{detailModal.installments && detailModal.installments.length > 0 ? (
<Table
size="small"
pagination={false}
rowKey="id"
dataSource={detailModal.installments}
renderItem={(item: any) => (
<List.Item
actions={[
item.status === 'pending' && (
<PermissionButton
key="pay"
permission="deposit:edit"
size="small"
type="primary"
icon={<DollarOutlined />}
onClick={() => handlePayInstallment(item.id)}
>
</PermissionButton>
),
<Popconfirm
title="确定删除?"
onConfirm={() => handleDeleteInstallment(item.id)}
columns={[
{
title: '金额',
dataIndex: 'amount',
render: (value: number) => `¥${Number(value).toFixed(2)}`,
},
{ title: '到期日', dataIndex: 'dueDate' },
{
title: '实付日',
dataIndex: 'paidDate',
render: (value: string, item: any) => (
<EditableCell
value={value}
editor="date"
permission="deposit:edit"
onSave={(next) => saveInstallmentCell(item.id, 'paidDate', next)}
>
<PermissionButton key="del" permission="deposit:delete" size="small" danger icon={<DeleteOutlined />}>
</PermissionButton>
</Popconfirm>
].filter(Boolean)}
>
<List.Item.Meta
title={`¥${Number(item.amount).toFixed(2)}`}
description={`到期: ${item.dueDate}${item.paidDate ? ` | 缴纳: ${item.paidDate}` : ''}`}
/>
<Tag color={installmentStatusMap[item.status]?.color}>
{installmentStatusMap[item.status]?.text || item.status}
</Tag>
</List.Item>
)}
{value || '-'}
</EditableCell>
),
},
{
title: '状态',
dataIndex: 'status',
render: (value: string, item: any) => (
<EditableCell
value={value}
editor="select"
options={[
{ value: 'pending', label: '待缴' },
{ value: 'paid', label: '已缴' },
{ value: 'overdue', label: '逾期' },
]}
permission="deposit:edit"
onSave={(next) => saveInstallmentCell(item.id, 'status', next)}
>
<Tag color={installmentStatusMap[value]?.color}>
{installmentStatusMap[value]?.text || value}
</Tag>
</EditableCell>
),
},
{
title: '操作',
render: (_: unknown, item: any) => (
<Space>
{item.status === 'pending' && (
<PermissionButton
permission="deposit:edit"
size="small"
type="primary"
icon={<DollarOutlined />}
onClick={() => handlePayInstallment(item.id)}
>
</PermissionButton>
)}
<Popconfirm
title="确定归档?"
onConfirm={() => handleDeleteInstallment(item.id)}
>
<PermissionButton
permission="deposit:delete"
size="small"
danger
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
</Space>
),
},
]}
/>
) : (
<p style={{ color: '#999' }}></p>
@@ -492,15 +802,13 @@ const DepositsPage: React.FC = () => {
>
<Form form={installmentForm} layout="vertical">
<Form.Item name="amount" label="分期金额(元)" rules={[{ required: true }]}>
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="dueDate" label="到期日期" rules={[{ required: true }]}>
<DatePicker style={{ width: '100%' }} placeholder="选择到期日期" format="YYYY-MM-DD" />
</Form.Item>
</Form>
</Modal>
</div>
);
};

View File

@@ -0,0 +1,59 @@
import React from 'react';
import { DatePicker, Form, Input, Modal, Select } from 'antd';
import type { FormInstance } from 'antd';
import type { ClassOption, ExamFormValues } from './types';
import { EXAM_TYPE_OPTIONS } from './types';
interface Props {
open: boolean;
editing: boolean;
saving: boolean;
form: FormInstance<ExamFormValues>;
classes: ClassOption[];
onCancel: () => void;
onSubmit: () => void;
}
const ExamFormModal: React.FC<Props> = ({
open,
editing,
saving,
form,
classes,
onCancel,
onSubmit,
}) => (
<Modal
title={editing ? '编辑考试' : '创建考试'}
open={open}
confirmLoading={saving}
onCancel={onCancel}
onOk={onSubmit}
width={560}
>
<Form form={form} layout="vertical">
<Form.Item name="examType" label="考试类型" rules={[{ required: true, message: '请选择考试类型' }]}>
<Select options={EXAM_TYPE_OPTIONS} placeholder="请选择" />
</Form.Item>
<Form.Item name="examName" label="考试名称" rules={[{ required: true, message: '请输入考试名称' }]}>
<Input placeholder="如2026 年 7 月月考" />
</Form.Item>
<Form.Item name="subject" label="科目" rules={[{ required: true, message: '请输入科目' }]}>
<Input placeholder="如:数学" />
</Form.Item>
<Form.Item name="examDate" label="考试日期" rules={[{ required: true, message: '请选择考试日期' }]}>
<DatePicker style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="classId" label="考试班级" rules={[{ required: true, message: '请选择考试班级' }]}>
<Select
showSearch
optionFilterProp="label"
placeholder="选择在读班级"
options={classes.filter((item) => !item.isArchived).map((item) => ({ value: item.id, label: item.name }))}
/>
</Form.Item>
</Form>
</Modal>
);
export default ExamFormModal;

View File

@@ -0,0 +1,185 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Alert, Button, Card, Descriptions, Empty, Space, Spin, Table, Tag, Tooltip } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { ArrowLeftOutlined, EyeOutlined } from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import api from '../../api';
import EditableCell from '../../components/EditableCell';
import { useViewSensitive } from '../../hooks/useViewSensitive';
import { maskPhone } from '../../utils/sensitive';
import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
import type { ExamItem } from './types';
import './style.css';
interface ScoreRow {
id: number;
studentId: number;
phone: string;
name: string;
score: number | null;
classAvg: number | null;
rank: number | null;
}
interface ExamDetail extends ExamItem {
scores: ScoreRow[];
}
const PhoneCell: React.FC<{ row: ScoreRow }> = ({ row }) => {
const { hasPermission } = usePermission();
const reveal = useViewSensitive(row.studentId, '考试管理', hasPermission('log:create'));
if (!row.phone) return <>-</>;
return (
<Space size={4}>
<span>{maskPhone(row.phone)}</span>
{hasPermission('log:create') ? (
<Tooltip title="查看完整手机号">
<Button
type="text"
size="small"
icon={<EyeOutlined />}
onClick={() => reveal('手机号', row.phone)}
/>
</Tooltip>
) : null}
</Space>
);
};
const ExamDetailPage: React.FC = () => {
const { id } = useParams();
const navigate = useNavigate();
const [detail, setDetail] = useState<ExamDetail | null>(null);
const [loading, setLoading] = useState(true);
const load = useCallback(async () => {
setLoading(true);
try {
setDetail(await api.get<ExamDetail>(`/exams/${id}`));
} catch (error) {
message.error((error as { message?: string })?.message || '加载考试失败');
} finally {
setLoading(false);
}
}, [id]);
useEffect(() => {
void load();
}, [load]);
const saveScore = useCallback(
async (row: ScoreRow, value: number | undefined) => {
await api.put(`/exams/${id}/scores/${row.id}`, { score: value ?? null });
message.success('成绩已保存');
await load();
},
[id, load],
);
const columns = useMemo<ColumnsType<ScoreRow>>(() => {
if (!detail) return [];
const fixed = [
{
title: '手机号*',
width: 155,
render: (_: unknown, row: ScoreRow) => <PhoneCell row={row} />,
},
{ title: '姓名', dataIndex: 'name', width: 100 },
{ title: '考试类型*', width: 110, render: () => detail.examType },
{ title: '考试名称', width: 170, render: () => detail.examName },
{ title: '科目*', width: 90, render: () => detail.subject },
];
return [
...fixed,
{
title: '成绩*',
dataIndex: 'score',
width: 100,
render: (value: number | null, row: ScoreRow) => (
detail.status === 'archived' ? (
value ?? '-'
) : (
<EditableCell<number | undefined>
value={value ?? undefined}
editor="money"
min={0}
max={999.99}
permission="exam:view"
onSave={(next) => saveScore(row, next)}
>
{value ?? '-'}
</EditableCell>
)
),
},
{
title: '班级均分',
dataIndex: 'classAvg',
width: 110,
render: (value: number | null) => value ?? '-',
},
{
title: '排名',
dataIndex: 'rank',
width: 80,
render: (value: number | null) => value ?? '-',
},
{ title: '考试日期', width: 110, render: () => detail.examDate },
{ title: '关联报读(班级名)', width: 180, render: () => detail.className },
];
}, [detail, saveScore]);
if (loading && !detail)
return (
<div className="exam-detail-loading">
<Spin size="large" />
</div>
);
if (!detail) return <Empty description="考试不存在或无权访问" />;
const average = detail.scores.find((row) => row.classAvg !== null)?.classAvg ?? null;
return (
<div className="exam-detail-page">
<div className="exam-detail-header">
<Space>
<Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/exams')}>
</Button>
<h2>{detail.examName}</h2>
{detail.status === 'archived' ? <Tag></Tag> : null}
</Space>
</div>
{detail.status === 'archived' ? (
<Alert type="info" showIcon message="该考试已归档,成绩仅供查看。如需继续录入,请先在考试列表中恢复。" />
) : null}
<Card className="exam-summary">
<Descriptions column={{ xs: 1, sm: 2, lg: 5 }}>
<Descriptions.Item label="考试类型">{detail.examType}</Descriptions.Item>
<Descriptions.Item label="科目">{detail.subject}</Descriptions.Item>
<Descriptions.Item label="考试班级">{detail.className}</Descriptions.Item>
<Descriptions.Item label="考试日期">{detail.examDate}</Descriptions.Item>
<Descriptions.Item label="录入进度">
{detail.enteredScores}/{detail.totalStudents} {average ?? '-'}
</Descriptions.Item>
</Descriptions>
</Card>
<Card title="成绩表">
<Table<ScoreRow>
columns={columns}
dataSource={detail.scores}
rowKey="id"
loading={loading}
scroll={{ x: 1310 }}
pagination={{
defaultPageSize: 30,
showSizeChanger: true,
pageSizeOptions: [30, 50, 100],
}}
locale={{ emptyText: <Empty description="暂无学生名单" /> }}
/>
</Card>
</div>
);
};
export default ExamDetailPage;

View File

@@ -0,0 +1,251 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Button, Card, Checkbox, Col, Empty, Form, Input, Popconfirm, Progress, Row, Select, Space, Switch, Tag } from 'antd';
import { CalendarOutlined, InboxOutlined, PlusOutlined, SearchOutlined, TeamOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';
import api from '../../api';
import { message } from '../../ui/app-message';
import ExamFormModal from './ExamFormModal';
import { selectAllExamIds, toggleExamSelection } from './selection';
import type { ClassOption, ExamFormValues, ExamItem } from './types';
import { EXAM_TYPE_OPTIONS } from './types';
import './style.css';
const ExamsPage: React.FC = () => {
const navigate = useNavigate();
const [form] = Form.useForm<ExamFormValues>();
const [data, setData] = useState<ExamItem[]>([]);
const [classes, setClasses] = useState<ClassOption[]>([]);
const [loading, setLoading] = useState(false);
const [batchLoading, setBatchLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
const [keyword, setKeyword] = useState('');
const [examType, setExamType] = useState<string>();
const [classId, setClassId] = useState<number>();
const [showArchived, setShowArchived] = useState(false);
const [selectedExamIds, setSelectedExamIds] = useState<number[]>([]);
const loadClasses = useCallback(async () => {
const result = await api.get<ClassOption[]>('/classes');
setClasses(result ?? []);
}, []);
const loadExams = useCallback(async () => {
setSelectedExamIds([]);
setLoading(true);
try {
const params = new URLSearchParams();
if (keyword.trim()) params.set('keyword', keyword.trim());
if (examType) params.set('examType', examType);
if (classId) params.set('classId', String(classId));
params.set('isArchived', String(showArchived));
const result = await api.get<ExamItem[]>(`/exams?${params.toString()}`);
setData(result ?? []);
} catch (error) {
message.error((error as { message?: string })?.message || '加载考试失败');
} finally {
setLoading(false);
}
}, [classId, examType, keyword, showArchived]);
useEffect(() => {
void loadClasses().catch((error: { message?: string }) => message.error(error?.message || '加载班级失败'));
}, [loadClasses]);
useEffect(() => {
const timer = window.setTimeout(() => void loadExams(), 200);
return () => window.clearTimeout(timer);
}, [loadExams]);
const classOptions = useMemo(
() => classes.map((item) => ({ value: item.id, label: item.name })),
[classes],
);
const openCreate = () => {
form.resetFields();
form.setFieldValue('examDate', dayjs());
setModalOpen(true);
};
const submit = async () => {
try {
const values = await form.validateFields();
setSaving(true);
const payload = { ...values, examDate: values.examDate.format('YYYY-MM-DD') };
await api.post('/exams', payload);
message.success('考试已创建');
setModalOpen(false);
await loadExams();
} catch (error) {
if ((error as { errorFields?: unknown[] }).errorFields) return;
message.error((error as { message?: string })?.message || '保存失败');
} finally {
setSaving(false);
}
};
const changeArchiveStatus = async (exam: ExamItem, archive: boolean) => {
try {
await api.put(`/exams/${exam.id}/${archive ? 'archive' : 'restore'}`);
message.success(archive ? '考试已归档' : '考试已恢复');
await loadExams();
} catch (error) {
message.error((error as { message?: string })?.message || '操作失败');
}
};
const allCurrentSelected = data.length > 0 && selectedExamIds.length === data.length;
const partiallySelected = selectedExamIds.length > 0 && !allCurrentSelected;
const toggleSelectAll = (checked: boolean) => {
setSelectedExamIds(selectAllExamIds(data.map((exam) => exam.id), checked));
};
const changeArchiveView = (checked: boolean) => {
setSelectedExamIds([]);
setShowArchived(checked);
};
const batchChangeArchiveStatus = async (archive: boolean) => {
if (selectedExamIds.length === 0 || batchLoading) return;
setBatchLoading(true);
try {
if (archive) {
const result = await api.put<{ archived: number; skipped: number }>('/exams/batch-archive', {
ids: selectedExamIds,
});
message.success(
`已归档 ${result.archived} 场考试${result.skipped ? `,跳过 ${result.skipped}` : ''}`,
);
} else {
const result = await api.put<{ restored: number; skipped: number }>('/exams/batch-restore', {
ids: selectedExamIds,
});
message.success(
`已恢复 ${result.restored} 场考试${result.skipped ? `,跳过 ${result.skipped}` : ''}`,
);
}
setSelectedExamIds([]);
await loadExams();
} catch (error) {
message.error((error as { message?: string })?.message || '批量操作失败');
} finally {
setBatchLoading(false);
}
};
return (
<div className="exam-page">
<div className="exam-toolbar">
<Space wrap>
<Input value={keyword} onChange={(event) => setKeyword(event.target.value)} prefix={<SearchOutlined />} placeholder="搜索考试名称" allowClear />
<Select value={examType} onChange={setExamType} options={EXAM_TYPE_OPTIONS} placeholder="考试类型" allowClear style={{ width: 140 }} />
<Select value={classId} onChange={setClassId} options={classOptions} placeholder="考试班级" allowClear showSearch optionFilterProp="label" style={{ width: 180 }} />
</Space>
<Space wrap>
<Checkbox
checked={allCurrentSelected}
indeterminate={partiallySelected}
disabled={data.length === 0 || loading || batchLoading}
onChange={(event) => toggleSelectAll(event.target.checked)}
>
</Checkbox>
<Popconfirm
title={showArchived ? '确认恢复选中的考试?' : '确认归档选中的考试?'}
description={
showArchived
? `将恢复选中的 ${selectedExamIds.length} 场考试。`
: `将归档选中的 ${selectedExamIds.length} 场考试,归档后成绩将变为只读。`
}
disabled={selectedExamIds.length === 0 || batchLoading}
onConfirm={() => void batchChangeArchiveStatus(!showArchived)}
>
<Button
danger={!showArchived}
loading={batchLoading}
disabled={selectedExamIds.length === 0}
>
{showArchived ? '批量恢复' : '批量归档'}
</Button>
</Popconfirm>
<span className="exam-archive-toggle">
<InboxOutlined />
<Switch size="small" checked={showArchived} onChange={changeArchiveView} />
</span>
{!showArchived ? (
<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}></Button>
) : null}
</Space>
</div>
{data.length === 0 && !loading ? (
<div className="exam-empty"><Empty description="暂无考试" /></div>
) : (
<Row gutter={[16, 16]}>
{data.map((exam) => {
const percent = exam.totalStudents === 0 ? 0 : Math.round((exam.enteredScores / exam.totalStudents) * 100);
return (
<Col key={exam.id} xs={24} sm={12} xl={8} xxl={6}>
<Card
className={`exam-card${selectedExamIds.includes(exam.id) ? ' exam-card-selected' : ''}`}
loading={loading}
title={(
<Space>
<Checkbox
aria-label={`选择考试 ${exam.examName}`}
checked={selectedExamIds.includes(exam.id)}
disabled={batchLoading}
onChange={(event) => {
setSelectedExamIds((current) =>
toggleExamSelection(current, exam.id, event.target.checked),
);
}}
/>
<Tag color="blue">{exam.examType}</Tag>
<span>{exam.examName}</span>
</Space>
)}
extra={<Tag color={exam.status === 'archived' ? 'default' : 'green'}>{exam.status === 'archived' ? '已归档' : '成绩录入'}</Tag>}
actions={[
<span key="detail" onClick={() => navigate(`/exams/${exam.id}`)}></span>,
exam.status === 'archived' ? (
<Popconfirm
key="restore"
title="确认恢复该考试?"
onConfirm={() => changeArchiveStatus(exam, false)}
>
<span></span>
</Popconfirm>
) : (
<Popconfirm
key="archive"
title="确认归档该考试?"
description={`当前已录入 ${exam.enteredScores}/${exam.totalStudents} 人,归档后成绩将变为只读。`}
onConfirm={() => changeArchiveStatus(exam, true)}
>
<span></span>
</Popconfirm>
),
]}
>
<div className="exam-meta"><span></span><strong>{exam.subject}</strong></div>
<div className="exam-meta"><span><TeamOutlined /> </span><strong>{exam.className}</strong></div>
<div className="exam-meta"><span><CalendarOutlined /> </span><strong>{exam.examDate}</strong></div>
<div className="exam-progress"><div><span></span><strong>{exam.enteredScores}/{exam.totalStudents}</strong></div><Progress percent={percent} size="small" /></div>
</Card>
</Col>
);
})}
</Row>
)}
<ExamFormModal open={modalOpen} editing={false} saving={saving} form={form} classes={classes} onCancel={() => setModalOpen(false)} onSubmit={() => void submit()} />
</div>
);
};
export default ExamsPage;

View File

@@ -0,0 +1,15 @@
import { describe, expect, it } from 'vitest';
import { selectAllExamIds, toggleExamSelection } from './selection';
describe('考试批量选择', () => {
it('可以选择和取消单场考试且不会重复选择', () => {
expect(toggleExamSelection([1], 2, true)).toEqual([1, 2]);
expect(toggleExamSelection([1, 2], 2, true)).toEqual([1, 2]);
expect(toggleExamSelection([1, 2], 1, false)).toEqual([2]);
});
it('全选只包含当前结果并去重,取消全选后清空', () => {
expect(selectAllExamIds([1, 2, 2, 3], true)).toEqual([1, 2, 3]);
expect(selectAllExamIds([1, 2, 3], false)).toEqual([]);
});
});

View File

@@ -0,0 +1,13 @@
export const toggleExamSelection = (
selectedIds: number[],
examId: number,
checked: boolean,
): number[] => {
if (checked) {
return selectedIds.includes(examId) ? selectedIds : [...selectedIds, examId];
}
return selectedIds.filter((id) => id !== examId);
};
export const selectAllExamIds = (examIds: number[], checked: boolean): number[] =>
checked ? [...new Set(examIds)] : [];

View File

@@ -0,0 +1,89 @@
.exam-page,
.exam-detail-page {
display: flex;
flex-direction: column;
gap: 16px;
}
.exam-toolbar,
.exam-detail-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
.exam-detail-header h2 {
margin: 0;
font-size: 20px;
letter-spacing: 0;
}
.exam-card {
height: 100%;
border-radius: 8px;
}
.exam-card-selected {
border-color: #1677ff;
box-shadow: 0 0 0 1px #1677ff;
}
.exam-card .ant-card-head-title {
min-width: 0;
}
.exam-card .ant-card-head-title > .ant-space {
max-width: 100%;
}
.exam-card .ant-card-head-title span:last-child {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.exam-meta,
.exam-progress > div {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 10px;
}
.exam-meta span,
.exam-progress span {
color: rgba(0, 0, 0, 0.55);
}
.exam-progress {
margin-top: 16px;
}
.exam-empty,
.exam-detail-loading {
min-height: 360px;
display: grid;
place-items: center;
}
.exam-summary {
border-radius: 8px;
}
.exam-archive-toggle {
display: inline-flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
@media (max-width: 575px) {
.exam-toolbar > .ant-space,
.exam-toolbar .ant-input-affix-wrapper,
.exam-toolbar .ant-select {
width: 100% !important;
}
}

View File

@@ -0,0 +1,37 @@
import type dayjs from 'dayjs';
export interface ExamItem {
id: number;
examType: string;
examName: string;
subject: string;
examDate: string;
classId: number;
className: string;
status: 'active' | 'archived';
totalStudents: number;
enteredScores: number;
}
export interface ExamFormValues {
examType: string;
examName: string;
subject: string;
examDate: dayjs.Dayjs;
classId: number;
}
export interface ClassOption {
id: number;
name: string;
isArchived: boolean;
}
export const EXAM_TYPE_OPTIONS = [
{ value: '月考', label: '月考' },
{ value: '周测', label: '周测' },
{ value: '期中考试', label: '期中考试' },
{ value: '期末考试', label: '期末考试' },
{ value: '模拟考试', label: '模拟考试' },
{ value: '入学测试', label: '入学测试' },
];

File diff suppressed because it is too large Load Diff

View File

@@ -1,13 +1,34 @@
import React, { useEffect, useState, useMemo, useCallback } from 'react';
import {
Card, Form, Input, Button, Space, Spin, Switch, Alert, Descriptions, Tag,
Tabs, Drawer, Tree, Select, TreeSelect, Modal, DatePicker, InputNumber,
Row, Col, List,
Card,
Form,
Input,
Button,
Space,
Spin,
Alert,
Descriptions,
Tag,
Divider,
Drawer,
Tree,
Select,
TreeSelect,
Modal,
DatePicker,
Row,
Col,
List,
} from 'antd';
import {
SaveOutlined, ApiOutlined, CheckCircleOutlined, CloseCircleOutlined,
SyncOutlined, BankOutlined, UserOutlined,
DeleteOutlined,
SaveOutlined,
ApiOutlined,
CheckCircleOutlined,
CloseCircleOutlined,
SyncOutlined,
BankOutlined,
UserOutlined,
StopOutlined,
} from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
import type { TreeSelectProps } from 'antd/es/tree-select';
@@ -15,12 +36,21 @@ import api from '../../api';
import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
import PermissionButton from '../../components/PermissionButton';
import {
buildDingTalkConfigPayload,
isAppSecretRequired,
type DingTalkConfigFormValues,
} from './integration-config-form';
import {
cacheDingTalkDraft,
cacheDingTalkServerSnapshot,
commitDingTalkConfig,
readDingTalkConfigCache,
} from './integration-config-cache';
interface DingTalkConfig {
agentId: string;
appSecret: string;
corpId: string;
startEnable: boolean;
}
interface DingOrgTreeNodeExt {
@@ -56,13 +86,13 @@ interface ClassItem {
classType?: string;
startDate?: string;
endDate?: string;
maxStudents?: number;
notes?: string;
}
interface ImportResult {
imported: number;
skipped: number;
conflicts: number;
}
interface DingTalkAttendanceGroup {
@@ -86,17 +116,18 @@ interface DeleteAttendanceGroupsResponse {
};
}
const IntegrationConfigPage: React.FC = () => {
const { hasAllPermissions } = usePermission();
const [loading, setLoading] = useState(false);
const initialCache = useMemo(() => readDingTalkConfigCache(), []);
const { hasPermission, hasAllPermissions } = usePermission();
const canCreateClass = hasPermission('class:create');
const [loading, setLoading] = useState(!initialCache.loaded);
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const [config, setConfig] = useState<DingTalkConfig | null>(null);
const [verified, setVerified] = useState<boolean | null>(null);
const [form] = Form.useForm<DingTalkConfig>();
const [config, setConfig] = useState<DingTalkConfig | null>(initialCache.config);
const [verified, setVerified] = useState<boolean | null>(initialCache.verified);
const [form] = Form.useForm<DingTalkConfigFormValues>();
// ── Sync Users Tab ──
// ── Manual organization sync ──
const [syncRootDeptId, setSyncRootDeptId] = useState<number | undefined>(undefined);
const [orgTree, setOrgTree] = useState<DingOrgTreeNodeExt[]>([]);
const [drawerOpen, setDrawerOpen] = useState(false);
@@ -113,34 +144,45 @@ const IntegrationConfigPage: React.FC = () => {
const [loadingGroups, setLoadingGroups] = useState(false);
const [deletingGroups, setDeletingGroups] = useState(false);
const fetchConfig = async () => {
setLoading(true);
const fetchConfig = useCallback(async (showLoading = false) => {
if (showLoading) setLoading(true);
try {
const res = await api.get<{ success: boolean; data: Array<{ type: string; verify: boolean; config: DingTalkConfig }> }>('/integration/config');
const res = await api.get<{
success: boolean;
data: Array<{ type: string; verify: boolean; config: DingTalkConfig }>;
}>('/integration/config');
const dt = res.data?.find((c) => c.type === 'DINGTALK');
if (dt) {
setConfig(dt.config);
setVerified(dt.verify);
form.setFieldsValue(dt.config);
cacheDingTalkServerSnapshot(dt.config, dt.verify);
form.setFieldsValue(readDingTalkConfigCache().formValues);
} else {
setConfig(null);
setVerified(null);
cacheDingTalkServerSnapshot(null, null);
}
} catch {
// not configured
} finally {
setLoading(false);
if (showLoading) setLoading(false);
}
};
}, [form]);
useEffect(() => {
void fetchConfig();
}, []);
form.setFieldsValue(initialCache.formValues);
void fetchConfig(!initialCache.loaded);
}, [fetchConfig, form, initialCache]);
const handleSave = async () => {
const values = await form.validateFields();
const payload = buildDingTalkConfigPayload(values);
setSaving(true);
try {
await api.post('/integration/config', { type: 'DINGTALK', config: values });
await api.post('/integration/config', { type: 'DINGTALK', config: payload });
message.success('配置已保存');
commitDingTalkConfig({ corpId: payload.corpId, agentId: payload.agentId });
form.setFieldValue('appSecret', undefined);
await fetchConfig();
} catch (e: unknown) {
const err = e as { message?: string };
@@ -152,12 +194,16 @@ const IntegrationConfigPage: React.FC = () => {
const handleTest = async () => {
const values = await form.validateFields();
const payload = buildDingTalkConfigPayload(values);
setTesting(true);
try {
const res = await api.post<{ success: boolean; message: string }>('/integration/config/test', {
type: 'DINGTALK',
config: values,
});
const res = await api.post<{ success: boolean; message: string }>(
'/integration/config/test',
{
type: 'DINGTALK',
config: payload,
},
);
setVerified(res.success);
message.success(res.message);
} catch (e: unknown) {
@@ -169,7 +215,6 @@ const IntegrationConfigPage: React.FC = () => {
}
};
const loadDeptTree = async () => {
try {
const res = await api.get<OrgTreeResponse>('/sync/dingtalk/org-tree');
@@ -195,7 +240,9 @@ const IntegrationConfigPage: React.FC = () => {
} else {
setClasses(res.data ?? []);
}
} catch { /* ignore */ }
} catch {
/* ignore */
}
};
const handleFetchOrgTree = async () => {
@@ -203,7 +250,9 @@ const IntegrationConfigPage: React.FC = () => {
try {
const params: Record<string, string> = {};
if (syncRootDeptId) params.rootDeptId = String(syncRootDeptId);
const res = await api.get<OrgTreeWithUsersResponse>('/sync/dingtalk/org-tree-with-users', { params });
const res = await api.get<OrgTreeWithUsersResponse>('/sync/dingtalk/org-tree-with-users', {
params,
});
if (res.success && res.data) {
setOrgTree(res.data);
setCheckedKeys([]);
@@ -221,7 +270,6 @@ const IntegrationConfigPage: React.FC = () => {
}
};
const buildTreeData = useCallback((nodes: DingOrgTreeNodeExt[]): DataNode[] => {
return nodes.map((node) => {
const users = node.users ?? [];
@@ -257,7 +305,11 @@ const IntegrationConfigPage: React.FC = () => {
const treeData = useMemo(() => buildTreeData(orgTree), [orgTree, buildTreeData]);
const extractCheckedUsers = useCallback((): Array<{ dingUserId: string; name: string; mobile?: string }> => {
const extractCheckedUsers = useCallback((): Array<{
dingUserId: string;
name: string;
mobile?: string;
}> => {
const result: Array<{ dingUserId: string; name: string; mobile?: string }> = [];
const walk = (nodes: DingOrgTreeNodeExt[]) => {
for (const node of nodes) {
@@ -280,8 +332,16 @@ const IntegrationConfigPage: React.FC = () => {
setImporting(true);
try {
const res = await api.post<ImportResult>(`/classes/${selectedClassId}/students/import`, { users });
message.success(`导入 ${res.imported} 人,跳过 ${res.skipped}`);
const res = await api.post<ImportResult>(`/classes/${selectedClassId}/students/import`, {
users,
});
if (res.conflicts > 0) {
message.warning(
`导入 ${res.imported} 人,跳过 ${res.skipped} 人,${res.conflicts} 人需人工绑定`,
);
} else {
message.success(`导入 ${res.imported} 人,跳过 ${res.skipped}`);
}
setCheckedKeys([]);
setSelectedClassId(null);
} catch (e: unknown) {
@@ -333,263 +393,320 @@ const IntegrationConfigPage: React.FC = () => {
setAttendanceGroups([]);
if (response.data.failed.length > 0) {
message.warning(
`删除 ${response.data.deleted.length} 个,失败 ${response.data.failed.length}`,
`清空 ${response.data.deleted.length} 个,失败 ${response.data.failed.length}`,
);
} else {
message.success(`删除钉钉全部 ${response.data.deleted.length} 个考勤组`);
message.success(`清空钉钉全部 ${response.data.deleted.length} 个考勤组`);
}
} catch (error: unknown) {
message.error(error instanceof Error ? error.message : '删除钉钉考勤组失败');
message.error(error instanceof Error ? error.message : '清空钉钉考勤组失败');
} finally {
setDeletingGroups(false);
}
};
const syncTabItems = config && hasAllPermissions('sync:read', 'class:view', 'class:edit')
? [
{
key: 'sync-users',
label: '同步用户',
children: (
<div>
<Alert
type="info"
message="从钉钉获取组织架构,勾选用户后批量导入到班级。"
style={{ marginBottom: 16 }}
showIcon
/>
const syncPanel =
config && hasAllPermissions('sync:read', 'class:view', 'class:edit') ? (
<div>
<Alert
type="info"
message="从钉钉获取组织架构,勾选用户后批量导入到班级。"
style={{ marginBottom: 16 }}
showIcon
/>
<Space>
<TreeSelect
treeData={deptPickerTree}
value={syncRootDeptId}
onChange={(v) => setSyncRootDeptId(v)}
placeholder="选择起始部门(不选=全部)"
allowClear
treeDefaultExpandAll
style={{ minWidth: 240 }}
onDropdownVisibleChange={(open) => {
if (open) loadDeptTree();
}}
/>
<Button
type="primary"
icon={<SyncOutlined />}
loading={fetchingTree}
onClick={handleFetchOrgTree}
>
</Button>
<PermissionButton
permission="sync:trigger"
danger
icon={<StopOutlined />}
loading={loadingGroups}
onClick={openDeleteAllGroups}
>
</PermissionButton>
</Space>
{drawerOpen && (
<Drawer
title="钉钉组织架构 — 批量导入"
open={drawerOpen}
onClose={() => {
setDrawerOpen(false);
}}
width="min(900px, 100vw)"
footer={
<Space>
<TreeSelect
treeData={deptPickerTree}
value={syncRootDeptId}
onChange={(v) => setSyncRootDeptId(v)}
placeholder="选择起始部门(不选=全部)"
allowClear
treeDefaultExpandAll
style={{ minWidth: 240 }}
onDropdownVisibleChange={(open) => { if (open) loadDeptTree(); }}
/>
<Button
onClick={() => {
setDrawerOpen(false);
}}
>
</Button>
<Button
type="primary"
icon={<SyncOutlined />}
loading={fetchingTree}
onClick={handleFetchOrgTree}
loading={importing}
disabled={
checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0 ||
selectedClassId === null
}
onClick={handleJoinClass}
>
</Button>
<PermissionButton
permission="sync:trigger"
danger
icon={<DeleteOutlined />}
loading={loadingGroups}
onClick={openDeleteAllGroups}
>
</PermissionButton>
{canCreateClass ? (
<Button
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0}
onClick={() => setClassModalOpen(true)}
>
</Button>
) : null}
</Space>
{drawerOpen && (
<Drawer
title="钉钉组织架构 — 批量导入"
open={drawerOpen}
onClose={() => { setDrawerOpen(false); }}
width={900}
footer={
<Space>
<Button onClick={() => { setDrawerOpen(false); }}></Button>
<Button
type="primary"
loading={importing}
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0 || selectedClassId === null}
onClick={handleJoinClass}
></Button>
<Button
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0}
onClick={() => setClassModalOpen(true)}
></Button>
</Space>
}
>
<Row gutter={[16, 16]}>
<Col xs={24} md={14}>
<div style={{ maxHeight: '60vh', overflow: 'auto' }}>
<Tree
checkable
treeData={treeData}
defaultExpandAll
showLine={{ showLeafIcon: false }}
checkedKeys={checkedKeys}
onCheck={(checked) => setCheckedKeys(checked as React.Key[])}
/>
</div>
</Col>
<Col xs={24} md={10}>
<Card
title="班级列表"
size="small"
extra={
canCreateClass ? (
<Button size="small" onClick={() => setClassModalOpen(true)}>
+
</Button>
) : null
}
>
<Row gutter={16}>
<Col span={14}>
<div style={{ maxHeight: '60vh', overflow: 'auto' }}>
<Tree
checkable
treeData={treeData}
defaultExpandAll
showLine={{ showLeafIcon: false }}
checkedKeys={checkedKeys}
onCheck={(checked) => setCheckedKeys(checked as React.Key[])}
<List
dataSource={classes}
renderItem={(cls: ClassItem) => (
<List.Item
onClick={() => setSelectedClassId(cls.id)}
style={{
cursor: 'pointer',
background: selectedClassId === cls.id ? '#e6f4ff' : undefined,
borderRadius: 4,
padding: '8px 12px',
}}
>
<List.Item.Meta
title={cls.name}
description={`${cls.code} ${cls.classType || ''}`}
/>
</div>
</Col>
<Col span={10}>
<Card title="班级列表" size="small"
extra={<Button size="small" onClick={() => setClassModalOpen(true)}>+ </Button>}>
<List
dataSource={classes}
renderItem={(cls: ClassItem) => (
<List.Item
onClick={() => setSelectedClassId(cls.id)}
style={{
cursor: 'pointer',
background: selectedClassId === cls.id ? '#e6f4ff' : undefined,
borderRadius: 4,
padding: '8px 12px',
}}
>
<List.Item.Meta title={cls.name} description={`${cls.code} ${cls.classType || ''}`} />
</List.Item>
)}
/>
</Card>
</Col>
</Row>
</List.Item>
)}
/>
</Card>
</Col>
</Row>
{ /* Create class Modal */ }
<Modal
title="创建班级"
open={classModalOpen}
onOk={handleCreateClass}
onCancel={() => { setClassModalOpen(false); classForm.resetFields(); }}
confirmLoading={importing}
destroyOnClose
>
<Form form={classForm} layout="vertical">
<Form.Item name="name" label="班级名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="code" label="班级编码" rules={[{ required: true }]}>
<Input placeholder="如 CS2024-01" />
</Form.Item>
<Form.Item name="classType" label="班型" rules={[{ required: true }]}>
<Select options={[
{ value: 'culture', label: '文化课' },
{ value: 'professional', label: '专业课' },
{ value: 'bootcamp', label: '集训营' },
{ value: 'sprint', label: '冲刺班' },
]} />
</Form.Item>
<Form.Item name="startDate" label="开班日期">
<DatePicker style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="endDate" label="结束日期">
<DatePicker style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="maxStudents" label="最大人数">
<InputNumber min={0} style={{ width: '100%' }} placeholder="0=不限制" />
</Form.Item>
<Form.Item name="notes" label="备注">
<Input.TextArea rows={2} />
</Form.Item>
</Form>
</Modal>
</Drawer>
)}
{/* Create class Modal */}
{canCreateClass ? (
<Modal
title="确认删除钉钉全部考勤组"
open={deleteGroupsOpen}
okText="确认全部删除"
okButtonProps={{ danger: true, disabled: attendanceGroups.length === 0 }}
cancelText="取消"
confirmLoading={deletingGroups}
onOk={deleteAllGroups}
onCancel={() => setDeleteGroupsOpen(false)}
title="创建班级"
open={classModalOpen}
onOk={handleCreateClass}
onCancel={() => {
setClassModalOpen(false);
classForm.resetFields();
}}
confirmLoading={importing}
destroyOnClose
>
<Alert
type="error"
showIcon
message={`将永久删除钉钉上的 ${attendanceGroups.length} 个考勤组`}
description="本地班级和排课不会删除。删除后需在排课管理中重新同步,才能重建考勤组。"
style={{ marginBottom: 12 }}
/>
<List
size="small"
bordered
dataSource={attendanceGroups}
style={{ maxHeight: 280, overflow: 'auto' }}
renderItem={(group) => (
<List.Item>
<List.Item.Meta
title={group.group_name}
description={`ID ${group.group_id} · ${group.member_count}`}
/>
</List.Item>
)}
/>
<Form form={classForm} layout="vertical">
<Form.Item name="name" label="班级名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="code" label="班级编码" rules={[{ required: true }]}>
<Input placeholder="如 CS2024-01" />
</Form.Item>
<Form.Item name="classType" label="班型" rules={[{ required: true }]}>
<Select
options={[
{ value: 'culture', label: '文化课' },
{ value: 'professional', label: '专业课' },
{ value: 'bootcamp', label: '集训营' },
{ value: 'sprint', label: '冲刺班' },
]}
/>
</Form.Item>
<Form.Item name="startDate" label="开班日期">
<DatePicker style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="endDate" label="结束日期">
<DatePicker style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="notes" label="备注">
<Input.TextArea rows={2} />
</Form.Item>
</Form>
</Modal>
</div>
),
},
]
: [];
const tabItems = [
{
key: 'config',
label: '配置',
children: (
<Spin spinning={loading}>
{config && (
<Descriptions size="small" column={2} style={{ marginBottom: 24 }}>
<Descriptions.Item label="CorpId">{config.corpId || '-'}</Descriptions.Item>
<Descriptions.Item label="AppKey">{config.agentId || '-'}</Descriptions.Item>
<Descriptions.Item label="启用同步">
<Tag color={config.startEnable ? 'green' : 'default'}>
{config.startEnable ? '已启用' : '未启用'}
</Tag>
</Descriptions.Item>
</Descriptions>
)}
) : null}
</Drawer>
)}
<Modal
title="确认清空钉钉全部考勤组"
open={deleteGroupsOpen}
okText="确认全部清空"
okButtonProps={{ danger: true, disabled: attendanceGroups.length === 0 }}
cancelText="取消"
confirmLoading={deletingGroups}
onOk={deleteAllGroups}
onCancel={() => setDeleteGroupsOpen(false)}
>
<Alert
type="info"
message="配置钉钉应用凭证后,可使用组织架构同步、考勤导入和排班同步功能。"
style={{ marginBottom: 24 }}
type="error"
showIcon
message={`将永久清空钉钉上的 ${attendanceGroups.length} 个考勤组`}
description="本地班级和排课不会清空。清空后需在排课管理中重新同步,才能重建考勤组。"
style={{ marginBottom: 12 }}
/>
<Form form={form} layout="vertical" style={{ maxWidth: 480 }}>
<Form.Item name="corpId" label="CorpId企业ID" rules={[{ required: true, message: '请输入 CorpId' }]}>
<Input placeholder="dingxxxxxxxx" />
</Form.Item>
<Form.Item name="agentId" label="AppKey应用凭证" rules={[{ required: true, message: '请输入 AppKey' }]}>
<Input placeholder="从钉钉开放平台获取" />
</Form.Item>
<Form.Item
name="appSecret"
label="AppSecret应用密钥"
rules={[{ required: true, message: '请输入 AppSecret' }]}
extra="保存后仅返回脱敏信息,重新编辑时需再次输入完整密钥"
>
<Input.Password placeholder="从钉钉开放平台获取" />
</Form.Item>
<Form.Item name="startEnable" label="启用同步" valuePropName="checked">
<Switch />
</Form.Item>
<Space>
<PermissionButton permission="integration:trigger" type="primary" icon={<SaveOutlined />} loading={saving} onClick={handleSave}>
</PermissionButton>
<Button icon={<ApiOutlined />} loading={testing} onClick={handleTest}>
</Button>
</Space>
</Form>
</Spin>
),
},
...syncTabItems,
];
<List
size="small"
bordered
dataSource={attendanceGroups}
style={{ maxHeight: 280, overflow: 'auto' }}
renderItem={(group) => (
<List.Item>
<List.Item.Meta
title={group.group_name}
description={`ID ${group.group_id} · ${group.member_count}`}
/>
</List.Item>
)}
/>
</Modal>
</div>
) : null;
return (
<Card title="钉钉集成配置" extra={
<Space>
{verified === true && <Tag icon={<CheckCircleOutlined />} color="success"></Tag>}
{verified === false && <Tag icon={<CloseCircleOutlined />} color="error"></Tag>}
</Space>
}>
<Tabs items={tabItems} />
<Card
title="钉钉集成配置"
extra={
<Space>
{verified === true && (
<Tag icon={<CheckCircleOutlined />} color="success">
</Tag>
)}
{verified === false && (
<Tag icon={<CloseCircleOutlined />} color="error">
</Tag>
)}
</Space>
}
>
<Spin spinning={loading}>
{config && (
<Descriptions size="small" column={2} style={{ marginBottom: 24 }}>
<Descriptions.Item label="CorpId">{config.corpId || '-'}</Descriptions.Item>
<Descriptions.Item label="AppKey">{config.agentId || '-'}</Descriptions.Item>
<Descriptions.Item label="同步方式"></Descriptions.Item>
</Descriptions>
)}
<Alert
type="info"
message="配置钉钉应用凭证后,可在本页手动获取组织架构并导入用户。排班同步仍在排课管理中手动触发。"
style={{ marginBottom: 24 }}
showIcon
/>
<Form
form={form}
layout="vertical"
initialValues={initialCache.formValues}
onValuesChange={(_changed, values) => cacheDingTalkDraft(values)}
style={{ maxWidth: 520 }}
>
<Form.Item
name="corpId"
label="CorpId企业ID"
rules={[{ required: true, message: '请输入 CorpId' }]}
>
<Input placeholder="dingxxxxxxxx" />
</Form.Item>
<Form.Item
name="agentId"
label="AppKey应用凭证"
rules={[{ required: true, message: '请输入 AppKey' }]}
>
<Input placeholder="从钉钉开放平台获取" />
</Form.Item>
<Form.Item
name="appSecret"
label="AppSecret应用密钥"
rules={[
{
required: isAppSecretRequired(!!config),
message: '首次配置请输入 AppSecret',
},
]}
extra={
config
? '已保存密钥;留空保持原值,输入新值将替换原密钥'
: '首次配置需要填写完整 AppSecret'
}
>
<Input.Password placeholder={config ? '留空保持已保存的密钥' : '从钉钉开放平台获取'} />
</Form.Item>
<Space>
<PermissionButton
permission="integration:trigger"
type="primary"
icon={<SaveOutlined />}
loading={saving}
onClick={handleSave}
>
</PermissionButton>
<Button icon={<ApiOutlined />} loading={testing} onClick={handleTest}>
</Button>
</Space>
</Form>
{syncPanel && (
<>
<Divider titlePlacement="start"></Divider>
{syncPanel}
</>
)}
</Spin>
</Card>
);
};

View File

@@ -0,0 +1,39 @@
import { beforeEach, describe, expect, it } from 'vitest';
import {
cacheDingTalkDraft,
cacheDingTalkServerSnapshot,
commitDingTalkConfig,
readDingTalkConfigCache,
resetDingTalkConfigCache,
} from './integration-config-cache';
describe('DingTalk integration config page cache', () => {
beforeEach(resetDingTalkConfigCache);
it('keeps an unsaved secret when a background refresh returns', () => {
cacheDingTalkDraft({ corpId: 'draft-corp', agentId: 'draft-key', appSecret: 'draft-secret' });
cacheDingTalkServerSnapshot({ corpId: 'saved-corp', agentId: 'saved-key' }, true);
expect(readDingTalkConfigCache()).toMatchObject({
loaded: true,
dirty: true,
config: { corpId: 'saved-corp', agentId: 'saved-key' },
formValues: {
corpId: 'draft-corp',
agentId: 'draft-key',
appSecret: 'draft-secret',
},
});
});
it('clears the secret after a successful save', () => {
cacheDingTalkDraft({ corpId: 'corp', agentId: 'key', appSecret: 'secret' });
commitDingTalkConfig({ corpId: 'corp', agentId: 'key' });
expect(readDingTalkConfigCache()).toMatchObject({
loaded: true,
dirty: false,
formValues: { corpId: 'corp', agentId: 'key', appSecret: undefined },
});
});
});

View File

@@ -0,0 +1,62 @@
import type { DingTalkConfigFormValues } from './integration-config-form';
export interface DingTalkSavedConfig {
agentId: string;
corpId: string;
}
interface DingTalkConfigCache {
loaded: boolean;
config: DingTalkSavedConfig | null;
verified: boolean | null;
formValues: Partial<DingTalkConfigFormValues>;
dirty: boolean;
}
const cache: DingTalkConfigCache = {
loaded: false,
config: null,
verified: null,
formValues: {},
dirty: false,
};
export function readDingTalkConfigCache(): DingTalkConfigCache {
return {
...cache,
config: cache.config ? { ...cache.config } : null,
formValues: { ...cache.formValues },
};
}
export function cacheDingTalkDraft(values: Partial<DingTalkConfigFormValues>): void {
cache.formValues = { ...values };
cache.dirty = true;
}
export function cacheDingTalkServerSnapshot(
config: DingTalkSavedConfig | null,
verified: boolean | null,
): void {
cache.loaded = true;
cache.config = config ? { ...config } : null;
cache.verified = verified;
if (!cache.dirty) {
cache.formValues = config ? { ...config, appSecret: undefined } : {};
}
}
export function commitDingTalkConfig(config: DingTalkSavedConfig): void {
cache.loaded = true;
cache.config = { ...config };
cache.formValues = { ...config, appSecret: undefined };
cache.dirty = false;
}
export function resetDingTalkConfigCache(): void {
cache.loaded = false;
cache.config = null;
cache.verified = null;
cache.formValues = {};
cache.dirty = false;
}

View File

@@ -0,0 +1,23 @@
import { describe, expect, it } from 'vitest';
import { buildDingTalkConfigPayload, isAppSecretRequired } from './integration-config-form';
describe('DingTalk integration config form', () => {
it('requires AppSecret only for the first configuration', () => {
expect(isAppSecretRequired(false)).toBe(true);
expect(isAppSecretRequired(true)).toBe(false);
});
it('builds a manual-sync config without the retired startEnable flag', () => {
expect(
buildDingTalkConfigPayload({
corpId: 'ding-corp',
agentId: 'app-key',
appSecret: '',
}),
).toEqual({
corpId: 'ding-corp',
agentId: 'app-key',
appSecret: undefined,
});
});
});

View File

@@ -0,0 +1,13 @@
export interface DingTalkConfigFormValues {
agentId: string;
appSecret?: string;
corpId: string;
}
export const isAppSecretRequired = (hasSavedConfig: boolean) => !hasSavedConfig;
export const buildDingTalkConfigPayload = (values: DingTalkConfigFormValues) => ({
corpId: values.corpId.trim(),
agentId: values.agentId.trim(),
appSecret: values.appSecret?.trim() || undefined,
});

View File

@@ -4,7 +4,7 @@ import { Form, Input, Button, Card, Typography } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import api from '../../api';
import { message } from '../../ui/app-message';
import { writePermissions } from '../../auth/permission-store';
import { clearPermissions, writePermissions } from '../../auth/permission-store';
import { findRoleAwareLandingPath } from '../../auth/menu-policy';
const { Title } = Typography;
@@ -13,22 +13,28 @@ const LoginPage: React.FC = () => {
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const onFinish = useCallback(async (values: any) => {
setLoading(true);
try {
const res: any = await api.post('/auth/login', values);
localStorage.setItem('token', res.access_token);
localStorage.setItem('user', JSON.stringify(res.user));
const permissions = res.user.permissions || [];
writePermissions(permissions);
message.success('登录成功');
navigate(findRoleAwareLandingPath(res.user.roles || [], permissions) || '/', { replace: true });
} catch (err: any) {
message.error(err?.message || '登录失败');
} finally {
setLoading(false);
}
}, [navigate]);
const onFinish = useCallback(
async (values: any) => {
clearPermissions();
setLoading(true);
try {
const res: any = await api.post('/auth/login', values);
localStorage.setItem('token', res.access_token);
localStorage.setItem('user', JSON.stringify(res.user));
const permissions = res.user.permissions || [];
writePermissions(permissions);
message.success('登录成功');
navigate(findRoleAwareLandingPath(res.user.roles || [], permissions) || '/', {
replace: true,
});
} catch (err: any) {
message.error(err?.message || '登录失败');
} finally {
setLoading(false);
}
},
[navigate],
);
return (
<div
@@ -51,16 +57,28 @@ const LoginPage: React.FC = () => {
>
<div style={{ textAlign: 'center', marginBottom: 32 }}>
<Title level={3} style={{ margin: 0, fontWeight: 600, color: '#1d1d1f' }}>
</Title>
<p style={{ color: '#86868b', marginTop: 8 }}></p>
<p style={{ color: '#86868b', marginTop: 8 }}></p>
</div>
<Form name="login" onFinish={onFinish} size="large">
<Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名' }]}>
<Input prefix={<UserOutlined />} placeholder="用户名" />
<Form name="login" layout="vertical" onFinish={onFinish} size="large">
<Form.Item
label="用户名"
name="username"
rules={[{ required: true, message: '请输入用户名' }]}
>
<Input prefix={<UserOutlined />} placeholder="用户名" autoComplete="username" />
</Form.Item>
<Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码' }]}>
<Input.Password prefix={<LockOutlined />} placeholder="密码" />
<Form.Item
label="密码"
name="password"
rules={[{ required: true, message: '请输入密码' }]}
>
<Input.Password
prefix={<LockOutlined />}
placeholder="密码"
autoComplete="current-password"
/>
</Form.Item>
<Form.Item>
<Button

View File

@@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react';
import { List, Typography, Menu, Layout, Button, Empty, Spin, Space } from 'antd';
import { List, Typography, Menu, Layout, Button, Empty, Spin, Space, Grid, Select } from 'antd';
import {
BellOutlined,
DollarOutlined,
@@ -10,8 +10,10 @@ import {
import { useNavigate } from 'react-router-dom';
import api from '../../api';
import { message } from '../../ui/app-message';
import { formatNotificationText } from '../../utils/notification-display';
const { Sider, Content } = Layout;
const { useBreakpoint } = Grid;
interface NotificationItem {
id: number;
@@ -48,6 +50,8 @@ function timeAgo(dateStr: string): string {
}
const NotificationsPage: React.FC = () => {
const screens = useBreakpoint();
const isMobile = !screens.sm;
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
const [filter, setFilter] = useState('all');
const [loading, setLoading] = useState(false);
@@ -56,7 +60,7 @@ const NotificationsPage: React.FC = () => {
const fetchData = async () => {
setLoading(true);
try {
const data = await api.get('/notifications?limit=50') as unknown as NotificationItem[];
const data = (await api.get('/notifications?limit=50')) as unknown as NotificationItem[];
setNotifications(data);
} catch (e: any) {
console.error('加载通知失败', e);
@@ -87,40 +91,51 @@ const NotificationsPage: React.FC = () => {
const handleMarkAll = async () => {
try {
await api.put('/notifications/read-all');
setNotifications((prev) =>
prev.map((n) => ({ ...n, isRead: true })),
);
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
} catch (e: any) {
console.error('全部已读失败', e);
message.error(e?.message || '操作失败');
}
};
const filtered = filter === 'all'
? notifications
: notifications.filter((n) => n.type === filter);
const filtered =
filter === 'all' ? notifications : notifications.filter((n) => n.type === filter);
const filterItems = [
{ key: 'all', icon: <BellOutlined />, label: '全部' },
{ key: 'bill_generated', icon: <DollarOutlined />, label: '账单' },
{ key: 'check_in', icon: <HomeOutlined />, label: '入住' },
{ key: 'class_change', icon: <TeamOutlined />, label: '班级' },
{ key: 'announcement', icon: <SettingOutlined />, label: '公告' },
];
return (
<Layout style={{ minHeight: '100%', background: '#fff' }}>
<Sider width={180} style={{ background: '#fff', borderRight: '1px solid #f0f0f0' }}>
<Menu
mode="inline"
selectedKeys={[filter]}
onClick={({ key }) => setFilter(key)}
items={[
{ key: 'all', icon: <BellOutlined />, label: '全部' },
{ key: 'bill_generated', icon: <DollarOutlined />, label: '账单' },
{ key: 'check_in', icon: <HomeOutlined />, label: '入住' },
{ key: 'class_change', icon: <TeamOutlined />, label: '班级' },
{ key: 'announcement', icon: <SettingOutlined />, label: '公告' },
]}
/>
</Sider>
<Content style={{ padding: 24 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
<Typography.Title level={4} style={{ margin: 0 }}></Typography.Title>
<Layout className="notifications-layout" style={{ minHeight: '100%', background: '#fff' }}>
{!isMobile && (
<Sider width={180} style={{ background: '#fff', borderRight: '1px solid #f0f0f0' }}>
<Menu
mode="inline"
selectedKeys={[filter]}
onClick={({ key }) => setFilter(key)}
items={filterItems}
/>
</Sider>
)}
<Content className="notifications-content" style={{ padding: isMobile ? 0 : 24 }}>
<div className="notifications-header">
<Typography.Title level={4} style={{ margin: 0 }}>
</Typography.Title>
<Button onClick={handleMarkAll}></Button>
</div>
{isMobile && (
<Select
value={filter}
onChange={setFilter}
options={filterItems.map((item) => ({ value: item.key, label: item.label }))}
className="notifications-filter"
/>
)}
<Spin spinning={loading}>
{filtered.length === 0 ? (
<Empty description="暂无通知" />
@@ -164,12 +179,9 @@ const NotificationsPage: React.FC = () => {
</div>
}
title={
<Space>
<Typography.Text
strong={!item.isRead}
style={{ fontSize: 15 }}
>
{item.title}
<Space wrap size={[8, 2]}>
<Typography.Text strong={!item.isRead} style={{ fontSize: 15 }}>
{formatNotificationText(item.title)}
</Typography.Text>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
{timeAgo(item.createdAt)}
@@ -183,7 +195,7 @@ const NotificationsPage: React.FC = () => {
ellipsis={{ rows: 1 }}
style={{ marginBottom: 0 }}
>
{item.content}
{formatNotificationText(item.content)}
</Typography.Paragraph>
)
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,75 @@
import { describe, expect, it } from 'vitest';
import dayjs from 'dayjs';
import { buildCheckInPayload, buildTransferPayload } from './occupancy-form';
describe('occupancy check-in form', () => {
it('submits all required manual check-in fields with defaults', () => {
expect(
buildCheckInPayload({
studentId: 1,
roomId: 2,
checkInDate: dayjs('2026-07-18'),
billingStartDate: dayjs('2026-07-18'),
stayType: 'short',
collectDeposit: true,
depositAmount: 500,
bedId: 3,
notes: ' 备注 ',
}),
).toEqual({
studentId: 1,
roomId: 2,
checkInDate: '2026-07-18',
billingStartDate: '2026-07-18',
stayType: 'short',
collectDeposit: true,
depositAmount: 500,
notes: '备注',
bedId: 3,
lockerId: undefined,
});
});
it('falls back to check-in date and short stay type', () => {
expect(
buildCheckInPayload({
studentId: 1,
roomId: 2,
checkInDate: dayjs('2026-07-18'),
collectDeposit: false,
bedId: 3,
}),
).toEqual(
expect.objectContaining({
billingStartDate: '2026-07-18',
stayType: 'short',
collectDeposit: false,
depositAmount: undefined,
}),
);
});
});
describe('occupancy transfer form', () => {
it('submits the target room resources with the transfer dates', () => {
expect(
buildTransferPayload({
newRoomId: 5,
newBedId: 12,
newLockerId: 18,
transferDate: dayjs('2026-07-13'),
oldBillingEndDate: dayjs('2026-07-13'),
newBillingStartDate: dayjs('2026-07-14'),
reason: '调整宿舍',
}),
).toEqual({
newRoomId: 5,
newBedId: 12,
newLockerId: 18,
transferDate: '2026-07-13',
oldBillingEndDate: '2026-07-13',
newBillingStartDate: '2026-07-14',
reason: '调整宿舍',
});
});
});

View File

@@ -0,0 +1,50 @@
import type { Dayjs } from 'dayjs';
export interface CheckInFormValues {
studentId: number;
roomId: number;
checkInDate: Dayjs;
billingStartDate?: Dayjs;
stayType?: string;
collectDeposit?: boolean;
depositAmount?: number;
notes?: string;
bedId: number;
lockerId?: number;
}
export const buildCheckInPayload = (values: CheckInFormValues) => {
const collectDeposit = values.collectDeposit ?? false;
return {
studentId: values.studentId,
roomId: values.roomId,
checkInDate: values.checkInDate.format('YYYY-MM-DD'),
billingStartDate: (values.billingStartDate || values.checkInDate).format('YYYY-MM-DD'),
stayType: values.stayType || 'short',
collectDeposit,
depositAmount: collectDeposit ? values.depositAmount ?? 500 : undefined,
notes: values.notes?.trim() || undefined,
bedId: values.bedId,
lockerId: values.lockerId || undefined,
};
};
export interface TransferFormValues {
newRoomId: number;
newBedId: number;
newLockerId?: number;
transferDate: Dayjs;
oldBillingEndDate?: Dayjs;
newBillingStartDate?: Dayjs;
reason?: string;
}
export const buildTransferPayload = (values: TransferFormValues) => ({
newRoomId: values.newRoomId,
newBedId: values.newBedId,
newLockerId: values.newLockerId || undefined,
transferDate: values.transferDate.format('YYYY-MM-DD'),
oldBillingEndDate: values.oldBillingEndDate?.format('YYYY-MM-DD'),
newBillingStartDate: values.newBillingStartDate?.format('YYYY-MM-DD'),
reason: values.reason,
});

View File

@@ -26,13 +26,14 @@ const OperationLogsPage: React.FC = () => {
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [filterModule, setFilterModule] = useState<string | undefined>();
const [dateRange, setDateRange] = useState<[string, string] | null>(null);
const fetchData = useCallback(async () => {
setLoading(true);
try {
const params: any = { page, pageSize: 20 };
const params: any = { page, pageSize };
if (filterModule) params.module = filterModule;
if (dateRange) {
params.startDate = dateRange[0];
@@ -46,69 +47,73 @@ const OperationLogsPage: React.FC = () => {
message.error(err?.message || '加载失败,请稍后重试');
}
setLoading(false);
}, [page, filterModule, dateRange]);
}, [page, pageSize, filterModule, dateRange]);
useEffect(() => {
fetchData();
}, [fetchData]);
const columns = useMemo(() => [
{
title: '时间',
dataIndex: 'createdAt',
width: 170,
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm:ss'),
},
{ title: '操作人', dataIndex: 'username', width: 100 },
{
title: '模块',
dataIndex: 'module',
width: 100,
render: (v: string) => <Tag color={moduleColorMap[v] || 'default'}>{v}</Tag>,
},
{ title: '操作', dataIndex: 'action', width: 150 },
{
title: '状态',
dataIndex: 'status',
width: 80,
render: (v: string) => {
const s = statusMap[v] || statusMap['success'];
return <Tag color={s.color}>{s.text}</Tag>;
const columns = useMemo(
() => [
{
title: '时间',
dataIndex: 'createdAt',
width: 170,
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm:ss'),
},
},
{
title: '详情', width: 200,
dataIndex: 'detail',
ellipsis: true,
render: (v: string) =>
v ? (
<Tooltip title={v}>
<span>{v}</span>
</Tooltip>
) : (
'-'
),
},
{ title: 'IP地址', dataIndex: 'ipAddress', width: 130, render: (v: string) => v || '-' },
{
title: '终端',
dataIndex: 'userAgent',
width: 120,
ellipsis: true,
render: (v: string) => {
if (!v) return '-';
if (v.includes('Mobile')) return <Tag color="blue"></Tag>;
if (v.includes('Windows')) return <Tag>Windows</Tag>;
if (v.includes('Mac')) return <Tag>Mac</Tag>;
if (v.includes('Linux')) return <Tag>Linux</Tag>;
return (
<Tooltip title={v}>
<Tag></Tag>
</Tooltip>
);
{ title: '操作人', dataIndex: 'username', width: 100 },
{
title: '模块',
dataIndex: 'module',
width: 100,
render: (v: string) => <Tag color={moduleColorMap[v] || 'default'}>{v}</Tag>,
},
},
], []);
{ title: '操作', dataIndex: 'action', width: 150 },
{
title: '状态',
dataIndex: 'status',
width: 80,
render: (v: string) => {
const s = statusMap[v] || statusMap['success'];
return <Tag color={s.color}>{s.text}</Tag>;
},
},
{
title: '详情',
width: 200,
dataIndex: 'detail',
ellipsis: true,
render: (v: string) =>
v ? (
<Tooltip title={v}>
<span>{v}</span>
</Tooltip>
) : (
'-'
),
},
{ title: 'IP地址', dataIndex: 'ipAddress', width: 130, render: (v: string) => v || '-' },
{
title: '终端',
dataIndex: 'userAgent',
width: 120,
ellipsis: true,
render: (v: string) => {
if (!v) return '-';
if (v.includes('Mobile')) return <Tag color="blue"></Tag>;
if (v.includes('Windows')) return <Tag>Windows</Tag>;
if (v.includes('Mac')) return <Tag>Mac</Tag>;
if (v.includes('Linux')) return <Tag>Linux</Tag>;
return (
<Tooltip title={v}>
<Tag></Tag>
</Tooltip>
);
},
},
],
[],
);
return (
<div>
@@ -159,8 +164,13 @@ const OperationLogsPage: React.FC = () => {
pagination={{
current: page,
total,
pageSize: 20,
onChange: setPage,
pageSize,
showSizeChanger: true,
pageSizeOptions: [20, 50, 100],
onChange: (nextPage, nextPageSize) => {
setPage(nextPage);
setPageSize(nextPageSize);
},
showTotal: (t) => `${t}`,
}}
/>

View File

@@ -1,8 +1,9 @@
import React, { useEffect, useMemo, useState } from 'react';
import { Alert, Empty, Form, Input, Modal, Popconfirm, Select, Space, Table, Tag } from 'antd';
import { BankOutlined, InboxOutlined, PlusOutlined } from '@ant-design/icons';
import { BankOutlined, InboxOutlined, PlusOutlined, UndoOutlined } from '@ant-design/icons';
import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell';
import { message } from '../../ui/app-message';
const PRESET_COLORS = [
@@ -93,46 +94,108 @@ const OrganizationsPage: React.FC = () => {
}
};
const saveCell = async (record: OrganizationItem, field: string, value: unknown) => {
await api.put(`/organizations/${record.id}`, { [field]: value });
message.success('已保存');
await fetchData();
};
const columns = [
{
title: '机构',
dataIndex: 'name',
width: 220,
render: (name: string, record: OrganizationItem) => (
<Space>
<span
style={{
width: 10,
height: 10,
borderRadius: '50%',
background: record.color || '#8c8c8c',
}}
/>
<strong>{name}</strong>
{record.isHost ? (
<Tag color="blue" icon={<BankOutlined />}>
</Tag>
) : (
<Tag></Tag>
)}
</Space>
<EditableCell
value={name}
required
permission="organization:edit"
disabled={record.status === 'archived'}
onSave={(next) => saveCell(record, 'name', next)}
>
<Space>
<span
style={{
width: 10,
height: 10,
borderRadius: '50%',
background: record.color || '#8c8c8c',
}}
/>
<strong>{name}</strong>
{record.isHost ? (
<Tag color="blue" icon={<BankOutlined />}>
</Tag>
) : (
<Tag></Tag>
)}
</Space>
</EditableCell>
),
},
{
title: '机构编码',
dataIndex: 'code',
width: 130,
render: (value: string) => <code>{value}</code>,
render: (value: string, record: OrganizationItem) => (
<EditableCell
value={value}
required
permission="organization:edit"
disabled={record.status === 'archived'}
onSave={(next) => saveCell(record, 'code', next)}
>
<code>{value}</code>
</EditableCell>
),
},
{
title: '联系人',
dataIndex: 'contactName',
width: 120,
render: (value?: string) => value || '-',
render: (value: string | undefined, record: OrganizationItem) => (
<EditableCell
value={value}
permission="organization:edit"
disabled={record.status === 'archived'}
onSave={(next) => saveCell(record, 'contactName', next)}
>
{value || '-'}
</EditableCell>
),
},
{
title: '电话',
dataIndex: 'phone',
width: 140,
render: (value: string | undefined, record: OrganizationItem) => (
<EditableCell
value={value}
permission="organization:edit"
disabled={record.status === 'archived'}
onSave={(next) => saveCell(record, 'phone', next)}
>
{value || '-'}
</EditableCell>
),
},
{
title: '备注',
dataIndex: 'notes',
ellipsis: true,
render: (value: string | undefined, record: OrganizationItem) => (
<EditableCell
value={value}
editor="textarea"
permission="organization:edit"
disabled={record.status === 'archived'}
onSave={(next) => saveCell(record, 'notes', next)}
>
{value || '-'}
</EditableCell>
),
},
{ title: '电话', dataIndex: 'phone', width: 140, render: (value?: string) => value || '-' },
{ title: '备注', dataIndex: 'notes', ellipsis: true, render: (value?: string) => value || '-' },
{
title: '状态',
dataIndex: 'status',
@@ -148,35 +211,61 @@ const OrganizationsPage: React.FC = () => {
width: 160,
render: (_: unknown, record: OrganizationItem) => (
<Space>
<PermissionButton
permission="organization:edit"
size="small"
onClick={() => openEditor(record)}
>
</PermissionButton>
{!record.isHost && record.status === 'active' ? (
{record.status === 'archived' ? (
<Popconfirm
title="归档后仍保留历史学生、入住和租赁记录"
title="确定恢复此机构?"
onConfirm={async () => {
try {
await api.delete(`/organizations/${record.id}`);
message.success('机构已归档');
await api.put(`/organizations/${record.id}`, { status: 'active' });
message.success('机构已恢复');
await fetchData();
} catch (error: any) {
message.error(error?.message || '归档失败');
message.error(error?.message || '恢复失败');
}
}}
>
<PermissionButton
permission="organization:delete"
permission="organization:edit"
size="small"
icon={<InboxOutlined />}
type="link"
icon={<UndoOutlined />}
>
</PermissionButton>
</Popconfirm>
) : null}
) : (
<>
<PermissionButton
permission="organization:edit"
size="small"
onClick={() => openEditor(record)}
>
</PermissionButton>
{!record.isHost ? (
<Popconfirm
title="归档后仍保留历史学生、入住和租赁记录"
onConfirm={async () => {
try {
await api.delete(`/organizations/${record.id}`);
message.success('机构已归档');
await fetchData();
} catch (error: any) {
message.error(error?.message || '归档失败');
}
}}
>
<PermissionButton
permission="organization:delete"
size="small"
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
) : null}
</>
)}
</Space>
),
},
@@ -235,7 +324,12 @@ const OrganizationsPage: React.FC = () => {
loading={loading}
locale={{ emptyText: <Empty description="暂无机构" /> }}
scroll={{ x: 1100 }}
pagination={{ pageSize: 20, showTotal: (total) => `${total} 个机构` }}
pagination={{
defaultPageSize: 20,
showSizeChanger: true,
pageSizeOptions: [20, 50, 100],
showTotal: (total) => `${total} 个机构`,
}}
/>
<Modal
title={editing ? `编辑机构 · ${editing.name}` : '添加外部机构'}

View File

@@ -37,14 +37,11 @@ const PermissionsPage: React.FC = () => {
class: '班级管理',
schedule: '排课管理',
attendance: '考勤管理',
learning: '学习记录',
exam: '考试管理',
sync: '数据同步',
integration: '集成配置',
department: '部门管理',
notification: '通知中心',
profile: '个人资料',
ai: 'AI 模型配置',
'ai-chat': 'AI 助手',
};
useEffect(() => {

View File

@@ -1,19 +1,9 @@
import React, { useEffect, useState, useMemo, useCallback } from 'react';
import {
Table,
Modal,
Form,
Input,
Space,
Tag,
Popconfirm,
Card,
Checkbox,
Empty,
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { Table, Modal, Form, Input, Space, Tag, Popconfirm, Card, Checkbox, Empty } from 'antd';
import { PlusOutlined, EditOutlined, StopOutlined } from '@ant-design/icons';
import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell';
import { message } from '../../ui/app-message';
interface PermissionItem {
@@ -106,79 +96,153 @@ const RolesPage: React.FC = () => {
}
};
const handleDelete = async (id: number) => {
const handleDisable = async (id: number) => {
try {
await api.delete(`/rbac/roles/${id}`);
message.success('角色已删除');
message.success('角色已停用');
fetchData();
} catch (e: any) {
message.error(e.message || '删除失败');
message.error(e.message || '停用失败');
}
};
const groupNames: Record<string, string> = {
dashboard: '数据面板',
notification: '通知中心',
student: '学生管理',
'student-scope': '学生范围权限',
teacher: '教师管理',
'teacher-workspace': '教师工作台',
room: '宿舍管理',
occupancy: '入住管理',
expense: '费用管理',
bill: '账单管理',
deposit: '押金管理',
wallet: '学生余额',
classroom: '教室管理',
organization: '机构管理',
rental: '租赁订单',
class: '班级管理',
schedule: '排课管理',
attendance: '考勤管理',
'attendance-scope': '考勤范围权限',
log: '操作日志',
user: '用户管理',
role: '角色管理',
sync: '数据同步',
integration: '集成配置',
ai: 'AI 配置',
'ai-chat': 'AI 助手',
};
const columns = useMemo(() => [
{ title: 'ID', dataIndex: 'id', width: 80 },
{ title: '名称', dataIndex: 'name', width: 120 },
{ title: '描述', dataIndex: 'description', width: 200 },
{
title: '权限标签',
dataIndex: 'permissions',
width: 150,
render: (perms: PermissionItem[]) =>
perms?.length > 0 ? (
<Tag color="blue">{perms.length} </Tag>
) : (
<Tag color="default"></Tag>
),
const permissionOptions = useMemo(
() =>
allPerms
.flatMap((group) => group.permissions)
.map((item) => ({ value: item.id, label: `${item.group} · ${item.name}` })),
[allPerms],
);
const saveCell = useCallback(
async (record: RoleItem, field: string, value: unknown) => {
await api.put(`/rbac/roles/${record.id}`, { [field]: value });
message.success('已保存');
await fetchData();
},
{
title: '系统',
dataIndex: 'isSystem',
width: 80,
render: (v: boolean) => (v ? <Tag color="orange"></Tag> : null),
},
{
title: '操作',
width: 180,
fixed: 'right' as const,
render: (_: any, record: RoleItem) => (
<Space>
<PermissionButton
[fetchData],
);
const columns = useMemo(
() => [
{ title: 'ID', dataIndex: 'id', width: 80 },
{
title: '名称',
dataIndex: 'name',
width: 120,
render: (v: string, r: RoleItem) => (
<EditableCell
value={v}
required
permission="role:edit"
type="link"
size="small"
icon={<EditOutlined />}
onClick={() => handleEdit(record)}
onSave={(next) => saveCell(r, 'name', next)}
>
</PermissionButton>
{!record.isSystem && (
<Popconfirm title="确认删除该角色?" onConfirm={() => handleDelete(record.id)}>
<PermissionButton permission="role:delete" type="link" size="small" danger icon={<DeleteOutlined />}>
</PermissionButton>
</Popconfirm>
)}
</Space>
),
},
], []);
{v}
</EditableCell>
),
},
{
title: '描述',
dataIndex: 'description',
width: 200,
render: (v: string, r: RoleItem) => (
<EditableCell
value={v}
editor="textarea"
permission="role:edit"
onSave={(next) => saveCell(r, 'description', next)}
>
{v || '-'}
</EditableCell>
),
},
{
title: '权限标签',
dataIndex: 'permissions',
width: 150,
render: (perms: PermissionItem[], record: RoleItem) => (
<EditableCell
value={perms?.map((item) => item.id) || []}
editor="multi-select"
options={permissionOptions}
permission="role:edit"
onSave={(next) => saveCell(record, 'permissionIds', next)}
>
{perms?.length > 0 ? (
<Tag color="blue">{perms.length} </Tag>
) : (
<Tag color="default"></Tag>
)}
</EditableCell>
),
},
{
title: '系统',
dataIndex: 'isSystem',
width: 80,
render: (v: boolean) => (v ? <Tag color="orange"></Tag> : null),
},
{
title: '操作',
width: 180,
fixed: 'right' as const,
render: (_: any, record: RoleItem) => (
<Space>
<PermissionButton
permission="role:edit"
type="link"
size="small"
icon={<EditOutlined />}
onClick={() => handleEdit(record)}
>
</PermissionButton>
{!record.isSystem && (
<Popconfirm title="确认停用该角色?" onConfirm={() => handleDisable(record.id)}>
<PermissionButton
permission="role:delete"
type="link"
size="small"
icon={<StopOutlined />}
>
</PermissionButton>
</Popconfirm>
)}
</Space>
),
},
],
[permissionOptions, saveCell],
);
const handleGroupCheckAll = (group: string, checked: boolean) => {
const groupPermIds =

View File

@@ -1,18 +1,50 @@
import React, { useEffect, useState, useCallback } from 'react';
import { Row, Col, Card, Tag, Select, Statistic, Modal, Spin, Badge, Tooltip, DatePicker, Alert, Button } from 'antd';
import { HomeOutlined, UserOutlined, CalendarOutlined, BankOutlined, HistoryOutlined, ShopOutlined } from '@ant-design/icons';
import {
Row,
Col,
Card,
Tag,
Select,
Statistic,
Modal,
Spin,
Badge,
Tooltip,
DatePicker,
Alert,
Button,
Switch,
Space,
} from 'antd';
import {
HomeOutlined,
UserOutlined,
CalendarOutlined,
BankOutlined,
HistoryOutlined,
ShopOutlined,
CheckCircleOutlined,
SaveOutlined,
} from '@ant-design/icons';
import dayjs, { Dayjs } from 'dayjs';
import api from '../../api';
import { message } from '../../ui/app-message';
import PermissionButton from '../../components/PermissionButton';
import { usePermission } from '../../hooks/usePermission';
import { getInitialPresentOccupancyIds, togglePresentOccupancy } from './inspection-state';
function getCardStyle(room: any): React.CSSProperties {
let base: React.CSSProperties;
if (room.status === 'maintenance') base = { background: '#f5f5f5', borderColor: '#d9d9d9' };
else if (room.currentCount === 0) base = { background: '#f6ffed', borderColor: '#b7eb8f' };
else if (room.currentCount >= room.capacity) base = { background: '#fff2f0', borderColor: '#ffccc7' };
else if (room.currentCount >= room.capacity)
base = { background: '#fff2f0', borderColor: '#ffccc7' };
else base = { background: '#e6f4ff', borderColor: '#91caff' };
if (room.organizationColor) {
return { ...base, background: `color-mix(in srgb, ${room.organizationColor} 15%, ${base.background || '#fff'} 85%)` };
return {
...base,
background: `color-mix(in srgb, ${room.organizationColor} 15%, ${base.background || '#fff'} 85%)`,
};
}
return base;
}
@@ -29,7 +61,10 @@ function getOrganizationTags(occupants: any[]) {
...new Map(
occupants
.filter((o: any) => o.organizationName)
.map((o: any) => [o.organizationId, { name: o.organizationName, color: o.organizationColor }]),
.map((o: any) => [
o.organizationId,
{ name: o.organizationName, color: o.organizationColor },
]),
).values(),
] as { name: string; color: string | null }[];
if (organizationList.length === 0) return null;
@@ -56,6 +91,9 @@ const RoomVisualPage: React.FC = () => {
const [selectedOrganization, setSelectedOrganization] = useState<number | 'all'>('all');
const [detailRoom, setDetailRoom] = useState<any>(null);
const [asOf, setAsOf] = useState<Dayjs | null>(null);
const [presentOccupancyIds, setPresentOccupancyIds] = useState<number[]>([]);
const [inspectionSaving, setInspectionSaving] = useState(false);
const { hasPermission } = usePermission();
const isHistorical = !!asOf && !asOf.isSame(dayjs(), 'day');
@@ -76,11 +114,48 @@ const RoomVisualPage: React.FC = () => {
fetchData();
}, [fetchData]);
useEffect(() => {
if (!detailRoom) {
setPresentOccupancyIds([]);
return;
}
setPresentOccupancyIds(
getInitialPresentOccupancyIds(
detailRoom.occupants || [],
detailRoom.inspection?.submitted === true,
),
);
}, [detailRoom]);
const inspectionDate = (asOf || dayjs()).format('YYYY-MM-DD');
const submitInspection = async () => {
if (!detailRoom || isHistorical) return;
setInspectionSaving(true);
try {
await api.put(`/rooms/${detailRoom.id}/inspections/${inspectionDate}`, {
presentOccupancyIds,
});
message.success(detailRoom.inspection?.submitted ? '查寝记录已更新' : '查寝已提交');
const params = isHistorical ? { asOf: inspectionDate } : undefined;
const res: any = await api.get('/rooms/visual', { params });
setData(res);
const updatedRoom = res.rooms.find((room: any) => room.id === detailRoom.id);
if (updatedRoom) setDetailRoom(updatedRoom);
} catch (e: unknown) {
const err = e as { message?: string };
message.error(err?.message || '查寝提交失败');
} finally {
setInspectionSaving(false);
}
};
if (!data) return <Spin size="large" style={{ display: 'block', margin: '100px auto' }} />;
const rooms = data.rooms.filter((r: any) => {
if (selectedBuilding !== 'all' && r.building !== selectedBuilding) return false;
if (selectedOrganization !== 'all' && !(r.organizationIds || []).includes(selectedOrganization)) return false;
if (selectedOrganization !== 'all' && !(r.organizationIds || []).includes(selectedOrganization))
return false;
return true;
});
@@ -138,7 +213,15 @@ const RoomVisualPage: React.FC = () => {
label: (
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
{t.color && (
<span style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: t.color, display: 'inline-block' }} />
<span
style={{
width: 8,
height: 8,
borderRadius: '50%',
backgroundColor: t.color,
display: 'inline-block',
}}
/>
)}
{t.name}
</span>
@@ -175,17 +258,29 @@ const RoomVisualPage: React.FC = () => {
</Col>
<Col xs={12} sm={6}>
<Card size="small">
<Statistic title="空闲房间" value={emptyRooms} styles={{ value: { color: '#34C759' } }} />
<Statistic
title="空闲房间"
value={emptyRooms}
styles={{ value: { color: '#34C759' } }}
/>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card size="small">
<Statistic title="可安排床位" value={availableBedsCount} styles={{ value: { color: '#007AFF' } }} />
<Statistic
title="可安排床位"
value={availableBedsCount}
styles={{ value: { color: '#007AFF' } }}
/>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card size="small">
<Statistic title="满员房间" value={fullRooms} styles={{ value: { color: '#FF3B30' } }} />
<Statistic
title="满员房间"
value={fullRooms}
styles={{ value: { color: '#FF3B30' } }}
/>
</Card>
</Col>
</Row>
@@ -214,13 +309,27 @@ const RoomVisualPage: React.FC = () => {
marginBottom: 8,
}}
>
<span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 16, fontWeight: 600, color: '#1d1d1f' }}>
<span
style={{
display: 'flex',
alignItems: 'center',
gap: 6,
fontSize: 16,
fontWeight: 600,
color: '#1d1d1f',
}}
>
{room.organizationColor && (
<span style={{
width: 10, height: 10, borderRadius: '50%',
backgroundColor: room.organizationColor, display: 'inline-block',
flexShrink: 0,
}} />
<span
style={{
width: 10,
height: 10,
borderRadius: '50%',
backgroundColor: room.organizationColor,
display: 'inline-block',
flexShrink: 0,
}}
/>
)}
{room.roomNumber}
</span>
@@ -231,7 +340,13 @@ const RoomVisualPage: React.FC = () => {
{room.floor && <span>{room.floor}F</span>}
</div>
{room.totalBeds > 0 && (
<div style={{ fontSize: 12, color: room.occupiedBeds >= room.totalBeds ? '#FF3B30' : '#34C759', marginBottom: 6 }}>
<div
style={{
fontSize: 12,
color: room.occupiedBeds >= room.totalBeds ? '#FF3B30' : '#34C759',
marginBottom: 6,
}}
>
: {room.occupiedBeds}/{room.totalBeds}
</div>
)}
@@ -259,10 +374,16 @@ const RoomVisualPage: React.FC = () => {
)}
{getOrganizationTags(room.occupants)}
{room.occupants.length > 0 && (
<div className="room-card-tag-wrapper" style={{ borderTop: '1px solid rgba(0,0,0,0.06)', paddingTop: 6 }}>
<div
className="room-card-tag-wrapper"
style={{ borderTop: '1px solid rgba(0,0,0,0.06)', paddingTop: 6 }}
>
{room.occupants.slice(0, 4).map((o: any) => (
<Tooltip key={o.studentId} title={`入住 ${o.days} 天 (${o.checkInDate} 起)`}>
<Tag style={{ margin: '0 4px 4px 0', fontSize: 12, maxWidth: '100%' }} icon={<UserOutlined />}>
<Tag
style={{ margin: '0 4px 4px 0', fontSize: 12, maxWidth: '100%' }}
icon={<UserOutlined />}
>
{o.studentName}
</Tag>
</Tooltip>
@@ -270,6 +391,17 @@ const RoomVisualPage: React.FC = () => {
{room.occupants.length > 4 && <Tag>+{room.occupants.length - 4}</Tag>}
</div>
)}
{room.occupants.length > 0 && (
<div style={{ marginTop: 4 }}>
{room.inspection?.submitted ? (
<Tag color={room.inspection.source === 'automatic' ? 'orange' : 'green'}>
{room.inspection.source === 'automatic' ? '自动补记' : '已查寝'}
</Tag>
) : (
<Tag></Tag>
)}
</div>
)}
</Card>
</Col>
))}
@@ -313,9 +445,30 @@ const RoomVisualPage: React.FC = () => {
<div style={{ marginBottom: 16 }}>{getStatusLabel(detailRoom)}</div>
{detailRoom.occupants.length > 0 ? (
<div>
<h4 style={{ marginBottom: 8 }}></h4>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
gap: 12,
marginBottom: 8,
flexWrap: 'wrap',
}}
>
<h4 style={{ margin: 0 }}></h4>
{detailRoom.inspection?.submitted && (
<Tag color={detailRoom.inspection.source === 'automatic' ? 'orange' : 'green'}>
{detailRoom.inspection.source === 'automatic' ? '自动补记' : '已提交'} ·{' '}
{detailRoom.inspection.inspectorName}
</Tag>
)}
</div>
{detailRoom.occupants.map((o: any) => (
<Card key={o.studentId} size="small" style={{ marginBottom: 8, borderRadius: 8 }}>
<Card
key={o.occupancyId}
size="small"
style={{ marginBottom: 8, borderRadius: 8 }}
>
<div
style={{
display: 'flex',
@@ -332,17 +485,83 @@ const RoomVisualPage: React.FC = () => {
</Tag>
)}
</div>
<Tag color="blue">{o.days} </Tag>
{isHistorical ? (
<Tag
color={
o.inspectionStatus === 'present'
? 'green'
: o.inspectionStatus === 'absent'
? 'red'
: 'default'
}
>
{o.inspectionStatus === 'present'
? '在寝'
: o.inspectionStatus === 'absent'
? '缺勤'
: '无记录'}
</Tag>
) : (
<Space size="small">
<span style={{ color: '#86868b', fontSize: 12 }}>
{presentOccupancyIds.includes(o.occupancyId) ? '在寝' : '缺勤'}
</span>
{hasPermission('room:inspect') ? (
<Switch
checked={presentOccupancyIds.includes(o.occupancyId)}
checkedChildren="在寝"
unCheckedChildren="缺勤"
onChange={(checked) =>
setPresentOccupancyIds((current) =>
togglePresentOccupancy(current, o.occupancyId, checked),
)
}
/>
) : null}
</Space>
)}
</div>
<div style={{ color: '#86868b', fontSize: 12, marginTop: 4 }}>
<CalendarOutlined style={{ marginRight: 4 }} />
{o.checkInDate} | {o.billingStartDate}
{o.bedNumber || '未分配'} | {o.checkInDate} |
{o.billingStartDate}
{o.supervisor && (
<span style={{ marginLeft: 8 }}>{o.supervisor}</span>
)}
</div>
</Card>
))}
{!isHistorical && hasPermission('room:inspect') && (
<div
style={{
display: 'flex',
justifyContent: 'flex-end',
gap: 8,
marginTop: 16,
flexWrap: 'wrap',
}}
>
<Button
icon={<CheckCircleOutlined />}
onClick={() =>
setPresentOccupancyIds(
detailRoom.occupants.map((occupant: any) => occupant.occupancyId),
)
}
>
宿
</Button>
<PermissionButton
permission="room:inspect"
type="primary"
icon={<SaveOutlined />}
loading={inspectionSaving}
onClick={submitInspection}
>
</PermissionButton>
</div>
)}
</div>
) : (
<div style={{ textAlign: 'center', padding: 24, color: '#86868b' }}>

View File

@@ -0,0 +1,22 @@
import { describe, expect, it } from 'vitest';
import { getInitialPresentOccupancyIds, togglePresentOccupancy } from './inspection-state';
describe('room inspection state', () => {
const occupants = [
{ occupancyId: 11, inspectionStatus: 'present' as const },
{ occupancyId: 12, inspectionStatus: 'absent' as const },
];
it('starts every occupant unchecked before the room is submitted', () => {
expect(getInitialPresentOccupancyIds(occupants, false)).toEqual([]);
});
it('restores the saved present occupants after submission', () => {
expect(getInitialPresentOccupancyIds(occupants, true)).toEqual([11]);
});
it('adds and removes a single occupant without changing the others', () => {
expect(togglePresentOccupancy([11], 12, true).sort()).toEqual([11, 12]);
expect(togglePresentOccupancy([11, 12], 11, false)).toEqual([12]);
});
});

View File

@@ -0,0 +1,25 @@
export interface InspectionOccupant {
occupancyId: number;
inspectionStatus?: 'present' | 'absent' | null;
}
export function getInitialPresentOccupancyIds(
occupants: InspectionOccupant[],
submitted: boolean,
): number[] {
if (!submitted) return [];
return occupants
.filter((occupant) => occupant.inspectionStatus === 'present')
.map((occupant) => occupant.occupancyId);
}
export function togglePresentOccupancy(
currentIds: number[],
occupancyId: number,
present: boolean,
): number[] {
const next = new Set(currentIds);
if (present) next.add(occupancyId);
else next.delete(occupancyId);
return [...next];
}

File diff suppressed because it is too large Load Diff

View File

@@ -6,6 +6,7 @@ import {
Modal,
Form,
Input,
InputNumber,
DatePicker,
TimePicker,
Popconfirm,
@@ -26,10 +27,10 @@ import {
CalendarOutlined,
LeftOutlined,
RightOutlined,
DeleteOutlined,
CloudSyncOutlined,
PlusOutlined,
EditOutlined,
StopOutlined,
} from '@ant-design/icons';
import dayjs, { Dayjs } from 'dayjs';
import api from '../../api';
@@ -53,6 +54,7 @@ interface ClassScheduleItem {
weekDay: number;
startTime: string;
endTime: string;
attendanceAdvanceMinutes: number;
startDate: string;
endDate: string;
subject: string;
@@ -351,7 +353,7 @@ const SchedulesPage: React.FC = () => {
setEditingSchedule(null);
setModalMode('create');
form.resetFields();
form.setFieldsValue({ classroomId, weekDay });
form.setFieldsValue({ classroomId, weekDay, attendanceAdvanceMinutes: 30 });
setModalOpen(true);
}
};
@@ -453,23 +455,26 @@ const SchedulesPage: React.FC = () => {
void loadClassTeachers(editableSchedule.classId);
};
// ---- Delete schedule ----
const removeScheduleFromSelection = (id: number) => {
const remaining = selectedSchedules.filter((s) => s.id !== id);
setSelectedSchedules(remaining);
if (remaining.length === 0) {
setModalOpen(false);
}
};
const handleDelete = async (id: number | null) => {
// ---- Disable / delete schedule ----
const handleDisable = async (id: number | null) => {
if (id === null) return;
try {
await api.delete(`/class-schedules/${id}`);
message.success('排课已删除');
// Refresh the displayed schedules
const remaining = selectedSchedules.filter((s) => s.id !== id);
setSelectedSchedules(remaining);
if (remaining.length === 0) {
setModalOpen(false);
}
await api.put(`/class-schedules/${id}`, { status: 'inactive' });
message.success('排课已停用,历史考勤记录已保留,教室占用已释放');
removeScheduleFromSelection(id);
fetchData();
} catch (e: unknown) {
const err = e as { message?: string };
message.error(err?.message || '删除失败');
message.error(err?.message || '停用失败');
}
};
@@ -947,9 +952,41 @@ const SchedulesPage: React.FC = () => {
/>
</Form.Item>
<Form.Item
name="notes"
label="备注"
rules={[{ max: 500, message: '备注不能超过500字' }]}
>
<Input.TextArea
rows={3}
maxLength={500}
showCount
placeholder="可填写排课说明、设备需求或临时调整原因"
/>
</Form.Item>
<Form.Item
name="attendanceAdvanceMinutes"
label="课前签到时间"
tooltip="从上课前指定分钟开始,到下课时间结束;期间任意上班或下班打卡都计为出勤"
initialValue={30}
rules={[{ required: true, message: '请设置课前签到时间' }]}
>
<InputNumber
min={0}
max={1440}
step={5}
addonAfter="分钟"
style={{ width: '100%' }}
placeholder="例如 30"
/>
</Form.Item>
<Form.Item
name="timeRange"
label="上课时段"
tooltip="同一教室的前后两节排课必须至少间隔10分钟"
extra="系统按10分钟选择时间并为相邻排课强制预留至少10分钟。"
rules={[{ required: true, message: '请选择时段' }]}
>
<TimePicker.RangePicker
@@ -995,6 +1032,7 @@ const SchedulesPage: React.FC = () => {
weekDay:
selectedCell?.weekDay ?? (selectedDate ? selectedDate.day() || 7 : undefined),
dateRange: selectedDate ? [selectedDate, selectedDate] : undefined,
attendanceAdvanceMinutes: 30,
});
}}
>
@@ -1041,6 +1079,12 @@ const SchedulesPage: React.FC = () => {
<strong></strong>
{s.startTime} ~ {s.endTime}
</div>
{!isMaskedSchedule(s) && (
<div>
<strong></strong>
{s.attendanceAdvanceMinutes ?? 30}
</div>
)}
<div>
<strong></strong>
{s.startDate} ~ {s.endDate}
@@ -1072,21 +1116,23 @@ const SchedulesPage: React.FC = () => {
</PermissionButton>
)}
<Popconfirm
title="确认删除该排课?"
onConfirm={() => handleDelete(s.id)}
okText="删除"
cancelText="取消"
>
<PermissionButton
permission="schedule:delete"
size="small"
danger
icon={<DeleteOutlined />}
{s.scheduleType !== 'RENTAL' && s.status === 'active' && (
<Popconfirm
title="确认停用该排课?"
description="停用后历史考勤记录会保留,但该排课不会再显示或占用教室。"
onConfirm={() => handleDisable(s.id)}
okText="停用"
cancelText="取消"
>
</PermissionButton>
</Popconfirm>
<PermissionButton
permission="schedule:edit"
size="small"
icon={<StopOutlined />}
>
</PermissionButton>
</Popconfirm>
)}
</Space>
)}
</div>
@@ -1145,17 +1191,17 @@ const SchedulesPage: React.FC = () => {
{syncResult ? (
/* ── 同步结果 ── */
<div>
<Row gutter={16} style={{ marginBottom: 16 }}>
<Col span={6}>
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
<Col xs={12} sm={6}>
<Statistic title="排课" value={syncResult.scheduleCount} suffix="条" />
</Col>
<Col span={6}>
<Col xs={12} sm={6}>
<Statistic title="班次" value={syncResult.shiftCount} suffix="个" />
</Col>
<Col span={6}>
<Col xs={12} sm={6}>
<Statistic title="考勤组" value={syncResult.groupCount} suffix="个" />
</Col>
<Col span={6}>
<Col xs={12} sm={6}>
<Statistic
title="排班数"
value={syncResult.syncedItems}
@@ -1210,11 +1256,11 @@ const SchedulesPage: React.FC = () => {
) : syncStatus ? (
/* ── 同步确认信息 ── */
<div>
<Row gutter={16} style={{ marginBottom: 16 }}>
<Col span={8}>
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
<Col xs={24} sm={8}>
<Statistic title="活跃排课" value={syncStatus.activeSchedules} suffix="条" />
</Col>
<Col span={8}>
<Col xs={24} sm={8}>
<Statistic
title="已就绪班级"
value={syncStatus.mappedClasses}
@@ -1225,7 +1271,7 @@ const SchedulesPage: React.FC = () => {
}}
/>
</Col>
<Col span={8}>
<Col xs={24} sm={8}>
<Statistic
title="无绑定学生班级"
value={syncStatus.totalClasses - syncStatus.mappedClasses}

View File

@@ -15,10 +15,14 @@ describe('schedule edit form mapping', () => {
endTime: '18:00',
startDate: '2026-07-01',
endDate: '2026-07-31',
notes: '需要投影设备',
attendanceAdvanceMinutes: 45,
});
expect(values.classroomId).toBe(1);
expect(values.weekDay).toBe(5);
expect(values.notes).toBe('需要投影设备');
expect(values.attendanceAdvanceMinutes).toBe(45);
expect(values.timeRange.map((item) => item.format('HH:mm'))).toEqual(['14:00', '18:00']);
expect(values.dateRange.map((item) => item.format('YYYY-MM-DD'))).toEqual([
'2026-07-01',
@@ -36,6 +40,8 @@ describe('schedule edit form mapping', () => {
teacherId: 4,
timeRange: [dayjs('2026-01-01 13:30'), dayjs('2026-01-01 17:20')],
dateRange: [dayjs('2026-08-01'), dayjs('2026-08-31')],
notes: ' 临时调整教室 ',
attendanceAdvanceMinutes: 20,
}),
).toEqual({
classId: 1,
@@ -47,6 +53,25 @@ describe('schedule edit form mapping', () => {
endTime: '17:20',
startDate: '2026-08-01',
endDate: '2026-08-31',
notes: '临时调整教室',
attendanceAdvanceMinutes: 20,
});
});
});
describe('schedule notes normalization', () => {
it('omits whitespace-only notes from the payload', () => {
expect(
buildSchedulePayload({
classId: 1,
classroomId: 2,
weekDay: 6,
subject: '作文',
timeRange: [dayjs('2026-01-01 13:30'), dayjs('2026-01-01 17:20')],
dateRange: [dayjs('2026-08-01'), dayjs('2026-08-31')],
notes: ' ',
attendanceAdvanceMinutes: 30,
}).notes,
).toBeUndefined();
});
});

View File

@@ -6,6 +6,8 @@ export interface ScheduleFormValues {
weekDay: number;
subject: string;
teacherId?: number;
notes?: string;
attendanceAdvanceMinutes: number;
timeRange: [Dayjs, Dayjs];
dateRange: [Dayjs, Dayjs];
}
@@ -17,6 +19,8 @@ export interface EditableSchedule {
weekDay: number;
subject: string;
teacherId: number | null;
notes?: string | null;
attendanceAdvanceMinutes?: number | null;
startTime: string;
endTime: string;
startDate: string;
@@ -29,6 +33,8 @@ export const scheduleToFormValues = (schedule: EditableSchedule): ScheduleFormVa
weekDay: schedule.weekDay,
subject: schedule.subject,
teacherId: schedule.teacherId ?? undefined,
notes: schedule.notes ?? undefined,
attendanceAdvanceMinutes: schedule.attendanceAdvanceMinutes ?? 30,
timeRange: [dayjs(`2000-01-01 ${schedule.startTime}`), dayjs(`2000-01-01 ${schedule.endTime}`)],
dateRange: [dayjs(schedule.startDate), dayjs(schedule.endDate)],
});
@@ -39,6 +45,8 @@ export const buildSchedulePayload = (values: ScheduleFormValues) => ({
weekDay: values.weekDay,
subject: values.subject,
teacherId: values.teacherId,
notes: values.notes?.trim() || undefined,
attendanceAdvanceMinutes: values.attendanceAdvanceMinutes,
startTime: values.timeRange[0].format('HH:mm'),
endTime: values.timeRange[1].format('HH:mm'),
startDate: values.dateRange[0].format('YYYY-MM-DD'),

File diff suppressed because it is too large Load Diff

View File

@@ -74,56 +74,65 @@ const TeacherWorkspacePage: React.FC = () => {
fetchData();
}, []);
const classColumns: ColumnsType<AssignedClass> = useMemo(() => [
{
title: '班级名称',
dataIndex: 'className',
render: (v: string, r: AssignedClass) => `${v} (${r.classCode})`,
},
{
title: '角色',
dataIndex: 'roleType',
render: (v: string) => <Tag>{ROLE_LABELS[v] || v}</Tag>,
},
{
title: '科目',
dataIndex: 'subject',
render: (v: string | null) => v || '-',
},
], []);
const classColumns: ColumnsType<AssignedClass> = useMemo(
() => [
{
title: '班级名称',
dataIndex: 'className',
render: (v: string, r: AssignedClass) => `${v} (${r.classCode})`,
},
{
title: '角色',
dataIndex: 'roleType',
render: (v: string) => <Tag>{ROLE_LABELS[v] || v}</Tag>,
},
{
title: '科目',
dataIndex: 'subject',
render: (v: string | null) => v || '-',
},
],
[],
);
const scheduleColumns: ColumnsType<ScheduleItem> = useMemo(() => [
{
title: '时间',
key: 'time',
render: (_: unknown, r: ScheduleItem) => `${r.startTime} - ${r.endTime}`,
},
{
title: '星期',
dataIndex: 'weekDay',
render: (v: number) => <Tag>{WEEKDAY_LABELS[String(v)] || v}</Tag>,
},
{
title: '科目',
dataIndex: 'subject',
},
{
title: '类型',
dataIndex: 'scheduleType',
render: (v: string) => (
<Tag color={v === 'INTERNAL' ? 'blue' : 'orange'}>
{v === 'INTERNAL' ? '内部课程' : '租赁'}
</Tag>
),
},
], []);
const scheduleColumns: ColumnsType<ScheduleItem> = useMemo(
() => [
{
title: '时间',
key: 'time',
render: (_: unknown, r: ScheduleItem) => `${r.startTime} - ${r.endTime}`,
},
{
title: '星期',
dataIndex: 'weekDay',
render: (v: number) => <Tag>{WEEKDAY_LABELS[String(v)] || v}</Tag>,
},
{
title: '科目',
dataIndex: 'subject',
},
{
title: '类型',
dataIndex: 'scheduleType',
render: (v: string) => (
<Tag color={v === 'INTERNAL' ? 'blue' : 'orange'}>
{v === 'INTERNAL' ? '内部课程' : '租赁'}
</Tag>
),
},
],
[],
);
const studentColumns: ColumnsType<StudentItem> = useMemo(() => [
{ title: '姓名', dataIndex: 'studentName' },
{ title: '学号', dataIndex: 'studentNo', render: (v: string) => v || '-' },
{ title: '班级', dataIndex: 'className' },
{ title: '加入日期', dataIndex: 'joinDate', render: (v: string) => v || '-' },
], []);
const studentColumns: ColumnsType<StudentItem> = useMemo(
() => [
{ title: '姓名', dataIndex: 'studentName' },
{ title: '学号', dataIndex: 'studentNo', render: (v: string) => v || '-' },
{ title: '班级', dataIndex: 'className' },
{ title: '加入日期', dataIndex: 'joinDate', render: (v: string) => v || '-' },
],
[],
);
if (loading) {
return (
@@ -146,7 +155,12 @@ const TeacherWorkspacePage: React.FC = () => {
columns={classColumns}
dataSource={data.assignedClasses}
rowKey="classId"
pagination={{ pageSize: 20, showTotal: (total) => `${total} 个班级` }}
pagination={{
defaultPageSize: 20,
showSizeChanger: true,
pageSizeOptions: [20, 50, 100],
showTotal: (total) => `${total} 个班级`,
}}
/>
) : (
<Empty description="暂无分配的班级" />
@@ -160,7 +174,12 @@ const TeacherWorkspacePage: React.FC = () => {
columns={scheduleColumns}
dataSource={data.todaySchedules}
rowKey="id"
pagination={{ pageSize: 20, showTotal: (total) => `${total}` }}
pagination={{
defaultPageSize: 20,
showSizeChanger: true,
pageSizeOptions: [20, 50, 100],
showTotal: (total) => `${total}`,
}}
/>
) : (
<Empty description="今日无排课" />
@@ -174,7 +193,12 @@ const TeacherWorkspacePage: React.FC = () => {
columns={studentColumns}
dataSource={data.myStudents}
rowKey="studentId"
pagination={{ pageSize: 20, showTotal: (total) => `${total}` }}
pagination={{
defaultPageSize: 20,
showSizeChanger: true,
pageSizeOptions: [20, 50, 100],
showTotal: (total) => `${total}`,
}}
/>
) : (
<Empty description="暂无学生" />

Some files were not shown because too many files have changed in this diff Show More