87 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
285 changed files with 21456 additions and 25492 deletions

View File

@@ -1,40 +1,43 @@
# PR 自动检查:代码风格 + 类型检查 + 测试
name: CI 检查
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]
push:
branches: [main]
workflow_dispatch:
jobs:
lint:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- run: npm ci
- run: npm run lint
container: node:22.22.0-bookworm
timeout-minutes: 30
typecheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- name: Checkout
uses: https://gitee.com/mirrors_actions/checkout@v4
with:
node-version: '22'
- run: npm ci
- run: npm run typecheck
github-server-url: https://git.gongxue100.com
fetch-depth: 1
test:
runs-on: ubuntu-latest
needs: [lint, typecheck]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- run: npm ci
- run: npm run test
- 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

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

@@ -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';
@@ -24,6 +26,8 @@ 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 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'));
@@ -56,9 +60,19 @@ const App: React.FC = () => {
},
}}
>
<AntdApp>
<AppMessageBridge />
<BrowserRouter>
<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' }}>
@@ -174,6 +188,22 @@ const App: React.FC = () => {
</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={
@@ -312,8 +342,9 @@ const App: React.FC = () => {
</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',
@@ -21,7 +22,7 @@ instance.interceptors.response.use(
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',
@@ -54,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

@@ -61,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' },

View File

@@ -30,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

@@ -24,6 +24,11 @@ export const PERMISSION_PAGES: readonly PermissionPage[] = [
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' },

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,17 +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 || [];

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

@@ -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 {

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

@@ -59,6 +59,88 @@ canvas {
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;
@@ -75,6 +157,22 @@ canvas {
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;
}
@@ -90,12 +188,40 @@ canvas {
max-width: 100%;
}
.ant-table-wrapper .ant-table-container {
overflow-x: auto;
.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;
}
/* ── 表格单元格省略号截断(按需启用) ──
在 .ant-table-wrapper 上添加 .table-cell-ellipsis 类即可生效:
<Table className="table-cell-ellipsis" ... /> */
@@ -135,6 +261,16 @@ canvas {
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;

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,6 +53,7 @@ const iconMap: Record<string, React.ReactNode> = {
students: <TeamOutlined />,
classes: <TeamOutlined />,
teachers: <UserOutlined />,
exam: <TrophyOutlined />,
home: <HomeOutlined />,
overview: <AppstoreOutlined />,
occupancy: <SwapOutlined />,
@@ -68,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();
@@ -79,23 +89,57 @@ 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.
});
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);
};
}, []);
@@ -113,7 +157,7 @@ const MainLayout: React.FC = () => {
const handleLogout = useCallback(() => {
localStorage.removeItem('token');
localStorage.removeItem('user');
localStorage.removeItem('permissions');
clearPermissions();
navigate('/login');
}, [navigate]);
@@ -160,14 +204,13 @@ const MainLayout: React.FC = () => {
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[] => {
@@ -217,7 +260,7 @@ const MainLayout: React.FC = () => {
borderBottom: '1px solid #e5e5e7',
}}
>
{collapsed ? '' : '恭学教育基地'}
{collapsed ? '' : '学生管理系统'}
</div>
{menuContent}
</Sider>
@@ -230,7 +273,7 @@ const MainLayout: React.FC = () => {
size={240}
styles={{ body: { padding: 0 } }}
className="app-navigation-drawer"
title="恭学教育基地"
title="学生管理系统"
>
{menuContent}
</Drawer>
@@ -263,6 +306,16 @@ const MainLayout: React.FC = () => {
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={{
@@ -288,6 +341,12 @@ const MainLayout: React.FC = () => {
</Dropdown>
</div>
</Header>
<RouteDock
location={location}
menuItems={menuItems}
onNavigate={navigate}
draggable={isDesktop}
/>
<Content
className="app-content"
style={{
@@ -300,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

@@ -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,23 +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,
WarningOutlined,
ReloadOutlined,
CloudServerOutlined,
SafetyOutlined,
RobotOutlined,
} from '@ant-design/icons';
import api from '../../api';
import { message } from '../../ui/app-message';
@@ -54,6 +58,7 @@ interface AiConfigData {
keySource: 'database' | 'environment' | 'none';
defaultModel: string | null;
enabled: boolean;
supportsVision: boolean;
timeoutMs: number;
verified: boolean;
lastTestedAt: string | null;
@@ -71,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
// ---------------------------------------------------------------------------
@@ -86,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);
@@ -107,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 {
@@ -122,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]);
@@ -130,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) {
@@ -186,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,
@@ -234,7 +329,7 @@ const AiConfigPage: React.FC = () => {
} finally {
setTesting(false);
}
}, [form, loadConfig, currentProvider]);
}, [formValues, form, loadConfig, currentProvider]);
// ── Clear key ──
@@ -260,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) {
@@ -286,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>
@@ -331,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="请求超时 (毫秒)"
@@ -368,6 +455,7 @@ const AiConfigPage: React.FC = () => {
{ required: true, message: '请输入超时时间' },
{ type: 'number', min: 1000, max: 120000, message: '范围: 1000-120000' },
]}
preserve
>
<InputNumber
min={1000}
@@ -375,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>
@@ -430,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}>
@@ -438,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

@@ -1335,22 +1335,6 @@
color: var(--student-muted);
}
.student-trend-bars {
display: flex;
align-items: end;
gap: 8px;
height: 110px;
padding: 12px;
border-radius: 8px;
background: var(--student-soft);
}
.student-trend-bars i {
flex: 1;
min-height: 18px;
border-radius: 5px 5px 0 0;
background: linear-gradient(180deg, #56bea3, #157a65);
}
@media (max-width: 1280px) {
.student-filter-panel {

View File

@@ -12,7 +12,6 @@ import {
Form,
Input,
Modal,
Progress,
Segmented,
Row,
Select,
@@ -36,26 +35,54 @@ import {
import dayjs, { type Dayjs } from 'dayjs';
import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell';
import { usePermission } from '../../hooks/usePermission';
import { message } from '../../ui/app-message';
import {
canPullAttendance,
filterLessonAttendanceRecords,
getAttendanceExperience,
getPunchDisplayInfo,
getSchedulePhase,
summarizeLessonCheckins,
getPunchDisplayInfo,
type AttendanceSummary,
type LessonAttendanceFilter,
type SchedulePhase,
} from './attendance-workspace';
import LessonAttendanceDetail from './LessonAttendanceDetail';
import type { LessonAttendanceRecord, LessonAttendanceSchedule } from './types';
import './attendance.css';
const DEFAULT_ATTENDANCE_PERIODS = [
{ periodKey: 'morning_reading', label: '早自习', startTime: '07:30', endTime: '08:30', sortOrder: 1, enabled: true },
{ periodKey: 'morning', label: '早课', startTime: '09:00', endTime: '12:00', sortOrder: 2, enabled: true },
{ periodKey: 'afternoon', label: '晚课', startTime: '14:00', endTime: '17:00', sortOrder: 3, enabled: true },
{ periodKey: 'evening_study', label: '晚自习', startTime: '18:30', endTime: '21:00', sortOrder: 4, enabled: true },
{
periodKey: 'morning_reading',
label: '早自习',
startTime: '07:30',
endTime: '08:30',
sortOrder: 1,
enabled: true,
},
{
periodKey: 'morning',
label: '早课',
startTime: '09:00',
endTime: '12:00',
sortOrder: 2,
enabled: true,
},
{
periodKey: 'afternoon',
label: '晚课',
startTime: '14:00',
endTime: '17:00',
sortOrder: 3,
enabled: true,
},
{
periodKey: 'evening_study',
label: '晚自习',
startTime: '18:30',
endTime: '21:00',
sortOrder: 4,
enabled: true,
},
];
const STATUS_META: Record<
@@ -88,25 +115,7 @@ interface ClassOption {
teachers?: ClassTeacherOption[];
}
interface AttendanceRecordItem {
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;
}
type AttendanceRecordItem = LessonAttendanceRecord;
interface AssignedClass {
classId: number;
@@ -116,14 +125,7 @@ interface AssignedClass {
subject: string;
}
interface TodaySchedule {
id: number;
classId: number;
classroomId: number;
startTime: string;
endTime: string;
subject: string;
}
type TodaySchedule = LessonAttendanceSchedule;
interface HistoryScheduleOption {
id: number;
@@ -140,20 +142,6 @@ interface HistoryScheduleOption {
status: string;
}
interface LessonAttendanceSession {
id: number;
scheduleId: number;
classId: number;
lessonDate: string;
status: 'in_progress' | 'completed';
}
interface LessonAttendanceResponse {
schedule: TodaySchedule;
session: LessonAttendanceSession | null;
records: AttendanceRecordItem[];
}
interface TeacherWorkspaceData {
assignedClasses: AssignedClass[];
todaySchedules: TodaySchedule[];
@@ -246,58 +234,22 @@ function AttendanceStatusTag({ status }: { status: string }) {
);
}
function LessonCheckinSummaryStrip({ records }: { records: readonly AttendanceRecordItem[] }) {
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 AttendancePage: React.FC = () => {
const { permissions, hasPermission } = usePermission();
const roles = useMemo(readCurrentRoles, []);
const experience = getAttendanceExperience(permissions, roles);
if (experience === 'teacher') {
return <TeacherAttendanceWorkspace />;
return <TeacherAttendanceWorkspace canCreate={hasPermission('attendance:create')} />;
}
return <AdminAttendanceArchive canEdit={hasPermission('attendance:edit')} />;
};
const TeacherAttendanceWorkspace: React.FC = () => {
const TeacherAttendanceWorkspace: React.FC<{ canCreate: boolean }> = ({ canCreate }) => {
const [loading, setLoading] = useState(true);
const [workspace, setWorkspace] = useState<TeacherWorkspaceData | null>(null);
const [selectedSchedule, setSelectedSchedule] = useState<TodaySchedule | null>(null);
const [lessonSession, setLessonSession] = useState<LessonAttendanceSession | null>(null);
const [lessonRecords, setLessonRecords] = useState<AttendanceRecordItem[]>([]);
const [recordLoading, setRecordLoading] = useState(false);
const [drawerOpen, setDrawerOpen] = useState(false);
const [studentKeyword, setStudentKeyword] = useState('');
const [checkinFilter, setCheckinFilter] = useState<LessonAttendanceFilter>('all');
const loadWorkspace = useCallback(async () => {
setLoading(true);
@@ -319,70 +271,26 @@ const TeacherAttendanceWorkspace: React.FC = () => {
[workspace],
);
const openAttendance = useCallback(async (schedule: TodaySchedule) => {
setStudentKeyword('');
setCheckinFilter('all');
const openAttendance = useCallback((schedule: TodaySchedule) => {
setSelectedSchedule(schedule);
setDrawerOpen(true);
setRecordLoading(true);
try {
const today = dayjs().format('YYYY-MM-DD');
const data = await api.post<LessonAttendanceResponse>(
`/attendance-lessons/schedules/${schedule.id}/pull`,
{ date: today },
);
setSelectedSchedule(data.schedule);
setLessonSession(data.session);
setLessonRecords(data.records);
message.success('钉钉打卡已更新;课程截止后系统将自动结算');
} catch (error: unknown) {
setLessonSession(null);
setLessonRecords([]);
message.error(error instanceof Error ? error.message : '加载本节课考勤失败');
} finally {
setRecordLoading(false);
}
}, []);
const updateLessonRecord = useCallback(
async (record: AttendanceRecordItem, status: string) => {
const previous = record.status;
setLessonRecords((items) =>
items.map((item) => (item.id === record.id ? { ...item, status } : item)),
);
try {
await api.put(`/attendance-records/${record.id}`, { status });
} catch (error: unknown) {
setLessonRecords((items) =>
items.map((item) => (item.id === record.id ? { ...item, status: previous } : item)),
);
message.error((error as { message?: string })?.message || '更新考勤失败');
}
},
[],
);
const now = new Date();
const schedules = workspace?.todaySchedules ?? [];
const startedCount = schedules.filter(
(item) => canPullAttendance(getSchedulePhase(item.startTime, item.endTime, now)),
const startedCount = schedules.filter((item) =>
canPullAttendance(getSchedulePhase(item.startTime, item.endTime, now)),
).length;
const nextSchedule = schedules.find(
(item) => getSchedulePhase(item.startTime, item.endTime, now) !== 'ended',
);
const isAttendanceCompleted = lessonSession?.status === 'completed';
const filteredLessonRecords = useMemo(
() => filterLessonAttendanceRecords(lessonRecords, studentKeyword, checkinFilter),
[lessonRecords, studentKeyword, checkinFilter],
);
return (
<div className="attendance-page teacher-attendance">
<section className="attendance-hero attendance-hero--teacher">
<div>
<span className="attendance-eyebrow">TEACHING DAY · {dayjs().format('MM月DD日 dddd')}</span>
<span className="attendance-eyebrow">
TEACHING DAY · {dayjs().format('MM月DD日 dddd')}
</span>
<h1></h1>
<p></p>
</div>
@@ -393,18 +301,33 @@ const TeacherAttendanceWorkspace: React.FC = () => {
<Row gutter={[16, 16]} className="teacher-overview">
<Col xs={24} md={8}>
<div className="teacher-kpi"><span></span><strong>{schedules.length}</strong><small></small></div>
<div className="teacher-kpi">
<span></span>
<strong>{schedules.length}</strong>
<small></small>
</div>
</Col>
<Col xs={24} md={8}>
<div className="teacher-kpi"><span></span><strong>{startedCount}</strong><small></small></div>
<div className="teacher-kpi">
<span></span>
<strong>{startedCount}</strong>
<small></small>
</div>
</Col>
<Col xs={24} md={8}>
<div className="teacher-kpi teacher-kpi--next"><span></span><strong>{nextSchedule ? nextSchedule.startTime : '—'}</strong><small>{nextSchedule?.subject || '今天没有更多课程'}</small></div>
<div className="teacher-kpi teacher-kpi--next">
<span></span>
<strong>{nextSchedule ? nextSchedule.startTime : '—'}</strong>
<small>{nextSchedule?.subject || '今天没有更多课程'}</small>
</div>
</Col>
</Row>
<div className="attendance-section-heading">
<div><span></span><h2></h2></div>
<div>
<span></span>
<h2></h2>
</div>
<span className="attendance-section-note"></span>
</div>
@@ -413,7 +336,12 @@ const TeacherAttendanceWorkspace: React.FC = () => {
<Card className="attendance-empty-card">
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={<div><strong></strong><p></p></div>}
description={
<div>
<strong></strong>
<p></p>
</div>
}
/>
</Card>
) : (
@@ -427,7 +355,7 @@ const TeacherAttendanceWorkspace: React.FC = () => {
phase={phase}
className={classNameById.get(schedule.classId) || `班级 ${schedule.classId}`}
index={index + 1}
onOpen={() => void openAttendance(schedule)}
onOpen={canCreate ? () => openAttendance(schedule) : undefined}
/>
);
})}
@@ -435,104 +363,17 @@ const TeacherAttendanceWorkspace: React.FC = () => {
)}
</Spin>
<Drawer open={drawerOpen} onClose={() => setDrawerOpen(false)} width={960} title={null} className="attendance-drawer">
<div className="lesson-record-header">
<span className="attendance-eyebrow">LESSON ATTENDANCE</span>
<h2>{selectedSchedule?.subject || '课程考勤'}</h2>
<p>{selectedSchedule ? classNameById.get(selectedSchedule.classId) : ''} · {selectedSchedule?.startTime}{selectedSchedule?.endTime} · {dayjs().format('YYYY-MM-DD')}</p>
</div>
{lessonSession && (
<Alert
type={isAttendanceCompleted ? 'success' : 'info'}
showIcon
title={isAttendanceCompleted ? '本节课考勤已结算' : '当前打卡结果;课程截止后将自动做最终结算'}
style={{ marginBottom: 16 }}
/>
)}
<LessonCheckinSummaryStrip records={lessonRecords} />
<div className="lesson-record-filters">
<Input.Search
allowClear
value={studentKeyword}
placeholder="搜索学生姓名"
onChange={(event) => setStudentKeyword(event.target.value)}
className="lesson-record-search"
/>
<Select<LessonAttendanceFilter>
value={checkinFilter}
onChange={setCheckinFilter}
options={[
{ value: 'all', label: '全部学生' },
{ value: 'checked_in', label: '已打卡' },
{ value: 'not_checked_in', label: '未打卡' },
]}
className="lesson-record-filter-select"
/>
<span className="lesson-record-filter-count">
{filteredLessonRecords.length} / {lessonRecords.length}
</span>
</div>
<Table<AttendanceRecordItem>
rowKey="id"
loading={recordLoading}
dataSource={filteredLessonRecords}
pagination={false}
locale={{
emptyText: <Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={lessonRecords.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: AttendanceRecordItem) => {
const checkedIn = value === 'present' || value === 'late';
return (
<div className="attendance-marking-actions">
<Button
size="small"
type={checkedIn ? 'primary' : 'default'}
onClick={() => void updateLessonRecord(record, 'present')}
>
</Button>
<Button
size="small"
type={!checkedIn ? 'primary' : 'default'}
danger={!checkedIn}
onClick={() => void updateLessonRecord(record, 'absent')}
>
</Button>
</div>
);
},
},
{ title: '当前状态', dataIndex: 'status', width: 105, render: (value: string) => <AttendanceStatusTag status={value === 'present' || value === 'late' ? 'present' : 'absent'} /> },
{
title: '打卡设备',
width: 220,
render: (_: unknown, record: AttendanceRecordItem) => {
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> },
]}
{canCreate ? (
<LessonAttendanceDetail
schedule={selectedSchedule}
className={
selectedSchedule
? classNameById.get(selectedSchedule.classId) || `班级 ${selectedSchedule.classId}`
: ''
}
onClose={() => setSelectedSchedule(null)}
/>
</Drawer>
) : null}
</div>
);
};
@@ -542,7 +383,7 @@ const LessonCard: React.FC<{
phase: SchedulePhase;
className: string;
index: number;
onOpen: () => void;
onOpen?: () => void;
}> = ({ schedule, phase, className, index, onOpen }) => {
const phaseMeta = {
upcoming: { label: '待上课', icon: <ClockCircleOutlined />, tone: 'upcoming' },
@@ -553,25 +394,36 @@ const LessonCard: React.FC<{
return (
<article className={`lesson-card lesson-card--${phaseMeta.tone}`}>
<div className="lesson-sequence">{String(index).padStart(2, '0')}</div>
<div className="lesson-time"><strong>{schedule.startTime}</strong><span /><strong>{schedule.endTime}</strong></div>
<div className="lesson-time">
<strong>{schedule.startTime}</strong>
<span />
<strong>{schedule.endTime}</strong>
</div>
<div className="lesson-main">
<div className="lesson-title-row"><h3>{schedule.subject}</h3><Tag icon={phaseMeta.icon}>{phaseMeta.label}</Tag></div>
<p><TeamOutlined /> {className}<span> {schedule.classroomId}</span></p>
<div className="lesson-title-row">
<h3>{schedule.subject}</h3>
<Tag icon={phaseMeta.icon}>{phaseMeta.label}</Tag>
</div>
<p>
<TeamOutlined /> {className}
<span> {schedule.classroomId}</span>
</p>
</div>
<div className="lesson-action">
{phase === 'upcoming' ? (
<Tooltip title="课程尚未开始"><Button disabled></Button></Tooltip>
) : (
<Tooltip title="课程尚未开始">
<Button disabled></Button>
</Tooltip>
) : onOpen ? (
<Button type="primary" onClick={onOpen}>
{phase === 'ongoing' ? '查看当前考勤' : '拉取 / 查看考勤'} <ArrowRightOutlined />
</Button>
)}
) : null}
</div>
</article>
);
};
interface AdminStudentPanel {
key: string;
studentId: number;
@@ -594,7 +446,11 @@ const ADMIN_METRIC_META = [
function pickPrimaryStatus(records: AttendanceRecordItem[]) {
const priority = ['absent', 'leave', 'present'];
return priority.find((item) => records.some((record) => displayAttendanceStatus(record.status) === item)) || 'absent';
return (
priority.find((item) =>
records.some((record) => displayAttendanceStatus(record.status) === item),
) || 'absent'
);
}
function buildAdminStudentPanels(records: AttendanceRecordItem[]): AdminStudentPanel[] {
@@ -621,9 +477,7 @@ function buildAdminStudentPanels(records: AttendanceRecordItem[]): AdminStudentP
}
return Array.from(map.values()).map((item) => {
const checked = item.records.filter(
(record) => record.status === 'present',
).length;
const checked = item.records.filter((record) => record.status === 'present').length;
return {
...item,
primaryStatus: pickPrimaryStatus(item.records),
@@ -660,7 +514,6 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
const [selectedStudent, setSelectedStudent] = useState<AdminStudentPanel | null>(null);
const [correctingRecordId, setCorrectingRecordId] = useState<number | null>(null);
const enabledPeriods = useMemo(
() => periods.filter((period) => period.enabled).sort((a, b) => a.sortOrder - b.sortOrder),
[periods],
@@ -712,7 +565,10 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
enabled: period.enabled ?? true,
})),
};
const data = await api.put<AttendancePeriodConfigItem[]>('/attendance-period-configs', payload);
const data = await api.put<AttendancePeriodConfigItem[]>(
'/attendance-period-configs',
payload,
);
setPeriods(data);
setPeriodModalOpen(false);
message.success('考勤时段配置已保存');
@@ -796,14 +652,16 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
}
setRefreshingDingTalk(true);
try {
const result = await api.post<{ refreshed: number; imported: number; matched: number; errors: string[] }>(
'/attendance-records/refresh-dingtalk',
{
date: attendanceDate.format('YYYY-MM-DD'),
classId,
session,
},
);
const result = await api.post<{
refreshed: number;
imported: number;
matched: number;
errors: string[];
}>('/attendance-records/refresh-dingtalk', {
date: attendanceDate.format('YYYY-MM-DD'),
classId,
session,
});
if (result.errors.length > 0) {
message.warning(result.errors[0]);
} else {
@@ -933,6 +791,15 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
}
};
const saveAdminRecordCell = async (
record: AttendanceRecordItem,
field: 'status' | 'remark',
value: unknown,
) => {
await api.put(`/attendance-records/${record.id}`, { [field]: value });
message.success('考勤记录已保存');
await loadRecords();
};
const studentPanels = useMemo(() => buildAdminStudentPanels(records), [records]);
const visibleStudents = useMemo(() => {
@@ -952,7 +819,8 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
const selectedClassOption = classId
? classOptions.find((item) => item.classId === classId)
: undefined;
const selectedClass = selectedClassOption?.className || (classId ? `班级 ${classId}` : '全部班级');
const selectedClass =
selectedClassOption?.className || (classId ? `班级 ${classId}` : '全部班级');
const overviewTeachers = selectedClassOption?.teachers ?? [];
const headTeacherNames = classId
? formatTeacherNames(overviewTeachers.filter((teacher) => teacher.roleType === 'head_teacher'))
@@ -1004,7 +872,20 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
title: '状态',
dataIndex: 'status',
width: 105,
render: (value: string) => <AttendanceStatusTag status={displayAttendanceStatus(value)} />,
render: (value: string, record) => (
<EditableCell
value={displayAttendanceStatus(value)}
editor="select"
options={ADMIN_CORRECTION_OPTIONS.map((item) => ({
value: String(item.value),
label: item.label,
}))}
disabled={!canEdit}
onSave={(next) => saveAdminRecordCell(record, 'status', next)}
>
<AttendanceStatusTag status={displayAttendanceStatus(value)} />
</EditableCell>
),
},
{
title: '签到来源',
@@ -1025,7 +906,16 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
title: '备注',
dataIndex: 'remark',
ellipsis: true,
render: (value: string | null) => value || <span className="muted-text"></span>,
render: (value: string | null, record) => (
<EditableCell
value={value}
editor="textarea"
disabled={!canEdit}
onSave={(next) => saveAdminRecordCell(record, 'remark', next)}
>
{value || <span className="muted-text"></span>}
</EditableCell>
),
},
...(canEdit
? [
@@ -1256,9 +1146,9 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
value={studentSearch}
onChange={(event) => setStudentSearch(event.target.value)}
/>
<Button icon={<ExportOutlined />} onClick={handleExport}>
<PermissionButton permission="attendance:export" icon={<ExportOutlined />} onClick={handleExport}>
</Button>
</PermissionButton>
</div>
</header>
<div className="student-legend">
@@ -1405,20 +1295,10 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
))}
</div>
</section>
<section className="student-detail-section">
<h5> 7 </h5>
<div className="student-trend-bars">
{Array.from({ length: 7 }).map((_, index) => {
const value = Math.max(60, Math.min(100, selectedStudent.rate + index * 3 - 8));
return <i key={index} style={{ height: `${value}%` }} title={`${value}%`} />;
})}
</div>
</section>
</div>
)}
</Drawer>
<Modal
open={periodModalOpen}
title="考勤时段配置"
@@ -1514,7 +1394,6 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
</Form.List>
</Form>
</Modal>
</div>
);
};

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

@@ -4,6 +4,7 @@ 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 {
@@ -119,6 +120,12 @@ const AttendanceDevicesPage: React.FC = () => {
}
};
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}`);
@@ -130,37 +137,102 @@ const AttendanceDevicesPage: React.FC = () => {
};
const columns: ColumnsType<AttendanceDeviceRow> = [
{ title: '设备名称', dataIndex: 'deviceName', width: 180 },
{
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) => <span style={{ fontFamily: 'monospace' }}>{value}</span>,
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) => record.classroom?.name || `教室 ${record.classroomId}`,
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) => value || <span style={{ color: '#999' }}></span>,
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) => (
<Tag color={statusMeta[value]?.color}>{statusMeta[value]?.text || value}</Tag>
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) => value || <span style={{ color: '#999' }}></span>,
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: '操作',

View File

@@ -103,7 +103,7 @@ export const buildBillPrintHtml = (bill: BillPrintData) => {
<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>
<div class="footer">本账单由学生管理系统自动生成</div>
<script>window.addEventListener('load', function () { setTimeout(function () { window.print(); }, 100); });</script>
</body>
</html>`;

View File

@@ -189,9 +189,19 @@ const ClassDetailPage: React.FC = () => {
}
}, [id]);
const fetchUsers = useCallback(async () => {
try {
const res = (await api.get('/rbac/users')) as UserItem[];
setAllUsers(res || []);
} catch {
setAllUsers([]);
}
}, []);
useEffect(() => {
fetchDetail();
}, [fetchDetail]);
fetchUsers();
}, [fetchDetail, fetchUsers]);
const fetchSchedules = useCallback(async () => {
if (!id) return;
@@ -320,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('');
@@ -332,6 +341,9 @@ 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> = [
@@ -360,7 +372,7 @@ const ClassDetailPage: React.FC = () => {
];
const teacherColumns: ColumnsType<ClassTeacher> = [
{ title: '姓名', dataIndex: 'username' },
{ title: '姓名', render: (_: unknown, teacher) => getTeacherName(teacher) },
{
title: '角色',
dataIndex: 'roleType',
@@ -509,7 +521,12 @@ const ClassDetailPage: React.FC = () => {
{detail.studentCount}/{detail.maxStudents || '-'}
</Descriptions.Item>
<Descriptions.Item label="班主任">
{teachers.find((t) => t.roleType === 'head_teacher')?.username || '-'}
{(() => {
const headTeacher = teachers.find(
(teacher) => teacher.roleType === 'head_teacher',
);
return headTeacher ? getTeacherName(headTeacher) : '-';
})()}
</Descriptions.Item>
<Descriptions.Item label="备注">{detail.notes || '-'}</Descriptions.Item>
</Descriptions>

View File

@@ -21,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 ----
@@ -167,6 +168,15 @@ const ClassesPage: React.FC = () => {
}
};
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(
() => [
{
@@ -174,33 +184,103 @@ const ClassesPage: React.FC = () => {
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: '编码',
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: 'code', width: 140 },
{
title: '班型',
dataIndex: 'classType',
width: 100,
render: (v: string) => <Tag>{TYPE_MAP[v] || v}</Tag>,
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) => v || '-',
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) => `${r.studentCount || 0}/${r.maxStudents || '-'}`,
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) => {
const cfg = STATUS_MAP[v] || { color: 'default', text: v };
return <Tag color={cfg.color}>{cfg.text}</Tag>;
},
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: '操作',
@@ -237,7 +317,7 @@ const ClassesPage: React.FC = () => {
),
},
],
[],
[saveCell],
);
return (

View File

@@ -10,7 +10,6 @@ const baseUser = (overrides: Partial<TeacherCandidateUser> = {}): TeacherCandida
id: 1,
username: 'teacher',
name: '测试老师',
isActive: true,
isArchived: false,
studentStatus: null,
roles: [{ code: 'teacher', name: '任课老师' }],
@@ -29,13 +28,12 @@ describe('class teacher candidates', () => {
expect(isTeacherCandidate(baseUser({ studentStatus: 'staff' }))).toBe(true);
});
it('excludes active students, disabled, archived, and super-admin accounts', () => {
it('excludes active students, archived, and super-admin accounts', () => {
const users = [
baseUser({ id: 1, studentStatus: 'active' }),
baseUser({ id: 2, isActive: false }),
baseUser({ id: 3, isArchived: true }),
baseUser({ id: 2, isArchived: true }),
baseUser({
id: 4,
id: 3,
roles: [{ code: 'super_admin', name: '超级管理员' }],
}),
];

View File

@@ -7,7 +7,6 @@ export interface TeacherCandidateUser {
id: number;
username: string;
name?: string | null;
isActive: boolean;
isArchived: boolean;
studentStatus?: string | null;
roles?: TeacherCandidateRole[];
@@ -18,7 +17,7 @@ const isSuperAdminRole = (role: TeacherCandidateRole) =>
role.code === 'super_admin' || role.name === '超级管理员' || role.name === '超管';
export const isTeacherCandidate = (user: TeacherCandidateUser) => {
if (!user.isActive || user.isArchived) return false;
if (user.isArchived) return false;
if (user.studentStatus && user.studentStatus !== 'staff') return false;
return !(user.roles || []).some(isSuperAdminRole);
};

View File

@@ -26,6 +26,7 @@ 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';
@@ -36,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[]>([]);
@@ -214,6 +215,12 @@ 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}`);
@@ -279,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,
@@ -319,13 +387,35 @@ 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: '状态',
@@ -356,11 +446,13 @@ const ClassroomRentalsPage: React.FC = () => {
</Button>
</Tooltip>
<Popconfirm title="移除合同文件?" onConfirm={() => handleDeleteContract(r.id)}>
<Button size="small" danger icon={<StopOutlined />} 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}
@@ -389,6 +481,8 @@ const ClassroomRentalsPage: React.FC = () => {
PDF
</Button>
</Upload>
) : (
'-'
),
},
{
@@ -448,7 +542,7 @@ const ClassroomRentalsPage: React.FC = () => {
),
},
],
[],
[classrooms, organizations, hasPermission],
);
return (

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);
@@ -110,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}`);
@@ -155,16 +164,83 @@ const ClassroomsPage: React.FC = () => {
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: '楼栋',
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: '楼栋', dataIndex: 'building', width: 80 },
{ title: '楼层', dataIndex: 'floor', width: 80 },
{
title: '类型',
width: 90,
dataIndex: 'roomType',
render: (v: string) => <Tag color={typeColor[v] || 'default'}>{v || '-'}</Tag>,
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: '容量', dataIndex: 'capacity', width: 80 },
{
title: '状态',
width: 100,
@@ -175,17 +251,29 @@ const ClassroomsPage: React.FC = () => {
) => {
const effectiveStatus = record.effectiveStatus || record.status;
return (
<Tooltip
title={
record.currentUsage
? `${record.currentUsage.title} (${record.currentUsage.startTime}-${record.currentUsage.endTime})`
: undefined
}
<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)}
>
<Tag color={statusMap[effectiveStatus]?.color}>
{statusMap[effectiveStatus]?.text || effectiveStatus}
</Tag>
</Tooltip>
<Tooltip
title={
record.currentUsage
? `${record.currentUsage.title} (${record.currentUsage.startTime}-${record.currentUsage.endTime})`
: undefined
}
>
<Tag color={statusMap[effectiveStatus]?.color}>
{statusMap[effectiveStatus]?.text || effectiveStatus}
</Tag>
</Tooltip>
</EditableCell>
);
},
},
@@ -316,27 +404,29 @@ const ClassroomsPage: React.FC = () => {
>
</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' },
});
message.success(res.message);
onSuccess?.(res);
fetchData();
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
}}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
{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 />}

View File

@@ -10,7 +10,6 @@ import {
Space,
Tag,
Popconfirm,
List,
Card,
Empty,
} from 'antd';
@@ -18,6 +17,7 @@ import { PlusOutlined, InboxOutlined, DollarOutlined, TeamOutlined } from '@ant-
import dayjs from 'dayjs';
import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell';
import { message } from '../../ui/app-message';
import { buildDepositStudentOptions, type DepositStudentLookup } from './deposit-student-option';
@@ -314,6 +314,20 @@ 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}`);
@@ -691,49 +705,85 @@ const DepositsPage: React.FC = () => {
</PermissionButton>
</div>
{detailModal.installments && detailModal.installments.length > 0 ? (
<List
<Table
size="small"
pagination={false}
rowKey="id"
dataSource={detailModal.installments}
renderItem={(item) => (
<List.Item
actions={[
item.status === 'pending' && (
<PermissionButton
key="pay"
permission="deposit:edit"
size="small"
type="primary"
icon={<DollarOutlined />}
onClick={() => handlePayInstallment(item.id)}
>
</PermissionButton>
),
<Popconfirm
key="archive"
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={<InboxOutlined />}
{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>
</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>
)}
<PermissionButton
permission="deposit:delete"
size="small"
danger
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
</Space>
),
},
]}
/>
) : (
<p style={{ color: '#999' }}></p>

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: '入学测试' },
];

View File

@@ -22,12 +22,16 @@ import {
UploadOutlined,
DownloadOutlined,
ExportOutlined,
UndoOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell';
import { downloadBlob } from '../../utils/download';
import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
import { archiveViewPolicy, expenseStatusForView } from '../archive-view';
const { RangePicker } = DatePicker;
@@ -37,6 +41,7 @@ const isFormValidationError = (error: unknown) =>
Array.isArray((error as { errorFields?: unknown }).errorFields);
const ExpensesPage: React.FC = () => {
const { hasPermission } = usePermission();
const [roomExpenses, setRoomExpenses] = useState<any[]>([]);
const [personalExpenses, setPersonalExpenses] = useState<any[]>([]);
const [rooms, setRooms] = useState<any[]>([]);
@@ -58,6 +63,8 @@ const ExpensesPage: React.FC = () => {
const [selectedPersonalKeys, setSelectedPersonalKeys] = useState<number[]>([]);
const [saving, setSaving] = useState(false);
const [batchLoading, setBatchLoading] = useState(false);
const [showArchived, setShowArchived] = useState(false);
const expenseViewPolicy = archiveViewPolicy(showArchived ? 'archived' : 'active');
// Dynamic expense type options from API
const [typeOptions, setTypeOptions] = useState<{ value: string; label: string }[]>([]);
@@ -121,12 +128,56 @@ const ExpensesPage: React.FC = () => {
}
};
const handleBatchRestoreRoom = async () => {
if (batchLoading) return;
setBatchLoading(true);
try {
const res = await api.put<{ restored: number; skipped: number }>(
'/expenses/room/batch-restore',
{ ids: selectedRoomKeys },
);
message.success(
`已恢复 ${res.restored} 条宿舍费用${res.skipped ? `,跳过 ${res.skipped}` : ''}`,
);
setSelectedRoomKeys([]);
fetchData();
} catch (e: any) {
message.error(e?.message || '批量恢复失败');
} finally {
setBatchLoading(false);
}
};
const handleBatchRestorePersonal = async () => {
if (batchLoading) return;
setBatchLoading(true);
try {
const res = await api.put<{ restored: number; skipped: number }>(
'/expenses/personal/batch-restore',
{ ids: selectedPersonalKeys },
);
message.success(
`已恢复 ${res.restored} 条个人费用${res.skipped ? `,跳过 ${res.skipped}` : ''}`,
);
setSelectedPersonalKeys([]);
fetchData();
} catch (e: any) {
message.error(e?.message || '批量恢复失败');
} finally {
setBatchLoading(false);
}
};
const fetchData = useCallback(async () => {
setLoading(true);
try {
const [re, pe, lookups]: any[] = await Promise.all([
api.get('/expenses/room'),
api.get('/expenses/personal'),
api.get('/expenses/room', {
params: { status: expenseStatusForView(showArchived ? 'archived' : 'active') },
}),
api.get('/expenses/personal', {
params: { status: expenseStatusForView(showArchived ? 'archived' : 'active') },
}),
api.get('/expenses/lookups').catch(() => ({ rooms: [], students: [] })),
]);
setRoomExpenses(re);
@@ -137,10 +188,12 @@ const ExpensesPage: React.FC = () => {
message.error(e?.message || '加载失败,请稍后重试');
}
setLoading(false);
}, []);
}, [showArchived]);
useEffect(() => {
fetchData();
setSelectedRoomKeys([]);
setSelectedPersonalKeys([]);
}, [fetchData]);
const filteredRoomExpenses = useMemo(() => {
@@ -197,6 +250,24 @@ const ExpensesPage: React.FC = () => {
}
};
const saveRoomCell = useCallback(
async (record: any, field: string, value: unknown) => {
await api.put(`/expenses/room/${record.id}`, { [field]: value });
message.success('已保存');
await fetchData();
},
[fetchData],
);
const savePersonalCell = useCallback(
async (record: any, field: string, value: unknown) => {
await api.put(`/expenses/personal/${record.id}`, { [field]: value });
message.success('已保存');
await fetchData();
},
[fetchData],
);
const handleStudentUtility = async () => {
const values = await utilityForm.validateFields();
setSaving(true);
@@ -257,25 +328,92 @@ const ExpensesPage: React.FC = () => {
const roomColumns = useMemo(
() => [
{ title: '宿舍', width: 120, render: (_: any, r: any) => r.room?.roomNumber || '-' },
{
title: '宿舍',
width: 120,
render: (_: any, r: any) => (
<EditableCell
value={r.roomId}
editor="select"
options={rooms.map((item) => ({ value: item.id, label: item.roomNumber }))}
permission="expense:edit"
disabled={expenseViewPolicy.readonly}
required
onSave={(next) => saveRoomCell(r, 'roomId', next)}
>
{r.room?.roomNumber || '-'}
</EditableCell>
),
},
{
title: '费用类型',
width: 100,
dataIndex: 'expenseType',
render: (v: string) => <Tag>{typeMap[v] || v}</Tag>,
render: (v: string, r: any) => (
<EditableCell
value={v}
editor="select"
options={typeOptions}
permission="expense:edit"
disabled={expenseViewPolicy.readonly}
required
onSave={(next) => saveRoomCell(r, 'expenseType', next)}
>
<Tag>{typeMap[v] || v}</Tag>
</EditableCell>
),
},
{
title: '金额',
dataIndex: 'amount',
width: 100,
render: (v: number) => `¥${Number(v).toFixed(2)}`,
render: (v: number, r: any) => (
<EditableCell
value={v}
editor="money"
min={0.01}
permission="expense:edit"
disabled={expenseViewPolicy.readonly}
required
onSave={(next) => saveRoomCell(r, 'amount', next)}
>{`¥${Number(v).toFixed(2)}`}</EditableCell>
),
},
{
title: '账单周期',
width: 200,
render: (_: any, r: any) => `${r.periodStart} ~ ${r.periodEnd}`,
render: (_: any, r: any) => (
<EditableCell
value={[r.periodStart, r.periodEnd]}
editor="date-range"
permission="expense:edit"
disabled={expenseViewPolicy.readonly}
required
onSave={async (next) => {
const [periodStart, periodEnd] = next as unknown as [string, string];
await api.put(`/expenses/room/${r.id}`, { periodStart, periodEnd });
message.success('已保存');
await fetchData();
}}
>{`${r.periodStart} ~ ${r.periodEnd}`}</EditableCell>
),
},
{
title: '说明',
dataIndex: 'description',
width: 150,
render: (v: string, r: any) => (
<EditableCell
value={v}
editor="textarea"
permission="expense:edit"
disabled={expenseViewPolicy.readonly}
onSave={(next) => saveRoomCell(r, 'description', next)}
>
{v || '-'}
</EditableCell>
),
},
{ title: '说明', dataIndex: 'description', width: 150 },
{
title: '录入时间',
width: 160,
@@ -285,112 +423,217 @@ const ExpensesPage: React.FC = () => {
{
title: '操作',
width: 120,
render: (_: any, record: any) => (
<Space>
<PermissionButton
permission="expense:edit"
size="small"
icon={<EditOutlined />}
onClick={() => {
setEditingRoom(record);
roomForm.setFieldsValue({
roomId: record.roomId,
expenseType: record.expenseType,
amount: Number(record.amount),
period: [dayjs(record.periodStart), dayjs(record.periodEnd)],
description: record.description,
});
setRoomModal(true);
}}
>
</PermissionButton>
<Popconfirm
title="确定归档?"
onConfirm={async () => {
await api.delete(`/expenses/room/${record.id}`);
message.success('归档成功');
fetchData();
}}
>
render: (_: any, record: any) =>
showArchived ? (
<Tag color="#999"></Tag>
) : (
<Space>
<PermissionButton
permission="expense:delete"
permission="expense:edit"
size="small"
danger
icon={<InboxOutlined />}
icon={<EditOutlined />}
onClick={() => {
setEditingRoom(record);
roomForm.setFieldsValue({
roomId: record.roomId,
expenseType: record.expenseType,
amount: Number(record.amount),
period: [dayjs(record.periodStart), dayjs(record.periodEnd)],
description: record.description,
});
setRoomModal(true);
}}
>
</PermissionButton>
</Popconfirm>
</Space>
),
<Popconfirm
title="确定归档?"
onConfirm={async () => {
await api.delete(`/expenses/room/${record.id}`);
message.success('归档成功');
fetchData();
}}
>
<PermissionButton
permission="expense:delete"
size="small"
danger
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
</Space>
),
},
],
[setEditingRoom, roomForm, setRoomModal, fetchData, typeMap],
[
rooms,
typeOptions,
typeMap,
saveRoomCell,
roomForm,
fetchData,
showArchived,
expenseViewPolicy.readonly,
],
);
const personalColumns = useMemo(
() => [
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
{
title: '学生',
width: 120,
render: (_: any, r: any) => (
<EditableCell
value={r.studentId}
editor="select"
options={students.map((item) => ({ value: item.id, label: item.name }))}
permission="expense:edit"
disabled={expenseViewPolicy.readonly}
required
onSave={(next) => savePersonalCell(r, 'studentId', next)}
>
{r.student?.name || '-'}
</EditableCell>
),
},
{
title: '费用类型',
width: 100,
dataIndex: 'expenseType',
render: (v: string) => <Tag color="orange">{typeMap[v] || v}</Tag>,
render: (v: string, r: any) => (
<EditableCell
value={v}
editor="select"
options={personalTypeOptions}
permission="expense:edit"
disabled={expenseViewPolicy.readonly}
required
onSave={(next) => savePersonalCell(r, 'expenseType', next)}
>
<Tag color="orange">{typeMap[v] || v}</Tag>
</EditableCell>
),
},
{
title: '金额',
dataIndex: 'amount',
render: (v: number, r: any) => (
<EditableCell
value={v}
editor="money"
min={0.01}
permission="expense:edit"
disabled={expenseViewPolicy.readonly}
required
onSave={(next) => savePersonalCell(r, 'amount', next)}
>{`¥${Number(v).toFixed(2)}`}</EditableCell>
),
},
{
title: '日期',
dataIndex: 'expenseDate',
width: 110,
render: (v: string, r: any) => (
<EditableCell
value={v}
editor="date"
permission="expense:edit"
disabled={expenseViewPolicy.readonly}
required
onSave={(next) => savePersonalCell(r, 'expenseDate', next)}
>
{v}
</EditableCell>
),
},
{
title: '说明',
dataIndex: 'description',
width: 150,
render: (v: string, r: any) => (
<EditableCell
value={v}
editor="textarea"
permission="expense:edit"
disabled={expenseViewPolicy.readonly}
onSave={(next) => savePersonalCell(r, 'description', next)}
>
{v || '-'}
</EditableCell>
),
},
{ title: '金额', dataIndex: 'amount', render: (v: number) => `¥${Number(v).toFixed(2)}` },
{ title: '日期', dataIndex: 'expenseDate', width: 110 },
{ title: '说明', dataIndex: 'description', width: 150 },
{
title: '操作',
width: 120,
render: (_: any, record: any) => (
<Space>
<PermissionButton
permission="expense:edit"
size="small"
icon={<EditOutlined />}
onClick={() => {
setEditingPersonal(record);
personalForm.setFieldsValue({
studentId: record.studentId,
roomId: record.roomId,
expenseType: record.expenseType,
amount: Number(record.amount),
expenseDate: dayjs(record.expenseDate),
description: record.description,
});
setPersonalModal(true);
}}
>
</PermissionButton>
<Popconfirm
title="确定归档?"
onConfirm={async () => {
await api.delete(`/expenses/personal/${record.id}`);
message.success('归档成功');
fetchData();
}}
>
render: (_: any, record: any) =>
showArchived ? (
<Tag color="#999"></Tag>
) : (
<Space>
<PermissionButton
permission="expense:delete"
permission="expense:edit"
size="small"
danger
icon={<InboxOutlined />}
icon={<EditOutlined />}
onClick={() => {
setEditingPersonal(record);
personalForm.setFieldsValue({
studentId: record.studentId,
roomId: record.roomId,
expenseType: record.expenseType,
amount: Number(record.amount),
expenseDate: dayjs(record.expenseDate),
description: record.description,
});
setPersonalModal(true);
}}
>
</PermissionButton>
</Popconfirm>
</Space>
),
<Popconfirm
title="确定归档?"
onConfirm={async () => {
await api.delete(`/expenses/personal/${record.id}`);
message.success('归档成功');
fetchData();
}}
>
<PermissionButton
permission="expense:delete"
size="small"
danger
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
</Space>
),
},
],
[setEditingPersonal, personalForm, setPersonalModal, fetchData, typeMap],
[
students,
personalTypeOptions,
typeMap,
savePersonalCell,
personalForm,
fetchData,
showArchived,
expenseViewPolicy.readonly,
],
);
return (
<div>
<Space style={{ marginBottom: 16 }}>
<Button type={!showArchived ? 'primary' : 'default'} onClick={() => setShowArchived(false)}>
</Button>
<Button type={showArchived ? 'primary' : 'default'} onClick={() => setShowArchived(true)}>
</Button>
</Space>
<Tabs
items={[
{
@@ -425,74 +668,100 @@ const ExpensesPage: React.FC = () => {
onChange={(v) => setRoomTypeFilter(v)}
options={typeOptions}
/>
<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('/expenses/utility/import', formData);
if (res.errors?.length > 0) {
Modal.warning({
title: res.message,
content: res.errors.join('\n'),
width: 500,
});
} else {
message.success(res.message);
{!showArchived && hasPermission('expense: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('/expenses/utility/import', formData);
if (res.errors?.length > 0) {
Modal.warning({
title: res.message,
content: res.errors.join('\n'),
width: 500,
});
} else {
message.success(res.message);
}
onSuccess?.(res);
fetchData();
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
onSuccess?.(res);
fetchData();
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
}}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
<PermissionButton
permission="expense:view"
icon={<DownloadOutlined />}
onClick={() => {
downloadBlob('/expenses/utility/template', '水电费导入模板.xlsx').catch(
() => message.error('下载失败'),
);
}}
>
</PermissionButton>
}}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
) : null}
{!showArchived ? (
<PermissionButton
permission="expense:view"
icon={<DownloadOutlined />}
onClick={() => {
downloadBlob('/expenses/utility/template', '水电费导入模板.xlsx').catch(
() => message.error('下载失败'),
);
}}
>
</PermissionButton>
) : null}
</Space>
<Space>
<Popconfirm
title={`确定归档选中的 ${selectedRoomKeys.length} 条费用?`}
onConfirm={handleBatchDeleteRoom}
okText="归档"
cancelText="取消"
disabled={selectedRoomKeys.length === 0}
>
<PermissionButton
permission="expense:delete"
danger
icon={<InboxOutlined />}
{showArchived ? (
<Popconfirm
title={`确定恢复选中的 ${selectedRoomKeys.length} 条费用?`}
onConfirm={handleBatchRestoreRoom}
okText="恢复"
cancelText="取消"
disabled={selectedRoomKeys.length === 0}
>
<PermissionButton
permission="expense:edit"
type="primary"
icon={<UndoOutlined />}
loading={batchLoading}
disabled={selectedRoomKeys.length === 0}
>
</PermissionButton>
</Popconfirm>
) : (
<Popconfirm
title={`确定归档选中的 ${selectedRoomKeys.length} 条费用?`}
onConfirm={handleBatchDeleteRoom}
okText="归档"
cancelText="取消"
disabled={selectedRoomKeys.length === 0}
>
<PermissionButton
permission="expense:delete"
danger
icon={<InboxOutlined />}
disabled={selectedRoomKeys.length === 0}
>
</PermissionButton>
</Popconfirm>
)}
{!showArchived ? (
<PermissionButton
permission="expense:create"
type="primary"
icon={<PlusOutlined />}
onClick={() => {
setEditingRoom(null);
roomForm.resetFields();
setRoomModal(true);
}}
>
宿
</PermissionButton>
</Popconfirm>
<PermissionButton
permission="expense:create"
type="primary"
icon={<PlusOutlined />}
onClick={() => {
setEditingRoom(null);
roomForm.resetFields();
setRoomModal(true);
}}
>
宿
</PermissionButton>
) : null}
</Space>
</div>
<Table
@@ -548,90 +817,120 @@ const ExpensesPage: React.FC = () => {
onChange={(v) => setPersonalTypeFilter(v)}
options={personalTypeOptions}
/>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }: any) => {
try {
const formData = new FormData();
formData.append('file', file);
const res: any = await api.post('/expenses/personal/import', formData);
message.success(res.message || '导入完成');
if (res.errors?.length)
res.errors.forEach((e: string) => message.warning(e));
fetchData();
onSuccess?.(res);
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
}}
>
<Button icon={<UploadOutlined />}></Button>
</Upload>
<PermissionButton
permission="expense:view"
icon={<DownloadOutlined />}
onClick={() => {
downloadBlob(
'/expenses/personal/template',
'个人附加费导入模板.xlsx',
).catch(() => message.error('下载失败'));
}}
>
</PermissionButton>
<PermissionButton
permission="expense:view"
icon={<ExportOutlined />}
onClick={() => {
downloadBlob('/expenses/personal/export', '个人附加费导出.xlsx').catch(() =>
message.error('导出失败'),
);
}}
>
</PermissionButton>
{!showArchived && hasPermission('expense:create') ? (
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }: any) => {
try {
const formData = new FormData();
formData.append('file', file);
const res: any = await api.post('/expenses/personal/import', formData);
message.success(res.message || '导入完成');
if (res.errors?.length)
res.errors.forEach((e: string) => message.warning(e));
fetchData();
onSuccess?.(res);
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
}}
>
<Button icon={<UploadOutlined />}></Button>
</Upload>
) : null}
{!showArchived ? (
<PermissionButton
permission="expense:view"
icon={<DownloadOutlined />}
onClick={() => {
downloadBlob(
'/expenses/personal/template',
'个人附加费导入模板.xlsx',
).catch(() => message.error('下载失败'));
}}
>
</PermissionButton>
) : null}
{!showArchived ? (
<PermissionButton
permission="expense:view"
icon={<ExportOutlined />}
onClick={() => {
downloadBlob('/expenses/personal/export', '个人附加费导出.xlsx').catch(
() => message.error('导出失败'),
);
}}
>
</PermissionButton>
) : null}
</Space>
<Space>
<Popconfirm
title={`确定归档选中的 ${selectedPersonalKeys.length} 条个人费用?`}
onConfirm={handleBatchDeletePersonal}
okText="归档"
cancelText="取消"
disabled={selectedPersonalKeys.length === 0}
>
<PermissionButton
permission="expense:delete"
danger
icon={<InboxOutlined />}
{showArchived ? (
<Popconfirm
title={`确定恢复选中的 ${selectedPersonalKeys.length} 条个人费用?`}
onConfirm={handleBatchRestorePersonal}
okText="恢复"
cancelText="取消"
disabled={selectedPersonalKeys.length === 0}
>
<PermissionButton
permission="expense:edit"
type="primary"
icon={<UndoOutlined />}
loading={batchLoading}
disabled={selectedPersonalKeys.length === 0}
>
</PermissionButton>
</Popconfirm>
) : (
<Popconfirm
title={`确定归档选中的 ${selectedPersonalKeys.length} 条个人费用?`}
onConfirm={handleBatchDeletePersonal}
okText="归档"
cancelText="取消"
disabled={selectedPersonalKeys.length === 0}
>
<PermissionButton
permission="expense:delete"
danger
icon={<InboxOutlined />}
disabled={selectedPersonalKeys.length === 0}
>
</PermissionButton>
</Popconfirm>
)}
{!showArchived ? (
<PermissionButton
permission="expense:create"
icon={<PlusOutlined />}
onClick={() => {
utilityForm.resetFields();
setUtilityModal(true);
}}
>
</PermissionButton>
</Popconfirm>
<PermissionButton
permission="expense:create"
icon={<PlusOutlined />}
onClick={() => {
utilityForm.resetFields();
setUtilityModal(true);
}}
>
</PermissionButton>
<PermissionButton
permission="expense:create"
type="primary"
icon={<PlusOutlined />}
onClick={() => {
setEditingPersonal(null);
personalForm.resetFields();
setPersonalModal(true);
}}
>
</PermissionButton>
) : null}
{!showArchived ? (
<PermissionButton
permission="expense:create"
type="primary"
icon={<PlusOutlined />}
onClick={() => {
setEditingPersonal(null);
personalForm.resetFields();
setPersonalModal(true);
}}
>
</PermissionButton>
) : null}
</Space>
</div>
<Table

View File

@@ -41,6 +41,12 @@ import {
isAppSecretRequired,
type DingTalkConfigFormValues,
} from './integration-config-form';
import {
cacheDingTalkDraft,
cacheDingTalkServerSnapshot,
commitDingTalkConfig,
readDingTalkConfigCache,
} from './integration-config-cache';
interface DingTalkConfig {
agentId: string;
@@ -111,12 +117,14 @@ 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 [config, setConfig] = useState<DingTalkConfig | null>(initialCache.config);
const [verified, setVerified] = useState<boolean | null>(initialCache.verified);
const [form] = Form.useForm<DingTalkConfigFormValues>();
// ── Manual organization sync ──
@@ -136,8 +144,8 @@ 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;
@@ -147,18 +155,24 @@ const IntegrationConfigPage: React.FC = () => {
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();
@@ -167,6 +181,8 @@ const IntegrationConfigPage: React.FC = () => {
try {
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 };
@@ -458,12 +474,14 @@ const IntegrationConfigPage: React.FC = () => {
>
</Button>
<Button
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0}
onClick={() => setClassModalOpen(true)}
>
</Button>
{canCreateClass ? (
<Button
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0}
onClick={() => setClassModalOpen(true)}
>
</Button>
) : null}
</Space>
}
>
@@ -485,9 +503,11 @@ const IntegrationConfigPage: React.FC = () => {
title="班级列表"
size="small"
extra={
<Button size="small" onClick={() => setClassModalOpen(true)}>
+
</Button>
canCreateClass ? (
<Button size="small" onClick={() => setClassModalOpen(true)}>
+
</Button>
) : null
}
>
<List
@@ -514,45 +534,47 @@ const IntegrationConfigPage: React.FC = () => {
</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="notes" label="备注">
<Input.TextArea rows={2} />
</Form.Item>
</Form>
</Modal>
{canCreateClass ? (
<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="notes" label="备注">
<Input.TextArea rows={2} />
</Form.Item>
</Form>
</Modal>
) : null}
</Drawer>
)}
<Modal
@@ -624,7 +646,13 @@ const IntegrationConfigPage: React.FC = () => {
showIcon
/>
<Form form={form} layout="vertical" style={{ maxWidth: 520 }}>
<Form
form={form}
layout="vertical"
initialValues={initialCache.formValues}
onValuesChange={(_changed, values) => cacheDingTalkDraft(values)}
style={{ maxWidth: 520 }}
>
<Form.Item
name="corpId"
label="CorpId企业ID"

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

@@ -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;
@@ -15,6 +15,7 @@ const LoginPage: React.FC = () => {
const onFinish = useCallback(
async (values: any) => {
clearPermissions();
setLoading(true);
try {
const res: any = await api.post('/auth/login', values);
@@ -56,24 +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 name="login" layout="vertical" onFinish={onFinish} size="large">
<Form.Item
label="用户名"
name="username"
rules={[{ required: true, message: '请输入用户名' }]}
>
<Input prefix={<UserOutlined />} placeholder="用户名" />
<Input prefix={<UserOutlined />} placeholder="用户名" autoComplete="username" />
</Form.Item>
<Form.Item
label="密码"
name="password"
rules={[{ required: true, message: '请输入密码' }]}
>
<Input.Password prefix={<LockOutlined />} placeholder="密码" />
<Input.Password
prefix={<LockOutlined />}
placeholder="密码"
autoComplete="current-password"
/>
</Form.Item>
<Form.Item>
<Button

View File

@@ -25,6 +25,7 @@ import {
UploadOutlined,
DownloadOutlined,
ExportOutlined,
UndoOutlined,
} from '@ant-design/icons';
import dayjs, { type Dayjs } from 'dayjs';
import api from '../../api';
@@ -33,10 +34,17 @@ import { maskPhone, maskIdNumber } from '../../utils/sensitive';
import PermissionButton from '../../components/PermissionButton';
import { message } from '../../ui/app-message';
import { buildCheckInPayload, buildTransferPayload } from './occupancy-form';
import { usePermission } from '../../hooks/usePermission';
import { occupancyParamsForView, occupancyViewPolicy, type OccupancyView } from '../archive-view';
const { RangePicker } = DatePicker;
const OccupanciesPage: React.FC = () => {
const { hasPermission, permissionsReady } = usePermission();
const canCheckIn = permissionsReady && hasPermission('occupancy:checkin');
const canCheckOut = permissionsReady && hasPermission('occupancy:checkout');
const canTransfer = permissionsReady && hasPermission('occupancy:transfer');
const canDelete = permissionsReady && hasPermission('occupancy:delete');
const [data, setData] = useState<any[]>([]);
const [students, setStudents] = useState<any[]>([]);
const [rooms, setRooms] = useState<any[]>([]);
@@ -44,7 +52,8 @@ const OccupanciesPage: React.FC = () => {
const [checkInModal, setCheckInModal] = useState(false);
const [checkOutModal, setCheckOutModal] = useState<any>(null);
const [transferModal, setTransferModal] = useState<any>(null);
const [showActive, setShowActive] = useState(true);
const [viewMode, setViewMode] = useState<OccupancyView>('active');
const viewPolicy = occupancyViewPolicy(viewMode);
const [autoDeposit, setAutoDeposit] = useState(true);
const [depositAmount, setDepositAmount] = useState(500);
const [searchText, setSearchText] = useState('');
@@ -66,6 +75,32 @@ const OccupanciesPage: React.FC = () => {
const selectedCheckInRoomId = Form.useWatch('roomId', checkInForm);
const selectedTransferRoomId = Form.useWatch('newRoomId', transferForm);
// Close modals when the user loses the required permission
useEffect(() => {
if (!canCheckIn) {
setCheckInModal(false);
checkInForm.resetFields();
}
}, [canCheckIn, checkInForm]);
useEffect(() => {
if (!canCheckOut && checkOutModal) {
setCheckOutModal(null);
checkOutForm.resetFields();
}
}, [canCheckOut, checkOutModal, checkOutForm]);
useEffect(() => {
if (!canCheckOut) {
setBatchCheckOutModal(false);
batchCheckOutForm.resetFields();
}
}, [canCheckOut, batchCheckOutForm]);
useEffect(() => {
if (!canTransfer && transferModal) {
setTransferModal(null);
transferForm.resetFields();
}
}, [canTransfer, transferModal, transferForm]);
const activeOccupancyByStudentId = useMemo(() => {
const map = new Map<number, any>();
data.forEach((item) => {
@@ -93,7 +128,12 @@ const OccupanciesPage: React.FC = () => {
[data, selectedRowKeys],
);
const latestSelectedCheckInDate = useMemo(
() => selectedBatchRecords.map((item) => item.checkInDate).filter(Boolean).sort().at(-1),
() =>
selectedBatchRecords
.map((item) => item.checkInDate)
.filter(Boolean)
.sort()
.at(-1),
[selectedBatchRecords],
);
const latestSelectedBillingStartDate = useMemo(
@@ -106,7 +146,8 @@ const OccupanciesPage: React.FC = () => {
[selectedBatchRecords],
);
const dateNotBefore = (start: string | Dayjs | null | undefined, messageText: string) =>
const dateNotBefore =
(start: string | Dayjs | null | undefined, messageText: string) =>
(_: unknown, value?: Dayjs | null) => {
if (!value || !start) return Promise.resolve();
const startDate = dayjs.isDayjs(start) ? start : dayjs(start);
@@ -121,7 +162,7 @@ const OccupanciesPage: React.FC = () => {
const [occRes, stuRes, rmRes] = (await Promise.allSettled([
api.get('/occupancies', {
params: {
active: showActive ? 'true' : undefined,
...occupancyParamsForView(viewMode),
dateFrom: dateRange?.[0]?.format('YYYY-MM-DD'),
dateTo: dateRange?.[1]?.format('YYYY-MM-DD'),
},
@@ -143,7 +184,7 @@ const OccupanciesPage: React.FC = () => {
message.error('数据加载异常');
}
setLoading(false);
}, [showActive, dateRange]);
}, [viewMode, dateRange]);
useEffect(() => {
fetchData();
@@ -267,6 +308,7 @@ const OccupanciesPage: React.FC = () => {
};
const handleBatchCheckOut = async () => {
if (batchLoading) return;
const values = await batchCheckOutForm.validateFields();
setBatchLoading(true);
try {
@@ -289,6 +331,7 @@ const OccupanciesPage: React.FC = () => {
};
const handleBatchDelete = async () => {
if (batchLoading) return;
setBatchLoading(true);
try {
const res: any = await api.post('/occupancies/batch-delete', { ids: selectedRowKeys });
@@ -302,6 +345,26 @@ const OccupanciesPage: React.FC = () => {
}
};
const handleBatchRestore = async () => {
if (batchLoading) return;
setBatchLoading(true);
try {
const res = await api.put<{ restored: number; skipped: number }>(
'/occupancies/batch-restore',
{ ids: selectedRowKeys },
);
message.success(
`已恢复 ${res.restored} 条入住记录${res.skipped ? `,跳过 ${res.skipped}` : ''}`,
);
setSelectedRowKeys([]);
fetchData();
} catch (e: any) {
message.error(e?.message || '批量恢复失败');
} finally {
setBatchLoading(false);
}
};
const columns = useMemo(
() => [
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
@@ -332,7 +395,9 @@ const OccupanciesPage: React.FC = () => {
title: '操作',
width: 220,
render: (_: any, record: any) =>
!record.checkOutDate ? (
viewPolicy.readonly ? (
<Tag color="#999"></Tag>
) : !record.checkOutDate ? (
<Space>
<PermissionButton
permission="occupancy:checkout"
@@ -363,42 +428,47 @@ const OccupanciesPage: React.FC = () => {
) : (
<Space>
<Tag>退宿</Tag>
<Popconfirm
title="确定归档此记录?"
onConfirm={async () => {
try {
await api.delete(`/occupancies/${record.id}`);
message.success('归档成功');
fetchData();
} catch (e: any) {
message.error(e?.message || '归档失败');
}
}}
>
<PermissionButton
permission="occupancy:delete"
size="small"
danger
icon={<InboxOutlined />}
{canDelete ? (
<Popconfirm
title="确定归档此记录?"
onConfirm={async () => {
try {
await api.delete(`/occupancies/${record.id}`);
message.success('归档成功');
fetchData();
} catch (e: any) {
message.error(e?.message || '归档失败');
}
}}
>
</PermissionButton>
</Popconfirm>
<Button size="small" danger icon={<InboxOutlined />}>
</Button>
</Popconfirm>
) : null}
</Space>
),
},
],
[fetchData, setCheckOutModal, checkOutForm, setTransferModal, transferForm],
[
fetchData,
setCheckOutModal,
checkOutForm,
setTransferModal,
transferForm,
viewPolicy.readonly,
],
);
const rowSelection = useMemo(
() => ({
selectedRowKeys,
onChange: (keys: any[]) => setSelectedRowKeys(keys),
// 「在住记录」Tab禁用已退宿防止误选用于批量退宿「全部记录」Tab均可选用于批量归档
getCheckboxProps: (record: any) => (showActive ? { disabled: !!record.checkOutDate } : {}),
// 「在住记录」视图禁用已退宿;其余视图中的记录均可选择。
getCheckboxProps: (record: any) =>
viewMode === 'active' ? { disabled: !!record.checkOutDate } : {},
}),
[selectedRowKeys, showActive],
[selectedRowKeys, viewMode],
);
return (
@@ -413,12 +483,24 @@ const OccupanciesPage: React.FC = () => {
/>
<div className="responsive-toolbar">
<Space wrap className="responsive-toolbar__group">
<Button type={showActive ? 'primary' : 'default'} onClick={() => setShowActive(true)}>
<Button
type={viewMode === 'active' ? 'primary' : 'default'}
onClick={() => setViewMode('active')}
>
</Button>
<Button type={!showActive ? 'primary' : 'default'} onClick={() => setShowActive(false)}>
<Button
type={viewMode === 'all' ? 'primary' : 'default'}
onClick={() => setViewMode('all')}
>
</Button>
<Button
type={viewMode === 'archived' ? 'primary' : 'default'}
onClick={() => setViewMode('archived')}
>
</Button>
<Input.Search
placeholder="搜索学生姓名或房间号"
onSearch={setSearchText}
@@ -435,119 +517,129 @@ const OccupanciesPage: React.FC = () => {
/>
</Space>
<Space wrap className="responsive-toolbar__group">
<PermissionButton
permission="occupancy:checkin"
type="primary"
icon={<PlusOutlined />}
onClick={() => {
checkInForm.resetFields();
setAvailableBeds([]);
setAvailableLockers([]);
setAvailableResourcesLoading(false);
const today = dayjs();
checkInForm.setFieldsValue({
checkInDate: today,
billingStartDate: today,
stayType: 'short',
collectDeposit: true,
depositAmount: 500,
});
setCheckInModal(true);
}}
>
</PermissionButton>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }: any) => {
const formData = new FormData();
formData.append('file', file);
const params = new URLSearchParams();
if (autoDeposit) {
params.set('autoDeposit', 'true');
params.set('depositAmount', String(depositAmount));
}
try {
const res: any = await api.post(
`/occupancies/import?${params.toString()}`,
formData,
{ headers: { 'Content-Type': 'multipart/form-data' } },
{viewMode !== 'archived' ? (
<PermissionButton
permission="occupancy:checkin"
type="primary"
icon={<PlusOutlined />}
onClick={() => {
checkInForm.resetFields();
setAvailableBeds([]);
setAvailableLockers([]);
setAvailableResourcesLoading(false);
const today = dayjs();
checkInForm.setFieldsValue({
checkInDate: today,
billingStartDate: today,
stayType: 'short',
collectDeposit: true,
depositAmount: 500,
});
setCheckInModal(true);
}}
>
</PermissionButton>
) : null}
{viewMode !== 'archived' && canCheckIn ? (
<>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }: any) => {
const formData = new FormData();
formData.append('file', file);
const params = new URLSearchParams();
if (autoDeposit) {
params.set('autoDeposit', 'true');
params.set('depositAmount', String(depositAmount));
}
try {
const res: any = await api.post(
`/occupancies/import?${params.toString()}`,
formData,
{ headers: { 'Content-Type': 'multipart/form-data' } },
);
if (res.errors?.length > 0) {
Modal.warning({
title: res.message,
content: res.errors.join('\n'),
width: 500,
});
} else {
message.success(res.message);
}
onSuccess?.(res);
fetchData();
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
}}
>
<Tooltip title="按手机号关联学生,并自动创建缺失的学生、宿舍和入住记录">
<Button type="primary" ghost icon={<UploadOutlined />}>
</Button>
</Tooltip>
</Upload>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
<Switch size="small" checked={autoDeposit} onChange={setAutoDeposit} />
{autoDeposit && (
<Space.Compact>
<InputNumber
size="small"
min={0}
value={depositAmount}
onChange={(v) => setDepositAmount(v || 500)}
style={{ width: 60 }}
/>
<span
style={{
padding: '0 8px',
display: 'flex',
alignItems: 'center',
border: '1px solid #d9d9d9',
backgroundColor: '#fafafa',
fontSize: 12,
}}
>
</span>
</Space.Compact>
)}
</span>
</>
) : null}
{viewMode !== 'archived' ? (
<PermissionButton
permission="occupancy:view"
icon={<DownloadOutlined />}
onClick={() => {
downloadBlob('/occupancies/template', '入住名单导入模板.xlsx').catch(() =>
message.error('下载失败'),
);
if (res.errors?.length > 0) {
Modal.warning({
title: res.message,
content: res.errors.join('\n'),
width: 500,
});
} else {
message.success(res.message);
}
onSuccess?.(res);
fetchData();
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
}}
>
<Tooltip title="按手机号关联学生,并自动创建缺失的学生、宿舍和入住记录">
<Button type="primary" ghost icon={<UploadOutlined />}>
</Button>
</Tooltip>
</Upload>
<PermissionButton
permission="occupancy:view"
icon={<DownloadOutlined />}
onClick={() => {
downloadBlob('/occupancies/template', '入住名单导入模板.xlsx').catch(() =>
message.error('下载失败'),
);
}}
>
</PermissionButton>
<PermissionButton
permission="occupancy:view"
icon={<ExportOutlined />}
onClick={() => {
const params = showActive ? '?active=true' : '';
const filename = showActive ? '在住记录.xlsx' : '全部入住记录.xlsx';
downloadBlob('/occupancies/export' + params, filename).catch(() =>
message.error('导出失败'),
);
}}
>
</PermissionButton>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
<Switch size="small" checked={autoDeposit} onChange={setAutoDeposit} />
{autoDeposit && (
<Space.Compact>
<InputNumber
size="small"
min={0}
value={depositAmount}
onChange={(v) => setDepositAmount(v || 500)}
style={{ width: 60 }}
/>
<span
style={{
padding: '0 8px',
display: 'flex',
alignItems: 'center',
border: '1px solid #d9d9d9',
backgroundColor: '#fafafa',
fontSize: 12,
}}
>
</span>
</Space.Compact>
)}
</span>
}}
>
</PermissionButton>
) : null}
{viewMode !== 'archived' ? (
<PermissionButton
permission="occupancy:view"
icon={<ExportOutlined />}
onClick={() => {
const params = viewMode === 'active' ? '?active=true' : '';
const filename = viewMode === 'active' ? '在住记录.xlsx' : '全部入住记录.xlsx';
downloadBlob('/occupancies/export' + params, filename).catch(() =>
message.error('导出失败'),
);
}}
>
</PermissionButton>
) : null}
</Space>
</div>
{selectedRowKeys.length > 0 && (
@@ -555,7 +647,7 @@ const OccupanciesPage: React.FC = () => {
title={
<span>
<strong>{selectedRowKeys.length}</strong>
{showActive ? (
{viewPolicy.batchAction === 'checkout' ? (
<PermissionButton
permission="occupancy:checkout"
type="primary"
@@ -571,25 +663,43 @@ const OccupanciesPage: React.FC = () => {
>
退宿
</PermissionButton>
) : (
) : viewPolicy.batchAction === 'archive' ? (
canDelete ? (
<Popconfirm
title={`确定归档选中的 ${selectedRowKeys.length} 条入住记录?在住记录会自动跳过`}
onConfirm={handleBatchDelete}
okText="归档"
cancelText="取消"
>
<Button
danger
size="small"
icon={<InboxOutlined />}
style={{ marginLeft: 12 }}
loading={batchLoading}
>
</Button>
</Popconfirm>
) : null
) : canDelete ? (
<Popconfirm
title={`确定归档选中的 ${selectedRowKeys.length} 条入住记录?在住记录会自动跳过`}
onConfirm={handleBatchDelete}
okText="归档"
title={`确定恢复选中的 ${selectedRowKeys.length} 条入住记录?`}
onConfirm={handleBatchRestore}
okText="恢复"
cancelText="取消"
>
<PermissionButton
permission="occupancy:delete"
danger
<Button
type="primary"
size="small"
icon={<InboxOutlined />}
icon={<UndoOutlined />}
style={{ marginLeft: 12 }}
loading={batchLoading}
>
</PermissionButton>
</Button>
</Popconfirm>
)}
) : null}
<Button size="small" onClick={() => setSelectedRowKeys([])} style={{ marginLeft: 8 }}>
</Button>
@@ -616,8 +726,8 @@ const OccupanciesPage: React.FC = () => {
/>
<Modal
title="入住登记"
open={checkInModal}
onOk={handleCheckIn}
open={checkInModal && canCheckIn}
onOk={canCheckIn ? handleCheckIn : undefined}
onCancel={() => {
setCheckInModal(false);
setAvailableBeds([]);
@@ -642,7 +752,11 @@ const OccupanciesPage: React.FC = () => {
.filter((s: any) => s.status === 'active')
.map((s: any) => {
const activeOccupancy = activeOccupancyByStudentId.get(s.id);
const identifier = s.idNumber ? maskIdNumber(s.idNumber) : s.phone ? maskPhone(s.phone) : '';
const identifier = s.idNumber
? maskIdNumber(s.idNumber)
: s.phone
? maskPhone(s.phone)
: '';
return {
value: s.id,
label: `${s.name} (${identifier})${activeOccupancy ? ` · 已入住${activeOccupancy.room?.roomNumber ? ` ${activeOccupancy.room.roomNumber}` : ''}` : ''}`,
@@ -668,18 +782,25 @@ const OccupanciesPage: React.FC = () => {
}))}
/>
</Form.Item>
<Form.Item name="checkInDate" label="入住日期" rules={[{ required: true, message: '请选择入住日期' }]}>
<Form.Item
name="checkInDate"
label="入住日期"
rules={[{ required: true, message: '请选择入住日期' }]}
>
<DatePicker style={{ width: '100%' }} placeholder="选择入住日期" format="YYYY-MM-DD" />
</Form.Item>
<Form.Item
name="billingStartDate"
label="计费起始日"
dependencies={["checkInDate"]}
dependencies={['checkInDate']}
extra="默认与入住日期相同,可调整(如学生要求从次日开始计费)"
rules={[
{ required: true, message: '请选择计费起始日' },
({ getFieldValue }) => ({
validator: dateNotBefore(getFieldValue('checkInDate'), '计费起始日不能早于入住日期'),
validator: dateNotBefore(
getFieldValue('checkInDate'),
'计费起始日不能早于入住日期',
),
}),
]}
>
@@ -689,7 +810,11 @@ const OccupanciesPage: React.FC = () => {
format="YYYY-MM-DD"
/>
</Form.Item>
<Form.Item name="stayType" label="入住类型" rules={[{ required: true, message: '请选择入住类型' }]}>
<Form.Item
name="stayType"
label="入住类型"
rules={[{ required: true, message: '请选择入住类型' }]}
>
<Select
options={[
{ value: 'short', label: '短租' },
@@ -714,7 +839,9 @@ const OccupanciesPage: React.FC = () => {
<Select
placeholder={selectedCheckInRoomId ? '请选择床位' : '请先选择房间'}
loading={availableResourcesLoading}
disabled={!selectedCheckInRoomId || availableResourcesLoading || availableBeds.length === 0}
disabled={
!selectedCheckInRoomId || availableResourcesLoading || availableBeds.length === 0
}
options={availableBeds.map((b) => ({
value: b.id,
label: b.bedNumber,
@@ -732,7 +859,9 @@ const OccupanciesPage: React.FC = () => {
allowClear
placeholder="可选分配柜子"
loading={availableResourcesLoading}
disabled={!selectedCheckInRoomId || availableResourcesLoading || availableLockers.length === 0}
disabled={
!selectedCheckInRoomId || availableResourcesLoading || availableLockers.length === 0
}
options={availableLockers.map((l) => ({
value: l.id,
label: l.lockerNumber,
@@ -772,8 +901,8 @@ const OccupanciesPage: React.FC = () => {
{/* 退宿弹窗 */}
<Modal
title={`退宿 - ${checkOutModal?.student?.name}`}
open={!!checkOutModal}
onOk={handleCheckOut}
open={!!checkOutModal && canCheckOut}
onOk={canCheckOut ? handleCheckOut : undefined}
onCancel={() => setCheckOutModal(null)}
okText="确认退宿"
confirmLoading={saving}
@@ -792,12 +921,14 @@ const OccupanciesPage: React.FC = () => {
<Form.Item
name="billingEndDate"
label="计费截止日"
dependencies={["checkOutDate"]}
dependencies={['checkOutDate']}
extra="默认与退宿日期相同"
rules={[
({ getFieldValue }) => ({
validator: dateNotBefore(
checkOutModal?.billingStartDate || checkOutModal?.checkInDate || getFieldValue('checkOutDate'),
checkOutModal?.billingStartDate ||
checkOutModal?.checkInDate ||
getFieldValue('checkOutDate'),
'计费截止日不能早于计费起始日',
),
}),
@@ -827,8 +958,8 @@ const OccupanciesPage: React.FC = () => {
{/* 批量退宿弹窗 */}
<Modal
title={`批量退宿(${selectedRowKeys.length} 人)`}
open={batchCheckOutModal}
onOk={handleBatchCheckOut}
open={batchCheckOutModal && canCheckOut}
onOk={canCheckOut ? handleBatchCheckOut : undefined}
onCancel={() => setBatchCheckOutModal(false)}
okText="确认批量退宿"
width={500}
@@ -904,7 +1035,7 @@ const OccupanciesPage: React.FC = () => {
{/* 换房弹窗 */}
<Modal
title={`换房 - ${transferModal?.student?.name}`}
open={!!transferModal}
open={!!transferModal && canTransfer}
onOk={handleTransfer}
onCancel={() => {
setTransferModal(null);
@@ -948,7 +1079,11 @@ const OccupanciesPage: React.FC = () => {
<Select
placeholder={selectedTransferRoomId ? '请选择目标床位' : '请先选择目标宿舍'}
loading={transferResourcesLoading}
disabled={!selectedTransferRoomId || transferResourcesLoading || transferAvailableBeds.length === 0}
disabled={
!selectedTransferRoomId ||
transferResourcesLoading ||
transferAvailableBeds.length === 0
}
options={transferAvailableBeds.map((bed) => ({
value: bed.id,
label: bed.bedNumber,
@@ -966,7 +1101,11 @@ const OccupanciesPage: React.FC = () => {
allowClear
placeholder="可选分配目标宿舍柜子"
loading={transferResourcesLoading}
disabled={!selectedTransferRoomId || transferResourcesLoading || transferAvailableLockers.length === 0}
disabled={
!selectedTransferRoomId ||
transferResourcesLoading ||
transferAvailableLockers.length === 0
}
options={transferAvailableLockers.map((locker) => ({
value: locker.id,
label: locker.lockerNumber,
@@ -979,7 +1118,9 @@ const OccupanciesPage: React.FC = () => {
label="换房日期"
rules={[
{ required: true, message: '请选择换房日期' },
{ validator: dateNotBefore(transferModal?.checkInDate, '换房日期不能早于原入住日期') },
{
validator: dateNotBefore(transferModal?.checkInDate, '换房日期不能早于原入住日期'),
},
]}
>
<DatePicker style={{ width: '100%' }} placeholder="选择换房日期" format="YYYY-MM-DD" />
@@ -987,12 +1128,14 @@ const OccupanciesPage: React.FC = () => {
<Form.Item
name="oldBillingEndDate"
label="旧房计费截止日"
dependencies={["transferDate"]}
dependencies={['transferDate']}
extra="默认为换房当天"
rules={[
({ getFieldValue }) => ({
validator: dateNotBefore(
transferModal?.billingStartDate || transferModal?.checkInDate || getFieldValue('transferDate'),
transferModal?.billingStartDate ||
transferModal?.checkInDate ||
getFieldValue('transferDate'),
'旧房计费截止日不能早于计费起始日',
),
}),
@@ -1007,11 +1150,14 @@ const OccupanciesPage: React.FC = () => {
<Form.Item
name="newBillingStartDate"
label="新房计费起始日"
dependencies={["transferDate"]}
dependencies={['transferDate']}
extra="默认为换房次日"
rules={[
({ getFieldValue }) => ({
validator: dateNotBefore(getFieldValue('transferDate'), '新房计费起始日不能早于换房日期'),
validator: dateNotBefore(
getFieldValue('transferDate'),
'新房计费起始日不能早于换房日期',
),
}),
]}
>

View File

@@ -3,6 +3,7 @@ import { Alert, Empty, Form, Input, Modal, Popconfirm, Select, Space, Table, Tag
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',

View File

@@ -41,6 +41,7 @@ const PermissionsPage: React.FC = () => {
integration: '集成配置',
notification: '通知中心',
ai: 'AI 模型配置',
'ai-chat': 'AI 助手',
};
useEffect(() => {

View File

@@ -3,6 +3,7 @@ import { Table, Modal, Form, Input, Space, Tag, Popconfirm, Card, Checkbox, Empt
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 {
@@ -131,23 +132,77 @@ const RolesPage: React.FC = () => {
sync: '数据同步',
integration: '集成配置',
ai: 'AI 配置',
'ai-chat': 'AI 助手',
};
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();
},
[fetchData],
);
const columns = useMemo(
() => [
{ title: 'ID', dataIndex: 'id', width: 80 },
{ title: '名称', dataIndex: 'name', width: 120 },
{ title: '描述', dataIndex: 'description', width: 200 },
{
title: '名称',
dataIndex: 'name',
width: 120,
render: (v: string, r: RoleItem) => (
<EditableCell
value={v}
required
permission="role:edit"
onSave={(next) => saveCell(r, 'name', next)}
>
{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[]) =>
perms?.length > 0 ? (
<Tag color="blue">{perms.length} </Tag>
) : (
<Tag color="default"></Tag>
),
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: '系统',
@@ -186,7 +241,7 @@ const RolesPage: React.FC = () => {
),
},
],
[],
[permissionOptions, saveCell],
);
const handleGroupCheckAll = (group: string, checked: boolean) => {

View File

@@ -13,6 +13,8 @@ import {
DatePicker,
Alert,
Button,
Switch,
Space,
} from 'antd';
import {
HomeOutlined,
@@ -21,10 +23,15 @@ import {
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;
@@ -84,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');
@@ -104,6 +114,42 @@ 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) => {
@@ -345,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>
))}
@@ -388,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',
@@ -407,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];
}

View File

@@ -29,7 +29,10 @@ import {
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';
import { selectArchiveRecords } from '../archive-view';
const statusMap: Record<string, { text: string; color: string }> = {
available: { text: '可入住', color: 'green' },
@@ -83,12 +86,16 @@ function parseRoomNumber(input: string) {
}
const RoomsPage: React.FC = () => {
const { hasPermission, permissionsReady } = usePermission();
const canEditRooms = permissionsReady && hasPermission('room:edit');
const canCreateRooms = permissionsReady && hasPermission('room:create');
const canDeleteRooms = permissionsReady && hasPermission('room:delete');
const [data, setData] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
const [editing, setEditing] = useState<any>(null);
const canSaveRoom = editing ? canEditRooms : canCreateRooms;
const [showArchived, setShowArchived] = useState(false);
const [archivedCount, setArchivedCount] = useState(0);
const [searchText, setSearchText] = useState('');
const [filterBuilding, setFilterBuilding] = useState<string | undefined>(undefined);
const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
@@ -110,7 +117,17 @@ const RoomsPage: React.FC = () => {
const [savingLocker, setSavingLocker] = useState(false);
const [batchLoading, setBatchLoading] = useState(false);
// Close modals when the required permission is lost
useEffect(() => {
if (!canSaveRoom && modalOpen) {
setModalOpen(false);
setEditing(null);
form.resetFields();
}
}, [canSaveRoom, modalOpen, form]);
const handleBatchDelete = async () => {
if (batchLoading) return;
setBatchLoading(true);
try {
const res: any = await api.post('/rooms/batch-delete', { ids: selectedRowKeys });
@@ -124,14 +141,32 @@ const RoomsPage: React.FC = () => {
}
};
const handleBatchRestore = async () => {
if (batchLoading) return;
setBatchLoading(true);
try {
const res = await api.put<{ message?: string; restored: number; skipped: number }>(
'/rooms/batch-restore',
{ ids: selectedRowKeys },
);
message.success(
`已批量恢复 ${res.restored}${res.skipped ? `,跳过 ${res.skipped}` : ''}`,
);
setSelectedRowKeys([]);
fetchData();
} catch (e: any) {
message.error(e?.message || '批量恢复失败');
} finally {
setBatchLoading(false);
}
};
const fetchData = async () => {
setLoading(true);
try {
const params: any = { includeArchived: 'true' };
const params: any = { includeArchived: showArchived ? 'true' : undefined };
const res: any = await api.get('/rooms/overview', { params });
const archived = res.filter((r: any) => r.status === 'archived');
setArchivedCount(archived.length);
const filtered = showArchived ? res : res.filter((r: any) => r.status !== 'archived');
const filtered = selectArchiveRecords(res, showArchived ? 'archived' : 'active');
setData(filtered);
} catch (e: unknown) {
const err = e as { message?: string };
@@ -199,6 +234,26 @@ const RoomsPage: React.FC = () => {
setSaving(false);
}
};
const saveRoomCell = async (record: any, field: string, value: unknown) => {
await api.put(`/rooms/${record.id}`, { [field]: value });
message.success('已保存');
await fetchData();
};
const saveBedCell = async (record: BedItem, field: string, value: unknown) => {
if (!drawerRoom) return;
await api.put(`/rooms/${drawerRoom.id}/beds/${record.id}`, { [field]: value });
message.success('已保存');
await fetchBeds(drawerRoom.id);
};
const saveLockerCell = async (record: LockerItem, field: string, value: unknown) => {
if (!drawerRoom) return;
await api.put(`/rooms/${drawerRoom.id}/lockers/${record.id}`, { [field]: value });
message.success('已保存');
await fetchLockers(drawerRoom.id);
};
const fetchBeds = useCallback(async (roomId: number) => {
try {
const res = await api.get<BedItem[]>(`/rooms/${roomId}/beds`);
@@ -337,27 +392,123 @@ const RoomsPage: React.FC = () => {
dataIndex: 'roomNumber',
width: 100,
sorter: (a: any, b: any) => a.roomNumber.localeCompare(b.roomNumber),
render: (v: string, r: any) => (
<EditableCell
value={v}
required
permission="room:edit"
disabled={r.status === 'archived'}
onSave={(next) => saveRoomCell(r, 'roomNumber', next)}
>
{v}
</EditableCell>
),
},
{
title: '楼栋',
dataIndex: 'building',
width: 80,
render: (v: string, r: any) => (
<EditableCell
value={v}
permission="room:edit"
disabled={r.status === 'archived'}
onSave={(next) => saveRoomCell(r, 'building', next)}
>
{v || '-'}
</EditableCell>
),
},
{
title: '楼层',
dataIndex: 'floor',
width: 80,
render: (v: number, r: any) => (
<EditableCell
value={v}
editor="number"
permission="room:edit"
disabled={r.status === 'archived'}
onSave={(next) => saveRoomCell(r, 'floor', next)}
>
{v ?? '-'}
</EditableCell>
),
},
{
title: '类型',
dataIndex: 'roomType',
width: 90,
render: (v: any, r: any) => (
<EditableCell
value={v}
permission="room:edit"
disabled={r.status === 'archived'}
onSave={(next) => saveRoomCell(r, 'roomType', next)}
>
{v || '-'}
</EditableCell>
),
},
{ title: '楼栋', dataIndex: 'building', width: 80 },
{ title: '楼层', dataIndex: 'floor', width: 80 },
{ title: '类型', dataIndex: 'roomType', width: 90, render: (v: any) => v || '-' },
{
title: '租赁类型',
dataIndex: 'rentalCategory',
width: 100,
render: (v: string) => {
if (v === 'long') return <Tag color="blue"></Tag>;
if (v === 'short') return <Tag color="green"></Tag>;
return '-';
},
render: (v: string, r: any) => (
<EditableCell
value={v}
editor="select"
options={[
{ value: 'long', label: '长租' },
{ value: 'short', label: '短租' },
]}
permission="room:edit"
disabled={r.status === 'archived'}
onSave={(next) => saveRoomCell(r, 'rentalCategory', next)}
>
{(() => {
if (v === 'long') return <Tag color="blue"></Tag>;
if (v === 'short') return <Tag color="green"></Tag>;
return '-';
})()}
</EditableCell>
),
},
{
title: '月租金',
dataIndex: 'monthlyRate',
width: 100,
render: (v: number) => (v ? `¥${v}` : '-'),
render: (v: number, r: any) => (
<EditableCell
value={v}
editor="money"
min={0}
permission="room:edit"
disabled={r.status === 'archived'}
onSave={(next) => saveRoomCell(r, 'monthlyRate', next)}
>
{v ? `¥${v}` : '-'}
</EditableCell>
),
},
{
title: '额定人数',
dataIndex: 'capacity',
width: 80,
render: (v: number, r: any) => (
<EditableCell
value={v}
editor="number"
min={1}
required
permission="room:edit"
disabled={r.status === 'archived'}
onSave={(next) => saveRoomCell(r, 'capacity', next)}
>
{v}
</EditableCell>
),
},
{ title: '额定人数', dataIndex: 'capacity', width: 80 },
{
title: '当前入住',
width: 80,
@@ -377,7 +528,22 @@ const RoomsPage: React.FC = () => {
title: '状态',
dataIndex: 'status',
width: 80,
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>,
render: (s: string, r: any) => (
<EditableCell
value={s}
editor="select"
options={[
{ value: 'available', label: '可入住' },
{ value: 'full', label: '已满' },
{ value: 'maintenance', label: '维修中' },
]}
permission="room:edit"
disabled={r.status === 'archived'}
onSave={(next) => saveRoomCell(r, 'status', next)}
>
<Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>
</EditableCell>
),
},
{
title: '操作',
@@ -387,16 +553,13 @@ const RoomsPage: React.FC = () => {
return (
<Space>
{r.status === 'archived' ? (
<Popconfirm title="确定恢复此宿舍?" onConfirm={() => handleRestore(r.id)}>
<PermissionButton
permission="room:edit"
size="small"
icon={<UndoOutlined />}
type="link"
>
</PermissionButton>
</Popconfirm>
canEditRooms ? (
<Popconfirm title="确定恢复此宿舍?" onConfirm={() => handleRestore(r.id)}>
<Button size="small" icon={<UndoOutlined />} type="link">
</Button>
</Popconfirm>
) : null
) : (
<>
<PermissionButton
@@ -424,15 +587,13 @@ const RoomsPage: React.FC = () => {
>
</PermissionButton>
<Popconfirm title="确定归档?" onConfirm={() => handleArchive(r.id)}>
<PermissionButton
permission="room:delete"
size="small"
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
{canDeleteRooms ? (
<Popconfirm title="确定归档?" onConfirm={() => handleArchive(r.id)}>
<Button size="small" icon={<InboxOutlined />}>
</Button>
</Popconfirm>
) : null}
</>
)}
</Space>
@@ -495,70 +656,94 @@ const RoomsPage: React.FC = () => {
/>
<Button
type={showArchived ? 'primary' : 'default'}
onClick={() => setShowArchived(!showArchived)}
onClick={() => {
setShowArchived(!showArchived);
setFilterStatus(undefined);
setSelectedRowKeys([]);
}}
>
{showArchived
? '隐藏已归档'
: `显示已归档${archivedCount > 0 ? ` (${archivedCount})` : ''}`}
{showArchived ? '返回正常数据' : '查看已归档'}
</Button>
</Space>
<Space wrap className="responsive-toolbar__group">
<Popconfirm
title={`确定批量归档选中的 ${selectedRowKeys.length} 间宿舍?(有在住人员的会跳过)`}
onConfirm={handleBatchDelete}
okText="归档"
cancelText="取消"
disabled={selectedRowKeys.length === 0}
>
<PermissionButton
permission="room:delete"
danger
icon={<InboxOutlined />}
{showArchived && canEditRooms ? (
<Popconfirm
title={`确定批量恢复选中的 ${selectedRowKeys.length} 间宿舍?`}
onConfirm={handleBatchRestore}
okText="恢复"
cancelText="取消"
disabled={selectedRowKeys.length === 0}
loading={batchLoading}
>
<Button
type="primary"
icon={<UndoOutlined />}
disabled={selectedRowKeys.length === 0}
loading={batchLoading}
>
</Button>
</Popconfirm>
) : !showArchived && canDeleteRooms ? (
<Popconfirm
title={`确定批量归档选中的 ${selectedRowKeys.length} 间宿舍?(有在住人员的会跳过)`}
onConfirm={handleBatchDelete}
okText="归档"
cancelText="取消"
disabled={selectedRowKeys.length === 0}
>
<Button
danger
icon={<InboxOutlined />}
disabled={selectedRowKeys.length === 0}
loading={batchLoading}
>
</Button>
</Popconfirm>
) : null}
{!showArchived ? (
<PermissionButton
permission="room:create"
type="primary"
icon={<PlusOutlined />}
onClick={() => {
setEditing(null);
form.resetFields();
setModalOpen(true);
}}
>
宿
</PermissionButton>
</Popconfirm>
<PermissionButton
permission="room:create"
type="primary"
icon={<PlusOutlined />}
onClick={() => {
setEditing(null);
form.resetFields();
setModalOpen(true);
}}
>
宿
</PermissionButton>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async (options: UploadRequestOption<{ message?: string }>) => {
const { file, onSuccess, onError } = options;
if (typeof file === 'string') {
message.error('不支持字符串文件');
return;
}
try {
const formData = new FormData();
formData.append('file', file);
const res = await api.post<{ message?: string }>('/rooms/import', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
message.success(res.message || '导入成功');
onSuccess?.(res);
fetchData();
} catch (e: unknown) {
const err = e as { message?: string };
message.error(err?.message || '导入失败');
onError?.(e as UploadRequestError);
}
}}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
) : null}
{!showArchived && hasPermission('room:create') ? (
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async (options: UploadRequestOption<{ message?: string }>) => {
const { file, onSuccess, onError } = options;
if (typeof file === 'string') {
message.error('不支持字符串文件');
return;
}
try {
const formData = new FormData();
formData.append('file', file);
const res = await api.post<{ message?: string }>('/rooms/import', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
message.success(res.message || '导入成功');
onSuccess?.(res);
fetchData();
} catch (e: unknown) {
const err = e as { message?: string };
message.error(err?.message || '导入失败');
onError?.(e as UploadRequestError);
}
}}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
) : null}
<PermissionButton
permission="room:view"
icon={<DownloadOutlined />}
@@ -588,15 +773,14 @@ const RoomsPage: React.FC = () => {
rowSelection={{
selectedRowKeys,
onChange: (keys) => setSelectedRowKeys(keys as number[]),
getCheckboxProps: (record: any) => ({ disabled: record.status === 'archived' }),
}}
/>
<style>{`.archived-row { opacity: 0.6; background: #fafafa !important; }`}</style>
<Modal
title={editing ? '编辑宿舍' : '添加宿舍'}
open={modalOpen}
onOk={handleSave}
open={modalOpen && canSaveRoom}
onOk={canSaveRoom ? handleSave : undefined}
onCancel={() => {
setModalOpen(false);
setEditing(null);
@@ -722,77 +906,123 @@ const RoomsPage: React.FC = () => {
label: `床位管理 (${beds.length})`,
children: (
<div>
<div style={{ marginBottom: 12, display: 'flex', gap: 8 }}>
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
onClick={() => {
setBedEditing(null);
bedForm.resetFields();
setBedModalOpen(true);
}}
>
</Button>
<Popconfirm
title={remainingBedSlots > 0 ? '批量生成床位' : '床位已达到额定人数'}
description={
remainingBedSlots > 0 ? (
<InputNumber
min={1}
max={remainingBedSlots}
defaultValue={defaultBatchBedCount}
id="batch-bed-count"
style={{ width: 80 }}
/>
) : (
'如需增加床位,请先调整宿舍额定人数'
)
}
onConfirm={() => {
const input = document.getElementById(
'batch-bed-count',
) as HTMLInputElement;
handleBatchBeds(
input
? parseInt(input.value) || defaultBatchBedCount
: defaultBatchBedCount,
);
}}
okText="生成"
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
>
{canEditRooms ? (
<div style={{ marginBottom: 12, display: 'flex', gap: 8 }}>
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
onClick={() => {
setBedEditing(null);
bedForm.resetFields();
setBedModalOpen(true);
}}
>
</Button>
<Popconfirm
title={remainingBedSlots > 0 ? '批量生成床位' : '床位已达到额定人数'}
description={
remainingBedSlots > 0 ? (
<InputNumber
min={1}
max={remainingBedSlots}
defaultValue={defaultBatchBedCount}
id="batch-bed-count"
style={{ width: 80 }}
/>
) : (
'如需增加床位,请先调整宿舍额定人数'
)
}
onConfirm={() => {
const input = document.getElementById(
'batch-bed-count',
) as HTMLInputElement;
handleBatchBeds(
input
? parseInt(input.value) || defaultBatchBedCount
: defaultBatchBedCount,
);
}}
okText="生成"
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
>
</Button>
</Popconfirm>
</div>
<Button
size="small"
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
>
</Button>
</Popconfirm>
</div>
) : null}
<Table
dataSource={beds}
rowKey="id"
pagination={false}
size="small"
columns={[
{ title: '编号', dataIndex: 'bedNumber', width: 80 },
{
title: '编号',
dataIndex: 'bedNumber',
width: 80,
render: (v: string, r: BedItem) => (
<EditableCell
value={v}
required
permission="room:edit"
disabled={drawerRoom?.status === 'archived'}
onSave={(next) => saveBedCell(r, 'bedNumber', next)}
>
{v}
</EditableCell>
),
},
{
title: '状态',
dataIndex: 'status',
width: 80,
render: (s: string) => {
const map: Record<string, { text: string; color: string }> = {
available: { text: '空闲', color: 'green' },
occupied: { text: '占用', color: 'blue' },
maintenance: { text: '维修', color: 'orange' },
};
return <Tag color={map[s]?.color}>{map[s]?.text || s}</Tag>;
},
render: (s: string, r: BedItem) => (
<EditableCell
value={s}
editor="select"
options={[
{ value: 'available', label: '空闲' },
{ value: 'occupied', label: '占用' },
{ value: 'maintenance', label: '维修' },
]}
permission="room:edit"
disabled={drawerRoom?.status === 'archived'}
onSave={(next) => saveBedCell(r, 'status', next)}
>
{(() => {
const map: Record<string, { text: string; color: string }> = {
available: { text: '空闲', color: 'green' },
occupied: { text: '占用', color: 'blue' },
maintenance: { text: '维修', color: 'orange' },
};
return <Tag color={map[s]?.color}>{map[s]?.text || s}</Tag>;
})()}
</EditableCell>
),
},
{
title: '备注',
dataIndex: 'notes',
render: (v: string, r: BedItem) => (
<EditableCell
value={v}
editor="textarea"
permission="room:edit"
disabled={drawerRoom?.status === 'archived'}
onSave={(next) => saveBedCell(r, 'notes', next)}
>
{v || '-'}
</EditableCell>
),
},
{ title: '备注', dataIndex: 'notes', render: (v: string) => v || '-' },
{
title: '操作',
width: 120,
@@ -811,20 +1041,19 @@ const RoomsPage: React.FC = () => {
>
</PermissionButton>
{r.status !== 'occupied' && (
{r.status !== 'occupied' && canEditRooms && (
<Popconfirm
title="确定归档?"
onConfirm={() => handleDeleteBed(r.id)}
>
<PermissionButton
permission="room:edit"
<Button
size="small"
type="link"
danger
disabled={drawerRoom?.status === 'archived'}
>
</PermissionButton>
</Button>
</Popconfirm>
)}
</Space>
@@ -840,66 +1069,112 @@ const RoomsPage: React.FC = () => {
label: `柜子管理 (${lockers.length})`,
children: (
<div>
<div style={{ marginBottom: 12, display: 'flex', gap: 8 }}>
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
disabled={drawerRoom?.status === 'archived'}
onClick={() => {
setLockerEditing(null);
lockerForm.resetFields();
setLockerModalOpen(true);
}}
>
</Button>
<Popconfirm
title="批量生成柜子"
description={
<InputNumber
min={1}
max={20}
defaultValue={4}
id="batch-locker-count"
style={{ width: 80 }}
/>
}
onConfirm={() => {
const input = document.getElementById(
'batch-locker-count',
) as HTMLInputElement;
handleBatchLockers(input ? parseInt(input.value) || 4 : 4);
}}
okText="生成"
disabled={drawerRoom?.status === 'archived'}
>
<Button size="small" disabled={drawerRoom?.status === 'archived'}>
{canEditRooms ? (
<div style={{ marginBottom: 12, display: 'flex', gap: 8 }}>
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
disabled={drawerRoom?.status === 'archived'}
onClick={() => {
setLockerEditing(null);
lockerForm.resetFields();
setLockerModalOpen(true);
}}
>
</Button>
</Popconfirm>
</div>
<Popconfirm
title="批量生成柜子"
description={
<InputNumber
min={1}
max={20}
defaultValue={4}
id="batch-locker-count"
style={{ width: 80 }}
/>
}
onConfirm={() => {
const input = document.getElementById(
'batch-locker-count',
) as HTMLInputElement;
handleBatchLockers(input ? parseInt(input.value) || 4 : 4);
}}
okText="生成"
disabled={drawerRoom?.status === 'archived'}
>
<Button size="small" disabled={drawerRoom?.status === 'archived'}>
</Button>
</Popconfirm>
</div>
) : null}
<Table
dataSource={lockers}
rowKey="id"
pagination={false}
size="small"
columns={[
{ title: '编号', dataIndex: 'lockerNumber', width: 80 },
{
title: '编号',
dataIndex: 'lockerNumber',
width: 80,
render: (v: string, r: LockerItem) => (
<EditableCell
value={v}
required
permission="room:edit"
disabled={drawerRoom?.status === 'archived'}
onSave={(next) => saveLockerCell(r, 'lockerNumber', next)}
>
{v}
</EditableCell>
),
},
{
title: '状态',
dataIndex: 'status',
width: 80,
render: (s: string) => {
const map: Record<string, { text: string; color: string }> = {
available: { text: '空闲', color: 'green' },
occupied: { text: '占用', color: 'blue' },
maintenance: { text: '维修', color: 'orange' },
};
return <Tag color={map[s]?.color}>{map[s]?.text || s}</Tag>;
},
render: (s: string, r: LockerItem) => (
<EditableCell
value={s}
editor="select"
options={[
{ value: 'available', label: '空闲' },
{ value: 'occupied', label: '占用' },
{ value: 'maintenance', label: '维修' },
]}
permission="room:edit"
disabled={drawerRoom?.status === 'archived'}
onSave={(next) => saveLockerCell(r, 'status', next)}
>
{(() => {
const map: Record<string, { text: string; color: string }> = {
available: { text: '空闲', color: 'green' },
occupied: { text: '占用', color: 'blue' },
maintenance: { text: '维修', color: 'orange' },
};
return <Tag color={map[s]?.color}>{map[s]?.text || s}</Tag>;
})()}
</EditableCell>
),
},
{
title: '备注',
dataIndex: 'notes',
render: (v: string, r: LockerItem) => (
<EditableCell
value={v}
editor="textarea"
permission="room:edit"
disabled={drawerRoom?.status === 'archived'}
onSave={(next) => saveLockerCell(r, 'notes', next)}
>
{v || '-'}
</EditableCell>
),
},
{ title: '备注', dataIndex: 'notes', render: (v: string) => v || '-' },
{
title: '操作',
width: 120,
@@ -918,20 +1193,19 @@ const RoomsPage: React.FC = () => {
>
</PermissionButton>
{r.status !== 'occupied' && (
{r.status !== 'occupied' && canEditRooms && (
<Popconfirm
title="确定归档?"
onConfirm={() => handleDeleteLocker(r.id)}
>
<PermissionButton
permission="room:edit"
<Button
size="small"
type="link"
danger
disabled={drawerRoom?.status === 'archived'}
>
</PermissionButton>
</Button>
</Popconfirm>
)}
</Space>
@@ -948,8 +1222,8 @@ const RoomsPage: React.FC = () => {
<Modal
title={bedEditing ? '编辑床位' : '添加床位'}
open={bedModalOpen}
onOk={handleSaveBed}
open={bedModalOpen && canEditRooms}
onOk={canEditRooms ? handleSaveBed : undefined}
onCancel={() => {
setBedModalOpen(false);
setBedEditing(null);
@@ -978,8 +1252,8 @@ const RoomsPage: React.FC = () => {
<Modal
title={lockerEditing ? '编辑柜子' : '添加柜子'}
open={lockerModalOpen}
onOk={handleSaveLocker}
open={lockerModalOpen && canEditRooms}
onOk={canEditRooms ? handleSaveLocker : undefined}
onCancel={() => {
setLockerModalOpen(false);
setLockerEditing(null);

View File

@@ -21,6 +21,7 @@ import {
} from 'antd';
import type { UploadProps } from 'antd';
import {
CloudUploadOutlined,
DownloadOutlined,
ExportOutlined,
EyeOutlined,
@@ -33,8 +34,12 @@ import {
import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
import StudentProfileContent from '../../components/StudentProfileContent';
import EditableCell from '../../components/EditableCell';
import JinshujuMatchModal from '../../components/JinshujuMatchModal';
import { maskIdNumber, maskPhone } from '../../utils/sensitive';
import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
import { selectArchiveRecords } from '../archive-view';
const statusMap: Record<string, { text: string; color: string }> = {
active: { text: '在读', color: 'green' },
@@ -81,11 +86,24 @@ interface StudentFilterLookups {
const StudentsPage: React.FC = () => {
const { modal } = App.useApp();
const { hasPermission, hasAnyPermission, hasAllPermissions } = usePermission();
const canViewOrganizations = hasPermission('organization:view');
const canLoadOrganizations = hasAnyPermission(
'organization:view',
'student:create',
'student:edit',
);
const canChooseOrganization = hasAnyPermission('student:create', 'student:edit');
const canCreateStudent = hasPermission('student:create');
const canEditStudent = hasPermission('student:edit');
const canDeleteStudent = hasPermission('student:delete');
const canSyncJinshuju = hasAllPermissions('sync:read', 'sync:trigger');
const [data, setData] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
const [organizations, setOrganizations] = useState<any[]>([]);
const [editing, setEditing] = useState<any>(null);
const canSaveStudent = editing ? canEditStudent : canCreateStudent;
const [searchName, setSearchName] = useState('');
const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
const [filterOrganizationId, setFilterOrganizationId] = useState<number | undefined>(undefined);
@@ -94,7 +112,6 @@ const StudentsPage: React.FC = () => {
const [classOptions, setClassOptions] = useState<StudentFilterLookups['classes']>([]);
const [teacherOptions, setTeacherOptions] = useState<StudentFilterLookups['teachers']>([]);
const [showArchived, setShowArchived] = useState(false);
const [archivedCount, setArchivedCount] = useState(0);
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
const [batchLoading, setBatchLoading] = useState(false);
const [enrollmentData, setEnrollmentData] = useState<Record<number, EnrollmentInfo[]>>({});
@@ -108,13 +125,42 @@ const StudentsPage: React.FC = () => {
setDrawerOpen(true);
};
const [jinshujuOpen, setJinshujuOpen] = useState(false);
// Sensitive info modal — command-style; destroy when log:create is lost or comp unmounts.
// Close the student form modal when the user loses the required permission.
useEffect(() => {
if (!canSaveStudent && modalOpen) {
setModalOpen(false);
setEditing(null);
form.resetFields();
}
}, [canSaveStudent, modalOpen, form]);
// Close sensitive modal when log:create is lost (imperative ref already set above).
const logCreateRef = React.useRef(hasPermission('log:create'));
const sensitiveModalRef = React.useRef<ReturnType<typeof modal.confirm> | null>(null);
logCreateRef.current = hasPermission('log:create');
useEffect(() => {
if (!logCreateRef.current && sensitiveModalRef.current) {
sensitiveModalRef.current.destroy();
sensitiveModalRef.current = null;
}
return () => {
sensitiveModalRef.current?.destroy();
sensitiveModalRef.current = null;
};
}, []);
const handleViewSensitive = (studentId: number, field: string, value: string) => {
modal.confirm({
if (!logCreateRef.current) return;
sensitiveModalRef.current = modal.confirm({
title: '查看敏感信息',
content: `您即将查看 "${field}" 的完整信息。此操作将被记录。`,
okText: '确认查看',
cancelText: '取消',
onOk: async () => {
if (!logCreateRef.current) return;
try {
await api.post('/operation-logs/audit', {
module: '学生管理',
@@ -132,10 +178,14 @@ const StudentsPage: React.FC = () => {
message.error('审计日志记录失败,请稍后重试');
}
},
afterClose: () => {
sensitiveModalRef.current = null;
},
});
};
const handleBatchDelete = async () => {
if (batchLoading) return;
setBatchLoading(true);
try {
const res: any = await api.post('/students/batch-delete', { ids: selectedRowKeys });
@@ -149,40 +199,80 @@ const StudentsPage: React.FC = () => {
}
};
const handleBatchRestore = async () => {
if (batchLoading) return;
setBatchLoading(true);
try {
const res = await api.put<{ message?: string; restored: number; skipped: number }>(
'/students/batch-restore',
{ ids: selectedRowKeys },
);
message.success(
`已批量恢复 ${res.restored}${res.skipped ? `,跳过 ${res.skipped}` : ''}`,
);
setSelectedRowKeys([]);
fetchData();
} catch (e: any) {
message.error(e?.message || '批量恢复失败');
} finally {
setBatchLoading(false);
}
};
const fetchData = useCallback(async () => {
setLoading(true);
try {
const params: Record<string, unknown> = {
name: searchName || undefined,
includeArchived: 'true',
includeArchived: showArchived ? 'true' : undefined,
};
if (filterStatus) params.status = filterStatus;
if (showArchived) params.status = 'archived';
else if (filterStatus) params.status = filterStatus;
if (filterOrganizationId) params.organizationId = filterOrganizationId;
if (filterClassId) params.classId = filterClassId;
if (filterTeacherId) params.teacherId = filterTeacherId;
const res = (await api.get('/students', { params })) as Array<Record<string, unknown>>;
const list = res as Array<Record<string, unknown>>;
const archived = list.filter((r) => r.status === 'archived');
setArchivedCount(archived.length);
setData(showArchived ? list : list.filter((r) => r.status !== 'archived'));
setData(selectArchiveRecords(list, showArchived ? 'archived' : 'active'));
} catch (e: unknown) {
const err = e as { message?: string };
message.error(err?.message || '加载失败,请稍后重试');
}
setLoading(false);
}, [searchName, showArchived, filterStatus, filterOrganizationId, filterClassId, filterTeacherId]);
}, [
searchName,
showArchived,
filterStatus,
filterOrganizationId,
filterClassId,
filterTeacherId,
]);
useEffect(() => {
fetchData();
}, [fetchData]);
useEffect(() => {
api
.get('/organizations', { params: { includeArchived: 'false' } })
.then((res: unknown) => {
setOrganizations(res as Array<{ id: number; name: string }>);
})
.catch(() => {});
if (!canLoadOrganizations) {
setOrganizations([]);
setFilterOrganizationId(undefined);
return;
}
if (canViewOrganizations) {
api
.get('/organizations', { params: { includeArchived: 'false' } })
.then((res: unknown) => {
setOrganizations(res as Array<{ id: number; name: string; isHost?: boolean }>);
})
.catch(() => {});
} else {
api
.get('/organizations/options')
.then((res: unknown) => {
setOrganizations(res as Array<{ id: number; name: string; isHost?: boolean }>);
})
.catch(() => {});
}
api
.get<StudentFilterLookups>('/students/filter-lookups')
.then((res) => {
@@ -190,7 +280,7 @@ const StudentsPage: React.FC = () => {
setTeacherOptions(res.teachers || []);
})
.catch(() => {});
}, []);
}, [canLoadOrganizations]);
const handleSave = async () => {
const values = await form.validateFields();
setSaving(true);
@@ -213,6 +303,15 @@ const StudentsPage: React.FC = () => {
}
};
const saveCell = useCallback(
async (record: any, field: string, value: unknown) => {
await api.put(`/students/${record.id}`, { [field]: value });
message.success('已保存');
await fetchData();
},
[fetchData],
);
const handleArchive = async (id: number) => {
try {
await api.delete(`/students/${id}`);
@@ -376,9 +475,15 @@ const StudentsPage: React.FC = () => {
dataIndex: 'name',
width: 120,
render: (v: string, record: any) => (
<Button type="link" size="small" onClick={() => openDrawer(record.id)}>
<EditableCell
value={v}
required
permission="student:edit"
disabled={record.status === 'archived'}
onSave={(next) => saveCell(record, 'name', next)}
>
{v}
</Button>
</EditableCell>
),
},
{
@@ -390,15 +495,17 @@ const StudentsPage: React.FC = () => {
return (
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
<span style={{ marginRight: 4 }}>{maskPhone(v)}</span>
<Button
type="link"
size="small"
style={{ padding: '8px 4px', flex: 'none' }}
onClick={() => handleViewSensitive(record.id, '电话', v)}
title="点击查看完整号码"
>
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</Button>
{hasPermission('log:create') ? (
<Button
type="link"
size="small"
style={{ padding: '8px 4px', flex: 'none' }}
onClick={() => handleViewSensitive(record.id, '电话', v)}
title="点击查看完整号码"
>
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</Button>
) : null}
</span>
);
},
@@ -407,7 +514,16 @@ const StudentsPage: React.FC = () => {
title: '学号',
dataIndex: 'studentNo',
width: 120,
render: (v: string) => v || '-',
render: (v: string, record: any) => (
<EditableCell
value={v}
permission="student:edit"
disabled={record.status === 'archived'}
onSave={(next) => saveCell(record, 'studentNo', next)}
>
{v || '-'}
</EditableCell>
),
},
{
title: '身份证',
@@ -418,21 +534,51 @@ const StudentsPage: React.FC = () => {
return (
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
<span style={{ marginRight: 4 }}>{maskIdNumber(v)}</span>
<Button
type="link"
size="small"
style={{ padding: '8px 4px', flex: 'none' }}
onClick={() => handleViewSensitive(record.id, '身份证号', v)}
title="点击查看完整号码"
>
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</Button>
{hasPermission('log:create') ? (
<Button
type="link"
size="small"
style={{ padding: '8px 4px', flex: 'none' }}
onClick={() => handleViewSensitive(record.id, '身份证号', v)}
title="点击查看完整号码"
>
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</Button>
) : null}
</span>
);
},
},
{ title: '民族', dataIndex: 'ethnicity', width: 90 },
{ title: '紧急联系人', dataIndex: 'emergencyContact', width: 100 },
{
title: '民族',
dataIndex: 'ethnicity',
width: 90,
render: (v: string, record: any) => (
<EditableCell
value={v}
permission="student:edit"
disabled={record.status === 'archived'}
onSave={(next) => saveCell(record, 'ethnicity', next)}
>
{v || '-'}
</EditableCell>
),
},
{
title: '紧急联系人',
dataIndex: 'emergencyContact',
width: 100,
render: (v: string, record: any) => (
<EditableCell
value={v}
permission="student:edit"
disabled={record.status === 'archived'}
onSave={(next) => saveCell(record, 'emergencyContact', next)}
>
{v || '-'}
</EditableCell>
),
},
{
title: '紧急联系人电话',
dataIndex: 'emergencyPhone',
@@ -442,15 +588,17 @@ const StudentsPage: React.FC = () => {
return (
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
<span style={{ marginRight: 4 }}>{maskPhone(v)}</span>
<Button
type="link"
size="small"
style={{ padding: '8px 4px', flex: 'none' }}
onClick={() => handleViewSensitive(record.id, '紧急联系人电话', v)}
title="点击查看完整号码"
>
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</Button>
{hasPermission('log:create') ? (
<Button
type="link"
size="small"
style={{ padding: '8px 4px', flex: 'none' }}
onClick={() => handleViewSensitive(record.id, '紧急联系人电话', v)}
title="点击查看完整号码"
>
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</Button>
) : null}
</span>
);
},
@@ -459,30 +607,73 @@ const StudentsPage: React.FC = () => {
title: '所属机构',
dataIndex: 'organization',
width: 100,
render: (organization: { name?: string } | null) =>
organization?.name ? (
<Tag
color="purple"
style={{ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis' }}
render: (organization: { name?: string } | null, record: any) =>
canChooseOrganization ? (
<EditableCell
value={record.organizationId}
editor="select"
options={organizations.map((item) => ({ value: item.id, label: item.name }))}
permission="student:edit"
disabled={record.status === 'archived'}
required
onSave={(next) => saveCell(record, 'organizationId', next)}
>
{organization.name}
</Tag>
{organization?.name ? (
<Tag
color="purple"
style={{ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis' }}
>
{organization.name}
</Tag>
) : (
'-'
)}
</EditableCell>
) : organization?.name ? (
<Tag color="purple">{organization.name}</Tag>
) : (
'-'
),
},
{ title: '负责人', dataIndex: 'supervisor', width: 100 },
{
title: '负责人',
dataIndex: 'supervisor',
width: 100,
render: (v: string, record: any) => (
<EditableCell
value={v}
permission="student:edit"
disabled={record.status === 'archived'}
onSave={(next) => saveCell(record, 'supervisor', next)}
>
{v || '-'}
</EditableCell>
),
},
{
title: '状态',
dataIndex: 'status',
width: 80,
render: (s: string) => (
<Tag
color={statusMap[s]?.color}
style={{ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis' }}
render: (s: string, record: any) => (
<EditableCell
value={s}
editor="select"
options={[
{ value: 'active', label: '在读' },
{ value: 'graduated', label: '已毕业' },
{ value: 'withdrawn', label: '已退训' },
]}
permission="student:edit"
disabled={record.status === 'archived'}
onSave={(next) => saveCell(record, 'status', next)}
>
{statusMap[s]?.text || s}
</Tag>
<Tag
color={statusMap[s]?.color}
style={{ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis' }}
>
{statusMap[s]?.text || s}
</Tag>
</EditableCell>
),
},
{
@@ -491,21 +682,18 @@ const StudentsPage: React.FC = () => {
render: (_: any, record: any) => (
<Space>
{record.status === 'archived' ? (
<Popconfirm
title="确定恢复此学生?恢复后将重新出现在学生列表中。"
onConfirm={() => handleRestore(record.id)}
okText="恢复"
cancelText="取消"
>
<PermissionButton
permission="student:edit"
size="small"
icon={<UndoOutlined />}
type="link"
canEditStudent ? (
<Popconfirm
title="确定恢复此学生?恢复后将重新出现在学生列表中。"
onConfirm={() => handleRestore(record.id)}
okText="恢复"
cancelText="取消"
>
</PermissionButton>
</Popconfirm>
<Button size="small" icon={<UndoOutlined />} type="link">
</Button>
</Popconfirm>
) : null
) : (
<>
<PermissionButton
@@ -527,27 +715,33 @@ const StudentsPage: React.FC = () => {
>
</PermissionButton>
<Popconfirm
title="归档后不会删除数据,可随时恢复。确定归档?"
onConfirm={() => handleArchive(record.id)}
okText="归档"
cancelText="取消"
>
<PermissionButton
permission="student:delete"
size="small"
icon={<InboxOutlined />}
{canDeleteStudent ? (
<Popconfirm
title="归档后不会删除数据,可随时恢复。确定归档?"
onConfirm={() => handleArchive(record.id)}
okText="归档"
cancelText="取消"
>
</PermissionButton>
</Popconfirm>
<Button size="small" icon={<InboxOutlined />}>
</Button>
</Popconfirm>
) : null}
</>
)}
</Space>
),
},
],
[handleViewSensitive, openDrawer, showArchived, organizations],
[
handleViewSensitive,
openDrawer,
showArchived,
organizations,
saveCell,
hasPermission,
canChooseOrganization,
],
);
return (
@@ -577,21 +771,23 @@ const StudentsPage: React.FC = () => {
</Select.Option>
))}
</Select>
<Select
placeholder="所属机构"
allowClear
style={{ width: 140 }}
value={filterOrganizationId}
onChange={(v) => {
setFilterOrganizationId(v);
}}
>
{organizations.map((t: { id: number; name: string }) => (
<Select.Option key={t.id} value={t.id}>
{t.name}
</Select.Option>
))}
</Select>
{canViewOrganizations ? (
<Select
placeholder="所属机构"
allowClear
style={{ width: 140 }}
value={filterOrganizationId}
onChange={(v) => {
setFilterOrganizationId(v);
}}
>
{organizations.map((t: { id: number; name: string }) => (
<Select.Option key={t.id} value={t.id}>
{t.name}
</Select.Option>
))}
</Select>
) : null}
<Select
placeholder="所属班级"
allowClear
@@ -624,59 +820,90 @@ const StudentsPage: React.FC = () => {
/>
<Button
type={showArchived ? 'primary' : 'default'}
onClick={() => setShowArchived(!showArchived)}
onClick={() => {
setShowArchived(!showArchived);
setFilterStatus(undefined);
setSelectedRowKeys([]);
}}
>
{showArchived
? '隐藏已归档'
: `显示已归档${archivedCount > 0 ? ` (${archivedCount})` : ''}`}
{showArchived ? '返回正常数据' : '查看已归档'}
</Button>
</Space>
<Space wrap className="responsive-toolbar__group">
<Popconfirm
title={`确定批量归档选中的 ${selectedRowKeys.length} 名学生?(数据保留,可恢复)`}
onConfirm={handleBatchDelete}
okText="归档"
cancelText="取消"
disabled={selectedRowKeys.length === 0}
>
<PermissionButton
permission="student:delete"
danger
icon={<InboxOutlined />}
{showArchived && canEditStudent ? (
<Popconfirm
title={`确定批量恢复选中的 ${selectedRowKeys.length} 名学生?`}
onConfirm={handleBatchRestore}
okText="恢复"
cancelText="取消"
disabled={selectedRowKeys.length === 0}
loading={batchLoading}
>
<Button
type="primary"
icon={<UndoOutlined />}
disabled={selectedRowKeys.length === 0}
loading={batchLoading}
>
</Button>
</Popconfirm>
) : !showArchived && canDeleteStudent ? (
<Popconfirm
title={`确定批量归档选中的 ${selectedRowKeys.length} 名学生?(数据保留,可恢复)`}
onConfirm={handleBatchDelete}
okText="归档"
cancelText="取消"
disabled={selectedRowKeys.length === 0}
>
<Button
danger
icon={<InboxOutlined />}
disabled={selectedRowKeys.length === 0}
loading={batchLoading}
>
</Button>
</Popconfirm>
) : null}
{!showArchived ? (
<PermissionButton
permission="student:create"
type="primary"
icon={<PlusOutlined />}
onClick={() => {
setEditing(null);
form.resetFields();
const host = organizations.find((organization) => organization.isHost);
if (host) form.setFieldValue('organizationId', host.id);
setModalOpen(true);
}}
>
</PermissionButton>
</Popconfirm>
<PermissionButton
permission="student:create"
type="primary"
icon={<PlusOutlined />}
onClick={() => {
setEditing(null);
form.resetFields();
const host = organizations.find((organization) => organization.isHost);
if (host) form.setFieldValue('organizationId', host.id);
setModalOpen(true);
}}
>
</PermissionButton>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={handleCreateStudentsImport}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={handleUpdateExistingStudentsImport}
>
<Button icon={<SwapOutlined />}></Button>
</Upload>
) : null}
{!showArchived && hasPermission('student:import') ? (
<>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={handleCreateStudentsImport}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={handleUpdateExistingStudentsImport}
>
<Button icon={<SwapOutlined />}></Button>
</Upload>
</>
) : null}
{!showArchived && canSyncJinshuju ? (
<Button icon={<CloudUploadOutlined />} onClick={() => setJinshujuOpen(true)}>
</Button>
) : null}
<PermissionButton
permission="student:view"
icon={<DownloadOutlined />}
@@ -721,7 +948,6 @@ const StudentsPage: React.FC = () => {
rowSelection={{
selectedRowKeys,
onChange: (keys) => setSelectedRowKeys(keys as number[]),
getCheckboxProps: (record: any) => ({ disabled: record.status === 'archived' }),
}}
expandable={{
rowExpandable: () => true,
@@ -783,8 +1009,10 @@ const StudentsPage: React.FC = () => {
<style>{`.archived-row { opacity: 0.6; background: #fafafa !important; }`}</style>
<Modal
title={editing ? '编辑学生' : '添加学生'}
open={modalOpen}
onOk={handleSave}
className="student-form-modal"
width={720}
open={modalOpen && canSaveStudent}
onOk={canSaveStudent ? handleSave : undefined}
onCancel={() => {
setModalOpen(false);
setEditing(null);
@@ -792,7 +1020,7 @@ const StudentsPage: React.FC = () => {
okText="保存"
confirmLoading={saving}
>
<Form form={form} layout="vertical">
<Form form={form} layout="vertical" className="student-form-grid">
<Form.Item name="name" label="姓名" rules={[{ required: true }]}>
<Input />
</Form.Item>
@@ -823,23 +1051,27 @@ const StudentsPage: React.FC = () => {
<Form.Item name="emergencyPhone" label="紧急联系人电话">
<Input />
</Form.Item>
<Form.Item
name="organizationId"
label="所属机构"
rules={[{ required: true, message: '请选择所属机构' }]}
>
<Select
showSearch
optionFilterProp="label"
placeholder="选择所属机构"
options={organizations.map(
(organization: { id: number; name: string; isHost?: boolean }) => ({
value: organization.id,
label: organization.isHost ? `${organization.name}(本机构)` : organization.name,
}),
)}
/>
</Form.Item>
{canChooseOrganization ? (
<Form.Item
name="organizationId"
label="所属机构"
rules={[{ required: true, message: '请选择所属机构' }]}
>
<Select
showSearch
optionFilterProp="label"
placeholder="选择所属机构"
options={organizations.map(
(organization: { id: number; name: string; isHost?: boolean }) => ({
value: organization.id,
label: organization.isHost
? `${organization.name}(本机构)`
: organization.name,
}),
)}
/>
</Form.Item>
) : null}
<Form.Item name="supervisor" label="负责人/班主任">
<Input />
</Form.Item>
@@ -857,6 +1089,16 @@ const StudentsPage: React.FC = () => {
</Form>
</Modal>
{canSyncJinshuju ? (
<JinshujuMatchModal
open={jinshujuOpen}
onClose={() => setJinshujuOpen(false)}
onApplied={() => {
setJinshujuOpen(false);
fetchData();
}}
/>
) : null}
<Drawer
title={null}
open={drawerOpen}

View File

@@ -1,15 +1,17 @@
import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Table, Input, Button, Modal, Form, Select, DatePicker, Tag, Space } from 'antd';
import { Table, Input, Modal, Form, Select, DatePicker, Tag, Space } from 'antd';
import { EditOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import api from '../../api';
import { message } from '../../ui/app-message';
import EditableCell from '../../components/EditableCell';
import PermissionButton from '../../components/PermissionButton';
import { usePermission } from '../../hooks/usePermission';
interface TeacherRow {
id: number;
username: string;
name: string;
isActive: boolean;
profile: { subjects?: string[]; joinedAt?: string; qualifications?: string } | null;
lastLoginAt: string;
roles: { code: string; name: string }[];
@@ -49,6 +51,8 @@ const ROLE_TYPE_LABELS: Record<string, string> = {
const DEFAULT_PAGE_SIZE = 20;
const TeachersPage: React.FC = () => {
const { hasPermission } = usePermission();
const canEditTeachers = hasPermission('teacher:edit');
const [data, setData] = useState<TeacherRow[]>([]);
const [loading, setLoading] = useState(false);
const [total, setTotal] = useState(0);
@@ -101,6 +105,15 @@ const TeachersPage: React.FC = () => {
}
};
const saveProfileCell = useCallback(
async (record: TeacherRow, field: string, value: unknown) => {
await api.put(`/rbac/teachers/${record.id}/profile`, { [field]: value });
message.success('已保存');
await fetchData();
},
[fetchData],
);
const columns = useMemo(
() => [
{ title: '姓名', dataIndex: 'name', key: 'name', width: 120 },
@@ -133,21 +146,33 @@ const TeachersPage: React.FC = () => {
dataIndex: 'profile',
key: 'subjects',
width: 130,
render: (p: TeacherRow['profile']) => p?.subjects?.join('、') || '-',
render: (p: TeacherRow['profile'], r: TeacherRow) => (
<EditableCell
value={p?.subjects || []}
editor="tags"
options={(p?.subjects || []).map((value) => ({ value, label: value }))}
permission="teacher:edit"
onSave={(next) => saveProfileCell(r, 'subjects', next)}
>
{p?.subjects?.join('、') || '-'}
</EditableCell>
),
},
{
title: '入职日期',
dataIndex: 'profile',
key: 'joinedAt',
width: 110,
render: (p: TeacherRow['profile']) => p?.joinedAt || '-',
},
{
title: '状态',
dataIndex: 'isActive',
key: 'status',
width: 90,
render: (v: boolean) => <Tag color={v ? 'green' : 'red'}>{v ? '在职' : '停用'}</Tag>,
render: (p: TeacherRow['profile'], r: TeacherRow) => (
<EditableCell
value={p?.joinedAt}
editor="date"
permission="teacher:edit"
onSave={(next) => saveProfileCell(r, 'joinedAt', next)}
>
{p?.joinedAt || '-'}
</EditableCell>
),
},
{
title: '最后登录',
@@ -161,7 +186,8 @@ const TeachersPage: React.FC = () => {
key: 'actions',
width: 100,
render: (_: unknown, r: TeacherRow) => (
<Button
<PermissionButton
permission="teacher:edit"
size="small"
icon={<EditOutlined />}
onClick={() => {
@@ -174,11 +200,11 @@ const TeachersPage: React.FC = () => {
}}
>
</Button>
</PermissionButton>
),
},
],
[],
[saveProfileCell, form],
);
return (
@@ -234,8 +260,8 @@ const TeachersPage: React.FC = () => {
/>
<Modal
title={`编辑档案 — ${profileModal?.name || ''}`}
open={!!profileModal}
onOk={handleSaveProfile}
open={!!profileModal && canEditTeachers}
onOk={canEditTeachers ? handleSaveProfile : undefined}
onCancel={() => setProfileModal(null)}
okText="保存"
confirmLoading={saving}

View File

@@ -10,6 +10,7 @@ import {
import dayjs from 'dayjs';
import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell';
import { message } from '../../ui/app-message';
import { userProfileResponseToFormValues, type UserProfileResponse } from './user-profile-form';
@@ -86,7 +87,6 @@ const UsersPage: React.FC = () => {
form.setFieldsValue({
username: record.username,
name: record.name,
isActive: record.isActive,
roleIds: record.roles?.map((r: any) => r.id) || [],
});
setModalOpen(true);
@@ -100,7 +100,6 @@ const UsersPage: React.FC = () => {
await api.put(`/rbac/users/${editing.id}`, {
username: values.username,
name: values.name,
isActive: values.isActive,
roleIds: values.roleIds || [],
});
message.success('更新成功');
@@ -153,31 +152,74 @@ const UsersPage: React.FC = () => {
}
};
const saveCell = useCallback(
async (record: any, field: string, value: unknown) => {
await api.put(`/rbac/users/${record.id}`, { [field]: value });
message.success('已保存');
await fetchData();
},
[fetchData],
);
const columns = useMemo(
() => [
{ title: 'ID', dataIndex: 'id', width: 60 },
{ title: '用户名', dataIndex: 'username', width: 120 },
{ title: '名', dataIndex: 'name', width: 120 },
{
title: '用户名',
dataIndex: 'username',
width: 120,
render: (v: string, r: any) => (
<EditableCell
value={v}
required
permission="user:edit"
disabled={r.isArchived}
onSave={(next) => saveCell(r, 'username', next)}
>
{v}
</EditableCell>
),
},
{
title: '姓名',
dataIndex: 'name',
width: 120,
render: (v: string, r: any) => (
<EditableCell
value={v}
required
permission="user:edit"
disabled={r.isArchived}
onSave={(next) => saveCell(r, 'name', next)}
>
{v}
</EditableCell>
),
},
{
title: '角色',
dataIndex: 'roles',
width: 200,
render: (v: any[]) =>
v && v.length > 0 ? (
v.map((r: any) => (
<Tag key={r.id} color="blue">
{r.name}
</Tag>
))
) : (
<Tag color="default"></Tag>
),
},
{
title: '状态',
dataIndex: 'isActive',
width: 80,
render: (v: boolean) => <Tag color={v ? 'green' : 'default'}>{v ? '启用' : '禁用'}</Tag>,
render: (v: any[], record: any) => (
<EditableCell
value={v?.map((item) => item.id) || []}
editor="multi-select"
options={roles.map((item) => ({ value: item.id, label: item.name }))}
permission="user:edit"
disabled={record.isArchived}
onSave={(next) => saveCell(record, 'roleIds', next)}
>
{v && v.length > 0 ? (
v.map((r: any) => (
<Tag key={r.id} color="blue">
{r.name}
</Tag>
))
) : (
<Tag color="default"></Tag>
)}
</EditableCell>
),
},
{
title: '最后登录',
@@ -244,7 +286,7 @@ const UsersPage: React.FC = () => {
),
},
],
[],
[roles, saveCell],
);
return (
@@ -286,7 +328,7 @@ const UsersPage: React.FC = () => {
dataSource={data}
rowKey="id"
loading={loading}
scroll={{ x: 1250 }}
scroll={{ x: 1150 }}
pagination={false}
/>
@@ -318,11 +360,6 @@ const UsersPage: React.FC = () => {
<Form.Item name="name" label="姓名" rules={[{ required: true, message: '请输入姓名' }]}>
<Input />
</Form.Item>
{editing && (
<Form.Item name="isActive" label="状态" valuePropName="checked">
<Switch checkedChildren="启用" unCheckedChildren="禁用" />
</Form.Item>
)}
<Form.Item
name="roleIds"
label="角色分配"

View File

@@ -273,7 +273,12 @@ const WalletsPage: React.FC = () => {
dataSource={rows}
columns={columns}
rowSelection={{ selectedRowKeys, onChange: setSelectedRowKeys }}
pagination={{ pageSize: 15, showTotal: (total) => `${total}` }}
pagination={{
defaultPageSize: 15,
showSizeChanger: true,
pageSizeOptions: [15, 30, 50, 100],
showTotal: (total) => `${total}`,
}}
/>
<Modal
title={`${selected?.studentName || ''} - 余额操作`}

View File

@@ -0,0 +1,58 @@
import { describe, expect, it } from 'vitest';
import {
archiveViewPolicy,
expenseStatusForView,
occupancyParamsForView,
occupancyViewPolicy,
selectArchiveRecords,
shouldClearSelectionOnViewChange,
} from './archive-view';
describe('归档数据视图', () => {
it('正常视图与归档视图不会混合记录', () => {
const records = [
{ id: 1, status: 'active' },
{ id: 2, status: 'graduated' },
{ id: 3, status: 'archived' },
];
expect(selectArchiveRecords(records, 'active').map((item) => item.id)).toEqual([1, 2]);
expect(selectArchiveRecords(records, 'archived').map((item) => item.id)).toEqual([3]);
});
it('费用视图映射为后端 status 查询', () => {
expect(expenseStatusForView('active')).toBe('active');
expect(expenseStatusForView('archived')).toBe('archived');
});
it('入住三态分别映射为在住、全部活动记录和归档记录', () => {
expect(occupancyParamsForView('active')).toEqual({ active: 'true', status: 'active' });
expect(occupancyParamsForView('all')).toEqual({ active: undefined, status: 'active' });
expect(occupancyParamsForView('archived')).toEqual({
active: undefined,
status: 'archived',
});
});
it('正常与归档视图的批量动作互斥,且归档视图只读', () => {
expect(archiveViewPolicy('active')).toEqual({ batchAction: 'archive', readonly: false });
expect(archiveViewPolicy('archived')).toEqual({ batchAction: 'restore', readonly: true });
});
it('入住三态分别只提供退宿、归档和恢复动作', () => {
expect(occupancyViewPolicy('active')).toEqual({
batchAction: 'checkout',
readonly: false,
});
expect(occupancyViewPolicy('all')).toEqual({ batchAction: 'archive', readonly: false });
expect(occupancyViewPolicy('archived')).toEqual({
batchAction: 'restore',
readonly: true,
});
});
it('只有实际切换视图时才要求清空选择', () => {
expect(shouldClearSelectionOnViewChange('active', 'archived')).toBe(true);
expect(shouldClearSelectionOnViewChange('archived', 'archived')).toBe(false);
});
});

View File

@@ -0,0 +1,36 @@
export type ArchiveView = 'active' | 'archived';
export type OccupancyView = 'active' | 'all' | 'archived';
export type BatchAction = 'archive' | 'restore' | 'checkout';
export interface ViewPolicy {
batchAction: BatchAction;
readonly: boolean;
}
export const selectArchiveRecords = <T extends { status?: string }>(
records: T[],
view: ArchiveView,
) =>
records.filter((record) =>
view === 'archived' ? record.status === 'archived' : record.status !== 'archived',
);
export const expenseStatusForView = (view: ArchiveView) => view;
export const archiveViewPolicy = (view: ArchiveView): ViewPolicy => ({
batchAction: view === 'archived' ? 'restore' : 'archive',
readonly: view === 'archived',
});
export const occupancyViewPolicy = (view: OccupancyView): ViewPolicy => ({
batchAction: view === 'active' ? 'checkout' : view === 'all' ? 'archive' : 'restore',
readonly: view === 'archived',
});
export const shouldClearSelectionOnViewChange = <T extends string>(current: T, next: T) =>
current !== next;
export const occupancyParamsForView = (view: OccupancyView) => ({
active: view === 'active' ? 'true' : undefined,
status: view === 'archived' ? 'archived' : 'active',
});

View File

@@ -5,7 +5,7 @@ import tseslint from 'typescript-eslint';
export default tseslint.config(
{
ignores: ['eslint.config.mjs'],
ignores: ['eslint.config.mjs', 'dist/**'],
},
eslint.configs.recommended,
...tseslint.configs.recommendedTypeChecked,
@@ -27,6 +27,29 @@ export default tseslint.config(
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
'@typescript-eslint/no-unsafe-assignment': 'warn',
'@typescript-eslint/no-unsafe-call': 'warn',
'@typescript-eslint/no-unsafe-enum-comparison': 'warn',
'@typescript-eslint/no-unsafe-member-access': 'warn',
'@typescript-eslint/no-unsafe-return': 'warn',
'@typescript-eslint/no-unused-vars': [
'warn',
{
argsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
varsIgnorePattern: '^_',
},
],
'@typescript-eslint/no-base-to-string': 'warn',
'@typescript-eslint/no-require-imports': 'warn',
'@typescript-eslint/no-unnecessary-type-assertion': 'warn',
'@typescript-eslint/restrict-template-expressions': 'warn',
'no-empty': ['warn', { allowEmptyCatch: true }],
'no-useless-escape': 'warn',
},
},
{
files: ['**/*.spec.ts', '**/*.test.ts', 'test/**/*.ts'],
extends: [tseslint.configs.disableTypeChecked],
},
);

View File

@@ -13,7 +13,9 @@
"start": "nest start",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"generate:student-import": "ts-node -r tsconfig-paths/register -P tsconfig.json scripts/generate-student-import-xlsx.ts",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\"",
"lint:fix": "npm run lint -- --fix",
"typecheck": "tsc -p tsconfig.build.json --noEmit",
"test": "jest",
"test:watch": "jest --watch",
@@ -35,7 +37,7 @@
"@nestjs/jwt": "^11.0.2",
"@nestjs/mapped-types": "^2.1.1",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.1.19",
"@nestjs/platform-express": "^11.1.28",
"@nestjs/schedule": "^6.1.3",
"@nestjs/throttler": "^6.5.0",
"@nestjs/typeorm": "^11.0.1",
@@ -45,15 +47,17 @@
"class-validator": "^0.15.1",
"echarts": "^6.1.0",
"exceljs": "^4.4.0",
"multer": "^2.1.1",
"mammoth": "^1.12.0",
"multer": "^2.2.0",
"mysql2": "^3.22.2",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"passport-local": "^1.0.0",
"pdf-parse": "^2.4.5",
"pdfkit": "^0.18.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"typeorm": "^0.3.28"
"typeorm": "^0.3.31"
},
"optionalDependencies": {
"better-sqlite3": "^12.9.0"

View File

@@ -0,0 +1,106 @@
/// <reference types="node" />
import * as ExcelJS from 'exceljs';
import {
STUDENT_IMPORT_COLUMNS,
createStudentImportTemplateWorkbook,
} from '../src/students/student-import';
const count = Number(process.argv[2] || 1000);
const output = process.argv[3] || `student-import-${count}.xlsx`;
function getWorksheetOrThrow(workbook: ExcelJS.Workbook, name: string) {
const sheet = workbook.getWorksheet(name);
if (!sheet) throw new Error(`Worksheet not found: ${name}`);
return sheet;
}
async function main() {
if (!Number.isInteger(count) || count <= 0) {
throw new Error('Count must be a positive integer');
}
const workbook = createStudentImportTemplateWorkbook();
const students = getWorksheetOrThrow(workbook, '学生基础+档案+录取');
const enrollments = getWorksheetOrThrow(workbook, '报读班型');
const examScores = getWorksheetOrThrow(workbook, '考试成绩');
const learningRecords = getWorksheetOrThrow(workbook, '课堂回访');
for (let i = 1; i <= count; i++) {
const serial = String(i).padStart(4, '0');
const phone = `138${String(i).padStart(8, '0')}`;
students.addRow({
phone,
name: `导入学生${serial}`,
studentNo: `GX${serial}`,
gender: i % 2 === 0 ? '女' : '男',
idNumber: `110101200601${String((i % 28) + 1).padStart(2, '0')}${String(i % 1000).padStart(3, '0')}X`,
ethnicity: '汉族',
emergencyContact: `联系人${serial}`,
emergencyPhone: `139${String(i).padStart(8, '0')}`,
organization: '',
supervisor: '',
targetCollege: `目标院校${(i % 20) + 1}`,
targetMajor: `目标专业${(i % 10) + 1}`,
collegeSchool: `大专院校${(i % 12) + 1}`,
collegeMajor: `大专专业${(i % 8) + 1}`,
subjectDirection: ['物化生', '物化地', '史政地'][i % 3],
grade: '高三',
profileDate: '2024-09-01',
notes: '',
cultureFinalScore: 500 + (i % 151),
professionalFinalScore: 300 + (i % 101),
admissionStatus: 'pending',
admittedCollege: '',
admittedMajor: '',
});
enrollments.addRow({
phone,
name: `导入学生${serial}`,
courseCategory: i % 2 === 0 ? 'culture' : 'professional',
classType: i % 3 === 0 ? 'small_group' : 'one_on_one',
className: `导入测试班${(i % 10) + 1}`,
headTeacher: '',
subjectTeacher: '',
startDate: '2024-09-01',
endDate: '2025-06-01',
status: 'active',
});
examScores.addRow({
phone,
name: `导入学生${serial}`,
examType: 'monthly',
examName: '导入测试月考',
subject: '语文',
score: 80 + (i % 41),
classAvg: 90,
rank: (i % 50) + 1,
examDate: '2024-10-15',
enrollmentName: `导入测试班${(i % 10) + 1}`,
});
learningRecords.addRow({
phone,
name: `导入学生${serial}`,
recordDate: '2024-10-20',
recordType: 'study_feedback',
content: `导入测试回访${serial}`,
followUpMethod: 'phone',
nextStep: '',
});
}
for (const sheet of workbook.worksheets) {
sheet.views = [{ state: 'frozen', ySplit: 1 }];
}
await workbook.xlsx.writeFile(output);
console.log(`Generated ${count} students with ${STUDENT_IMPORT_COLUMNS.length} main columns: ${output}`);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View File

@@ -0,0 +1,39 @@
import { Injectable } from '@nestjs/common';
import { CaslAbilityFactory } from '../authorization/casl-ability.factory';
import { CaslAction, SubjectName } from '../authorization/casl.constants';
import type { AgentToolContext } from './agent-tool.types';
@Injectable()
export class AgentBusinessScopeFactory {
constructor(private readonly abilityFactory: CaslAbilityFactory) {}
private ability(context: AgentToolContext) {
return this.abilityFactory.createForUser({
permissions: context.permissions,
isSuperAdmin: context.isSuperAdmin,
});
}
canManageAllClasses(context: AgentToolContext): boolean {
const ability = this.ability(context);
return context.isSuperAdmin || ability.can(CaslAction.Update, SubjectName.Class);
}
canManageAllAttendance(context: AgentToolContext): boolean {
const ability = this.ability(context);
return (
context.isSuperAdmin ||
ability.can(CaslAction.Manage, SubjectName.Attendance) ||
ability.can(CaslAction.Update, SubjectName.Class)
);
}
canManageAllDashboard(context: AgentToolContext): boolean {
const ability = this.ability(context);
return (
context.isSuperAdmin ||
ability.can(CaslAction.Manage, SubjectName.Dashboard) ||
ability.can(CaslAction.Update, SubjectName.Class)
);
}
}

View File

@@ -0,0 +1,36 @@
import type { AgentSkillDescriptor } from './agent-tool.types';
export const AGENT_SKILLS: readonly Omit<AgentSkillDescriptor, 'tools'>[] = [
{
key: 'overview',
name: '经营总览',
description: '查看当前权限范围内的学生、班级和今日考勤概览。',
examples: ['今天整体运营情况怎么样?', '帮我汇总当前学生和班级数量'],
},
{
key: 'student',
name: '学生与班级',
description: '查询学生基础信息、班级和在读人数。',
examples: ['查找姓名包含张的学生', '有哪些在读班级?'],
},
{
key: 'attendance',
name: '考勤分析',
description: '按日期和班级汇总有权限查看的考勤数据。',
examples: ['汇总今天的考勤情况', '这个月哪个班缺勤最多?'],
},
{
key: 'dormitory',
name: '宿舍管理',
description: '查询宿舍、入住数量和空余床位。',
examples: ['哪些房间还有空床?', '汇总当前宿舍入住情况'],
},
{
key: 'billing',
name: '账单查询',
description: '查询账单编号、账期、金额和状态。',
examples: ['查找本月未支付账单', '查询张同学最近的账单'],
},
];
export const AGENT_SKILL_KEYS = new Set(AGENT_SKILLS.map((skill) => skill.key));

View File

@@ -37,6 +37,7 @@ const noPermCtx = makeCtx({ id: 3, username: 'guest', permissions: [] });
function makeTool(overrides: Partial<ToolDef> = {}): ToolDef {
return {
name: 'echo',
skillKey: 'student',
description: 'echoes input',
requiredPermission: 'student:view',
inputSchema: { type: 'object', properties: { text: { type: 'string' } }, additionalProperties: false },

View File

@@ -2,9 +2,16 @@ import { Injectable, NotFoundException } from '@nestjs/common';
import { CaslAbilityFactory } from '../authorization/casl-ability.factory';
import { AuthorizationService } from '../authorization';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
import { AGENT_SKILLS } from './agent-skill.catalog';
import { AgentToolRegistry } from './agent-tool.registry';
import { AgentToolContextFactory } from './agent-tool.types';
import type { AgentToolContext, ToolExecutionResult, ToolStatus, ToolDescriptor } from './agent-tool.types';
import type {
AgentSkillDescriptor,
AgentToolContext,
ToolDescriptor,
ToolExecutionResult,
ToolStatus,
} from './agent-tool.types';
/** Safe tool name: alphanumeric + underscore, max 64 chars. */
const TOOL_NAME_RE = /^[a-zA-Z0-9_]+$/;
@@ -60,7 +67,7 @@ export class AgentToolExecutor {
* @param context — trusted context from
* {@link AgentToolContextFactory.fromAuthenticatedUser}.
*/
listAvailable(context: AgentToolContext): ToolDescriptor[] {
listAvailable(context: AgentToolContext, skillKey?: string | null): ToolDescriptor[] {
AgentToolContextFactory.assertTrusted(context);
const ability = this.abilityFactory.createForUser({
@@ -70,13 +77,25 @@ export class AgentToolExecutor {
return this.registry
.listAvailableInternal(ability)
.map(({ name, description, inputSchema }) => ({
.filter((tool) => !skillKey || tool.skillKey === skillKey)
.map(({ name, skillKey: toolSkillKey, description, inputSchema }) => ({
name,
skillKey: toolSkillKey,
description,
...(inputSchema ? { inputSchema } : {}),
}));
}
listSkills(context: AgentToolContext): AgentSkillDescriptor[] {
const tools = this.listAvailable(context);
return AGENT_SKILLS.map((skill) => ({
...skill,
tools: tools
.filter((tool) => tool.skillKey === skill.key)
.map(({ name, description }) => ({ name, description })),
})).filter((skill) => skill.tools.length > 0);
}
/**
* Execute a tool by name.
*
@@ -89,6 +108,7 @@ export class AgentToolExecutor {
name: string,
rawInput: unknown,
context: AgentToolContext,
allowedSkillKey?: string | null,
): Promise<ToolExecutionResult> {
// 0. Context trust validation — must be first
try {
@@ -111,6 +131,17 @@ export class AgentToolExecutor {
);
}
if (allowedSkillKey && tool.skillKey !== allowedSkillKey) {
return this.auditAndReturn(
safeName,
'denied',
undefined,
SAFE_MESSAGES.permissionDenied,
context,
tool.skillKey,
);
}
// 2. Build ability from principal fields — never trust a pre-built one
const ability = this.abilityFactory.createForUser({
permissions: context.permissions,
@@ -125,6 +156,7 @@ export class AgentToolExecutor {
undefined,
SAFE_MESSAGES.permissionDenied,
context,
tool.skillKey,
);
}
@@ -136,6 +168,7 @@ export class AgentToolExecutor {
undefined,
SAFE_MESSAGES.invalidInput,
context,
tool.skillKey,
);
}
@@ -150,6 +183,7 @@ export class AgentToolExecutor {
undefined,
SAFE_MESSAGES.invalidInput,
context,
tool.skillKey,
);
}
if (!parsed.ok) {
@@ -159,13 +193,21 @@ export class AgentToolExecutor {
undefined,
SAFE_MESSAGES.invalidInput,
context,
tool.skillKey,
);
}
// 6. Execute
try {
const result = await tool.execute(parsed.value, context);
return this.auditAndReturn(safeName, 'success', result, undefined, context);
return this.auditAndReturn(
safeName,
'success',
result,
undefined,
context,
tool.skillKey,
);
} catch (err: unknown) {
// NotFoundException → not_found with safe message
if (err instanceof NotFoundException) {
@@ -175,6 +217,7 @@ export class AgentToolExecutor {
undefined,
SAFE_MESSAGES.notFound,
context,
tool.skillKey,
);
}
// All other errors → generic failed message
@@ -184,6 +227,7 @@ export class AgentToolExecutor {
undefined,
SAFE_MESSAGES.executionFailed,
context,
tool.skillKey,
);
}
}
@@ -213,6 +257,7 @@ export class AgentToolExecutor {
result: unknown,
error: string | undefined,
context: AgentToolContext,
skillKey?: string,
): Promise<ToolExecutionResult> {
// Await audit (best-effort — failure is silently swallowed)
try {
@@ -228,7 +273,7 @@ export class AgentToolExecutor {
// Swallow — audit failure must not break the tool call
}
return { status, toolName, result, error };
return { status, toolName, skillKey, result, error };
}
/**

View File

@@ -104,6 +104,8 @@ export class AgentToolContextFactory {
export interface ToolDescriptor {
/** Unique tool name exposed to the LLM (e.g. "search_students"). */
readonly name: string;
/** Product-facing skill grouping key. */
readonly skillKey: string;
/** Human-readable description for the model. */
readonly description: string;
/**
@@ -113,6 +115,14 @@ export interface ToolDescriptor {
readonly inputSchema?: Record<string, unknown>;
}
export interface AgentSkillDescriptor {
readonly key: string;
readonly name: string;
readonly description: string;
readonly examples: readonly string[];
readonly tools: readonly Pick<ToolDescriptor, 'name' | 'description'>[];
}
// ---------------------------------------------------------------------------
// ToolDef — internal tool definition (NOT for SDK consumers)
// ---------------------------------------------------------------------------
@@ -137,6 +147,8 @@ export type ToolInputResult<T> =
export interface ToolDef<TInput = unknown> {
/** Unique tool name exposed to the LLM (e.g. "search_students"). */
readonly name: string;
/** Product-facing skill grouping key. */
readonly skillKey: string;
/** Human-readable description for the model. */
readonly description: string;
/**
@@ -172,6 +184,7 @@ export type ToolStatus = 'success' | 'denied' | 'failed' | 'not_found';
export interface ToolExecutionResult {
readonly status: ToolStatus;
readonly toolName: string;
readonly skillKey?: string;
/** Set on success; `undefined` on denied / failed / not_found. */
readonly result?: unknown;
/** Set on denied / failed / not_found; `undefined` on success.

View File

@@ -1,9 +1,21 @@
import { Module, OnModuleInit } from '@nestjs/common';
import { StudentsModule } from '../students/students.module';
import { ClassesModule } from '../classes/classes.module';
import { AttendanceModule } from '../attendance/attendance.module';
import { RoomsModule } from '../rooms/rooms.module';
import { BillsModule } from '../bills/bills.module';
import { DashboardModule } from '../dashboard/dashboard.module';
import { AgentToolRegistry } from './agent-tool.registry';
import { AgentToolExecutor } from './agent-tool.executor';
import { SearchStudentsTool } from './tools/search-students.tool';
import { GetStudentBasicTool } from './tools/get-student-basic.tool';
import { AgentBusinessScopeFactory } from './agent-business-scope.factory';
import { SearchClassesTool } from './tools/search-classes.tool';
import { GetAttendanceSummaryTool } from './tools/get-attendance-summary.tool';
import { SearchRoomsTool } from './tools/search-rooms.tool';
import { GetRoomOccupancySummaryTool } from './tools/get-room-occupancy-summary.tool';
import { SearchBillsTool } from './tools/search-bills.tool';
import { GetDashboardStatsTool } from './tools/get-dashboard-stats.tool';
/**
* Agent Tools feature module.
@@ -20,12 +32,19 @@ import { GetStudentBasicTool } from './tools/get-student-basic.tool';
* globally available `AuthorizationModule` and `OperationLogsModule`.
*/
@Module({
imports: [StudentsModule],
imports: [StudentsModule, ClassesModule, AttendanceModule, RoomsModule, BillsModule, DashboardModule],
providers: [
AgentToolRegistry,
AgentToolExecutor,
SearchStudentsTool,
GetStudentBasicTool,
AgentBusinessScopeFactory,
SearchClassesTool,
GetAttendanceSummaryTool,
SearchRoomsTool,
GetRoomOccupancySummaryTool,
SearchBillsTool,
GetDashboardStatsTool,
],
exports: [AgentToolExecutor],
})
@@ -34,10 +53,22 @@ export class AgentToolsModule implements OnModuleInit {
private readonly registry: AgentToolRegistry,
private readonly searchTool: SearchStudentsTool,
private readonly getTool: GetStudentBasicTool,
private readonly searchClassesTool: SearchClassesTool,
private readonly attendanceSummaryTool: GetAttendanceSummaryTool,
private readonly searchRoomsTool: SearchRoomsTool,
private readonly roomOccupancyTool: GetRoomOccupancySummaryTool,
private readonly searchBillsTool: SearchBillsTool,
private readonly dashboardStatsTool: GetDashboardStatsTool,
) {}
onModuleInit(): void {
this.registry.register(this.searchTool);
this.registry.register(this.getTool);
this.registry.register(this.searchClassesTool);
this.registry.register(this.attendanceSummaryTool);
this.registry.register(this.searchRoomsTool);
this.registry.register(this.roomOccupancyTool);
this.registry.register(this.searchBillsTool);
this.registry.register(this.dashboardStatsTool);
}
}

View File

@@ -1,4 +1,9 @@
export { AgentToolsModule } from './agent-tools.module';
export { AgentToolExecutor } from './agent-tool.executor';
export { AgentToolContextFactory, AgentToolContext } from './agent-tool.types';
export type { ToolDescriptor, ToolExecutionResult, ToolStatus } from './agent-tool.types';
export type {
AgentSkillDescriptor,
ToolDescriptor,
ToolExecutionResult,
ToolStatus,
} from './agent-tool.types';

View File

@@ -0,0 +1,79 @@
import { CaslAbilityFactory } from '../../authorization/casl-ability.factory';
import type { AuthenticatedUser } from '../../authorization';
import { AgentBusinessScopeFactory } from '../agent-business-scope.factory';
import { AgentToolContextFactory } from '../agent-tool.types';
import { SearchClassesTool } from './search-classes.tool';
import { GetAttendanceSummaryTool } from './get-attendance-summary.tool';
import { SearchRoomsTool } from './search-rooms.tool';
import { GetRoomOccupancySummaryTool } from './get-room-occupancy-summary.tool';
import { SearchBillsTool } from './search-bills.tool';
import { GetDashboardStatsTool } from './get-dashboard-stats.tool';
function context(permissions: string[] = [], isSuperAdmin = false) {
const user: AuthenticatedUser = { id: 7, username: 'teacher', permissions, isSuperAdmin, roles: [] };
return AgentToolContextFactory.fromAuthenticatedUser(user);
}
const scopes = new AgentBusinessScopeFactory(new CaslAbilityFactory());
describe('agent business tools', () => {
it('search_classes rejects unknown fields and enforces teacher scope', async () => {
const service = { agentSearchClasses: jest.fn().mockResolvedValue([]) };
const tool = new SearchClassesTool(service as never, scopes);
expect(tool.validate({ userId: 1 }).ok).toBe(false);
expect(tool.validate({ limit: 51 }).ok).toBe(false);
await tool.execute({ keyword: '一班' }, context(['class:view']));
expect(service.agentSearchClasses).toHaveBeenCalledWith(7, false, { keyword: '一班' });
});
it('class:edit grants full class and attendance scope', async () => {
const classService = { agentSearchClasses: jest.fn().mockResolvedValue([]) };
const attendanceService = { agentGetAttendanceSummary: jest.fn().mockResolvedValue([]) };
const ctx = context(['class:view', 'class:edit', 'attendance:view']);
await new SearchClassesTool(classService as never, scopes).execute({}, ctx);
await new GetAttendanceSummaryTool(attendanceService as never, scopes).execute({}, ctx);
expect(classService.agentSearchClasses).toHaveBeenCalledWith(7, true, {});
expect(attendanceService.agentGetAttendanceSummary).toHaveBeenCalledWith(7, true, {});
});
it('attendance validates date range and limit', () => {
const tool = new GetAttendanceSummaryTool({} as never, scopes);
expect(tool.validate({ dateFrom: '2026-07-23', dateTo: '2026-07-22' }).ok).toBe(false);
expect(tool.validate({ dateFrom: '2026-02-30' }).ok).toBe(false);
expect(tool.validate({ limit: 50 }).ok).toBe(true);
});
it('room tools reject sensitive/unknown fields and forward safe input', async () => {
const service = {
agentSearchRooms: jest.fn().mockResolvedValue([]),
agentGetRoomOccupancySummary: jest.fn().mockResolvedValue([]),
};
const search = new SearchRoomsTool(service as never);
const summary = new GetRoomOccupancySummaryTool(service as never);
expect(search.validate({ studentName: '张三' }).ok).toBe(false);
expect(summary.validate({ permissions: ['room:view'] }).ok).toBe(false);
await search.execute({ building: '1号楼', limit: 10 }, context(['room:view']));
await summary.execute({ date: '2026-07-23' }, context(['room:view']));
expect(service.agentSearchRooms).toHaveBeenCalledWith({ building: '1号楼', limit: 10 });
expect(service.agentGetRoomOccupancySummary).toHaveBeenCalledWith({ date: '2026-07-23' });
});
it('bill tool exposes read permission and validates ranges', async () => {
const service = { agentSearchBills: jest.fn().mockResolvedValue([]) };
const tool = new SearchBillsTool(service as never);
expect(tool.requiredPermission).toBe('bill:view');
expect(tool.validate({ periodStart: '2026-07-31', periodEnd: '2026-07-01' }).ok).toBe(false);
await tool.execute({ status: 'unpaid', limit: 20 }, context(['bill:view']));
expect(service.agentSearchBills).toHaveBeenCalledWith({ status: 'unpaid', limit: 20 });
});
it('dashboard uses teacher scope unless super admin', async () => {
const service = { agentGetDashboardStats: jest.fn().mockResolvedValue({}) };
const tool = new GetDashboardStatsTool(service as never, scopes);
expect(tool.validate({ debug: true }).ok).toBe(false);
await tool.execute({}, context(['dashboard:view']));
await tool.execute({}, context([], true));
expect(service.agentGetDashboardStats).toHaveBeenNthCalledWith(1, 7, false);
expect(service.agentGetDashboardStats).toHaveBeenNthCalledWith(2, 7, true);
});
});

View File

@@ -0,0 +1,31 @@
import { Injectable } from '@nestjs/common';
import { AttendanceService } from '../../attendance/attendance.service';
import { AgentBusinessScopeFactory } from '../agent-business-scope.factory';
import type { AgentToolContext, ToolDef, ToolInputResult } from '../agent-tool.types';
import { optionalDate, optionalPositiveInt, rejectUnknownKeys } from './tool-input';
interface Input { classId?: number; dateFrom?: string; dateTo?: string; limit?: number }
@Injectable()
export class GetAttendanceSummaryTool implements ToolDef<Input> {
readonly name = 'get_attendance_summary';
readonly skillKey = 'attendance';
readonly description = '按日期和班级汇总当前用户有权查看的考勤数据。';
readonly requiredPermission = 'attendance:view';
readonly inputSchema = { type: 'object', properties: {
classId: { type: 'integer', minimum: 1 }, dateFrom: { type: 'string', format: 'date' },
dateTo: { type: 'string', format: 'date' }, limit: { type: 'integer', minimum: 1, maximum: 50 },
}, additionalProperties: false };
constructor(private readonly service: AttendanceService, private readonly scopes: AgentBusinessScopeFactory) {}
validate(raw: Record<string, unknown>): ToolInputResult<Input> {
const invalid = rejectUnknownKeys(raw, ['classId', 'dateFrom', 'dateTo', 'limit']); if (invalid) return invalid;
const classId = optionalPositiveInt(raw.classId, 'classId'); if (!classId.ok) return classId;
const dateFrom = optionalDate(raw.dateFrom, 'dateFrom'); if (!dateFrom.ok) return dateFrom;
const dateTo = optionalDate(raw.dateTo, 'dateTo'); if (!dateTo.ok) return dateTo;
if (dateFrom.value && dateTo.value && dateFrom.value > dateTo.value) return { ok: false, error: 'dateTo 不能早于 dateFrom' };
const limit = optionalPositiveInt(raw.limit, 'limit', 50); if (!limit.ok) return limit;
return { ok: true, value: { classId: classId.value, dateFrom: dateFrom.value, dateTo: dateTo.value, limit: limit.value } };
}
execute(input: Input, context: AgentToolContext) {
return this.service.agentGetAttendanceSummary(context.userId, this.scopes.canManageAllAttendance(context), input);
}
}

View File

@@ -0,0 +1,19 @@
import { Injectable } from '@nestjs/common';
import { DashboardService } from '../../dashboard/dashboard.service';
import { AgentBusinessScopeFactory } from '../agent-business-scope.factory';
import type { AgentToolContext, ToolDef, ToolInputResult } from '../agent-tool.types';
import { rejectUnknownKeys } from './tool-input';
@Injectable()
export class GetDashboardStatsTool implements ToolDef<Record<string, never>> {
readonly name = 'get_dashboard_stats'; readonly skillKey = 'overview'; readonly requiredPermission = 'dashboard:view';
readonly description = '获取当前用户数据范围内的学生、班级和今日考勤概览。';
readonly inputSchema = { type: 'object', properties: {}, additionalProperties: false };
constructor(private readonly service: DashboardService, private readonly scopes: AgentBusinessScopeFactory) {}
validate(raw: Record<string, unknown>): ToolInputResult<Record<string, never>> {
const invalid = rejectUnknownKeys(raw, []); return invalid ?? { ok: true, value: {} };
}
execute(_input: Record<string, never>, context: AgentToolContext) {
return this.service.agentGetDashboardStats(context.userId, this.scopes.canManageAllDashboard(context));
}
}

View File

@@ -0,0 +1,21 @@
import { Injectable } from '@nestjs/common';
import { RoomsService } from '../../rooms/rooms.service';
import type { AgentToolContext, ToolDef, ToolInputResult } from '../agent-tool.types';
import { optionalDate, optionalPositiveInt, optionalString, rejectUnknownKeys } from './tool-input';
interface Input { date?: string; building?: string; limit?: number }
@Injectable()
export class GetRoomOccupancySummaryTool implements ToolDef<Input> {
readonly name = 'get_room_occupancy_summary'; readonly skillKey = 'dormitory'; readonly requiredPermission = 'room:view';
readonly description = '按日期汇总宿舍入住数量和空余床位,不返回住户资料。';
readonly inputSchema = { type: 'object', properties: { date: { type: 'string', format: 'date' }, building: { type: 'string', maxLength: 50 }, limit: { type: 'integer', minimum: 1, maximum: 100 } }, additionalProperties: false };
constructor(private readonly service: RoomsService) {}
validate(raw: Record<string, unknown>): ToolInputResult<Input> {
const invalid = rejectUnknownKeys(raw, ['date', 'building', 'limit']); if (invalid) return invalid;
const date = optionalDate(raw.date, 'date'); if (!date.ok) return date;
const building = optionalString(raw.building, 'building', 50); if (!building.ok) return building;
const limit = optionalPositiveInt(raw.limit, 'limit', 100); if (!limit.ok) return limit;
return { ok: true, value: { date: date.value, building: building.value, limit: limit.value } };
}
execute(input: Input, _context: AgentToolContext) { return this.service.agentGetRoomOccupancySummary(input); }
}

View File

@@ -34,6 +34,7 @@ export class GetStudentBasicTool implements ToolDef<GetStudentBasicInput> {
additionalProperties: false,
};
readonly name = 'get_student_basic';
readonly skillKey = 'student';
readonly description = '获取单个学生基本信息。仅返回基础公开字段。';
readonly requiredPermission = 'student:view';

View File

@@ -0,0 +1,24 @@
import { Injectable } from '@nestjs/common';
import { BillsService } from '../../bills/bills.service';
import type { AgentToolContext, ToolDef, ToolInputResult } from '../agent-tool.types';
import { optionalDate, optionalPositiveInt, optionalString, rejectUnknownKeys } from './tool-input';
interface Input { keyword?: string; periodStart?: string; periodEnd?: string; status?: string; limit?: number }
@Injectable()
export class SearchBillsTool implements ToolDef<Input> {
readonly name = 'search_bills'; readonly skillKey = 'billing'; readonly requiredPermission = 'bill:view';
readonly description = '查询账单编号、学生显示名、账期、金额和状态。';
readonly inputSchema = { type: 'object', properties: { keyword: { type: 'string', maxLength: 100 }, periodStart: { type: 'string', format: 'date' }, periodEnd: { type: 'string', format: 'date' }, status: { type: 'string', maxLength: 20 }, limit: { type: 'integer', minimum: 1, maximum: 50 } }, additionalProperties: false };
constructor(private readonly service: BillsService) {}
validate(raw: Record<string, unknown>): ToolInputResult<Input> {
const invalid = rejectUnknownKeys(raw, ['keyword', 'periodStart', 'periodEnd', 'status', 'limit']); if (invalid) return invalid;
const keyword = optionalString(raw.keyword, 'keyword', 100); if (!keyword.ok) return keyword;
const periodStart = optionalDate(raw.periodStart, 'periodStart'); if (!periodStart.ok) return periodStart;
const periodEnd = optionalDate(raw.periodEnd, 'periodEnd'); if (!periodEnd.ok) return periodEnd;
if (periodStart.value && periodEnd.value && periodStart.value > periodEnd.value) return { ok: false, error: 'periodEnd 不能早于 periodStart' };
const status = optionalString(raw.status, 'status', 20); if (!status.ok) return status;
const limit = optionalPositiveInt(raw.limit, 'limit', 50); if (!limit.ok) return limit;
return { ok: true, value: { keyword: keyword.value, periodStart: periodStart.value, periodEnd: periodEnd.value, status: status.value, limit: limit.value } };
}
execute(input: Input, _context: AgentToolContext) { return this.service.agentSearchBills(input); }
}

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