Compare commits
120 Commits
cd1996f281
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| db0d972633 | |||
| 8d4ebcf9c0 | |||
| 5f9566e26d | |||
| 5b5ffb5b9e | |||
| 899d2dde5b | |||
| 54b002455f | |||
| b032890b4f | |||
| f560b046a4 | |||
| 549a3ff14b | |||
| 7fdfdbc717 | |||
| edb798b752 | |||
| a436d9aa38 | |||
| bbeea440f9 | |||
| 9048816abc | |||
| 14db28afc6 | |||
| c72ff2cb8a | |||
| 24e0ecbdaf | |||
| d9c541dacc | |||
| ae88372ef8 | |||
| 259271f56c | |||
| 824c33a71c | |||
| 7f09d5271e | |||
| 7f3e30ba38 | |||
| d0ab8da01b | |||
| 6a18fd264d | |||
| 026a9f35d8 | |||
| 2e7bb81ebd | |||
| 67e14e357c | |||
| 6249fefc64 | |||
| d1c933f032 | |||
| 1a1e90c72f | |||
| ab4765cee5 | |||
| b70f45fb04 | |||
| b882411f42 | |||
| 6ba7f4e3d0 | |||
| c8316e9e8e | |||
| 32343b271b | |||
| 2a519a3714 | |||
| 1e1e24f0f0 | |||
| 47720a8fcc | |||
| 81e622fa09 | |||
| fd39e1686a | |||
| 80e6fccf05 | |||
| 0c94ca54df | |||
| e9c8a1085d | |||
| c622e40a12 | |||
| 0e6e3e2d96 | |||
| 644c35ce53 | |||
| 68270e7571 | |||
| d53bbd8176 | |||
| e21f0de427 | |||
| a9ce5563b1 | |||
| 5f89335dbb | |||
| bd55e0a061 | |||
| 3a1ed717d8 | |||
| 216a20ffaf | |||
| 50c44e4410 | |||
| f07ffdc64c | |||
| ce1dcc07ea | |||
| 75c42f52a1 | |||
| c38c508547 | |||
| d2411a0a9f | |||
| 095eccea76 | |||
| 0ef86e65ce | |||
| 5e67d81bf5 | |||
| 1da763109b | |||
| 4d77848bf7 | |||
| 1d656a80e7 | |||
| c1bb05502e | |||
| 3bd72596c9 | |||
| 4fc77aec07 | |||
| 6dcb2bc28a | |||
| d5a1d23037 | |||
| 1f198d48ea | |||
| 5cf68e3f8a | |||
| 8656394b9b | |||
| 3573351f59 | |||
| 4046e29e33 | |||
| 525bbd1a56 | |||
| f53934c67d | |||
| e605586fc9 | |||
| 150e6ecff0 | |||
| 065dfd9a38 | |||
| a272403f27 | |||
| 13ef357448 | |||
| a9c6578569 | |||
| 106c30683f | |||
| 3a2b3f1239 | |||
| b8d5927a16 | |||
| fb787c3e0d | |||
| 176f098923 | |||
| c401766bc5 | |||
| 2a20b1fc97 | |||
| 6f29220257 | |||
| 446c6bcc91 | |||
| a7a7af1667 | |||
| 9f54fec972 | |||
| f3b59935d6 | |||
| c98d37307e | |||
| adf738288f | |||
| 585e955720 | |||
| eaca56617c | |||
| 0bdc8a067b | |||
| 490a337446 | |||
| 302dbe0621 | |||
| 5bd63846d1 | |||
| 301064dbf6 | |||
| fa7ed8e128 | |||
| 099cff7f00 | |||
| a267238e7c | |||
| d93f6cb0b9 | |||
| 0ce8f58adb | |||
| 43ca5a6e36 | |||
| 90cc321221 | |||
| d33c37b4b0 | |||
| bf867eedaa | |||
| 6286864df0 | |||
| 5b10e80d3a | |||
| a9009f86fb | |||
| 7ffc573d2e |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -20,6 +20,7 @@ build/
|
|||||||
# 上传文件(合同PDF等敏感文件,不入版本库和部署包)
|
# 上传文件(合同PDF等敏感文件,不入版本库和部署包)
|
||||||
uploads/
|
uploads/
|
||||||
backend/uploads/
|
backend/uploads/
|
||||||
|
data/ai-attachments/
|
||||||
|
|
||||||
# 日志
|
# 日志
|
||||||
logs/
|
logs/
|
||||||
@@ -54,3 +55,7 @@ apps/admin/dist/
|
|||||||
.claude/
|
.claude/
|
||||||
.omp/
|
.omp/
|
||||||
.superpowers/
|
.superpowers/
|
||||||
|
|
||||||
|
# 测试截图产物
|
||||||
|
.vitest-attachments/
|
||||||
|
**/__screenshots__/
|
||||||
|
|||||||
@@ -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.
|
If there is no `.codegraph/` directory, skip CodeGraph entirely — indexing is the user's decision.
|
||||||
<!-- CODEGRAPH_END -->
|
<!-- CODEGRAPH_END -->
|
||||||
|
|
||||||
|
## Ant Design X
|
||||||
|
|
||||||
|
修改 AI 助手、SSE 消息、运行时技能、附件或 Agent 工具前,先读取 `docs/skills/ant-design-x/SKILL.md`,优先使用项目已安装的 Ant Design X 组件与 SDK。
|
||||||
|
|||||||
11
README.md
11
README.md
@@ -24,10 +24,10 @@
|
|||||||
```
|
```
|
||||||
前端 (React + Vite) 后端 (NestJS) 数据库
|
前端 (React + Vite) 后端 (NestJS) 数据库
|
||||||
┌─────────────────┐ ┌──────────────────┐ ┌──────────┐
|
┌─────────────────┐ ┌──────────────────┐ ┌──────────┐
|
||||||
│ React 19 │ │ NestJS 11 │ │ SQLite │
|
│ React 19 │ │ NestJS 11 │ │ MySQL 8 │
|
||||||
│ Ant Design 6 │────▶│ TypeORM 0.3 │────▶│ (开发) │
|
│ Ant Design 6 │────▶│ TypeORM 0.3 │────▶│ │
|
||||||
│ ECharts │ │ JWT + Passport │ │ MySQL 8 │
|
│ ECharts │ │ JWT + Passport │ │ │
|
||||||
│ Vite 8 │ │ ExcelJS + PDFKit │ │ (生产) │
|
│ Vite 8 │ │ ExcelJS + PDFKit │ │ │
|
||||||
└─────────────────┘ └──────────────────┘ └──────────┘
|
└─────────────────┘ └──────────────────┘ └──────────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -37,6 +37,7 @@
|
|||||||
|
|
||||||
- Node.js >= 18
|
- Node.js >= 18
|
||||||
- npm >= 9
|
- npm >= 9
|
||||||
|
- MySQL 8.0
|
||||||
|
|
||||||
### 后端启动
|
### 后端启动
|
||||||
|
|
||||||
@@ -93,7 +94,7 @@ docker-compose up -d # 一键启动 MySQL + 后端 + 前端
|
|||||||
|
|
||||||
| 配置项 | 说明 | 默认值 |
|
| 配置项 | 说明 | 默认值 |
|
||||||
|--------|------|--------|
|
|--------|------|--------|
|
||||||
| `DB_TYPE` | 数据库类型 | `mysql` |
|
| `DB_TYPE` | 数据库类型(仅支持 MySQL) | `mysql` |
|
||||||
| `DB_HOST` | 数据库地址 | `localhost` |
|
| `DB_HOST` | 数据库地址 | `localhost` |
|
||||||
| `DB_PORT` | 数据库端口 | `3306` |
|
| `DB_PORT` | 数据库端口 | `3306` |
|
||||||
| `DB_USERNAME` | 数据库用户名 | `dorm_billing` |
|
| `DB_USERNAME` | 数据库用户名 | `dorm_billing` |
|
||||||
|
|||||||
@@ -25,6 +25,22 @@ server {
|
|||||||
add_header Cache-Control "no-cache";
|
add_header Cache-Control "no-cache";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# SSE 长连接:禁用代理缓冲并放宽读写超时,避免 60s 空闲被掐断
|
||||||
|
location ~ ^/api/(notifications/stream|attendance-records/import/dingtalk/stream|ai/chat/.*/stream)$ {
|
||||||
|
proxy_pass http://backend:3000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Connection "";
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_buffering off;
|
||||||
|
proxy_cache off;
|
||||||
|
proxy_read_timeout 3600s;
|
||||||
|
proxy_send_timeout 3600s;
|
||||||
|
add_header X-Accel-Buffering no;
|
||||||
|
}
|
||||||
|
|
||||||
location /api/ {
|
location /api/ {
|
||||||
proxy_pass http://backend:3000/api/;
|
proxy_pass http://backend:3000/api/;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
|
|||||||
@@ -14,29 +14,45 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ant-design/icons": "^6.1.1",
|
"@ant-design/icons": "^6.1.1",
|
||||||
|
"@ant-design/x": "^2.8.0",
|
||||||
|
"@ant-design/x-card": "^2.9.0",
|
||||||
|
"@ant-design/x-markdown": "^2.8.0",
|
||||||
|
"@ant-design/x-sdk": "^2.8.0",
|
||||||
"@dnd-kit/core": "^6.3.1",
|
"@dnd-kit/core": "^6.3.1",
|
||||||
"@dnd-kit/sortable": "^10.0.0",
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
"@dnd-kit/utilities": "^3.2.2",
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
|
"@rc-component/upload": "^1.1.1",
|
||||||
|
"@tanstack/react-query": "^5.101.4",
|
||||||
"antd": "^6.3.6",
|
"antd": "^6.3.6",
|
||||||
"axios": "^1.15.1",
|
"axios": "^1.15.1",
|
||||||
"dayjs": "^1.11.20",
|
"dayjs": "^1.11.20",
|
||||||
"echarts": "^6.0.0",
|
"echarts": "^6.0.0",
|
||||||
"echarts-for-react": "^3.0.6",
|
"fast-deep-equal": "^3.1.3",
|
||||||
|
"file-saver": "^2.0.5",
|
||||||
|
"mermaid": "^11.16.0",
|
||||||
"react": "^19.2.5",
|
"react": "^19.2.5",
|
||||||
"react-dom": "^19.2.5",
|
"react-dom": "^19.2.5",
|
||||||
"react-router-dom": "^7.14.1",
|
"react-router": "^8.3.0",
|
||||||
"tslib": "^2.8.1"
|
"react-syntax-highlighter": "^16.1.1",
|
||||||
|
"use-immer": "^0.11.0",
|
||||||
|
"usehooks-ts": "^3.1.1",
|
||||||
|
"zod": "^4.4.3",
|
||||||
|
"zustand": "^5.0.14"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@gongxue/typescript-config": "*",
|
"@gongxue/typescript-config": "*",
|
||||||
|
"@tanstack/react-query-devtools": "^5.101.4",
|
||||||
|
"@types/file-saver": "^2.0.7",
|
||||||
"@types/node": "^24.12.2",
|
"@types/node": "^24.12.2",
|
||||||
"@types/react": "^19.2.14",
|
"@types/react": "^19.2.14",
|
||||||
"@types/react-dom": "^19.2.3",
|
"@types/react-dom": "^19.2.3",
|
||||||
|
"@types/react-syntax-highlighter": "^15.5.13",
|
||||||
"@vitejs/plugin-react": "^6.0.1",
|
"@vitejs/plugin-react": "^6.0.1",
|
||||||
"@vitest/browser": "^4.1.10",
|
"@vitest/browser": "^4.1.10",
|
||||||
"@vitest/browser-playwright": "^4.1.10",
|
"@vitest/browser-playwright": "^4.1.10",
|
||||||
"@vitest/coverage-v8": "^4.1.10",
|
"@vitest/coverage-v8": "^4.1.10",
|
||||||
"playwright": "^1.61.1",
|
"playwright": "^1.61.1",
|
||||||
|
"rollup-plugin-visualizer": "^7.0.1",
|
||||||
"typescript": "~6.0.2",
|
"typescript": "~6.0.2",
|
||||||
"vite": "^8.0.9",
|
"vite": "^8.0.9",
|
||||||
"vitest": "^4.1.10"
|
"vitest": "^4.1.10"
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 9.3 KiB After Width: | Height: | Size: 343 B |
@@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,14 @@
|
|||||||
import React, { Suspense, lazy } from 'react';
|
import React, { Suspense, lazy } from 'react';
|
||||||
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
|
import { BrowserRouter, Routes, Route, Navigate } from 'react-router';
|
||||||
import { ConfigProvider, App as AntdApp, Spin } from 'antd';
|
import { ConfigProvider, App as AntdApp, Spin } from 'antd';
|
||||||
|
import XProvider from '@ant-design/x/es/x-provider';
|
||||||
|
import xZhCN from '@ant-design/x/es/locale/zh_CN';
|
||||||
import zhCN from 'antd/es/locale/zh_CN';
|
import zhCN from 'antd/es/locale/zh_CN';
|
||||||
import MainLayout from './layouts/MainLayout';
|
import MainLayout from './layouts/MainLayout';
|
||||||
import PermissionRoute from './components/PermissionRoute';
|
import PermissionRoute from './components/PermissionRoute';
|
||||||
import DefaultRoute from './components/DefaultRoute';
|
import DefaultRoute from './components/DefaultRoute';
|
||||||
import AppMessageBridge from './ui/AppMessageBridge';
|
import AppMessageBridge from './ui/AppMessageBridge';
|
||||||
|
import { useUserStore } from './store/user/userStore';
|
||||||
|
|
||||||
const LoginPage = lazy(() => import('./pages/Login'));
|
const LoginPage = lazy(() => import('./pages/Login'));
|
||||||
const DashboardPage = lazy(() => import('./pages/Dashboard'));
|
const DashboardPage = lazy(() => import('./pages/Dashboard'));
|
||||||
@@ -40,7 +43,7 @@ const IntegrationConfigPage = lazy(() => import('./pages/IntegrationConfig'));
|
|||||||
const AiConfigPage = lazy(() => import('./pages/AiConfig'));
|
const AiConfigPage = lazy(() => import('./pages/AiConfig'));
|
||||||
|
|
||||||
const PrivateRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
const PrivateRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||||
const token = localStorage.getItem('token');
|
const token = useUserStore((state) => state.token);
|
||||||
return token ? <>{children}</> : <Navigate to="/login" />;
|
return token ? <>{children}</> : <Navigate to="/login" />;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -58,9 +61,19 @@ const App: React.FC = () => {
|
|||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<AntdApp>
|
<XProvider
|
||||||
<AppMessageBridge />
|
locale={{ ...zhCN, ...xZhCN }}
|
||||||
<BrowserRouter>
|
theme={{
|
||||||
|
token: { colorPrimary: '#007AFF', borderRadius: 10 },
|
||||||
|
components: {
|
||||||
|
Sender: { colorBorder: '#d9d9de' },
|
||||||
|
Bubble: { colorBgContainer: '#f5f7fa' },
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<AntdApp>
|
||||||
|
<AppMessageBridge />
|
||||||
|
<BrowserRouter>
|
||||||
<Suspense
|
<Suspense
|
||||||
fallback={
|
fallback={
|
||||||
<div style={{ minHeight: '40vh', display: 'grid', placeItems: 'center' }}>
|
<div style={{ minHeight: '40vh', display: 'grid', placeItems: 'center' }}>
|
||||||
@@ -330,8 +343,9 @@ const App: React.FC = () => {
|
|||||||
</Route>
|
</Route>
|
||||||
</Routes>
|
</Routes>
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
</AntdApp>
|
</AntdApp>
|
||||||
|
</XProvider>
|
||||||
</ConfigProvider>
|
</ConfigProvider>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
77
apps/admin/src/api/imports.ts
Normal file
77
apps/admin/src/api/imports.ts
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
import api from './index';
|
||||||
|
import { validateResponse } from '../utils/validate';
|
||||||
|
import { importRunEnvelopeSchema } from './schemas';
|
||||||
|
import type {
|
||||||
|
ImportPreviewResult,
|
||||||
|
ImportReceipt,
|
||||||
|
ImportRunDetail,
|
||||||
|
ImportStageRequest,
|
||||||
|
} from '../components/ImportWizard/types';
|
||||||
|
|
||||||
|
interface ApiEnvelope<T> {
|
||||||
|
success: boolean;
|
||||||
|
data: T;
|
||||||
|
message?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createImportRun(
|
||||||
|
file: File,
|
||||||
|
options: {
|
||||||
|
source: 'ai' | 'manual';
|
||||||
|
conversationId?: number;
|
||||||
|
stages?: ImportStageRequest[];
|
||||||
|
mapping?: Record<string, Record<string, string>>;
|
||||||
|
},
|
||||||
|
): Promise<ImportRunDetail> {
|
||||||
|
const form = new FormData();
|
||||||
|
form.append('file', file);
|
||||||
|
form.append('source', options.source);
|
||||||
|
if (options.conversationId) form.append('conversationId', String(options.conversationId));
|
||||||
|
if (options.stages?.length) form.append('stages', JSON.stringify(options.stages));
|
||||||
|
if (options.mapping && Object.keys(options.mapping).length > 0) {
|
||||||
|
form.append('mapping', JSON.stringify(options.mapping));
|
||||||
|
}
|
||||||
|
const res = await api.post<ApiEnvelope<ImportRunDetail>>('/imports/runs', form);
|
||||||
|
return res.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getImportRun(runId: string): Promise<ImportRunDetail> {
|
||||||
|
const res = await api.get<ApiEnvelope<ImportRunDetail>>(
|
||||||
|
`/imports/runs/${encodeURIComponent(runId)}`,
|
||||||
|
);
|
||||||
|
return validateResponse<ApiEnvelope<ImportRunDetail>>(importRunEnvelopeSchema, res).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function previewImportStep(
|
||||||
|
runId: string,
|
||||||
|
stepKey: string,
|
||||||
|
body: { sheets?: string[]; mapping?: Record<string, string> },
|
||||||
|
): Promise<ImportPreviewResult> {
|
||||||
|
const res = await api.post<ApiEnvelope<ImportPreviewResult>>(
|
||||||
|
`/imports/runs/${encodeURIComponent(runId)}/steps/${encodeURIComponent(stepKey)}/preview`,
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
return res.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function commitImportStep(
|
||||||
|
runId: string,
|
||||||
|
stepKey: string,
|
||||||
|
decisions: Array<{ rowId: number; action: 'create' | 'update' | 'skip' }>,
|
||||||
|
): Promise<ImportReceipt> {
|
||||||
|
const res = await api.post<ApiEnvelope<ImportReceipt>>(
|
||||||
|
`/imports/runs/${encodeURIComponent(runId)}/steps/${encodeURIComponent(stepKey)}/commit`,
|
||||||
|
{ decisions },
|
||||||
|
);
|
||||||
|
return res.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function importErrorReportUrl(runId: string, stepKey?: string): string {
|
||||||
|
const base = import.meta.env.PROD
|
||||||
|
? '/api'
|
||||||
|
: `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (stepKey) params.set('stepKey', stepKey);
|
||||||
|
const query = params.toString();
|
||||||
|
return `${base}/imports/runs/${encodeURIComponent(runId)}/report${query ? `?${query}` : ''}`;
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
import axios, { type AxiosRequestConfig } from 'axios';
|
import axios, { type AxiosRequestConfig } from 'axios';
|
||||||
|
import { usePermissionStore } from '../store/permission/permissionStore';
|
||||||
|
import { useUserStore } from '../store/user/userStore';
|
||||||
|
|
||||||
const instance = axios.create({
|
const instance = axios.create({
|
||||||
baseURL: '/api',
|
baseURL: '/api',
|
||||||
@@ -6,7 +8,7 @@ const instance = axios.create({
|
|||||||
});
|
});
|
||||||
|
|
||||||
instance.interceptors.request.use((config) => {
|
instance.interceptors.request.use((config) => {
|
||||||
const token = localStorage.getItem('token');
|
const token = useUserStore.getState().token;
|
||||||
if (token) {
|
if (token) {
|
||||||
config.headers.Authorization = `Bearer ${token}`;
|
config.headers.Authorization = `Bearer ${token}`;
|
||||||
}
|
}
|
||||||
@@ -19,9 +21,8 @@ instance.interceptors.response.use(
|
|||||||
const isLoginRequest = err.config?.url === '/auth/login' || err.config?.url === 'auth/login';
|
const isLoginRequest = err.config?.url === '/auth/login' || err.config?.url === 'auth/login';
|
||||||
|
|
||||||
if (err.response?.status === 401 && !isLoginRequest) {
|
if (err.response?.status === 401 && !isLoginRequest) {
|
||||||
localStorage.removeItem('token');
|
useUserStore.getState().logout();
|
||||||
localStorage.removeItem('user');
|
usePermissionStore.getState().clearPermissions();
|
||||||
localStorage.removeItem('permissions');
|
|
||||||
window.location.href = '/login';
|
window.location.href = '/login';
|
||||||
}
|
}
|
||||||
if (err.response?.status === 403) {
|
if (err.response?.status === 403) {
|
||||||
|
|||||||
29
apps/admin/src/api/schemas/ai.ts
Normal file
29
apps/admin/src/api/schemas/ai.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
export const aiConfigSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
provider: z.string(),
|
||||||
|
baseUrl: z.string(),
|
||||||
|
hasApiKey: z.boolean(),
|
||||||
|
hasDatabaseKey: z.boolean(),
|
||||||
|
maskedApiKey: z.string().nullable(),
|
||||||
|
keySource: z.enum(['database', 'environment', 'none']),
|
||||||
|
defaultModel: z.string().nullable(),
|
||||||
|
enabled: z.boolean(),
|
||||||
|
supportsVision: z.boolean(),
|
||||||
|
timeoutMs: z.number(),
|
||||||
|
reasoningEffort: z.string().nullable(),
|
||||||
|
verified: z.boolean(),
|
||||||
|
lastTestedAt: z.string().nullable(),
|
||||||
|
lastTestLatencyMs: z.number().nullable(),
|
||||||
|
createdAt: z.string(),
|
||||||
|
updatedAt: z.string(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const aiConfigEnvelopeSchema = z
|
||||||
|
.object({ success: z.boolean(), data: aiConfigSchema })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
/** 导入任务 */
|
||||||
80
apps/admin/src/api/schemas/attendance.ts
Normal file
80
apps/admin/src/api/schemas/attendance.ts
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
export const attendanceRecordSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
studentId: z.number(),
|
||||||
|
classId: z.number().nullable(),
|
||||||
|
attendanceDate: z.string(),
|
||||||
|
session: z.string(),
|
||||||
|
status: z.string(),
|
||||||
|
remark: z.string().nullable(),
|
||||||
|
createdAt: z.string(),
|
||||||
|
student: z
|
||||||
|
.object({ id: z.number(), name: z.string(), studentNo: z.string().nullable().optional() })
|
||||||
|
.passthrough(),
|
||||||
|
class: z.object({ id: z.number(), name: z.string() }).passthrough().nullable(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const attendanceRecordsResponseSchema = z
|
||||||
|
.object({ list: z.array(attendanceRecordSchema), total: z.number() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const attendanceSummarySchema = z
|
||||||
|
.object({
|
||||||
|
total: z.number(),
|
||||||
|
present: z.number(),
|
||||||
|
late: z.number(),
|
||||||
|
absent: z.number(),
|
||||||
|
leave: z.number(),
|
||||||
|
pending: z.number(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const dingTalkSyncStatusSchema = z
|
||||||
|
.object({
|
||||||
|
lastPulledAt: z.string().nullable(),
|
||||||
|
action: z.string().nullable(),
|
||||||
|
username: z.string().nullable(),
|
||||||
|
detail: z.string().nullable(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
/** 学生档案聚合 */
|
||||||
|
|
||||||
|
export const attendanceClassOptionSchema = z
|
||||||
|
.object({ classId: z.number(), className: z.string() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const attendanceClassOptionsSchema = z.array(attendanceClassOptionSchema);
|
||||||
|
|
||||||
|
export const attendanceAlertSchema = z
|
||||||
|
.object({ id: z.number(), type: z.string(), message: z.string() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const attendanceAlertsSchema = z.array(attendanceAlertSchema);
|
||||||
|
|
||||||
|
export const attendancePeriodSchema = z
|
||||||
|
.object({
|
||||||
|
periodKey: z.string(),
|
||||||
|
label: z.string(),
|
||||||
|
startTime: z.string(),
|
||||||
|
endTime: z.string(),
|
||||||
|
sortOrder: z.number(),
|
||||||
|
enabled: z.boolean(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const attendancePeriodsSchema = z.array(attendancePeriodSchema);
|
||||||
|
|
||||||
|
export const attendanceScheduleOptionSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
subject: z.string(),
|
||||||
|
startTime: z.string(),
|
||||||
|
endTime: z.string(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const attendanceScheduleOptionsSchema = z.array(attendanceScheduleOptionSchema);
|
||||||
346
apps/admin/src/api/schemas/core.ts
Normal file
346
apps/admin/src/api/schemas/core.ts
Normal file
@@ -0,0 +1,346 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
export const studentProfileAggregateSchema = z
|
||||||
|
.object({
|
||||||
|
student: z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
name: z.string(),
|
||||||
|
phone: z.string(),
|
||||||
|
idNumber: z.string(),
|
||||||
|
studentNo: z.string(),
|
||||||
|
status: z.string(),
|
||||||
|
})
|
||||||
|
.passthrough(),
|
||||||
|
profile: z.record(z.string(), z.unknown()).nullable(),
|
||||||
|
enrollments: z.array(z.record(z.string(), z.unknown())),
|
||||||
|
examScores: z.array(z.record(z.string(), z.unknown())),
|
||||||
|
learningRecords: z.array(z.record(z.string(), z.unknown())),
|
||||||
|
result: z.record(z.string(), z.unknown()).nullable(),
|
||||||
|
attachments: z.array(z.record(z.string(), z.unknown())),
|
||||||
|
attendances: z.array(z.record(z.string(), z.unknown())),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
/** 权限树 */
|
||||||
|
export const permissionItemSchema = z
|
||||||
|
.object({ id: z.number(), code: z.string(), name: z.string(), group: z.string() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const permissionTreeSchema = z.array(
|
||||||
|
z.object({ group: z.string(), permissions: z.array(permissionItemSchema) }).passthrough(),
|
||||||
|
);
|
||||||
|
|
||||||
|
/** 机构 */
|
||||||
|
export const organizationSchema = z
|
||||||
|
.object({ id: z.number(), name: z.string(), code: z.string(), status: z.string() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const organizationsSchema = z.array(organizationSchema);
|
||||||
|
|
||||||
|
export const organizationOptionSchema = z
|
||||||
|
.object({ id: z.number(), name: z.string() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const organizationOptionsSchema = z.array(organizationOptionSchema);
|
||||||
|
|
||||||
|
/** 账单 */
|
||||||
|
export const billSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
status: z.string(),
|
||||||
|
student: z
|
||||||
|
.object({ id: z.number(), name: z.string() })
|
||||||
|
.passthrough()
|
||||||
|
.nullable()
|
||||||
|
.optional(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const billsSchema = z.array(billSchema);
|
||||||
|
|
||||||
|
/** 班级 */
|
||||||
|
export const classSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
name: z.string(),
|
||||||
|
code: z.string(),
|
||||||
|
classType: z.string(),
|
||||||
|
isArchived: z.boolean(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const classesSchema = z.array(classSchema);
|
||||||
|
|
||||||
|
/** 教师 */
|
||||||
|
export const teacherSchema = z
|
||||||
|
.object({ id: z.number(), username: z.string(), name: z.string() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const teacherListSchema = z
|
||||||
|
.object({ list: z.array(teacherSchema), total: z.number() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
/** 角色 / 用户 */
|
||||||
|
export const roleSchema = z
|
||||||
|
.object({ id: z.number(), name: z.string(), status: z.number() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const rolesSchema = z.array(roleSchema);
|
||||||
|
|
||||||
|
export const userSchema = z
|
||||||
|
.object({ id: z.number(), username: z.string(), name: z.string() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const usersSchema = z.array(userSchema);
|
||||||
|
|
||||||
|
/** 操作日志 */
|
||||||
|
export const operationLogSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
module: z.string(),
|
||||||
|
action: z.string(),
|
||||||
|
username: z.string(),
|
||||||
|
createdAt: z.string(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const operationLogsSchema = z
|
||||||
|
.object({ data: z.array(operationLogSchema), total: z.number() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
/** 通知 */
|
||||||
|
export const notificationSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
type: z.string(),
|
||||||
|
title: z.string(),
|
||||||
|
content: z.string(),
|
||||||
|
isRead: z.boolean(),
|
||||||
|
createdAt: z.string(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const notificationsSchema = z.array(notificationSchema);
|
||||||
|
|
||||||
|
/** 考勤机 / 教室选项 */
|
||||||
|
export const attendanceDeviceSchema = z
|
||||||
|
.object({ id: z.number(), deviceSn: z.string(), deviceName: z.string(), status: z.string() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const attendanceDevicesSchema = z.array(attendanceDeviceSchema);
|
||||||
|
|
||||||
|
export const classroomOptionSchema = z
|
||||||
|
.object({ id: z.number(), name: z.string() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const classroomOptionsSchema = z.array(classroomOptionSchema);
|
||||||
|
|
||||||
|
/** 宿舍 / 教室 */
|
||||||
|
export const roomSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
roomNumber: z.string(),
|
||||||
|
status: z.string(),
|
||||||
|
currentCount: z.number(),
|
||||||
|
capacity: z.number(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const roomsOverviewSchema = z.array(roomSchema);
|
||||||
|
|
||||||
|
export const classroomSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
name: z.string(),
|
||||||
|
building: z.string().nullable().optional(),
|
||||||
|
status: z.string().nullable().optional(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const classroomsSchema = z.array(classroomSchema);
|
||||||
|
|
||||||
|
/** 学生 */
|
||||||
|
export const studentSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
name: z.string(),
|
||||||
|
studentNo: z.string().nullable().optional(),
|
||||||
|
status: z.string(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const studentsSchema = z.array(studentSchema);
|
||||||
|
|
||||||
|
/** 押金 */
|
||||||
|
export const depositSchema = z
|
||||||
|
.object({ id: z.number(), studentId: z.number(), amount: z.number(), status: z.string() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const depositsSchema = z.array(depositSchema);
|
||||||
|
|
||||||
|
export const depositStudentLookupSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
name: z.string().nullable().optional(),
|
||||||
|
studentNo: z.string().nullable().optional(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const depositStudentLookupsSchema = z.array(depositStudentLookupSchema);
|
||||||
|
|
||||||
|
export const eligibleStudentSchema = z
|
||||||
|
.object({ studentId: z.number(), roomId: z.number(), roomNumber: z.string() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const eligibleStudentsSchema = z.array(eligibleStudentSchema);
|
||||||
|
|
||||||
|
/** 钱包 */
|
||||||
|
export const walletSchema = z
|
||||||
|
.object({
|
||||||
|
studentId: z.number(),
|
||||||
|
studentName: z.string(),
|
||||||
|
balance: z.number(),
|
||||||
|
outstandingAmount: z.number(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const walletsSchema = z.array(walletSchema);
|
||||||
|
|
||||||
|
export const roomTypesSchema = z.array(z.string());
|
||||||
|
|
||||||
|
/** 费用 */
|
||||||
|
export const expenseRecordSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
expenseType: z.string(),
|
||||||
|
amount: z.number(),
|
||||||
|
status: z.string().optional(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const expenseRecordsSchema = z.array(expenseRecordSchema);
|
||||||
|
|
||||||
|
export const expenseStudentLookupSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
name: z.string().nullable().optional(),
|
||||||
|
studentNo: z.string().nullable().optional(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const expenseStudentLookupsSchema = z.array(expenseStudentLookupSchema);
|
||||||
|
|
||||||
|
export const expenseRoomsListSchema = z.array(z.record(z.string(), z.unknown()));
|
||||||
|
|
||||||
|
export const expenseLookupsSchema = z
|
||||||
|
.object({
|
||||||
|
rooms: z.array(z.record(z.string(), z.unknown())),
|
||||||
|
students: z.array(z.record(z.string(), z.unknown())),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const expenseTypesSchema = z.array(
|
||||||
|
z.object({ code: z.string(), name: z.string(), category: z.string() }),
|
||||||
|
);
|
||||||
|
|
||||||
|
/** 入住 */
|
||||||
|
export const occupancySchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
studentId: z.number(),
|
||||||
|
roomId: z.number(),
|
||||||
|
checkInDate: z.string().optional(),
|
||||||
|
status: z.string().optional(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const occupanciesSchema = z.array(occupancySchema);
|
||||||
|
|
||||||
|
/** 排课 */
|
||||||
|
export const scheduleLookupsSchema = z
|
||||||
|
.object({
|
||||||
|
classrooms: z.array(classroomOptionSchema),
|
||||||
|
classes: z.array(z.object({ id: z.number(), name: z.string() }).passthrough()),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const weeklyScheduleSchema = z.record(
|
||||||
|
z.string(),
|
||||||
|
z.record(
|
||||||
|
z.string(),
|
||||||
|
z.array(
|
||||||
|
z
|
||||||
|
.object({
|
||||||
|
id: z.number().nullable(),
|
||||||
|
classId: z.number().nullable(),
|
||||||
|
classroomId: z.number(),
|
||||||
|
weekDay: z.number(),
|
||||||
|
startTime: z.string(),
|
||||||
|
endTime: z.string(),
|
||||||
|
})
|
||||||
|
.passthrough(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
/** 租赁订单 */
|
||||||
|
export const rentalSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
classroom: z
|
||||||
|
.object({ id: z.number(), name: z.string() })
|
||||||
|
.passthrough()
|
||||||
|
.nullable()
|
||||||
|
.optional(),
|
||||||
|
lesseeOrganization: z
|
||||||
|
.object({ id: z.number(), name: z.string() })
|
||||||
|
.passthrough()
|
||||||
|
.nullable()
|
||||||
|
.optional(),
|
||||||
|
status: z.string().optional(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const rentalsSchema = z.array(rentalSchema);
|
||||||
|
|
||||||
|
/** 考试 */
|
||||||
|
export const examSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
examName: z.string(),
|
||||||
|
examType: z.string(),
|
||||||
|
isArchived: z.boolean(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const examsSchema = z.array(examSchema);
|
||||||
|
|
||||||
|
export const examDetailSchema = z
|
||||||
|
.object({ id: z.number(), examName: z.string() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const classOptionSchema = z
|
||||||
|
.object({ id: z.number(), name: z.string() })
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const classOptionsSchema = z.array(classOptionSchema);
|
||||||
|
|
||||||
|
export const studentFilterLookupsSchema = z
|
||||||
|
.object({
|
||||||
|
classes: z.array(z.object({ id: z.number(), name: z.string() }).passthrough()),
|
||||||
|
teachers: z.array(z.object({ id: z.number(), name: z.string() }).passthrough()),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
/** 教师工作台 */
|
||||||
|
export const teacherWorkspaceSchema = z
|
||||||
|
.object({
|
||||||
|
assignedClasses: z.array(
|
||||||
|
z.object({ classId: z.number(), className: z.string() }).passthrough(),
|
||||||
|
),
|
||||||
|
todaySchedules: z.array(z.record(z.string(), z.unknown())),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
/** 集成配置 */
|
||||||
44
apps/admin/src/api/schemas/dashboard.integration.test.ts
Normal file
44
apps/admin/src/api/schemas/dashboard.integration.test.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { ganttRoomsSchema } from './dashboard';
|
||||||
|
|
||||||
|
describe('ganttRoomsSchema 接口校验', () => {
|
||||||
|
const validPayload = [
|
||||||
|
{
|
||||||
|
roomNumber: 'A101',
|
||||||
|
occupancies: [
|
||||||
|
{
|
||||||
|
studentName: '张三',
|
||||||
|
studentId: 3,
|
||||||
|
checkInDate: '2026-05-01',
|
||||||
|
checkOutDate: null,
|
||||||
|
billingStartDate: '2026-05-01',
|
||||||
|
billingEndDate: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
it('接受合法的甘特图数据(studentId 为数字)', () => {
|
||||||
|
expect(ganttRoomsSchema.safeParse(validPayload).success).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('拒绝缺少 checkInDate 的入住记录', () => {
|
||||||
|
const payload = [
|
||||||
|
{
|
||||||
|
roomNumber: 'A101',
|
||||||
|
occupancies: [{ studentName: '张三', checkOutDate: null }],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
expect(ganttRoomsSchema.safeParse(payload).success).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('拒绝缺少 studentName 的入住记录', () => {
|
||||||
|
const payload = [
|
||||||
|
{
|
||||||
|
roomNumber: 'A101',
|
||||||
|
occupancies: [{ checkInDate: '2026-05-01', checkOutDate: null }],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
expect(ganttRoomsSchema.safeParse(payload).success).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
91
apps/admin/src/api/schemas/dashboard.ts
Normal file
91
apps/admin/src/api/schemas/dashboard.ts
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
export const classroomScheduleSchema = z
|
||||||
|
.object({
|
||||||
|
classrooms: z.array(z.record(z.string(), z.unknown())),
|
||||||
|
organizations: z.array(z.record(z.string(), z.unknown())),
|
||||||
|
// matrix: 教室 id → 日期 → 单条排课/租赁记录(对象,非数组)
|
||||||
|
matrix: z.record(z.string(), z.record(z.string(), z.record(z.string(), z.unknown()))),
|
||||||
|
summary: z.record(z.string(), z.record(z.string(), z.unknown())),
|
||||||
|
days: z.number().optional(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
/** Dashboard 统计 */
|
||||||
|
export const dashboardStatsSchema = z
|
||||||
|
.object({
|
||||||
|
totalRooms: z.number(),
|
||||||
|
totalStudents: z.number(),
|
||||||
|
occupiedBeds: z.number(),
|
||||||
|
totalCapacity: z.number(),
|
||||||
|
occupancyRate: z.string(),
|
||||||
|
classroomCount: z.number(),
|
||||||
|
classroomOccupancyRate: z.string(),
|
||||||
|
todayAttendanceRate: z.string().optional(),
|
||||||
|
monthlyIncome: z.number(),
|
||||||
|
classCount: z.number(),
|
||||||
|
teacherCount: z.number(),
|
||||||
|
pendingDeposits: z.number(),
|
||||||
|
activeRentals: z.number(),
|
||||||
|
todayPresent: z.number(),
|
||||||
|
occupancyByBuilding: z.array(
|
||||||
|
z.object({ building: z.string(), count: z.string() }).passthrough(),
|
||||||
|
),
|
||||||
|
attendanceByStatus: z.record(z.string(), z.number()),
|
||||||
|
expenseByType: z.array(z.object({ type: z.string(), total: z.string() }).passthrough()),
|
||||||
|
attendanceTrend: z.array(z.object({ date: z.string(), rate: z.string() }).passthrough()),
|
||||||
|
incomeTrend: z.array(z.object({ month: z.string(), amount: z.number() }).passthrough()),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const roomRankingSchema = z.array(
|
||||||
|
z.object({ roomNumber: z.string(), total: z.string() }).passthrough(),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const classAttendanceRankingSchema = z
|
||||||
|
.object({
|
||||||
|
top: z.array(
|
||||||
|
z
|
||||||
|
.object({ className: z.string(), present: z.number(), total: z.number(), rate: z.number() })
|
||||||
|
.passthrough(),
|
||||||
|
),
|
||||||
|
bottom: z.array(
|
||||||
|
z
|
||||||
|
.object({ className: z.string(), present: z.number(), total: z.number(), rate: z.number() })
|
||||||
|
.passthrough(),
|
||||||
|
),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const ganttRoomsSchema = z.array(
|
||||||
|
z
|
||||||
|
.object({
|
||||||
|
roomNumber: z.string(),
|
||||||
|
occupancies: z.array(
|
||||||
|
z.object({
|
||||||
|
studentName: z.string(),
|
||||||
|
studentId: z.union([z.string(), z.number()]).optional(),
|
||||||
|
checkInDate: z.string(),
|
||||||
|
checkOutDate: z.string().nullable(),
|
||||||
|
billingStartDate: z.string().optional(),
|
||||||
|
billingEndDate: z.string().nullable().optional(),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const classroomOccupanciesSchema = z.array(
|
||||||
|
z
|
||||||
|
.object({ name: z.string(), building: z.string(), capacity: z.number(), occupancy: z.number() })
|
||||||
|
.passthrough(),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const classroomUtilStatsSchema = z
|
||||||
|
.object({
|
||||||
|
totalClassrooms: z.number(),
|
||||||
|
inUseCount: z.number(),
|
||||||
|
utilizationRate: z.string(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
/** 考勤元数据 */
|
||||||
71
apps/admin/src/api/schemas/import-run.ts
Normal file
71
apps/admin/src/api/schemas/import-run.ts
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
export const importSheetMetaSchema = z
|
||||||
|
.object({
|
||||||
|
name: z.string(),
|
||||||
|
headers: z.array(z.string()),
|
||||||
|
rowCount: z.number(),
|
||||||
|
suggestedStepKey: z.string().nullable(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const importStepSummarySchema = z
|
||||||
|
.object({
|
||||||
|
total: z.number(),
|
||||||
|
valid: z.number(),
|
||||||
|
error: z.number(),
|
||||||
|
create: z.number(),
|
||||||
|
update: z.number(),
|
||||||
|
skip: z.number(),
|
||||||
|
})
|
||||||
|
.passthrough()
|
||||||
|
.nullable();
|
||||||
|
|
||||||
|
export const importStepDetailSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
stepKey: z.string(),
|
||||||
|
label: z.string(),
|
||||||
|
sheets: z.array(z.string()),
|
||||||
|
status: z.string(),
|
||||||
|
mapping: z.record(z.string(), z.string()),
|
||||||
|
summary: importStepSummarySchema,
|
||||||
|
committedAt: z.string().nullable(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const importRunSettingsSchema = z
|
||||||
|
.object({
|
||||||
|
mapping: z.record(z.string(), z.record(z.string(), z.string())).optional(),
|
||||||
|
organization: z.string().nullable().optional(),
|
||||||
|
updateExisting: z.boolean().optional(),
|
||||||
|
duplicatePolicy: z.enum(['error', 'skip']).optional(),
|
||||||
|
skipUnmatched: z.boolean().optional(),
|
||||||
|
})
|
||||||
|
.passthrough()
|
||||||
|
.nullable()
|
||||||
|
.optional();
|
||||||
|
|
||||||
|
export const importRunDetailSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.string(),
|
||||||
|
fileName: z.string(),
|
||||||
|
source: z.enum(['ai', 'manual']),
|
||||||
|
status: z.string(),
|
||||||
|
currentStepKey: z.string().nullable(),
|
||||||
|
createdAt: z.string(),
|
||||||
|
sheets: z.array(importSheetMetaSchema),
|
||||||
|
steps: z.array(importStepDetailSchema),
|
||||||
|
settings: importRunSettingsSchema,
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const importRunEnvelopeSchema = z
|
||||||
|
.object({
|
||||||
|
success: z.boolean(),
|
||||||
|
data: importRunDetailSchema,
|
||||||
|
message: z.string().optional(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
/** 考勤记录 */
|
||||||
6
apps/admin/src/api/schemas/index.ts
Normal file
6
apps/admin/src/api/schemas/index.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
export * from './core';
|
||||||
|
export * from './attendance';
|
||||||
|
export * from './dashboard';
|
||||||
|
export * from './import-run';
|
||||||
|
export * from './ai';
|
||||||
|
export * from './integration';
|
||||||
23
apps/admin/src/api/schemas/integration.ts
Normal file
23
apps/admin/src/api/schemas/integration.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
export const integrationConfigSchema = z
|
||||||
|
.object({
|
||||||
|
success: z.boolean(),
|
||||||
|
data: z.array(
|
||||||
|
z
|
||||||
|
.object({
|
||||||
|
type: z.string(),
|
||||||
|
verify: z.boolean(),
|
||||||
|
config: z.record(z.string(), z.unknown()),
|
||||||
|
})
|
||||||
|
.passthrough(),
|
||||||
|
),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
/** 金数据规则 */
|
||||||
|
export const jinshujuRulesSchema = z.array(
|
||||||
|
z.object({ id: z.number(), name: z.string(), formToken: z.string() }).passthrough(),
|
||||||
|
);
|
||||||
|
|
||||||
|
/** 教室排课总览 */
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 13 KiB |
@@ -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 |
@@ -1,3 +1,4 @@
|
|||||||
|
// aislop-ignore-file: duplicate-block -- 表格/表单声明结构相似且参数不同,渲染逻辑已共享组件化
|
||||||
export interface AppMenuItem {
|
export interface AppMenuItem {
|
||||||
key: string;
|
key: string;
|
||||||
label: string;
|
label: string;
|
||||||
@@ -36,100 +37,112 @@ const ROLE_ALIASES: Record<string, string> = {
|
|||||||
super_admin: 'super',
|
super_admin: 'super',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function entry(key: string, label: string, icon: string, permission: string): MenuEntry {
|
||||||
|
return { key, label, icon, permission };
|
||||||
|
}
|
||||||
|
|
||||||
|
function section(
|
||||||
|
key: string,
|
||||||
|
label: string,
|
||||||
|
icon: string,
|
||||||
|
roles: string[],
|
||||||
|
children: MenuEntry[],
|
||||||
|
): MenuSection {
|
||||||
|
return { key, label, icon, roles, children };
|
||||||
|
}
|
||||||
|
|
||||||
const SECTIONS: MenuSection[] = [
|
const SECTIONS: MenuSection[] = [
|
||||||
{
|
section(
|
||||||
key: 'teaching-group',
|
'teaching-group',
|
||||||
label: '教学工作',
|
'教学工作',
|
||||||
icon: 'calendar',
|
'calendar',
|
||||||
roles: ['teacher'],
|
['teacher'],
|
||||||
children: [
|
[
|
||||||
{
|
entry('/teacher-workspace', '今日教学', 'workspace', 'teacher-workspace:view'),
|
||||||
key: '/teacher-workspace',
|
|
||||||
label: '今日教学',
|
entry('/schedules', '我的排课', 'calendar', 'schedule:view'),
|
||||||
icon: 'workspace',
|
|
||||||
permission: 'teacher-workspace:view',
|
entry('/attendance', '课程考勤', 'attendance', 'attendance:view'),
|
||||||
},
|
|
||||||
{ key: '/schedules', label: '我的排课', icon: 'calendar', permission: 'schedule:view' },
|
|
||||||
{ key: '/attendance', label: '课程考勤', icon: 'attendance', permission: 'attendance:view' },
|
|
||||||
],
|
],
|
||||||
},
|
),
|
||||||
{
|
section(
|
||||||
key: 'academic-group',
|
'academic-group',
|
||||||
label: '教务管理',
|
'教务管理',
|
||||||
icon: 'academic',
|
'academic',
|
||||||
roles: ['academic', 'super'],
|
['academic', 'super'],
|
||||||
children: [
|
[
|
||||||
{ key: '/students', label: '学生管理', icon: 'students', permission: 'student:view' },
|
entry('/students', '学生管理', 'students', 'student:view'),
|
||||||
{ key: '/classes', label: '班级管理', icon: 'classes', permission: 'class:view' },
|
|
||||||
{ key: '/exams', label: '考试管理', icon: 'exam', permission: 'exam:view' },
|
entry('/classes', '班级管理', 'classes', 'class:view'),
|
||||||
{ key: '/teachers', label: '教师管理', icon: 'teachers', permission: 'teacher:view' },
|
|
||||||
{ key: '/schedules', label: '排课管理', icon: 'calendar', permission: 'schedule:view' },
|
entry('/exams', '考试管理', 'exam', 'exam:view'),
|
||||||
{ key: '/attendance', label: '历史考勤', icon: 'attendance', permission: 'attendance:view' },
|
|
||||||
{ key: '/classrooms', label: '教室查看', icon: 'classroom', permission: 'classroom:view' },
|
entry('/teachers', '教师管理', 'teachers', 'teacher:view'),
|
||||||
|
|
||||||
|
entry('/schedules', '排课管理', 'calendar', 'schedule:view'),
|
||||||
|
|
||||||
|
entry('/attendance', '历史考勤', 'attendance', 'attendance:view'),
|
||||||
|
|
||||||
|
entry('/classrooms', '教室查看', 'classroom', 'classroom:view'),
|
||||||
],
|
],
|
||||||
},
|
),
|
||||||
{
|
section(
|
||||||
key: 'accommodation-group',
|
'accommodation-group',
|
||||||
label: '住宿运营',
|
'住宿运营',
|
||||||
icon: 'home',
|
'home',
|
||||||
roles: ['accommodation', 'super'],
|
['accommodation', 'super'],
|
||||||
children: [
|
[
|
||||||
{ key: '/room-visual', label: '住宿总览', icon: 'overview', permission: 'room:view' },
|
entry('/room-visual', '住宿总览', 'overview', 'room:view'),
|
||||||
{ key: '/rooms', label: '房间管理', icon: 'home', permission: 'room:view' },
|
|
||||||
{ key: '/occupancies', label: '入住管理', icon: 'occupancy', permission: 'occupancy:view' },
|
entry('/rooms', '房间管理', 'home', 'room:view'),
|
||||||
{ key: '/expenses', label: '费用管理', icon: 'expense', permission: 'expense:view' },
|
|
||||||
{ key: '/bills', label: '账单管理', icon: 'bill', permission: 'bill:view' },
|
entry('/occupancies', '入住管理', 'occupancy', 'occupancy:view'),
|
||||||
{ key: '/wallets', label: '学生余额', icon: 'wallet', permission: 'wallet:view' },
|
|
||||||
{ key: '/deposits', label: '押金管理', icon: 'deposit', permission: 'deposit:view' },
|
entry('/expenses', '费用管理', 'expense', 'expense:view'),
|
||||||
|
|
||||||
|
entry('/bills', '账单管理', 'bill', 'bill:view'),
|
||||||
|
|
||||||
|
entry('/wallets', '学生余额', 'wallet', 'wallet:view'),
|
||||||
|
|
||||||
|
entry('/deposits', '押金管理', 'deposit', 'deposit:view'),
|
||||||
],
|
],
|
||||||
},
|
),
|
||||||
{
|
section(
|
||||||
key: 'classroom-group',
|
'classroom-group',
|
||||||
label: '教室运营',
|
'教室运营',
|
||||||
icon: 'classroom',
|
'classroom',
|
||||||
roles: ['classroom', 'super'],
|
['classroom', 'super'],
|
||||||
children: [
|
[
|
||||||
{
|
entry('/classroom-schedule', '教室排期', 'calendar', 'rental:view'),
|
||||||
key: '/classroom-schedule',
|
|
||||||
label: '教室排期',
|
entry('/classrooms', '教室管理', 'classroom', 'classroom:view'),
|
||||||
icon: 'calendar',
|
|
||||||
permission: 'rental:view',
|
entry('/attendance-devices', '考勤机绑定', 'attendance', 'classroom:view'),
|
||||||
},
|
|
||||||
{ key: '/classrooms', label: '教室管理', icon: 'classroom', permission: 'classroom:view' },
|
entry('/classroom-rentals', '租赁订单', 'rental', 'rental:view'),
|
||||||
{
|
|
||||||
key: '/attendance-devices',
|
entry('/organizations', '机构管理', 'organization', 'organization:view'),
|
||||||
label: '考勤机绑定',
|
|
||||||
icon: 'attendance',
|
|
||||||
permission: 'classroom:view',
|
|
||||||
},
|
|
||||||
{ key: '/classroom-rentals', label: '租赁订单', icon: 'rental', permission: 'rental:view' },
|
|
||||||
{
|
|
||||||
key: '/organizations',
|
|
||||||
label: '机构管理',
|
|
||||||
icon: 'organization',
|
|
||||||
permission: 'organization:view',
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
},
|
),
|
||||||
{
|
section(
|
||||||
key: 'system-group',
|
'system-group',
|
||||||
label: '系统管理',
|
'系统管理',
|
||||||
icon: 'settings',
|
'settings',
|
||||||
roles: ['system', 'super'],
|
['system', 'super'],
|
||||||
children: [
|
[
|
||||||
{ key: '/users', label: '账号管理', icon: 'users', permission: 'user:view' },
|
entry('/users', '账号管理', 'users', 'user:view'),
|
||||||
{ key: '/roles', label: '角色管理', icon: 'role', permission: 'role:view' },
|
|
||||||
{ key: '/permissions', label: '权限一览', icon: 'permission', permission: 'role:view' },
|
entry('/roles', '角色管理', 'role', 'role:view'),
|
||||||
{ key: '/operation-logs', label: '操作日志', icon: 'log', permission: 'log:view' },
|
|
||||||
{
|
entry('/permissions', '权限一览', 'permission', 'role:view'),
|
||||||
key: '/integration-config',
|
|
||||||
label: '钉钉集成',
|
entry('/operation-logs', '操作日志', 'log', 'log:view'),
|
||||||
icon: 'integration',
|
|
||||||
permission: 'integration:read',
|
entry('/integration-config', '钉钉集成', 'integration', 'integration:read'),
|
||||||
},
|
|
||||||
{ key: '/ai-config', label: 'AI 配置', icon: 'ai', permission: 'ai:config:read' },
|
entry('/ai-config', 'AI 配置', 'ai', 'ai:config:read'),
|
||||||
],
|
],
|
||||||
},
|
),
|
||||||
];
|
];
|
||||||
|
|
||||||
export function getRoleDomains(
|
export function getRoleDomains(
|
||||||
|
|||||||
67
apps/admin/src/auth/permission-state.integration.test.tsx
Normal file
67
apps/admin/src/auth/permission-state.integration.test.tsx
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
import { act } from 'react';
|
||||||
|
import { createRoot } from 'react-dom/client';
|
||||||
|
import { afterEach, beforeAll, describe, expect, it } from 'vitest';
|
||||||
|
import PermissionButton from '../components/PermissionButton';
|
||||||
|
import { usePermissionStore } from '../store/permission/permissionStore';
|
||||||
|
|
||||||
|
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>);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function readPermissionState() {
|
||||||
|
return {
|
||||||
|
permissions: usePermissionStore.getState().permissions,
|
||||||
|
status: usePermissionStore.getState().status,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
if (root) await act(async () => root?.unmount());
|
||||||
|
container?.remove();
|
||||||
|
root = null;
|
||||||
|
container = null;
|
||||||
|
usePermissionStore.getState().clearPermissions();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('permission state', () => {
|
||||||
|
it('ignores cached localStorage permissions until profile verification succeeds', async () => {
|
||||||
|
localStorage.setItem('permissions', JSON.stringify(['student:edit']));
|
||||||
|
usePermissionStore.getState().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 () => {
|
||||||
|
usePermissionStore.getState().beginPermissionVerification();
|
||||||
|
await renderPermissionButton();
|
||||||
|
expect(container?.textContent).not.toContain('编辑学生');
|
||||||
|
|
||||||
|
await act(async () => usePermissionStore.getState().writePermissions(['student:edit']));
|
||||||
|
expect(container?.textContent).toContain('编辑学生');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps verified permissions while profile verification refreshes in the background', async () => {
|
||||||
|
usePermissionStore.getState().writePermissions(['student:edit']);
|
||||||
|
usePermissionStore.getState().beginPermissionVerification();
|
||||||
|
|
||||||
|
expect(readPermissionState()).toEqual({ permissions: ['student:edit'], status: 'ready' });
|
||||||
|
await renderPermissionButton();
|
||||||
|
expect(container?.textContent).toContain('编辑学生');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
export const PERMISSIONS_UPDATED_EVENT = 'permissions-updated';
|
|
||||||
|
|
||||||
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 [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function writePermissions(permissions: string[]): void {
|
|
||||||
localStorage.setItem('permissions', JSON.stringify([...new Set(permissions)]));
|
|
||||||
window.dispatchEvent(new Event(PERMISSIONS_UPDATED_EVENT));
|
|
||||||
}
|
|
||||||
122
apps/admin/src/components/AiChat/AiChatDrawer.helpers.tsx
Normal file
122
apps/admin/src/components/AiChat/AiChatDrawer.helpers.tsx
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import type { BubbleListProps } from '@ant-design/x';
|
||||||
|
import type { Attachment } from '@ant-design/x/es/attachments';
|
||||||
|
import type { MessageInfo } from '@ant-design/x-sdk';
|
||||||
|
import { Tooltip } from 'antd';
|
||||||
|
import type { AiAttachment, AiChatMessage, AiConversation } from './types';
|
||||||
|
|
||||||
|
export interface ConversationData extends AiConversation {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ConversationRunStatus = 'running' | 'done' | 'error' | 'stopped';
|
||||||
|
|
||||||
|
export function conversationStatusMeta(status: ConversationRunStatus): {
|
||||||
|
label: string;
|
||||||
|
color: string;
|
||||||
|
} {
|
||||||
|
if (status === 'running') return { label: '生成中', color: 'processing' };
|
||||||
|
if (status === 'done') return { label: '已完成', color: 'success' };
|
||||||
|
if (status === 'error') return { label: '失败', color: 'error' };
|
||||||
|
return { label: '已停止', color: 'default' };
|
||||||
|
}
|
||||||
|
|
||||||
|
export 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;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toConversationData(item: AiConversation): ConversationData {
|
||||||
|
return { ...item, key: String(item.id), label: item.title };
|
||||||
|
}
|
||||||
|
|
||||||
|
export 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',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function emptyAssistant(): AiChatMessage {
|
||||||
|
return {
|
||||||
|
role: 'assistant',
|
||||||
|
content: '',
|
||||||
|
reasoningContent: '',
|
||||||
|
toolRuns: [],
|
||||||
|
attachments: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当前会话内新发送的用户消息还没有服务端数字 ID(本地为 msg_N 临时 key),
|
||||||
|
* 但紧随其后的 AI 回答会携带 replyToMessageId,可据此反推用户消息 ID。
|
||||||
|
*/
|
||||||
|
export function resolveUserMessageId(
|
||||||
|
info: MessageInfo<AiChatMessage>,
|
||||||
|
all: MessageInfo<AiChatMessage>[],
|
||||||
|
): number | null {
|
||||||
|
if (typeof info.message.id === 'number') return info.message.id;
|
||||||
|
const index = all.findIndex((item) => item.id === info.id);
|
||||||
|
if (index === -1) return null;
|
||||||
|
for (const item of all.slice(index + 1)) {
|
||||||
|
if (typeof item.message.replyToMessageId === 'number') {
|
||||||
|
return item.message.replyToMessageId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HoverActionItem {
|
||||||
|
key: string;
|
||||||
|
title: string;
|
||||||
|
icon: React.ReactNode;
|
||||||
|
danger?: boolean;
|
||||||
|
onClick: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Codex Desktop 风格:hover 消息时在气泡外显示的纯图标操作,不包裹 Button */
|
||||||
|
export function MessageHoverActions({ items }: { items: HoverActionItem[] }) {
|
||||||
|
return (
|
||||||
|
<div className="ai-chat-hover-actions" role="toolbar" aria-label="消息操作">
|
||||||
|
{items.map((item) => (
|
||||||
|
<Tooltip key={item.key} title={item.title}>
|
||||||
|
<span
|
||||||
|
role="button"
|
||||||
|
tabIndex={0}
|
||||||
|
className={`ai-chat-hover-action${item.danger ? ' is-danger' : ''}`}
|
||||||
|
aria-label={item.title}
|
||||||
|
onClick={item.onClick}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === 'Enter' || event.key === ' ') {
|
||||||
|
event.preventDefault();
|
||||||
|
item.onClick();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{item.icon}
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const aiBubbleRoles: BubbleListProps['role'] = {
|
||||||
|
user: { placement: 'end', variant: 'filled', shape: 'corner' },
|
||||||
|
assistant: { placement: 'start', variant: 'borderless' },
|
||||||
|
};
|
||||||
232
apps/admin/src/components/AiChat/AiChatDrawer.parts.tsx
Normal file
232
apps/admin/src/components/AiChat/AiChatDrawer.parts.tsx
Normal file
@@ -0,0 +1,232 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import {
|
||||||
|
CheckSquareOutlined,
|
||||||
|
MenuFoldOutlined,
|
||||||
|
MenuUnfoldOutlined,
|
||||||
|
PaperClipOutlined,
|
||||||
|
PlusOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import Attachments from '@ant-design/x/es/attachments';
|
||||||
|
import Conversations from '@ant-design/x/es/conversations';
|
||||||
|
import Sender from '@ant-design/x/es/sender';
|
||||||
|
import type { ConversationItemType } from '@ant-design/x';
|
||||||
|
import type { AttachmentsProps } from '@ant-design/x/es/attachments';
|
||||||
|
import { Button, Dropdown, Spin, Tooltip, Typography } from 'antd';
|
||||||
|
import type { MenuProps } from 'antd';
|
||||||
|
import type { AiSkill } from './types';
|
||||||
|
|
||||||
|
export interface AiChatSidebarProps {
|
||||||
|
className?: string;
|
||||||
|
conversationItems: ConversationItemType[];
|
||||||
|
activeConversationKey?: string;
|
||||||
|
selectionMode: boolean;
|
||||||
|
selectedKeys: string[];
|
||||||
|
loadingList: boolean;
|
||||||
|
conversationCount: number;
|
||||||
|
onActiveChange: (key: string) => void;
|
||||||
|
menu?: MenuProps | ((item: ConversationItemType) => MenuProps);
|
||||||
|
onStartNewConversation: () => void;
|
||||||
|
onSelectAll: () => void;
|
||||||
|
onInvertSelection: () => void;
|
||||||
|
onDeleteSelected: () => void;
|
||||||
|
onExitSelectionMode: () => void;
|
||||||
|
onEnterSelectionMode: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AiChatSidebar: React.FC<AiChatSidebarProps> = ({
|
||||||
|
className,
|
||||||
|
conversationItems,
|
||||||
|
activeConversationKey,
|
||||||
|
selectionMode,
|
||||||
|
selectedKeys,
|
||||||
|
loadingList,
|
||||||
|
conversationCount,
|
||||||
|
onActiveChange,
|
||||||
|
menu,
|
||||||
|
onStartNewConversation,
|
||||||
|
onSelectAll,
|
||||||
|
onInvertSelection,
|
||||||
|
onDeleteSelected,
|
||||||
|
onExitSelectionMode,
|
||||||
|
onEnterSelectionMode,
|
||||||
|
}) => {
|
||||||
|
return (
|
||||||
|
<aside className={className ?? 'ai-chat-sidebar'}>
|
||||||
|
<Conversations
|
||||||
|
items={conversationItems}
|
||||||
|
activeKey={activeConversationKey}
|
||||||
|
onActiveChange={onActiveChange}
|
||||||
|
menu={selectionMode ? undefined : menu}
|
||||||
|
creation={
|
||||||
|
selectionMode
|
||||||
|
? undefined
|
||||||
|
: { label: '新对话', icon: <PlusOutlined />, onClick: onStartNewConversation }
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{loadingList && <Spin className="ai-chat-sidebar__loading" />}
|
||||||
|
<div className="ai-chat-sidebar__footer">
|
||||||
|
{selectionMode ? (
|
||||||
|
<>
|
||||||
|
<span className="ai-chat-sidebar__selected-count">{selectedKeys.length} 已选</span>
|
||||||
|
<Button size="small" type="text" onClick={onSelectAll}>
|
||||||
|
全选
|
||||||
|
</Button>
|
||||||
|
<Button size="small" type="text" onClick={onInvertSelection}>
|
||||||
|
反选
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
type="text"
|
||||||
|
danger
|
||||||
|
disabled={selectedKeys.length === 0}
|
||||||
|
onClick={onDeleteSelected}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
<Button size="small" type="text" onClick={onExitSelectionMode}>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
type="text"
|
||||||
|
icon={<CheckSquareOutlined />}
|
||||||
|
disabled={conversationCount === 0}
|
||||||
|
onClick={onEnterSelectionMode}
|
||||||
|
>
|
||||||
|
管理
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface AiChatComposerProps {
|
||||||
|
conversationTitle: string;
|
||||||
|
input: string;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
isRequesting: boolean;
|
||||||
|
onSubmit: (value: string) => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
uploadItems: AttachmentsProps['items'];
|
||||||
|
onCustomUpload: AttachmentsProps['customRequest'];
|
||||||
|
onRemoveAttachment: AttachmentsProps['onRemove'];
|
||||||
|
deepThinking: boolean;
|
||||||
|
onDeepThinkingChange: (value: boolean) => void;
|
||||||
|
lockedSkill?: AiSkill;
|
||||||
|
onClearSkill: () => void;
|
||||||
|
onToggleSidebar: () => void;
|
||||||
|
sidebarOpen: boolean;
|
||||||
|
skillMenu: MenuProps;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AiChatComposer: React.FC<AiChatComposerProps> = ({
|
||||||
|
conversationTitle,
|
||||||
|
input,
|
||||||
|
onChange,
|
||||||
|
isRequesting,
|
||||||
|
onSubmit,
|
||||||
|
onCancel,
|
||||||
|
uploadItems,
|
||||||
|
onCustomUpload,
|
||||||
|
onRemoveAttachment,
|
||||||
|
deepThinking,
|
||||||
|
onDeepThinkingChange,
|
||||||
|
lockedSkill,
|
||||||
|
onClearSkill,
|
||||||
|
onToggleSidebar,
|
||||||
|
sidebarOpen,
|
||||||
|
skillMenu,
|
||||||
|
}) => {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="ai-chat-toolbar">
|
||||||
|
<Tooltip title={sidebarOpen ? '收起会话' : '展开会话'}>
|
||||||
|
<Button
|
||||||
|
type="text"
|
||||||
|
icon={sidebarOpen ? <MenuFoldOutlined /> : <MenuUnfoldOutlined />}
|
||||||
|
onClick={onToggleSidebar}
|
||||||
|
/>
|
||||||
|
</Tooltip>
|
||||||
|
<Typography.Text ellipsis>{conversationTitle}</Typography.Text>
|
||||||
|
<Dropdown menu={skillMenu} trigger={['click']}>
|
||||||
|
<Button size="small">{lockedSkill?.name || '自动技能'}</Button>
|
||||||
|
</Dropdown>
|
||||||
|
</div>
|
||||||
|
<div className="ai-chat-composer">
|
||||||
|
<Sender
|
||||||
|
value={input}
|
||||||
|
onChange={onChange}
|
||||||
|
loading={isRequesting}
|
||||||
|
onSubmit={onSubmit}
|
||||||
|
onCancel={onCancel}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
// 中文输入法合成中的回车(确认候选词)不应触发发送。
|
||||||
|
// 浏览器在 compositionend 后仍会派发 Enter keydown,
|
||||||
|
// 此时 Sender 内部的 composition 标记已失效,需用
|
||||||
|
// KeyboardEvent.isComposing / keyCode 229 兜底。
|
||||||
|
if (e.nativeEvent.isComposing || e.keyCode === 229) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}}
|
||||||
|
autoSize={{ minRows: 1, maxRows: 6 }}
|
||||||
|
placeholder="询问学生、考勤、宿舍或账单数据"
|
||||||
|
skill={
|
||||||
|
lockedSkill
|
||||||
|
? {
|
||||||
|
title: lockedSkill.name,
|
||||||
|
value: lockedSkill.key,
|
||||||
|
closable: { onClose: onClearSkill },
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
header={
|
||||||
|
(uploadItems ?? []).length > 0 && (
|
||||||
|
<div className="ai-chat-sender-header">
|
||||||
|
<Attachments
|
||||||
|
items={uploadItems}
|
||||||
|
customRequest={onCustomUpload}
|
||||||
|
onRemove={onRemoveAttachment}
|
||||||
|
accept="image/jpeg,image/png,image/webp,application/pdf,.docx,.xlsx"
|
||||||
|
multiple
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
footer={
|
||||||
|
<div className="ai-chat-sender-footer">
|
||||||
|
<Tooltip title="添加附件">
|
||||||
|
<Attachments
|
||||||
|
items={[]}
|
||||||
|
customRequest={onCustomUpload}
|
||||||
|
onRemove={onRemoveAttachment}
|
||||||
|
accept="image/jpeg,image/png,image/webp,application/pdf,.docx,.xlsx"
|
||||||
|
multiple
|
||||||
|
placeholder={{
|
||||||
|
title: '添加附件',
|
||||||
|
description: '图片、PDF、Word、Excel,单个不超过 10MB',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Button type="text" icon={<PaperClipOutlined />} aria-label="添加附件" />
|
||||||
|
</Attachments>
|
||||||
|
</Tooltip>
|
||||||
|
<Sender.Switch
|
||||||
|
checkedChildren="深度思考"
|
||||||
|
unCheckedChildren="普通"
|
||||||
|
value={deepThinking}
|
||||||
|
onChange={onDeepThinkingChange}
|
||||||
|
disabled={isRequesting}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Typography.Text type="secondary" className="ai-chat-disclaimer">
|
||||||
|
AI 操作均在权限范围内执行,写操作需通过表单确认,重要信息请以系统记录为准
|
||||||
|
</Typography.Text>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
554
apps/admin/src/components/AiChat/AiChatDrawer.tsx
Normal file
554
apps/admin/src/components/AiChat/AiChatDrawer.tsx
Normal file
@@ -0,0 +1,554 @@
|
|||||||
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import {
|
||||||
|
DeleteOutlined,
|
||||||
|
EditOutlined,
|
||||||
|
ArrowRightOutlined,
|
||||||
|
LoadingOutlined,
|
||||||
|
RobotOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import Bubble from '@ant-design/x/es/bubble';
|
||||||
|
import Prompts from '@ant-design/x/es/prompts';
|
||||||
|
import Welcome from '@ant-design/x/es/welcome';
|
||||||
|
import type { ConversationItemType } from '@ant-design/x';
|
||||||
|
import { useXConversations } from '@ant-design/x-sdk';
|
||||||
|
import {
|
||||||
|
App,
|
||||||
|
Checkbox,
|
||||||
|
Drawer,
|
||||||
|
Grid,
|
||||||
|
Input,
|
||||||
|
} from 'antd';
|
||||||
|
import type { MenuProps } from 'antd';
|
||||||
|
import { message } from '../../ui/app-message';
|
||||||
|
import { aiChatApi, conversationStreamUrl } from './api';
|
||||||
|
import { GongxueAiChatProvider } from './provider';
|
||||||
|
import { ImportWizardModal } from '../ImportWizard/ImportWizardModal';
|
||||||
|
import type { AiSkill } from './types';
|
||||||
|
import { useAiChatMessageActions } from './useAiChatMessageActions';
|
||||||
|
import { AiChatComposer, AiChatSidebar } from './AiChatDrawer.parts';
|
||||||
|
import {
|
||||||
|
aiBubbleRoles,
|
||||||
|
conversationStatusMeta,
|
||||||
|
sortConversations,
|
||||||
|
toConversationData,
|
||||||
|
type ConversationData,
|
||||||
|
type ConversationRunStatus,
|
||||||
|
} from './AiChatDrawer.helpers';
|
||||||
|
import './style.css';
|
||||||
|
|
||||||
|
export {
|
||||||
|
aiBubbleRoles,
|
||||||
|
conversationStatusMeta,
|
||||||
|
type ConversationData,
|
||||||
|
type ConversationRunStatus,
|
||||||
|
} from './AiChatDrawer.helpers';
|
||||||
|
|
||||||
|
interface AiChatDrawerProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onRequestingChange?: (working: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequestingChange }) => {
|
||||||
|
const { modal } = App.useApp();
|
||||||
|
const screens = Grid.useBreakpoint();
|
||||||
|
const isMobile = !screens.sm;
|
||||||
|
const [loadingList, setLoadingList] = useState(false);
|
||||||
|
// 断点首帧可能尚未解析(isMobile 误判为 true),桌面端默认展开会话侧边栏,
|
||||||
|
// 移动端通过 effectiveSidebarOpen 统一隐藏。
|
||||||
|
const [sidebarOpen, setSidebarOpen] = useState(true);
|
||||||
|
const effectiveSidebarOpen = isMobile ? false : sidebarOpen;
|
||||||
|
const [skills, setSkills] = useState<AiSkill[]>([]);
|
||||||
|
const [conversationStatus, setConversationStatus] = useState<
|
||||||
|
Record<number, ConversationRunStatus>
|
||||||
|
>({});
|
||||||
|
const [importWizardRunId, setImportWizardRunId] = useState<string | null>(null);
|
||||||
|
const [selectionMode, setSelectionMode] = useState(false);
|
||||||
|
const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
|
||||||
|
const requestAbortRef = useRef(new Map<number, () => void>());
|
||||||
|
const providersRef = useRef(new Map<number, GongxueAiChatProvider>());
|
||||||
|
const loadedRef = useRef(false);
|
||||||
|
|
||||||
|
const {
|
||||||
|
conversations,
|
||||||
|
activeConversationKey,
|
||||||
|
setActiveConversationKey,
|
||||||
|
addConversation,
|
||||||
|
removeConversation,
|
||||||
|
setConversation,
|
||||||
|
setConversations,
|
||||||
|
} = useXConversations({});
|
||||||
|
const activeConversationKeyRef = useRef(activeConversationKey);
|
||||||
|
|
||||||
|
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);
|
||||||
|
activeConversationKeyRef.current = activeConversationKey;
|
||||||
|
|
||||||
|
const refreshConversations = useCallback(async () => {
|
||||||
|
const items = sortConversations(await aiChatApi.listConversations()).map(toConversationData);
|
||||||
|
setConversations(items);
|
||||||
|
const current = activeConversationKeyRef.current;
|
||||||
|
setActiveConversationKey(
|
||||||
|
current && items.some((item) => item.key === current) ? current : (items[0]?.key ?? ''),
|
||||||
|
);
|
||||||
|
}, [setActiveConversationKey, setConversations]);
|
||||||
|
|
||||||
|
const markConversationRunning = useCallback((conversationId: number) => {
|
||||||
|
setConversationStatus((current) => ({ ...current, [conversationId]: 'running' }));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const markConversationFinished = useCallback(
|
||||||
|
(conversationId: number, result?: { ok: boolean; aborted?: boolean }) => {
|
||||||
|
requestAbortRef.current.delete(conversationId);
|
||||||
|
setConversationStatus((current) => ({
|
||||||
|
...current,
|
||||||
|
[conversationId]: result?.ok ? 'done' : result?.aborted ? 'stopped' : 'error',
|
||||||
|
}));
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
const provider = useMemo(() => {
|
||||||
|
if (!activeId) return undefined;
|
||||||
|
const existing = providersRef.current.get(activeId);
|
||||||
|
if (existing) return existing;
|
||||||
|
const created = new GongxueAiChatProvider(conversationStreamUrl(activeId), (result) => {
|
||||||
|
void refreshConversations();
|
||||||
|
markConversationFinished(activeId, result);
|
||||||
|
});
|
||||||
|
providersRef.current.set(activeId, created);
|
||||||
|
return created;
|
||||||
|
}, [activeId, markConversationFinished, refreshConversations]);
|
||||||
|
|
||||||
|
const {
|
||||||
|
input,
|
||||||
|
setInput,
|
||||||
|
deepThinking,
|
||||||
|
setDeepThinking,
|
||||||
|
isRequesting,
|
||||||
|
messages,
|
||||||
|
stopRequest,
|
||||||
|
submit,
|
||||||
|
customUpload,
|
||||||
|
removeAttachment,
|
||||||
|
discardPendingAttachments,
|
||||||
|
uploadItems,
|
||||||
|
promptItems,
|
||||||
|
bubbleItems,
|
||||||
|
} = useAiChatMessageActions({
|
||||||
|
activeConversation,
|
||||||
|
activeId,
|
||||||
|
provider,
|
||||||
|
requestAbortRef,
|
||||||
|
markConversationRunning,
|
||||||
|
addConversation,
|
||||||
|
setActiveConversationKey,
|
||||||
|
refreshConversations,
|
||||||
|
skills,
|
||||||
|
lockedSkill,
|
||||||
|
setImportWizardRunId,
|
||||||
|
});
|
||||||
|
|
||||||
|
// isRequesting 由 @ant-design/x-sdk 的 useXChat 内部维护且没有完成回调,
|
||||||
|
// 这里把它视为外部 SDK 状态做订阅转发,是 Effect 的合理用法。
|
||||||
|
useEffect(() => {
|
||||||
|
onRequestingChange?.(isRequesting);
|
||||||
|
}, [isRequesting, onRequestingChange]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || loadedRef.current) return;
|
||||||
|
let cancelled = false;
|
||||||
|
setLoadingList(true);
|
||||||
|
Promise.all([aiChatApi.listSkills(), aiChatApi.listConversations()])
|
||||||
|
.then(([skillItems, conversationItems]) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
loadedRef.current = true;
|
||||||
|
setSkills(skillItems);
|
||||||
|
const data = sortConversations(conversationItems).map(toConversationData);
|
||||||
|
setConversations(data);
|
||||||
|
setActiveConversationKey(data[0]?.key ?? '');
|
||||||
|
})
|
||||||
|
.catch(() => message.error('加载 AI 助手失败'))
|
||||||
|
.finally(() => !cancelled && setLoadingList(false));
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [open, setActiveConversationKey, setConversations]);
|
||||||
|
|
||||||
|
const switchConversation = useCallback(
|
||||||
|
(key: string) => {
|
||||||
|
discardPendingAttachments();
|
||||||
|
if (isMobile) setSidebarOpen(false);
|
||||||
|
setActiveConversationKey(key);
|
||||||
|
},
|
||||||
|
[discardPendingAttachments, isMobile, setActiveConversationKey],
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(
|
||||||
|
() => () => {
|
||||||
|
for (const abort of requestAbortRef.current.values()) abort();
|
||||||
|
requestAbortRef.current.clear();
|
||||||
|
providersRef.current.clear();
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
/** 新建对话(Codex 风格):先进入草稿态,发送第一条消息时才创建 session */
|
||||||
|
const startNewConversation = useCallback(() => {
|
||||||
|
switchConversation('');
|
||||||
|
}, [switchConversation]);
|
||||||
|
|
||||||
|
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, modal],
|
||||||
|
);
|
||||||
|
|
||||||
|
/** 删除单个会话时中止请求并清理会话运行时状态 */
|
||||||
|
const removeConversationEntry = useCallback(
|
||||||
|
(conversation: ConversationData) => {
|
||||||
|
const abortRequest = requestAbortRef.current.get(conversation.id);
|
||||||
|
if (abortRequest) abortRequest();
|
||||||
|
else if (conversation.id === activeId) stopRequest();
|
||||||
|
requestAbortRef.current.delete(conversation.id);
|
||||||
|
providersRef.current.delete(conversation.id);
|
||||||
|
setConversationStatus((current) => {
|
||||||
|
const next = { ...current };
|
||||||
|
delete next[conversation.id];
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[activeId, setConversationStatus, stopRequest],
|
||||||
|
);
|
||||||
|
|
||||||
|
const deleteConversation = useCallback(
|
||||||
|
(conversation: ConversationData) => {
|
||||||
|
modal.confirm({
|
||||||
|
title: '删除会话',
|
||||||
|
content: '该会话及全部历史消息将被永久删除。',
|
||||||
|
okText: '删除',
|
||||||
|
okButtonProps: { danger: true },
|
||||||
|
cancelText: '取消',
|
||||||
|
onOk: async () => {
|
||||||
|
await aiChatApi.deleteConversation(conversation.id);
|
||||||
|
removeConversationEntry(conversation);
|
||||||
|
removeConversation(conversation.key);
|
||||||
|
const remaining = conversations.filter((item) => item.key !== conversation.key);
|
||||||
|
if (!remaining.length) {
|
||||||
|
switchConversation('');
|
||||||
|
} else if (conversation.id === activeId) {
|
||||||
|
switchConversation(remaining[0].key);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[
|
||||||
|
activeId,
|
||||||
|
conversations,
|
||||||
|
switchConversation,
|
||||||
|
removeConversation,
|
||||||
|
removeConversationEntry,
|
||||||
|
modal,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
const enterSelectionMode = useCallback(() => {
|
||||||
|
setSelectedKeys([]);
|
||||||
|
setSelectionMode(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const exitSelectionMode = useCallback(() => {
|
||||||
|
setSelectedKeys([]);
|
||||||
|
setSelectionMode(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const selectAllConversations = useCallback(() => {
|
||||||
|
setSelectedKeys(conversations.map((item) => item.key));
|
||||||
|
}, [conversations]);
|
||||||
|
|
||||||
|
const invertConversationSelection = useCallback(() => {
|
||||||
|
setSelectedKeys((current) => {
|
||||||
|
const selected = new Set(current);
|
||||||
|
return conversations.map((item) => item.key).filter((key) => !selected.has(key));
|
||||||
|
});
|
||||||
|
}, [conversations]);
|
||||||
|
|
||||||
|
const toggleConversationSelection = useCallback((key: string) => {
|
||||||
|
setSelectedKeys((current) =>
|
||||||
|
current.includes(key) ? current.filter((item) => item !== key) : [...current, key],
|
||||||
|
);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const deleteSelectedConversations = useCallback(() => {
|
||||||
|
const selected = conversations.filter((item) =>
|
||||||
|
selectedKeys.includes(item.key),
|
||||||
|
) as ConversationData[];
|
||||||
|
if (!selected.length) return;
|
||||||
|
modal.confirm({
|
||||||
|
title: `删除选中的 ${selected.length} 个会话`,
|
||||||
|
content: '选中的会话及全部历史消息将被永久删除,此操作不可恢复。',
|
||||||
|
okText: '删除',
|
||||||
|
okButtonProps: { danger: true },
|
||||||
|
cancelText: '取消',
|
||||||
|
onOk: async () => {
|
||||||
|
if (selected.length === conversations.length) {
|
||||||
|
for (const abort of requestAbortRef.current.values()) abort();
|
||||||
|
requestAbortRef.current.clear();
|
||||||
|
providersRef.current.clear();
|
||||||
|
setConversationStatus({});
|
||||||
|
await aiChatApi.deleteAllConversations();
|
||||||
|
setConversations([]);
|
||||||
|
switchConversation('');
|
||||||
|
} else {
|
||||||
|
for (const item of selected) removeConversationEntry(item);
|
||||||
|
const deletedKeys: string[] = [];
|
||||||
|
const failedTitles: string[] = [];
|
||||||
|
await Promise.all(
|
||||||
|
selected.map(async (item) => {
|
||||||
|
try {
|
||||||
|
await aiChatApi.deleteConversation(item.id);
|
||||||
|
removeConversation(item.key);
|
||||||
|
deletedKeys.push(item.key);
|
||||||
|
} catch {
|
||||||
|
failedTitles.push(item.title);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const deleted = new Set(deletedKeys);
|
||||||
|
const remaining = conversations.filter((item) => !deleted.has(item.key));
|
||||||
|
setConversations(remaining);
|
||||||
|
if (!remaining.length) {
|
||||||
|
switchConversation('');
|
||||||
|
} else if (activeId != null && !remaining.some((item) => item.id === activeId)) {
|
||||||
|
switchConversation(remaining[0].key);
|
||||||
|
}
|
||||||
|
if (failedTitles.length) message.error(`删除失败:${failedTitles.join('、')}`);
|
||||||
|
}
|
||||||
|
setSelectedKeys([]);
|
||||||
|
setSelectionMode(false);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}, [
|
||||||
|
activeId,
|
||||||
|
conversations,
|
||||||
|
removeConversation,
|
||||||
|
removeConversationEntry,
|
||||||
|
selectedKeys,
|
||||||
|
switchConversation,
|
||||||
|
setConversations,
|
||||||
|
modal,
|
||||||
|
]);
|
||||||
|
|
||||||
|
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 (error) {
|
||||||
|
console.error('切换技能失败', error);
|
||||||
|
message.error('切换技能失败');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[activeConversation, setConversation],
|
||||||
|
);
|
||||||
|
|
||||||
|
const conversationItems = useMemo<ConversationItemType[]>(
|
||||||
|
() =>
|
||||||
|
conversations.map((item) => {
|
||||||
|
const status = conversationStatus[item.id];
|
||||||
|
let statusIndicator: React.ReactNode = null;
|
||||||
|
if (status === 'running') {
|
||||||
|
statusIndicator = (
|
||||||
|
<LoadingOutlined
|
||||||
|
spin
|
||||||
|
className="ai-chat-conversation-loading"
|
||||||
|
aria-label="生成中"
|
||||||
|
role="status"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
} else if (status === 'error' || status === 'stopped') {
|
||||||
|
statusIndicator = (
|
||||||
|
<span
|
||||||
|
className={`ai-chat-conversation-state is-${status}`}
|
||||||
|
aria-label={conversationStatusMeta(status).label}
|
||||||
|
>
|
||||||
|
<i />
|
||||||
|
{conversationStatusMeta(status).label}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const label = (
|
||||||
|
<span className="ai-chat-conversation-label">
|
||||||
|
{selectionMode && (
|
||||||
|
<Checkbox
|
||||||
|
checked={selectedKeys.includes(item.key)}
|
||||||
|
className="ai-chat-conversation-check"
|
||||||
|
aria-label={`选择 ${item.title}`}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<span className="ai-chat-conversation-label__title">{item.title}</span>
|
||||||
|
{statusIndicator}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
return { ...item, label };
|
||||||
|
}),
|
||||||
|
[conversationStatus, conversations, selectedKeys, selectionMode],
|
||||||
|
);
|
||||||
|
|
||||||
|
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}
|
||||||
|
closeIcon={<ArrowRightOutlined title="收起到后台继续运行" />}
|
||||||
|
onClose={onClose}
|
||||||
|
size={isMobile ? '100%' : 'min(1040px, 92vw)'}
|
||||||
|
destroyOnHidden={false}
|
||||||
|
className="ai-chat-drawer"
|
||||||
|
styles={{ body: { padding: 0, height: '100%' } }}
|
||||||
|
>
|
||||||
|
<div className="ai-chat-layout">
|
||||||
|
<AiChatSidebar
|
||||||
|
className={`ai-chat-sidebar${effectiveSidebarOpen ? ' is-open' : ''}`}
|
||||||
|
conversationItems={conversationItems}
|
||||||
|
activeConversationKey={activeConversationKey}
|
||||||
|
selectionMode={selectionMode}
|
||||||
|
selectedKeys={selectedKeys}
|
||||||
|
loadingList={loadingList}
|
||||||
|
conversationCount={conversations.length}
|
||||||
|
onActiveChange={(key) => {
|
||||||
|
if (selectionMode) toggleConversationSelection(key);
|
||||||
|
else switchConversation(key);
|
||||||
|
}}
|
||||||
|
menu={conversationMenu}
|
||||||
|
onStartNewConversation={startNewConversation}
|
||||||
|
onSelectAll={selectAllConversations}
|
||||||
|
onInvertSelection={invertConversationSelection}
|
||||||
|
onDeleteSelected={deleteSelectedConversations}
|
||||||
|
onExitSelectionMode={exitSelectionMode}
|
||||||
|
onEnterSelectionMode={enterSelectionMode}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<main className="ai-chat-main">
|
||||||
|
<AiChatComposer
|
||||||
|
input={input}
|
||||||
|
onChange={setInput}
|
||||||
|
isRequesting={isRequesting}
|
||||||
|
onSubmit={submit}
|
||||||
|
onCancel={stopRequest}
|
||||||
|
uploadItems={uploadItems}
|
||||||
|
onCustomUpload={customUpload}
|
||||||
|
onRemoveAttachment={removeAttachment}
|
||||||
|
deepThinking={deepThinking}
|
||||||
|
onDeepThinkingChange={setDeepThinking}
|
||||||
|
lockedSkill={lockedSkill}
|
||||||
|
onClearSkill={() => void setLockedSkill(null)}
|
||||||
|
onToggleSidebar={() => setSidebarOpen((value) => !value)}
|
||||||
|
sidebarOpen={effectiveSidebarOpen}
|
||||||
|
skillMenu={skillMenu}
|
||||||
|
conversationTitle={activeConversation?.title || 'AI 助手'}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
|
||||||
|
{importWizardRunId !== null && (
|
||||||
|
<ImportWizardModal
|
||||||
|
key={importWizardRunId}
|
||||||
|
open
|
||||||
|
runId={importWizardRunId}
|
||||||
|
onClose={() => setImportWizardRunId(null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</Drawer>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AiChatDrawer;
|
||||||
383
apps/admin/src/components/AiChat/AiMessageContent.tsx
Normal file
383
apps/admin/src/components/AiChat/AiMessageContent.tsx
Normal file
@@ -0,0 +1,383 @@
|
|||||||
|
import React, { useMemo, useState } from 'react';
|
||||||
|
import {
|
||||||
|
CheckCircleOutlined,
|
||||||
|
CloseCircleOutlined,
|
||||||
|
LoadingOutlined,
|
||||||
|
TableOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import FileCard from '@ant-design/x/es/file-card';
|
||||||
|
import Sources from '@ant-design/x/es/sources';
|
||||||
|
import Think from '@ant-design/x/es/think';
|
||||||
|
import ThoughtChain from '@ant-design/x/es/thought-chain';
|
||||||
|
import type { ThoughtChainItemType } from '@ant-design/x';
|
||||||
|
import XMarkdown, { type ComponentProps } from '@ant-design/x-markdown';
|
||||||
|
import { Alert, Button, Flex, Input, Space, Typography } from 'antd';
|
||||||
|
import { useUserStore } from '../../store/user/userStore';
|
||||||
|
import { DynamicChart } from './DynamicChart';
|
||||||
|
import { DynamicForm } from './DynamicForm';
|
||||||
|
import { DynamicReview } from './DynamicReview';
|
||||||
|
import { LiteCodeHighlighter } from './LiteCodeHighlighter';
|
||||||
|
import { LiteMermaid } from './LiteMermaid';
|
||||||
|
import type {
|
||||||
|
AiAttachment,
|
||||||
|
AiChatMessage,
|
||||||
|
AiChatMessageStatus,
|
||||||
|
AiChartSchema,
|
||||||
|
AiFormSchema,
|
||||||
|
AiImportWizard,
|
||||||
|
AiReviewSection,
|
||||||
|
AiReviewSchema,
|
||||||
|
AiReviewSectionType,
|
||||||
|
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: '读取经营概览',
|
||||||
|
render_form: '生成表单',
|
||||||
|
render_review: '生成导入预览',
|
||||||
|
render_chart: '生成图表',
|
||||||
|
start_import_wizard: '生成导入向导',
|
||||||
|
create_student: '创建学生',
|
||||||
|
search_exams: '查询考试',
|
||||||
|
search_schedules: '查询课表',
|
||||||
|
search_deposits: '查询押金',
|
||||||
|
search_expenses: '查询费用',
|
||||||
|
search_classrooms: '查询教室',
|
||||||
|
search_classroom_rentals: '查询教室租用',
|
||||||
|
get_sync_status: '查询同步状态',
|
||||||
|
get_business_context: '读取业务流程',
|
||||||
|
get_entity_schema: '读取实体字典',
|
||||||
|
get_pending_tasks: '查询业务待办',
|
||||||
|
};
|
||||||
|
|
||||||
|
const markdownComponents = {
|
||||||
|
code: ({ children, lang, block }: ComponentProps) => {
|
||||||
|
const content = String(children ?? '').replace(/\n$/, '');
|
||||||
|
if (!block) return <code>{content}</code>;
|
||||||
|
if (lang === 'mermaid') return <LiteMermaid>{content}</LiteMermaid>;
|
||||||
|
return <LiteCodeHighlighter lang={lang}>{content}</LiteCodeHighlighter>;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
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 = useUserStore.getState().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);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openSourceUrl(item: { url?: string }): Promise<void> {
|
||||||
|
if (!item.url) return;
|
||||||
|
const token = useUserStore.getState().token;
|
||||||
|
const response = await fetch(item.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" />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function EditUserContent({
|
||||||
|
initial,
|
||||||
|
onConfirm,
|
||||||
|
onCancel,
|
||||||
|
}: {
|
||||||
|
initial: string;
|
||||||
|
onConfirm: (value: string) => void;
|
||||||
|
onCancel?: () => void;
|
||||||
|
}) {
|
||||||
|
const [draft, setDraft] = useState(initial);
|
||||||
|
return (
|
||||||
|
<Space orientation="vertical" size={8} className="ai-chat-user-edit">
|
||||||
|
<Input.TextArea
|
||||||
|
value={draft}
|
||||||
|
onChange={(event) => setDraft(event.target.value)}
|
||||||
|
autoSize={{ minRows: 2, maxRows: 8 }}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
// 中文输入法合成中的回车不应触发保存
|
||||||
|
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
|
||||||
|
if (event.key === 'Enter' && !event.shiftKey) {
|
||||||
|
event.preventDefault();
|
||||||
|
onConfirm(draft);
|
||||||
|
} else if (event.key === 'Escape') {
|
||||||
|
onCancel?.();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Flex gap={8} justify="flex-end">
|
||||||
|
<Button size="small" onClick={onCancel}>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button size="small" type="primary" onClick={() => onConfirm(draft)}>
|
||||||
|
保存
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AiMessageContentProps {
|
||||||
|
message: AiChatMessage;
|
||||||
|
status?: AiChatMessageStatus;
|
||||||
|
editing?: boolean;
|
||||||
|
onEditConfirm?: (value: string) => void;
|
||||||
|
onEditCancel?: () => void;
|
||||||
|
onSubmitForm?: (form: AiFormSchema, values: Record<string, unknown>) => void;
|
||||||
|
onSubmitReview?: (reviewId: string, reviewTitle?: string) => void;
|
||||||
|
onConfirmReviewStep?: (
|
||||||
|
messageId: number | undefined,
|
||||||
|
reviewId: string,
|
||||||
|
sectionKey: AiReviewSection['key'],
|
||||||
|
) => AiReviewSchema | Promise<AiReviewSchema> | void;
|
||||||
|
onConfirmReviewGroup?: (
|
||||||
|
messageId: number | undefined,
|
||||||
|
reviewId: string,
|
||||||
|
type: AiReviewSectionType,
|
||||||
|
) => AiReviewSchema | Promise<AiReviewSchema> | void;
|
||||||
|
onOpenImportWizard?: (runId: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AiMessageContent: React.FC<AiMessageContentProps> = ({
|
||||||
|
message,
|
||||||
|
status,
|
||||||
|
editing,
|
||||||
|
onEditConfirm,
|
||||||
|
onEditCancel,
|
||||||
|
onSubmitForm,
|
||||||
|
onSubmitReview,
|
||||||
|
onConfirmReviewStep,
|
||||||
|
onConfirmReviewGroup,
|
||||||
|
onOpenImportWizard,
|
||||||
|
}) => {
|
||||||
|
const streaming = status === 'loading' || status === 'updating';
|
||||||
|
const formSubmission = message.metadata?.a2uiSubmit;
|
||||||
|
const reviewSubmission = message.metadata?.a2uiReviewSubmit;
|
||||||
|
const sourceMeta = message.metadata?.a2uiSources;
|
||||||
|
const sourceItems = Array.isArray(sourceMeta)
|
||||||
|
? sourceMeta
|
||||||
|
.filter(
|
||||||
|
(item): item is { title: string; url?: string; description?: string } =>
|
||||||
|
Boolean(item) && typeof (item as { title?: unknown }).title === 'string',
|
||||||
|
)
|
||||||
|
.map((item, index) => ({
|
||||||
|
key: `source-${index}`,
|
||||||
|
title: item.title,
|
||||||
|
...(item.url ? { url: item.url } : {}),
|
||||||
|
...(item.description ? { description: item.description } : {}),
|
||||||
|
}))
|
||||||
|
: [];
|
||||||
|
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') {
|
||||||
|
if (reviewSubmission && typeof reviewSubmission === 'object') {
|
||||||
|
const reviewTitle =
|
||||||
|
typeof (reviewSubmission as Record<string, unknown>).reviewTitle === 'string'
|
||||||
|
? String((reviewSubmission as Record<string, unknown>).reviewTitle)
|
||||||
|
: '批量导入';
|
||||||
|
return (
|
||||||
|
<Space orientation="vertical" size={8} className="ai-chat-user-content">
|
||||||
|
<Alert type="success" showIcon title={`已确认导入《${reviewTitle}》`} />
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (formSubmission && typeof formSubmission === 'object') {
|
||||||
|
const formTitle =
|
||||||
|
typeof (formSubmission as Record<string, unknown>).formTitle === 'string'
|
||||||
|
? String((formSubmission as Record<string, unknown>).formTitle)
|
||||||
|
: '表单';
|
||||||
|
return (
|
||||||
|
<Space orientation="vertical" size={8} className="ai-chat-user-content">
|
||||||
|
<Alert type="info" showIcon title={`已提交《${formTitle}》`} />
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<Space orientation="vertical" size={8} className="ai-chat-user-content">
|
||||||
|
{attachmentCards.length > 0 && (
|
||||||
|
<Flex wrap gap={8}>
|
||||||
|
{attachmentCards}
|
||||||
|
</Flex>
|
||||||
|
)}
|
||||||
|
{editing ? (
|
||||||
|
<EditUserContent
|
||||||
|
initial={message.content}
|
||||||
|
onConfirm={(value) => onEditConfirm?.(value)}
|
||||||
|
onCancel={onEditCancel}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="ai-chat-user-text">{message.content}</div>
|
||||||
|
)}
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Space orientation="vertical" size={10} className="ai-chat-answer">
|
||||||
|
{streaming &&
|
||||||
|
!message.content &&
|
||||||
|
!message.reasoningContent &&
|
||||||
|
message.toolRuns.length === 0 && (
|
||||||
|
<div className="ai-chat-streaming-placeholder" role="status" aria-label="生成中">
|
||||||
|
<LoadingOutlined spin />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{message.retrying && (
|
||||||
|
<Alert
|
||||||
|
type="warning"
|
||||||
|
showIcon
|
||||||
|
title={`AI 服务繁忙,正在自动重试(第 ${message.retrying.attempt} / ${message.retrying.maxRetries} 次)...`}
|
||||||
|
description={message.retrying.reason ? `原因:${message.retrying.reason}` : undefined}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{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>
|
||||||
|
)}
|
||||||
|
{(() => {
|
||||||
|
const wizard = message.metadata?.a2uiImportWizard as AiImportWizard | undefined;
|
||||||
|
if (!wizard || !onOpenImportWizard) return null;
|
||||||
|
return (
|
||||||
|
<Flex wrap gap={8} align="center">
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
icon={<TableOutlined />}
|
||||||
|
onClick={() => onOpenImportWizard(wizard.runId)}
|
||||||
|
>
|
||||||
|
打开导入向导
|
||||||
|
</Button>
|
||||||
|
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||||
|
{wizard.fileName}
|
||||||
|
</Typography.Text>
|
||||||
|
</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' },
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{sourceItems.length > 0 && (
|
||||||
|
<Sources
|
||||||
|
items={sourceItems}
|
||||||
|
title="引用来源"
|
||||||
|
onClick={(item) => void openSourceUrl(item as { url?: string })}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{(message.forms ?? []).map((form) => (
|
||||||
|
<DynamicForm
|
||||||
|
key={form.id}
|
||||||
|
form={form}
|
||||||
|
disabled={streaming}
|
||||||
|
onSubmit={(values) => onSubmitForm?.(form, values)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
{(message.reviews ?? []).map((review: AiReviewSchema) => (
|
||||||
|
<DynamicReview
|
||||||
|
key={review.id}
|
||||||
|
review={review}
|
||||||
|
messageId={typeof message.id === 'number' ? message.id : undefined}
|
||||||
|
disabled={streaming}
|
||||||
|
onSubmit={(reviewId) => onSubmitReview?.(reviewId, review.title)}
|
||||||
|
onConfirmStep={onConfirmReviewStep}
|
||||||
|
onConfirmGroup={onConfirmReviewGroup}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
{(message.charts ?? []).map((chart: AiChartSchema) => (
|
||||||
|
<DynamicChart key={chart.id} chart={chart} />
|
||||||
|
))}
|
||||||
|
{message.error && <Alert type="error" showIcon title={message.error} />}
|
||||||
|
{message.cancelled && <Typography.Text type="secondary">回答已停止</Typography.Text>}
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
};
|
||||||
305
apps/admin/src/components/AiChat/DynamicChart.tsx
Normal file
305
apps/admin/src/components/AiChat/DynamicChart.tsx
Normal file
@@ -0,0 +1,305 @@
|
|||||||
|
import React, { lazy, Suspense, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import { XCard, registerCatalog, type XAgentCommand_v0_9 } from '@ant-design/x-card';
|
||||||
|
import { Button, Spin, Tag, Tooltip, Typography } from 'antd';
|
||||||
|
import { DownloadOutlined } from '@ant-design/icons';
|
||||||
|
import type { EChartsType } from 'echarts/core';
|
||||||
|
import type { EChartsOption } from '../../components/ECharts';
|
||||||
|
import type { AiChartSchema } from './types';
|
||||||
|
|
||||||
|
// echarts 体积较大,仅在真正渲染图表时加载,避免打开 AI 抽屉就拉取
|
||||||
|
const ReactECharts = lazy(() => import('../../components/ECharts'));
|
||||||
|
|
||||||
|
const CHART_CATALOG_ID = 'gongxue-chart-catalog';
|
||||||
|
|
||||||
|
registerCatalog({
|
||||||
|
catalogId: CHART_CATALOG_ID,
|
||||||
|
components: {
|
||||||
|
ChartPreview: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
chart: { type: 'object' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
function surfaceId(chartId: string): string {
|
||||||
|
return `chart-${chartId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function numberValue(value: unknown): number {
|
||||||
|
const parsed = Number(value);
|
||||||
|
return Number.isFinite(parsed) ? parsed : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const CHART_TYPE_LABELS: Record<string, string> = {
|
||||||
|
line: '折线图',
|
||||||
|
bar: '柱状图',
|
||||||
|
pie: '饼图',
|
||||||
|
area: '面积图',
|
||||||
|
scatter: '散点图',
|
||||||
|
radar: '雷达图',
|
||||||
|
gauge: '仪表盘',
|
||||||
|
funnel: '漏斗图',
|
||||||
|
};
|
||||||
|
|
||||||
|
function buildNameValueRows(chart: AiChartSchema): { name: string; value: number }[] {
|
||||||
|
const nameField = chart.columns[0]?.key ?? '';
|
||||||
|
const valueField = chart.columns[1]?.key ?? '';
|
||||||
|
return chart.rows.map((row) => ({
|
||||||
|
name: String(row[nameField] ?? ''),
|
||||||
|
value: numberValue(row[valueField]),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildScatterOption(chart: AiChartSchema): EChartsOption {
|
||||||
|
const columns = chart.columns;
|
||||||
|
const nameField = columns[0]?.key ?? '';
|
||||||
|
const xField = columns[1]?.key ?? '';
|
||||||
|
const yField = columns[2]?.key ?? '';
|
||||||
|
const data = chart.rows.map((row) => ({
|
||||||
|
name: String(row[nameField] ?? ''),
|
||||||
|
value: [numberValue(row[xField]), numberValue(row[yField])],
|
||||||
|
}));
|
||||||
|
return {
|
||||||
|
tooltip: {
|
||||||
|
trigger: 'item',
|
||||||
|
formatter: (params: unknown) => {
|
||||||
|
const item = params as { name?: string; value?: number[] };
|
||||||
|
const [x, y] = item.value ?? [];
|
||||||
|
return `${item.name ?? ''}: (${x ?? 0}, ${y ?? 0})`;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
grid: { left: 8, right: 16, top: 32, bottom: 48, containLabel: true },
|
||||||
|
xAxis: { type: 'value', name: columns[1]?.title },
|
||||||
|
yAxis: { type: 'value', name: columns[2]?.title },
|
||||||
|
series: [{ type: 'scatter', symbolSize: 10, data }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildRadarOption(chart: AiChartSchema): EChartsOption {
|
||||||
|
const columns = chart.columns;
|
||||||
|
const seriesNameField = columns[0]?.key ?? '';
|
||||||
|
const indicatorColumns = columns.slice(1);
|
||||||
|
const indicators = indicatorColumns.map((column) => {
|
||||||
|
const values = chart.rows.map((row) => numberValue(row[column.key]));
|
||||||
|
const max = Math.max(1, ...values);
|
||||||
|
return { name: column.title, max: Math.ceil(max * 1.1) };
|
||||||
|
});
|
||||||
|
const seriesData = chart.rows.map((row) => ({
|
||||||
|
name: String(row[seriesNameField] ?? ''),
|
||||||
|
value: indicatorColumns.map((column) => numberValue(row[column.key])),
|
||||||
|
}));
|
||||||
|
return {
|
||||||
|
tooltip: { trigger: 'item' },
|
||||||
|
legend: { bottom: 0, type: 'scroll' },
|
||||||
|
radar: { indicator: indicators, radius: '65%' },
|
||||||
|
series: [{ type: 'radar', data: seriesData }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildGaugeOption(chart: AiChartSchema): EChartsOption {
|
||||||
|
const columns = chart.columns;
|
||||||
|
const nameField = columns[0]?.key ?? '';
|
||||||
|
const valueField = columns[1]?.key ?? '';
|
||||||
|
const maxField = columns[2]?.key;
|
||||||
|
const gauges = chart.rows.map((row) => ({
|
||||||
|
name: String(row[nameField] ?? ''),
|
||||||
|
value: numberValue(row[valueField]),
|
||||||
|
max: maxField ? Math.max(1, numberValue(row[maxField])) : 100,
|
||||||
|
}));
|
||||||
|
return {
|
||||||
|
series: gauges.map((gauge, index) => ({
|
||||||
|
type: 'gauge',
|
||||||
|
center: [`${((index + 0.5) * 100) / gauges.length}%`, '58%'],
|
||||||
|
radius: '75%',
|
||||||
|
min: 0,
|
||||||
|
max: gauge.max,
|
||||||
|
title: { show: true, offsetCenter: [0, '82%'], fontSize: 12 },
|
||||||
|
detail: { formatter: '{value}', fontSize: 14, offsetCenter: [0, '20%'] },
|
||||||
|
data: [{ value: gauge.value, name: gauge.name }],
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildNameValueOption(chart: AiChartSchema): EChartsOption {
|
||||||
|
const data = buildNameValueRows(chart);
|
||||||
|
return chart.chartType === 'funnel'
|
||||||
|
? {
|
||||||
|
tooltip: { trigger: 'item', formatter: '{b}: {c}' },
|
||||||
|
legend: { bottom: 0, type: 'scroll' },
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
type: 'funnel',
|
||||||
|
left: '10%',
|
||||||
|
top: 20,
|
||||||
|
bottom: 40,
|
||||||
|
width: '80%',
|
||||||
|
minSize: '20%',
|
||||||
|
label: { formatter: '{b}: {c}' },
|
||||||
|
data,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
tooltip: { trigger: 'item' },
|
||||||
|
legend: { bottom: 0, type: 'scroll' },
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
type: 'pie',
|
||||||
|
radius: ['35%', '68%'],
|
||||||
|
center: ['50%', '45%'],
|
||||||
|
data,
|
||||||
|
label: { formatter: '{b}: {c}' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildOption(chart: AiChartSchema): EChartsOption {
|
||||||
|
if (chart.chartType === 'scatter') return buildScatterOption(chart);
|
||||||
|
if (chart.chartType === 'radar') return buildRadarOption(chart);
|
||||||
|
if (chart.chartType === 'gauge') return buildGaugeOption(chart);
|
||||||
|
if (chart.chartType === 'funnel' || chart.chartType === 'pie') return buildNameValueOption(chart);
|
||||||
|
return buildCategoryOption(chart);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildCategoryOption(chart: AiChartSchema): EChartsOption {
|
||||||
|
const columns = chart.columns;
|
||||||
|
const categoryField = columns[0]?.key ?? '';
|
||||||
|
const categories = chart.rows.map((row) => String(row[categoryField] ?? ''));
|
||||||
|
const series = columns.slice(1).map((column) => ({
|
||||||
|
name: column.title,
|
||||||
|
type: chart.chartType === 'area' ? 'line' : chart.chartType,
|
||||||
|
smooth: chart.chartType === 'line',
|
||||||
|
...(chart.chartType === 'area' ? { areaStyle: { opacity: 0.18 } } : {}),
|
||||||
|
data: chart.rows.map((row) => numberValue(row[column.key])),
|
||||||
|
}));
|
||||||
|
return {
|
||||||
|
tooltip: { trigger: 'axis' },
|
||||||
|
legend: { bottom: 0, type: 'scroll' },
|
||||||
|
grid: { left: 8, right: 16, top: 32, bottom: 48, containLabel: true },
|
||||||
|
xAxis: {
|
||||||
|
type: 'category',
|
||||||
|
data: categories,
|
||||||
|
axisLabel: { interval: 0, rotate: categories.length > 8 ? 30 : 0 },
|
||||||
|
},
|
||||||
|
yAxis: { type: 'value' },
|
||||||
|
series,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ChartPreviewProps {
|
||||||
|
chart?: AiChartSchema;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A2UI component registered for the `gongxue-chart-catalog` catalog.
|
||||||
|
* Receives the validated tabular chart data through data binding and
|
||||||
|
* renders an ECharts option built from it.
|
||||||
|
*/
|
||||||
|
const ChartPreview: React.FC<ChartPreviewProps> = ({ chart }) => {
|
||||||
|
const option = useMemo<EChartsOption>(() => (chart ? buildOption(chart) : {}), [chart]);
|
||||||
|
const [instance, setInstance] = useState<EChartsType | null>(null);
|
||||||
|
if (!chart) return null;
|
||||||
|
|
||||||
|
const downloadImage = () => {
|
||||||
|
if (!instance) return;
|
||||||
|
const url = instance.getDataURL({
|
||||||
|
type: 'png',
|
||||||
|
pixelRatio: 2,
|
||||||
|
backgroundColor: '#fff',
|
||||||
|
});
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = `${chart.title || '图表'}.png`;
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="ai-chat-chart-card">
|
||||||
|
<div className="ai-chat-chart-card__header">
|
||||||
|
<Typography.Text strong>{chart.title}</Typography.Text>
|
||||||
|
<span className="ai-chat-chart-card__header-actions">
|
||||||
|
<Tag color="blue">{CHART_TYPE_LABELS[chart.chartType] ?? chart.chartType}</Tag>
|
||||||
|
<Tooltip title="下载图片">
|
||||||
|
<Button
|
||||||
|
type="text"
|
||||||
|
size="small"
|
||||||
|
className="ai-chat-chart-card__download"
|
||||||
|
aria-label="下载图表图片"
|
||||||
|
icon={<DownloadOutlined />}
|
||||||
|
onClick={downloadImage}
|
||||||
|
disabled={!instance}
|
||||||
|
/>
|
||||||
|
</Tooltip>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<Suspense fallback={<Spin size="small" />}>
|
||||||
|
<ReactECharts option={option} style={{ width: '100%', height: 260 }} onReady={setInstance} />
|
||||||
|
</Suspense>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface DynamicChartProps {
|
||||||
|
chart: AiChartSchema;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Chart card rendered through the official @ant-design/x-card renderer.
|
||||||
|
* Display-only: no submit endpoint, the schema lives in message metadata
|
||||||
|
* so history replays identically.
|
||||||
|
*/
|
||||||
|
export const DynamicChart: React.FC<DynamicChartProps> = ({ chart }) => {
|
||||||
|
const commandsRef = useRef<XAgentCommand_v0_9[]>([]);
|
||||||
|
const [commands, setCommands] = useState<XAgentCommand_v0_9[]>([]);
|
||||||
|
const idRef = useRef<string>('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const sid = surfaceId(chart.id);
|
||||||
|
if (idRef.current !== sid) {
|
||||||
|
commandsRef.current = [];
|
||||||
|
idRef.current = sid;
|
||||||
|
}
|
||||||
|
const cmds = commandsRef.current;
|
||||||
|
if (cmds.length === 0) {
|
||||||
|
cmds.push({
|
||||||
|
version: 'v0.9',
|
||||||
|
createSurface: { surfaceId: sid, catalogId: CHART_CATALOG_ID },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
cmds.push({
|
||||||
|
version: 'v0.9',
|
||||||
|
updateDataModel: {
|
||||||
|
surfaceId: sid,
|
||||||
|
path: '/chart',
|
||||||
|
value: chart,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
cmds.push({
|
||||||
|
version: 'v0.9',
|
||||||
|
updateComponents: {
|
||||||
|
surfaceId: sid,
|
||||||
|
components: [
|
||||||
|
{
|
||||||
|
id: 'root',
|
||||||
|
component: 'ChartPreview',
|
||||||
|
chart: { path: '/chart' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
setCommands([...cmds]);
|
||||||
|
}, [chart]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="ai-chat-chart">
|
||||||
|
<XCard.Box components={{ ChartPreview }} commands={commands}>
|
||||||
|
<XCard.Card id={surfaceId(chart.id)} />
|
||||||
|
</XCard.Box>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
257
apps/admin/src/components/AiChat/DynamicForm.tsx
Normal file
257
apps/admin/src/components/AiChat/DynamicForm.tsx
Normal file
@@ -0,0 +1,257 @@
|
|||||||
|
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import {
|
||||||
|
XCard,
|
||||||
|
registerCatalog,
|
||||||
|
type ActionPayload,
|
||||||
|
type XAgentCommand_v0_9,
|
||||||
|
} from '@ant-design/x-card';
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
Button,
|
||||||
|
DatePicker,
|
||||||
|
Flex,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
InputNumber,
|
||||||
|
Select,
|
||||||
|
Typography,
|
||||||
|
} from 'antd';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
import type { AiFormField, AiFormSchema } from './types';
|
||||||
|
|
||||||
|
const FORM_CATALOG_ID = 'gongxue-form-catalog';
|
||||||
|
|
||||||
|
registerCatalog({
|
||||||
|
catalogId: FORM_CATALOG_ID,
|
||||||
|
components: {
|
||||||
|
FormPreview: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
form: { type: 'object' },
|
||||||
|
disabled: { type: 'boolean' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
function surfaceId(formId: string): string {
|
||||||
|
return `form-${formId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function initialValue(field: AiFormField): unknown {
|
||||||
|
if (field.type === 'date' && typeof field.defaultValue === 'string') {
|
||||||
|
const parsed = dayjs(field.defaultValue);
|
||||||
|
return parsed.isValid() ? parsed : undefined;
|
||||||
|
}
|
||||||
|
return field.defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeValues(
|
||||||
|
fields: AiFormField[],
|
||||||
|
raw: Record<string, unknown>,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
const values: Record<string, unknown> = {};
|
||||||
|
for (const field of fields) {
|
||||||
|
const value = raw[field.name];
|
||||||
|
if (value === undefined || value === null || value === '') continue;
|
||||||
|
values[field.name] =
|
||||||
|
field.type === 'date' && dayjs.isDayjs(value) ? value.format('YYYY-MM-DD') : value;
|
||||||
|
}
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FormPreviewProps {
|
||||||
|
form?: AiFormSchema & {
|
||||||
|
submitting?: boolean;
|
||||||
|
submitted?: boolean;
|
||||||
|
error?: string | null;
|
||||||
|
};
|
||||||
|
disabled?: boolean;
|
||||||
|
onAction?: (name: string, context: Record<string, unknown>) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A2UI component registered for the `gongxue-form-catalog` catalog.
|
||||||
|
* Receives the validated form schema through data binding and reports
|
||||||
|
* normalized values back through the `form:submit` action.
|
||||||
|
*/
|
||||||
|
const FormPreview: React.FC<FormPreviewProps> = ({ form, disabled, onAction }) => {
|
||||||
|
const submitting = Boolean(form?.submitting);
|
||||||
|
const initialValues = useMemo(
|
||||||
|
() =>
|
||||||
|
Object.fromEntries((form?.fields ?? []).map((field) => [field.name, initialValue(field)])),
|
||||||
|
[form?.fields],
|
||||||
|
);
|
||||||
|
if (!form) return null;
|
||||||
|
const finished = Boolean(form.submitted) || form.status === 'submitted';
|
||||||
|
const expired = form.status === 'expired';
|
||||||
|
|
||||||
|
const handleFinish = (values: Record<string, unknown>) => {
|
||||||
|
onAction?.('form:submit', { values: normalizeValues(form.fields, values) });
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Flex vertical gap={8}>
|
||||||
|
<Typography.Text strong>{form.title}</Typography.Text>
|
||||||
|
{form.description && (
|
||||||
|
<Typography.Text type="secondary" className="ai-chat-dynamic-form__desc">
|
||||||
|
{form.description}
|
||||||
|
</Typography.Text>
|
||||||
|
)}
|
||||||
|
{expired ? (
|
||||||
|
<Alert type="warning" showIcon title="表单已失效" description="此表单已被新的请求替代,请让助手重新生成。" />
|
||||||
|
) : finished ? (
|
||||||
|
<Alert type="success" showIcon title="已提交,AI 正在处理…" />
|
||||||
|
) : (
|
||||||
|
<Form
|
||||||
|
layout="vertical"
|
||||||
|
size="small"
|
||||||
|
initialValues={initialValues}
|
||||||
|
onFinish={(values) => void handleFinish(values as Record<string, unknown>)}
|
||||||
|
disabled={disabled || submitting}
|
||||||
|
requiredMark={false}
|
||||||
|
>
|
||||||
|
{form.fields.map((field) => (
|
||||||
|
<Form.Item
|
||||||
|
key={field.name}
|
||||||
|
name={field.name}
|
||||||
|
label={field.label}
|
||||||
|
rules={[
|
||||||
|
{
|
||||||
|
required: field.required,
|
||||||
|
message: field.required
|
||||||
|
? field.type === 'select' || field.type === 'date'
|
||||||
|
? `请选择${field.label}`
|
||||||
|
: `请输入${field.label}`
|
||||||
|
: undefined,
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{field.type === 'textarea' ? (
|
||||||
|
<Input.TextArea rows={3} placeholder={field.placeholder} />
|
||||||
|
) : field.type === 'number' ? (
|
||||||
|
<InputNumber
|
||||||
|
className="ai-chat-dynamic-form__number"
|
||||||
|
placeholder={field.placeholder}
|
||||||
|
/>
|
||||||
|
) : field.type === 'select' ? (
|
||||||
|
<Select
|
||||||
|
allowClear={!field.required}
|
||||||
|
placeholder={field.placeholder}
|
||||||
|
options={field.options}
|
||||||
|
/>
|
||||||
|
) : field.type === 'date' ? (
|
||||||
|
<DatePicker
|
||||||
|
className="ai-chat-dynamic-form__date"
|
||||||
|
placeholder={field.placeholder}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Input placeholder={field.placeholder} />
|
||||||
|
)}
|
||||||
|
</Form.Item>
|
||||||
|
))}
|
||||||
|
{form.error && (
|
||||||
|
<Alert
|
||||||
|
type="error"
|
||||||
|
showIcon
|
||||||
|
title={form.error}
|
||||||
|
className="ai-chat-dynamic-form__error"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Button type="primary" htmlType="submit" loading={submitting} disabled={disabled}>
|
||||||
|
{form.submitLabel || '提交'}
|
||||||
|
</Button>
|
||||||
|
</Form>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface DynamicFormProps {
|
||||||
|
form: AiFormSchema;
|
||||||
|
disabled?: boolean;
|
||||||
|
onSubmit: (values: Record<string, unknown>) => void | Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A2UI form rendered through the official @ant-design/x-card renderer.
|
||||||
|
* The validated schema is bound into the surface data model; submit
|
||||||
|
* success/failure/loading transitions are pushed as incremental commands.
|
||||||
|
*/
|
||||||
|
export const DynamicForm: React.FC<DynamicFormProps> = ({ form, disabled, onSubmit }) => {
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [submitted, setSubmitted] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const commandsRef = useRef<XAgentCommand_v0_9[]>([]);
|
||||||
|
const [commands, setCommands] = useState<XAgentCommand_v0_9[]>([]);
|
||||||
|
const idRef = useRef<string>('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const sid = surfaceId(form.id);
|
||||||
|
if (idRef.current !== sid) {
|
||||||
|
commandsRef.current = [];
|
||||||
|
idRef.current = sid;
|
||||||
|
}
|
||||||
|
const cmds = commandsRef.current;
|
||||||
|
if (cmds.length === 0) {
|
||||||
|
cmds.push({
|
||||||
|
version: 'v0.9',
|
||||||
|
createSurface: { surfaceId: sid, catalogId: FORM_CATALOG_ID },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
cmds.push({
|
||||||
|
version: 'v0.9',
|
||||||
|
updateDataModel: {
|
||||||
|
surfaceId: sid,
|
||||||
|
path: '/form',
|
||||||
|
value: { ...form, submitting, submitted, error },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
cmds.push({
|
||||||
|
version: 'v0.9',
|
||||||
|
updateComponents: {
|
||||||
|
surfaceId: sid,
|
||||||
|
components: [
|
||||||
|
{
|
||||||
|
id: 'root',
|
||||||
|
component: 'FormPreview',
|
||||||
|
form: { path: '/form' },
|
||||||
|
disabled: Boolean(disabled),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
setCommands([...cmds]);
|
||||||
|
}, [disabled, error, form, submitted, submitting]);
|
||||||
|
|
||||||
|
const handleSubmit = async (values: Record<string, unknown>) => {
|
||||||
|
if (submitting) return;
|
||||||
|
setSubmitting(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await onSubmit(values);
|
||||||
|
setSubmitted(true);
|
||||||
|
} catch (reason) {
|
||||||
|
setError(reason instanceof Error ? reason.message : '提交失败,请稍后重试');
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAction = (payload: ActionPayload) => {
|
||||||
|
if (payload.name !== 'form:submit') return;
|
||||||
|
const values =
|
||||||
|
payload.context?.values && typeof payload.context.values === 'object'
|
||||||
|
? (payload.context.values as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
void handleSubmit(values);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="ai-chat-dynamic-form">
|
||||||
|
<XCard.Box components={{ FormPreview }} commands={commands} onAction={handleAction}>
|
||||||
|
<XCard.Card id={surfaceId(form.id)} />
|
||||||
|
</XCard.Box>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
600
apps/admin/src/components/AiChat/DynamicReview.tsx
Normal file
600
apps/admin/src/components/AiChat/DynamicReview.tsx
Normal file
@@ -0,0 +1,600 @@
|
|||||||
|
import React, { useEffect, useRef, useState } from 'react';
|
||||||
|
import {
|
||||||
|
XCard,
|
||||||
|
registerCatalog,
|
||||||
|
type ActionPayload,
|
||||||
|
type XAgentCommand_v0_9,
|
||||||
|
} from '@ant-design/x-card';
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
Button,
|
||||||
|
Flex,
|
||||||
|
Popconfirm,
|
||||||
|
Steps,
|
||||||
|
Table,
|
||||||
|
Tag,
|
||||||
|
Typography,
|
||||||
|
type TableProps,
|
||||||
|
} from 'antd';
|
||||||
|
import type { AiReviewRow, AiReviewSchema, AiReviewSection, AiReviewSectionType } from './types';
|
||||||
|
import {
|
||||||
|
GROUP_STATUS_LABELS,
|
||||||
|
SECTION_ORDER,
|
||||||
|
SECTION_STATUS_LABELS,
|
||||||
|
SECTION_TYPE_LABELS,
|
||||||
|
dependencyHint,
|
||||||
|
groupSections,
|
||||||
|
groupStatus,
|
||||||
|
sectionCount,
|
||||||
|
sectionResultText,
|
||||||
|
sectionStatus,
|
||||||
|
sectionType,
|
||||||
|
} from './reviewSection';
|
||||||
|
|
||||||
|
const REVIEW_CATALOG_ID = 'gongxue-review-catalog';
|
||||||
|
|
||||||
|
registerCatalog({
|
||||||
|
catalogId: REVIEW_CATALOG_ID,
|
||||||
|
components: {
|
||||||
|
ReviewPreview: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
review: { type: 'object' },
|
||||||
|
disabled: { type: 'boolean' },
|
||||||
|
activeKey: { type: 'string' },
|
||||||
|
activeType: { type: 'string' },
|
||||||
|
submittingKey: { type: ['string', 'null'] },
|
||||||
|
submittingGroup: { type: 'boolean' },
|
||||||
|
error: { type: ['string', 'null'] },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
function surfaceId(reviewId: string): string {
|
||||||
|
return `review-${reviewId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function errorMessage(reason: unknown): string {
|
||||||
|
if (reason instanceof Error) return reason.message;
|
||||||
|
if (reason && typeof reason === 'object' && 'message' in reason) {
|
||||||
|
return String((reason as { message?: unknown }).message ?? '确认失败,请稍后重试');
|
||||||
|
}
|
||||||
|
return '确认失败,请稍后重试';
|
||||||
|
}
|
||||||
|
|
||||||
|
function SectionTable({ section }: { section: AiReviewSection }) {
|
||||||
|
const columns: TableProps<AiReviewRow>['columns'] = section.columns.map((column) => ({
|
||||||
|
title: column.title,
|
||||||
|
dataIndex: column.key,
|
||||||
|
key: column.key,
|
||||||
|
ellipsis: true,
|
||||||
|
render: (value: unknown) =>
|
||||||
|
value === null || value === undefined || value === '' ? (
|
||||||
|
<Typography.Text type="secondary">-</Typography.Text>
|
||||||
|
) : (
|
||||||
|
String(value)
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
return (
|
||||||
|
<Table<AiReviewRow>
|
||||||
|
size="small"
|
||||||
|
rowKey="__rowKey"
|
||||||
|
columns={columns}
|
||||||
|
dataSource={section.rows.map((row, index) => ({ ...row, __rowKey: `row-${index}` }))}
|
||||||
|
pagination={{ pageSize: 10, size: 'small', hideOnSinglePage: true }}
|
||||||
|
scroll={{ x: 'max-content' }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ReviewPreviewProps {
|
||||||
|
review?: AiReviewSchema & {
|
||||||
|
submitting?: boolean;
|
||||||
|
activeKey?: string;
|
||||||
|
activeType?: AiReviewSectionType;
|
||||||
|
submittingKey?: string | null;
|
||||||
|
submittingGroup?: boolean;
|
||||||
|
error?: string | null;
|
||||||
|
};
|
||||||
|
disabled?: boolean;
|
||||||
|
onAction?: (name: string, context: Record<string, unknown>) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ReviewPreview: React.FC<ReviewPreviewProps> = ({ review, disabled, onAction }) => {
|
||||||
|
if (!review) return null;
|
||||||
|
const submitted = review.status === 'submitted';
|
||||||
|
const expired = review.status === 'expired';
|
||||||
|
const submitting = Boolean(review.submitting);
|
||||||
|
const submittingKey = review.submittingKey ?? null;
|
||||||
|
const submittingGroup = Boolean(review.submittingGroup);
|
||||||
|
const sections = review.sections;
|
||||||
|
const presentTypes = SECTION_ORDER.filter((type) =>
|
||||||
|
sections.some((section) => sectionType(section) === type),
|
||||||
|
);
|
||||||
|
const activeType = presentTypes.includes(review.activeType as AiReviewSectionType)
|
||||||
|
? (review.activeType as AiReviewSectionType)
|
||||||
|
: presentTypes[0];
|
||||||
|
if (!activeType) return null;
|
||||||
|
const activeSection =
|
||||||
|
sections.find((section) => section.key === review.activeKey) ??
|
||||||
|
groupSections(sections, activeType)[0];
|
||||||
|
const activeStatus = activeSection ? sectionStatus(activeSection) : 'pending';
|
||||||
|
const dependency =
|
||||||
|
activeSection === undefined ? null : dependencyHint(sections, sectionType(activeSection));
|
||||||
|
const typeItems = presentTypes.map((type, index) => {
|
||||||
|
const items = groupSections(sections, type);
|
||||||
|
const status = groupStatus(sections, type, submittingKey, submittingGroup, activeType);
|
||||||
|
const stepStatus: 'finish' | 'error' | 'process' | 'wait' =
|
||||||
|
status === 'submitted'
|
||||||
|
? 'finish'
|
||||||
|
: status === 'failed'
|
||||||
|
? 'error'
|
||||||
|
: status === 'importing' || type === activeType
|
||||||
|
? 'process'
|
||||||
|
: 'wait';
|
||||||
|
return {
|
||||||
|
key: type,
|
||||||
|
title: `${SECTION_TYPE_LABELS[type]}(${items.reduce((sum, item) => sum + sectionCount(item), 0)})`,
|
||||||
|
content: GROUP_STATUS_LABELS[status],
|
||||||
|
status: stepStatus,
|
||||||
|
index,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const group = groupSections(sections, activeType);
|
||||||
|
const typeTotal = group.reduce((sum, section) => sum + sectionCount(section), 0);
|
||||||
|
const groupDep = dependencyHint(sections, activeType);
|
||||||
|
const groupReady =
|
||||||
|
!submitted &&
|
||||||
|
!expired &&
|
||||||
|
!disabled &&
|
||||||
|
!submitting &&
|
||||||
|
!submittingKey &&
|
||||||
|
!submittingGroup &&
|
||||||
|
group.length > 0 &&
|
||||||
|
!group.every((section) => sectionStatus(section) === 'submitted') &&
|
||||||
|
!groupDep;
|
||||||
|
const anyRunning = submitting || Boolean(submittingKey) || submittingGroup;
|
||||||
|
const allIssues = sections.flatMap((section) => section.issues);
|
||||||
|
const allRows = sections.reduce((sum, section) => sum + sectionCount(section), 0);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="ai-chat-review-card">
|
||||||
|
<Flex justify="space-between" align="center" wrap gap={8}>
|
||||||
|
<Typography.Text strong className="ai-chat-review-card__title">
|
||||||
|
{review.title}
|
||||||
|
</Typography.Text>
|
||||||
|
{submitted ? (
|
||||||
|
<Tag color="success">已导入</Tag>
|
||||||
|
) : expired ? (
|
||||||
|
<Tag>已失效</Tag>
|
||||||
|
) : anyRunning ? (
|
||||||
|
<Tag color="processing">导入中</Tag>
|
||||||
|
) : (
|
||||||
|
<Tag color="gold">待确认</Tag>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
{review.summary && (
|
||||||
|
<Typography.Paragraph type="secondary" className="ai-chat-review-card__summary">
|
||||||
|
{review.summary}
|
||||||
|
</Typography.Paragraph>
|
||||||
|
)}
|
||||||
|
{expired && (
|
||||||
|
<Alert
|
||||||
|
type="warning"
|
||||||
|
showIcon
|
||||||
|
title="此导入预览已被新的预览替代,已失效"
|
||||||
|
description="如需导入,请使用最新的预览卡。"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Steps
|
||||||
|
size="small"
|
||||||
|
current={Math.max(
|
||||||
|
0,
|
||||||
|
typeItems.findIndex((item) => item.key === activeType),
|
||||||
|
)}
|
||||||
|
items={typeItems.map((item) => ({
|
||||||
|
key: item.key,
|
||||||
|
title: item.title,
|
||||||
|
content: item.content,
|
||||||
|
status: item.status,
|
||||||
|
}))}
|
||||||
|
onChange={(index) => {
|
||||||
|
const type = typeItems[index]?.key;
|
||||||
|
if (type) onAction?.('review:selectType', { type });
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{activeType && (
|
||||||
|
<Flex vertical gap={8} className="ai-chat-review-card__group">
|
||||||
|
<Flex justify="space-between" align="center" wrap gap={8}>
|
||||||
|
<Flex vertical gap={2}>
|
||||||
|
<Typography.Text strong>
|
||||||
|
{SECTION_TYPE_LABELS[activeType]} · 共 {group.length} 张表 / {typeTotal} 行
|
||||||
|
</Typography.Text>
|
||||||
|
<Typography.Text type="secondary">
|
||||||
|
{
|
||||||
|
GROUP_STATUS_LABELS[
|
||||||
|
groupStatus(sections, activeType, submittingKey, submittingGroup, activeType)
|
||||||
|
]
|
||||||
|
}
|
||||||
|
</Typography.Text>
|
||||||
|
</Flex>
|
||||||
|
{groupDep && (
|
||||||
|
<Alert
|
||||||
|
type="warning"
|
||||||
|
showIcon
|
||||||
|
title={
|
||||||
|
groupDep.step === -1
|
||||||
|
? `「${groupDep.title}」分表尚未生成或导入,请先确认前置步骤`
|
||||||
|
: `请先确认第 ${groupDep.step + 1} 步「${groupDep.title}」`
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{!submitted && !expired && group.length > 0 && (
|
||||||
|
<Popconfirm
|
||||||
|
title={`确认导入本组 ${group.length} 张表?`}
|
||||||
|
description={`本组共 ${typeTotal} 行,确认后将按顺序逐表导入。`}
|
||||||
|
okText="确认导入"
|
||||||
|
cancelText="取消"
|
||||||
|
disabled={!groupReady}
|
||||||
|
onConfirm={() =>
|
||||||
|
onAction?.('review:confirmGroup', {
|
||||||
|
reviewId: review.id,
|
||||||
|
type: activeType,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Button type="primary" loading={submittingGroup} disabled={!groupReady}>
|
||||||
|
{groupStatus(sections, activeType, submittingKey, submittingGroup, activeType) ===
|
||||||
|
'submitted'
|
||||||
|
? '已导入'
|
||||||
|
: `确认本组 ${group.length} 张表`}
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
<Flex vertical gap={8} className="ai-chat-review-card__sheets">
|
||||||
|
{group.map((section, index) => {
|
||||||
|
const status = sectionStatus(section);
|
||||||
|
const dep = dependencyHint(sections, sectionType(section));
|
||||||
|
const canConfirm =
|
||||||
|
!submitted &&
|
||||||
|
!expired &&
|
||||||
|
!disabled &&
|
||||||
|
!anyRunning &&
|
||||||
|
status !== 'submitted' &&
|
||||||
|
status !== 'skipped' &&
|
||||||
|
!dep;
|
||||||
|
return (
|
||||||
|
<Flex
|
||||||
|
key={section.key}
|
||||||
|
justify="space-between"
|
||||||
|
align="center"
|
||||||
|
wrap
|
||||||
|
gap={8}
|
||||||
|
className="ai-chat-review-card__sheet"
|
||||||
|
onClick={() => onAction?.('review:selectStep', { sectionKey: section.key })}
|
||||||
|
>
|
||||||
|
<Flex vertical gap={2} style={{ minWidth: 160 }}>
|
||||||
|
<Typography.Text>
|
||||||
|
{index + 1}. {section.title}
|
||||||
|
{section.sheet ? (
|
||||||
|
<Typography.Text type="secondary">({section.sheet})</Typography.Text>
|
||||||
|
) : null}
|
||||||
|
</Typography.Text>
|
||||||
|
<Typography.Text type="secondary">
|
||||||
|
{sectionCount(section)} 行 · {SECTION_STATUS_LABELS[status]}
|
||||||
|
</Typography.Text>
|
||||||
|
</Flex>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
loading={submittingKey === section.key}
|
||||||
|
disabled={!canConfirm}
|
||||||
|
onClick={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
onAction?.('review:confirmStep', {
|
||||||
|
reviewId: review.id,
|
||||||
|
sectionKey: section.key,
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{status === 'failed'
|
||||||
|
? '重试导入本步'
|
||||||
|
: status === 'submitted'
|
||||||
|
? '已导入'
|
||||||
|
: status === 'skipped'
|
||||||
|
? '已跳过'
|
||||||
|
: expired
|
||||||
|
? '已失效'
|
||||||
|
: '确认导入本步'}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Flex>
|
||||||
|
{activeSection && (
|
||||||
|
<Flex vertical gap={8} className="ai-chat-review-card__step">
|
||||||
|
{activeSection.issues.length > 0 && (
|
||||||
|
<Alert
|
||||||
|
type="warning"
|
||||||
|
showIcon
|
||||||
|
title={`${activeSection.title}:${activeSection.issues.length} 条待处理`}
|
||||||
|
description={
|
||||||
|
<ul className="ai-chat-review__issues">
|
||||||
|
{activeSection.issues.slice(0, 20).map((issue, issueIndex) => (
|
||||||
|
<li key={issueIndex}>{issue}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<SectionTable section={activeSection} />
|
||||||
|
{dependency && (
|
||||||
|
<Alert
|
||||||
|
type="warning"
|
||||||
|
showIcon
|
||||||
|
title={
|
||||||
|
dependency.step === -1
|
||||||
|
? `「${dependency.title}」分表尚未生成或导入,请先确认前置步骤`
|
||||||
|
: `请先确认第 ${dependency.step + 1} 步「${dependency.title}」`
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{activeStatus === 'failed' && (
|
||||||
|
<Alert type="error" showIcon title="本步导入失败,可重试" />
|
||||||
|
)}
|
||||||
|
{activeSection.resultSummary && activeStatus === 'submitted' && (
|
||||||
|
<Typography.Text type="secondary" className="ai-chat-review-card__step-result">
|
||||||
|
{sectionResultText(activeSection)}
|
||||||
|
</Typography.Text>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
)}
|
||||||
|
<Flex
|
||||||
|
justify="space-between"
|
||||||
|
align="center"
|
||||||
|
wrap
|
||||||
|
gap={8}
|
||||||
|
className="ai-chat-review-card__footer"
|
||||||
|
>
|
||||||
|
<Typography.Text type="secondary">
|
||||||
|
共 {allRows} 行,含 {allIssues.length} 条提示
|
||||||
|
</Typography.Text>
|
||||||
|
{!submitted && !expired && (
|
||||||
|
<Popconfirm
|
||||||
|
title={`确认导入全部 ${sections.length} 张表?`}
|
||||||
|
description={`全部共 ${allRows} 行,将按类型与依赖顺序逐表导入。`}
|
||||||
|
okText="确认导入"
|
||||||
|
cancelText="取消"
|
||||||
|
disabled={submitting || anyRunning || disabled}
|
||||||
|
onConfirm={() => onAction?.('review:submit', { reviewId: review.id })}
|
||||||
|
>
|
||||||
|
<Button type="primary" loading={submitting} disabled={disabled || anyRunning}>
|
||||||
|
全部确认并入库
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
{submitted && <Alert type="success" showIcon title="已确认导入,数据已入库" />}
|
||||||
|
{review.error && (
|
||||||
|
<Alert
|
||||||
|
type="error"
|
||||||
|
showIcon
|
||||||
|
title={review.error}
|
||||||
|
className="ai-chat-review-card__step-error"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface DynamicReviewProps {
|
||||||
|
review: AiReviewSchema;
|
||||||
|
disabled?: boolean;
|
||||||
|
messageId?: number;
|
||||||
|
onSubmit: (reviewId: string) => void | Promise<void>;
|
||||||
|
onConfirmStep?: (
|
||||||
|
messageId: number | undefined,
|
||||||
|
reviewId: string,
|
||||||
|
sectionKey: string,
|
||||||
|
) => AiReviewSchema | Promise<AiReviewSchema> | void;
|
||||||
|
onConfirmGroup?: (
|
||||||
|
messageId: number | undefined,
|
||||||
|
reviewId: string,
|
||||||
|
type: AiReviewSectionType,
|
||||||
|
) => AiReviewSchema | Promise<AiReviewSchema> | void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Batch-import review card rendered through the official A2UI renderer
|
||||||
|
* (@ant-design/x-card). Sections are grouped by business type; each sheet is
|
||||||
|
* confirmed independently, the whole type group can be confirmed together, or
|
||||||
|
* everything can be confirmed in one flow.
|
||||||
|
*/
|
||||||
|
export const DynamicReview: React.FC<DynamicReviewProps> = ({
|
||||||
|
review,
|
||||||
|
disabled,
|
||||||
|
messageId,
|
||||||
|
onSubmit,
|
||||||
|
onConfirmStep,
|
||||||
|
onConfirmGroup,
|
||||||
|
}) => {
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [submittingKey, setSubmittingKey] = useState<string | null>(null);
|
||||||
|
const [submittingGroup, setSubmittingGroup] = useState(false);
|
||||||
|
const [activeKey, setActiveKey] = useState<string | undefined>(undefined);
|
||||||
|
const [activeType, setActiveType] = useState<AiReviewSectionType | undefined>(undefined);
|
||||||
|
const activeTypeRef = useRef<AiReviewSectionType | undefined>(activeType);
|
||||||
|
activeTypeRef.current = activeType;
|
||||||
|
const [localReview, setLocalReview] = useState<AiReviewSchema>(review);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const commandsRef = useRef<XAgentCommand_v0_9[]>([]);
|
||||||
|
const [commands, setCommands] = useState<XAgentCommand_v0_9[]>([]);
|
||||||
|
const idRef = useRef<string>('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setLocalReview(review);
|
||||||
|
const types = SECTION_ORDER.filter((type) =>
|
||||||
|
review.sections.some((section) => sectionType(section) === type),
|
||||||
|
);
|
||||||
|
const preferredType =
|
||||||
|
activeTypeRef.current && types.includes(activeTypeRef.current)
|
||||||
|
? activeTypeRef.current
|
||||||
|
: types[0];
|
||||||
|
setActiveType(preferredType);
|
||||||
|
setActiveKey((current) =>
|
||||||
|
current &&
|
||||||
|
review.sections.some(
|
||||||
|
(section) => section.key === current && sectionType(section) === preferredType,
|
||||||
|
)
|
||||||
|
? current
|
||||||
|
: review.sections.find((section) => sectionType(section) === preferredType)?.key,
|
||||||
|
);
|
||||||
|
}, [review]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const sid = surfaceId(localReview.id);
|
||||||
|
if (idRef.current !== sid) {
|
||||||
|
commandsRef.current = [];
|
||||||
|
idRef.current = sid;
|
||||||
|
}
|
||||||
|
const cmds = commandsRef.current;
|
||||||
|
if (cmds.length === 0) {
|
||||||
|
cmds.push({
|
||||||
|
version: 'v0.9',
|
||||||
|
createSurface: { surfaceId: sid, catalogId: REVIEW_CATALOG_ID },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
cmds.push({
|
||||||
|
version: 'v0.9',
|
||||||
|
updateDataModel: {
|
||||||
|
surfaceId: sid,
|
||||||
|
path: '/review',
|
||||||
|
value: {
|
||||||
|
...localReview,
|
||||||
|
submitting,
|
||||||
|
activeKey,
|
||||||
|
activeType,
|
||||||
|
submittingKey,
|
||||||
|
submittingGroup,
|
||||||
|
error,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
cmds.push({
|
||||||
|
version: 'v0.9',
|
||||||
|
updateComponents: {
|
||||||
|
surfaceId: sid,
|
||||||
|
components: [
|
||||||
|
{
|
||||||
|
id: 'root',
|
||||||
|
component: 'ReviewPreview',
|
||||||
|
review: { path: '/review' },
|
||||||
|
disabled: Boolean(disabled),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
setCommands([...cmds]);
|
||||||
|
}, [
|
||||||
|
activeKey,
|
||||||
|
activeType,
|
||||||
|
disabled,
|
||||||
|
error,
|
||||||
|
localReview,
|
||||||
|
submitting,
|
||||||
|
submittingGroup,
|
||||||
|
submittingKey,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const handleSubmit = async (reviewId: string) => {
|
||||||
|
if (submitting) return;
|
||||||
|
setSubmitting(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await onSubmit(reviewId);
|
||||||
|
} catch (reason) {
|
||||||
|
setError(errorMessage(reason));
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleConfirmStep = async (reviewId: string, sectionKey: string) => {
|
||||||
|
if (submittingKey) return;
|
||||||
|
setSubmittingKey(sectionKey);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const updated = await onConfirmStep?.(messageId, reviewId, sectionKey);
|
||||||
|
if (updated) setLocalReview(updated);
|
||||||
|
} catch (reason) {
|
||||||
|
setError(errorMessage(reason));
|
||||||
|
} finally {
|
||||||
|
setSubmittingKey(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleConfirmGroup = async (reviewId: string, type: AiReviewSectionType) => {
|
||||||
|
if (submittingGroup) return;
|
||||||
|
setSubmittingGroup(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const updated = await onConfirmGroup?.(messageId, reviewId, type);
|
||||||
|
if (updated) setLocalReview(updated);
|
||||||
|
} catch (reason) {
|
||||||
|
setError(errorMessage(reason));
|
||||||
|
} finally {
|
||||||
|
setSubmittingGroup(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAction = (payload: ActionPayload) => {
|
||||||
|
const context = payload.context ?? {};
|
||||||
|
if (payload.name === 'review:submit') {
|
||||||
|
const reviewId = typeof context.reviewId === 'string' ? context.reviewId : localReview.id;
|
||||||
|
void handleSubmit(reviewId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (payload.name === 'review:selectType') {
|
||||||
|
const type = context.type as AiReviewSectionType | undefined;
|
||||||
|
if (type && SECTION_ORDER.includes(type)) {
|
||||||
|
setActiveType(type);
|
||||||
|
setActiveKey(localReview.sections.find((section) => sectionType(section) === type)?.key);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (payload.name === 'review:selectStep') {
|
||||||
|
if (typeof context.sectionKey === 'string') {
|
||||||
|
const section = localReview.sections.find((item) => item.key === context.sectionKey);
|
||||||
|
setActiveKey(context.sectionKey);
|
||||||
|
if (section) setActiveType(sectionType(section));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (payload.name === 'review:confirmStep') {
|
||||||
|
const reviewId = typeof context.reviewId === 'string' ? context.reviewId : localReview.id;
|
||||||
|
if (typeof context.sectionKey === 'string') {
|
||||||
|
void handleConfirmStep(reviewId, context.sectionKey);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (payload.name === 'review:confirmGroup') {
|
||||||
|
const reviewId = typeof context.reviewId === 'string' ? context.reviewId : localReview.id;
|
||||||
|
const type = context.type as AiReviewSectionType | undefined;
|
||||||
|
if (type && SECTION_ORDER.includes(type)) {
|
||||||
|
void handleConfirmGroup(reviewId, type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="ai-chat-review">
|
||||||
|
<XCard.Box components={{ ReviewPreview }} commands={commands} onAction={handleAction}>
|
||||||
|
<XCard.Card id={surfaceId(localReview.id)} />
|
||||||
|
</XCard.Box>
|
||||||
|
{error && <Alert type="error" showIcon title={error} className="ai-chat-review__error" />}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
49
apps/admin/src/components/AiChat/LiteCodeHighlighter.tsx
Normal file
49
apps/admin/src/components/AiChat/LiteCodeHighlighter.tsx
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import SyntaxHighlighter from 'react-syntax-highlighter/dist/esm/prism-light';
|
||||||
|
import { oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism';
|
||||||
|
import tsx from 'react-syntax-highlighter/dist/esm/languages/prism/tsx';
|
||||||
|
import typescript from 'react-syntax-highlighter/dist/esm/languages/prism/typescript';
|
||||||
|
import javascript from 'react-syntax-highlighter/dist/esm/languages/prism/javascript';
|
||||||
|
import json from 'react-syntax-highlighter/dist/esm/languages/prism/json';
|
||||||
|
import bash from 'react-syntax-highlighter/dist/esm/languages/prism/bash';
|
||||||
|
import sql from 'react-syntax-highlighter/dist/esm/languages/prism/sql';
|
||||||
|
import css from 'react-syntax-highlighter/dist/esm/languages/prism/css';
|
||||||
|
|
||||||
|
// 只注册 AI 对话里常用的语言,避免 @ant-design/x 的 CodeHighlighter
|
||||||
|
// 把所有 prism 语言都打进主包
|
||||||
|
SyntaxHighlighter.registerLanguage('tsx', tsx);
|
||||||
|
SyntaxHighlighter.registerLanguage('typescript', typescript);
|
||||||
|
SyntaxHighlighter.registerLanguage('javascript', javascript);
|
||||||
|
SyntaxHighlighter.registerLanguage('json', json);
|
||||||
|
SyntaxHighlighter.registerLanguage('bash', bash);
|
||||||
|
SyntaxHighlighter.registerLanguage('shell', bash);
|
||||||
|
SyntaxHighlighter.registerLanguage('sql', sql);
|
||||||
|
SyntaxHighlighter.registerLanguage('css', css);
|
||||||
|
|
||||||
|
const SUPPORTED_LANGUAGES = new Set([
|
||||||
|
'tsx',
|
||||||
|
'typescript',
|
||||||
|
'javascript',
|
||||||
|
'json',
|
||||||
|
'bash',
|
||||||
|
'shell',
|
||||||
|
'sql',
|
||||||
|
'css',
|
||||||
|
]);
|
||||||
|
|
||||||
|
interface LiteCodeHighlighterProps {
|
||||||
|
lang?: string;
|
||||||
|
children: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LiteCodeHighlighter({ lang, children }: LiteCodeHighlighterProps) {
|
||||||
|
const language = lang && SUPPORTED_LANGUAGES.has(lang) ? lang : undefined;
|
||||||
|
return (
|
||||||
|
<SyntaxHighlighter
|
||||||
|
language={language}
|
||||||
|
style={oneLight}
|
||||||
|
customStyle={{ margin: '12px 0', borderRadius: 8, fontSize: 13 }}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</SyntaxHighlighter>
|
||||||
|
);
|
||||||
|
}
|
||||||
48
apps/admin/src/components/AiChat/LiteMermaid.tsx
Normal file
48
apps/admin/src/components/AiChat/LiteMermaid.tsx
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
|
interface LiteMermaidProps {
|
||||||
|
children: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 轻量 Mermaid 渲染:动态 import mermaid,只有出现 mermaid 代码块时才加载
|
||||||
|
* mermaid 及其解析器/图布局依赖,避免随 AI 抽屉主包一起加载。
|
||||||
|
*/
|
||||||
|
export function LiteMermaid({ children }: LiteMermaidProps) {
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
const container = containerRef.current;
|
||||||
|
if (!container) return;
|
||||||
|
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
const mermaid = (await import('mermaid')).default;
|
||||||
|
mermaid.initialize({ startOnLoad: false, theme: 'neutral', securityLevel: 'strict' });
|
||||||
|
const { svg } = await mermaid.render(`mermaid-${crypto.randomUUID()}`, children);
|
||||||
|
if (!cancelled) {
|
||||||
|
const doc = new DOMParser().parseFromString(svg, 'image/svg+xml');
|
||||||
|
container.replaceChildren(doc.documentElement);
|
||||||
|
setError(null);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (!cancelled) {
|
||||||
|
setError(e instanceof Error ? e.message : '图表渲染失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [children]);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<pre style={{ whiteSpace: 'pre-wrap', color: '#cf1322', fontSize: 12 }}>{children}</pre>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return <div ref={containerRef} className="ai-chat-mermaid" />;
|
||||||
|
}
|
||||||
74
apps/admin/src/components/AiChat/api.integration.test.ts
Normal file
74
apps/admin/src/components/AiChat/api.integration.test.ts
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
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]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('confirmReviewStep posts to the per-section confirm endpoint', async () => {
|
||||||
|
const updated = {
|
||||||
|
id: 'review-1',
|
||||||
|
title: '批量导入',
|
||||||
|
status: 'pending',
|
||||||
|
sections: [
|
||||||
|
{ key: 'students', type: 'students', title: '学生', status: 'submitted' },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
vi.spyOn(api, 'post').mockResolvedValue({ success: true, data: updated });
|
||||||
|
|
||||||
|
await expect(aiChatApi.confirmReviewStep('review-1', 'students')).resolves.toEqual(updated);
|
||||||
|
expect(api.post).toHaveBeenCalledWith(
|
||||||
|
'/ai/chat/reviews/review-1/steps/students/confirm',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('confirmReviewGroup posts to the per-type confirm endpoint', async () => {
|
||||||
|
const updated = {
|
||||||
|
id: 'review-1',
|
||||||
|
title: '批量导入',
|
||||||
|
status: 'pending',
|
||||||
|
sections: [
|
||||||
|
{ key: 'checkins_a', type: 'checkins', title: '入住A', status: 'submitted' },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
vi.spyOn(api, 'post').mockResolvedValue({ success: true, data: updated });
|
||||||
|
|
||||||
|
await expect(aiChatApi.confirmReviewGroup('review-1', 'checkins')).resolves.toEqual(updated);
|
||||||
|
expect(api.post).toHaveBeenCalledWith(
|
||||||
|
'/ai/chat/reviews/review-1/types/checkins/confirm',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
84
apps/admin/src/components/AiChat/api.ts
Normal file
84
apps/admin/src/components/AiChat/api.ts
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
import api from '../../api';
|
||||||
|
import type {
|
||||||
|
AiApiResponse,
|
||||||
|
AiAttachment,
|
||||||
|
AiConversation,
|
||||||
|
AiMessagePage,
|
||||||
|
AiReviewSchema,
|
||||||
|
AiReviewSection,
|
||||||
|
AiReviewSectionType,
|
||||||
|
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}`),
|
||||||
|
deleteAllConversations: async () =>
|
||||||
|
(await api.delete<{ success: boolean; data: { deleted: number } }>(basePath)).data,
|
||||||
|
deleteMessage: async (conversationId: number, messageId: number) =>
|
||||||
|
(
|
||||||
|
await api.delete<AiApiResponse<{ deletedIds: number[] }>>(
|
||||||
|
`${basePath}/${conversationId}/messages/${messageId}`,
|
||||||
|
)
|
||||||
|
).data,
|
||||||
|
uploadAttachment: async (file: File): Promise<AiAttachment> => {
|
||||||
|
const form = new FormData();
|
||||||
|
form.append('file', file);
|
||||||
|
return (
|
||||||
|
await api.post<AiApiResponse<AiAttachment>>('/ai/chat/attachments', form, {
|
||||||
|
timeout: 120_000,
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
},
|
||||||
|
deleteAttachment: (id: number) => api.delete<void>(`/ai/chat/attachments/${id}`),
|
||||||
|
confirmReviewStep: async (
|
||||||
|
reviewId: string,
|
||||||
|
sectionKey: AiReviewSection['key'],
|
||||||
|
): Promise<AiReviewSchema> =>
|
||||||
|
(
|
||||||
|
await api.post<AiApiResponse<AiReviewSchema>>(
|
||||||
|
`/ai/chat/reviews/${reviewId}/steps/${sectionKey}/confirm`,
|
||||||
|
)
|
||||||
|
).data,
|
||||||
|
confirmReviewGroup: async (
|
||||||
|
reviewId: string,
|
||||||
|
type: AiReviewSectionType,
|
||||||
|
): Promise<AiReviewSchema> =>
|
||||||
|
(
|
||||||
|
await api.post<AiApiResponse<AiReviewSchema>>(
|
||||||
|
`/ai/chat/reviews/${reviewId}/types/${type}/confirm`,
|
||||||
|
)
|
||||||
|
).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`;
|
||||||
|
}
|
||||||
507
apps/admin/src/components/AiChat/bubble.integration.test.tsx
Normal file
507
apps/admin/src/components/AiChat/bubble.integration.test.tsx
Normal file
@@ -0,0 +1,507 @@
|
|||||||
|
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, conversationStatusMeta } from './AiChatDrawer';
|
||||||
|
import { AiMessageContent } from './AiMessageContent';
|
||||||
|
import { DynamicChart } from './DynamicChart';
|
||||||
|
import { DynamicForm } from './DynamicForm';
|
||||||
|
import { DynamicReview } from './DynamicReview';
|
||||||
|
import type { AiChatMessage, AiChartSchema, AiReviewSchema } 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('maps conversation run statuses to list labels', () => {
|
||||||
|
expect(conversationStatusMeta('running')).toEqual({ label: '生成中', color: 'processing' });
|
||||||
|
expect(conversationStatusMeta('done')).toEqual({ label: '已完成', color: 'success' });
|
||||||
|
expect(conversationStatusMeta('error')).toEqual({ label: '失败', color: 'error' });
|
||||||
|
expect(conversationStatusMeta('stopped')).toEqual({ label: '已停止', color: 'default' });
|
||||||
|
});
|
||||||
|
|
||||||
|
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,
|
||||||
|
contentRender: (content: AiChatMessage) => <div>{content.content}</div>,
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(container.textContent).toContain('查询今天的系统概览');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders an A2UI form and submits normalized values', async () => {
|
||||||
|
let submitted: Record<string, unknown> | null = null;
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
root?.render(
|
||||||
|
<DynamicForm
|
||||||
|
form={{
|
||||||
|
id: 'form-1',
|
||||||
|
title: '新增学生',
|
||||||
|
submitLabel: '提交创建',
|
||||||
|
fields: [
|
||||||
|
{ name: 'name', label: '姓名', type: 'input', required: true },
|
||||||
|
{ name: 'studentNo', label: '学号', type: 'input' },
|
||||||
|
],
|
||||||
|
}}
|
||||||
|
onSubmit={(values) => {
|
||||||
|
submitted = values;
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(container.textContent).toContain('新增学生');
|
||||||
|
const input = container.querySelector('input#name') as HTMLInputElement | null;
|
||||||
|
expect(input).not.toBeNull();
|
||||||
|
if (input) {
|
||||||
|
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
|
||||||
|
setter?.call(input, '张三');
|
||||||
|
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
}
|
||||||
|
const submitButton = container.querySelector('button[type="submit"]') as HTMLButtonElement | null;
|
||||||
|
expect(submitButton).not.toBeNull();
|
||||||
|
await act(async () => {
|
||||||
|
submitButton?.click();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(submitted).toEqual({ name: '张三' });
|
||||||
|
expect(container.textContent).toContain('已提交');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders an expired A2UI form as disabled without submit action', async () => {
|
||||||
|
let submitted = false;
|
||||||
|
const el = document.createElement('div');
|
||||||
|
container = el;
|
||||||
|
document.body.appendChild(el);
|
||||||
|
root = createRoot(el);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
root?.render(
|
||||||
|
<DynamicForm
|
||||||
|
form={{
|
||||||
|
id: 'form-expired',
|
||||||
|
title: '已失效的表单',
|
||||||
|
status: 'expired',
|
||||||
|
fields: [{ name: 'name', label: '姓名', type: 'input', required: true }],
|
||||||
|
}}
|
||||||
|
onSubmit={() => {
|
||||||
|
submitted = true;
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(el.textContent).toContain('已失效');
|
||||||
|
expect(el.querySelector('button[type="submit"]')).toBeNull();
|
||||||
|
await act(async () => {
|
||||||
|
const buttons = Array.from(el.querySelectorAll('button'));
|
||||||
|
buttons.forEach((button) => button.click());
|
||||||
|
});
|
||||||
|
expect(submitted).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders an A2UI review card and submits via the confirm button', async () => {
|
||||||
|
let submittedId: string | null = null;
|
||||||
|
const review: AiReviewSchema = {
|
||||||
|
id: 'review-1',
|
||||||
|
title: '开学导入',
|
||||||
|
summary: '来自报名 Excel',
|
||||||
|
status: 'pending',
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
key: 'students',
|
||||||
|
type: 'students',
|
||||||
|
title: '学生',
|
||||||
|
kind: 'table',
|
||||||
|
columns: [
|
||||||
|
{ key: 'name', title: '姓名' },
|
||||||
|
{ key: 'phone', title: '手机号' },
|
||||||
|
],
|
||||||
|
rows: [
|
||||||
|
{ name: '张三', phone: '13800138000' },
|
||||||
|
{ name: '李四', phone: '13900139000' },
|
||||||
|
],
|
||||||
|
issues: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
root?.render(
|
||||||
|
<DynamicReview
|
||||||
|
review={review}
|
||||||
|
onSubmit={(reviewId) => {
|
||||||
|
submittedId = reviewId;
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(container.textContent).toContain('开学导入');
|
||||||
|
expect(container.textContent).toContain('确认导入本步');
|
||||||
|
expect(container.textContent).toContain('全部确认并入库');
|
||||||
|
const button = Array.from(container.querySelectorAll('button')).find((item) =>
|
||||||
|
item.textContent?.includes('全部确认并入库'),
|
||||||
|
) as HTMLButtonElement | undefined;
|
||||||
|
expect(button).not.toBeNull();
|
||||||
|
await act(async () => {
|
||||||
|
button?.click();
|
||||||
|
});
|
||||||
|
const confirmButton = Array.from(document.body.querySelectorAll('button')).find(
|
||||||
|
(item) => item.textContent?.trim() === '确认导入',
|
||||||
|
) as HTMLButtonElement | undefined;
|
||||||
|
expect(confirmButton).toBeDefined();
|
||||||
|
await act(async () => {
|
||||||
|
confirmButton?.click();
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||||
|
});
|
||||||
|
expect(submittedId).toBe('review-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders grouped sheets and confirms one type group via Popconfirm', async () => {
|
||||||
|
let submittedGroup: { reviewId: string; type: string } | null = null;
|
||||||
|
const review: AiReviewSchema = {
|
||||||
|
id: 'review-2',
|
||||||
|
title: '入住分表',
|
||||||
|
status: 'pending',
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
key: 'checkins_girls_4',
|
||||||
|
type: 'checkins',
|
||||||
|
title: '四人间女',
|
||||||
|
kind: 'table',
|
||||||
|
columns: [
|
||||||
|
{ key: 'name', title: '姓名' },
|
||||||
|
{ key: 'roomNumber', title: '宿舍号' },
|
||||||
|
],
|
||||||
|
rows: [{ name: '张三', roomNumber: '4-401' }],
|
||||||
|
issues: [],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'checkins_boys_4',
|
||||||
|
type: 'checkins',
|
||||||
|
title: '四人间男',
|
||||||
|
kind: 'table',
|
||||||
|
columns: [
|
||||||
|
{ key: 'name', title: '姓名' },
|
||||||
|
{ key: 'roomNumber', title: '宿舍号' },
|
||||||
|
],
|
||||||
|
rows: [{ name: '李四', roomNumber: '4-402' }],
|
||||||
|
issues: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
root?.render(
|
||||||
|
<DynamicReview
|
||||||
|
review={review}
|
||||||
|
onSubmit={() => undefined}
|
||||||
|
onConfirmGroup={(_, reviewId, type) => {
|
||||||
|
submittedGroup = { reviewId, type };
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(container.textContent).toContain('入住记录 · 共 2 张表');
|
||||||
|
expect(container.textContent).toContain('确认本组 2 张表');
|
||||||
|
const groupButton = Array.from(container.querySelectorAll('button')).find((item) =>
|
||||||
|
item.textContent?.includes('确认本组 2 张表'),
|
||||||
|
) as HTMLButtonElement | undefined;
|
||||||
|
expect(groupButton).not.toBeNull();
|
||||||
|
await act(async () => {
|
||||||
|
groupButton?.click();
|
||||||
|
});
|
||||||
|
const confirmButton = Array.from(document.body.querySelectorAll('button')).find(
|
||||||
|
(item) => item.textContent?.trim() === '确认导入',
|
||||||
|
) as HTMLButtonElement | undefined;
|
||||||
|
expect(confirmButton).toBeDefined();
|
||||||
|
await act(async () => {
|
||||||
|
confirmButton?.click();
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||||
|
});
|
||||||
|
expect(submittedGroup).toEqual({ reviewId: 'review-2', type: 'checkins' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders legacy review sections missing type by inferring from key', async () => {
|
||||||
|
const review: AiReviewSchema = {
|
||||||
|
id: 'review-3',
|
||||||
|
title: '旧数据预览',
|
||||||
|
status: 'pending',
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
key: 'checkins_legacy',
|
||||||
|
title: '旧入住表',
|
||||||
|
kind: 'table',
|
||||||
|
columns: [{ key: 'name', title: '姓名' }],
|
||||||
|
rows: [{ name: '张三' }],
|
||||||
|
issues: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
await act(async () => {
|
||||||
|
root?.render(<DynamicReview review={review} onSubmit={() => undefined} />);
|
||||||
|
});
|
||||||
|
expect(container.textContent).toContain('入住记录 · 共 1 张表');
|
||||||
|
expect(container.textContent).toContain('旧入住表');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders an expired review card with table content but disabled actions', async () => {
|
||||||
|
let confirmed = false;
|
||||||
|
const review: AiReviewSchema = {
|
||||||
|
id: 'review-4',
|
||||||
|
title: '已被替代的预览',
|
||||||
|
status: 'expired',
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
key: 'checkins_old',
|
||||||
|
type: 'checkins',
|
||||||
|
title: '旧入住表',
|
||||||
|
kind: 'table',
|
||||||
|
columns: [{ key: 'name', title: '姓名' }],
|
||||||
|
rows: [{ name: '张三' }],
|
||||||
|
issues: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
await act(async () => {
|
||||||
|
root?.render(
|
||||||
|
<DynamicReview
|
||||||
|
review={review}
|
||||||
|
onSubmit={() => {
|
||||||
|
confirmed = true;
|
||||||
|
}}
|
||||||
|
onConfirmStep={() => {
|
||||||
|
confirmed = true;
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
expect(container.textContent).toContain('已失效');
|
||||||
|
expect(container.textContent).toContain('已被新的预览替代');
|
||||||
|
expect(container.textContent).toContain('张三');
|
||||||
|
expect(container.textContent).not.toContain('全部确认并入库');
|
||||||
|
const disabledButton = Array.from(container.querySelectorAll('button')).find(
|
||||||
|
(item) => item.textContent?.trim() === '已失效',
|
||||||
|
) as HTMLButtonElement | undefined;
|
||||||
|
expect(disabledButton).toBeDefined();
|
||||||
|
expect(disabledButton?.disabled).toBe(true);
|
||||||
|
await act(async () => {
|
||||||
|
disabledButton?.click();
|
||||||
|
});
|
||||||
|
expect(confirmed).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders an A2UI chart card with title and chart container', async () => {
|
||||||
|
const chart: AiChartSchema = {
|
||||||
|
id: 'chart-1',
|
||||||
|
title: '各班级人数',
|
||||||
|
chartType: 'bar',
|
||||||
|
columns: [
|
||||||
|
{ key: 'className', title: '班级' },
|
||||||
|
{ key: 'count', title: '人数' },
|
||||||
|
],
|
||||||
|
rows: [
|
||||||
|
{ className: '一班', count: 20 },
|
||||||
|
{ className: '二班', count: 15 },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
root?.render(<DynamicChart chart={chart} />);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(container.textContent).toContain('各班级人数');
|
||||||
|
expect(container.textContent).toContain('柱状图');
|
||||||
|
expect(container.querySelector('.ai-chat-chart-card canvas')).not.toBeNull();
|
||||||
|
expect(container.querySelector('.ai-chat-chart-card__download')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders charts persisted on an assistant message', async () => {
|
||||||
|
const message: AiChatMessage = {
|
||||||
|
role: 'assistant',
|
||||||
|
content: '这是学生性别比例图',
|
||||||
|
reasoningContent: '',
|
||||||
|
toolRuns: [],
|
||||||
|
attachments: [],
|
||||||
|
charts: [
|
||||||
|
{
|
||||||
|
id: 'chart-9',
|
||||||
|
title: '学生性别比例',
|
||||||
|
chartType: 'pie',
|
||||||
|
columns: [
|
||||||
|
{ key: 'gender', title: '性别' },
|
||||||
|
{ key: 'count', title: '人数' },
|
||||||
|
],
|
||||||
|
rows: [
|
||||||
|
{ gender: '男', count: 2 },
|
||||||
|
{ gender: '女', count: 0 },
|
||||||
|
{ gender: '未填写', count: 61 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
root?.render(<AiMessageContent message={message} />);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(container.textContent).toContain('学生性别比例');
|
||||||
|
expect(container.querySelector('.ai-chat-chart-card canvas')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders source references from assistant message metadata', async () => {
|
||||||
|
const message: AiChatMessage = {
|
||||||
|
role: 'assistant',
|
||||||
|
content: '这是基于你上传的名单整理的入住统计。',
|
||||||
|
reasoningContent: '',
|
||||||
|
toolRuns: [],
|
||||||
|
attachments: [],
|
||||||
|
metadata: {
|
||||||
|
a2uiSources: [
|
||||||
|
{ title: '26暑期文化课宿舍.xlsx', url: '/api/ai/chat/attachments/7', description: 'excel' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
root?.render(<AiMessageContent message={message} />);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(container.textContent).toContain('引用来源');
|
||||||
|
expect(container.textContent).toContain('26暑期文化课宿舍.xlsx');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders model retrying hint while waiting for the upstream retry', async () => {
|
||||||
|
const message: AiChatMessage = {
|
||||||
|
role: 'assistant',
|
||||||
|
content: '',
|
||||||
|
reasoningContent: '',
|
||||||
|
toolRuns: [],
|
||||||
|
attachments: [],
|
||||||
|
retrying: { attempt: 2, maxRetries: 3, reason: '上游返回 503' },
|
||||||
|
};
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
root?.render(<AiMessageContent message={message} />);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(container.textContent).toContain('正在自动重试(第 2 / 3 次)');
|
||||||
|
expect(container.textContent).toContain('上游返回 503');
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['area', '面积图', [{ key: 'month', title: '月份' }, { key: 'amount', title: '金额' }], [
|
||||||
|
{ month: '1月', amount: 100 },
|
||||||
|
{ month: '2月', amount: 150 },
|
||||||
|
]],
|
||||||
|
['scatter', '散点图', [
|
||||||
|
{ key: 'room', title: '宿舍' },
|
||||||
|
{ key: 'capacity', title: '容量' },
|
||||||
|
{ key: 'occupied', title: '入住人数' },
|
||||||
|
], [
|
||||||
|
{ room: '1-101', capacity: 4, occupied: 3 },
|
||||||
|
{ room: '1-102', capacity: 6, occupied: 5 },
|
||||||
|
]],
|
||||||
|
['radar', '雷达图', [
|
||||||
|
{ key: 'className', title: '班级' },
|
||||||
|
{ key: 'attendance', title: '考勤' },
|
||||||
|
{ key: 'score', title: '成绩' },
|
||||||
|
], [
|
||||||
|
{ className: '一班', attendance: 90, score: 85 },
|
||||||
|
{ className: '二班', attendance: 80, score: 92 },
|
||||||
|
]],
|
||||||
|
['gauge', '仪表盘', [
|
||||||
|
{ key: 'metric', title: '指标' },
|
||||||
|
{ key: 'value', title: '数值' },
|
||||||
|
{ key: 'max', title: '最大值' },
|
||||||
|
], [
|
||||||
|
{ metric: '入住率', value: 82, max: 100 },
|
||||||
|
]],
|
||||||
|
['funnel', '漏斗图', [
|
||||||
|
{ key: 'stage', title: '阶段' },
|
||||||
|
{ key: 'count', title: '人数' },
|
||||||
|
], [
|
||||||
|
{ stage: '咨询', count: 100 },
|
||||||
|
{ stage: '报名', count: 60 },
|
||||||
|
]],
|
||||||
|
])('渲染 %s 图表卡片', async (chartType, label, columns, rows) => {
|
||||||
|
const chart: AiChartSchema = {
|
||||||
|
id: `chart-${chartType}`,
|
||||||
|
title: `${label}示例`,
|
||||||
|
chartType: chartType as AiChartSchema['chartType'],
|
||||||
|
columns,
|
||||||
|
rows,
|
||||||
|
};
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
root?.render(<DynamicChart chart={chart} />);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(container.textContent).toContain(`${label}示例`);
|
||||||
|
expect(container.textContent).toContain(label);
|
||||||
|
expect(container.querySelector('.ai-chat-chart-card canvas')).not.toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
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',
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
|
||||||
|
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');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('restores a persisted A2UI form from message metadata', () => {
|
||||||
|
const mapped = mapHistoryMessage({
|
||||||
|
id: 5,
|
||||||
|
role: 'assistant',
|
||||||
|
content: '请填写表单',
|
||||||
|
reasoningContent: null,
|
||||||
|
status: 'completed',
|
||||||
|
errorCode: null,
|
||||||
|
createdAt: '2026-07-23T00:00:00.000Z',
|
||||||
|
metadata: {
|
||||||
|
a2uiForm: {
|
||||||
|
id: 'form-9',
|
||||||
|
title: '新增学生',
|
||||||
|
submitLabel: '提交创建',
|
||||||
|
status: 'pending',
|
||||||
|
fields: [
|
||||||
|
{ name: 'name', label: '姓名', type: 'input', required: true },
|
||||||
|
{ name: 'gender', label: '性别', type: 'select', options: [{ label: '男', value: 'male' }] },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(mapped.message.forms).toHaveLength(1);
|
||||||
|
expect(mapped.message.forms?.[0]).toMatchObject({ id: 'form-9', title: '新增学生' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('restores uiArtifacts from message metadata and derives legacy lists', () => {
|
||||||
|
const mapped = mapHistoryMessage({
|
||||||
|
id: 8,
|
||||||
|
role: 'assistant',
|
||||||
|
content: '请处理',
|
||||||
|
reasoningContent: null,
|
||||||
|
status: 'completed',
|
||||||
|
errorCode: null,
|
||||||
|
createdAt: '2026-07-23T00:00:00.000Z',
|
||||||
|
metadata: {
|
||||||
|
uiArtifacts: [
|
||||||
|
{
|
||||||
|
id: 'form-10',
|
||||||
|
type: 'form',
|
||||||
|
status: 'submitted',
|
||||||
|
messageId: 8,
|
||||||
|
conversationId: 3,
|
||||||
|
payload: {
|
||||||
|
id: 'form-10',
|
||||||
|
title: '新增学生',
|
||||||
|
status: 'submitted',
|
||||||
|
fields: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'review-10',
|
||||||
|
type: 'review',
|
||||||
|
status: 'expired',
|
||||||
|
messageId: 8,
|
||||||
|
conversationId: 3,
|
||||||
|
payload: {
|
||||||
|
id: 'review-10',
|
||||||
|
title: '旧预览',
|
||||||
|
status: 'expired',
|
||||||
|
sections: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(mapped.message.uiArtifacts).toHaveLength(2);
|
||||||
|
expect(mapped.message.forms?.[0]).toMatchObject({ id: 'form-10', status: 'submitted' });
|
||||||
|
expect(mapped.message.reviews?.[0]).toMatchObject({ id: 'review-10', status: 'expired' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('restores a persisted A2UI review from message metadata', () => {
|
||||||
|
const mapped = mapHistoryMessage({
|
||||||
|
id: 6,
|
||||||
|
role: 'assistant',
|
||||||
|
content: '请审阅导入预览',
|
||||||
|
reasoningContent: null,
|
||||||
|
status: 'completed',
|
||||||
|
errorCode: null,
|
||||||
|
createdAt: '2026-07-23T00:00:00.000Z',
|
||||||
|
metadata: {
|
||||||
|
a2uiReview: {
|
||||||
|
id: 'review-9',
|
||||||
|
title: '批量导入',
|
||||||
|
status: 'pending',
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
key: 'transfers',
|
||||||
|
type: 'transfers',
|
||||||
|
title: '换宿',
|
||||||
|
kind: 'table',
|
||||||
|
columns: [{ key: 'newRoom', title: '目标宿舍' }],
|
||||||
|
rows: [{ newRoom: '3-301' }],
|
||||||
|
issues: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(mapped.message.reviews).toHaveLength(1);
|
||||||
|
expect(mapped.message.reviews?.[0]).toMatchObject({ id: 'review-9', title: '批量导入' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('restores persisted A2UI charts from message metadata', () => {
|
||||||
|
const mapped = mapHistoryMessage({
|
||||||
|
id: 7,
|
||||||
|
role: 'assistant',
|
||||||
|
content: '这是图表',
|
||||||
|
reasoningContent: null,
|
||||||
|
status: 'completed',
|
||||||
|
errorCode: null,
|
||||||
|
createdAt: '2026-07-23T00:00:00.000Z',
|
||||||
|
metadata: {
|
||||||
|
a2uiChart: [
|
||||||
|
{
|
||||||
|
id: 'chart-9',
|
||||||
|
title: '各班级人数',
|
||||||
|
chartType: 'bar',
|
||||||
|
columns: [
|
||||||
|
{ key: 'className', title: '班级' },
|
||||||
|
{ key: 'count', title: '人数' },
|
||||||
|
],
|
||||||
|
rows: [{ className: '一班', count: 20 }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(mapped.message.charts).toHaveLength(1);
|
||||||
|
expect(mapped.message.charts?.[0]).toMatchObject({ id: 'chart-9', chartType: 'bar' });
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
91
apps/admin/src/components/AiChat/message-mappers.ts
Normal file
91
apps/admin/src/components/AiChat/message-mappers.ts
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
import type { MessageInfo } from '@ant-design/x-sdk';
|
||||||
|
import type {
|
||||||
|
AiChatMessage,
|
||||||
|
AiChatMessageStatus,
|
||||||
|
AiChartSchema,
|
||||||
|
AiArtifactSchema,
|
||||||
|
AiFormSchema,
|
||||||
|
AiMessageRecord,
|
||||||
|
AiReviewSchema,
|
||||||
|
AiToolRun,
|
||||||
|
} from './types';
|
||||||
|
import { mergeArtifactIntoMessage } from './uiArtifacts';
|
||||||
|
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function historyForms(record: AiMessageRecord): AiFormSchema[] | undefined {
|
||||||
|
const a2uiForm = record.metadata?.a2uiForm;
|
||||||
|
if (!a2uiForm || typeof a2uiForm !== 'object' || Array.isArray(a2uiForm)) return undefined;
|
||||||
|
return [a2uiForm as AiFormSchema];
|
||||||
|
}
|
||||||
|
|
||||||
|
function historyReviews(record: AiMessageRecord): AiReviewSchema[] | undefined {
|
||||||
|
const a2uiReview = record.metadata?.a2uiReview;
|
||||||
|
if (!a2uiReview || typeof a2uiReview !== 'object' || Array.isArray(a2uiReview)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return [a2uiReview as AiReviewSchema];
|
||||||
|
}
|
||||||
|
|
||||||
|
function historyCharts(record: AiMessageRecord): AiChartSchema[] | undefined {
|
||||||
|
const a2uiChart = record.metadata?.a2uiChart;
|
||||||
|
if (Array.isArray(a2uiChart)) {
|
||||||
|
return a2uiChart.filter(
|
||||||
|
(item): item is AiChartSchema =>
|
||||||
|
Boolean(item) && typeof item === 'object' && typeof (item as AiChartSchema).id === 'string',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!a2uiChart || typeof a2uiChart !== 'object') return undefined;
|
||||||
|
return [a2uiChart as AiChartSchema];
|
||||||
|
}
|
||||||
|
|
||||||
|
function historyArtifacts(record: AiMessageRecord) {
|
||||||
|
const artifacts = record.metadata?.uiArtifacts;
|
||||||
|
if (!Array.isArray(artifacts)) return undefined;
|
||||||
|
return artifacts.filter(
|
||||||
|
(item): item is AiArtifactSchema =>
|
||||||
|
Boolean(item) && typeof item === 'object' && typeof (item as AiArtifactSchema).id === 'string',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapHistoryMessage(record: AiMessageRecord): MessageInfo<AiChatMessage> {
|
||||||
|
const artifacts = historyArtifacts(record);
|
||||||
|
const baseMessage = {
|
||||||
|
id: record.id,
|
||||||
|
role: record.role,
|
||||||
|
content: record.content || '',
|
||||||
|
reasoningContent: record.reasoningContent || '',
|
||||||
|
toolRuns: (record.toolRuns || []).map(normalizeToolRun),
|
||||||
|
attachments: record.attachments ?? [],
|
||||||
|
forms: historyForms(record),
|
||||||
|
reviews: historyReviews(record),
|
||||||
|
charts: historyCharts(record),
|
||||||
|
replyToMessageId: record.replyToMessageId,
|
||||||
|
metadata: record.metadata,
|
||||||
|
error: record.status === 'failed' ? record.errorCode || 'AI 回答生成失败' : undefined,
|
||||||
|
cancelled: record.status === 'cancelled',
|
||||||
|
};
|
||||||
|
if (artifacts) {
|
||||||
|
for (const artifact of artifacts) {
|
||||||
|
mergeArtifactIntoMessage(baseMessage as AiChatMessage, artifact);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: record.id,
|
||||||
|
status: mapStatus(record),
|
||||||
|
message: baseMessage as AiChatMessage,
|
||||||
|
};
|
||||||
|
}
|
||||||
524
apps/admin/src/components/AiChat/provider.integration.test.ts
Normal file
524
apps/admin/src/components/AiChat/provider.integration.test.ts
Normal file
@@ -0,0 +1,524 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import {
|
||||||
|
authenticatedFetch,
|
||||||
|
GongxueAiChatProvider,
|
||||||
|
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 message 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,
|
||||||
|
attachments: message.attachments,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
expect(message.attachments).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
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('merges ui.form events into the assistant message by id', () => {
|
||||||
|
const form = {
|
||||||
|
id: 'form-1',
|
||||||
|
title: '新增学生',
|
||||||
|
submitLabel: '提交创建',
|
||||||
|
fields: [
|
||||||
|
{ name: 'name', label: '姓名', type: 'input', required: true },
|
||||||
|
{ name: 'gender', label: '性别', type: 'select', options: [{ label: '男', value: 'male' }] },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let message = reduceAiSseMessage(undefined, {
|
||||||
|
event: 'ui.form',
|
||||||
|
data: JSON.stringify({ messageId: 8, form }),
|
||||||
|
});
|
||||||
|
message = reduceAiSseMessage(message, {
|
||||||
|
event: 'ui.form',
|
||||||
|
data: JSON.stringify({ messageId: 8, form: { ...form, id: 'form-1' } }),
|
||||||
|
});
|
||||||
|
message = reduceAiSseMessage(message, {
|
||||||
|
event: 'ui.form',
|
||||||
|
data: JSON.stringify({
|
||||||
|
messageId: 8,
|
||||||
|
form: { id: 'form-2', title: '入住确认', fields: [] },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(message.forms).toHaveLength(2);
|
||||||
|
expect(message.forms?.[0]).toMatchObject({ id: 'form-1', title: '新增学生' });
|
||||||
|
expect(message.forms?.[1]).toMatchObject({ id: 'form-2' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('merges ui.artifact events into uiArtifacts and legacy lists by id', () => {
|
||||||
|
let message = reduceAiSseMessage(undefined, {
|
||||||
|
event: 'ui.artifact',
|
||||||
|
data: JSON.stringify({
|
||||||
|
messageId: 12,
|
||||||
|
artifact: {
|
||||||
|
id: 'form-1',
|
||||||
|
type: 'form',
|
||||||
|
status: 'pending',
|
||||||
|
messageId: 12,
|
||||||
|
conversationId: 3,
|
||||||
|
payload: { id: 'form-1', title: '新增学生', fields: [] },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
message = reduceAiSseMessage(message, {
|
||||||
|
event: 'ui.artifact',
|
||||||
|
data: JSON.stringify({
|
||||||
|
messageId: 12,
|
||||||
|
artifact: {
|
||||||
|
id: 'review-1',
|
||||||
|
type: 'review',
|
||||||
|
status: 'expired',
|
||||||
|
messageId: 12,
|
||||||
|
conversationId: 3,
|
||||||
|
payload: { id: 'review-1', title: '旧导入预览', status: 'expired', sections: [] },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(message.uiArtifacts).toHaveLength(2);
|
||||||
|
expect(message.forms?.[0]).toMatchObject({ id: 'form-1', title: '新增学生' });
|
||||||
|
expect(message.reviews?.[0]).toMatchObject({ id: 'review-1', status: 'expired' });
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
it('restores a persisted form from message.completed metadata', () => {
|
||||||
|
const message = reduceAiSseMessage(undefined, {
|
||||||
|
event: 'message.completed',
|
||||||
|
data: JSON.stringify({
|
||||||
|
message: {
|
||||||
|
id: 12,
|
||||||
|
content: '请填写表单',
|
||||||
|
status: 'completed',
|
||||||
|
metadata: {
|
||||||
|
a2uiForm: {
|
||||||
|
id: 'form-9',
|
||||||
|
title: '新增学生',
|
||||||
|
fields: [{ name: 'name', label: '姓名', type: 'input', required: true }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(message.forms).toHaveLength(1);
|
||||||
|
expect(message.forms?.[0].id).toBe('form-9');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('merges ui.review events into the assistant message and updates by id', () => {
|
||||||
|
const review = {
|
||||||
|
id: 'review-1',
|
||||||
|
title: '开学导入',
|
||||||
|
summary: '来自报名 Excel',
|
||||||
|
status: 'pending',
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
key: 'students',
|
||||||
|
type: 'students',
|
||||||
|
title: '学生',
|
||||||
|
kind: 'table',
|
||||||
|
columns: [
|
||||||
|
{ key: 'name', title: '姓名' },
|
||||||
|
{ key: 'phone', title: '手机号' },
|
||||||
|
],
|
||||||
|
rows: [{ name: '张三', phone: '13800138000' }],
|
||||||
|
issues: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let message = reduceAiSseMessage(undefined, {
|
||||||
|
event: 'ui.review',
|
||||||
|
data: JSON.stringify({ messageId: 8, review }),
|
||||||
|
});
|
||||||
|
message = reduceAiSseMessage(message, {
|
||||||
|
event: 'ui.review',
|
||||||
|
data: JSON.stringify({
|
||||||
|
messageId: 8,
|
||||||
|
review: { ...review, status: 'submitted', resultSummary: '{"students":{"created":1}}' },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(message.reviews).toHaveLength(1);
|
||||||
|
expect(message.reviews?.[0]).toMatchObject({ id: 'review-1', status: 'submitted' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows model retrying state and clears it when content starts', () => {
|
||||||
|
let message = reduceAiSseMessage(undefined, {
|
||||||
|
event: 'model.retrying',
|
||||||
|
data: JSON.stringify({
|
||||||
|
messageId: 8,
|
||||||
|
retry: { attempt: 1, maxRetries: 3, delayMs: 500, reason: '上游返回 503' },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
expect(message.retrying).toMatchObject({ attempt: 1, maxRetries: 3 });
|
||||||
|
message = reduceAiSseMessage(message, {
|
||||||
|
event: 'content.delta',
|
||||||
|
data: JSON.stringify({ messageId: 8, delta: '你好' }),
|
||||||
|
});
|
||||||
|
expect(message.retrying).toBeNull();
|
||||||
|
expect(message.content).toContain('你好');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('restores a persisted review from message.completed metadata', () => {
|
||||||
|
const message = reduceAiSseMessage(undefined, {
|
||||||
|
event: 'message.completed',
|
||||||
|
data: JSON.stringify({
|
||||||
|
message: {
|
||||||
|
id: 12,
|
||||||
|
content: '请审阅',
|
||||||
|
status: 'completed',
|
||||||
|
metadata: {
|
||||||
|
a2uiReview: {
|
||||||
|
id: 'review-9',
|
||||||
|
title: '批量导入',
|
||||||
|
status: 'pending',
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
key: 'rooms',
|
||||||
|
type: 'rooms',
|
||||||
|
title: '宿舍',
|
||||||
|
kind: 'table',
|
||||||
|
columns: [{ key: 'roomNumber', title: '房间号' }],
|
||||||
|
rows: [{ roomNumber: '3-301' }],
|
||||||
|
issues: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(message.reviews).toHaveLength(1);
|
||||||
|
expect(message.reviews?.[0]).toMatchObject({ id: 'review-9', title: '批量导入' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('merges ui.chart events into the assistant message by id', () => {
|
||||||
|
const chart = {
|
||||||
|
id: 'chart-1',
|
||||||
|
title: '各班级人数',
|
||||||
|
chartType: 'bar',
|
||||||
|
columns: [
|
||||||
|
{ key: 'className', title: '班级' },
|
||||||
|
{ key: 'count', title: '人数' },
|
||||||
|
],
|
||||||
|
rows: [
|
||||||
|
{ className: '一班', count: 20 },
|
||||||
|
{ className: '二班', count: 15 },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let message = reduceAiSseMessage(undefined, {
|
||||||
|
event: 'ui.chart',
|
||||||
|
data: JSON.stringify({ messageId: 8, chart }),
|
||||||
|
});
|
||||||
|
message = reduceAiSseMessage(message, {
|
||||||
|
event: 'ui.chart',
|
||||||
|
data: JSON.stringify({
|
||||||
|
messageId: 8,
|
||||||
|
chart: { ...chart, id: 'chart-2', title: '女生人数' },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(message.charts).toHaveLength(2);
|
||||||
|
expect(message.charts?.[0]).toMatchObject({ id: 'chart-1', chartType: 'bar' });
|
||||||
|
expect(message.charts?.[1]).toMatchObject({ id: 'chart-2' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('restores persisted charts from message.completed metadata', () => {
|
||||||
|
const message = reduceAiSseMessage(undefined, {
|
||||||
|
event: 'message.completed',
|
||||||
|
data: JSON.stringify({
|
||||||
|
message: {
|
||||||
|
id: 12,
|
||||||
|
content: '这是图表',
|
||||||
|
status: 'completed',
|
||||||
|
metadata: {
|
||||||
|
a2uiChart: [
|
||||||
|
{
|
||||||
|
id: 'chart-9',
|
||||||
|
title: '男女比例',
|
||||||
|
chartType: 'pie',
|
||||||
|
columns: [
|
||||||
|
{ key: 'name', title: '性别' },
|
||||||
|
{ key: 'value', title: '人数' },
|
||||||
|
],
|
||||||
|
rows: [
|
||||||
|
{ name: '男', value: 20 },
|
||||||
|
{ name: '女', value: 15 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(message.charts).toHaveLength(1);
|
||||||
|
expect(message.charts?.[0]).toMatchObject({ id: 'chart-9', chartType: 'pie' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rewrites review submissions to the review submit stream endpoint', async () => {
|
||||||
|
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
try {
|
||||||
|
await authenticatedFetch('http://x/api/ai/chat/conversations/3/stream', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
message: '确认批量导入',
|
||||||
|
attachmentIds: [],
|
||||||
|
skillKey: null,
|
||||||
|
clientRequestId: '6a8bc680-3cb5-4f2d-85ee-974974e0f194',
|
||||||
|
reasoningEffort: 'high',
|
||||||
|
reviewSubmission: { reviewId: 'review-1', reviewTitle: '开学导入' },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
expect(String(fetchMock.mock.calls[0][0])).toBe(
|
||||||
|
'http://x/api/ai/chat/reviews/review-1/submit/stream',
|
||||||
|
);
|
||||||
|
const body = JSON.parse(
|
||||||
|
(fetchMock.mock.calls[0][1] as RequestInit).body as string,
|
||||||
|
) as Record<string, unknown>;
|
||||||
|
expect(body).toEqual({
|
||||||
|
clientRequestId: '6a8bc680-3cb5-4f2d-85ee-974974e0f194',
|
||||||
|
reasoningEffort: 'high',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps reasoningEffort when rewriting regenerate requests', async () => {
|
||||||
|
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
try {
|
||||||
|
await authenticatedFetch('http://x/api/ai/chat/conversations/3/stream', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
message: '',
|
||||||
|
attachmentIds: [],
|
||||||
|
skillKey: null,
|
||||||
|
clientRequestId: '6a8bc680-3cb5-4f2d-85ee-974974e0f194',
|
||||||
|
reasoningEffort: 'high',
|
||||||
|
regenerateMessageId: 99,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
expect(String(fetchMock.mock.calls[0][0])).toBe(
|
||||||
|
'http://x/api/ai/chat/conversations/3/messages/99/regenerate/stream',
|
||||||
|
);
|
||||||
|
const body = JSON.parse(
|
||||||
|
(fetchMock.mock.calls[0][1] as RequestInit).body as string,
|
||||||
|
) as Record<string, unknown>;
|
||||||
|
expect(body).toEqual({
|
||||||
|
clientRequestId: '6a8bc680-3cb5-4f2d-85ee-974974e0f194',
|
||||||
|
reasoningEffort: 'high',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps reasoningEffort when rewriting form submissions', async () => {
|
||||||
|
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
try {
|
||||||
|
await authenticatedFetch('http://x/api/ai/chat/conversations/3/stream', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
message: '',
|
||||||
|
attachmentIds: [],
|
||||||
|
skillKey: null,
|
||||||
|
clientRequestId: '6a8bc680-3cb5-4f2d-85ee-974974e0f194',
|
||||||
|
reasoningEffort: 'high',
|
||||||
|
formSubmission: { formId: 'form-1', values: { name: '张三' } },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
expect(String(fetchMock.mock.calls[0][0])).toBe(
|
||||||
|
'http://x/api/ai/chat/forms/form-1/submit/stream',
|
||||||
|
);
|
||||||
|
const body = JSON.parse(
|
||||||
|
(fetchMock.mock.calls[0][1] as RequestInit).body as string,
|
||||||
|
) as Record<string, unknown>;
|
||||||
|
expect(body).toEqual({
|
||||||
|
clientRequestId: '6a8bc680-3cb5-4f2d-85ee-974974e0f194',
|
||||||
|
values: { name: '张三' },
|
||||||
|
reasoningEffort: 'high',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('routes submit-time ui.review to the original message instead of the streaming one', () => {
|
||||||
|
const provider = new GongxueAiChatProvider('http://x/api/ai/chat/conversations/3/stream');
|
||||||
|
const onExternalReview = vi.fn();
|
||||||
|
provider.onExternalReview = onExternalReview;
|
||||||
|
const review = {
|
||||||
|
id: 'review-1',
|
||||||
|
title: '批量导入',
|
||||||
|
status: 'submitted',
|
||||||
|
sections: [],
|
||||||
|
};
|
||||||
|
const origin = {
|
||||||
|
id: 13,
|
||||||
|
role: 'assistant' as const,
|
||||||
|
content: '生成中',
|
||||||
|
reasoningContent: '',
|
||||||
|
toolRuns: [],
|
||||||
|
attachments: [],
|
||||||
|
reviews: [],
|
||||||
|
};
|
||||||
|
const next = provider.transformMessage({
|
||||||
|
originMessage: origin,
|
||||||
|
chunk: { event: 'ui.review', data: JSON.stringify({ messageId: 12, review }) },
|
||||||
|
status: 'updating',
|
||||||
|
chunks: [],
|
||||||
|
responseHeaders: {} as Headers,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(onExternalReview).toHaveBeenCalledWith(12, review);
|
||||||
|
expect(next).toBe(origin);
|
||||||
|
expect(next.reviews ?? []).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('routes ui.review without an origin message to the external handler', () => {
|
||||||
|
const provider = new GongxueAiChatProvider('http://x/api/ai/chat/conversations/3/stream');
|
||||||
|
const onExternalReview = vi.fn();
|
||||||
|
provider.onExternalReview = onExternalReview;
|
||||||
|
const next = provider.transformMessage({
|
||||||
|
chunk: {
|
||||||
|
event: 'ui.review',
|
||||||
|
data: JSON.stringify({
|
||||||
|
messageId: 12,
|
||||||
|
review: { id: 'review-1', title: '批量导入', status: 'submitted', sections: [] },
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
status: 'updating',
|
||||||
|
chunks: [],
|
||||||
|
responseHeaders: {} as Headers,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(onExternalReview).toHaveBeenCalledWith(
|
||||||
|
12,
|
||||||
|
expect.objectContaining({ id: 'review-1' }),
|
||||||
|
);
|
||||||
|
expect(next.reviews ?? []).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tolerates non-JSON event data', () => {
|
||||||
|
expect(parseSsePayload({ event: 'content.delta', data: 'plain text' })).toEqual({
|
||||||
|
event: 'content.delta',
|
||||||
|
payload: { delta: 'plain text' },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
220
apps/admin/src/components/AiChat/provider.ts
Normal file
220
apps/admin/src/components/AiChat/provider.ts
Normal file
@@ -0,0 +1,220 @@
|
|||||||
|
import {
|
||||||
|
AbstractChatProvider,
|
||||||
|
XRequest,
|
||||||
|
type TransformMessage,
|
||||||
|
type XRequestOptions,
|
||||||
|
} from '@ant-design/x-sdk';
|
||||||
|
import { usePermissionStore } from '../../store/permission/permissionStore';
|
||||||
|
import { useUserStore } from '../../store/user/userStore';
|
||||||
|
import type { AiArtifactSchema, AiChatInput, AiChatMessage, AiReviewSchema, AiSseChunk } from './types';
|
||||||
|
import { emptyAssistant, parseSsePayload, reduceAiSseMessage } from './sseReducer';
|
||||||
|
|
||||||
|
export { parseSsePayload, reduceAiSseMessage };
|
||||||
|
|
||||||
|
export async function authenticatedFetch(
|
||||||
|
input: RequestInfo | URL,
|
||||||
|
init?: RequestInit,
|
||||||
|
): Promise<Response> {
|
||||||
|
const headers = new Headers(init?.headers);
|
||||||
|
const token = useUserStore.getState().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,
|
||||||
|
reasoningEffort: body.reasoningEffort,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
} else if (body.editMessageId) {
|
||||||
|
requestInput = `${String(input).replace(/\/stream$/, '')}/messages/${body.editMessageId}/edit/stream`;
|
||||||
|
requestInit = {
|
||||||
|
...init,
|
||||||
|
body: JSON.stringify({
|
||||||
|
content: body.message,
|
||||||
|
clientRequestId: body.clientRequestId,
|
||||||
|
reasoningEffort: body.reasoningEffort,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
} else if (body.formSubmission) {
|
||||||
|
requestInput = `${String(input).replace(/\/conversations\/\d+\/stream$/, '')}/forms/${body.formSubmission.formId}/submit/stream`;
|
||||||
|
requestInit = {
|
||||||
|
...init,
|
||||||
|
body: JSON.stringify({
|
||||||
|
clientRequestId: body.clientRequestId,
|
||||||
|
values: body.formSubmission.values,
|
||||||
|
reasoningEffort: body.reasoningEffort,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
} else if (body.reviewSubmission) {
|
||||||
|
requestInput = `${String(input).replace(/\/conversations\/\d+\/stream$/, '')}/reviews/${body.reviewSubmission.reviewId}/submit/stream`;
|
||||||
|
requestInit = {
|
||||||
|
...init,
|
||||||
|
body: JSON.stringify({
|
||||||
|
clientRequestId: body.clientRequestId,
|
||||||
|
reasoningEffort: body.reasoningEffort,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
const {
|
||||||
|
localAttachments: _localAttachments,
|
||||||
|
reloadMessage: _reloadMessage,
|
||||||
|
regenerateMessageId: _regenerateMessageId,
|
||||||
|
editMessageId: _editMessageId,
|
||||||
|
formSubmission: _formSubmission,
|
||||||
|
reviewSubmission: _reviewSubmission,
|
||||||
|
...payload
|
||||||
|
} = body;
|
||||||
|
requestInit = { ...init, body: JSON.stringify(payload) };
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
requestInit = init;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const response = await fetch(requestInput, { ...requestInit, headers });
|
||||||
|
if (response.status === 401) {
|
||||||
|
useUserStore.getState().logout();
|
||||||
|
usePermissionStore.getState().clearPermissions();
|
||||||
|
window.location.href = '/login';
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GongxueAiChatProvider extends AbstractChatProvider<
|
||||||
|
AiChatMessage,
|
||||||
|
AiChatInput,
|
||||||
|
AiSseChunk
|
||||||
|
> {
|
||||||
|
/** Routes events that target another (already streamed) message. */
|
||||||
|
onExternalReview?: (messageId: number, review: AiReviewSchema) => void;
|
||||||
|
onExternalArtifact?: (messageId: number, artifact: AiArtifactSchema) => void;
|
||||||
|
|
||||||
|
constructor(url: string, onSettled?: (result?: { ok: boolean; aborted?: boolean }) => void) {
|
||||||
|
super({
|
||||||
|
request: XRequest<AiChatInput, AiSseChunk, AiChatMessage>(url, {
|
||||||
|
manual: true,
|
||||||
|
fetch: authenticatedFetch,
|
||||||
|
timeout: 15_000,
|
||||||
|
streamTimeout: 1_800_000,
|
||||||
|
callbacks: {
|
||||||
|
onUpdate: () => undefined,
|
||||||
|
onSuccess: () => onSettled?.({ ok: true }),
|
||||||
|
onError: (error) =>
|
||||||
|
onSettled?.({
|
||||||
|
ok: false,
|
||||||
|
aborted: error?.name === 'AbortError',
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
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(),
|
||||||
|
reasoningEffort: requestParams.reasoningEffort,
|
||||||
|
localAttachments: requestParams.localAttachments,
|
||||||
|
formSubmission: requestParams.formSubmission,
|
||||||
|
reviewSubmission: requestParams.reviewSubmission,
|
||||||
|
regenerateMessageId: requestParams.regenerateMessageId,
|
||||||
|
editMessageId: requestParams.editMessageId,
|
||||||
|
reloadMessage: requestParams.reloadMessage,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
transformLocalMessage(requestParams: Partial<AiChatInput>): AiChatMessage | AiChatMessage[] {
|
||||||
|
if (requestParams.editMessageId) {
|
||||||
|
// 编辑消息不需要新增用户气泡,store 里已原位更新原消息。
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
if (requestParams.formSubmission) {
|
||||||
|
return {
|
||||||
|
role: 'user',
|
||||||
|
content: '',
|
||||||
|
reasoningContent: '',
|
||||||
|
toolRuns: [],
|
||||||
|
attachments: requestParams.localAttachments ?? [],
|
||||||
|
metadata: {
|
||||||
|
a2uiSubmit: {
|
||||||
|
formTitle: requestParams.formSubmission.formTitle,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (requestParams.reviewSubmission) {
|
||||||
|
return {
|
||||||
|
role: 'user',
|
||||||
|
content: '',
|
||||||
|
reasoningContent: '',
|
||||||
|
toolRuns: [],
|
||||||
|
attachments: requestParams.localAttachments ?? [],
|
||||||
|
metadata: {
|
||||||
|
a2uiReviewSubmit: {
|
||||||
|
reviewTitle: requestParams.reviewSubmission.reviewTitle,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
role: 'user',
|
||||||
|
content: requestParams.message?.trim() || '',
|
||||||
|
reasoningContent: '',
|
||||||
|
toolRuns: [],
|
||||||
|
attachments: requestParams.localAttachments ?? [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
transformMessage(info: TransformMessage<AiChatMessage, AiSseChunk>): AiChatMessage {
|
||||||
|
const { event, payload } = parseSsePayload(info.chunk);
|
||||||
|
if (
|
||||||
|
event === 'ui.artifact' &&
|
||||||
|
payload.artifact &&
|
||||||
|
typeof payload.messageId === 'number' &&
|
||||||
|
info.originMessage?.id !== payload.messageId
|
||||||
|
) {
|
||||||
|
this.onExternalArtifact?.(payload.messageId, payload.artifact);
|
||||||
|
return info.originMessage ?? emptyAssistant();
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
event === 'ui.form' &&
|
||||||
|
payload.form &&
|
||||||
|
typeof payload.messageId === 'number' &&
|
||||||
|
info.originMessage?.id !== payload.messageId
|
||||||
|
) {
|
||||||
|
this.onExternalArtifact?.(payload.messageId, {
|
||||||
|
id: payload.form.id,
|
||||||
|
type: 'form',
|
||||||
|
status: payload.form.status ?? 'pending',
|
||||||
|
messageId: payload.messageId,
|
||||||
|
payload: payload.form,
|
||||||
|
});
|
||||||
|
return info.originMessage ?? emptyAssistant();
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
event === 'ui.review' &&
|
||||||
|
payload.review &&
|
||||||
|
typeof payload.messageId === 'number' &&
|
||||||
|
info.originMessage?.id !== payload.messageId
|
||||||
|
) {
|
||||||
|
// The submitted review belongs to the original assistant message;
|
||||||
|
// do not merge it into the message currently being streamed.
|
||||||
|
this.onExternalReview?.(payload.messageId, payload.review);
|
||||||
|
return info.originMessage ?? emptyAssistant();
|
||||||
|
}
|
||||||
|
return reduceAiSseMessage(info.originMessage, info.chunk);
|
||||||
|
}
|
||||||
|
}
|
||||||
115
apps/admin/src/components/AiChat/reviewSection.ts
Normal file
115
apps/admin/src/components/AiChat/reviewSection.ts
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
import type { AiReviewSection, AiReviewSectionStatus, AiReviewSectionType } from './types';
|
||||||
|
|
||||||
|
export const SECTION_TYPE_LABELS: Record<AiReviewSectionType, string> = {
|
||||||
|
students: '学生',
|
||||||
|
rooms: '宿舍',
|
||||||
|
transfers: '换宿',
|
||||||
|
checkins: '入住记录',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const SECTION_ORDER: AiReviewSectionType[] = ['students', 'rooms', 'transfers', 'checkins'];
|
||||||
|
|
||||||
|
const SECTION_DEPENDENCIES: Record<AiReviewSectionType, AiReviewSectionType[]> = {
|
||||||
|
students: [],
|
||||||
|
rooms: [],
|
||||||
|
transfers: ['students', 'rooms'],
|
||||||
|
checkins: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
export function sectionType(section: Pick<AiReviewSection, 'key' | 'type'>): AiReviewSectionType {
|
||||||
|
if (
|
||||||
|
section.type === 'students' ||
|
||||||
|
section.type === 'rooms' ||
|
||||||
|
section.type === 'transfers' ||
|
||||||
|
section.type === 'checkins'
|
||||||
|
) {
|
||||||
|
return section.type;
|
||||||
|
}
|
||||||
|
const key = section.key as AiReviewSectionType;
|
||||||
|
if (key === 'students' || key === 'rooms' || key === 'transfers' || key === 'checkins') {
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
const prefix = SECTION_ORDER.find((type) => section.key.startsWith(`${type}_`));
|
||||||
|
return prefix ?? 'students';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sectionCount(section: AiReviewSection): number {
|
||||||
|
return section.rows.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sectionStatus(section: AiReviewSection): AiReviewSectionStatus {
|
||||||
|
return section.status ?? 'pending';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sectionResultText(section: AiReviewSection): string {
|
||||||
|
if (!section.resultSummary) return '';
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(section.resultSummary) as { message?: unknown };
|
||||||
|
if (typeof parsed.message === 'string') return parsed.message;
|
||||||
|
} catch {
|
||||||
|
// Older data may store a plain text summary.
|
||||||
|
}
|
||||||
|
return section.resultSummary;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const SECTION_STATUS_LABELS: Record<AiReviewSectionStatus, string> = {
|
||||||
|
pending: '待确认',
|
||||||
|
submitted: '已导入',
|
||||||
|
failed: '失败',
|
||||||
|
skipped: '已跳过',
|
||||||
|
};
|
||||||
|
|
||||||
|
export type GroupStatus = 'pending' | 'partial' | 'submitted' | 'failed' | 'importing';
|
||||||
|
|
||||||
|
export const GROUP_STATUS_LABELS: Record<GroupStatus, string> = {
|
||||||
|
pending: '待确认',
|
||||||
|
partial: '部分完成',
|
||||||
|
submitted: '已导入',
|
||||||
|
failed: '失败',
|
||||||
|
importing: '导入中',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function groupSections(
|
||||||
|
sections: AiReviewSection[],
|
||||||
|
type: AiReviewSectionType,
|
||||||
|
): AiReviewSection[] {
|
||||||
|
return sections.filter((section) => sectionType(section) === type);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function groupStatus(
|
||||||
|
sections: AiReviewSection[],
|
||||||
|
type: AiReviewSectionType,
|
||||||
|
submittingKey: string | null,
|
||||||
|
submittingGroup: boolean,
|
||||||
|
activeType?: AiReviewSectionType,
|
||||||
|
): GroupStatus {
|
||||||
|
const items = groupSections(sections, type);
|
||||||
|
if (items.length === 0) return 'pending';
|
||||||
|
if (
|
||||||
|
(submittingGroup && type === activeType) ||
|
||||||
|
items.some((item) => submittingKey === item.key)
|
||||||
|
) {
|
||||||
|
return 'importing';
|
||||||
|
}
|
||||||
|
if (items.some((item) => sectionStatus(item) === 'failed')) return 'failed';
|
||||||
|
if (items.every((item) => sectionStatus(item) === 'submitted')) return 'submitted';
|
||||||
|
return 'partial';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function dependencyHint(
|
||||||
|
sections: AiReviewSection[],
|
||||||
|
type: AiReviewSectionType,
|
||||||
|
): { step: number; title: string } | null {
|
||||||
|
for (const dependencyType of SECTION_DEPENDENCIES[type] ?? []) {
|
||||||
|
const matches = groupSections(sections, dependencyType);
|
||||||
|
if (matches.length === 0) {
|
||||||
|
return { step: -1, title: SECTION_TYPE_LABELS[dependencyType] };
|
||||||
|
}
|
||||||
|
for (const section of matches) {
|
||||||
|
if (sectionStatus(section) !== 'submitted') {
|
||||||
|
return { step: sections.indexOf(section), title: section.title };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
204
apps/admin/src/components/AiChat/sseReducer.ts
Normal file
204
apps/admin/src/components/AiChat/sseReducer.ts
Normal file
@@ -0,0 +1,204 @@
|
|||||||
|
import type {
|
||||||
|
AiArtifactSchema,
|
||||||
|
AiAttachment,
|
||||||
|
AiChartSchema,
|
||||||
|
AiChatMessage,
|
||||||
|
AiFormSchema,
|
||||||
|
AiModelRetryInfo,
|
||||||
|
AiReviewSchema,
|
||||||
|
AiSseChunk,
|
||||||
|
AiToolRun,
|
||||||
|
} from './types';
|
||||||
|
import { mergeArtifactIntoMessage, mergeById, mergeForms } from './uiArtifacts';
|
||||||
|
|
||||||
|
export 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;
|
||||||
|
form?: AiFormSchema;
|
||||||
|
artifact?: AiArtifactSchema;
|
||||||
|
review?: AiReviewSchema;
|
||||||
|
chart?: AiChartSchema;
|
||||||
|
wizard?: unknown;
|
||||||
|
retry?: AiModelRetryInfo;
|
||||||
|
message?:
|
||||||
|
| string
|
||||||
|
| {
|
||||||
|
id?: number;
|
||||||
|
content?: string;
|
||||||
|
reasoningContent?: string | null;
|
||||||
|
status?: string;
|
||||||
|
toolRuns?: AiToolRun[];
|
||||||
|
attachments?: AiAttachment[];
|
||||||
|
replyToMessageId?: number | null;
|
||||||
|
metadata?: Record<string, unknown> | null;
|
||||||
|
};
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function emptyAssistant(): AiChatMessage {
|
||||||
|
return {
|
||||||
|
role: 'assistant',
|
||||||
|
content: '',
|
||||||
|
reasoningContent: '',
|
||||||
|
toolRuns: [],
|
||||||
|
attachments: [],
|
||||||
|
forms: [],
|
||||||
|
uiArtifacts: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyMessagePayload(
|
||||||
|
message: AiChatMessage,
|
||||||
|
nested: AiSsePayload['message'],
|
||||||
|
payload: AiSsePayload,
|
||||||
|
): void {
|
||||||
|
if (typeof nested !== 'object' || nested === null) return;
|
||||||
|
message.forms = mergeForms(
|
||||||
|
message.forms,
|
||||||
|
(nested.metadata?.a2uiForm as AiFormSchema | undefined) ?? payload.form,
|
||||||
|
);
|
||||||
|
message.reviews = mergeById<AiReviewSchema>(
|
||||||
|
message.reviews,
|
||||||
|
(nested.metadata?.a2uiReview as AiReviewSchema | undefined) ?? payload.review,
|
||||||
|
);
|
||||||
|
message.charts = mergeById<AiChartSchema>(
|
||||||
|
message.charts,
|
||||||
|
(nested.metadata?.a2uiChart as AiChartSchema | AiChartSchema[] | undefined) ?? payload.chart,
|
||||||
|
);
|
||||||
|
const artifacts = nested.metadata?.uiArtifacts;
|
||||||
|
if (Array.isArray(artifacts)) {
|
||||||
|
for (const artifact of artifacts) {
|
||||||
|
if (artifact && typeof artifact === 'object' && typeof artifact.id === 'string') {
|
||||||
|
mergeArtifactIntoMessage(message, artifact as AiArtifactSchema);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
message.replyToMessageId = nested.replyToMessageId ?? message.replyToMessageId;
|
||||||
|
message.metadata = nested.metadata ?? message.metadata;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
applyMessagePayload(message, nested, payload);
|
||||||
|
} else if (event === 'reasoning.delta') {
|
||||||
|
message.retrying = null;
|
||||||
|
message.reasoningContent += payload.delta ?? payload.reasoningContent ?? '';
|
||||||
|
} else if (event === 'content.delta') {
|
||||||
|
message.retrying = null;
|
||||||
|
message.content += payload.delta ?? payload.content ?? '';
|
||||||
|
} else if (event === 'model.retrying' && payload.retry) {
|
||||||
|
message.retrying = payload.retry;
|
||||||
|
} else if (event === 'ui.form' && payload.form) {
|
||||||
|
message.forms = mergeForms(message.forms, payload.form);
|
||||||
|
} else if (event === 'ui.review' && payload.review) {
|
||||||
|
message.reviews = mergeById<AiReviewSchema>(message.reviews, payload.review);
|
||||||
|
} else if (event === 'ui.chart' && payload.chart) {
|
||||||
|
message.charts = mergeById<AiChartSchema>(message.charts, payload.chart);
|
||||||
|
} else if (event === 'ui.artifact' && payload.artifact) {
|
||||||
|
mergeArtifactIntoMessage(message, payload.artifact);
|
||||||
|
} else if (event === 'ui.import_wizard' && payload.wizard) {
|
||||||
|
message.metadata = { ...message.metadata, a2uiImportWizard: payload.wizard };
|
||||||
|
} 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;
|
||||||
|
applyMessagePayload(message, nested, payload);
|
||||||
|
message.retrying = null;
|
||||||
|
} else if (event === 'message.cancelled') {
|
||||||
|
message.id = payload.messageId ?? message.id;
|
||||||
|
message.cancelled = true;
|
||||||
|
message.retrying = null;
|
||||||
|
} else if (event === 'error') {
|
||||||
|
message.retrying = null;
|
||||||
|
message.error =
|
||||||
|
(typeof payload.message === 'string' ? payload.message : undefined) ||
|
||||||
|
payload.error ||
|
||||||
|
'AI 回答生成失败';
|
||||||
|
}
|
||||||
|
return message;
|
||||||
|
}
|
||||||
508
apps/admin/src/components/AiChat/style.css
Normal file
508
apps/admin/src/components/AiChat/style.css
Normal file
@@ -0,0 +1,508 @@
|
|||||||
|
.ai-chat-drawer .ant-drawer-body {
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-sender-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-sender-footer {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-sender-footer .ant-sender-switch {
|
||||||
|
margin-inline: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-layout {
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
height: 100%;
|
||||||
|
min-height: 0;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-sidebar {
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
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;
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
height: auto;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-sidebar .ant-conversations-creation {
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-conversation-label {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-conversation-label__title {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-conversation-check {
|
||||||
|
flex: none;
|
||||||
|
pointer-events: none;
|
||||||
|
margin-inline-end: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 运行中指示:使用 antd LoadingOutlined 旋转图标 */
|
||||||
|
.ai-chat-conversation-loading {
|
||||||
|
color: #007aff;
|
||||||
|
font-size: 12px;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-streaming-placeholder {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
color: #007aff;
|
||||||
|
font-size: 16px;
|
||||||
|
padding: 4px 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 失败 / 已停止:极简状态文字,不再使用 Tag */
|
||||||
|
.ai-chat-conversation-state {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
flex: none;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-conversation-state i {
|
||||||
|
width: 5px;
|
||||||
|
height: 5px;
|
||||||
|
border-radius: 50%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-conversation-state.is-error {
|
||||||
|
color: #ff4d4f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-conversation-state.is-error i {
|
||||||
|
background: #ff4d4f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-conversation-state.is-stopped {
|
||||||
|
color: #8c8c8c;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-conversation-state.is-stopped i {
|
||||||
|
background: #bfbfbf;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-sidebar__loading {
|
||||||
|
position: absolute;
|
||||||
|
inset: 68px 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-sidebar__footer {
|
||||||
|
flex: none;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 2px;
|
||||||
|
padding-top: 8px;
|
||||||
|
margin-top: 8px;
|
||||||
|
border-top: 1px solid #f0f0f0;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-sidebar__selected-count {
|
||||||
|
margin-right: auto;
|
||||||
|
padding: 0 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #8c8c8c;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-main {
|
||||||
|
display: flex;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
flex-direction: column;
|
||||||
|
min-width: 0;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-main .ai-chat-toolbar {
|
||||||
|
order: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-main .ai-chat-messages {
|
||||||
|
order: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-main .ai-chat-composer {
|
||||||
|
order: 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.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 {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-messages .ant-bubble-content {
|
||||||
|
max-width: min(100%, 680px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-messages .ant-bubble-extra {
|
||||||
|
position: absolute;
|
||||||
|
top: 2px;
|
||||||
|
right: 10px;
|
||||||
|
z-index: 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-hover-actions {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 2px;
|
||||||
|
padding: 3px;
|
||||||
|
background: rgba(255, 255, 255, 0.94);
|
||||||
|
border: 1px solid #eceef2;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.07);
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(-3px);
|
||||||
|
transition:
|
||||||
|
opacity 0.15s ease,
|
||||||
|
transform 0.15s ease;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-messages .ant-bubble:hover .ai-chat-hover-actions,
|
||||||
|
.ai-chat-hover-actions:focus-within {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0);
|
||||||
|
pointer-events: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-hover-action {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 26px;
|
||||||
|
height: 26px;
|
||||||
|
border-radius: 6px;
|
||||||
|
color: #5f6672;
|
||||||
|
font-size: 14px;
|
||||||
|
cursor: pointer;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-hover-action:hover {
|
||||||
|
background: #f0f2f5;
|
||||||
|
color: #1f2329;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-hover-action.is-danger:hover {
|
||||||
|
background: #fff1f0;
|
||||||
|
color: #cf1322;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-user-text {
|
||||||
|
max-width: 100%;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-user-content {
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-user-edit {
|
||||||
|
width: min(520px, 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-composer .ant-sender-prefix {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
align-self: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-composer .ant-sender-prefix .ant-btn {
|
||||||
|
color: #8a8f99;
|
||||||
|
}
|
||||||
|
|
||||||
|
.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%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-dynamic-form {
|
||||||
|
margin-top: 10px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border: 1px solid #e5e7eb;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: #fafafa;
|
||||||
|
max-width: 420px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-dynamic-form__desc {
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-dynamic-form .ant-form-item {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-dynamic-form__number,
|
||||||
|
.ai-chat-dynamic-form__date {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-dynamic-form__error {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-review {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-review-card {
|
||||||
|
margin-top: 10px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border: 1px solid #e5e7eb;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-review-card__title {
|
||||||
|
font-size: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-review-card__summary {
|
||||||
|
margin: 4px 0 8px !important;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-review-card__footer {
|
||||||
|
margin-top: 6px;
|
||||||
|
padding-top: 10px;
|
||||||
|
border-top: 1px dashed #e5e7eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-review-card__step {
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-review-card__group {
|
||||||
|
margin-top: 12px;
|
||||||
|
padding: 10px;
|
||||||
|
border: 1px solid #e8e8e8;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #fafafa;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-review-card__sheets {
|
||||||
|
padding: 4px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-review-card__sheet {
|
||||||
|
padding: 8px 10px;
|
||||||
|
border: 1px solid #f0f0f0;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: #fff;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: border-color 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-review-card__sheet:hover {
|
||||||
|
border-color: #1677ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-review-card__step-result {
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-review-card__step-error {
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-review__issues {
|
||||||
|
margin: 4px 0 0;
|
||||||
|
padding-left: 18px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-review__error {
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-chart {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-chart-card {
|
||||||
|
margin-top: 10px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border: 1px solid #e5e7eb;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-chat-chart-card__header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
239
apps/admin/src/components/AiChat/types.ts
Normal file
239
apps/admin/src/components/AiChat/types.ts
Normal file
@@ -0,0 +1,239 @@
|
|||||||
|
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 interface AiFormFieldOption {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AiFormField {
|
||||||
|
name: string;
|
||||||
|
label: string;
|
||||||
|
type: 'input' | 'textarea' | 'number' | 'select' | 'date';
|
||||||
|
required?: boolean;
|
||||||
|
placeholder?: string;
|
||||||
|
defaultValue?: string | number;
|
||||||
|
options?: AiFormFieldOption[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AiFormSchema {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
description?: string | null;
|
||||||
|
submitLabel?: string;
|
||||||
|
fields: AiFormField[];
|
||||||
|
status?: 'pending' | 'submitted' | 'expired';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AiReviewColumn {
|
||||||
|
key: string;
|
||||||
|
title: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AiReviewRow {
|
||||||
|
[key: string]: string | number | boolean | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AiReviewSectionStatus = 'pending' | 'submitted' | 'failed' | 'skipped';
|
||||||
|
export type AiReviewSectionType = 'students' | 'rooms' | 'transfers' | 'checkins';
|
||||||
|
|
||||||
|
export interface AiReviewSection {
|
||||||
|
key: string;
|
||||||
|
type?: AiReviewSectionType;
|
||||||
|
title: string;
|
||||||
|
kind: 'table';
|
||||||
|
sheet?: string;
|
||||||
|
columns: AiReviewColumn[];
|
||||||
|
rows: AiReviewRow[];
|
||||||
|
issues: string[];
|
||||||
|
status?: AiReviewSectionStatus;
|
||||||
|
resultSummary?: string | null;
|
||||||
|
submittedAt?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AiReviewSchema {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
summary?: string | null;
|
||||||
|
sections: AiReviewSection[];
|
||||||
|
status?: 'pending' | 'submitted' | 'expired';
|
||||||
|
resultSummary?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AiChartSchema {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
chartType: 'line' | 'bar' | 'pie' | 'area' | 'scatter' | 'radar' | 'gauge' | 'funnel';
|
||||||
|
columns: AiReviewColumn[];
|
||||||
|
rows: AiReviewRow[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AiArtifactType =
|
||||||
|
| 'form'
|
||||||
|
| 'review'
|
||||||
|
| 'chart'
|
||||||
|
| 'import_wizard';
|
||||||
|
|
||||||
|
export type AiArtifactStatus = 'rendering' | 'pending' | 'submitted' | 'expired' | 'cancelled';
|
||||||
|
|
||||||
|
export interface AiArtifactSchema<T = unknown> {
|
||||||
|
id: string;
|
||||||
|
type: AiArtifactType;
|
||||||
|
status: AiArtifactStatus;
|
||||||
|
messageId: number;
|
||||||
|
conversationId?: number;
|
||||||
|
payload: T;
|
||||||
|
createdAt?: string | null;
|
||||||
|
submittedAt?: string | null;
|
||||||
|
supersededBy?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AiImportWizard {
|
||||||
|
runId: string;
|
||||||
|
fileName: string;
|
||||||
|
sheets: Array<{
|
||||||
|
name: string;
|
||||||
|
suggestedStepKey?: AiReviewSectionType | null;
|
||||||
|
headers: string[];
|
||||||
|
rowCount: number;
|
||||||
|
}>;
|
||||||
|
steps: Array<{
|
||||||
|
stepKey: AiReviewSectionType;
|
||||||
|
label: string;
|
||||||
|
sheets: string[];
|
||||||
|
status: 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 interface AiModelRetryInfo {
|
||||||
|
attempt: number;
|
||||||
|
maxRetries: number;
|
||||||
|
delayMs?: number;
|
||||||
|
reason?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AiMessageRole = 'user' | 'assistant';
|
||||||
|
|
||||||
|
export interface AiChatMessage {
|
||||||
|
id?: number | string;
|
||||||
|
role: AiMessageRole;
|
||||||
|
content: string;
|
||||||
|
reasoningContent: string;
|
||||||
|
toolRuns: AiToolRun[];
|
||||||
|
attachments: AiAttachment[];
|
||||||
|
forms?: AiFormSchema[];
|
||||||
|
reviews?: AiReviewSchema[];
|
||||||
|
charts?: AiChartSchema[];
|
||||||
|
uiArtifacts?: AiArtifactSchema[];
|
||||||
|
replyToMessageId?: number | null;
|
||||||
|
metadata?: Record<string, unknown> | null;
|
||||||
|
retrying?: AiModelRetryInfo | 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;
|
||||||
|
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;
|
||||||
|
reasoningEffort?: string | null;
|
||||||
|
editMessageId?: number;
|
||||||
|
localAttachments?: AiAttachment[];
|
||||||
|
formSubmission?: {
|
||||||
|
formId: string;
|
||||||
|
values: Record<string, unknown>;
|
||||||
|
formTitle?: string;
|
||||||
|
};
|
||||||
|
reviewSubmission?: {
|
||||||
|
reviewId: string;
|
||||||
|
reviewTitle?: string;
|
||||||
|
};
|
||||||
|
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;
|
||||||
|
}
|
||||||
67
apps/admin/src/components/AiChat/uiArtifacts.ts
Normal file
67
apps/admin/src/components/AiChat/uiArtifacts.ts
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
import type {
|
||||||
|
AiArtifactSchema,
|
||||||
|
AiChartSchema,
|
||||||
|
AiChatMessage,
|
||||||
|
AiFormSchema,
|
||||||
|
AiReviewSchema,
|
||||||
|
} from './types';
|
||||||
|
|
||||||
|
export function mergeById<T extends { id: string }>(
|
||||||
|
current: T[] | undefined,
|
||||||
|
incoming: T | T[] | undefined,
|
||||||
|
): T[] {
|
||||||
|
const items = Array.isArray(incoming) ? incoming : incoming ? [incoming] : [];
|
||||||
|
if (!items.length) return current ?? [];
|
||||||
|
const next = [...(current ?? [])];
|
||||||
|
for (const item of items) {
|
||||||
|
if (!item || typeof item !== 'object') continue;
|
||||||
|
const index = next.findIndex((existing) => existing.id === item.id);
|
||||||
|
if (index === -1) {
|
||||||
|
next.push(item);
|
||||||
|
} else {
|
||||||
|
next[index] = item;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mergeForms(
|
||||||
|
current: AiFormSchema[] | undefined,
|
||||||
|
incoming: AiFormSchema | AiFormSchema[] | undefined,
|
||||||
|
): AiFormSchema[] {
|
||||||
|
const items = Array.isArray(incoming) ? incoming : incoming ? [incoming] : [];
|
||||||
|
if (!items.length) return current ?? [];
|
||||||
|
const next = [...(current ?? [])];
|
||||||
|
for (const item of items) {
|
||||||
|
if (item && typeof item === 'object' && !next.some((existing) => existing.id === item.id)) {
|
||||||
|
next.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
function payloadOf(artifact: AiArtifactSchema): unknown {
|
||||||
|
return artifact.payload && typeof artifact.payload === 'object' ? artifact.payload : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将统一 artifact 归入 uiArtifacts,并按类型派发到 legacy 列表。
|
||||||
|
* payload 来自服务端契约(表单/审阅/图表/预检/向导),按类型做单次断言。
|
||||||
|
*/
|
||||||
|
export function mergeArtifactIntoMessage(
|
||||||
|
message: AiChatMessage,
|
||||||
|
artifact: AiArtifactSchema,
|
||||||
|
): AiChatMessage {
|
||||||
|
message.uiArtifacts = mergeById<AiArtifactSchema>(message.uiArtifacts, artifact);
|
||||||
|
const payload = payloadOf(artifact);
|
||||||
|
if (artifact.type === 'form') {
|
||||||
|
message.forms = mergeForms(message.forms, payload as AiFormSchema);
|
||||||
|
} else if (artifact.type === 'review') {
|
||||||
|
message.reviews = mergeById<AiReviewSchema>(message.reviews, payload as AiReviewSchema);
|
||||||
|
} else if (artifact.type === 'chart') {
|
||||||
|
message.charts = mergeById<AiChartSchema>(message.charts, payload as AiChartSchema);
|
||||||
|
} else if (artifact.type === 'import_wizard') {
|
||||||
|
message.metadata = { ...message.metadata, a2uiImportWizard: payload };
|
||||||
|
}
|
||||||
|
return message;
|
||||||
|
}
|
||||||
580
apps/admin/src/components/AiChat/useAiChatMessageActions.tsx
Normal file
580
apps/admin/src/components/AiChat/useAiChatMessageActions.tsx
Normal file
@@ -0,0 +1,580 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useRef, useState, type MutableRefObject } from 'react';
|
||||||
|
import { CopyOutlined, DeleteOutlined, EditOutlined, ReloadOutlined } from '@ant-design/icons';
|
||||||
|
import type { BubbleItemType, PromptsItemType } from '@ant-design/x';
|
||||||
|
import { useXChat, type MessageInfo } from '@ant-design/x-sdk';
|
||||||
|
import { App } from 'antd';
|
||||||
|
import type { UploadFile, UploadProps } from 'antd';
|
||||||
|
import { message } from '../../ui/app-message';
|
||||||
|
import { useSettingsStore } from '../../store/settings/settingsStore';
|
||||||
|
import { aiChatApi } from './api';
|
||||||
|
import { AiMessageContent } from './AiMessageContent';
|
||||||
|
import { mapHistoryMessage } from './message-mappers';
|
||||||
|
import { GongxueAiChatProvider } from './provider';
|
||||||
|
import { mergeArtifactIntoMessage } from './uiArtifacts';
|
||||||
|
import {
|
||||||
|
emptyAssistant,
|
||||||
|
MessageHoverActions,
|
||||||
|
resolveUserMessageId,
|
||||||
|
toConversationData,
|
||||||
|
toUploadFile,
|
||||||
|
type ConversationData,
|
||||||
|
} from './AiChatDrawer.helpers';
|
||||||
|
import type {
|
||||||
|
AiAttachment,
|
||||||
|
AiChatInput,
|
||||||
|
AiChatMessage,
|
||||||
|
AiChatMessageStatus,
|
||||||
|
AiFormSchema,
|
||||||
|
AiReviewSchema,
|
||||||
|
AiReviewSection,
|
||||||
|
AiReviewSectionType,
|
||||||
|
AiSkill,
|
||||||
|
AiSseChunk,
|
||||||
|
} from './types';
|
||||||
|
|
||||||
|
interface UseAiChatMessageActionsParams {
|
||||||
|
activeConversation: ConversationData | undefined;
|
||||||
|
activeId: number | null;
|
||||||
|
provider: GongxueAiChatProvider | undefined;
|
||||||
|
requestAbortRef: MutableRefObject<Map<number, () => void>>;
|
||||||
|
markConversationRunning: (conversationId: number) => void;
|
||||||
|
addConversation: (conversation: ConversationData, placement?: 'prepend' | 'append') => boolean;
|
||||||
|
setActiveConversationKey: (key: string) => boolean;
|
||||||
|
refreshConversations: () => Promise<void>;
|
||||||
|
skills: AiSkill[];
|
||||||
|
lockedSkill: AiSkill | undefined;
|
||||||
|
setImportWizardRunId: (runId: string | null) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAiChatMessageActions({
|
||||||
|
activeConversation,
|
||||||
|
activeId,
|
||||||
|
provider,
|
||||||
|
requestAbortRef,
|
||||||
|
markConversationRunning,
|
||||||
|
addConversation,
|
||||||
|
setActiveConversationKey,
|
||||||
|
refreshConversations,
|
||||||
|
skills,
|
||||||
|
lockedSkill,
|
||||||
|
setImportWizardRunId,
|
||||||
|
}: UseAiChatMessageActionsParams) {
|
||||||
|
const { modal } = App.useApp();
|
||||||
|
const [input, setInput] = useState('');
|
||||||
|
const [attachments, setAttachments] = useState<AiAttachment[]>([]);
|
||||||
|
const [editingMessageId, setEditingMessageId] = useState<number | string | null>(null);
|
||||||
|
const deepThinking = useSettingsStore((state) => state.aiChat.deepThinking);
|
||||||
|
const setDeepThinking = useSettingsStore((state) => state.setAiChatDeepThinking);
|
||||||
|
const requestingRef = useRef(false);
|
||||||
|
const abortRef = useRef<() => void>(() => undefined);
|
||||||
|
const attachmentsRef = useRef<AiAttachment[]>([]);
|
||||||
|
const pendingDraftConversationIdRef = useRef<number | null>(null);
|
||||||
|
const messagesRef = useRef<MessageInfo<AiChatMessage>[]>([]);
|
||||||
|
|
||||||
|
const {
|
||||||
|
messages,
|
||||||
|
onRequest,
|
||||||
|
onReload,
|
||||||
|
isRequesting,
|
||||||
|
abort,
|
||||||
|
setMessage,
|
||||||
|
removeMessage,
|
||||||
|
queueRequest,
|
||||||
|
} = useXChat<AiChatMessage, AiChatMessage, AiChatInput, AiSseChunk>({
|
||||||
|
provider,
|
||||||
|
conversationKey: activeConversation?.key || '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',
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!provider) return;
|
||||||
|
provider.onExternalReview = (messageId, review) => {
|
||||||
|
setMessage(messageId, (info) => ({
|
||||||
|
message: {
|
||||||
|
...info.message,
|
||||||
|
reviews: (info.message.reviews ?? []).some((item) => item.id === review.id)
|
||||||
|
? (info.message.reviews ?? []).map((item) => (item.id === review.id ? review : item))
|
||||||
|
: [...(info.message.reviews ?? []), review],
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
provider.onExternalArtifact = (messageId, artifact) => {
|
||||||
|
setMessage(messageId, (info) => ({
|
||||||
|
message: mergeArtifactIntoMessage(info.message, artifact),
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
}, [provider, setMessage]);
|
||||||
|
|
||||||
|
requestingRef.current = isRequesting;
|
||||||
|
abortRef.current = abort;
|
||||||
|
attachmentsRef.current = attachments;
|
||||||
|
messagesRef.current = messages;
|
||||||
|
|
||||||
|
const stopRequest = useCallback(() => {
|
||||||
|
if (requestingRef.current) abortRef.current();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const requestWithStatus = useCallback(
|
||||||
|
(params: AiChatInput) => {
|
||||||
|
if (!activeId || !provider) return;
|
||||||
|
requestAbortRef.current.set(activeId, () => provider.request.abort());
|
||||||
|
markConversationRunning(activeId);
|
||||||
|
onRequest(params);
|
||||||
|
},
|
||||||
|
[activeId, markConversationRunning, onRequest, provider, requestAbortRef],
|
||||||
|
);
|
||||||
|
|
||||||
|
const reloadWithStatus = useCallback(
|
||||||
|
(messageInfo: MessageInfo<AiChatMessage>) => {
|
||||||
|
if (!activeId || !provider || typeof messageInfo.message.id !== 'number') return;
|
||||||
|
requestAbortRef.current.set(activeId, () => provider.request.abort());
|
||||||
|
markConversationRunning(activeId);
|
||||||
|
onReload(messageInfo.id, {
|
||||||
|
message: '',
|
||||||
|
attachmentIds: [],
|
||||||
|
skillKey: activeConversation?.lockedSkillKey ?? null,
|
||||||
|
clientRequestId: crypto.randomUUID(),
|
||||||
|
reasoningEffort: deepThinking ? 'high' : null,
|
||||||
|
regenerateMessageId: messageInfo.message.id,
|
||||||
|
reloadMessage: messageInfo.message,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[
|
||||||
|
activeConversation?.lockedSkillKey,
|
||||||
|
activeId,
|
||||||
|
deepThinking,
|
||||||
|
markConversationRunning,
|
||||||
|
onReload,
|
||||||
|
provider,
|
||||||
|
requestAbortRef,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
const discardPendingAttachments = useCallback(() => {
|
||||||
|
const pending = attachmentsRef.current;
|
||||||
|
attachmentsRef.current = [];
|
||||||
|
setAttachments([]);
|
||||||
|
for (const attachment of pending) {
|
||||||
|
void aiChatApi.deleteAttachment(attachment.id).catch(() => undefined);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const submit = useCallback(
|
||||||
|
(value: string) => {
|
||||||
|
const text = value.trim();
|
||||||
|
if (!text || isRequesting) return;
|
||||||
|
const submittedAttachments = attachmentsRef.current;
|
||||||
|
attachmentsRef.current = [];
|
||||||
|
setAttachments([]);
|
||||||
|
setInput('');
|
||||||
|
const params: AiChatInput = {
|
||||||
|
message: text,
|
||||||
|
attachmentIds: submittedAttachments.map((item) => item.id),
|
||||||
|
skillKey: activeConversation?.lockedSkillKey ?? null,
|
||||||
|
clientRequestId: crypto.randomUUID(),
|
||||||
|
reasoningEffort: deepThinking ? 'high' : null,
|
||||||
|
localAttachments: submittedAttachments,
|
||||||
|
};
|
||||||
|
if (activeId != null) {
|
||||||
|
requestWithStatus(params);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 草稿态:先创建 session,再发送第一条消息
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
const created = toConversationData(await aiChatApi.createConversation());
|
||||||
|
addConversation(created, 'prepend');
|
||||||
|
pendingDraftConversationIdRef.current = created.id;
|
||||||
|
markConversationRunning(created.id);
|
||||||
|
// 通过 XChat 的队列机制发送:等会话 key 切换并加载完成后再真正发出,
|
||||||
|
// 保证消息写入新会话的 store,界面能正常显示对话内容。
|
||||||
|
queueRequest(created.key, params);
|
||||||
|
setActiveConversationKey(created.key);
|
||||||
|
} catch {
|
||||||
|
message.error('创建会话失败,请重试');
|
||||||
|
attachmentsRef.current = submittedAttachments;
|
||||||
|
setAttachments(submittedAttachments);
|
||||||
|
setInput(text);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
},
|
||||||
|
[
|
||||||
|
activeConversation?.lockedSkillKey,
|
||||||
|
activeId,
|
||||||
|
addConversation,
|
||||||
|
deepThinking,
|
||||||
|
isRequesting,
|
||||||
|
markConversationRunning,
|
||||||
|
queueRequest,
|
||||||
|
requestWithStatus,
|
||||||
|
setActiveConversationKey,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
// 草稿 session 创建完成、provider 就绪后注册中止句柄
|
||||||
|
useEffect(() => {
|
||||||
|
if (activeId == null || !provider) return;
|
||||||
|
if (activeId !== pendingDraftConversationIdRef.current) return;
|
||||||
|
pendingDraftConversationIdRef.current = null;
|
||||||
|
requestAbortRef.current.set(activeId, () => provider.request.abort());
|
||||||
|
}, [activeId, provider, requestAbortRef]);
|
||||||
|
|
||||||
|
const reloadMessage = useCallback(
|
||||||
|
(messageInfo: MessageInfo<AiChatMessage>) => {
|
||||||
|
reloadWithStatus(messageInfo);
|
||||||
|
},
|
||||||
|
[reloadWithStatus],
|
||||||
|
);
|
||||||
|
|
||||||
|
const copyMessage = useCallback((message: AiChatMessage) => {
|
||||||
|
if (!message.content) return;
|
||||||
|
void navigator.clipboard.writeText(message.content);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const confirmDeleteMessage = useCallback(
|
||||||
|
(messageInfo: MessageInfo<AiChatMessage>) => {
|
||||||
|
if (!activeId || isRequesting) return;
|
||||||
|
const messageId = resolveUserMessageId(messageInfo, messagesRef.current);
|
||||||
|
if (messageId == null) return;
|
||||||
|
const scopeLabel =
|
||||||
|
messageInfo.message.role === 'user' ? '这条消息及其 AI 回答' : '这条 AI 回答';
|
||||||
|
modal.confirm({
|
||||||
|
title: '删除消息',
|
||||||
|
content: `将删除${scopeLabel},此操作不可恢复。`,
|
||||||
|
okText: '删除',
|
||||||
|
okButtonProps: { danger: true },
|
||||||
|
cancelText: '取消',
|
||||||
|
onOk: async () => {
|
||||||
|
try {
|
||||||
|
const result = await aiChatApi.deleteMessage(activeId, messageId);
|
||||||
|
const storeIds = new Map<number, number | string>();
|
||||||
|
for (const item of messagesRef.current) {
|
||||||
|
if (typeof item.message.id === 'number') {
|
||||||
|
storeIds.set(item.message.id, item.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 当前会话内新发送的用户消息没有服务端 ID,但可映射到本地 msg_N key
|
||||||
|
storeIds.set(messageId, messageInfo.id);
|
||||||
|
for (const id of result.deletedIds) removeMessage(storeIds.get(id) ?? id);
|
||||||
|
void refreshConversations();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('删除消息失败', error);
|
||||||
|
message.error('删除消息失败');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[activeId, isRequesting, refreshConversations, removeMessage, modal],
|
||||||
|
);
|
||||||
|
|
||||||
|
const confirmEditMessage = useCallback(
|
||||||
|
(messageInfo: MessageInfo<AiChatMessage>, value: string) => {
|
||||||
|
if (!activeId) return;
|
||||||
|
const content = value.trim();
|
||||||
|
if (!content) {
|
||||||
|
message.warning('消息内容不能为空');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const messageId = resolveUserMessageId(messageInfo, messagesRef.current);
|
||||||
|
if (messageId == null) {
|
||||||
|
message.warning('消息尚未同步,请稍后重试');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setEditingMessageId(null);
|
||||||
|
if (content === messageInfo.message.content) return;
|
||||||
|
|
||||||
|
setMessage(messageInfo.id, (info) => ({
|
||||||
|
message: {
|
||||||
|
...info.message,
|
||||||
|
content,
|
||||||
|
metadata: { ...info.message.metadata, edited: true },
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
const index = messagesRef.current.findIndex((item) => item.id === messageInfo.id);
|
||||||
|
if (index >= 0) {
|
||||||
|
for (const item of messagesRef.current.slice(index + 1)) removeMessage(item.id);
|
||||||
|
}
|
||||||
|
requestWithStatus({
|
||||||
|
message: content,
|
||||||
|
attachmentIds: [],
|
||||||
|
skillKey: activeConversation?.lockedSkillKey ?? null,
|
||||||
|
clientRequestId: crypto.randomUUID(),
|
||||||
|
reasoningEffort: deepThinking ? 'high' : null,
|
||||||
|
editMessageId: messageId,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[
|
||||||
|
activeConversation?.lockedSkillKey,
|
||||||
|
activeId,
|
||||||
|
deepThinking,
|
||||||
|
removeMessage,
|
||||||
|
requestWithStatus,
|
||||||
|
setMessage,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
const submitForm = useCallback(
|
||||||
|
(form: AiFormSchema, values: Record<string, unknown>) => {
|
||||||
|
if (!activeId || isRequesting) return;
|
||||||
|
requestWithStatus({
|
||||||
|
message: '表单提交',
|
||||||
|
attachmentIds: [],
|
||||||
|
skillKey: activeConversation?.lockedSkillKey ?? null,
|
||||||
|
clientRequestId: crypto.randomUUID(),
|
||||||
|
reasoningEffort: deepThinking ? 'high' : null,
|
||||||
|
formSubmission: { formId: form.id, values, formTitle: form.title },
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[activeConversation?.lockedSkillKey, activeId, deepThinking, isRequesting, requestWithStatus],
|
||||||
|
);
|
||||||
|
|
||||||
|
const submitReview = useCallback(
|
||||||
|
(reviewId: string, reviewTitle?: string) => {
|
||||||
|
if (!activeId || isRequesting) return;
|
||||||
|
requestWithStatus({
|
||||||
|
message: '确认批量导入',
|
||||||
|
attachmentIds: [],
|
||||||
|
skillKey: activeConversation?.lockedSkillKey ?? null,
|
||||||
|
clientRequestId: crypto.randomUUID(),
|
||||||
|
reasoningEffort: deepThinking ? 'high' : null,
|
||||||
|
reviewSubmission: { reviewId, reviewTitle },
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[activeConversation?.lockedSkillKey, activeId, deepThinking, isRequesting, requestWithStatus],
|
||||||
|
);
|
||||||
|
|
||||||
|
const confirmReviewStep = useCallback(
|
||||||
|
async (
|
||||||
|
messageId: number | undefined,
|
||||||
|
reviewId: string,
|
||||||
|
sectionKey: AiReviewSection['key'],
|
||||||
|
): Promise<AiReviewSchema> => {
|
||||||
|
const updated = await aiChatApi.confirmReviewStep(reviewId, sectionKey);
|
||||||
|
const apply = (review: AiReviewSchema) => {
|
||||||
|
if (provider?.onExternalReview && typeof messageId === 'number') {
|
||||||
|
provider.onExternalReview(messageId, review);
|
||||||
|
} else if (typeof messageId === 'number') {
|
||||||
|
setMessage(messageId, (info) => {
|
||||||
|
const reviews = info.message.reviews ?? [];
|
||||||
|
const exists = reviews.some((item) => item.id === review.id);
|
||||||
|
return {
|
||||||
|
message: {
|
||||||
|
...info.message,
|
||||||
|
reviews: exists
|
||||||
|
? reviews.map((item) => (item.id === review.id ? review : item))
|
||||||
|
: [...reviews, review],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
apply(updated);
|
||||||
|
return updated;
|
||||||
|
},
|
||||||
|
[provider, setMessage],
|
||||||
|
);
|
||||||
|
|
||||||
|
const confirmReviewGroup = useCallback(
|
||||||
|
async (
|
||||||
|
messageId: number | undefined,
|
||||||
|
reviewId: string,
|
||||||
|
type: AiReviewSectionType,
|
||||||
|
): Promise<AiReviewSchema> => {
|
||||||
|
const updated = await aiChatApi.confirmReviewGroup(reviewId, type);
|
||||||
|
if (provider?.onExternalReview && typeof messageId === 'number') {
|
||||||
|
provider.onExternalReview(messageId, updated);
|
||||||
|
} else if (typeof messageId === 'number') {
|
||||||
|
setMessage(messageId, (info) => {
|
||||||
|
const reviews = info.message.reviews ?? [];
|
||||||
|
const exists = reviews.some((item) => item.id === updated.id);
|
||||||
|
return {
|
||||||
|
message: {
|
||||||
|
...info.message,
|
||||||
|
reviews: exists
|
||||||
|
? reviews.map((item) => (item.id === updated.id ? updated : item))
|
||||||
|
: [...reviews, updated],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return updated;
|
||||||
|
},
|
||||||
|
[provider, 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,
|
||||||
|
extra:
|
||||||
|
info.status !== 'loading' && info.status !== 'updating' && !isRequesting ? (
|
||||||
|
info.message.role === 'user' ? (
|
||||||
|
editingMessageId === info.id ? undefined : (
|
||||||
|
<MessageHoverActions
|
||||||
|
items={[
|
||||||
|
{
|
||||||
|
key: 'copy',
|
||||||
|
title: '复制',
|
||||||
|
icon: <CopyOutlined />,
|
||||||
|
onClick: () => copyMessage(info.message),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'edit',
|
||||||
|
title: '编辑',
|
||||||
|
icon: <EditOutlined />,
|
||||||
|
onClick: () => setEditingMessageId(info.id),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'delete',
|
||||||
|
title: '删除',
|
||||||
|
icon: <DeleteOutlined />,
|
||||||
|
danger: true,
|
||||||
|
onClick: () => void confirmDeleteMessage(info),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
) : (
|
||||||
|
<MessageHoverActions
|
||||||
|
items={[
|
||||||
|
{
|
||||||
|
key: 'copy',
|
||||||
|
title: '复制',
|
||||||
|
icon: <CopyOutlined />,
|
||||||
|
onClick: () => copyMessage(info.message),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'reload',
|
||||||
|
title: '重新生成',
|
||||||
|
icon: <ReloadOutlined />,
|
||||||
|
onClick: () => reloadMessage(info),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
) : undefined,
|
||||||
|
contentRender: (content: AiChatMessage) => (
|
||||||
|
<AiMessageContent
|
||||||
|
message={content}
|
||||||
|
status={info.status as AiChatMessageStatus}
|
||||||
|
editing={content.role === 'user' && editingMessageId === info.id}
|
||||||
|
onEditConfirm={
|
||||||
|
content.role === 'user' ? (value) => confirmEditMessage(info, value) : undefined
|
||||||
|
}
|
||||||
|
onEditCancel={content.role === 'user' ? () => setEditingMessageId(null) : undefined}
|
||||||
|
onSubmitForm={submitForm}
|
||||||
|
onSubmitReview={submitReview}
|
||||||
|
onConfirmReviewStep={confirmReviewStep}
|
||||||
|
onConfirmReviewGroup={confirmReviewGroup}
|
||||||
|
onOpenImportWizard={setImportWizardRunId}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
})),
|
||||||
|
[
|
||||||
|
copyMessage,
|
||||||
|
confirmDeleteMessage,
|
||||||
|
confirmEditMessage,
|
||||||
|
confirmReviewGroup,
|
||||||
|
confirmReviewStep,
|
||||||
|
editingMessageId,
|
||||||
|
isRequesting,
|
||||||
|
messages,
|
||||||
|
reloadMessage,
|
||||||
|
setImportWizardRunId,
|
||||||
|
submitForm,
|
||||||
|
submitReview,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
input,
|
||||||
|
setInput,
|
||||||
|
attachments,
|
||||||
|
setAttachments,
|
||||||
|
editingMessageId,
|
||||||
|
setEditingMessageId,
|
||||||
|
deepThinking,
|
||||||
|
setDeepThinking,
|
||||||
|
isRequesting,
|
||||||
|
messages,
|
||||||
|
stopRequest,
|
||||||
|
submit,
|
||||||
|
reloadMessage,
|
||||||
|
copyMessage,
|
||||||
|
confirmDeleteMessage,
|
||||||
|
confirmEditMessage,
|
||||||
|
submitForm,
|
||||||
|
submitReview,
|
||||||
|
confirmReviewStep,
|
||||||
|
confirmReviewGroup,
|
||||||
|
customUpload,
|
||||||
|
removeAttachment,
|
||||||
|
discardPendingAttachments,
|
||||||
|
uploadItems,
|
||||||
|
promptItems,
|
||||||
|
bubbleItems,
|
||||||
|
};
|
||||||
|
}
|
||||||
24
apps/admin/src/components/BrandLogo.tsx
Normal file
24
apps/admin/src/components/BrandLogo.tsx
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { ReadOutlined } from '@ant-design/icons';
|
||||||
|
|
||||||
|
const BRAND_COLOR = '#7e14ff';
|
||||||
|
|
||||||
|
/** 全局品牌标识:登录页 / 侧边栏 / 页头统一使用 */
|
||||||
|
export function BrandLogo({ size = 32 }: { size?: number }) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
display: 'inline-flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
width: size,
|
||||||
|
height: size,
|
||||||
|
borderRadius: 8,
|
||||||
|
background: BRAND_COLOR,
|
||||||
|
color: '#fff',
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ReadOutlined style={{ fontSize: size * 0.55 }} />
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,18 +1,16 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Navigate } from 'react-router-dom';
|
import { Navigate } from 'react-router';
|
||||||
import { Result } from 'antd';
|
import { Result, Spin } from 'antd';
|
||||||
import { usePermission } from '../hooks/usePermission';
|
import { usePermission } from '../hooks/usePermission';
|
||||||
import { findRoleAwareLandingPath } from '../auth/menu-policy';
|
import { findRoleAwareLandingPath } from '../auth/menu-policy';
|
||||||
|
import { useUserStore } from '../store/user/userStore';
|
||||||
|
|
||||||
const DefaultRoute: React.FC = () => {
|
const DefaultRoute: React.FC = () => {
|
||||||
const { permissions } = usePermission();
|
const { permissions, permissionsReady } = usePermission();
|
||||||
const roles = (() => {
|
const roles = useUserStore((state) => state.user?.roles ?? []);
|
||||||
try {
|
if (!permissionsReady) {
|
||||||
return JSON.parse(localStorage.getItem('user') || '{}').roles || [];
|
return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;
|
||||||
} catch {
|
}
|
||||||
return [];
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
const firstPath = findRoleAwareLandingPath(roles, permissions);
|
const firstPath = findRoleAwareLandingPath(roles, permissions);
|
||||||
if (firstPath) return <Navigate to={firstPath} replace />;
|
if (firstPath) return <Navigate to={firstPath} replace />;
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1,11 +1,22 @@
|
|||||||
import React, { useEffect, useRef } from 'react';
|
import React, { useEffect, useRef } from 'react';
|
||||||
import * as echarts from 'echarts/core';
|
import * as echarts from 'echarts/core';
|
||||||
|
import type { EChartsType } from 'echarts/core';
|
||||||
export type EChartsOption = Record<string, unknown>;
|
export type EChartsOption = Record<string, unknown>;
|
||||||
import { BarChart, CustomChart, LineChart, PieChart } from 'echarts/charts';
|
import {
|
||||||
|
BarChart,
|
||||||
|
CustomChart,
|
||||||
|
FunnelChart,
|
||||||
|
GaugeChart,
|
||||||
|
LineChart,
|
||||||
|
PieChart,
|
||||||
|
RadarChart,
|
||||||
|
ScatterChart,
|
||||||
|
} from 'echarts/charts';
|
||||||
import {
|
import {
|
||||||
DataZoomComponent,
|
DataZoomComponent,
|
||||||
GridComponent,
|
GridComponent,
|
||||||
LegendComponent,
|
LegendComponent,
|
||||||
|
RadarComponent,
|
||||||
TooltipComponent,
|
TooltipComponent,
|
||||||
VisualMapComponent,
|
VisualMapComponent,
|
||||||
} from 'echarts/components';
|
} from 'echarts/components';
|
||||||
@@ -14,11 +25,16 @@ import { CanvasRenderer } from 'echarts/renderers';
|
|||||||
echarts.use([
|
echarts.use([
|
||||||
BarChart,
|
BarChart,
|
||||||
CustomChart,
|
CustomChart,
|
||||||
|
FunnelChart,
|
||||||
|
GaugeChart,
|
||||||
LineChart,
|
LineChart,
|
||||||
PieChart,
|
PieChart,
|
||||||
|
RadarChart,
|
||||||
|
ScatterChart,
|
||||||
DataZoomComponent,
|
DataZoomComponent,
|
||||||
GridComponent,
|
GridComponent,
|
||||||
LegendComponent,
|
LegendComponent,
|
||||||
|
RadarComponent,
|
||||||
TooltipComponent,
|
TooltipComponent,
|
||||||
VisualMapComponent,
|
VisualMapComponent,
|
||||||
CanvasRenderer,
|
CanvasRenderer,
|
||||||
@@ -28,15 +44,22 @@ interface EChartsProps {
|
|||||||
option: EChartsOption;
|
option: EChartsOption;
|
||||||
style?: React.CSSProperties;
|
style?: React.CSSProperties;
|
||||||
className?: string;
|
className?: string;
|
||||||
|
/** 图表实例就绪回调(用于导出图片等场景) */
|
||||||
|
onReady?: (chart: EChartsType) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ECharts: React.FC<EChartsProps> = ({ option, style, className }) => {
|
const ECharts: React.FC<EChartsProps> = ({ option, style, className, onReady }) => {
|
||||||
const containerRef = useRef<HTMLDivElement>(null);
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const optionRef = useRef(option);
|
||||||
|
optionRef.current = option;
|
||||||
|
const onReadyRef = useRef(onReady);
|
||||||
|
onReadyRef.current = onReady;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!containerRef.current) return;
|
if (!containerRef.current) return;
|
||||||
const chart = echarts.init(containerRef.current);
|
const chart = echarts.init(containerRef.current);
|
||||||
chart.setOption(option);
|
chart.setOption(optionRef.current);
|
||||||
|
onReadyRef.current?.(chart);
|
||||||
const observer = new ResizeObserver(() => chart.resize());
|
const observer = new ResizeObserver(() => chart.resize());
|
||||||
observer.observe(containerRef.current);
|
observer.observe(containerRef.current);
|
||||||
return () => {
|
return () => {
|
||||||
|
|||||||
@@ -13,6 +13,21 @@ let root: ReturnType<typeof createRoot> | null = null;
|
|||||||
|
|
||||||
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
|
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 () => {
|
afterEach(async () => {
|
||||||
if (root) {
|
if (root) {
|
||||||
await act(async () => root?.unmount());
|
await act(async () => root?.unmount());
|
||||||
@@ -51,6 +66,70 @@ describe('editable cell value mapping', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('editable cell interactions', () => {
|
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 () => {
|
it('saves a single-select value immediately when an option is clicked', async () => {
|
||||||
const onSave = vi.fn(async () => undefined);
|
const onSave = vi.fn(async () => undefined);
|
||||||
container = document.createElement('div');
|
container = document.createElement('div');
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { DatePicker, Input, InputNumber, Select, Spin, Tooltip } from 'antd';
|
import { DatePicker, Input, InputNumber, Select, Spin, Tooltip } from 'antd';
|
||||||
import type { Dayjs } from 'dayjs';
|
import dayjs, { type Dayjs } from 'dayjs';
|
||||||
import dayjs from 'dayjs';
|
import equal from 'fast-deep-equal';
|
||||||
import { usePermission } from '../../hooks/usePermission';
|
import { usePermission } from '../../hooks/usePermission';
|
||||||
import { message } from '../../ui/app-message';
|
import { message } from '../../ui/app-message';
|
||||||
import './style.css';
|
import './style.css';
|
||||||
|
import { getErrorMessage } from '../../utils/error';
|
||||||
|
|
||||||
export type EditableCellEditor =
|
export type EditableCellEditor =
|
||||||
| 'text'
|
| 'text'
|
||||||
@@ -66,7 +67,7 @@ export function serializeEditableValue(value: unknown, editor: EditableCellEdito
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function editableValuesEqual(left: unknown, right: unknown) {
|
export function editableValuesEqual(left: unknown, right: unknown) {
|
||||||
return JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
|
return equal(left ?? null, right ?? null);
|
||||||
}
|
}
|
||||||
|
|
||||||
function isEditorOverlay(target: EventTarget | null) {
|
function isEditorOverlay(target: EventTarget | null) {
|
||||||
@@ -94,6 +95,8 @@ const EditableCell = <Value,>({
|
|||||||
const { hasPermission } = usePermission();
|
const { hasPermission } = usePermission();
|
||||||
const idRef = useRef(crypto.randomUUID());
|
const idRef = useRef(crypto.randomUUID());
|
||||||
const rootRef = useRef<HTMLDivElement>(null);
|
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 [editing, setEditing] = useState(false);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [draft, setDraft] = useState<unknown>(() =>
|
const [draft, setDraft] = useState<unknown>(() =>
|
||||||
@@ -110,43 +113,40 @@ const EditableCell = <Value,>({
|
|||||||
[editor, formatValue, value],
|
[editor, formatValue, value],
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!editing) {
|
|
||||||
setDraft(normalizeEditableValue(formatValue ? formatValue(value) : value, editor));
|
|
||||||
}
|
|
||||||
}, [editing, editor, formatValue, value]);
|
|
||||||
|
|
||||||
const cancel = useCallback(() => {
|
const cancel = useCallback(() => {
|
||||||
setDraft(normalizeEditableValue(formatValue ? formatValue(value) : value, editor));
|
setDraft(normalizeEditableValue(formatValue ? formatValue(value) : value, editor));
|
||||||
if (activeCell?.id === idRef.current) activeCell = null;
|
if (activeCell?.id === idRef.current) activeCell = null;
|
||||||
setEditing(false);
|
setEditing(false);
|
||||||
}, [editor, formatValue, value]);
|
}, [editor, formatValue, value]);
|
||||||
|
|
||||||
const saveValue = useCallback(async (nextDraft: unknown) => {
|
const saveValue = useCallback(
|
||||||
if (saving) return false;
|
async (nextDraft: unknown) => {
|
||||||
const serialized = serializeEditableValue(nextDraft, editor);
|
if (saving) return false;
|
||||||
if (required && (serialized === '' || serialized === undefined || serialized === null)) {
|
const serialized = serializeEditableValue(nextDraft, editor);
|
||||||
message.error('该字段不能为空');
|
if (required && (serialized === '' || serialized === undefined || serialized === null)) {
|
||||||
return false;
|
message.error('该字段不能为空');
|
||||||
}
|
return false;
|
||||||
if (editableValuesEqual(serialized, original)) {
|
}
|
||||||
if (activeCell?.id === idRef.current) activeCell = null;
|
if (editableValuesEqual(serialized, original)) {
|
||||||
setEditing(false);
|
if (activeCell?.id === idRef.current) activeCell = null;
|
||||||
return true;
|
setEditing(false);
|
||||||
}
|
return true;
|
||||||
setSaving(true);
|
}
|
||||||
try {
|
setSaving(true);
|
||||||
await onSave(parseValue ? parseValue(serialized) : (serialized as Value));
|
try {
|
||||||
if (activeCell?.id === idRef.current) activeCell = null;
|
await onSave(parseValue ? parseValue(serialized) : (serialized as Value));
|
||||||
setEditing(false);
|
if (activeCell?.id === idRef.current) activeCell = null;
|
||||||
return true;
|
setEditing(false);
|
||||||
} catch (error) {
|
return true;
|
||||||
message.error((error as { message?: string })?.message || '保存失败');
|
} catch (error) {
|
||||||
return false;
|
message.error(getErrorMessage(error, '保存失败'));
|
||||||
} finally {
|
return false;
|
||||||
setSaving(false);
|
} finally {
|
||||||
}
|
setSaving(false);
|
||||||
}, [editor, onSave, original, parseValue, required, saving]);
|
}
|
||||||
|
},
|
||||||
|
[editor, onSave, original, parseValue, required, saving],
|
||||||
|
);
|
||||||
|
|
||||||
const save = useCallback(() => saveValue(draft), [draft, saveValue]);
|
const save = useCallback(() => saveValue(draft), [draft, saveValue]);
|
||||||
|
|
||||||
@@ -197,9 +197,43 @@ const EditableCell = <Value,>({
|
|||||||
if (!saved) return;
|
if (!saved) return;
|
||||||
}
|
}
|
||||||
activeCell = { id: idRef.current, save };
|
activeCell = { id: idRef.current, save };
|
||||||
|
setDraft(normalizeEditableValue(formatValue ? formatValue(value) : value, editor));
|
||||||
setEditing(true);
|
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) => {
|
const onKeyDown = async (event: React.KeyboardEvent) => {
|
||||||
if (event.key === 'Escape') {
|
if (event.key === 'Escape') {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -245,10 +279,10 @@ const EditableCell = <Value,>({
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
} else if (editor === 'date') {
|
} else if (editor === 'date') {
|
||||||
control = <DatePicker {...commonProps} format="YYYY-MM-DD" />;
|
control = <DatePicker {...commonProps} format="YYYY-MM-DD" open />;
|
||||||
} else if (editor === 'date-range') {
|
} else if (editor === 'date-range') {
|
||||||
const { placeholder: _placeholder, ...rangeProps } = commonProps;
|
const { placeholder: _placeholder, ...rangeProps } = commonProps;
|
||||||
control = <DatePicker.RangePicker {...rangeProps} format="YYYY-MM-DD" />;
|
control = <DatePicker.RangePicker {...rangeProps} format="YYYY-MM-DD" open />;
|
||||||
} else if (editor === 'number' || editor === 'money') {
|
} else if (editor === 'number' || editor === 'money') {
|
||||||
control = (
|
control = (
|
||||||
<InputNumber {...commonProps} min={min} max={max} precision={editor === 'money' ? 2 : 0} />
|
<InputNumber {...commonProps} min={min} max={max} precision={editor === 'money' ? 2 : 0} />
|
||||||
@@ -264,11 +298,17 @@ const EditableCell = <Value,>({
|
|||||||
ref={rootRef}
|
ref={rootRef}
|
||||||
className={`editable-cell${enabled ? ' editable-cell--enabled' : ''}${editing ? ' editable-cell--editing' : ''}`}
|
className={`editable-cell${enabled ? ' editable-cell--enabled' : ''}${editing ? ' editable-cell--editing' : ''}`}
|
||||||
onDoubleClick={() => void beginEdit()}
|
onDoubleClick={() => void beginEdit()}
|
||||||
|
onPointerDown={onPointerDown}
|
||||||
|
onPointerUp={onPointerUp}
|
||||||
|
onPointerCancel={() => {
|
||||||
|
touchStartRef.current = null;
|
||||||
|
lastTouchTapRef.current = null;
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{editing ? (
|
{editing ? (
|
||||||
<Spin spinning={saving}>{control}</Spin>
|
<Spin spinning={saving}>{control}</Spin>
|
||||||
) : (
|
) : (
|
||||||
<Tooltip title={enabled ? '双击编辑' : undefined}>{children}</Tooltip>
|
<Tooltip title={enabled ? '双击编辑,触屏双击编辑' : undefined}>{children}</Tooltip>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
|
|
||||||
.editable-cell--enabled {
|
.editable-cell--enabled {
|
||||||
cursor: cell;
|
cursor: cell;
|
||||||
|
touch-action: manipulation;
|
||||||
padding: 4px 6px;
|
padding: 4px 6px;
|
||||||
margin: -4px -6px;
|
margin: -4px -6px;
|
||||||
border: 1px solid transparent;
|
border: 1px solid transparent;
|
||||||
|
|||||||
616
apps/admin/src/components/ImportWizard/ImportWizardModal.tsx
Normal file
616
apps/admin/src/components/ImportWizard/ImportWizardModal.tsx
Normal file
@@ -0,0 +1,616 @@
|
|||||||
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import {
|
||||||
|
CheckCircleOutlined,
|
||||||
|
CloseCircleOutlined,
|
||||||
|
DownloadOutlined,
|
||||||
|
InboxOutlined,
|
||||||
|
ReloadOutlined,
|
||||||
|
StepForwardOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
Button,
|
||||||
|
Checkbox,
|
||||||
|
Descriptions,
|
||||||
|
Flex,
|
||||||
|
Modal,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Spin,
|
||||||
|
Steps,
|
||||||
|
Table,
|
||||||
|
Tag,
|
||||||
|
Tooltip,
|
||||||
|
Typography,
|
||||||
|
Upload,
|
||||||
|
} from 'antd';
|
||||||
|
import type { UploadProps } from 'antd';
|
||||||
|
import { message } from '../../ui/app-message';
|
||||||
|
import { useUserStore } from '../../store/user/userStore';
|
||||||
|
import {
|
||||||
|
commitImportStep,
|
||||||
|
createImportRun,
|
||||||
|
getImportRun,
|
||||||
|
importErrorReportUrl,
|
||||||
|
previewImportStep,
|
||||||
|
} from '../../api/imports';
|
||||||
|
import {
|
||||||
|
STEP_FIELDS,
|
||||||
|
type ImportPreviewResult,
|
||||||
|
type ImportReceipt,
|
||||||
|
type ImportRunDetail,
|
||||||
|
type ImportStepKey,
|
||||||
|
} from './types';
|
||||||
|
|
||||||
|
interface ImportWizardModalProps {
|
||||||
|
open: boolean;
|
||||||
|
/** AI 对话生成的导入任务;为空时向导从上传文件开始。 */
|
||||||
|
runId?: string | null;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
type RowAction = 'create' | 'update' | 'skip';
|
||||||
|
|
||||||
|
const ACTION_META: Record<RowAction, { label: string; color: string }> = {
|
||||||
|
create: { label: '新建', color: 'blue' },
|
||||||
|
update: { label: '更新', color: 'orange' },
|
||||||
|
skip: { label: '跳过', color: 'default' },
|
||||||
|
};
|
||||||
|
|
||||||
|
function guessMapping(stepKey: ImportStepKey, headers: string[]): Record<string, string> {
|
||||||
|
const mapping: Record<string, string> = {};
|
||||||
|
for (const field of STEP_FIELDS[stepKey]) {
|
||||||
|
const hit = headers.find((header) => {
|
||||||
|
const normalizedHeader = header.replace(/[\s()()]/g, '').toLowerCase();
|
||||||
|
const normalizedLabel = field.label.replace(/[\s()()]/g, '').toLowerCase();
|
||||||
|
return (
|
||||||
|
normalizedHeader === normalizedLabel ||
|
||||||
|
normalizedHeader.includes(normalizedLabel) ||
|
||||||
|
normalizedLabel.includes(normalizedHeader)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
if (hit) mapping[field.key] = hit;
|
||||||
|
}
|
||||||
|
return mapping;
|
||||||
|
}
|
||||||
|
|
||||||
|
function keyInfo(stepKey: ImportStepKey, row: ImportPreviewResult['rows'][number]): string {
|
||||||
|
const fields = row.fields;
|
||||||
|
if (stepKey === 'students') {
|
||||||
|
return [fields.name, fields.studentNo, fields.phone].filter(Boolean).join(' / ');
|
||||||
|
}
|
||||||
|
if (stepKey === 'rooms') {
|
||||||
|
return [fields.roomNumber, fields.building, fields.floor].filter(Boolean).join(' / ');
|
||||||
|
}
|
||||||
|
if (stepKey === 'checkins') {
|
||||||
|
return [fields.name, fields.studentNo, fields.phone, fields.roomNumber, fields.checkInDate]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' / ');
|
||||||
|
}
|
||||||
|
return [fields.studentNo, fields.phone, fields.oldRoom, fields.newRoom, fields.transferDate]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' / ');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadErrorReport(runId: string, stepKey?: ImportStepKey): Promise<void> {
|
||||||
|
const token = useUserStore.getState().token;
|
||||||
|
const response = await fetch(importErrorReportUrl(runId, stepKey), {
|
||||||
|
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error('错误报告下载失败');
|
||||||
|
const blob = await response.blob();
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const anchor = document.createElement('a');
|
||||||
|
anchor.href = url;
|
||||||
|
anchor.download = `导入错误报告-${runId.slice(0, 8)}.csv`;
|
||||||
|
anchor.click();
|
||||||
|
window.setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ImportWizardModal: React.FC<ImportWizardModalProps> = ({
|
||||||
|
open,
|
||||||
|
runId: initialRunId,
|
||||||
|
onClose,
|
||||||
|
}) => {
|
||||||
|
const [run, setRun] = useState<ImportRunDetail | null>(null);
|
||||||
|
const [loadingRun, setLoadingRun] = useState(false);
|
||||||
|
const [uploading, setUploading] = useState(false);
|
||||||
|
const [activeStepKey, setActiveStepKey] = useState<ImportStepKey | null>(null);
|
||||||
|
const [sheetSelection, setSheetSelection] = useState<Record<string, string[]>>({});
|
||||||
|
const [mappingDraft, setMappingDraft] = useState<Record<string, Record<string, string>>>({});
|
||||||
|
const [previewByStep, setPreviewByStep] = useState<Record<string, ImportPreviewResult>>({});
|
||||||
|
const [previewLoading, setPreviewLoading] = useState(false);
|
||||||
|
const [onlyErrors, setOnlyErrors] = useState(false);
|
||||||
|
const [rowActions, setRowActions] = useState<Record<number, RowAction>>({});
|
||||||
|
const [commitLoading, setCommitLoading] = useState(false);
|
||||||
|
const [receipt, setReceipt] = useState<ImportReceipt | null>(null);
|
||||||
|
const [reportDownloading, setReportDownloading] = useState(false);
|
||||||
|
const requestSeq = useRef(0);
|
||||||
|
|
||||||
|
const loadRun = useCallback(async (runId: string) => {
|
||||||
|
const seq = ++requestSeq.current;
|
||||||
|
setLoadingRun(true);
|
||||||
|
try {
|
||||||
|
const detail = await getImportRun(runId);
|
||||||
|
if (seq !== requestSeq.current) return;
|
||||||
|
setRun(detail);
|
||||||
|
const selections: Record<string, string[]> = {};
|
||||||
|
const mappings: Record<string, Record<string, string>> = {};
|
||||||
|
const sheetHeaders = new Map(detail.sheets.map((sheet) => [sheet.name, sheet.headers]));
|
||||||
|
for (const step of detail.steps) {
|
||||||
|
selections[step.stepKey] = step.sheets;
|
||||||
|
const mapped =
|
||||||
|
step.mapping && Object.keys(step.mapping).length > 0
|
||||||
|
? step.mapping
|
||||||
|
: guessMapping(step.stepKey, sheetHeaders.get(step.sheets[0] ?? '') ?? []);
|
||||||
|
mappings[step.stepKey] = mapped;
|
||||||
|
}
|
||||||
|
setSheetSelection(selections);
|
||||||
|
setMappingDraft(mappings);
|
||||||
|
setPreviewByStep({});
|
||||||
|
setRowActions({});
|
||||||
|
setReceipt(null);
|
||||||
|
const firstActive =
|
||||||
|
detail.steps.find((step) => step.status !== 'skipped' && step.status !== 'committed') ??
|
||||||
|
detail.steps.find((step) => step.status !== 'skipped');
|
||||||
|
setActiveStepKey(firstActive?.stepKey ?? detail.currentStepKey);
|
||||||
|
} catch (error) {
|
||||||
|
if (seq !== requestSeq.current) return;
|
||||||
|
message.error(error instanceof Error ? error.message : '导入任务加载失败');
|
||||||
|
setRun(null);
|
||||||
|
} finally {
|
||||||
|
if (seq === requestSeq.current) setLoadingRun(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || !initialRunId) return;
|
||||||
|
void loadRun(initialRunId);
|
||||||
|
}, [open, initialRunId, loadRun]);
|
||||||
|
|
||||||
|
const activeStep = useMemo(
|
||||||
|
() => run?.steps.find((step) => step.stepKey === activeStepKey) ?? null,
|
||||||
|
[run, activeStepKey],
|
||||||
|
);
|
||||||
|
const preview = activeStepKey ? (previewByStep[activeStepKey] ?? null) : null;
|
||||||
|
|
||||||
|
const sheetOptions = useMemo(() => (run?.sheets ?? []).map((sheet) => sheet.name), [run]);
|
||||||
|
const headerOptions = useMemo(() => {
|
||||||
|
if (!run || !activeStepKey) return [];
|
||||||
|
const names = sheetSelection[activeStepKey] ?? [];
|
||||||
|
const headers = new Set<string>();
|
||||||
|
for (const sheet of run.sheets) {
|
||||||
|
if (names.includes(sheet.name)) sheet.headers.forEach((header) => headers.add(header));
|
||||||
|
}
|
||||||
|
return [...headers];
|
||||||
|
}, [run, activeStepKey, sheetSelection]);
|
||||||
|
|
||||||
|
const handleUpload: UploadProps['customRequest'] = async (options) => {
|
||||||
|
const file = options.file as File;
|
||||||
|
setUploading(true);
|
||||||
|
try {
|
||||||
|
const detail = await createImportRun(file, { source: 'manual' });
|
||||||
|
await loadRun(detail.id);
|
||||||
|
message.success(`已识别 ${detail.sheets.length} 个工作表`);
|
||||||
|
} catch (error) {
|
||||||
|
message.error(error instanceof Error ? error.message : '文件上传失败');
|
||||||
|
} finally {
|
||||||
|
setUploading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePreview = async () => {
|
||||||
|
if (!run || !activeStepKey || !activeStep) return;
|
||||||
|
const mapping = mappingDraft[activeStepKey] ?? {};
|
||||||
|
const required = STEP_FIELDS[activeStepKey]
|
||||||
|
.filter((field) => field.required)
|
||||||
|
.map((field) => field.key);
|
||||||
|
const missing = required.filter((key) => !mapping[key]);
|
||||||
|
if (missing.length > 0) {
|
||||||
|
message.warning('请先完成必填列的映射');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setPreviewLoading(true);
|
||||||
|
try {
|
||||||
|
const result = await previewImportStep(run.id, activeStepKey, {
|
||||||
|
sheets: sheetSelection[activeStepKey] ?? [],
|
||||||
|
mapping,
|
||||||
|
});
|
||||||
|
setPreviewByStep((prev) => ({ ...prev, [activeStepKey]: result }));
|
||||||
|
setRowActions({});
|
||||||
|
} catch (error) {
|
||||||
|
message.error(error instanceof Error ? error.message : '预览失败');
|
||||||
|
} finally {
|
||||||
|
setPreviewLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCommit = async () => {
|
||||||
|
if (!run || !activeStepKey || !preview) return;
|
||||||
|
setCommitLoading(true);
|
||||||
|
try {
|
||||||
|
const decisions = preview.rows
|
||||||
|
.filter((row) => row.status === 'valid')
|
||||||
|
.map((row) => ({ rowId: row.id, action: rowActions[row.id] ?? row.action ?? 'create' }));
|
||||||
|
const result = await commitImportStep(run.id, activeStepKey, decisions);
|
||||||
|
setReceipt(result);
|
||||||
|
const refreshed = await getImportRun(run.id);
|
||||||
|
setRun(refreshed);
|
||||||
|
setPreviewByStep({});
|
||||||
|
setRowActions({});
|
||||||
|
if (result.nextStepKey) {
|
||||||
|
setActiveStepKey(result.nextStepKey);
|
||||||
|
const nextStep = refreshed.steps.find((step) => step.stepKey === result.nextStepKey);
|
||||||
|
setMappingDraft((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[result.nextStepKey as string]: nextStep?.mapping ?? {},
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
message.error(error instanceof Error ? error.message : '提交失败');
|
||||||
|
} finally {
|
||||||
|
setCommitLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleReupload = async (file: File) => {
|
||||||
|
if (!run || !activeStepKey) return;
|
||||||
|
setUploading(true);
|
||||||
|
try {
|
||||||
|
const detail = await createImportRun(file, {
|
||||||
|
source: 'manual',
|
||||||
|
stages: [{ stepKey: activeStepKey, sheets: sheetSelection[activeStepKey] ?? [] }],
|
||||||
|
mapping: { [activeStepKey]: mappingDraft[activeStepKey] ?? {} },
|
||||||
|
});
|
||||||
|
await loadRun(detail.id);
|
||||||
|
message.success('已重新上传,并保留原列映射');
|
||||||
|
} catch (error) {
|
||||||
|
message.error(error instanceof Error ? error.message : '重新上传失败');
|
||||||
|
} finally {
|
||||||
|
setUploading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const previewRows = useMemo(() => {
|
||||||
|
if (!preview) return [];
|
||||||
|
return onlyErrors ? preview.rows.filter((row) => row.status === 'error') : preview.rows;
|
||||||
|
}, [preview, onlyErrors]);
|
||||||
|
|
||||||
|
const columns = useMemo(() => {
|
||||||
|
if (!activeStepKey) return [];
|
||||||
|
return [
|
||||||
|
{ title: '行号', dataIndex: 'rowNumber', width: 70 },
|
||||||
|
{ title: '工作表', dataIndex: 'sheetName', width: 120, ellipsis: true },
|
||||||
|
{
|
||||||
|
title: '数据',
|
||||||
|
key: 'data',
|
||||||
|
render: (_: unknown, row: ImportPreviewResult['rows'][number]) =>
|
||||||
|
keyInfo(activeStepKey, row),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '判定',
|
||||||
|
key: 'action',
|
||||||
|
width: 90,
|
||||||
|
render: (_: unknown, row: ImportPreviewResult['rows'][number]) => {
|
||||||
|
const action = rowActions[row.id] ?? row.action;
|
||||||
|
return action ? (
|
||||||
|
<Tag color={ACTION_META[action].color}>{ACTION_META[action].label}</Tag>
|
||||||
|
) : (
|
||||||
|
'-'
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
key: 'status',
|
||||||
|
width: 90,
|
||||||
|
render: (_: unknown, row: ImportPreviewResult['rows'][number]) =>
|
||||||
|
row.status === 'error' ? (
|
||||||
|
<Tag color="red" icon={<CloseCircleOutlined />}>
|
||||||
|
错误
|
||||||
|
</Tag>
|
||||||
|
) : (
|
||||||
|
<Tag color="green" icon={<CheckCircleOutlined />}>
|
||||||
|
有效
|
||||||
|
</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '错误信息',
|
||||||
|
key: 'errors',
|
||||||
|
ellipsis: true,
|
||||||
|
render: (_: unknown, row: ImportPreviewResult['rows'][number]) =>
|
||||||
|
row.errors.length > 0 ? (
|
||||||
|
<Tooltip title={row.errors.join(';')}>
|
||||||
|
<Typography.Text type="danger" style={{ maxWidth: 320 }}>
|
||||||
|
{row.errors.join(';')}
|
||||||
|
</Typography.Text>
|
||||||
|
</Tooltip>
|
||||||
|
) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '处理方式',
|
||||||
|
key: 'decision',
|
||||||
|
width: 120,
|
||||||
|
render: (_: unknown, row: ImportPreviewResult['rows'][number]) =>
|
||||||
|
row.status === 'valid' ? (
|
||||||
|
<Select
|
||||||
|
size="small"
|
||||||
|
value={rowActions[row.id] ?? row.action ?? 'create'}
|
||||||
|
options={
|
||||||
|
row.action === 'update'
|
||||||
|
? [
|
||||||
|
{ value: 'update', label: '更新' },
|
||||||
|
{ value: 'skip', label: '跳过' },
|
||||||
|
]
|
||||||
|
: [
|
||||||
|
{ value: 'create', label: '新建' },
|
||||||
|
{ value: 'skip', label: '跳过' },
|
||||||
|
]
|
||||||
|
}
|
||||||
|
onChange={(value: RowAction) =>
|
||||||
|
setRowActions((prev) => ({ ...prev, [row.id]: value }))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
) : null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}, [activeStepKey, rowActions]);
|
||||||
|
|
||||||
|
const stageItems = useMemo(
|
||||||
|
() =>
|
||||||
|
(run?.steps ?? [])
|
||||||
|
.filter((step) => step.status !== 'skipped')
|
||||||
|
.map((step) => ({
|
||||||
|
key: step.stepKey,
|
||||||
|
title: step.label,
|
||||||
|
status:
|
||||||
|
step.status === 'committed'
|
||||||
|
? ('finish' as const)
|
||||||
|
: step.stepKey === activeStepKey
|
||||||
|
? ('process' as const)
|
||||||
|
: ('wait' as const),
|
||||||
|
})),
|
||||||
|
[run, activeStepKey],
|
||||||
|
);
|
||||||
|
|
||||||
|
const allCommitted = run?.status === 'committed';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
onCancel={onClose}
|
||||||
|
footer={null}
|
||||||
|
width={980}
|
||||||
|
title="Excel 批量导入向导"
|
||||||
|
destroyOnHidden={false}
|
||||||
|
>
|
||||||
|
{!run && !loadingRun ? (
|
||||||
|
<Space orientation="vertical" size={16} style={{ width: '100%' }}>
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
title="上传 Excel 后,系统会自动识别工作表并按业务依赖分阶段(学生/宿舍 → 入住/换宿)。每一阶段都需要先预览、再确认,确认后才会写入数据库。"
|
||||||
|
/>
|
||||||
|
<Upload.Dragger
|
||||||
|
accept=".xlsx,.csv"
|
||||||
|
maxCount={1}
|
||||||
|
showUploadList={false}
|
||||||
|
disabled={uploading}
|
||||||
|
customRequest={handleUpload}
|
||||||
|
>
|
||||||
|
<p className="ant-upload-drag-icon">
|
||||||
|
<InboxOutlined />
|
||||||
|
</p>
|
||||||
|
<p className="ant-upload-text">点击或拖拽 .xlsx / .csv 文件到此区域</p>
|
||||||
|
<p className="ant-upload-hint">单文件不超过 10MB;.xls 请先另存为 .xlsx</p>
|
||||||
|
</Upload.Dragger>
|
||||||
|
</Space>
|
||||||
|
) : (
|
||||||
|
<Space orientation="vertical" size={16} style={{ width: '100%' }}>
|
||||||
|
<Flex justify="space-between" align="center" wrap gap={8}>
|
||||||
|
<Space wrap>
|
||||||
|
<Typography.Text strong>{run?.fileName}</Typography.Text>
|
||||||
|
<Tag color={allCommitted ? 'success' : 'processing'}>
|
||||||
|
{allCommitted ? '已完成' : '待处理'}
|
||||||
|
</Tag>
|
||||||
|
<Tag>当前阶段:{activeStep?.label ?? '—'}</Tag>
|
||||||
|
</Space>
|
||||||
|
<Space>
|
||||||
|
{preview && preview.summary.error > 0 && (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
icon={<DownloadOutlined />}
|
||||||
|
loading={reportDownloading}
|
||||||
|
onClick={() => {
|
||||||
|
setReportDownloading(true);
|
||||||
|
void downloadErrorReport(run?.id ?? '', activeStepKey ?? undefined)
|
||||||
|
.then(() => message.success('错误报告已下载'))
|
||||||
|
.catch((error: unknown) =>
|
||||||
|
message.error(error instanceof Error ? error.message : '下载失败'),
|
||||||
|
)
|
||||||
|
.finally(() => setReportDownloading(false));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
下载错误报告
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button size="small" onClick={onClose}>
|
||||||
|
关闭
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
<Steps
|
||||||
|
size="small"
|
||||||
|
items={stageItems}
|
||||||
|
onChange={(index) => {
|
||||||
|
const step = (run?.steps ?? []).filter((s) => s.status !== 'skipped')[index];
|
||||||
|
if (step) setActiveStepKey(step.stepKey);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{loadingRun ? (
|
||||||
|
<Flex justify="center" style={{ padding: 32 }}>
|
||||||
|
<Spin description="正在加载导入任务..." />
|
||||||
|
</Flex>
|
||||||
|
) : allCommitted ? (
|
||||||
|
<Space orientation="vertical" size={12} style={{ width: '100%' }}>
|
||||||
|
<Alert type="success" showIcon title="全部阶段已提交完成" />
|
||||||
|
<Descriptions
|
||||||
|
bordered
|
||||||
|
size="small"
|
||||||
|
column={2}
|
||||||
|
items={(run?.steps ?? [])
|
||||||
|
.filter((step) => step.status !== 'skipped')
|
||||||
|
.map((step) => ({
|
||||||
|
key: step.stepKey,
|
||||||
|
label: step.label,
|
||||||
|
children: step.summary
|
||||||
|
? `新建 ${step.summary.create} / 更新 ${step.summary.update} / 跳过 ${step.summary.skip} / 失败 ${step.summary.error}`
|
||||||
|
: '—',
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
<Button type="primary" onClick={onClose}>
|
||||||
|
完成
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
) : activeStep ? (
|
||||||
|
<Space orientation="vertical" size={12} style={{ width: '100%' }}>
|
||||||
|
{receipt && (
|
||||||
|
<Alert
|
||||||
|
type={receipt.status === 'committed' ? 'success' : 'warning'}
|
||||||
|
showIcon
|
||||||
|
title={receipt.message}
|
||||||
|
closable
|
||||||
|
onClose={() => setReceipt(null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{activeStep.status === 'committed' ? (
|
||||||
|
<Alert
|
||||||
|
type="success"
|
||||||
|
showIcon
|
||||||
|
title={`「${activeStep.label}」已提交`}
|
||||||
|
description={
|
||||||
|
activeStep.summary
|
||||||
|
? `新建 ${activeStep.summary.create} / 更新 ${activeStep.summary.update} / 跳过 ${activeStep.summary.skip} / 失败 ${activeStep.summary.error}`
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
) : preview ? (
|
||||||
|
<Space orientation="vertical" size={12} style={{ width: '100%' }}>
|
||||||
|
<Flex wrap gap={12} align="center">
|
||||||
|
<Space size={4}>
|
||||||
|
<Tag color="blue">共 {preview.summary.total} 行</Tag>
|
||||||
|
<Tag color="green">有效 {preview.summary.valid}</Tag>
|
||||||
|
<Tag color="red">错误 {preview.summary.error}</Tag>
|
||||||
|
<Tag color="blue">新建 {preview.summary.create}</Tag>
|
||||||
|
<Tag color="orange">更新 {preview.summary.update}</Tag>
|
||||||
|
</Space>
|
||||||
|
<Checkbox
|
||||||
|
checked={onlyErrors}
|
||||||
|
onChange={(e) => setOnlyErrors(e.target.checked)}
|
||||||
|
>
|
||||||
|
只看错误行
|
||||||
|
</Checkbox>
|
||||||
|
</Flex>
|
||||||
|
<Table
|
||||||
|
size="small"
|
||||||
|
rowKey="id"
|
||||||
|
columns={columns}
|
||||||
|
dataSource={previewRows}
|
||||||
|
pagination={{ pageSize: 10, showSizeChanger: false }}
|
||||||
|
scroll={{ x: 900 }}
|
||||||
|
/>
|
||||||
|
<Flex justify="end" gap={8}>
|
||||||
|
<Upload
|
||||||
|
accept=".xlsx,.csv"
|
||||||
|
showUploadList={false}
|
||||||
|
beforeUpload={(file) => {
|
||||||
|
void handleReupload(file);
|
||||||
|
return false;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Button icon={<ReloadOutlined />} loading={uploading}>
|
||||||
|
重新上传并保留映射
|
||||||
|
</Button>
|
||||||
|
</Upload>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
icon={<StepForwardOutlined />}
|
||||||
|
loading={commitLoading}
|
||||||
|
onClick={() => void handleCommit()}
|
||||||
|
>
|
||||||
|
确认提交本阶段
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Space>
|
||||||
|
) : (
|
||||||
|
<Space orientation="vertical" size={12} style={{ width: '100%' }}>
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
title={`配置「${activeStep.label}」阶段`}
|
||||||
|
description="选择该阶段使用的工作表,并确认列映射;系统会按“学号/手机号/宿舍号”自动区分新建或更新。"
|
||||||
|
/>
|
||||||
|
<Flex align="center" gap={8}>
|
||||||
|
<Typography.Text style={{ width: 120 }}>工作表</Typography.Text>
|
||||||
|
<Select
|
||||||
|
mode="multiple"
|
||||||
|
style={{ minWidth: 320, flex: 1 }}
|
||||||
|
placeholder="选择该阶段的工作表"
|
||||||
|
value={sheetSelection[activeStepKey ?? ''] ?? []}
|
||||||
|
options={sheetOptions.map((name) => ({ value: name, label: name }))}
|
||||||
|
onChange={(values: string[]) =>
|
||||||
|
setSheetSelection((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[activeStepKey ?? '']: values,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Flex>
|
||||||
|
{STEP_FIELDS[activeStep.stepKey].map((field) => (
|
||||||
|
<Flex key={field.key} align="center" gap={8}>
|
||||||
|
<Typography.Text style={{ width: 120 }}>
|
||||||
|
{field.label}
|
||||||
|
{field.required ? <span style={{ color: '#ff4d4f' }}> *</span> : null}
|
||||||
|
{field.identity ? <Tag style={{ marginLeft: 4 }}>匹配键</Tag> : null}
|
||||||
|
</Typography.Text>
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
showSearch
|
||||||
|
style={{ minWidth: 320, flex: 1 }}
|
||||||
|
placeholder="选择对应列(留空则自动识别)"
|
||||||
|
value={mappingDraft[activeStepKey ?? '']?.[field.key]}
|
||||||
|
options={headerOptions.map((header) => ({ value: header, label: header }))}
|
||||||
|
onChange={(value?: string) =>
|
||||||
|
setMappingDraft((prev) => {
|
||||||
|
const current = { ...prev[activeStepKey ?? ''] };
|
||||||
|
if (value) current[field.key] = value;
|
||||||
|
else delete current[field.key];
|
||||||
|
return { ...prev, [activeStepKey ?? '']: current };
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Flex>
|
||||||
|
))}
|
||||||
|
<Flex justify="end">
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
loading={previewLoading}
|
||||||
|
onClick={() => void handlePreview()}
|
||||||
|
>
|
||||||
|
开始校验预览
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Space>
|
||||||
|
)}
|
||||||
|
</Space>
|
||||||
|
) : (
|
||||||
|
<Alert type="warning" showIcon title="当前没有可处理的阶段" />
|
||||||
|
)}
|
||||||
|
</Space>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
};
|
||||||
132
apps/admin/src/components/ImportWizard/types.ts
Normal file
132
apps/admin/src/components/ImportWizard/types.ts
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
export type ImportStepKey = 'students' | 'rooms' | 'checkins' | 'transfers';
|
||||||
|
|
||||||
|
export interface ImportSheetMeta {
|
||||||
|
name: string;
|
||||||
|
headers: string[];
|
||||||
|
rowCount: number;
|
||||||
|
suggestedStepKey: ImportStepKey | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImportStepSummary {
|
||||||
|
total: number;
|
||||||
|
valid: number;
|
||||||
|
error: number;
|
||||||
|
create: number;
|
||||||
|
update: number;
|
||||||
|
skip: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImportStepDetail {
|
||||||
|
id: number;
|
||||||
|
stepKey: ImportStepKey;
|
||||||
|
label: string;
|
||||||
|
sheets: string[];
|
||||||
|
status: 'pending' | 'ready' | 'committing' | 'committed' | 'failed' | 'skipped';
|
||||||
|
mapping: Record<string, string>;
|
||||||
|
summary: ImportStepSummary | null;
|
||||||
|
committedAt: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImportRunDetail {
|
||||||
|
id: string;
|
||||||
|
fileName: string;
|
||||||
|
source: 'ai' | 'manual';
|
||||||
|
status: 'preparing' | 'ready' | 'committing' | 'committed' | 'failed' | 'expired';
|
||||||
|
currentStepKey: ImportStepKey | null;
|
||||||
|
createdAt: string;
|
||||||
|
sheets: ImportSheetMeta[];
|
||||||
|
steps: ImportStepDetail[];
|
||||||
|
settings?: {
|
||||||
|
mapping?: Partial<Record<ImportStepKey, Record<string, string>>>;
|
||||||
|
organization?: string | null;
|
||||||
|
updateExisting?: boolean;
|
||||||
|
duplicatePolicy?: 'error' | 'skip';
|
||||||
|
skipUnmatched?: boolean;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImportStageRequest {
|
||||||
|
stepKey: ImportStepKey;
|
||||||
|
/** 兼容旧调用:单个工作表名。 */
|
||||||
|
sheet?: string;
|
||||||
|
/** 一个阶段可包含多张工作表;与 sheet 二选一(sheets 优先)。 */
|
||||||
|
sheets?: string[];
|
||||||
|
headerRow?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImportPreviewRow {
|
||||||
|
id: number;
|
||||||
|
rowNumber: number;
|
||||||
|
sheetName: string;
|
||||||
|
raw: Record<string, string | number | boolean | null>;
|
||||||
|
fields: Record<string, string | number | boolean | null>;
|
||||||
|
action: 'create' | 'update' | 'skip' | null;
|
||||||
|
status: 'pending' | 'valid' | 'error' | 'committed' | 'skipped';
|
||||||
|
errors: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImportPreviewResult {
|
||||||
|
stepKey: ImportStepKey;
|
||||||
|
sheetNames: string[];
|
||||||
|
headers: string[];
|
||||||
|
mapping: Record<string, string>;
|
||||||
|
rows: ImportPreviewRow[];
|
||||||
|
summary: ImportStepSummary;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImportReceipt {
|
||||||
|
runId: string;
|
||||||
|
stepKey: ImportStepKey;
|
||||||
|
status: 'committed' | 'already_committed' | 'conflict';
|
||||||
|
created: number;
|
||||||
|
updated: number;
|
||||||
|
skipped: number;
|
||||||
|
failed: number;
|
||||||
|
total: number;
|
||||||
|
nextStepKey: ImportStepKey | null;
|
||||||
|
runStatus: 'preparing' | 'ready' | 'committing' | 'committed' | 'failed' | 'expired';
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const STEP_FIELDS: Record<
|
||||||
|
ImportStepKey,
|
||||||
|
Array<{ key: string; label: string; required?: boolean; identity?: boolean }>
|
||||||
|
> = {
|
||||||
|
students: [
|
||||||
|
{ key: 'name', label: '姓名', required: true },
|
||||||
|
{ key: 'studentNo', label: '学号', identity: true },
|
||||||
|
{ key: 'phone', label: '手机号', identity: true },
|
||||||
|
{ key: 'gender', label: '性别' },
|
||||||
|
{ key: 'idNumber', label: '身份证号' },
|
||||||
|
{ key: 'ethnicity', label: '民族' },
|
||||||
|
{ key: 'emergencyContact', label: '紧急联系人' },
|
||||||
|
{ key: 'emergencyPhone', label: '紧急联系电话' },
|
||||||
|
{ key: 'organization', label: '校区' },
|
||||||
|
{ key: 'status', label: '状态' },
|
||||||
|
],
|
||||||
|
rooms: [
|
||||||
|
{ key: 'roomNumber', label: '宿舍号', required: true },
|
||||||
|
{ key: 'building', label: '楼栋' },
|
||||||
|
{ key: 'floor', label: '楼层' },
|
||||||
|
{ key: 'capacity', label: '容量', required: true },
|
||||||
|
{ key: 'roomType', label: '房型' },
|
||||||
|
{ key: 'rentalCategory', label: '租期类型' },
|
||||||
|
{ key: 'monthlyRate', label: '月租' },
|
||||||
|
],
|
||||||
|
checkins: [
|
||||||
|
{ key: 'name', label: '姓名' },
|
||||||
|
{ key: 'studentNo', label: '学号', identity: true },
|
||||||
|
{ key: 'phone', label: '手机号', identity: true },
|
||||||
|
{ key: 'roomNumber', label: '宿舍号', required: true },
|
||||||
|
{ key: 'checkInDate', label: '入住日期', required: true },
|
||||||
|
{ key: 'stayType', label: '住宿类型' },
|
||||||
|
],
|
||||||
|
transfers: [
|
||||||
|
{ key: 'studentNo', label: '学号', identity: true },
|
||||||
|
{ key: 'phone', label: '手机号', identity: true },
|
||||||
|
{ key: 'oldRoom', label: '原宿舍', required: true },
|
||||||
|
{ key: 'newRoom', label: '新宿舍', required: true },
|
||||||
|
{ key: 'transferDate', label: '换宿日期', required: true },
|
||||||
|
{ key: 'reason', label: '原因/备注' },
|
||||||
|
],
|
||||||
|
};
|
||||||
@@ -1,222 +1,28 @@
|
|||||||
import React, { useEffect, useRef, useState } from 'react';
|
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
import { Button, Form, Input, Modal, Popconfirm, Select, Spin, Steps, Tag, Typography } from 'antd';
|
import { useImmer } from 'use-immer';
|
||||||
import {
|
import { Button, Form, Input, Modal, Select, Spin, Steps, Typography } from 'antd';
|
||||||
CloudUploadOutlined,
|
import { CloudUploadOutlined, EditOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons';
|
||||||
DeleteOutlined,
|
|
||||||
EditOutlined,
|
|
||||||
LinkOutlined,
|
|
||||||
PlusOutlined,
|
|
||||||
SaveOutlined,
|
|
||||||
SearchOutlined,
|
|
||||||
} from '@ant-design/icons';
|
|
||||||
import api from '../api';
|
import api from '../api';
|
||||||
import { message } from '../ui/app-message';
|
import { message } from '../ui/app-message';
|
||||||
|
import { usePermission } from '../hooks/usePermission';
|
||||||
|
import PermissionButton from './PermissionButton';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useApiMutation } from '../hooks/useApiMutation';
|
||||||
|
import { validateResponse } from '../utils/validate';
|
||||||
|
import { jinshujuRulesSchema } from '../api/schemas';
|
||||||
|
import MatchStep from './MatchStep';
|
||||||
|
import RuleEditor from './RuleEditor';
|
||||||
|
import type {
|
||||||
|
JinshujuEntryRow,
|
||||||
|
JinshujuFormField,
|
||||||
|
MatchDecision,
|
||||||
|
MatchRule,
|
||||||
|
PreviewResponse,
|
||||||
|
StudentOption,
|
||||||
|
} from './JinshujuMatchModal.types';
|
||||||
|
|
||||||
const { Text } = Typography;
|
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 {
|
interface MatchModalProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
@@ -224,10 +30,12 @@ interface MatchModalProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplied }) => {
|
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 [step, setStep] = useState<'connection' | 'rule' | 'match' | 'applying'>('connection');
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [selectedRuleId, setSelectedRuleId] = useState<number | undefined>();
|
const [selectedRuleId, setSelectedRuleId] = useState<number | undefined>();
|
||||||
const [rules, setRules] = useState<MatchRule[]>([]);
|
|
||||||
const [editingRule, setEditingRule] = useState<MatchRule | null>(null);
|
const [editingRule, setEditingRule] = useState<MatchRule | null>(null);
|
||||||
const [showRuleEditor, setShowRuleEditor] = useState(false);
|
const [showRuleEditor, setShowRuleEditor] = useState(false);
|
||||||
const [credForm] = Form.useForm();
|
const [credForm] = Form.useForm();
|
||||||
@@ -235,26 +43,38 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
|
|
||||||
const [entries, setEntries] = useState<JinshujuEntryRow[]>([]);
|
const [entries, setEntries] = useState<JinshujuEntryRow[]>([]);
|
||||||
const [studentOptions, setStudentOptions] = useState<StudentOption[]>([]);
|
const [studentOptions, setStudentOptions] = useState<StudentOption[]>([]);
|
||||||
const [decisions, setDecisions] = useState<Map<number, MatchDecision>>(new Map());
|
const [decisions, setDecisions] = useImmer<Map<number, MatchDecision>>(new Map());
|
||||||
const leftRef = useRef<HTMLDivElement>(null);
|
const leftRef = useRef<HTMLDivElement>(null);
|
||||||
const rightRef = useRef<HTMLDivElement>(null);
|
const rightRef = useRef<HTMLDivElement>(null);
|
||||||
const [formFields, setFormFields] = useState<JinshujuFormField[]>([]);
|
const [formFields, setFormFields] = useState<JinshujuFormField[]>([]);
|
||||||
const [formName, setFormName] = useState('');
|
const [formName, setFormName] = useState('');
|
||||||
const [scrollTop, setScrollTop] = useState(0);
|
const [scrollTop, setScrollTop] = useState(0);
|
||||||
|
|
||||||
// Load rules on open
|
const {
|
||||||
useEffect(() => {
|
data: rules = [],
|
||||||
if (open) loadRules();
|
refetch: refetchRules,
|
||||||
}, [open]);
|
} = useQuery<MatchRule[]>({
|
||||||
|
queryKey: ['sync', 'jinshuju', 'rules'],
|
||||||
const loadRules = async () => {
|
enabled: open && canEnterModal,
|
||||||
try {
|
queryFn: async () => {
|
||||||
const res = await api.get<{ success: boolean; data: MatchRule[] }>('/sync/jinshuju/rules');
|
try {
|
||||||
if (res.success) setRules(res.data);
|
const res = await api.get<{ success: boolean; data: MatchRule[] }>(
|
||||||
} catch { /* ignore */ }
|
'/sync/jinshuju/rules',
|
||||||
};
|
);
|
||||||
|
return res.success ? validateResponse<MatchRule[]>(jinshujuRulesSchema, res.data) : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const loadRules = useCallback(() => refetchRules(), [refetchRules]);
|
||||||
|
const deleteRuleMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/sync/jinshuju/rules/${id}`),
|
||||||
|
{ invalidate: [['sync', 'jinshuju', 'rules']] },
|
||||||
|
);
|
||||||
|
|
||||||
const handleConnectionNext = async () => {
|
const handleConnectionNext = async () => {
|
||||||
|
if (!canTriggerSync) return;
|
||||||
try {
|
try {
|
||||||
const values = await credForm.validateFields();
|
const values = await credForm.validateFields();
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -274,6 +94,7 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handlePreview = async () => {
|
const handlePreview = async () => {
|
||||||
|
if (!canTriggerSync) return;
|
||||||
try {
|
try {
|
||||||
const values = await credForm.validateFields();
|
const values = await credForm.validateFields();
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -286,7 +107,10 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
const initial = new Map<number, MatchDecision>();
|
const initial = new Map<number, MatchDecision>();
|
||||||
for (const entry of res.entries) {
|
for (const entry of res.entries) {
|
||||||
if (entry.suggestedStudent) {
|
if (entry.suggestedStudent) {
|
||||||
initial.set(entry.serialNumber, { action: 'match', matchStudentId: entry.suggestedStudent.id });
|
initial.set(entry.serialNumber, {
|
||||||
|
action: 'match',
|
||||||
|
matchStudentId: entry.suggestedStudent.id,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setDecisions(initial);
|
setDecisions(initial);
|
||||||
@@ -294,22 +118,29 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const err = e as { message?: string };
|
const err = e as { message?: string };
|
||||||
if (err?.message) message.error(err.message);
|
if (err?.message) message.error(err.message);
|
||||||
} finally { setLoading(false); }
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleApply = async () => {
|
const handleApply = async () => {
|
||||||
|
if (!canTriggerSync) return;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setStep('applying');
|
setStep('applying');
|
||||||
try {
|
try {
|
||||||
const decisionList = [...decisions.entries()].map(([serialNumber, d]) => ({ serialNumber, ...d }));
|
const decisionList = [...decisions.entries()].map(([serialNumber, d]) => ({
|
||||||
|
serialNumber,
|
||||||
|
...d,
|
||||||
|
}));
|
||||||
const body: Record<string, unknown> = {
|
const body: Record<string, unknown> = {
|
||||||
...credForm.getFieldsValue(),
|
...credForm.getFieldsValue(),
|
||||||
decisions: decisionList,
|
decisions: decisionList,
|
||||||
};
|
};
|
||||||
if (selectedRuleId) body.ruleId = selectedRuleId;
|
if (selectedRuleId) body.ruleId = selectedRuleId;
|
||||||
const res = await api.post<{ success: boolean; log: { recordsCount: number; message?: string } }>(
|
const res = await api.post<{
|
||||||
'/sync/jinshuju/apply', body,
|
success: boolean;
|
||||||
);
|
log: { recordsCount: number; message?: string };
|
||||||
|
}>('/sync/jinshuju/apply', body);
|
||||||
if (res.success) {
|
if (res.success) {
|
||||||
message.success(res.log.message || `处理 ${res.log.recordsCount} 条记录`);
|
message.success(res.log.message || `处理 ${res.log.recordsCount} 条记录`);
|
||||||
onApplied();
|
onApplied();
|
||||||
@@ -319,7 +150,9 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
const err = e as { message?: string };
|
const err = e as { message?: string };
|
||||||
if (err?.message) message.error(err.message);
|
if (err?.message) message.error(err.message);
|
||||||
setStep('match');
|
setStep('match');
|
||||||
} finally { setLoading(false); }
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const reset = () => {
|
const reset = () => {
|
||||||
@@ -334,7 +167,10 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
credForm.resetFields();
|
credForm.resetFields();
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleClose = () => { reset(); onClose(); };
|
const handleClose = () => {
|
||||||
|
reset();
|
||||||
|
onClose();
|
||||||
|
};
|
||||||
const handleScroll = (source: 'left' | 'right') => {
|
const handleScroll = (source: 'left' | 'right') => {
|
||||||
const el = source === 'left' ? leftRef.current : rightRef.current;
|
const el = source === 'left' ? leftRef.current : rightRef.current;
|
||||||
if (el) setScrollTop(el.scrollTop);
|
if (el) setScrollTop(el.scrollTop);
|
||||||
@@ -346,7 +182,10 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
}, [scrollTop]);
|
}, [scrollTop]);
|
||||||
|
|
||||||
const getDecision = (serial: number): MatchDecision | undefined => decisions.get(serial);
|
const getDecision = (serial: number): MatchDecision | undefined => decisions.get(serial);
|
||||||
const setDecision = (serial: number, d: MatchDecision) => setDecisions((prev) => new Map(prev).set(serial, d));
|
const setDecision = (serial: number, d: MatchDecision) =>
|
||||||
|
setDecisions((draft) => {
|
||||||
|
draft.set(serial, d);
|
||||||
|
});
|
||||||
const total = entries.length;
|
const total = entries.length;
|
||||||
const matched = [...decisions.values()].filter((d) => d.action !== 'skip').length;
|
const matched = [...decisions.values()].filter((d) => d.action !== 'skip').length;
|
||||||
|
|
||||||
@@ -401,7 +240,7 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
onChange={(value) => setSelectedRuleId(value)}
|
onChange={(value) => setSelectedRuleId(value)}
|
||||||
options={visibleRules.map((rule) => ({ value: rule.id, label: rule.name }))}
|
options={visibleRules.map((rule) => ({ value: rule.id, label: rule.name }))}
|
||||||
/>
|
/>
|
||||||
{selectedRule ? (
|
{canTriggerSync && selectedRule ? (
|
||||||
<Button
|
<Button
|
||||||
icon={<EditOutlined />}
|
icon={<EditOutlined />}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -412,15 +251,17 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
编辑
|
编辑
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
<Button
|
{canTriggerSync ? (
|
||||||
icon={<PlusOutlined />}
|
<Button
|
||||||
onClick={() => {
|
icon={<PlusOutlined />}
|
||||||
setEditingRule(null);
|
onClick={() => {
|
||||||
setShowRuleEditor(true);
|
setEditingRule(null);
|
||||||
}}
|
setShowRuleEditor(true);
|
||||||
>
|
}}
|
||||||
新建规则
|
>
|
||||||
</Button>
|
新建规则
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{visibleRules.length === 0 && !showRuleEditor ? (
|
{visibleRules.length === 0 && !showRuleEditor ? (
|
||||||
@@ -429,7 +270,7 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
</Text>
|
</Text>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{showRuleEditor ? (
|
{canTriggerSync && showRuleEditor ? (
|
||||||
<RuleEditor
|
<RuleEditor
|
||||||
rule={editingRule}
|
rule={editingRule}
|
||||||
formToken={formToken}
|
formToken={formToken}
|
||||||
@@ -439,11 +280,14 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
loadRules();
|
loadRules();
|
||||||
}}
|
}}
|
||||||
onDelete={async (id) => {
|
onDelete={async (id) => {
|
||||||
await api.delete(`/sync/jinshuju/rules/${id}`);
|
try {
|
||||||
message.success('规则已删除');
|
await deleteRuleMutation.mutateAsync(id);
|
||||||
if (selectedRuleId === id) setSelectedRuleId(undefined);
|
message.success('规则已删除');
|
||||||
setShowRuleEditor(false);
|
if (selectedRuleId === id) setSelectedRuleId(undefined);
|
||||||
loadRules();
|
setShowRuleEditor(false);
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
onCancel={() => setShowRuleEditor(false)}
|
onCancel={() => setShowRuleEditor(false)}
|
||||||
/>
|
/>
|
||||||
@@ -452,112 +296,92 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
);
|
);
|
||||||
|
|
||||||
const renderMatchStep = () => {
|
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 (
|
return (
|
||||||
<div style={{ position: 'relative' }}>
|
<MatchStep
|
||||||
<div style={{ marginBottom: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
entries={entries}
|
||||||
<Text type="secondary">共 {total} 条,已匹配 {matched} 条</Text>
|
studentOptions={studentOptions}
|
||||||
<Button size="small" onClick={() => setDecisions(new Map())}>清除全部匹配</Button>
|
getDecision={getDecision}
|
||||||
</div>
|
onDecisionChange={setDecision}
|
||||||
<div style={{ display: 'flex', position: 'relative' }}>
|
onClear={() => setDecisions(new Map())}
|
||||||
<svg style={{ position: 'absolute', top: 0, left: 0, width: LEFT_WIDTH + GAP, height: svgHeight, pointerEvents: 'none', zIndex: 1 }}>
|
leftRef={leftRef}
|
||||||
{lines}
|
rightRef={rightRef}
|
||||||
</svg>
|
onScroll={handleScroll}
|
||||||
<div ref={leftRef} onScroll={() => handleScroll('left')}
|
total={total}
|
||||||
style={{ width: LEFT_WIDTH, maxHeight: 480, overflowY: 'auto', flexShrink: 0 }}>
|
matched={matched}
|
||||||
{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 backCancelButtons = (onBack: () => void) => [
|
||||||
|
<Button key="back" onClick={onBack}>
|
||||||
|
上一步
|
||||||
|
</Button>,
|
||||||
|
<Button key="cancel" onClick={handleClose}>
|
||||||
|
取消
|
||||||
|
</Button>,
|
||||||
|
];
|
||||||
|
|
||||||
const currentStep = step === 'connection' ? 0 : step === 'rule' ? 1 : 2;
|
const currentStep = step === 'connection' ? 0 : step === 'rule' ? 1 : 2;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title="同步金数据"
|
title="同步金数据"
|
||||||
open={open}
|
open={open && canEnterModal}
|
||||||
onCancel={handleClose}
|
onCancel={handleClose}
|
||||||
width={step === 'match' || step === 'applying' ? 900 : 640}
|
width={step === 'match' || step === 'applying' ? 900 : 640}
|
||||||
maskClosable={false}
|
mask={{ closable: false }}
|
||||||
footer={
|
footer={
|
||||||
step === 'connection'
|
step === 'connection'
|
||||||
? [
|
? [
|
||||||
<Button key="cancel" onClick={handleClose}>取消</Button>,
|
<Button key="cancel" onClick={handleClose}>
|
||||||
<Button key="next" type="primary" onClick={handleConnectionNext}>下一步</Button>,
|
取消
|
||||||
|
</Button>,
|
||||||
|
<Button key="next" type="primary" onClick={handleConnectionNext}>
|
||||||
|
下一步
|
||||||
|
</Button>,
|
||||||
]
|
]
|
||||||
: step === 'rule'
|
: step === 'rule'
|
||||||
? [
|
? [
|
||||||
<Button key="back" onClick={() => setStep('connection')}>上一步</Button>,
|
...backCancelButtons(() => setStep('connection')),
|
||||||
<Button key="cancel" onClick={handleClose}>取消</Button>,
|
<Button
|
||||||
<Button key="next" type="primary" icon={<SearchOutlined />} loading={loading} onClick={handlePreview}>
|
key="next"
|
||||||
|
type="primary"
|
||||||
|
icon={<SearchOutlined />}
|
||||||
|
loading={loading}
|
||||||
|
onClick={handlePreview}
|
||||||
|
>
|
||||||
获取数据并下一步
|
获取数据并下一步
|
||||||
</Button>,
|
</Button>,
|
||||||
]
|
]
|
||||||
: step === 'match'
|
: step === 'match'
|
||||||
? [
|
? [
|
||||||
<Button key="back" onClick={() => setStep('rule')}>上一步</Button>,
|
...backCancelButtons(() => setStep('rule')),
|
||||||
<Button key="cancel" onClick={handleClose}>取消</Button>,
|
canTriggerSync ? (
|
||||||
<Button key="apply" type="primary" icon={<CloudUploadOutlined />} loading={loading} onClick={handleApply}>
|
<PermissionButton
|
||||||
应用匹配
|
key="apply"
|
||||||
</Button>,
|
permission="sync:trigger"
|
||||||
|
type="primary"
|
||||||
|
icon={<CloudUploadOutlined />}
|
||||||
|
loading={loading}
|
||||||
|
onClick={handleApply}
|
||||||
|
>
|
||||||
|
应用匹配
|
||||||
|
</PermissionButton>
|
||||||
|
) : null,
|
||||||
]
|
]
|
||||||
: null
|
: null
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<Steps
|
<Steps
|
||||||
current={currentStep}
|
current={currentStep}
|
||||||
items={[
|
items={[{ title: '连接表单' }, { title: '匹配规则' }, { title: '确认匹配' }]}
|
||||||
{ title: '连接表单' },
|
|
||||||
{ title: '匹配规则' },
|
|
||||||
{ title: '确认匹配' },
|
|
||||||
]}
|
|
||||||
/>
|
/>
|
||||||
{step === 'connection' ? renderConnectionStep() : null}
|
{step === 'connection' ? renderConnectionStep() : null}
|
||||||
{step === 'rule' ? renderRuleStep() : null}
|
{step === 'rule' ? renderRuleStep() : null}
|
||||||
{step === 'match' ? renderMatchStep() : null}
|
{step === 'match' ? renderMatchStep() : null}
|
||||||
{step === 'applying' ? <Spin tip="正在同步..." style={{ display: 'block', margin: '48px auto' }} /> : null}
|
{step === 'applying' ? (
|
||||||
|
<Spin description="正在同步..." style={{ display: 'block', margin: '48px auto' }} />
|
||||||
|
) : null}
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
58
apps/admin/src/components/JinshujuMatchModal.types.ts
Normal file
58
apps/admin/src/components/JinshujuMatchModal.types.ts
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
export interface JinshujuEntryRow {
|
||||||
|
serialNumber: number;
|
||||||
|
name: string;
|
||||||
|
phone: string | null;
|
||||||
|
suggestedStudent: {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
phone: string | null;
|
||||||
|
studentNo: string | null;
|
||||||
|
} | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StudentOption {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
phone: string | null;
|
||||||
|
studentNo: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PreviewResponse {
|
||||||
|
success: boolean;
|
||||||
|
entries: JinshujuEntryRow[];
|
||||||
|
students: StudentOption[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MatchRule {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
formToken: string;
|
||||||
|
mappings: Record<string, string>;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface JinshujuFormField {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
type: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MatchDecision =
|
||||||
|
| { action: 'match'; matchStudentId: number }
|
||||||
|
| { action: 'create'; createName: string; createPhone: string }
|
||||||
|
| { action: 'skip' };
|
||||||
|
|
||||||
|
export const ROW_HEIGHT = 72;
|
||||||
|
export const LEFT_WIDTH = 260;
|
||||||
|
export const GAP = 80;
|
||||||
|
|
||||||
|
export 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: '学号' },
|
||||||
|
];
|
||||||
124
apps/admin/src/components/MatchSelector.tsx
Normal file
124
apps/admin/src/components/MatchSelector.tsx
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Button, Input, Select, Tag, Typography } from 'antd';
|
||||||
|
import { LinkOutlined, PlusOutlined } from '@ant-design/icons';
|
||||||
|
import type { JinshujuEntryRow, MatchDecision, StudentOption } from './JinshujuMatchModal.types';
|
||||||
|
|
||||||
|
const { Text } = Typography;
|
||||||
|
|
||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default MatchSelector;
|
||||||
156
apps/admin/src/components/MatchStep.tsx
Normal file
156
apps/admin/src/components/MatchStep.tsx
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Button, Typography } from 'antd';
|
||||||
|
import MatchSelector from './MatchSelector';
|
||||||
|
import { GAP, LEFT_WIDTH, ROW_HEIGHT } from './JinshujuMatchModal.types';
|
||||||
|
import type { JinshujuEntryRow, MatchDecision, StudentOption } from './JinshujuMatchModal.types';
|
||||||
|
|
||||||
|
const { Text } = Typography;
|
||||||
|
|
||||||
|
interface MatchStepProps {
|
||||||
|
entries: JinshujuEntryRow[];
|
||||||
|
studentOptions: StudentOption[];
|
||||||
|
getDecision: (serial: number) => MatchDecision | undefined;
|
||||||
|
onDecisionChange: (serial: number, d: MatchDecision) => void;
|
||||||
|
onClear: () => void;
|
||||||
|
leftRef: React.RefObject<HTMLDivElement | null>;
|
||||||
|
rightRef: React.RefObject<HTMLDivElement | null>;
|
||||||
|
onScroll: (source: 'left' | 'right') => void;
|
||||||
|
total: number;
|
||||||
|
matched: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MatchStep: React.FC<MatchStepProps> = ({
|
||||||
|
entries,
|
||||||
|
studentOptions,
|
||||||
|
getDecision,
|
||||||
|
onDecisionChange,
|
||||||
|
onClear,
|
||||||
|
leftRef,
|
||||||
|
rightRef,
|
||||||
|
onScroll,
|
||||||
|
total,
|
||||||
|
matched,
|
||||||
|
}) => {
|
||||||
|
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={onClear}>
|
||||||
|
清除全部匹配
|
||||||
|
</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={() => onScroll('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={() => onScroll('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) => onDecisionChange(entry.serialNumber, newD)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default MatchStep;
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
import React, { useState, useEffect, useRef } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { Badge, Popover, Button, List, Typography, Empty } from 'antd';
|
import { Badge, Popover, Button, List, Typography, Empty } from 'antd';
|
||||||
import { BellOutlined } from '@ant-design/icons';
|
import { BellOutlined } from '@ant-design/icons';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
import { useInterval } from 'usehooks-ts';
|
||||||
import api from '../api';
|
import api from '../api';
|
||||||
import { formatNotificationText, notificationTypeLabels } from '../utils/notification-display';
|
import { formatNotificationText, notificationTypeLabels } from '../utils/notification-display';
|
||||||
|
import { useUserStore } from '../store/user/userStore';
|
||||||
|
|
||||||
interface NotificationItem {
|
interface NotificationItem {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -16,25 +19,19 @@ interface NotificationItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function timeAgo(dateStr: string): string {
|
function timeAgo(dateStr: string): string {
|
||||||
const diff = Date.now() - new Date(dateStr).getTime();
|
return dayjs(dateStr).fromNow();
|
||||||
const mins = Math.floor(diff / 60000);
|
|
||||||
if (mins < 1) return '刚刚';
|
|
||||||
if (mins < 60) return `${mins}分钟前`;
|
|
||||||
const hours = Math.floor(mins / 60);
|
|
||||||
if (hours < 24) return `${hours}小时前`;
|
|
||||||
const days = Math.floor(hours / 24);
|
|
||||||
return `${days}天前`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const NotificationBell: React.FC = () => {
|
const NotificationBell: React.FC = () => {
|
||||||
const [unreadCount, setUnreadCount] = useState(0);
|
const [unreadCount, setUnreadCount] = useState(0);
|
||||||
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
|
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
|
const [sseDown, setSseDown] = useState(false);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const fetchNotifications = async () => {
|
const fetchNotifications = async () => {
|
||||||
try {
|
try {
|
||||||
const data = (await api.get('/notifications?limit=20')) as unknown as NotificationItem[];
|
const data = await api.get<NotificationItem[]>('/notifications?limit=20');
|
||||||
setNotifications(data);
|
setNotifications(data);
|
||||||
} catch {
|
} catch {
|
||||||
/* ignore */
|
/* ignore */
|
||||||
@@ -43,7 +40,7 @@ const NotificationBell: React.FC = () => {
|
|||||||
|
|
||||||
const fetchUnread = async () => {
|
const fetchUnread = async () => {
|
||||||
try {
|
try {
|
||||||
const data = (await api.get('/notifications/unread-count')) as unknown as { count: number };
|
const data = await api.get<{ count: number }>('/notifications/unread-count');
|
||||||
setUnreadCount(data.count);
|
setUnreadCount(data.count);
|
||||||
} catch {
|
} catch {
|
||||||
/* ignore */
|
/* ignore */
|
||||||
@@ -51,14 +48,17 @@ const NotificationBell: React.FC = () => {
|
|||||||
};
|
};
|
||||||
const openRef = useRef(open);
|
const openRef = useRef(open);
|
||||||
openRef.current = open;
|
openRef.current = open;
|
||||||
const retryRef = useRef<number | null>(null);
|
useInterval(() => {
|
||||||
|
void fetchUnread();
|
||||||
|
}, sseDown ? 60_000 : null);
|
||||||
|
|
||||||
// SSE connection — decoupled from popover open state
|
// SSE connection — decoupled from popover open state
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchUnread();
|
fetchUnread();
|
||||||
const token = localStorage.getItem('token');
|
const token = useUserStore.getState().token;
|
||||||
if (!token) return;
|
if (!token) return;
|
||||||
const es = new EventSource(`/api/notifications/stream?token=${encodeURIComponent(token)}`);
|
const es = new EventSource(`/api/notifications/stream?token=${encodeURIComponent(token)}`);
|
||||||
|
es.onopen = () => setSseDown(false);
|
||||||
es.onmessage = (event) => {
|
es.onmessage = (event) => {
|
||||||
try {
|
try {
|
||||||
JSON.parse(event.data);
|
JSON.parse(event.data);
|
||||||
@@ -69,14 +69,12 @@ const NotificationBell: React.FC = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
es.onerror = () => {
|
es.onerror = () => {
|
||||||
es.close();
|
// 不主动关闭:EventSource 会自动重连,主动关闭会导致一次超时后实时通知永久断流
|
||||||
if (retryRef.current !== null) clearInterval(retryRef.current);
|
setSseDown(true);
|
||||||
retryRef.current = window.setInterval(fetchUnread, 60_000);
|
|
||||||
};
|
};
|
||||||
return () => {
|
return () => {
|
||||||
es.close();
|
es.close();
|
||||||
clearInterval(retryRef.current ?? undefined);
|
setSseDown(false);
|
||||||
retryRef.current = null;
|
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Button } from 'antd';
|
import { Button, type ButtonProps } from 'antd';
|
||||||
import type { ButtonProps } from 'antd';
|
|
||||||
import { usePermission } from '../hooks/usePermission';
|
import { usePermission } from '../hooks/usePermission';
|
||||||
|
|
||||||
interface PermissionButtonProps extends ButtonProps {
|
interface PermissionButtonProps extends ButtonProps {
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Result, Button } from 'antd';
|
import { Result, Button, Spin } from 'antd';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router';
|
||||||
import { findRoleAwareLandingPath } from '../auth/menu-policy';
|
import { findRoleAwareLandingPath } from '../auth/menu-policy';
|
||||||
import { usePermission } from '../hooks/usePermission';
|
import { usePermission } from '../hooks/usePermission';
|
||||||
|
import { useUserStore } from '../store/user/userStore';
|
||||||
|
|
||||||
interface PermissionRouteProps {
|
interface PermissionRouteProps {
|
||||||
permission: string;
|
permission: string;
|
||||||
@@ -10,15 +11,13 @@ interface PermissionRouteProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const PermissionRoute: React.FC<PermissionRouteProps> = ({ permission, children }) => {
|
const PermissionRoute: React.FC<PermissionRouteProps> = ({ permission, children }) => {
|
||||||
const { permissions, hasPermission } = usePermission();
|
const { permissions, permissionsReady, hasPermission } = usePermission();
|
||||||
|
const roles = useUserStore((state) => state.user?.roles ?? []);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
if (!permissionsReady) {
|
||||||
|
return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;
|
||||||
|
}
|
||||||
if (!hasPermission(permission)) {
|
if (!hasPermission(permission)) {
|
||||||
let roles: string[] = [];
|
|
||||||
try {
|
|
||||||
roles = JSON.parse(localStorage.getItem('user') || '{}').roles || [];
|
|
||||||
} catch {
|
|
||||||
roles = [];
|
|
||||||
}
|
|
||||||
const firstPath = findRoleAwareLandingPath(roles, permissions);
|
const firstPath = findRoleAwareLandingPath(roles, permissions);
|
||||||
return (
|
return (
|
||||||
<Result
|
<Result
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
import React, { useEffect, useMemo, useState } from 'react';
|
import React, { useEffect, useMemo } from 'react';
|
||||||
import type { DragEndEvent } from '@dnd-kit/core';
|
import {
|
||||||
import { closestCenter, DndContext, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
|
closestCenter,
|
||||||
|
DndContext,
|
||||||
|
PointerSensor,
|
||||||
|
useSensor,
|
||||||
|
useSensors,
|
||||||
|
type DragEndEvent,
|
||||||
|
} from '@dnd-kit/core';
|
||||||
import {
|
import {
|
||||||
arrayMove,
|
arrayMove,
|
||||||
horizontalListSortingStrategy,
|
horizontalListSortingStrategy,
|
||||||
@@ -8,17 +14,10 @@ import {
|
|||||||
useSortable,
|
useSortable,
|
||||||
} from '@dnd-kit/sortable';
|
} from '@dnd-kit/sortable';
|
||||||
import { CSS } from '@dnd-kit/utilities';
|
import { CSS } from '@dnd-kit/utilities';
|
||||||
import { Tabs } from 'antd';
|
import { Tabs, type TabsProps } from 'antd';
|
||||||
import type { TabsProps } from 'antd';
|
import type { Location } from 'react-router';
|
||||||
import type { Location } from 'react-router-dom';
|
|
||||||
import type { AppMenuItem } from '../../auth/menu-policy';
|
import type { AppMenuItem } from '../../auth/menu-policy';
|
||||||
|
import { useAppStore } from '../../store';
|
||||||
const STORAGE_KEY = 'gongxue-route-dock';
|
|
||||||
|
|
||||||
interface DockTab {
|
|
||||||
key: string;
|
|
||||||
label: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface RouteDockProps {
|
interface RouteDockProps {
|
||||||
location: Location;
|
location: Location;
|
||||||
@@ -50,19 +49,6 @@ function getRouteLabel(items: readonly AppMenuItem[], pathname: string): string
|
|||||||
return pathname === '/' ? '首页' : '页面';
|
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 DraggableTabNode: React.FC<Readonly<DraggableTabNodeProps>> = ({ ...props }) => {
|
||||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
|
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
|
||||||
id: props['data-node-key'],
|
id: props['data-node-key'],
|
||||||
@@ -87,28 +73,20 @@ const DraggableTabNode: React.FC<Readonly<DraggableTabNodeProps>> = ({ ...props
|
|||||||
|
|
||||||
const RouteDock: React.FC<RouteDockProps> = ({ location, menuItems, onNavigate, draggable }) => {
|
const RouteDock: React.FC<RouteDockProps> = ({ location, menuItems, onNavigate, draggable }) => {
|
||||||
const activeKey = `${location.pathname}${location.search}`;
|
const activeKey = `${location.pathname}${location.search}`;
|
||||||
const [tabs, setTabs] = useState<DockTab[]>(() => {
|
const tabs = useAppStore((state) => state.routeDockTabs);
|
||||||
const storedTabs = readStoredTabs();
|
const setRouteDockTabs = useAppStore((state) => state.setRouteDockTabs);
|
||||||
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 } }));
|
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }));
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (location.pathname === '/') return;
|
if (location.pathname === '/') return;
|
||||||
setTabs((currentTabs) => {
|
setRouteDockTabs((currentTabs) => {
|
||||||
const label = getRouteLabel(menuItems, location.pathname);
|
const label = getRouteLabel(menuItems, location.pathname);
|
||||||
const existing = currentTabs.find((tab) => tab.key === activeKey);
|
const existing = currentTabs.find((tab) => tab.key === activeKey);
|
||||||
if (!existing) return [...currentTabs, { key: activeKey, label }];
|
if (!existing) return [...currentTabs, { key: activeKey, label }];
|
||||||
if (existing.label === label) return currentTabs;
|
if (existing.label === label) return currentTabs;
|
||||||
return currentTabs.map((tab) => (tab.key === activeKey ? { ...tab, label } : tab));
|
return currentTabs.map((tab) => (tab.key === activeKey ? { ...tab, label } : tab));
|
||||||
});
|
});
|
||||||
}, [activeKey, location.pathname, menuItems]);
|
}, [activeKey, location.pathname, menuItems, setRouteDockTabs]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(tabs));
|
|
||||||
}, [tabs]);
|
|
||||||
|
|
||||||
const tabItems = useMemo<NonNullable<TabsProps['items']>>(
|
const tabItems = useMemo<NonNullable<TabsProps['items']>>(
|
||||||
() =>
|
() =>
|
||||||
@@ -124,7 +102,7 @@ const RouteDock: React.FC<RouteDockProps> = ({ location, menuItems, onNavigate,
|
|||||||
const targetIndex = tabs.findIndex((tab) => tab.key === targetKey);
|
const targetIndex = tabs.findIndex((tab) => tab.key === targetKey);
|
||||||
if (targetIndex < 0 || tabs.length === 1) return;
|
if (targetIndex < 0 || tabs.length === 1) return;
|
||||||
const nextTabs = tabs.filter((tab) => tab.key !== targetKey);
|
const nextTabs = tabs.filter((tab) => tab.key !== targetKey);
|
||||||
setTabs(nextTabs);
|
setRouteDockTabs(nextTabs);
|
||||||
if (targetKey === activeKey) {
|
if (targetKey === activeKey) {
|
||||||
const nextActiveTab = nextTabs[Math.min(targetIndex, nextTabs.length - 1)];
|
const nextActiveTab = nextTabs[Math.min(targetIndex, nextTabs.length - 1)];
|
||||||
if (nextActiveTab) onNavigate(nextActiveTab.key);
|
if (nextActiveTab) onNavigate(nextActiveTab.key);
|
||||||
@@ -133,7 +111,7 @@ const RouteDock: React.FC<RouteDockProps> = ({ location, menuItems, onNavigate,
|
|||||||
|
|
||||||
const handleDragEnd = ({ active, over }: DragEndEvent) => {
|
const handleDragEnd = ({ active, over }: DragEndEvent) => {
|
||||||
if (!over || active.id === over.id) return;
|
if (!over || active.id === over.id) return;
|
||||||
setTabs((currentTabs) => {
|
setRouteDockTabs((currentTabs) => {
|
||||||
const activeIndex = currentTabs.findIndex((tab) => tab.key === active.id);
|
const activeIndex = currentTabs.findIndex((tab) => tab.key === active.id);
|
||||||
const overIndex = currentTabs.findIndex((tab) => tab.key === over.id);
|
const overIndex = currentTabs.findIndex((tab) => tab.key === over.id);
|
||||||
return activeIndex < 0 || overIndex < 0
|
return activeIndex < 0 || overIndex < 0
|
||||||
|
|||||||
96
apps/admin/src/components/RouteKeeper.integration.test.tsx
Normal file
96
apps/admin/src/components/RouteKeeper.integration.test.tsx
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
import { act } from 'react';
|
||||||
|
import { createRoot } from 'react-dom/client';
|
||||||
|
import { MemoryRouter, Route, Routes, useNavigate } from 'react-router';
|
||||||
|
import { afterEach, describe, expect, it } from 'vitest';
|
||||||
|
import { RouteKeeper } from './RouteKeeper';
|
||||||
|
|
||||||
|
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;
|
||||||
|
});
|
||||||
|
|
||||||
|
function PageA() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<input data-testid="input-a" aria-label="A 输入" />
|
||||||
|
<button data-testid="go-b" onClick={() => navigate('/b')}>
|
||||||
|
去B
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function PageB() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<input data-testid="input-b" aria-label="B 输入" />
|
||||||
|
<button data-testid="go-a" onClick={() => navigate('/')}>
|
||||||
|
去A
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Harness() {
|
||||||
|
return (
|
||||||
|
<MemoryRouter initialEntries={['/']}>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/" element={<RouteKeeper />}>
|
||||||
|
<Route index element={<PageA />} />
|
||||||
|
<Route path="b" element={<PageB />} />
|
||||||
|
</Route>
|
||||||
|
</Routes>
|
||||||
|
</MemoryRouter>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function type(target: HTMLInputElement, value: string) {
|
||||||
|
const setter = Object.getOwnPropertyDescriptor(
|
||||||
|
window.HTMLInputElement.prototype,
|
||||||
|
'value',
|
||||||
|
)?.set;
|
||||||
|
setter?.call(target, value);
|
||||||
|
target.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('RouteKeeper', () => {
|
||||||
|
it('keeps page instances and input values alive across navigation', async () => {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
await act(async () => root?.render(<Harness />));
|
||||||
|
|
||||||
|
const inputA = document.querySelector('[data-testid="input-a"]') as HTMLInputElement;
|
||||||
|
expect(inputA).not.toBeNull();
|
||||||
|
await act(async () => type(inputA, '待保存的学生姓名'));
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
(document.querySelector('[data-testid="go-b"]') as HTMLButtonElement).click();
|
||||||
|
});
|
||||||
|
const inputB = document.querySelector('[data-testid="input-b"]') as HTMLInputElement;
|
||||||
|
expect(inputB).not.toBeNull();
|
||||||
|
await act(async () => type(inputB, '待保存的宿舍号'));
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
(document.querySelector('[data-testid="go-a"]') as HTMLButtonElement).click();
|
||||||
|
});
|
||||||
|
|
||||||
|
const keptA = document.querySelector('[data-testid="input-a"]') as HTMLInputElement;
|
||||||
|
expect(keptA).not.toBeNull();
|
||||||
|
expect(keptA.value).toBe('待保存的学生姓名');
|
||||||
|
const keptB = document.querySelector('[data-testid="input-b"]') as HTMLInputElement;
|
||||||
|
expect(keptB.value).toBe('待保存的宿舍号');
|
||||||
|
|
||||||
|
const pages = document.querySelectorAll('.route-keeper-page');
|
||||||
|
expect(pages.length).toBe(2);
|
||||||
|
const hidden = pages[1] as HTMLElement;
|
||||||
|
expect(hidden.style.display).toBe('none');
|
||||||
|
});
|
||||||
|
});
|
||||||
43
apps/admin/src/components/RouteKeeper.tsx
Normal file
43
apps/admin/src/components/RouteKeeper.tsx
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import React, { useRef } from 'react';
|
||||||
|
import { useLocation, useOutlet } from 'react-router';
|
||||||
|
|
||||||
|
const MAX_CACHED_PAGES = 30;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 路由保活:切换页面时保留已访问页面的组件实例(输入、滚动、弹窗状态不丢失)。
|
||||||
|
* 隐藏页面仍挂载在 DOM 中,仅通过 display:none 隐藏。
|
||||||
|
*/
|
||||||
|
export const RouteKeeper: React.FC = () => {
|
||||||
|
const location = useLocation();
|
||||||
|
const outlet = useOutlet();
|
||||||
|
const cacheRef = useRef<Map<string, React.ReactNode>>(new Map());
|
||||||
|
const orderRef = useRef<string[]>([]);
|
||||||
|
// 仅以 pathname 作为缓存键:页面内部通过 URL 参数同步状态时不会
|
||||||
|
// 产生第二个实例,切回时也不会因此重挂载。
|
||||||
|
const pageKey = location.pathname;
|
||||||
|
|
||||||
|
if (outlet && !cacheRef.current.has(pageKey)) {
|
||||||
|
cacheRef.current.set(pageKey, outlet);
|
||||||
|
orderRef.current.push(pageKey);
|
||||||
|
if (orderRef.current.length > MAX_CACHED_PAGES) {
|
||||||
|
const oldest = orderRef.current.shift();
|
||||||
|
if (oldest && oldest !== pageKey) cacheRef.current.delete(oldest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{Array.from(cacheRef.current.entries()).map(([key, node]) => (
|
||||||
|
<div
|
||||||
|
key={key}
|
||||||
|
className="route-keeper-page"
|
||||||
|
style={{ display: key === pageKey ? undefined : 'none' }}
|
||||||
|
>
|
||||||
|
{node}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default RouteKeeper;
|
||||||
123
apps/admin/src/components/RuleEditor.tsx
Normal file
123
apps/admin/src/components/RuleEditor.tsx
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Button, Input, Popconfirm, Select, Typography } from 'antd';
|
||||||
|
import { DeleteOutlined, SaveOutlined } from '@ant-design/icons';
|
||||||
|
import api from '../api';
|
||||||
|
import { message } from '../ui/app-message';
|
||||||
|
import { useApiMutation } from '../hooks/useApiMutation';
|
||||||
|
import { STUDENT_FIELDS } from './JinshujuMatchModal.types';
|
||||||
|
import type { JinshujuFormField, MatchRule } from './JinshujuMatchModal.types';
|
||||||
|
|
||||||
|
const { Text } = Typography;
|
||||||
|
|
||||||
|
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 saveMutation = useApiMutation(
|
||||||
|
async (payload: { name: string; mappings: Record<string, string> }) =>
|
||||||
|
rule
|
||||||
|
? api.put(`/sync/jinshuju/rules/${rule.id}`, payload)
|
||||||
|
: api.post('/sync/jinshuju/rules', { ...payload, formToken }),
|
||||||
|
{
|
||||||
|
invalidate: [['sync', 'jinshuju', 'rules']],
|
||||||
|
onSuccess: () => {
|
||||||
|
message.success('规则已保存');
|
||||||
|
onSave();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (!name.trim()) {
|
||||||
|
message.warning('请输入规则名称');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
await saveMutation.mutateAsync({ name, mappings });
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
} 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>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default RuleEditor;
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { App, Button, Popconfirm, Space, Table, Upload } from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import { EyeOutlined, InboxOutlined, UploadOutlined } from '@ant-design/icons';
|
||||||
|
import api from '../../api';
|
||||||
|
import { message } from '../../ui/app-message';
|
||||||
|
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||||
|
import { usePermission } from '../../hooks/usePermission';
|
||||||
|
import { getErrorMessage } from '../../utils/error';
|
||||||
|
import { ATTACHMENT_CATEGORY_OPTIONS, formatFileSize } from './shared';
|
||||||
|
import type { AttachmentRecord, TabProps } from './shared';
|
||||||
|
|
||||||
|
export const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({
|
||||||
|
data,
|
||||||
|
studentId,
|
||||||
|
}) => {
|
||||||
|
const { modal } = App.useApp();
|
||||||
|
const { hasPermission } = usePermission();
|
||||||
|
const canPurgeArchive = hasPermission('archive:purge');
|
||||||
|
const [uploading, setUploading] = useState(false);
|
||||||
|
|
||||||
|
const deleteAttachmentMutation = useApiMutation(
|
||||||
|
async (attachmentId: number) => api.delete(`/archive/attachments/${attachmentId}`),
|
||||||
|
{ invalidate: [['archive', studentId]] },
|
||||||
|
);
|
||||||
|
const purgeAttachmentMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/archive/attachments/${id}/permanent`),
|
||||||
|
{ invalidate: [['archive', studentId]] },
|
||||||
|
);
|
||||||
|
const uploadAttachmentMutation = useApiMutation(
|
||||||
|
async (formData: FormData) =>
|
||||||
|
api.post(`/archive/${studentId}/attachments`, formData),
|
||||||
|
{ invalidate: [['archive', studentId]] },
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleDelete = async (attachmentId: number) => {
|
||||||
|
try {
|
||||||
|
await deleteAttachmentMutation.mutateAsync(attachmentId);
|
||||||
|
message.success('已归档');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePurge = (record: AttachmentRecord) => {
|
||||||
|
modal.confirm({
|
||||||
|
title: `永久删除附件「${record.fileName}」?`,
|
||||||
|
content: '删除后不可恢复,磁盘上的附件文件将被清除。确定继续?',
|
||||||
|
okText: '永久删除',
|
||||||
|
okButtonProps: { danger: true },
|
||||||
|
cancelText: '取消',
|
||||||
|
onOk: async () => {
|
||||||
|
try {
|
||||||
|
await purgeAttachmentMutation.mutateAsync(record.id);
|
||||||
|
message.success('已永久删除(不可恢复)');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const columns: ColumnsType<AttachmentRecord> = [
|
||||||
|
{
|
||||||
|
title: '类别',
|
||||||
|
dataIndex: 'category',
|
||||||
|
render: (v: string) => ATTACHMENT_CATEGORY_OPTIONS.find((o) => o.value === v)?.label || v,
|
||||||
|
},
|
||||||
|
{ title: '文件名', dataIndex: 'fileName' },
|
||||||
|
{ title: '大小', dataIndex: 'fileSize', render: formatFileSize },
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
render: (_: unknown, record: AttachmentRecord) => (
|
||||||
|
<Space>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
icon={<EyeOutlined />}
|
||||||
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
const blob = await api.get<Blob>(`/archive/${studentId}/attachments/${record.id}`, {
|
||||||
|
responseType: 'blob',
|
||||||
|
});
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
window.open(url, '_blank');
|
||||||
|
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||||
|
} catch (e: unknown) {
|
||||||
|
message.error(getErrorMessage(e, '查看失败'));
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
查看
|
||||||
|
</Button>
|
||||||
|
{hasPermission('student:edit') && record.status !== 'archived' ? (
|
||||||
|
<Popconfirm title="确定归档该附件?" onConfirm={() => handleDelete(record.id)}>
|
||||||
|
<Button size="small" danger icon={<InboxOutlined />}>
|
||||||
|
归档
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
) : null}
|
||||||
|
{record.status === 'archived' && canPurgeArchive ? (
|
||||||
|
<Button size="small" danger type="link" onClick={() => handlePurge(record)}>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{hasPermission('student:edit') ? (
|
||||||
|
<Upload
|
||||||
|
showUploadList={false}
|
||||||
|
customRequest={async (options) => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append(
|
||||||
|
'file',
|
||||||
|
options.file instanceof File
|
||||||
|
? options.file
|
||||||
|
: new File([options.file as Blob], 'attachment'),
|
||||||
|
);
|
||||||
|
setUploading(true);
|
||||||
|
try {
|
||||||
|
await uploadAttachmentMutation.mutateAsync(formData);
|
||||||
|
message.success('上传成功');
|
||||||
|
options.onSuccess?.({});
|
||||||
|
} catch (e) {
|
||||||
|
options.onError?.(e instanceof Error ? e : new Error('上传失败'));
|
||||||
|
} finally {
|
||||||
|
setUploading(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Button icon={<UploadOutlined />} loading={uploading}>
|
||||||
|
上传附件
|
||||||
|
</Button>
|
||||||
|
</Upload>
|
||||||
|
) : null}
|
||||||
|
<Table<AttachmentRecord>
|
||||||
|
columns={columns}
|
||||||
|
dataSource={data}
|
||||||
|
rowKey="id"
|
||||||
|
rowClassName={(record) => (record.status === 'archived' ? 'archived-row' : '')}
|
||||||
|
pagination={{
|
||||||
|
defaultPageSize: 15,
|
||||||
|
showSizeChanger: true,
|
||||||
|
pageSizeOptions: [15, 30, 50],
|
||||||
|
}}
|
||||||
|
style={{ marginTop: 16 }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import EditableCell from '../EditableCell';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 学生档案模块统一的可编辑单元格:
|
||||||
|
* 固定 student:edit 权限,配合各 Tab 的 saveCell 使用。
|
||||||
|
*/
|
||||||
|
export const EditableArchiveCell = <R extends { id: number }>({
|
||||||
|
value,
|
||||||
|
field,
|
||||||
|
record,
|
||||||
|
editor,
|
||||||
|
min,
|
||||||
|
max,
|
||||||
|
required,
|
||||||
|
options,
|
||||||
|
onSave,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
value: unknown;
|
||||||
|
field: string;
|
||||||
|
record: R;
|
||||||
|
editor?: React.ComponentProps<typeof EditableCell>['editor'];
|
||||||
|
min?: number;
|
||||||
|
max?: number;
|
||||||
|
required?: boolean;
|
||||||
|
options?: Array<{ value: string | number; label: string }>;
|
||||||
|
onSave: (record: R, field: string, value: unknown) => Promise<void> | void;
|
||||||
|
children?: React.ReactNode;
|
||||||
|
}) => (
|
||||||
|
<EditableCell
|
||||||
|
value={value}
|
||||||
|
editor={editor}
|
||||||
|
min={min}
|
||||||
|
max={max}
|
||||||
|
required={required}
|
||||||
|
options={options}
|
||||||
|
permission="student:edit"
|
||||||
|
onSave={async (next) => {
|
||||||
|
await onSave(record, field, next);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children ?? String(value ?? '-')}
|
||||||
|
</EditableCell>
|
||||||
|
);
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { App, Button, DatePicker, Form, Input, Modal, Select, Table, Tag } from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import { PlusOutlined } from '@ant-design/icons';
|
||||||
|
import api from '../../api';
|
||||||
|
import { message } from '../../ui/app-message';
|
||||||
|
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||||
|
import { usePermission } from '../../hooks/usePermission';
|
||||||
|
import PermissionButton from '../PermissionButton';
|
||||||
|
import { EditableArchiveCell } from './EditableArchiveCell';
|
||||||
|
import { CLASS_TYPE_OPTIONS, COURSE_CATEGORY_OPTIONS, ENROLLMENT_STATUS_MAP, formatEnrollmentDisplayName, getClassTypeLabel, getCourseCategoryLabel, getEnrollmentStatus } from './shared';
|
||||||
|
import type { EnrollmentRecord, TabProps } from './shared';
|
||||||
|
|
||||||
|
const ENROLLMENT_FIELDS = {
|
||||||
|
courseCategory: 'courseCategory',
|
||||||
|
classType: 'classType',
|
||||||
|
className: 'className',
|
||||||
|
headTeacher: 'headTeacher',
|
||||||
|
subjectTeacher: 'subjectTeacher',
|
||||||
|
startDate: 'startDate',
|
||||||
|
endDate: 'endDate',
|
||||||
|
status: 'status',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
|
||||||
|
data,
|
||||||
|
studentId,
|
||||||
|
}) => {
|
||||||
|
const { modal } = App.useApp();
|
||||||
|
const { hasPermission } = usePermission();
|
||||||
|
const canPurgeArchive = hasPermission('archive:purge');
|
||||||
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
|
const [form] = Form.useForm();
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
const addEnrollmentMutation = useApiMutation(
|
||||||
|
async (payload: Record<string, unknown>) =>
|
||||||
|
api.post(`/archive/${studentId}/enrollments`, payload),
|
||||||
|
{ invalidate: [['archive', studentId]] },
|
||||||
|
);
|
||||||
|
const saveEnrollmentCellMutation = useApiMutation(
|
||||||
|
async ({ id, field, value }: { id: number; field: string; value: unknown }) =>
|
||||||
|
api.put(`/archive/enrollments/${id}`, { [field]: value }),
|
||||||
|
{ invalidate: [['archive', studentId]] },
|
||||||
|
);
|
||||||
|
const purgeEnrollmentMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/archive/enrollments/${id}/permanent`),
|
||||||
|
{ invalidate: [['archive', studentId]] },
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleAdd = async () => {
|
||||||
|
try {
|
||||||
|
const values = await form.validateFields();
|
||||||
|
setSaving(true);
|
||||||
|
await addEnrollmentMutation.mutateAsync({
|
||||||
|
...values,
|
||||||
|
startDate: values.startDate?.format('YYYY-MM-DD'),
|
||||||
|
endDate: values.endDate?.format('YYYY-MM-DD'),
|
||||||
|
});
|
||||||
|
message.success('报读记录已添加');
|
||||||
|
setModalOpen(false);
|
||||||
|
form.resetFields();
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveCell = async (record: EnrollmentRecord, field: string, value: unknown) => {
|
||||||
|
try {
|
||||||
|
await saveEnrollmentCellMutation.mutateAsync({ id: record.id, field, value });
|
||||||
|
message.success('报读记录已保存');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePurge = (record: EnrollmentRecord) => {
|
||||||
|
modal.confirm({
|
||||||
|
title: `永久删除报读记录(${formatEnrollmentDisplayName(record)})?`,
|
||||||
|
content: '删除后不可恢复,被考试成绩引用时将无法删除。确定继续?',
|
||||||
|
okText: '永久删除',
|
||||||
|
okButtonProps: { danger: true },
|
||||||
|
cancelText: '取消',
|
||||||
|
onOk: async () => {
|
||||||
|
try {
|
||||||
|
await purgeEnrollmentMutation.mutateAsync(record.id);
|
||||||
|
message.success('已永久删除(不可恢复)');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const columns: ColumnsType<EnrollmentRecord> = [
|
||||||
|
{
|
||||||
|
title: '课程类别',
|
||||||
|
dataIndex: 'courseCategory',
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={ENROLLMENT_FIELDS.courseCategory} record={r} editor="select" options={COURSE_CATEGORY_OPTIONS} onSave={saveCell}>
|
||||||
|
{getCourseCategoryLabel(v)}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '班型',
|
||||||
|
dataIndex: 'classType',
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={ENROLLMENT_FIELDS.classType} record={r} editor="select" options={CLASS_TYPE_OPTIONS} onSave={saveCell}>
|
||||||
|
{getClassTypeLabel(v)}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '班级名称',
|
||||||
|
dataIndex: 'className',
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={ENROLLMENT_FIELDS.className} record={r} onSave={saveCell}>
|
||||||
|
{v || '-'}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '班主任',
|
||||||
|
dataIndex: 'headTeacher',
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={ENROLLMENT_FIELDS.headTeacher} record={r} onSave={saveCell}>
|
||||||
|
{v || '-'}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '任课教师',
|
||||||
|
dataIndex: 'subjectTeacher',
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={ENROLLMENT_FIELDS.subjectTeacher} record={r} onSave={saveCell}>
|
||||||
|
{v || '-'}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '开始日期',
|
||||||
|
dataIndex: 'startDate',
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={ENROLLMENT_FIELDS.startDate} record={r} editor="date" onSave={saveCell}>
|
||||||
|
{v || '-'}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '结束日期',
|
||||||
|
dataIndex: 'endDate',
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={ENROLLMENT_FIELDS.endDate} record={r} editor="date" onSave={saveCell}>
|
||||||
|
{v || '-'}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'status',
|
||||||
|
render: (v: string, r) => {
|
||||||
|
const status = getEnrollmentStatus(v);
|
||||||
|
return (
|
||||||
|
<EditableArchiveCell
|
||||||
|
value={v}
|
||||||
|
field={ENROLLMENT_FIELDS.status}
|
||||||
|
record={r}
|
||||||
|
editor="select"
|
||||||
|
options={Object.entries(ENROLLMENT_STATUS_MAP).map(([value, item]) => ({
|
||||||
|
value,
|
||||||
|
label: item.text,
|
||||||
|
}))}
|
||||||
|
onSave={saveCell}
|
||||||
|
>
|
||||||
|
<Tag color={status.color}>{status.text}</Tag>
|
||||||
|
</EditableArchiveCell>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
render: (_: unknown, r: EnrollmentRecord) =>
|
||||||
|
r.status === 'archived' && canPurgeArchive ? (
|
||||||
|
<Button size="small" danger type="link" onClick={() => handlePurge(r)}>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
) : null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<PermissionButton
|
||||||
|
permission="student:edit"
|
||||||
|
icon={<PlusOutlined />}
|
||||||
|
type="primary"
|
||||||
|
onClick={() => {
|
||||||
|
form.resetFields();
|
||||||
|
setModalOpen(true);
|
||||||
|
}}
|
||||||
|
style={{ marginBottom: 16 }}
|
||||||
|
>
|
||||||
|
添加报读记录
|
||||||
|
</PermissionButton>
|
||||||
|
<Table<EnrollmentRecord>
|
||||||
|
columns={columns}
|
||||||
|
dataSource={data}
|
||||||
|
rowKey="id"
|
||||||
|
rowClassName={(record) => (record.status === 'archived' ? 'archived-row' : '')}
|
||||||
|
pagination={{
|
||||||
|
defaultPageSize: 15,
|
||||||
|
showSizeChanger: true,
|
||||||
|
pageSizeOptions: [15, 30, 50],
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Modal
|
||||||
|
title="添加报读记录"
|
||||||
|
open={modalOpen && hasPermission('student:edit')}
|
||||||
|
onOk={hasPermission('student:edit') ? handleAdd : undefined}
|
||||||
|
onCancel={() => setModalOpen(false)}
|
||||||
|
confirmLoading={saving}
|
||||||
|
>
|
||||||
|
<Form form={form} layout="vertical">
|
||||||
|
<Form.Item
|
||||||
|
name="courseCategory"
|
||||||
|
label="课程类别"
|
||||||
|
rules={[{ required: true, message: '请选择课程类别' }]}
|
||||||
|
>
|
||||||
|
<Select options={COURSE_CATEGORY_OPTIONS} placeholder="请选择" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="classType"
|
||||||
|
label="班型"
|
||||||
|
rules={[{ required: true, message: '请选择班型' }]}
|
||||||
|
>
|
||||||
|
<Select options={CLASS_TYPE_OPTIONS} placeholder="请选择" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="className" label="班级名称">
|
||||||
|
<Input placeholder="如:2024届冲刺班" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="headTeacher" label="班主任">
|
||||||
|
<Input placeholder="班主任姓名" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="subjectTeacher" label="任课教师">
|
||||||
|
<Input placeholder="任课教师姓名" />
|
||||||
|
</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>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { App, Button, DatePicker, Form, Input, InputNumber, Modal, Select, Table } from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import { PlusOutlined } from '@ant-design/icons';
|
||||||
|
import api from '../../api';
|
||||||
|
import { message } from '../../ui/app-message';
|
||||||
|
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||||
|
import { usePermission } from '../../hooks/usePermission';
|
||||||
|
import PermissionButton from '../PermissionButton';
|
||||||
|
import { EditableArchiveCell } from './EditableArchiveCell';
|
||||||
|
import { EXAM_TYPE_OPTIONS, formatEnrollmentDisplayName, getClassTypeLabel } from './shared';
|
||||||
|
import type { EnrollmentRecord, ExamScoreRecord, TabProps } from './shared';
|
||||||
|
|
||||||
|
const EXAM_SCORE_FIELDS = {
|
||||||
|
examType: 'examType',
|
||||||
|
examName: 'examName',
|
||||||
|
subject: 'subject',
|
||||||
|
score: 'score',
|
||||||
|
classAvg: 'classAvg',
|
||||||
|
rank: 'rank',
|
||||||
|
examDate: 'examDate',
|
||||||
|
enrollmentId: 'enrollmentId',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const ExamScoresTab: React.FC<
|
||||||
|
TabProps & { data: ExamScoreRecord[]; enrollments: EnrollmentRecord[] }
|
||||||
|
> = ({ data, studentId, enrollments }) => {
|
||||||
|
const { modal } = App.useApp();
|
||||||
|
const { hasPermission } = usePermission();
|
||||||
|
const canPurgeArchive = hasPermission('archive:purge');
|
||||||
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
|
const [form] = Form.useForm();
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
const addExamScoreMutation = useApiMutation(
|
||||||
|
async (payload: Record<string, unknown>) =>
|
||||||
|
api.post(`/archive/${studentId}/exam-scores`, payload),
|
||||||
|
{ invalidate: [['archive', studentId]] },
|
||||||
|
);
|
||||||
|
const saveExamScoreCellMutation = useApiMutation(
|
||||||
|
async ({ id, field, value }: { id: number; field: string; value: unknown }) =>
|
||||||
|
api.put(`/archive/exam-scores/${id}`, { [field]: value }),
|
||||||
|
{ invalidate: [['archive', studentId]] },
|
||||||
|
);
|
||||||
|
const purgeExamScoreMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/archive/exam-scores/${id}/permanent`),
|
||||||
|
{ invalidate: [['archive', studentId]] },
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleAdd = async () => {
|
||||||
|
try {
|
||||||
|
const values = await form.validateFields();
|
||||||
|
setSaving(true);
|
||||||
|
await addExamScoreMutation.mutateAsync({
|
||||||
|
...values,
|
||||||
|
examDate: values.examDate?.format('YYYY-MM-DD'),
|
||||||
|
});
|
||||||
|
message.success('考试成绩已添加');
|
||||||
|
setModalOpen(false);
|
||||||
|
form.resetFields();
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveCell = async (record: ExamScoreRecord, field: string, value: unknown) => {
|
||||||
|
try {
|
||||||
|
await saveExamScoreCellMutation.mutateAsync({ id: record.id, field, value });
|
||||||
|
message.success('考试成绩已保存');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePurge = (record: ExamScoreRecord) => {
|
||||||
|
modal.confirm({
|
||||||
|
title: `永久删除考试成绩(${record.examName || record.subject || `记录${record.id}`})?`,
|
||||||
|
content: '删除后不可恢复,成绩记录将被物理删除。确定继续?',
|
||||||
|
okText: '永久删除',
|
||||||
|
okButtonProps: { danger: true },
|
||||||
|
cancelText: '取消',
|
||||||
|
onOk: async () => {
|
||||||
|
try {
|
||||||
|
await purgeExamScoreMutation.mutateAsync(record.id);
|
||||||
|
message.success('已永久删除(不可恢复)');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const columns: ColumnsType<ExamScoreRecord> = [
|
||||||
|
{
|
||||||
|
title: '考试类型',
|
||||||
|
dataIndex: 'examType',
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={EXAM_SCORE_FIELDS.examType} record={r} editor="select" options={EXAM_TYPE_OPTIONS} onSave={saveCell}>
|
||||||
|
{EXAM_TYPE_OPTIONS.find((o) => o.value === v)?.label || v}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '考试名称',
|
||||||
|
dataIndex: 'examName',
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={EXAM_SCORE_FIELDS.examName} record={r} onSave={saveCell}>
|
||||||
|
{v || '-'}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '科目',
|
||||||
|
dataIndex: 'subject',
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={EXAM_SCORE_FIELDS.subject} record={r} required onSave={saveCell}>
|
||||||
|
{v}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '成绩',
|
||||||
|
dataIndex: 'score',
|
||||||
|
render: (v: number | null, r) => (
|
||||||
|
<EditableArchiveCell value={v ?? undefined} field={EXAM_SCORE_FIELDS.score} record={r} editor="number" min={0} onSave={saveCell}>
|
||||||
|
{v ?? '-'}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '班级均分',
|
||||||
|
dataIndex: 'classAvg',
|
||||||
|
render: (v: number | undefined, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={EXAM_SCORE_FIELDS.classAvg} record={r} editor="number" min={0} onSave={saveCell}>
|
||||||
|
{v !== undefined ? v : '-'}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '排名',
|
||||||
|
dataIndex: 'rank',
|
||||||
|
render: (v: number | undefined, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={EXAM_SCORE_FIELDS.rank} record={r} editor="number" min={1} onSave={saveCell}>
|
||||||
|
{v !== undefined ? v : '-'}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '考试日期',
|
||||||
|
dataIndex: 'examDate',
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={EXAM_SCORE_FIELDS.examDate} record={r} editor="date" onSave={saveCell}>
|
||||||
|
{v || '-'}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '关联报读',
|
||||||
|
dataIndex: 'enrollmentId',
|
||||||
|
render: (v: number | undefined, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={EXAM_SCORE_FIELDS.enrollmentId} record={r} editor="select" options={enrollments.map((item) => ({ value: item.id, label: formatEnrollmentDisplayName(item), }))} onSave={saveCell}>
|
||||||
|
{(() => {
|
||||||
|
if (r.examId) return r.exam?.class?.name || '-';
|
||||||
|
if (v === undefined) return '-';
|
||||||
|
const enr = enrollments.find((e) => e.id === v);
|
||||||
|
return enr ? formatEnrollmentDisplayName(enr) : String(v);
|
||||||
|
})()}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
render: (_: unknown, r: ExamScoreRecord) =>
|
||||||
|
r.status === 'archived' && canPurgeArchive ? (
|
||||||
|
<Button size="small" danger type="link" onClick={() => handlePurge(r)}>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
) : null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<PermissionButton
|
||||||
|
permission="student:edit"
|
||||||
|
icon={<PlusOutlined />}
|
||||||
|
type="primary"
|
||||||
|
onClick={() => {
|
||||||
|
form.resetFields();
|
||||||
|
setModalOpen(true);
|
||||||
|
}}
|
||||||
|
style={{ marginBottom: 16 }}
|
||||||
|
>
|
||||||
|
添加考试成绩
|
||||||
|
</PermissionButton>
|
||||||
|
<Table<ExamScoreRecord>
|
||||||
|
columns={columns}
|
||||||
|
dataSource={data}
|
||||||
|
rowKey="id"
|
||||||
|
rowClassName={(record) => (record.status === 'archived' ? 'archived-row' : '')}
|
||||||
|
pagination={{
|
||||||
|
defaultPageSize: 15,
|
||||||
|
showSizeChanger: true,
|
||||||
|
pageSizeOptions: [15, 30, 50],
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Modal
|
||||||
|
title="添加考试成绩"
|
||||||
|
open={modalOpen && hasPermission('student:edit')}
|
||||||
|
onOk={hasPermission('student:edit') ? handleAdd : undefined}
|
||||||
|
onCancel={() => setModalOpen(false)}
|
||||||
|
confirmLoading={saving}
|
||||||
|
>
|
||||||
|
<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="考试名称">
|
||||||
|
<Input placeholder="如:2024第一次月考" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="subject"
|
||||||
|
label="科目"
|
||||||
|
rules={[{ required: true, message: '请输入科目' }]}
|
||||||
|
>
|
||||||
|
<Input placeholder="如:数学" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="score" label="成绩" rules={[{ required: true, message: '请输入成绩' }]}>
|
||||||
|
<InputNumber min={0} style={{ width: '100%' }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="classAvg" label="班级均分">
|
||||||
|
<InputNumber min={0} style={{ width: '100%' }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="rank" label="排名">
|
||||||
|
<InputNumber min={1} style={{ width: '100%' }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="examDate" label="考试日期">
|
||||||
|
<DatePicker style={{ width: '100%' }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="enrollmentId" label="关联报读">
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
placeholder="选择关联的报读记录"
|
||||||
|
options={enrollments.map((e) => ({
|
||||||
|
value: e.id,
|
||||||
|
label: `${formatEnrollmentDisplayName(e)}(${getClassTypeLabel(e.classType)})`,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
215
apps/admin/src/components/StudentProfileContent/LearningTab.tsx
Normal file
215
apps/admin/src/components/StudentProfileContent/LearningTab.tsx
Normal file
@@ -0,0 +1,215 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { App, Button, DatePicker, Form, Input, Modal, Select, Table } from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import { PlusOutlined } from '@ant-design/icons';
|
||||||
|
import api from '../../api';
|
||||||
|
import { message } from '../../ui/app-message';
|
||||||
|
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||||
|
import { usePermission } from '../../hooks/usePermission';
|
||||||
|
import PermissionButton from '../PermissionButton';
|
||||||
|
import { EditableArchiveCell } from './EditableArchiveCell';
|
||||||
|
import { RECORD_TYPE_OPTIONS } from './shared';
|
||||||
|
import type { LearningRecord, TabProps } from './shared';
|
||||||
|
|
||||||
|
const LEARNING_FIELDS = {
|
||||||
|
recordDate: 'recordDate',
|
||||||
|
recordType: 'recordType',
|
||||||
|
content: 'content',
|
||||||
|
followUpMethod: 'followUpMethod',
|
||||||
|
nextStep: 'nextStep',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({
|
||||||
|
data,
|
||||||
|
studentId,
|
||||||
|
}) => {
|
||||||
|
const { modal } = App.useApp();
|
||||||
|
const { hasPermission } = usePermission();
|
||||||
|
const canPurgeArchive = hasPermission('archive:purge');
|
||||||
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
|
const [form] = Form.useForm();
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
const addLearningMutation = useApiMutation(
|
||||||
|
async (payload: Record<string, unknown>) =>
|
||||||
|
api.post(`/archive/${studentId}/learning-records`, payload),
|
||||||
|
{ invalidate: [['archive', studentId]] },
|
||||||
|
);
|
||||||
|
const saveLearningCellMutation = useApiMutation(
|
||||||
|
async ({ id, field, value }: { id: number; field: string; value: unknown }) =>
|
||||||
|
api.put(`/archive/learning-records/${id}`, { [field]: value }),
|
||||||
|
{ invalidate: [['archive', studentId]] },
|
||||||
|
);
|
||||||
|
const purgeLearningMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/archive/learning-records/${id}/permanent`),
|
||||||
|
{ invalidate: [['archive', studentId]] },
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleAdd = async () => {
|
||||||
|
try {
|
||||||
|
const values = await form.validateFields();
|
||||||
|
setSaving(true);
|
||||||
|
await addLearningMutation.mutateAsync({
|
||||||
|
...values,
|
||||||
|
recordDate: values.recordDate?.format('YYYY-MM-DD'),
|
||||||
|
});
|
||||||
|
message.success('学情记录已添加');
|
||||||
|
setModalOpen(false);
|
||||||
|
form.resetFields();
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveCell = async (record: LearningRecord, field: string, value: unknown) => {
|
||||||
|
try {
|
||||||
|
await saveLearningCellMutation.mutateAsync({ id: record.id, field, value });
|
||||||
|
message.success('学情记录已保存');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePurge = (record: LearningRecord) => {
|
||||||
|
modal.confirm({
|
||||||
|
title: `永久删除学情记录(${record.recordType || `记录${record.id}`})?`,
|
||||||
|
content: '删除后不可恢复,学习记录将被物理删除。确定继续?',
|
||||||
|
okText: '永久删除',
|
||||||
|
okButtonProps: { danger: true },
|
||||||
|
cancelText: '取消',
|
||||||
|
onOk: async () => {
|
||||||
|
try {
|
||||||
|
await purgeLearningMutation.mutateAsync(record.id);
|
||||||
|
message.success('已永久删除(不可恢复)');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const columns: ColumnsType<LearningRecord> = [
|
||||||
|
{
|
||||||
|
title: '记录日期',
|
||||||
|
dataIndex: 'recordDate',
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={LEARNING_FIELDS.recordDate} record={r} editor="date" onSave={saveCell}>
|
||||||
|
{v}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '记录类型',
|
||||||
|
dataIndex: 'recordType',
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={LEARNING_FIELDS.recordType} record={r} editor="select" options={RECORD_TYPE_OPTIONS} onSave={saveCell}>
|
||||||
|
{RECORD_TYPE_OPTIONS.find((o) => o.value === v)?.label || v}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '内容',
|
||||||
|
dataIndex: 'content',
|
||||||
|
ellipsis: true,
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={LEARNING_FIELDS.content} record={r} editor="textarea" onSave={saveCell}>
|
||||||
|
{v}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '跟进方式',
|
||||||
|
dataIndex: 'followUpMethod',
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={LEARNING_FIELDS.followUpMethod} record={r} onSave={saveCell}>
|
||||||
|
{v || '-'}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '下一步计划',
|
||||||
|
dataIndex: 'nextStep',
|
||||||
|
render: (v: string, r) => (
|
||||||
|
<EditableArchiveCell value={v} field={LEARNING_FIELDS.nextStep} record={r} editor="textarea" onSave={saveCell}>
|
||||||
|
{v || '-'}
|
||||||
|
</EditableArchiveCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
render: (_: unknown, r: LearningRecord) =>
|
||||||
|
r.status === 'archived' && canPurgeArchive ? (
|
||||||
|
<Button size="small" danger type="link" onClick={() => handlePurge(r)}>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
) : null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<PermissionButton
|
||||||
|
permission="student:edit"
|
||||||
|
icon={<PlusOutlined />}
|
||||||
|
type="primary"
|
||||||
|
onClick={() => {
|
||||||
|
form.resetFields();
|
||||||
|
setModalOpen(true);
|
||||||
|
}}
|
||||||
|
style={{ marginBottom: 16 }}
|
||||||
|
>
|
||||||
|
添加学情记录
|
||||||
|
</PermissionButton>
|
||||||
|
<Table<LearningRecord>
|
||||||
|
columns={columns}
|
||||||
|
dataSource={data}
|
||||||
|
rowKey="id"
|
||||||
|
rowClassName={(record) => (record.status === 'archived' ? 'archived-row' : '')}
|
||||||
|
pagination={{
|
||||||
|
defaultPageSize: 15,
|
||||||
|
showSizeChanger: true,
|
||||||
|
pageSizeOptions: [15, 30, 50],
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Modal
|
||||||
|
title="添加学情记录"
|
||||||
|
open={modalOpen && hasPermission('student:edit')}
|
||||||
|
onOk={hasPermission('student:edit') ? handleAdd : undefined}
|
||||||
|
onCancel={() => setModalOpen(false)}
|
||||||
|
confirmLoading={saving}
|
||||||
|
>
|
||||||
|
<Form form={form} layout="vertical">
|
||||||
|
<Form.Item
|
||||||
|
name="recordDate"
|
||||||
|
label="记录日期"
|
||||||
|
rules={[{ required: true, message: '请选择日期' }]}
|
||||||
|
>
|
||||||
|
<DatePicker style={{ width: '100%' }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="recordType"
|
||||||
|
label="记录类型"
|
||||||
|
rules={[{ required: true, message: '请选择记录类型' }]}
|
||||||
|
>
|
||||||
|
<Select options={RECORD_TYPE_OPTIONS} placeholder="请选择" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="content"
|
||||||
|
label="内容"
|
||||||
|
rules={[{ required: true, message: '请输入内容' }]}
|
||||||
|
>
|
||||||
|
<Input.TextArea rows={4} placeholder="请记录学情内容" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="followUpMethod" label="跟进方式">
|
||||||
|
<Input placeholder="如:电话、微信、面谈" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="nextStep" label="下一步计划">
|
||||||
|
<Input placeholder="后续跟进计划" />
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
File diff suppressed because it is too large
Load Diff
216
apps/admin/src/components/StudentProfileContent/shared.ts
Normal file
216
apps/admin/src/components/StudentProfileContent/shared.ts
Normal file
@@ -0,0 +1,216 @@
|
|||||||
|
export interface StudentInfo {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
phone: string;
|
||||||
|
idNumber: string;
|
||||||
|
studentNo: string;
|
||||||
|
gender?: string;
|
||||||
|
ethnicity?: string;
|
||||||
|
emergencyContact?: string;
|
||||||
|
emergencyPhone?: string;
|
||||||
|
organizationId?: number;
|
||||||
|
organization?: { id?: number; name?: string } | null;
|
||||||
|
supervisor?: string;
|
||||||
|
status: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProfileData {
|
||||||
|
targetCollege?: string;
|
||||||
|
targetMajor?: string;
|
||||||
|
collegeSchool?: string;
|
||||||
|
collegeMajor?: string;
|
||||||
|
subjectDirection?: string;
|
||||||
|
grade?: string;
|
||||||
|
profileDate?: string;
|
||||||
|
notes?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EnrollmentRecord {
|
||||||
|
id: number;
|
||||||
|
courseCategory: string;
|
||||||
|
classType: string;
|
||||||
|
className?: string;
|
||||||
|
headTeacher?: string;
|
||||||
|
subjectTeacher?: string;
|
||||||
|
startDate?: string;
|
||||||
|
endDate?: string;
|
||||||
|
status: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ExamScoreRecord {
|
||||||
|
id: number;
|
||||||
|
status?: string;
|
||||||
|
examId?: number;
|
||||||
|
exam?: { class?: { name?: string } };
|
||||||
|
examType: string;
|
||||||
|
examName?: string;
|
||||||
|
subject: string;
|
||||||
|
score: number | null;
|
||||||
|
classAvg?: number;
|
||||||
|
rank?: number;
|
||||||
|
examDate?: string;
|
||||||
|
enrollmentId?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LearningRecord {
|
||||||
|
id: number;
|
||||||
|
status?: string;
|
||||||
|
recordDate: string;
|
||||||
|
recordType: string;
|
||||||
|
content: string;
|
||||||
|
followUpMethod?: string;
|
||||||
|
nextStep?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ResultData {
|
||||||
|
cultureFinalScore?: number;
|
||||||
|
professionalFinalScore?: number;
|
||||||
|
admissionStatus?: string;
|
||||||
|
admittedCollege?: string;
|
||||||
|
admittedMajor?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AttachmentRecord {
|
||||||
|
id: number;
|
||||||
|
status?: string;
|
||||||
|
category: string;
|
||||||
|
fileName: string;
|
||||||
|
fileSize: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AttendanceRecordItem {
|
||||||
|
id: number;
|
||||||
|
attendanceDate: string;
|
||||||
|
session: string;
|
||||||
|
status: string;
|
||||||
|
source?: string;
|
||||||
|
remark?: string | null;
|
||||||
|
punchTime?: string | null;
|
||||||
|
punchDeviceName?: string | null;
|
||||||
|
punchDeviceId?: string | null;
|
||||||
|
schedule?: { subject?: string } | null;
|
||||||
|
class?: { name?: string } | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StudentProfileAggregate {
|
||||||
|
student: StudentInfo;
|
||||||
|
profile: ProfileData | null;
|
||||||
|
enrollments: EnrollmentRecord[];
|
||||||
|
examScores: ExamScoreRecord[];
|
||||||
|
learningRecords: LearningRecord[];
|
||||||
|
result: ResultData | null;
|
||||||
|
attachments: AttachmentRecord[];
|
||||||
|
attendances: AttendanceRecordItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StudentProfileContentProps {
|
||||||
|
studentId: number;
|
||||||
|
inDrawer?: boolean;
|
||||||
|
onClose?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ADMISSION_STATUS_MAP: Record<string, { text: string; color: string }> = {
|
||||||
|
admitted: { text: '已录取', color: 'green' },
|
||||||
|
pending: { text: '待录取', color: 'orange' },
|
||||||
|
rejected: { text: '未录取', color: 'red' },
|
||||||
|
withdrawn: { text: '放弃', color: '#999' },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const EXAM_TYPE_OPTIONS = [
|
||||||
|
{ value: 'monthly', label: '月考' },
|
||||||
|
{ value: 'midterm', label: '期中' },
|
||||||
|
{ value: 'final', label: '期末' },
|
||||||
|
{ value: 'mock', label: '模拟考' },
|
||||||
|
{ value: 'entrance', label: '入学测试' },
|
||||||
|
{ value: 'other', label: '其他' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const RECORD_TYPE_OPTIONS = [
|
||||||
|
{ value: 'study_feedback', label: '学习反馈' },
|
||||||
|
{ value: 'parent_communication', label: '家长沟通' },
|
||||||
|
{ value: 'behavior_note', label: '行为记录' },
|
||||||
|
{ value: 'meeting', label: '会议记录' },
|
||||||
|
{ value: 'other', label: '其他' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const ENROLLMENT_STATUS_MAP: Record<string, { text: string; color: string }> = {
|
||||||
|
active: { text: '报读中', color: 'green' },
|
||||||
|
completed: { text: '已结课', color: 'blue' },
|
||||||
|
withdrawn: { text: '已退训', color: 'red' },
|
||||||
|
archived: { text: '已归档', color: '#999' },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const COURSE_CATEGORY_OPTIONS = [
|
||||||
|
{ value: 'culture', label: '文化课' },
|
||||||
|
{ value: 'professional', label: '专业课' },
|
||||||
|
{ value: 'comprehensive', label: '综合' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const CLASS_TYPE_OPTIONS = [
|
||||||
|
{ value: 'one_on_one', label: '一对一' },
|
||||||
|
{ value: 'small_group', label: '小班' },
|
||||||
|
{ value: 'large_class', label: '大班' },
|
||||||
|
{ value: 'online', label: '线上' },
|
||||||
|
{ value: 'offline', label: '线下' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const getOptionLabel = (
|
||||||
|
options: Array<{ value: string; label: string }>,
|
||||||
|
value?: string | null,
|
||||||
|
): string => {
|
||||||
|
if (!value) return '-';
|
||||||
|
return options.find((option) => option.value === value)?.label || value;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getCourseCategoryLabel = (value?: string | null): string =>
|
||||||
|
getOptionLabel(COURSE_CATEGORY_OPTIONS, value);
|
||||||
|
|
||||||
|
export const getClassTypeLabel = (value?: string | null): string =>
|
||||||
|
getOptionLabel(CLASS_TYPE_OPTIONS, value);
|
||||||
|
|
||||||
|
export const getEnrollmentStatus = (value?: string | null): { text: string; color: string } => {
|
||||||
|
if (!value) return { text: '-', color: 'default' };
|
||||||
|
return ENROLLMENT_STATUS_MAP[value] || { text: value, color: 'default' };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const formatEnrollmentDisplayName = (enrollment: EnrollmentRecord): string =>
|
||||||
|
enrollment.className ||
|
||||||
|
(enrollment.courseCategory
|
||||||
|
? getCourseCategoryLabel(enrollment.courseCategory)
|
||||||
|
: String(enrollment.id));
|
||||||
|
|
||||||
|
export const ATTACHMENT_CATEGORY_OPTIONS = [
|
||||||
|
{ value: 'id_card', label: '身份证' },
|
||||||
|
{ value: 'transcript', label: '成绩单' },
|
||||||
|
{ value: 'certificate', label: '证书' },
|
||||||
|
{ value: 'contract', label: '合同' },
|
||||||
|
{ value: 'photo', label: '照片' },
|
||||||
|
{ value: 'other', label: '其他' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const formatFileSize = (bytes: number): string => {
|
||||||
|
if (bytes < 1024) return `${bytes} B`;
|
||||||
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||||
|
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ATTENDANCE_STATUS_MAP: Record<string, { text: string; color: string }> = {
|
||||||
|
present: { text: '出勤', color: 'green' },
|
||||||
|
late: { text: '迟到', color: 'orange' },
|
||||||
|
absent: { text: '缺勤', color: 'red' },
|
||||||
|
leave: { text: '请假', color: 'blue' },
|
||||||
|
pending: { text: '待确认', color: 'default' },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const SESSION_LABELS: Record<string, string> = {
|
||||||
|
morning_reading: '早自习',
|
||||||
|
morning: '上午',
|
||||||
|
afternoon: '下午',
|
||||||
|
evening_study: '晚自习',
|
||||||
|
night_check: '晚寝',
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface TabProps {
|
||||||
|
studentId: number;
|
||||||
|
onRefresh: () => void;
|
||||||
|
}
|
||||||
39
apps/admin/src/hooks/useApiMutation.ts
Normal file
39
apps/admin/src/hooks/useApiMutation.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { useMutation, useQueryClient, type QueryKey } from '@tanstack/react-query';
|
||||||
|
import { message } from '../ui/app-message';
|
||||||
|
import { getErrorMessage } from '../utils/error';
|
||||||
|
|
||||||
|
interface UseApiMutationOptions<TData, TVars> {
|
||||||
|
/** 成功后自动失效的查询 key(触发列表/详情刷新) */
|
||||||
|
invalidate?: QueryKey[];
|
||||||
|
/** 成功后回调(例如关闭弹窗) */
|
||||||
|
onSuccess?: (data: TData, vars: TVars) => void;
|
||||||
|
/** 失败回调;默认统一用 getErrorMessage 弹错误提示 */
|
||||||
|
onError?: (error: unknown) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* useMutation 的轻量封装:统一错误提示 + 成功后 invalidateQueries,
|
||||||
|
* 消除手写 `await api.xxx(); await fetchData();` 样板。
|
||||||
|
*/
|
||||||
|
export function useApiMutation<TData = unknown, TVars = void>(
|
||||||
|
mutationFn: (vars: TVars) => Promise<TData>,
|
||||||
|
options: UseApiMutationOptions<TData, TVars> = {},
|
||||||
|
) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
return useMutation<TData, Error, TVars>({
|
||||||
|
mutationFn,
|
||||||
|
onSuccess: (data, vars) => {
|
||||||
|
for (const key of options.invalidate ?? []) {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: key });
|
||||||
|
}
|
||||||
|
options.onSuccess?.(data, vars);
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
if (options.onError) {
|
||||||
|
options.onError(error);
|
||||||
|
} else {
|
||||||
|
message.error(getErrorMessage(error));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,31 +1,31 @@
|
|||||||
import { useCallback, useEffect, useState } from 'react';
|
import { useCallback } from 'react';
|
||||||
import { PERMISSIONS_UPDATED_EVENT, readPermissions } from '../auth/permission-store';
|
import { usePermissionStore } from '../store/permission/permissionStore';
|
||||||
|
|
||||||
export function usePermission() {
|
export function usePermission() {
|
||||||
const [permissions, setPermissions] = useState<string[]>(readPermissions);
|
const permissions = usePermissionStore((state) => state.permissions);
|
||||||
|
const permissionStatus = usePermissionStore((state) => state.status);
|
||||||
useEffect(() => {
|
const permissionsReady = permissionStatus === 'ready';
|
||||||
const refresh = () => setPermissions(readPermissions());
|
|
||||||
window.addEventListener(PERMISSIONS_UPDATED_EVENT, refresh);
|
|
||||||
window.addEventListener('storage', refresh);
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener(PERMISSIONS_UPDATED_EVENT, refresh);
|
|
||||||
window.removeEventListener('storage', refresh);
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const hasPermission = useCallback(
|
const hasPermission = useCallback(
|
||||||
(code: string): boolean => permissions.includes(code),
|
(code: string): boolean => permissionsReady && permissions.includes(code),
|
||||||
[permissions],
|
[permissions, permissionsReady],
|
||||||
);
|
);
|
||||||
const hasAnyPermission = useCallback(
|
const hasAnyPermission = useCallback(
|
||||||
(...codes: string[]): boolean => codes.some((code) => permissions.includes(code)),
|
(...codes: string[]): boolean =>
|
||||||
[permissions],
|
permissionsReady && codes.some((code) => permissions.includes(code)),
|
||||||
|
[permissions, permissionsReady],
|
||||||
);
|
);
|
||||||
const hasAllPermissions = useCallback(
|
const hasAllPermissions = useCallback(
|
||||||
(...codes: string[]): boolean => codes.every((code) => permissions.includes(code)),
|
(...codes: string[]): boolean =>
|
||||||
[permissions],
|
permissionsReady && codes.every((code) => permissions.includes(code)),
|
||||||
|
[permissions, permissionsReady],
|
||||||
);
|
);
|
||||||
|
|
||||||
return { permissions, hasPermission, hasAnyPermission, hasAllPermissions };
|
return {
|
||||||
|
permissions,
|
||||||
|
permissionStatus,
|
||||||
|
permissionsReady,
|
||||||
|
hasPermission,
|
||||||
|
hasAnyPermission,
|
||||||
|
hasAllPermissions,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useCallback } from 'react';
|
import { useCallback, useEffect, useRef } from 'react';
|
||||||
import { Modal } from 'antd';
|
import { App } from 'antd';
|
||||||
import api from '../api';
|
import api from '../api';
|
||||||
import { message } from '../ui/app-message';
|
import { message } from '../ui/app-message';
|
||||||
|
|
||||||
@@ -9,16 +9,36 @@ import { message } from '../ui/app-message';
|
|||||||
*
|
*
|
||||||
* @param studentId - The student whose data is being viewed
|
* @param studentId - The student whose data is being viewed
|
||||||
* @param module - Audit module label (e.g. '学生管理', '学生档案')
|
* @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 { modal } = App.useApp();
|
||||||
|
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(
|
return useCallback(
|
||||||
(field: string, value: string) => {
|
(field: string, value: string) => {
|
||||||
Modal.confirm({
|
if (!canLogRef.current) return;
|
||||||
|
modalRef.current = modal.confirm({
|
||||||
title: '查看敏感信息',
|
title: '查看敏感信息',
|
||||||
content: `您即将查看 "${field}" 的完整信息。此操作将被记录。`,
|
content: `您即将查看 "${field}" 的完整信息。此操作将被记录。`,
|
||||||
okText: '确认查看',
|
okText: '确认查看',
|
||||||
cancelText: '取消',
|
cancelText: '取消',
|
||||||
onOk: async () => {
|
onOk: async () => {
|
||||||
|
if (!canLogRef.current) return;
|
||||||
try {
|
try {
|
||||||
await api.post('/operation-logs/audit', {
|
await api.post('/operation-logs/audit', {
|
||||||
module,
|
module,
|
||||||
@@ -31,14 +51,17 @@ export function useViewSensitive(studentId: number, module: string) {
|
|||||||
message.error('操作日志记录失败,请稍后重试');
|
message.error('操作日志记录失败,请稍后重试');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Modal.info({
|
modal.info({
|
||||||
title: field,
|
title: field,
|
||||||
content: value,
|
content: value,
|
||||||
okText: '关闭',
|
okText: '关闭',
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
afterClose: () => {
|
||||||
|
modalRef.current = null;
|
||||||
|
},
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
[studentId, module],
|
[studentId, module, modal],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -157,6 +157,22 @@ canvas {
|
|||||||
gap: 8px;
|
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 {
|
.ant-drawer-content-wrapper {
|
||||||
max-width: 100vw !important;
|
max-width: 100vw !important;
|
||||||
}
|
}
|
||||||
@@ -172,12 +188,40 @@ canvas {
|
|||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.ant-table-wrapper .ant-table-container {
|
.ant-table-wrapper .ant-table-content {
|
||||||
overflow-x: auto;
|
|
||||||
overscroll-behavior-inline: contain;
|
overscroll-behavior-inline: contain;
|
||||||
-webkit-overflow-scrolling: touch;
|
-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 类即可生效:
|
在 .ant-table-wrapper 上添加 .table-cell-ellipsis 类即可生效:
|
||||||
<Table className="table-cell-ellipsis" ... /> */
|
<Table className="table-cell-ellipsis" ... /> */
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
|
||||||
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
|
import { useNavigate, useLocation } from 'react-router';
|
||||||
import { Layout, Menu, Button, Avatar, Dropdown, Drawer, Grid } from 'antd';
|
import { Layout, Menu, Button, Avatar, Badge, Dropdown, Drawer, Grid, Tooltip } from 'antd';
|
||||||
|
import { BrandLogo } from '../components/BrandLogo';
|
||||||
import {
|
import {
|
||||||
DashboardOutlined,
|
DashboardOutlined,
|
||||||
TeamOutlined,
|
TeamOutlined,
|
||||||
@@ -28,14 +29,21 @@ import {
|
|||||||
TrophyOutlined,
|
TrophyOutlined,
|
||||||
ApiOutlined,
|
ApiOutlined,
|
||||||
RobotOutlined,
|
RobotOutlined,
|
||||||
|
LoadingOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import { usePermission } from '../hooks/usePermission';
|
import { usePermission } from '../hooks/usePermission';
|
||||||
import api from '../api';
|
import api from '../api';
|
||||||
import { writePermissions } from '../auth/permission-store';
|
import { useAppStore } from '../store/app/appStore';
|
||||||
|
import { usePermissionStore } from '../store/permission/permissionStore';
|
||||||
|
import { useUserStore } from '../store/user/userStore';
|
||||||
|
import { AUTH_STORAGE_NAME, PERMISSION_STORAGE_NAME } from '../store/middleware/persist';
|
||||||
import NotificationBell from '../components/NotificationBell';
|
import NotificationBell from '../components/NotificationBell';
|
||||||
import RouteDock from '../components/RouteDock';
|
import RouteDock from '../components/RouteDock';
|
||||||
|
import RouteKeeper from '../components/RouteKeeper';
|
||||||
import { buildMenu, type AppMenuItem } from '../auth/menu-policy';
|
import { buildMenu, type AppMenuItem } from '../auth/menu-policy';
|
||||||
|
|
||||||
|
const AiChatDrawer = React.lazy(() => import('../components/AiChat/AiChatDrawer'));
|
||||||
|
|
||||||
const { Header, Sider, Content } = Layout;
|
const { Header, Sider, Content } = Layout;
|
||||||
|
|
||||||
const iconMap: Record<string, React.ReactNode> = {
|
const iconMap: Record<string, React.ReactNode> = {
|
||||||
@@ -69,38 +77,109 @@ const iconMap: Record<string, React.ReactNode> = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const MainLayout: React.FC = () => {
|
const MainLayout: React.FC = () => {
|
||||||
const [collapsed, setCollapsed] = useState(false);
|
|
||||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
|
||||||
const [openKeys, setOpenKeys] = useState<string[]>([]);
|
|
||||||
const prevPathname = useRef('');
|
const prevPathname = useRef('');
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const [user, setUser] = useState<{ name?: string; username?: string; roles?: string[] }>(() =>
|
const user = useUserStore((state) => state.user);
|
||||||
JSON.parse(localStorage.getItem('user') || '{}'),
|
const updateUser = useUserStore((state) => state.updateUser);
|
||||||
);
|
const logoutUser = useUserStore((state) => state.logout);
|
||||||
|
const collapsed = useAppStore((state) => state.sidebarCollapsed);
|
||||||
|
const drawerOpen = useAppStore((state) => state.mobileDrawerOpen);
|
||||||
|
const aiChatOpen = useAppStore((state) => state.aiChatOpen);
|
||||||
|
const aiWorking = useAppStore((state) => state.aiWorking);
|
||||||
|
const openKeys = useAppStore((state) => state.menuOpenKeys);
|
||||||
|
const toggleSidebar = useAppStore((state) => state.toggleSidebar);
|
||||||
|
const setDrawerOpen = useAppStore((state) => state.setMobileDrawerOpen);
|
||||||
|
const setAiChatOpen = useAppStore((state) => state.setAiChatOpen);
|
||||||
|
const setAiWorking = useAppStore((state) => state.setAiWorking);
|
||||||
|
const setOpenKeys = useAppStore((state) => state.setMenuOpenKeys);
|
||||||
const { permissions, hasPermission } = usePermission();
|
const { permissions, hasPermission } = usePermission();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
api
|
let retryTimer: number | undefined;
|
||||||
.get<{ id: number; username: string; permissions: string[]; roles?: string[] }>(
|
let verificationInFlight = false;
|
||||||
'/auth/profile',
|
|
||||||
)
|
const verifyPermissions = () => {
|
||||||
.then((profile) => {
|
if (cancelled || verificationInFlight || !useUserStore.getState().token) return;
|
||||||
if (cancelled) return;
|
if (retryTimer !== undefined) {
|
||||||
writePermissions(profile.permissions || []);
|
window.clearTimeout(retryTimer);
|
||||||
const cachedUser = JSON.parse(localStorage.getItem('user') || '{}');
|
retryTimer = undefined;
|
||||||
const nextUser = { ...cachedUser, ...profile };
|
}
|
||||||
localStorage.setItem('user', JSON.stringify(nextUser));
|
verificationInFlight = true;
|
||||||
setUser(nextUser);
|
usePermissionStore.getState().beginPermissionVerification();
|
||||||
})
|
api
|
||||||
.catch(() => {
|
.get<{ id: number; username: string; permissions: string[]; roles?: string[] }>(
|
||||||
// The API interceptor handles expired/invalid sessions.
|
'/auth/profile',
|
||||||
});
|
)
|
||||||
|
.then((profile) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
verificationInFlight = false;
|
||||||
|
usePermissionStore.getState().writePermissions(profile.permissions || []);
|
||||||
|
updateUser(profile);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
verificationInFlight = false;
|
||||||
|
if (cancelled || !useUserStore.getState().token) return;
|
||||||
|
retryTimer = window.setTimeout(verifyPermissions, 5_000);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleStorage = (event: StorageEvent) => {
|
||||||
|
if (event.key === PERMISSION_STORAGE_NAME) {
|
||||||
|
// 其他标签页的权限更新:原地应用,避免整页刷新造成刷新风暴。
|
||||||
|
try {
|
||||||
|
if (event.newValue === null) {
|
||||||
|
usePermissionStore.getState().clearPermissions();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const parsed = JSON.parse(event.newValue) as {
|
||||||
|
state?: { permissions?: string[] };
|
||||||
|
};
|
||||||
|
const permissions = parsed?.state?.permissions;
|
||||||
|
if (Array.isArray(permissions)) {
|
||||||
|
usePermissionStore.getState().writePermissions(permissions);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略无法解析的跨标签页权限写入
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (event.key === AUTH_STORAGE_NAME) {
|
||||||
|
// 仅当登录态(token)确实变化时才整页刷新:登录、退出或切换账号。
|
||||||
|
const currentToken = useUserStore.getState().token;
|
||||||
|
let otherToken: string | null = null;
|
||||||
|
if (event.newValue) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(event.newValue) as {
|
||||||
|
state?: { token?: string | null };
|
||||||
|
};
|
||||||
|
otherToken = parsed?.state?.token ?? null;
|
||||||
|
} catch {
|
||||||
|
otherToken = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (otherToken === currentToken) return;
|
||||||
|
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 () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
|
if (retryTimer !== undefined) window.clearTimeout(retryTimer);
|
||||||
|
window.removeEventListener('storage', handleStorage);
|
||||||
|
window.removeEventListener('online', handleOnline);
|
||||||
|
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||||
};
|
};
|
||||||
}, []);
|
}, [updateUser]);
|
||||||
|
|
||||||
const screens = Grid.useBreakpoint();
|
const screens = Grid.useBreakpoint();
|
||||||
const isMobile = !screens.sm; // < 576px (仅 xs)
|
const isMobile = !screens.sm; // < 576px (仅 xs)
|
||||||
@@ -109,35 +188,37 @@ const MainLayout: React.FC = () => {
|
|||||||
const usesDrawer = !isDesktop;
|
const usesDrawer = !isDesktop;
|
||||||
|
|
||||||
const menuItems = useMemo(
|
const menuItems = useMemo(
|
||||||
() => buildMenu(user.roles ?? [], permissions),
|
() => buildMenu(user?.roles ?? [], permissions),
|
||||||
[user.roles, permissions],
|
[user, permissions],
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleLogout = useCallback(() => {
|
const handleLogout = useCallback(() => {
|
||||||
localStorage.removeItem('token');
|
logoutUser();
|
||||||
localStorage.removeItem('user');
|
usePermissionStore.getState().clearPermissions();
|
||||||
localStorage.removeItem('permissions');
|
|
||||||
navigate('/login');
|
navigate('/login');
|
||||||
}, [navigate]);
|
}, [logoutUser, navigate]);
|
||||||
|
|
||||||
const handleMenuClick = useCallback(
|
const handleMenuClick = useCallback(
|
||||||
(key: string) => {
|
(key: string) => {
|
||||||
navigate(key);
|
navigate(key);
|
||||||
if (usesDrawer) setDrawerOpen(false);
|
if (usesDrawer) setDrawerOpen(false);
|
||||||
},
|
},
|
||||||
[navigate, usesDrawer],
|
[navigate, usesDrawer, setDrawerOpen],
|
||||||
);
|
);
|
||||||
|
|
||||||
const findSelectedKeys = (items: AppMenuItem[], pathname: string): string[] => {
|
const findSelectedKeys = useCallback(
|
||||||
for (const item of items) {
|
(items: AppMenuItem[], pathname: string): string[] => {
|
||||||
if (item.key === pathname) return [item.key];
|
for (const item of items) {
|
||||||
if (item.children) {
|
if (item.key === pathname) return [item.key];
|
||||||
const found = findSelectedKeys(item.children, pathname);
|
if (item.children) {
|
||||||
if (found.length > 0) return found;
|
const found = findSelectedKeys(item.children, pathname);
|
||||||
|
if (found.length > 0) return found;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
return [pathname];
|
||||||
return [pathname];
|
},
|
||||||
};
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
const findOpenKeys = (items: AppMenuItem[], pathname: string): string[] => {
|
const findOpenKeys = (items: AppMenuItem[], pathname: string): string[] => {
|
||||||
for (const item of items) {
|
for (const item of items) {
|
||||||
@@ -157,7 +238,7 @@ const MainLayout: React.FC = () => {
|
|||||||
|
|
||||||
const selectedKeys = useMemo(
|
const selectedKeys = useMemo(
|
||||||
() => findSelectedKeys(menuItems, location.pathname),
|
() => findSelectedKeys(menuItems, location.pathname),
|
||||||
[menuItems, location.pathname],
|
[menuItems, location.pathname, findSelectedKeys],
|
||||||
);
|
);
|
||||||
// 路径变化时同步展开的菜单(不干扰用户手动展开/收起)
|
// 路径变化时同步展开的菜单(不干扰用户手动展开/收起)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -166,20 +247,20 @@ const MainLayout: React.FC = () => {
|
|||||||
const routeOpenKeys = findOpenKeys(menuItems, location.pathname);
|
const routeOpenKeys = findOpenKeys(menuItems, location.pathname);
|
||||||
setOpenKeys((currentKeys) => [...new Set([...currentKeys, ...routeOpenKeys])]);
|
setOpenKeys((currentKeys) => [...new Set([...currentKeys, ...routeOpenKeys])]);
|
||||||
}
|
}
|
||||||
}, [location.pathname, menuItems]);
|
}, [location.pathname, menuItems, setOpenKeys]);
|
||||||
|
|
||||||
const handleOpenChange = useCallback((keys: string[]) => {
|
const handleOpenChange = useCallback((keys: string[]) => {
|
||||||
setOpenKeys(keys);
|
setOpenKeys(keys);
|
||||||
}, []);
|
}, [setOpenKeys]);
|
||||||
|
|
||||||
const transformToMenuItems = (items: AppMenuItem[]): any[] => {
|
const transformToMenuItems = useCallback((items: AppMenuItem[]): any[] => {
|
||||||
return items.map((item) => ({
|
return items.map((item) => ({
|
||||||
key: item.key,
|
key: item.key,
|
||||||
icon: item.icon ? iconMap[item.icon] : undefined,
|
icon: item.icon ? iconMap[item.icon] : undefined,
|
||||||
label: item.label,
|
label: item.label,
|
||||||
children: item.children ? transformToMenuItems(item.children) : undefined,
|
children: item.children ? transformToMenuItems(item.children) : undefined,
|
||||||
}));
|
}));
|
||||||
};
|
}, []);
|
||||||
const menuContent = useMemo(
|
const menuContent = useMemo(
|
||||||
() => (
|
() => (
|
||||||
<Menu
|
<Menu
|
||||||
@@ -193,7 +274,7 @@ const MainLayout: React.FC = () => {
|
|||||||
style={{ border: 'none' }}
|
style={{ border: 'none' }}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
[selectedKeys, openKeys, menuItems, handleMenuClick],
|
[selectedKeys, openKeys, menuItems, handleMenuClick, handleOpenChange, transformToMenuItems],
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -219,7 +300,17 @@ const MainLayout: React.FC = () => {
|
|||||||
borderBottom: '1px solid #e5e5e7',
|
borderBottom: '1px solid #e5e5e7',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{collapsed ? '学' : '学生管理系统'}
|
<div
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
gap: 8,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<BrandLogo size={collapsed ? 26 : 30} />
|
||||||
|
{!collapsed && <span>学生管理系统</span>}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{menuContent}
|
{menuContent}
|
||||||
</Sider>
|
</Sider>
|
||||||
@@ -232,7 +323,12 @@ const MainLayout: React.FC = () => {
|
|||||||
size={240}
|
size={240}
|
||||||
styles={{ body: { padding: 0 } }}
|
styles={{ body: { padding: 0 } }}
|
||||||
className="app-navigation-drawer"
|
className="app-navigation-drawer"
|
||||||
title="学生管理系统"
|
title={
|
||||||
|
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
|
||||||
|
<BrandLogo size={24} />
|
||||||
|
学生管理系统
|
||||||
|
</span>
|
||||||
|
}
|
||||||
>
|
>
|
||||||
{menuContent}
|
{menuContent}
|
||||||
</Drawer>
|
</Drawer>
|
||||||
@@ -262,9 +358,27 @@ const MainLayout: React.FC = () => {
|
|||||||
<MenuFoldOutlined />
|
<MenuFoldOutlined />
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
onClick={() => (usesDrawer ? setDrawerOpen(true) : setCollapsed(!collapsed))}
|
onClick={() => (usesDrawer ? setDrawerOpen(true) : toggleSidebar())}
|
||||||
/>
|
/>
|
||||||
<div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
|
<div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
|
||||||
|
{hasPermission('ai:chat:use') && (
|
||||||
|
<Tooltip title={aiWorking ? 'AI 处理中' : 'AI 助理'}>
|
||||||
|
<Badge dot={aiWorking} color="#007AFF" offset={[-3, 5]}>
|
||||||
|
<Button
|
||||||
|
type="text"
|
||||||
|
aria-label={aiWorking ? 'AI 助理处理中' : '打开 AI 助理'}
|
||||||
|
icon={
|
||||||
|
aiWorking ? (
|
||||||
|
<LoadingOutlined style={{ fontSize: 17, color: '#007AFF' }} spin />
|
||||||
|
) : (
|
||||||
|
<RobotOutlined style={{ fontSize: 17 }} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
onClick={() => setAiChatOpen(true)}
|
||||||
|
/>
|
||||||
|
</Badge>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
{hasPermission('notification:view') && <NotificationBell />}
|
{hasPermission('notification:view') && <NotificationBell />}
|
||||||
<Dropdown
|
<Dropdown
|
||||||
menu={{
|
menu={{
|
||||||
@@ -285,7 +399,7 @@ const MainLayout: React.FC = () => {
|
|||||||
style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8 }}
|
style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8 }}
|
||||||
>
|
>
|
||||||
<Avatar icon={<UserOutlined />} />
|
<Avatar icon={<UserOutlined />} />
|
||||||
{isDesktop && <span>{user.name || user.username || '用户'}</span>}
|
{isDesktop && <span>{user?.name || user?.username || '用户'}</span>}
|
||||||
</div>
|
</div>
|
||||||
</Dropdown>
|
</Dropdown>
|
||||||
</div>
|
</div>
|
||||||
@@ -305,9 +419,18 @@ const MainLayout: React.FC = () => {
|
|||||||
borderRadius: 12,
|
borderRadius: 12,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Outlet />
|
<RouteKeeper />
|
||||||
</Content>
|
</Content>
|
||||||
</Layout>
|
</Layout>
|
||||||
|
{hasPermission('ai:chat:use') && (
|
||||||
|
<React.Suspense fallback={null}>
|
||||||
|
<AiChatDrawer
|
||||||
|
open={aiChatOpen}
|
||||||
|
onClose={() => setAiChatOpen(false)}
|
||||||
|
onRequestingChange={setAiWorking}
|
||||||
|
/>
|
||||||
|
</React.Suspense>
|
||||||
|
)}
|
||||||
</Layout>
|
</Layout>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import ReactDOM from 'react-dom/client';
|
import ReactDOM from 'react-dom/client';
|
||||||
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||||
|
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
|
||||||
import App from './App';
|
import App from './App';
|
||||||
import './index.css';
|
import './index.css';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import 'dayjs/locale/zh-cn';
|
import 'dayjs/locale/zh-cn';
|
||||||
import customParseFormat from 'dayjs/plugin/customParseFormat';
|
import customParseFormat from 'dayjs/plugin/customParseFormat';
|
||||||
import advancedFormat from 'dayjs/plugin/advancedFormat';
|
import advancedFormat from 'dayjs/plugin/advancedFormat';
|
||||||
|
import relativeTime from 'dayjs/plugin/relativeTime';
|
||||||
import weekday from 'dayjs/plugin/weekday';
|
import weekday from 'dayjs/plugin/weekday';
|
||||||
import localeData from 'dayjs/plugin/localeData';
|
import localeData from 'dayjs/plugin/localeData';
|
||||||
import weekOfYear from 'dayjs/plugin/weekOfYear';
|
import weekOfYear from 'dayjs/plugin/weekOfYear';
|
||||||
@@ -15,6 +18,7 @@ import updateLocale from 'dayjs/plugin/updateLocale';
|
|||||||
// 扩展 antd DatePicker/RangePicker 面板所需的 dayjs 插件,否则中文 locale 无法生效
|
// 扩展 antd DatePicker/RangePicker 面板所需的 dayjs 插件,否则中文 locale 无法生效
|
||||||
dayjs.extend(customParseFormat);
|
dayjs.extend(customParseFormat);
|
||||||
dayjs.extend(advancedFormat);
|
dayjs.extend(advancedFormat);
|
||||||
|
dayjs.extend(relativeTime);
|
||||||
dayjs.extend(weekday);
|
dayjs.extend(weekday);
|
||||||
dayjs.extend(localeData);
|
dayjs.extend(localeData);
|
||||||
dayjs.extend(weekOfYear);
|
dayjs.extend(weekOfYear);
|
||||||
@@ -24,8 +28,23 @@ dayjs.extend(updateLocale);
|
|||||||
// 必须在所有插件加载后设置 locale
|
// 必须在所有插件加载后设置 locale
|
||||||
dayjs.locale('zh-cn');
|
dayjs.locale('zh-cn');
|
||||||
|
|
||||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
const queryClient = new QueryClient({
|
||||||
|
defaultOptions: {
|
||||||
|
queries: {
|
||||||
|
retry: 1,
|
||||||
|
staleTime: 30_000,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const rootElement = document.getElementById('root');
|
||||||
|
if (!rootElement) throw new Error('未找到 #root 挂载点');
|
||||||
|
|
||||||
|
ReactDOM.createRoot(rootElement).render(
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<App />
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<App />
|
||||||
|
{import.meta.env.DEV && <ReactQueryDevtools initialIsOpen={false} />}
|
||||||
|
</QueryClientProvider>
|
||||||
</React.StrictMode>,
|
</React.StrictMode>,
|
||||||
);
|
);
|
||||||
|
|||||||
415
apps/admin/src/pages/AiConfig/AiConfigSteps.tsx
Normal file
415
apps/admin/src/pages/AiConfig/AiConfigSteps.tsx
Normal file
@@ -0,0 +1,415 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import {
|
||||||
|
ApiOutlined,
|
||||||
|
CheckCircleOutlined,
|
||||||
|
CloseCircleOutlined,
|
||||||
|
CloudServerOutlined,
|
||||||
|
ReloadOutlined,
|
||||||
|
RobotOutlined,
|
||||||
|
SafetyOutlined,
|
||||||
|
SaveOutlined,
|
||||||
|
WarningOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
AutoComplete,
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Descriptions,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
InputNumber,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Switch,
|
||||||
|
Tag,
|
||||||
|
Typography,
|
||||||
|
} from 'antd';
|
||||||
|
import type { AiProvider } from './helpers';
|
||||||
|
import {
|
||||||
|
PROVIDER_OPTIONS,
|
||||||
|
PROVIDER_DEFAULTS,
|
||||||
|
formatDateTime,
|
||||||
|
sourceColor,
|
||||||
|
sourceLabel,
|
||||||
|
} from './helpers';
|
||||||
|
import styles from './index.module.css';
|
||||||
|
|
||||||
|
export interface AiConfigData {
|
||||||
|
id: number;
|
||||||
|
provider: AiProvider;
|
||||||
|
baseUrl: string;
|
||||||
|
hasApiKey: boolean;
|
||||||
|
hasDatabaseKey: boolean;
|
||||||
|
maskedApiKey: string | null;
|
||||||
|
keySource: 'database' | 'environment' | 'none';
|
||||||
|
defaultModel: string | null;
|
||||||
|
enabled: boolean;
|
||||||
|
supportsVision: boolean;
|
||||||
|
timeoutMs: number;
|
||||||
|
reasoningEffort: string | null;
|
||||||
|
verified: boolean;
|
||||||
|
lastTestedAt: string | null;
|
||||||
|
lastTestLatencyMs: number | null;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TestResult {
|
||||||
|
success: boolean;
|
||||||
|
latencyMs: number | null;
|
||||||
|
modelCount: number | null;
|
||||||
|
modelAvailable: boolean;
|
||||||
|
testedAt: string;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FormValues {
|
||||||
|
provider: AiProvider;
|
||||||
|
baseUrl: string;
|
||||||
|
apiKey: string;
|
||||||
|
defaultModel: string;
|
||||||
|
timeoutMs: number;
|
||||||
|
supportsVision: boolean;
|
||||||
|
reasoningEffort: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ProviderStep: React.FC<{
|
||||||
|
canWrite: boolean;
|
||||||
|
isFixedProvider: boolean;
|
||||||
|
config?: AiConfigData | null;
|
||||||
|
onProviderChange: (provider: AiProvider) => void;
|
||||||
|
}> = ({ canWrite, isFixedProvider, config, onProviderChange }) => {
|
||||||
|
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={onProviderChange}
|
||||||
|
disabled={!canWrite}
|
||||||
|
size="large"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
name="baseUrl"
|
||||||
|
label="Base URL"
|
||||||
|
rules={[
|
||||||
|
{ required: true, message: '请输入 Base URL' },
|
||||||
|
{ type: 'url', message: '请输入合法的 URL' },
|
||||||
|
]}
|
||||||
|
preserve
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
placeholder={
|
||||||
|
config?.provider ? PROVIDER_DEFAULTS[config.provider] : PROVIDER_DEFAULTS.DEEPSEEK
|
||||||
|
}
|
||||||
|
disabled={!canWrite || (isFixedProvider && canWrite)}
|
||||||
|
size="large"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
name="timeoutMs"
|
||||||
|
label="请求超时 (毫秒)"
|
||||||
|
rules={[
|
||||||
|
{ required: true, message: '请输入超时时间' },
|
||||||
|
{ type: 'number', min: 1000, max: 120000, message: '范围: 1000-120000' },
|
||||||
|
]}
|
||||||
|
preserve
|
||||||
|
>
|
||||||
|
<InputNumber
|
||||||
|
min={1000}
|
||||||
|
max={120000}
|
||||||
|
step={1000}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
disabled={!canWrite}
|
||||||
|
size="large"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const KeyStep: React.FC<{
|
||||||
|
canWrite: boolean;
|
||||||
|
config?: AiConfigData | null;
|
||||||
|
onClearKey: () => void;
|
||||||
|
}> = ({ canWrite, config, onClearKey }) => {
|
||||||
|
return (
|
||||||
|
<Card title={<span className={styles.cardTitle}>密钥配置</span>} extra={<SafetyOutlined />}>
|
||||||
|
<Form.Item name="apiKey" label="API Key" preserve>
|
||||||
|
<Input.Password
|
||||||
|
placeholder={config?.hasApiKey ? '已安全保存,留空则保持不变' : '请输入 API Key'}
|
||||||
|
disabled={!canWrite}
|
||||||
|
autoComplete="new-password"
|
||||||
|
size="large"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
{config && (
|
||||||
|
<Descriptions column={1} size="small" style={{ marginBottom: 12 }}>
|
||||||
|
<Descriptions.Item label="状态">
|
||||||
|
{config.hasApiKey ? (
|
||||||
|
<Tag color="green">{config.maskedApiKey || '••••'}</Tag>
|
||||||
|
) : (
|
||||||
|
<Tag color="default">未配置</Tag>
|
||||||
|
)}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="来源">
|
||||||
|
<Tag color={sourceColor(config.keySource)}>{sourceLabel(config.keySource)}</Tag>
|
||||||
|
{config.keySource === 'environment' && (
|
||||||
|
<span style={{ marginLeft: 8, fontSize: 12, color: '#999' }}>
|
||||||
|
由环境变量托管,需在服务器修改
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="最后更新">{formatDateTime(config.updatedAt)}</Descriptions.Item>
|
||||||
|
</Descriptions>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{config?.hasDatabaseKey && canWrite && (
|
||||||
|
<div style={{ marginBottom: 8 }}>
|
||||||
|
<Button danger size="small" onClick={onClearKey}>
|
||||||
|
清除服务器保存密钥
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{config?.keySource === 'environment' && !config.hasDatabaseKey && (
|
||||||
|
<div style={{ marginBottom: 8, fontSize: 12, color: '#999' }}>
|
||||||
|
密钥由环境变量提供,无法通过页面清除
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className={styles.safetyNote}>
|
||||||
|
API Key 使用 AES-256-GCM 加密存储,每次保存使用随机 IV。传输层通过 HTTPS
|
||||||
|
保护,服务端日志不记录密钥。
|
||||||
|
</div>
|
||||||
|
<div className={styles.safetyNoteKey}>
|
||||||
|
也可通过环境变量 <Typography.Text code>AI_API_KEY</Typography.Text> 注入密钥,环境变量优先级高于数据库存储。
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ModelStep: React.FC<{
|
||||||
|
canWrite: boolean;
|
||||||
|
config?: AiConfigData | null;
|
||||||
|
onFetchModels: () => void;
|
||||||
|
fetchingModels: boolean;
|
||||||
|
modelOptions: Array<{ value: string; label: string }>;
|
||||||
|
}> = ({ canWrite, config, onFetchModels, fetchingModels, modelOptions }) => {
|
||||||
|
return (
|
||||||
|
<Card title={<span className={styles.cardTitle}>模型选择</span>} extra={<RobotOutlined />}>
|
||||||
|
<div className={styles.modelFetchRow}>
|
||||||
|
<Button
|
||||||
|
icon={<ReloadOutlined />}
|
||||||
|
onClick={onFetchModels}
|
||||||
|
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
|
||||||
|
>
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
name="reasoningEffort"
|
||||||
|
label="推理强度 (reasoning_effort)"
|
||||||
|
extra="OpenAI o 系列等支持该参数的模型生效;DeepSeek 官方接口不支持,选择后也不会发送。"
|
||||||
|
preserve
|
||||||
|
>
|
||||||
|
<Select
|
||||||
|
disabled={!canWrite}
|
||||||
|
size="large"
|
||||||
|
options={[
|
||||||
|
{ value: '', label: '不设置(跟随模型默认)' },
|
||||||
|
{ value: 'low', label: '低 (low)' },
|
||||||
|
{ value: 'medium', label: '中 (medium)' },
|
||||||
|
{ value: 'high', label: '高 (high)' },
|
||||||
|
{ value: 'xhigh', label: '极高 (xhigh)' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</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>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const TestResultCard: React.FC<{ testResult: TestResult | null }> = ({ testResult }) =>
|
||||||
|
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>
|
||||||
|
) : null;
|
||||||
|
|
||||||
|
export const SaveTestStep: React.FC<{
|
||||||
|
canWrite: boolean;
|
||||||
|
canTest: boolean;
|
||||||
|
config?: AiConfigData | null;
|
||||||
|
currentProvider: AiProvider;
|
||||||
|
formValues: FormValues;
|
||||||
|
onSave: () => void;
|
||||||
|
saving: boolean;
|
||||||
|
onTest: () => void;
|
||||||
|
testing: boolean;
|
||||||
|
testResult: TestResult | null;
|
||||||
|
}> = ({
|
||||||
|
canWrite,
|
||||||
|
canTest,
|
||||||
|
config,
|
||||||
|
currentProvider,
|
||||||
|
formValues,
|
||||||
|
onSave,
|
||||||
|
saving,
|
||||||
|
onTest,
|
||||||
|
testing,
|
||||||
|
testResult,
|
||||||
|
}) => {
|
||||||
|
const providerLabel =
|
||||||
|
PROVIDER_OPTIONS.find((o) => o.value === currentProvider)?.label ?? currentProvider ?? '-';
|
||||||
|
const hasFormKey = formValues.apiKey && formValues.apiKey !== '••••';
|
||||||
|
return (
|
||||||
|
<Card title={<span className={styles.cardTitle}>保存并测试</span>} extra={<CheckCircleOutlined />}>
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
title="配置预览"
|
||||||
|
description={
|
||||||
|
<Descriptions column={1} size="small" style={{ marginTop: 8 }}>
|
||||||
|
<Descriptions.Item label="服务商">
|
||||||
|
<Tag color="blue">{providerLabel}</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="密钥">
|
||||||
|
{config?.hasApiKey ? (
|
||||||
|
<Tag color="green">{config.maskedApiKey || '••••'}</Tag>
|
||||||
|
) : hasFormKey ? (
|
||||||
|
<Tag color="blue">已填写(未保存)</Tag>
|
||||||
|
) : (
|
||||||
|
<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={onSave}
|
||||||
|
loading={saving}
|
||||||
|
size="large"
|
||||||
|
>
|
||||||
|
保存配置
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{canTest && (
|
||||||
|
<Button icon={<ApiOutlined />} onClick={onTest} loading={testing} size="large">
|
||||||
|
测试连接
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</Space>
|
||||||
|
<TestResultCard testResult={testResult} />
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -5,8 +5,8 @@ import {
|
|||||||
sourceLabel,
|
sourceLabel,
|
||||||
sourceColor,
|
sourceColor,
|
||||||
PROVIDER_DEFAULTS,
|
PROVIDER_DEFAULTS,
|
||||||
extractErrorMessage,
|
|
||||||
} from './helpers';
|
} from './helpers';
|
||||||
|
import { getErrorMessage } from '../../utils/error';
|
||||||
|
|
||||||
describe('AiConfig helpers', () => {
|
describe('AiConfig helpers', () => {
|
||||||
describe('shouldAutoSwapBaseUrl', () => {
|
describe('shouldAutoSwapBaseUrl', () => {
|
||||||
@@ -60,48 +60,48 @@ describe('AiConfig helpers', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('extractErrorMessage', () => {
|
describe('getErrorMessage', () => {
|
||||||
it('extracts message from server error response (interceptor unwraps to { message })', () => {
|
it('extracts message from server error response (interceptor unwraps to { message })', () => {
|
||||||
// The Axios interceptor at api/index.ts does Promise.reject(err.response?.data || err).
|
// The Axios interceptor at api/index.ts does Promise.reject(err.response?.data || err).
|
||||||
// For server errors, the rejection value is err.response.data — typically { message: '...' }.
|
// For server errors, the rejection value is err.response.data — typically { message: '...' }.
|
||||||
const err = { message: 'API出错' };
|
const err = { message: 'API出错' };
|
||||||
expect(extractErrorMessage(err)).toBe('API出错');
|
expect(getErrorMessage(err)).toBe('API出错');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('falls back to message property', () => {
|
it('falls back to message property', () => {
|
||||||
const err = { message: 'Network error' };
|
const err = { message: 'Network error' };
|
||||||
expect(extractErrorMessage(err)).toBe('Network error');
|
expect(getErrorMessage(err)).toBe('Network error');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('falls back to default on unknown type', () => {
|
it('uses string errors and falls back on unknown types', () => {
|
||||||
expect(extractErrorMessage('unknown string')).toBe('操作失败');
|
expect(getErrorMessage('unknown string')).toBe('unknown string');
|
||||||
expect(extractErrorMessage(null)).toBe('操作失败');
|
expect(getErrorMessage(null)).toBe('操作失败');
|
||||||
expect(extractErrorMessage(undefined)).toBe('操作失败');
|
expect(getErrorMessage(undefined)).toBe('操作失败');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('sanitizes: newlines replaced with spaces', () => {
|
it('sanitizes: newlines replaced with spaces', () => {
|
||||||
const err = { message: 'line1\nline2\r\nline3' };
|
const err = { message: 'line1\nline2\r\nline3' };
|
||||||
expect(extractErrorMessage(err)).toBe('line1 line2 line3');
|
expect(getErrorMessage(err)).toBe('line1 line2 line3');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('sanitizes: message > 120 chars truncated with ellipsis', () => {
|
it('sanitizes: message > 120 chars truncated with ellipsis', () => {
|
||||||
const long = 'x'.repeat(200);
|
const long = 'x'.repeat(200);
|
||||||
const err = { message: long };
|
const err = { message: long };
|
||||||
const result = extractErrorMessage(err);
|
const result = getErrorMessage(err);
|
||||||
expect(result).toHaveLength(121); // 120 + '…' (1 char)
|
expect(result).toHaveLength(121); // 120 + '…' (1 char)
|
||||||
expect(result.endsWith('\u2026')).toBe(true);
|
expect(result.endsWith('\u2026')).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('sanitizes: empty trimmed message falls back', () => {
|
it('sanitizes: empty trimmed message falls back', () => {
|
||||||
const err = { message: ' ' };
|
const err = { message: ' ' };
|
||||||
expect(extractErrorMessage(err)).toBe('操作失败');
|
expect(getErrorMessage(err)).toBe('操作失败');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('sanitizes: plain object message property sanitized', () => {
|
it('sanitizes: plain object message property sanitized', () => {
|
||||||
const err = {
|
const err = {
|
||||||
message: ' some \n\nerror \r\nmessage ',
|
message: ' some \n\nerror \r\nmessage ',
|
||||||
};
|
};
|
||||||
expect(extractErrorMessage(err)).toBe('some error message');
|
expect(getErrorMessage(err)).toBe('some error message');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,18 +1,21 @@
|
|||||||
// ---------------------------------------------------------------------------
|
import dayjs from 'dayjs';
|
||||||
// AiConfig helpers — pure functions, no React / DOM dependencies
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
export type AiProvider = 'OPENAI' | 'DEEPSEEK' | 'OPENAI_COMPATIBLE';
|
export type AiProvider = 'OPENAI' | 'DEEPSEEK' | 'OPENAI_COMPATIBLE';
|
||||||
|
|
||||||
export const PROVIDER_OPTIONS: { value: AiProvider; label: string }[] = [
|
export const PROVIDER_OPTIONS: { value: AiProvider; label: string }[] = [
|
||||||
{ value: 'OPENAI', label: 'OpenAI' },
|
|
||||||
{ value: 'DEEPSEEK', label: 'DeepSeek' },
|
{ value: 'DEEPSEEK', label: 'DeepSeek' },
|
||||||
|
{ value: 'OPENAI', label: 'OpenAI' },
|
||||||
{ value: 'OPENAI_COMPATIBLE', label: 'OpenAI 兼容' },
|
{ value: 'OPENAI_COMPATIBLE', label: 'OpenAI 兼容' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// aislop-ignore-next-line: hardcoded-url -- OpenAI 官方 API 固定端点
|
||||||
|
export const OPENAI_DEFAULT_BASE_URL = 'https://api.openai.com/v1';
|
||||||
|
// aislop-ignore-next-line: hardcoded-url -- DeepSeek 官方 API 固定端点
|
||||||
|
export const DEEPSEEK_DEFAULT_BASE_URL = 'https://api.deepseek.com';
|
||||||
|
|
||||||
export const PROVIDER_DEFAULTS: Record<AiProvider, string> = {
|
export const PROVIDER_DEFAULTS: Record<AiProvider, string> = {
|
||||||
OPENAI: 'https://api.openai.com/v1',
|
OPENAI: OPENAI_DEFAULT_BASE_URL,
|
||||||
DEEPSEEK: 'https://api.deepseek.com',
|
DEEPSEEK: DEEPSEEK_DEFAULT_BASE_URL,
|
||||||
OPENAI_COMPATIBLE: '',
|
OPENAI_COMPATIBLE: '',
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
@@ -20,7 +23,7 @@ export const FIXED_PROVIDERS: AiProvider[] = ['OPENAI', 'DEEPSEEK'];
|
|||||||
|
|
||||||
export function formatDateTime(iso: string | null): string {
|
export function formatDateTime(iso: string | null): string {
|
||||||
if (!iso) return '-';
|
if (!iso) return '-';
|
||||||
return new Date(iso).toLocaleString('zh-CN');
|
return dayjs(iso).format('YYYY-MM-DD HH:mm:ss');
|
||||||
}
|
}
|
||||||
|
|
||||||
export function sourceLabel(source: string): string {
|
export function sourceLabel(source: string): string {
|
||||||
@@ -59,25 +62,3 @@ export function shouldAutoSwapBaseUrl(
|
|||||||
}
|
}
|
||||||
return { baseUrl: currentBaseUrl, shouldSwap: false };
|
return { baseUrl: currentBaseUrl, shouldSwap: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Extract a safe user-facing error message from any caught value.
|
|
||||||
*
|
|
||||||
* The Axios interceptor at `api/index.ts` unwraps errors before rejection:
|
|
||||||
* `Promise.reject(err.response?.data || err)`. So server errors arrive as
|
|
||||||
* `{ message: '...' }` (the unwrapped data) and network errors as the raw
|
|
||||||
* `Error` object — never as a raw AxiosError with a `.response` property. */
|
|
||||||
export function extractErrorMessage(err: unknown, fallback: string = '操作失败'): string {
|
|
||||||
let msg = '';
|
|
||||||
|
|
||||||
// standard Error or any object with a string message property
|
|
||||||
if (err && typeof err === 'object' && 'message' in err && typeof err.message === 'string') {
|
|
||||||
msg = err.message;
|
|
||||||
}
|
|
||||||
|
|
||||||
// sanitize: trim, collapse whitespace, strip newlines, truncate
|
|
||||||
const trimmed = msg.trim();
|
|
||||||
if (!trimmed) return fallback;
|
|
||||||
|
|
||||||
const singleLine = trimmed.replace(/[\n\r]+/g, ' ').replace(/ {2,}/g, ' ');
|
|
||||||
return singleLine.length > 120 ? singleLine.slice(0, 120) + '\u2026' : singleLine;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
.container {
|
.container {
|
||||||
max-width: 1200px;
|
max-width: 900px;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
padding: 16px;
|
padding: 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.header {
|
.header {
|
||||||
margin-bottom: 16px;
|
margin-bottom: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.header h2 {
|
.header h2 {
|
||||||
@@ -24,17 +24,13 @@
|
|||||||
margin-top: 8px;
|
margin-top: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.grid {
|
.steps {
|
||||||
display: grid;
|
margin-bottom: 24px;
|
||||||
grid-template-columns: 1fr 1fr;
|
|
||||||
gap: 16px;
|
|
||||||
margin-bottom: 16px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
.stepContent {
|
||||||
.grid {
|
min-height: 320px;
|
||||||
grid-template-columns: 1fr;
|
margin-bottom: 16px;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.cardTitle {
|
.cardTitle {
|
||||||
@@ -42,10 +38,17 @@
|
|||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
|
|
||||||
.actions {
|
.stepNav {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 8px;
|
justify-content: space-between;
|
||||||
flex-wrap: wrap;
|
padding-top: 8px;
|
||||||
|
border-top: 1px solid #f0f0f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modelFetchRow {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.testResult {
|
.testResult {
|
||||||
|
|||||||
@@ -1,227 +1,269 @@
|
|||||||
import React, { useEffect, useState, useCallback, useRef } from 'react';
|
import React, { useEffect, useState, useCallback, useRef } from 'react';
|
||||||
import {
|
import { useQuery } from '@tanstack/react-query';
|
||||||
App,
|
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||||
Card,
|
import { validateResponse } from '../../utils/validate';
|
||||||
Form,
|
import { aiConfigEnvelopeSchema } from '../../api/schemas';
|
||||||
Input,
|
import { App, Alert, Button, Form, Space, Spin, Steps, Tag } from 'antd';
|
||||||
Button,
|
|
||||||
Select,
|
|
||||||
Switch,
|
|
||||||
InputNumber,
|
|
||||||
Tag,
|
|
||||||
Descriptions,
|
|
||||||
Spin,
|
|
||||||
Alert,
|
|
||||||
Typography,
|
|
||||||
Tooltip,
|
|
||||||
Space,
|
|
||||||
} from 'antd';
|
|
||||||
import {
|
|
||||||
SaveOutlined,
|
|
||||||
ApiOutlined,
|
|
||||||
CheckCircleOutlined,
|
|
||||||
CloseCircleOutlined,
|
|
||||||
KeyOutlined,
|
|
||||||
WarningOutlined,
|
|
||||||
} from '@ant-design/icons';
|
|
||||||
import api from '../../api';
|
import api from '../../api';
|
||||||
import { message } from '../../ui/app-message';
|
import { message } from '../../ui/app-message';
|
||||||
import { usePermission } from '../../hooks/usePermission';
|
import { usePermission } from '../../hooks/usePermission';
|
||||||
import type { AiProvider } from './helpers';
|
import type { AiProvider } from './helpers';
|
||||||
import {
|
import {
|
||||||
PROVIDER_OPTIONS,
|
|
||||||
PROVIDER_DEFAULTS,
|
PROVIDER_DEFAULTS,
|
||||||
FIXED_PROVIDERS,
|
FIXED_PROVIDERS,
|
||||||
formatDateTime,
|
|
||||||
sourceLabel,
|
sourceLabel,
|
||||||
sourceColor,
|
sourceColor,
|
||||||
shouldAutoSwapBaseUrl,
|
shouldAutoSwapBaseUrl,
|
||||||
extractErrorMessage,
|
|
||||||
} from './helpers';
|
} from './helpers';
|
||||||
|
import { getErrorMessage } from '../../utils/error';
|
||||||
|
import {
|
||||||
|
ProviderStep,
|
||||||
|
KeyStep,
|
||||||
|
ModelStep,
|
||||||
|
SaveTestStep,
|
||||||
|
} from './AiConfigSteps';
|
||||||
|
import type { AiConfigData, FormValues, TestResult } from './AiConfigSteps';
|
||||||
import styles from './index.module.css';
|
import styles from './index.module.css';
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Types
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
interface AiConfigData {
|
|
||||||
id: number;
|
|
||||||
provider: AiProvider;
|
|
||||||
baseUrl: string;
|
|
||||||
hasApiKey: boolean;
|
|
||||||
hasDatabaseKey: boolean;
|
|
||||||
maskedApiKey: string | null;
|
|
||||||
keySource: 'database' | 'environment' | 'none';
|
|
||||||
defaultModel: string | null;
|
|
||||||
enabled: boolean;
|
|
||||||
timeoutMs: number;
|
|
||||||
verified: boolean;
|
|
||||||
lastTestedAt: string | null;
|
|
||||||
lastTestLatencyMs: number | null;
|
|
||||||
createdAt: string;
|
|
||||||
updatedAt: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TestResult {
|
|
||||||
success: boolean;
|
|
||||||
latencyMs: number | null;
|
|
||||||
modelCount: number | null;
|
|
||||||
modelAvailable: boolean;
|
|
||||||
testedAt: string;
|
|
||||||
message: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ApiResponse<T> {
|
interface ApiResponse<T> {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
data: T;
|
data: T;
|
||||||
message?: string;
|
message?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
interface FetchModelsResult {
|
||||||
// Page Component
|
success: boolean;
|
||||||
// ---------------------------------------------------------------------------
|
models: Array<{ id: string }>;
|
||||||
|
message?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_FORM_VALUES: FormValues = {
|
||||||
|
provider: 'DEEPSEEK',
|
||||||
|
baseUrl: PROVIDER_DEFAULTS['DEEPSEEK'],
|
||||||
|
apiKey: '',
|
||||||
|
defaultModel: '',
|
||||||
|
timeoutMs: 30000,
|
||||||
|
supportsVision: false,
|
||||||
|
reasoningEffort: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
const STEP_ITEMS = [
|
||||||
|
{ title: '服务商', content: '选择 AI 服务商' },
|
||||||
|
{ title: '密钥', content: '配置 API 密钥' },
|
||||||
|
{ title: '模型', content: '获取并选择模型' },
|
||||||
|
{ title: '完成', content: '保存并测试连接' },
|
||||||
|
];
|
||||||
|
|
||||||
const AiConfigPage: React.FC = () => {
|
const AiConfigPage: React.FC = () => {
|
||||||
const { hasPermission } = usePermission();
|
const { hasPermission } = usePermission();
|
||||||
const { modal } = App.useApp();
|
const { modal } = App.useApp();
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
|
|
||||||
const [loading, setLoading] = useState(true);
|
const [currentStep, setCurrentStep] = useState(0);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [testing, setTesting] = useState(false);
|
const [testing, setTesting] = useState(false);
|
||||||
const [config, setConfig] = useState<AiConfigData | null>(null);
|
const [fetchingModels, setFetchingModels] = useState(false);
|
||||||
const [testResult, setTestResult] = useState<TestResult | 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);
|
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 lastProviderRef = useRef<AiProvider | null>(null);
|
||||||
|
const skipNextSyncRef = useRef(false);
|
||||||
|
const appliedConfigRef = useRef<AiConfigData | null>(null);
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: config,
|
||||||
|
isLoading: configLoading,
|
||||||
|
isFetching: configFetching,
|
||||||
|
refetch: refetchConfig,
|
||||||
|
} = useQuery<AiConfigData | null>({
|
||||||
|
queryKey: ['ai', 'config'],
|
||||||
|
queryFn: async () => {
|
||||||
|
try {
|
||||||
|
const res = await api.get<ApiResponse<AiConfigData>>('/ai/config');
|
||||||
|
return validateResponse<ApiResponse<AiConfigData>>(aiConfigEnvelopeSchema, res).data;
|
||||||
|
} catch (err: unknown) {
|
||||||
|
setError(getErrorMessage(err, '加载配置失败'));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const loading = configLoading || configFetching;
|
||||||
|
const refreshConfig = useCallback(() => {
|
||||||
|
skipNextSyncRef.current = true;
|
||||||
|
return refetchConfig();
|
||||||
|
}, [refetchConfig]);
|
||||||
|
const saveMutation = useApiMutation(
|
||||||
|
async (body: Record<string, unknown>) => api.put('/ai/config', body),
|
||||||
|
{ invalidate: [['ai', 'config']] },
|
||||||
|
);
|
||||||
|
const clearKeyMutation = useApiMutation(
|
||||||
|
async () => api.post('/ai/config/clear-key'),
|
||||||
|
{ invalidate: [['ai', 'config']] },
|
||||||
|
);
|
||||||
|
|
||||||
const canWrite = hasPermission('ai:config:write');
|
const canWrite = hasPermission('ai:config:write');
|
||||||
const canTest = hasPermission('ai:config:test');
|
const canTest = hasPermission('ai:config:test');
|
||||||
const canRead = hasPermission('ai:config:read');
|
const canRead = hasPermission('ai:config:read');
|
||||||
|
|
||||||
// ── Load config ──
|
// ── Sync form → state ──
|
||||||
|
|
||||||
const loadConfig = useCallback(async () => {
|
const handleFormChange = useCallback(
|
||||||
setLoading(true);
|
(_changed: Partial<FormValues>, all: Partial<FormValues>) => {
|
||||||
setError(null);
|
setFormValues((prev) => ({ ...prev, ...all }));
|
||||||
try {
|
},
|
||||||
const res = await api.get<ApiResponse<AiConfigData>>('/ai/config');
|
[],
|
||||||
setConfig(res.data);
|
);
|
||||||
form.setFieldsValue({
|
|
||||||
provider: res.data.provider,
|
|
||||||
baseUrl: res.data.baseUrl,
|
|
||||||
defaultModel: res.data.defaultModel ?? undefined,
|
|
||||||
enabled: res.data.enabled,
|
|
||||||
timeoutMs: res.data.timeoutMs,
|
|
||||||
});
|
|
||||||
lastProviderRef.current = res.data.provider;
|
|
||||||
} catch (err: unknown) {
|
|
||||||
setError(extractErrorMessage(err, '加载配置失败'));
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
}, [form]);
|
|
||||||
|
|
||||||
|
// 配置数据到位后同步进表单(antd Form 属于外部系统);
|
||||||
|
// refreshConfig(测试/拉模型后)只刷新展示,不覆盖用户表单输入。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadConfig();
|
if (!config) return;
|
||||||
}, [loadConfig]);
|
if (skipNextSyncRef.current) {
|
||||||
|
skipNextSyncRef.current = false;
|
||||||
|
appliedConfigRef.current = config;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (appliedConfigRef.current === config) return;
|
||||||
|
appliedConfigRef.current = config;
|
||||||
|
const initial: FormValues = {
|
||||||
|
provider: config.provider,
|
||||||
|
baseUrl: config.baseUrl,
|
||||||
|
apiKey: '',
|
||||||
|
defaultModel: config.defaultModel ?? '',
|
||||||
|
timeoutMs: config.timeoutMs,
|
||||||
|
supportsVision: config.supportsVision,
|
||||||
|
reasoningEffort: config.reasoningEffort ?? '',
|
||||||
|
};
|
||||||
|
form.setFieldsValue(initial);
|
||||||
|
setFormValues(initial);
|
||||||
|
lastProviderRef.current = config.provider;
|
||||||
|
if (config.defaultModel) {
|
||||||
|
setModelOptions([{ value: config.defaultModel, label: config.defaultModel }]);
|
||||||
|
}
|
||||||
|
setError(null);
|
||||||
|
}, [config, form]);
|
||||||
|
|
||||||
// ── Provider change → swap baseUrl ──
|
// ── Provider change → swap baseUrl ──
|
||||||
|
|
||||||
const handleProviderChange = useCallback(
|
const handleProviderChange = useCallback(
|
||||||
(provider: AiProvider) => {
|
(provider: AiProvider) => {
|
||||||
const currentBaseUrl = form.getFieldValue('baseUrl') || '';
|
const result = shouldAutoSwapBaseUrl(provider, formValues.baseUrl, lastProviderRef.current);
|
||||||
const result = shouldAutoSwapBaseUrl(provider, currentBaseUrl, lastProviderRef.current);
|
|
||||||
if (result.shouldSwap) {
|
if (result.shouldSwap) {
|
||||||
form.setFieldValue('baseUrl', result.baseUrl);
|
form.setFieldValue('baseUrl', result.baseUrl);
|
||||||
}
|
}
|
||||||
lastProviderRef.current = provider;
|
lastProviderRef.current = provider;
|
||||||
},
|
},
|
||||||
[form],
|
[form, formValues.baseUrl],
|
||||||
);
|
);
|
||||||
|
|
||||||
const currentProvider = Form.useWatch('provider', form) as AiProvider | undefined;
|
const currentProvider = formValues.provider;
|
||||||
const isFixedProvider = currentProvider ? FIXED_PROVIDERS.includes(currentProvider) : false;
|
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(getErrorMessage(err, '获取模型列表失败'));
|
||||||
|
} finally {
|
||||||
|
setFetchingModels(false);
|
||||||
|
}
|
||||||
|
}, [form, formValues]);
|
||||||
|
|
||||||
// ── Save ──
|
// ── Save ──
|
||||||
|
|
||||||
const handleSave = useCallback(async () => {
|
const handleSave = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const values = await form.validateFields();
|
// Validate fields (for UI error display) — actual values come from state
|
||||||
setSaving(true);
|
await form.validateFields(['provider', 'baseUrl', 'timeoutMs']);
|
||||||
|
|
||||||
// Validate baseUrl for OPENAI_COMPATIBLE
|
const {
|
||||||
if (values.provider === 'OPENAI_COMPATIBLE' && !values.baseUrl) {
|
provider,
|
||||||
|
baseUrl,
|
||||||
|
defaultModel,
|
||||||
|
apiKey,
|
||||||
|
timeoutMs,
|
||||||
|
supportsVision,
|
||||||
|
reasoningEffort,
|
||||||
|
} = formValues;
|
||||||
|
|
||||||
|
if (provider === 'OPENAI_COMPATIBLE' && !baseUrl) {
|
||||||
message.error('OPENAI_COMPATIBLE 模式必须填写 Base URL');
|
message.error('OPENAI_COMPATIBLE 模式必须填写 Base URL');
|
||||||
setSaving(false);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setSaving(true);
|
||||||
|
|
||||||
|
const resolvedBaseUrl = baseUrl || PROVIDER_DEFAULTS[provider] || '';
|
||||||
|
|
||||||
const body: Record<string, unknown> = {
|
const body: Record<string, unknown> = {
|
||||||
provider: values.provider,
|
provider,
|
||||||
baseUrl: values.baseUrl,
|
baseUrl: resolvedBaseUrl,
|
||||||
defaultModel: values.defaultModel || undefined,
|
defaultModel: defaultModel || undefined,
|
||||||
enabled: values.enabled,
|
enabled: true,
|
||||||
timeoutMs: values.timeoutMs,
|
supportsVision,
|
||||||
|
timeoutMs,
|
||||||
|
reasoningEffort: reasoningEffort || null,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (values.apiKey && values.apiKey !== '••••') {
|
if (apiKey && apiKey !== '••••') {
|
||||||
body.apiKey = values.apiKey;
|
body.apiKey = apiKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
await api.put('/ai/config', body);
|
await saveMutation.mutateAsync(body);
|
||||||
message.success('配置已保存');
|
message.success('配置已保存');
|
||||||
form.setFieldValue('apiKey', '');
|
form.setFieldValue('apiKey', '');
|
||||||
} catch (err: unknown) {
|
setFormValues((prev) => ({ ...prev, apiKey: '' }));
|
||||||
message.error(extractErrorMessage(err, '保存失败'));
|
} catch {
|
||||||
setSaving(false);
|
// 错误提示由 useApiMutation 统一处理
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reload config from server (non-fatal if it fails)
|
|
||||||
try {
|
|
||||||
await loadConfig();
|
|
||||||
} catch (err: unknown) {
|
|
||||||
message.warning(extractErrorMessage(err, '配置已保存,但刷新失败'));
|
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false);
|
setSaving(false);
|
||||||
}
|
}
|
||||||
}, [form, loadConfig]);
|
}, [formValues, form, saveMutation]);
|
||||||
|
|
||||||
// ── Test connection ──
|
// ── Test connection ──
|
||||||
|
|
||||||
const handleTest = useCallback(async () => {
|
const handleTest = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
// Validated fields: compatible requires baseUrl
|
|
||||||
const fieldsToValidate = ['provider', 'timeoutMs'] as string[];
|
const fieldsToValidate = ['provider', 'timeoutMs'] as string[];
|
||||||
if (currentProvider === 'OPENAI_COMPATIBLE') {
|
if (currentProvider === 'OPENAI_COMPATIBLE') {
|
||||||
fieldsToValidate.push('baseUrl');
|
fieldsToValidate.push('baseUrl');
|
||||||
}
|
}
|
||||||
const values = await form.validateFields(fieldsToValidate);
|
await form.validateFields(fieldsToValidate);
|
||||||
|
|
||||||
setTesting(true);
|
setTesting(true);
|
||||||
setTestResult(null);
|
setTestResult(null);
|
||||||
|
|
||||||
const body: Record<string, unknown> = {
|
const { provider, baseUrl, defaultModel, apiKey, timeoutMs, reasoningEffort } = formValues;
|
||||||
timeoutMs: values.timeoutMs,
|
const body: Record<string, unknown> = { provider, timeoutMs };
|
||||||
};
|
if (baseUrl) body.baseUrl = baseUrl;
|
||||||
|
|
||||||
// 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');
|
|
||||||
if (defaultModel) body.defaultModel = defaultModel;
|
if (defaultModel) body.defaultModel = defaultModel;
|
||||||
|
if (apiKey && apiKey !== '••••') body.apiKey = apiKey;
|
||||||
const typedKey = form.getFieldValue('apiKey');
|
if (reasoningEffort) body.reasoningEffort = reasoningEffort;
|
||||||
if (typedKey && typedKey !== '••••') {
|
|
||||||
body.apiKey = typedKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
const res = await api.post<TestResult>('/ai/config/test', body);
|
const res = await api.post<TestResult>('/ai/config/test', body);
|
||||||
setTestResult(res);
|
setTestResult(res);
|
||||||
await loadConfig();
|
await refreshConfig();
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
setTestResult({
|
setTestResult({
|
||||||
success: false,
|
success: false,
|
||||||
@@ -229,12 +271,12 @@ const AiConfigPage: React.FC = () => {
|
|||||||
modelCount: null,
|
modelCount: null,
|
||||||
modelAvailable: false,
|
modelAvailable: false,
|
||||||
testedAt: new Date().toISOString(),
|
testedAt: new Date().toISOString(),
|
||||||
message: extractErrorMessage(err, '测试请求失败'),
|
message: getErrorMessage(err, '测试请求失败'),
|
||||||
});
|
});
|
||||||
} finally {
|
} finally {
|
||||||
setTesting(false);
|
setTesting(false);
|
||||||
}
|
}
|
||||||
}, [form, loadConfig, currentProvider]);
|
}, [formValues, form, currentProvider, refreshConfig]);
|
||||||
|
|
||||||
// ── Clear key ──
|
// ── Clear key ──
|
||||||
|
|
||||||
@@ -250,15 +292,33 @@ const AiConfigPage: React.FC = () => {
|
|||||||
cancelText: '取消',
|
cancelText: '取消',
|
||||||
onOk: async () => {
|
onOk: async () => {
|
||||||
try {
|
try {
|
||||||
await api.post('/ai/config/clear-key');
|
await clearKeyMutation.mutateAsync();
|
||||||
message.success('密钥已清除');
|
message.success('密钥已清除');
|
||||||
await loadConfig();
|
} catch {
|
||||||
} catch (err: unknown) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error(extractErrorMessage(err, '清除失败'));
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}, [config, loadConfig, modal]);
|
}, [config, modal, clearKeyMutation]);
|
||||||
|
|
||||||
|
// ── Step navigation ──
|
||||||
|
|
||||||
|
const goNext = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
if (currentStep === 0) {
|
||||||
|
await form.validateFields(['provider', 'baseUrl', 'timeoutMs']);
|
||||||
|
} 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 ──
|
// ── No read permission ──
|
||||||
|
|
||||||
@@ -286,6 +346,49 @@ const AiConfigPage: React.FC = () => {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const renderStepContent = () => {
|
||||||
|
switch (currentStep) {
|
||||||
|
case 0:
|
||||||
|
return (
|
||||||
|
<ProviderStep
|
||||||
|
canWrite={canWrite}
|
||||||
|
isFixedProvider={isFixedProvider}
|
||||||
|
config={config}
|
||||||
|
onProviderChange={handleProviderChange}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
case 1:
|
||||||
|
return <KeyStep canWrite={canWrite} config={config} onClearKey={handleClearKey} />;
|
||||||
|
case 2:
|
||||||
|
return (
|
||||||
|
<ModelStep
|
||||||
|
canWrite={canWrite}
|
||||||
|
config={config}
|
||||||
|
onFetchModels={handleFetchModels}
|
||||||
|
fetchingModels={fetchingModels}
|
||||||
|
modelOptions={modelOptions}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
case 3:
|
||||||
|
return (
|
||||||
|
<SaveTestStep
|
||||||
|
canWrite={canWrite}
|
||||||
|
canTest={canTest}
|
||||||
|
config={config}
|
||||||
|
currentProvider={currentProvider}
|
||||||
|
formValues={formValues}
|
||||||
|
onSave={handleSave}
|
||||||
|
saving={saving}
|
||||||
|
onTest={handleTest}
|
||||||
|
testing={testing}
|
||||||
|
testResult={testResult}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// ── Render ──
|
// ── Render ──
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -308,204 +411,33 @@ const AiConfigPage: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Form form={form} layout="vertical" initialValues={{ timeoutMs: 30000, enabled: false }}>
|
<Steps
|
||||||
<div className={styles.grid}>
|
current={currentStep}
|
||||||
{/* Left: 模型路由 */}
|
items={STEP_ITEMS}
|
||||||
<Card title={<span className={styles.cardTitle}>模型路由</span>} extra={<ApiOutlined />}>
|
onChange={setCurrentStep}
|
||||||
<Form.Item
|
className={styles.steps}
|
||||||
name="provider"
|
size="small"
|
||||||
label="Provider"
|
/>
|
||||||
rules={[{ required: true, message: '请选择 Provider' }]}
|
|
||||||
>
|
|
||||||
<Select
|
|
||||||
options={PROVIDER_OPTIONS}
|
|
||||||
onChange={handleProviderChange}
|
|
||||||
disabled={!canWrite}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
|
|
||||||
<Form.Item
|
<Form
|
||||||
name="baseUrl"
|
form={form}
|
||||||
label="Base URL"
|
layout="vertical"
|
||||||
rules={[
|
initialValues={{ timeoutMs: 30000 }}
|
||||||
{ required: true, message: '请输入 Base URL' },
|
onValuesChange={handleFormChange}
|
||||||
{ type: 'url', message: '请输入合法的 URL' },
|
>
|
||||||
]}
|
<div className={styles.stepContent}>{renderStepContent()}</div>
|
||||||
>
|
|
||||||
<Input
|
|
||||||
placeholder={
|
|
||||||
config?.provider
|
|
||||||
? PROVIDER_DEFAULTS[config.provider]
|
|
||||||
: 'https://api.openai.com/v1'
|
|
||||||
}
|
|
||||||
disabled={!canWrite || (isFixedProvider && canWrite)}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
|
|
||||||
<Form.Item noStyle shouldUpdate={(prev, curr) => prev.enabled !== curr.enabled}>
|
<div className={styles.stepNav}>
|
||||||
{({ getFieldValue }) => {
|
<Button onClick={goPrev} disabled={currentStep === 0} icon={<span>←</span>}>
|
||||||
const enabled = getFieldValue('enabled');
|
上一步
|
||||||
return (
|
</Button>
|
||||||
<Form.Item
|
{currentStep < STEP_ITEMS.length - 1 ? (
|
||||||
name="defaultModel"
|
<Button type="primary" onClick={goNext} icon={<span>→</span>}>
|
||||||
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="请求超时 (毫秒)"
|
|
||||||
rules={[
|
|
||||||
{ required: true, message: '请输入超时时间' },
|
|
||||||
{ type: 'number', min: 1000, max: 120000, message: '范围: 1000-120000' },
|
|
||||||
]}
|
|
||||||
>
|
|
||||||
<InputNumber
|
|
||||||
min={1000}
|
|
||||||
max={120000}
|
|
||||||
step={1000}
|
|
||||||
style={{ width: '100%' }}
|
|
||||||
disabled={!canWrite}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Right: 密钥保险库 */}
|
|
||||||
<Card
|
|
||||||
title={<span className={styles.cardTitle}>密钥保险库</span>}
|
|
||||||
extra={<KeyOutlined />}
|
|
||||||
>
|
|
||||||
<Form.Item name="apiKey" label="API Key">
|
|
||||||
<Input.Password
|
|
||||||
placeholder={config?.hasApiKey ? '已安全保存,留空则保持不变' : '请输入 API Key'}
|
|
||||||
disabled={!canWrite}
|
|
||||||
autoComplete="new-password"
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
|
|
||||||
{config && (
|
|
||||||
<Descriptions column={1} size="small" style={{ marginBottom: 12 }}>
|
|
||||||
<Descriptions.Item label="状态">
|
|
||||||
{config.hasApiKey ? (
|
|
||||||
<Tag color="green">{config.maskedApiKey || '••••'}</Tag>
|
|
||||||
) : (
|
|
||||||
<Tag color="default">未配置</Tag>
|
|
||||||
)}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="来源">
|
|
||||||
<Tag color={sourceColor(config.keySource)}>{sourceLabel(config.keySource)}</Tag>
|
|
||||||
{config.keySource === 'environment' && (
|
|
||||||
<span style={{ marginLeft: 8, fontSize: 12, color: '#999' }}>
|
|
||||||
由环境变量托管,需在服务器修改
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="最后更新">
|
|
||||||
{formatDateTime(config.updatedAt)}
|
|
||||||
</Descriptions.Item>
|
|
||||||
</Descriptions>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{config?.hasDatabaseKey && canWrite && (
|
|
||||||
<div style={{ marginBottom: 8 }}>
|
|
||||||
<Button danger size="small" onClick={handleClearKey}>
|
|
||||||
清除服务器保存密钥
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{config?.keySource === 'environment' && !config.hasDatabaseKey && (
|
|
||||||
<div style={{ marginBottom: 8, fontSize: 12, color: '#999' }}>
|
|
||||||
密钥由环境变量提供,无法通过页面清除
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className={styles.safetyNote}>
|
|
||||||
API Key 使用 AES-256-GCM 加密存储,每次保存使用随机 IV。 传输层通过 HTTPS
|
|
||||||
保护,服务端日志不记录密钥。
|
|
||||||
</div>
|
|
||||||
<div className={styles.safetyNoteKey}>
|
|
||||||
也可通过环境变量 <Typography.Text code>AI_API_KEY</Typography.Text> 注入密钥,
|
|
||||||
环境变量优先级高于数据库存储。
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Actions */}
|
|
||||||
<div className={styles.actions}>
|
|
||||||
<Tooltip title={!canWrite ? '当前角色无写入权限' : undefined}>
|
|
||||||
<Button
|
|
||||||
type="primary"
|
|
||||||
icon={<SaveOutlined />}
|
|
||||||
onClick={handleSave}
|
|
||||||
loading={saving}
|
|
||||||
disabled={!canWrite}
|
|
||||||
>
|
|
||||||
保存配置
|
|
||||||
</Button>
|
</Button>
|
||||||
</Tooltip>
|
) : null}
|
||||||
<Tooltip title={!canTest ? '当前角色无测试权限' : undefined}>
|
|
||||||
<Button
|
|
||||||
icon={<ApiOutlined />}
|
|
||||||
onClick={handleTest}
|
|
||||||
loading={testing}
|
|
||||||
disabled={!canTest}
|
|
||||||
>
|
|
||||||
测试连接
|
|
||||||
</Button>
|
|
||||||
</Tooltip>
|
|
||||||
</div>
|
</div>
|
||||||
</Form>
|
</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>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
199
apps/admin/src/pages/Attendance/AttendanceAdmin.helpers.tsx
Normal file
199
apps/admin/src/pages/Attendance/AttendanceAdmin.helpers.tsx
Normal file
@@ -0,0 +1,199 @@
|
|||||||
|
import dayjs from 'dayjs';
|
||||||
|
import type { AttendanceSummary } from './attendance-workspace';
|
||||||
|
import type { LessonAttendanceRecord } from './types';
|
||||||
|
|
||||||
|
export type { AttendanceSummary } from './attendance-workspace';
|
||||||
|
|
||||||
|
export 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 },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const STATUS_META: Record<
|
||||||
|
string,
|
||||||
|
{ label: string; color: string; className: string; short: string }
|
||||||
|
> = {
|
||||||
|
present: { label: '出勤', color: 'success', className: 'is-present', short: '勤' },
|
||||||
|
absent: { label: '缺勤', color: 'error', className: 'is-absent', short: '缺' },
|
||||||
|
leave: { label: '请假', color: 'processing', className: 'is-leave', short: '假' },
|
||||||
|
pending: { label: '待确认', color: 'default', className: 'is-pending', short: '待' },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ADMIN_CORRECTION_OPTIONS = [
|
||||||
|
{ value: 'present', label: '正常' },
|
||||||
|
{ value: 'leave', label: '请假' },
|
||||||
|
{ value: 'absent', label: '缺勤' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export interface ClassTeacherOption {
|
||||||
|
userId: number;
|
||||||
|
username: string | null;
|
||||||
|
name: string | null;
|
||||||
|
roleType: string;
|
||||||
|
subject: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClassOption {
|
||||||
|
classId: number;
|
||||||
|
className: string;
|
||||||
|
teachers?: ClassTeacherOption[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AttendanceRecordItem = LessonAttendanceRecord;
|
||||||
|
|
||||||
|
export interface HistoryScheduleOption {
|
||||||
|
id: number;
|
||||||
|
classId: number;
|
||||||
|
weekDay: number;
|
||||||
|
startTime: string;
|
||||||
|
endTime: string;
|
||||||
|
startDate: string;
|
||||||
|
endDate: string;
|
||||||
|
subject: string;
|
||||||
|
teacherId: number | null;
|
||||||
|
teacherName?: string | null;
|
||||||
|
teacherUsername?: string | null;
|
||||||
|
status: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AlertItem {
|
||||||
|
studentId: number;
|
||||||
|
studentName: string;
|
||||||
|
studentNo: string;
|
||||||
|
className: string;
|
||||||
|
type: string;
|
||||||
|
count: number;
|
||||||
|
lastDate: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AttendancePeriodConfigItem {
|
||||||
|
id?: number;
|
||||||
|
periodKey: string;
|
||||||
|
label: string;
|
||||||
|
startTime: string;
|
||||||
|
endTime: string;
|
||||||
|
sortOrder: number;
|
||||||
|
enabled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DingTalkSyncStatus {
|
||||||
|
lastPulledAt: string | null;
|
||||||
|
action: string | null;
|
||||||
|
username: string | null;
|
||||||
|
detail: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const EMPTY_SUMMARY: AttendanceSummary = {
|
||||||
|
total: 0,
|
||||||
|
present: 0,
|
||||||
|
late: 0,
|
||||||
|
absent: 0,
|
||||||
|
leave: 0,
|
||||||
|
pending: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
export function displayAttendanceStatus(status?: string | null): string {
|
||||||
|
return status === 'pending' || !status ? 'absent' : status;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTeacherDisplayName(teacher?: {
|
||||||
|
name?: string | null;
|
||||||
|
username?: string | null;
|
||||||
|
}): string {
|
||||||
|
const name = teacher?.name?.trim();
|
||||||
|
if (name) return name;
|
||||||
|
return teacher?.username?.trim() || '未设置';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatTeacherNames(
|
||||||
|
teachers: readonly { name?: string | null; username?: string | null }[],
|
||||||
|
): string {
|
||||||
|
const names = [
|
||||||
|
...new Set(
|
||||||
|
teachers
|
||||||
|
.map((teacher) => getTeacherDisplayName(teacher))
|
||||||
|
.filter((name) => name && name !== '未设置'),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
return names.length > 0 ? names.join('、') : '未设置';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AttendanceStatusTag({ status }: { status: string }) {
|
||||||
|
const displayStatus = displayAttendanceStatus(status);
|
||||||
|
const meta = STATUS_META[displayStatus] ?? {
|
||||||
|
label: displayStatus,
|
||||||
|
color: 'default',
|
||||||
|
className: 'is-absent',
|
||||||
|
short: '?',
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<span className={`attendance-status ${meta.className}`}>
|
||||||
|
<span className="attendance-status__dot" />
|
||||||
|
{meta.label}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminStudentPanel {
|
||||||
|
key: string;
|
||||||
|
studentId: number;
|
||||||
|
studentName: string;
|
||||||
|
studentNo: string;
|
||||||
|
className: string;
|
||||||
|
records: AttendanceRecordItem[];
|
||||||
|
statusBySession: Partial<Record<string, AttendanceRecordItem>>;
|
||||||
|
primaryStatus: string;
|
||||||
|
rate: number;
|
||||||
|
latestDate: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ADMIN_METRIC_META = [
|
||||||
|
{ key: 'all', label: '出勤率', short: '率' },
|
||||||
|
{ key: 'present', label: '正常', short: '正常' },
|
||||||
|
{ key: 'leave', label: '请假', short: '请假' },
|
||||||
|
{ key: 'absent', label: '缺勤', short: '缺勤' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function pickPrimaryStatus(records: AttendanceRecordItem[]) {
|
||||||
|
const priority = ['absent', 'leave', 'present'];
|
||||||
|
return (
|
||||||
|
priority.find((item) =>
|
||||||
|
records.some((record) => displayAttendanceStatus(record.status) === item),
|
||||||
|
) || 'absent'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildAdminStudentPanels(records: AttendanceRecordItem[]): AdminStudentPanel[] {
|
||||||
|
const map = new Map<number, AdminStudentPanel>();
|
||||||
|
for (const record of records) {
|
||||||
|
const current = map.get(record.studentId) ?? {
|
||||||
|
key: String(record.studentId),
|
||||||
|
studentId: record.studentId,
|
||||||
|
studentName: record.student?.name || '未知学生',
|
||||||
|
studentNo: record.student?.studentNo?.trim() || '',
|
||||||
|
className: record.class?.name || '未关联班级',
|
||||||
|
records: [],
|
||||||
|
statusBySession: {},
|
||||||
|
primaryStatus: 'absent',
|
||||||
|
rate: 0,
|
||||||
|
latestDate: record.attendanceDate,
|
||||||
|
};
|
||||||
|
current.records.push(record);
|
||||||
|
if (!current.statusBySession[record.session]) current.statusBySession[record.session] = record;
|
||||||
|
if (dayjs(record.attendanceDate).isAfter(dayjs(current.latestDate))) {
|
||||||
|
current.latestDate = record.attendanceDate;
|
||||||
|
}
|
||||||
|
map.set(record.studentId, current);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Array.from(map.values()).map((item) => {
|
||||||
|
const checked = item.records.filter((record) => record.status === 'present').length;
|
||||||
|
return {
|
||||||
|
...item,
|
||||||
|
primaryStatus: pickPrimaryStatus(item.records),
|
||||||
|
rate: item.records.length > 0 ? Math.round((checked / item.records.length) * 100) : 0,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
131
apps/admin/src/pages/Attendance/AttendanceAdminColumns.tsx
Normal file
131
apps/admin/src/pages/Attendance/AttendanceAdminColumns.tsx
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
import { Avatar, Segmented, Tag } from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
import EditableCell from '../../components/EditableCell';
|
||||||
|
import { getPunchDisplayInfo } from './attendance-workspace';
|
||||||
|
import {
|
||||||
|
ADMIN_CORRECTION_OPTIONS,
|
||||||
|
AttendanceStatusTag,
|
||||||
|
displayAttendanceStatus,
|
||||||
|
type AttendanceRecordItem,
|
||||||
|
} from './AttendanceAdmin.helpers';
|
||||||
|
|
||||||
|
export interface AttendanceAdminColumnContext {
|
||||||
|
isMobile: boolean;
|
||||||
|
canEdit: boolean;
|
||||||
|
sessionMap: Record<string, string>;
|
||||||
|
correctingRecordId: number | null;
|
||||||
|
onSaveAdminRecordCell: (
|
||||||
|
record: AttendanceRecordItem,
|
||||||
|
field: 'status' | 'remark',
|
||||||
|
value: unknown,
|
||||||
|
) => void;
|
||||||
|
onUpdateAdminRecordStatus: (record: AttendanceRecordItem, nextStatus: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const buildAttendanceAdminDataColumns = (ctx: AttendanceAdminColumnContext) => {
|
||||||
|
const { isMobile, canEdit, sessionMap, onSaveAdminRecordCell } = ctx;
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
title: '学生',
|
||||||
|
dataIndex: ['student', 'name'],
|
||||||
|
fixed: (isMobile ? undefined : 'left') as 'left' | undefined,
|
||||||
|
width: 150,
|
||||||
|
render: (name: string, record: AttendanceRecordItem) => (
|
||||||
|
<div className="student-cell">
|
||||||
|
<Avatar size={34}>{name?.slice(0, 1)}</Avatar>
|
||||||
|
<div>
|
||||||
|
<strong>{name || '-'}</strong>
|
||||||
|
<span>{record.class?.name || '未关联班级'}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{ title: '日期', dataIndex: 'attendanceDate', width: 120 },
|
||||||
|
{
|
||||||
|
title: '时段',
|
||||||
|
dataIndex: 'session',
|
||||||
|
width: 110,
|
||||||
|
render: (value: string) => sessionMap[value] || value,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'status',
|
||||||
|
width: 105,
|
||||||
|
render: (value: string, record: AttendanceRecordItem) => (
|
||||||
|
<EditableCell
|
||||||
|
value={displayAttendanceStatus(value)}
|
||||||
|
editor="select"
|
||||||
|
options={ADMIN_CORRECTION_OPTIONS.map((item) => ({
|
||||||
|
value: String(item.value),
|
||||||
|
label: item.label,
|
||||||
|
}))}
|
||||||
|
disabled={!canEdit}
|
||||||
|
onSave={async (next) => {
|
||||||
|
onSaveAdminRecordCell(record, 'status', next);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<AttendanceStatusTag status={displayAttendanceStatus(value)} />
|
||||||
|
</EditableCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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',
|
||||||
|
ellipsis: true,
|
||||||
|
render: (value: string | null, record: AttendanceRecordItem) => (
|
||||||
|
<EditableCell
|
||||||
|
value={value}
|
||||||
|
editor="textarea"
|
||||||
|
disabled={!canEdit}
|
||||||
|
onSave={async (next) => {
|
||||||
|
onSaveAdminRecordCell(record, 'remark', next);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{value || <span className="muted-text">—</span>}
|
||||||
|
</EditableCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
] as ColumnsType<AttendanceRecordItem>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildAttendanceAdminActionColumn = (ctx: AttendanceAdminColumnContext) => {
|
||||||
|
const { isMobile, correctingRecordId, onUpdateAdminRecordStatus } = ctx;
|
||||||
|
return {
|
||||||
|
title: '操作',
|
||||||
|
key: 'action',
|
||||||
|
fixed: (isMobile ? undefined : 'right') as 'right' | undefined,
|
||||||
|
width: 220,
|
||||||
|
render: (_: unknown, record: AttendanceRecordItem) => (
|
||||||
|
<Segmented
|
||||||
|
size="small"
|
||||||
|
className="attendance-correction-segment"
|
||||||
|
options={ADMIN_CORRECTION_OPTIONS}
|
||||||
|
value={displayAttendanceStatus(record.status)}
|
||||||
|
disabled={correctingRecordId === record.id}
|
||||||
|
onChange={(value) => void onUpdateAdminRecordStatus(record, String(value))}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const buildAttendanceAdminColumns = (ctx: AttendanceAdminColumnContext) => {
|
||||||
|
const dataColumns = buildAttendanceAdminDataColumns(ctx);
|
||||||
|
const actionColumn = ctx.canEdit ? [buildAttendanceAdminActionColumn(ctx)] : [];
|
||||||
|
return [...dataColumns, ...actionColumn] as ColumnsType<AttendanceRecordItem>;
|
||||||
|
};
|
||||||
274
apps/admin/src/pages/Attendance/AttendanceAdminHeader.tsx
Normal file
274
apps/admin/src/pages/Attendance/AttendanceAdminHeader.tsx
Normal file
@@ -0,0 +1,274 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import {
|
||||||
|
Avatar,
|
||||||
|
Button,
|
||||||
|
DatePicker,
|
||||||
|
Select,
|
||||||
|
Spin,
|
||||||
|
Tooltip,
|
||||||
|
} from 'antd';
|
||||||
|
import {
|
||||||
|
ExportOutlined,
|
||||||
|
FileSearchOutlined,
|
||||||
|
ReloadOutlined,
|
||||||
|
ScheduleOutlined,
|
||||||
|
UndoOutlined,
|
||||||
|
WarningFilled,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import dayjs, { type Dayjs } from 'dayjs';
|
||||||
|
import PermissionButton from '../../components/PermissionButton';
|
||||||
|
import {
|
||||||
|
ADMIN_METRIC_META,
|
||||||
|
STATUS_META,
|
||||||
|
type AlertItem,
|
||||||
|
type AttendanceSummary,
|
||||||
|
type ClassOption,
|
||||||
|
type DingTalkSyncStatus,
|
||||||
|
type HistoryScheduleOption,
|
||||||
|
} from './AttendanceAdmin.helpers';
|
||||||
|
|
||||||
|
export const AttendanceAdminHeader: React.FC<{
|
||||||
|
syncStatus: DingTalkSyncStatus | null;
|
||||||
|
canEdit: boolean;
|
||||||
|
refreshingDingTalk: boolean;
|
||||||
|
onOpenPeriodConfig: () => void;
|
||||||
|
onRefreshDingTalk: () => void;
|
||||||
|
onExport: () => void;
|
||||||
|
attendanceDate: Dayjs | null;
|
||||||
|
onDateChange: (date: Dayjs | null) => void;
|
||||||
|
classId?: number;
|
||||||
|
onClassChange: (value?: number) => void;
|
||||||
|
classOptions: ClassOption[];
|
||||||
|
effectiveScheduleId?: number;
|
||||||
|
onScheduleChange: (value?: number) => void;
|
||||||
|
scheduleOptions: HistoryScheduleOption[];
|
||||||
|
scheduleOptionsLoading: boolean;
|
||||||
|
session?: string;
|
||||||
|
onSessionChange: (value?: string) => void;
|
||||||
|
sessionOptions: Array<{ value: string; label: string }>;
|
||||||
|
onReset: () => void;
|
||||||
|
onQuery: () => void;
|
||||||
|
selectedClass: string;
|
||||||
|
dateLabel: string;
|
||||||
|
visibleStudentCount: number;
|
||||||
|
total: number;
|
||||||
|
headTeacherNames: string;
|
||||||
|
lifeTeacherNames: string;
|
||||||
|
subjectTeacherNames: string;
|
||||||
|
attendanceRate: number;
|
||||||
|
summary: AttendanceSummary;
|
||||||
|
metricFilter: string;
|
||||||
|
onMetricFilterChange: (key: string) => void;
|
||||||
|
alerts: AlertItem[];
|
||||||
|
}> = ({
|
||||||
|
syncStatus,
|
||||||
|
canEdit,
|
||||||
|
refreshingDingTalk,
|
||||||
|
onOpenPeriodConfig,
|
||||||
|
onRefreshDingTalk,
|
||||||
|
onExport,
|
||||||
|
attendanceDate,
|
||||||
|
onDateChange,
|
||||||
|
classId,
|
||||||
|
onClassChange,
|
||||||
|
classOptions,
|
||||||
|
effectiveScheduleId,
|
||||||
|
onScheduleChange,
|
||||||
|
scheduleOptions,
|
||||||
|
scheduleOptionsLoading,
|
||||||
|
session,
|
||||||
|
onSessionChange,
|
||||||
|
sessionOptions,
|
||||||
|
onReset,
|
||||||
|
onQuery,
|
||||||
|
selectedClass,
|
||||||
|
dateLabel,
|
||||||
|
visibleStudentCount,
|
||||||
|
total,
|
||||||
|
headTeacherNames,
|
||||||
|
lifeTeacherNames,
|
||||||
|
subjectTeacherNames,
|
||||||
|
attendanceRate,
|
||||||
|
summary,
|
||||||
|
metricFilter,
|
||||||
|
onMetricFilterChange,
|
||||||
|
alerts,
|
||||||
|
}) => {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<header className="student-center-topbar">
|
||||||
|
<div className="student-center-title">
|
||||||
|
<h1>学生考勤中心</h1>
|
||||||
|
<span>班级考勤总览</span>
|
||||||
|
</div>
|
||||||
|
<div className="student-center-actions">
|
||||||
|
<Tooltip title={syncStatus?.detail || syncStatus?.action || '暂无钉钉拉取记录'}>
|
||||||
|
<span className="student-sync-status">
|
||||||
|
<i />
|
||||||
|
{syncStatus?.lastPulledAt
|
||||||
|
? `最近拉取钉钉 ${dayjs(syncStatus.lastPulledAt).format('YYYY-MM-DD HH:mm')}`
|
||||||
|
: '暂无钉钉拉取记录'}
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
{canEdit && (
|
||||||
|
<Button icon={<ScheduleOutlined />} onClick={onOpenPeriodConfig}>
|
||||||
|
时段配置
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<PermissionButton
|
||||||
|
permission="attendance:create"
|
||||||
|
icon={<ReloadOutlined />}
|
||||||
|
loading={refreshingDingTalk}
|
||||||
|
onClick={onRefreshDingTalk}
|
||||||
|
>
|
||||||
|
刷新钉钉考勤
|
||||||
|
</PermissionButton>
|
||||||
|
<PermissionButton permission="attendance:export" icon={<ExportOutlined />} onClick={onExport}>
|
||||||
|
导出当前报表
|
||||||
|
</PermissionButton>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section className="student-filter-panel" aria-label="考勤筛选">
|
||||||
|
<div className="student-filter-field student-filter-field--date">
|
||||||
|
<label>日期</label>
|
||||||
|
<DatePicker
|
||||||
|
allowClear={false}
|
||||||
|
value={attendanceDate}
|
||||||
|
disabledDate={(current) => current.isAfter(dayjs(), 'day')}
|
||||||
|
onChange={onDateChange}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="student-filter-field">
|
||||||
|
<label>班级</label>
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
showSearch
|
||||||
|
optionFilterProp="label"
|
||||||
|
placeholder="全部班级"
|
||||||
|
value={classId}
|
||||||
|
onChange={onClassChange}
|
||||||
|
options={classOptions.map((item) => ({ value: item.classId, label: item.className }))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="student-filter-field">
|
||||||
|
<label>科目</label>
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
showSearch
|
||||||
|
optionFilterProp="label"
|
||||||
|
placeholder={classId ? '全部科目' : '请先选择班级'}
|
||||||
|
value={effectiveScheduleId}
|
||||||
|
loading={scheduleOptionsLoading}
|
||||||
|
disabled={!classId || !attendanceDate}
|
||||||
|
notFoundContent={scheduleOptionsLoading ? <Spin size="small" /> : '当前日期没有排课'}
|
||||||
|
onChange={onScheduleChange}
|
||||||
|
options={scheduleOptions.map((schedule) => ({
|
||||||
|
value: schedule.id,
|
||||||
|
label: `${schedule.subject}(${schedule.startTime}-${schedule.endTime})`,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="student-filter-field">
|
||||||
|
<label>任课老师</label>
|
||||||
|
<Select disabled placeholder="全部老师" />
|
||||||
|
</div>
|
||||||
|
<div className="student-filter-field">
|
||||||
|
<label>时段</label>
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
placeholder="全部时段"
|
||||||
|
value={session}
|
||||||
|
onChange={onSessionChange}
|
||||||
|
options={sessionOptions}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="student-filter-actions">
|
||||||
|
<Button icon={<UndoOutlined />} onClick={onReset}>
|
||||||
|
重置
|
||||||
|
</Button>
|
||||||
|
<Button type="primary" icon={<FileSearchOutlined />} onClick={onQuery}>
|
||||||
|
查询
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="student-class-overview" aria-label="班级考勤汇总">
|
||||||
|
<div className="student-class-identity">
|
||||||
|
<div className="student-class-heading">
|
||||||
|
<h2>{selectedClass}</h2>
|
||||||
|
<p>
|
||||||
|
{dateLabel} · 当前展示 {visibleStudentCount} 名学生 / {total} 条记录
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="student-teacher-list" aria-label="筛选上下文">
|
||||||
|
<div className="student-teacher-item">
|
||||||
|
<Avatar>班</Avatar>
|
||||||
|
<div>
|
||||||
|
<span>班主任</span>
|
||||||
|
<strong>{headTeacherNames}</strong>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="student-teacher-item">
|
||||||
|
<Avatar>生</Avatar>
|
||||||
|
<div>
|
||||||
|
<span>生活老师</span>
|
||||||
|
<strong>{lifeTeacherNames}</strong>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="student-teacher-item">
|
||||||
|
<Avatar>任</Avatar>
|
||||||
|
<div>
|
||||||
|
<span>任课老师</span>
|
||||||
|
<strong>{subjectTeacherNames}</strong>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="student-metric-strip">
|
||||||
|
{ADMIN_METRIC_META.map((metric) => {
|
||||||
|
const value =
|
||||||
|
metric.key === 'all'
|
||||||
|
? `${attendanceRate}%`
|
||||||
|
: metric.key === 'absent'
|
||||||
|
? summary.absent + summary.pending
|
||||||
|
: (summary[metric.key as keyof AttendanceSummary] ?? 0);
|
||||||
|
const meta = STATUS_META[metric.key] ?? { className: 'is-present' };
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
key={metric.key}
|
||||||
|
className={`student-metric-card ${metricFilter === metric.key ? 'active' : ''}`}
|
||||||
|
onClick={() => onMetricFilterChange(metric.key)}
|
||||||
|
>
|
||||||
|
<span className={`student-metric-icon ${meta.className}`}>{metric.short}</span>
|
||||||
|
<span className="student-metric-copy">
|
||||||
|
<strong>{value}</strong>
|
||||||
|
<small>{metric.label}</small>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{alerts.length > 0 && (
|
||||||
|
<div className="archive-alert">
|
||||||
|
<WarningFilled />
|
||||||
|
<div>
|
||||||
|
<strong>{alerts.length} 名学生存在连续异常</strong>
|
||||||
|
<span>建议优先核查最近 14 天的缺勤记录</span>
|
||||||
|
</div>
|
||||||
|
<Tooltip
|
||||||
|
title={alerts
|
||||||
|
.slice(0, 5)
|
||||||
|
.map((item) => `${item.studentName}:${item.type}${item.count}次`)
|
||||||
|
.join(';')}
|
||||||
|
>
|
||||||
|
<Button type="link">查看摘要</Button>
|
||||||
|
</Tooltip>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
194
apps/admin/src/pages/Attendance/AttendanceAdminModals.tsx
Normal file
194
apps/admin/src/pages/Attendance/AttendanceAdminModals.tsx
Normal file
@@ -0,0 +1,194 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
Avatar,
|
||||||
|
Button,
|
||||||
|
Drawer,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
Modal,
|
||||||
|
Segmented,
|
||||||
|
Select,
|
||||||
|
} from 'antd';
|
||||||
|
import { UndoOutlined } from '@ant-design/icons';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
import {
|
||||||
|
ADMIN_CORRECTION_OPTIONS,
|
||||||
|
AttendanceStatusTag,
|
||||||
|
displayAttendanceStatus,
|
||||||
|
type AdminStudentPanel,
|
||||||
|
type AttendancePeriodConfigItem,
|
||||||
|
type AttendanceRecordItem,
|
||||||
|
} from './AttendanceAdmin.helpers';
|
||||||
|
|
||||||
|
export const PeriodConfigModal: React.FC<{
|
||||||
|
open: boolean;
|
||||||
|
form: ReturnType<typeof Form.useForm<{ periods: AttendancePeriodConfigItem[] }>>[0];
|
||||||
|
onOk: () => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
onReset: () => void;
|
||||||
|
}> = ({ open, form, onOk, onCancel, onReset }) => {
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
title="考勤时段配置"
|
||||||
|
okText="保存配置"
|
||||||
|
width={860}
|
||||||
|
className="attendance-period-modal"
|
||||||
|
onOk={onOk}
|
||||||
|
onCancel={onCancel}
|
||||||
|
footer={(_, { OkBtn, CancelBtn }) => (
|
||||||
|
<>
|
||||||
|
<Button icon={<UndoOutlined />} onClick={onReset}>
|
||||||
|
恢复默认
|
||||||
|
</Button>
|
||||||
|
<CancelBtn />
|
||||||
|
<OkBtn />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
title="按课程开始时间自动匹配时段"
|
||||||
|
description="默认:07:30-08:30 早自习,09:00-12:00 早课,14:00-17:00 晚课,18:30-21:00 晚自习。"
|
||||||
|
style={{ marginBottom: 16 }}
|
||||||
|
/>
|
||||||
|
<Form form={form} layout="vertical">
|
||||||
|
<Form.List name="periods">
|
||||||
|
{(fields, { add, remove }) => (
|
||||||
|
<div className="attendance-period-editor">
|
||||||
|
{fields.map((field) => (
|
||||||
|
<div className="attendance-period-row" key={field.key}>
|
||||||
|
<Form.Item name={[field.name, 'label']} label="显示名称" rules={[{ required: true, message: '请输入名称' }]}>
|
||||||
|
<Input placeholder="早课" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name={[field.name, 'periodKey']} label="类型标识" rules={[{ required: true, message: '请输入标识' }]}>
|
||||||
|
<Input placeholder="morning" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name={[field.name, 'startTime']} label="开始时间" rules={[{ required: true, message: '请选择开始时间' }]}>
|
||||||
|
<Input type="time" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name={[field.name, 'endTime']} label="结束时间" rules={[{ required: true, message: '请选择结束时间' }]}>
|
||||||
|
<Input type="time" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name={[field.name, 'enabled']} label="状态">
|
||||||
|
<Select
|
||||||
|
options={[
|
||||||
|
{ value: true, label: '启用' },
|
||||||
|
{ value: false, label: '停用' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Button danger className="attendance-period-row__delete" onClick={() => remove(field.name)}>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<Button
|
||||||
|
block
|
||||||
|
type="dashed"
|
||||||
|
className="attendance-period-add"
|
||||||
|
onClick={() =>
|
||||||
|
add({
|
||||||
|
periodKey: '',
|
||||||
|
label: '',
|
||||||
|
startTime: '00:00',
|
||||||
|
endTime: '00:30',
|
||||||
|
enabled: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
添加时段
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Form.List>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const StudentDetailDrawer: React.FC<{
|
||||||
|
student: AdminStudentPanel | null;
|
||||||
|
isMobile: boolean;
|
||||||
|
canEdit: boolean;
|
||||||
|
sessionMap: Record<string, string>;
|
||||||
|
correctingRecordId: number | null;
|
||||||
|
sortAttendanceRecords: (items: readonly AttendanceRecordItem[]) => AttendanceRecordItem[];
|
||||||
|
onClose: () => void;
|
||||||
|
onUpdateAdminRecordStatus: (record: AttendanceRecordItem, nextStatus: string) => void;
|
||||||
|
}> = ({
|
||||||
|
student,
|
||||||
|
isMobile,
|
||||||
|
canEdit,
|
||||||
|
sessionMap,
|
||||||
|
correctingRecordId,
|
||||||
|
sortAttendanceRecords,
|
||||||
|
onClose,
|
||||||
|
onUpdateAdminRecordStatus,
|
||||||
|
}) => {
|
||||||
|
return (
|
||||||
|
<Drawer
|
||||||
|
open={Boolean(student)}
|
||||||
|
onClose={onClose}
|
||||||
|
size={isMobile ? '100%' : 520}
|
||||||
|
title="学生考勤明细"
|
||||||
|
className="student-detail-drawer"
|
||||||
|
>
|
||||||
|
{student && (
|
||||||
|
<div className="student-detail-panel">
|
||||||
|
<section className="student-detail-profile">
|
||||||
|
<Avatar size={54}>{student.studentName.slice(0, 1)}</Avatar>
|
||||||
|
<div>
|
||||||
|
<h4>{student.studentName}</h4>
|
||||||
|
<p>
|
||||||
|
{student.className}
|
||||||
|
{student.studentNo ? ` · 学号 ${student.studentNo}` : ''}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="student-detail-rate">
|
||||||
|
<strong>{student.rate}%</strong>
|
||||||
|
<span>累计出勤率</span>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section className="student-detail-rates">
|
||||||
|
{sortAttendanceRecords(student.records).map((record) => {
|
||||||
|
const normal = record.status === 'present';
|
||||||
|
return (
|
||||||
|
<div key={record.id}>
|
||||||
|
<strong>{normal ? '100%' : '0%'}</strong>
|
||||||
|
<span>{sessionMap[record.session] || record.session}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</section>
|
||||||
|
<section className="student-detail-section">
|
||||||
|
<h5>当天打卡时间</h5>
|
||||||
|
<div className="student-detail-timeline">
|
||||||
|
{sortAttendanceRecords(student.records).map((record) => (
|
||||||
|
<div key={record.id}>
|
||||||
|
<span>{sessionMap[record.session] || record.session}</span>
|
||||||
|
<AttendanceStatusTag status={displayAttendanceStatus(record.status)} />
|
||||||
|
<strong>
|
||||||
|
{record.punchTime ? dayjs(record.punchTime).format('HH:mm:ss') : '未记录'}
|
||||||
|
</strong>
|
||||||
|
{canEdit && (
|
||||||
|
<Segmented
|
||||||
|
size="small"
|
||||||
|
className="attendance-correction-segment"
|
||||||
|
options={ADMIN_CORRECTION_OPTIONS}
|
||||||
|
value={displayAttendanceStatus(record.status)}
|
||||||
|
disabled={correctingRecordId === record.id}
|
||||||
|
onChange={(value) => void onUpdateAdminRecordStatus(record, String(value))}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Drawer>
|
||||||
|
);
|
||||||
|
};
|
||||||
164
apps/admin/src/pages/Attendance/AttendanceAdminWorkspace.tsx
Normal file
164
apps/admin/src/pages/Attendance/AttendanceAdminWorkspace.tsx
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Card, Empty, Input, Spin, Table } from 'antd';
|
||||||
|
import { ExportOutlined } from '@ant-design/icons';
|
||||||
|
import PermissionButton from '../../components/PermissionButton';
|
||||||
|
import {
|
||||||
|
ADMIN_METRIC_META,
|
||||||
|
STATUS_META,
|
||||||
|
displayAttendanceStatus,
|
||||||
|
type AdminStudentPanel,
|
||||||
|
type AttendanceRecordItem,
|
||||||
|
} from './AttendanceAdmin.helpers';
|
||||||
|
|
||||||
|
export const AttendanceAdminWorkspace: React.FC<{
|
||||||
|
metricFilter: string;
|
||||||
|
studentSearch: string;
|
||||||
|
onSearchChange: (value: string) => void;
|
||||||
|
onExport: () => void;
|
||||||
|
visibleStudents: AdminStudentPanel[];
|
||||||
|
loading: boolean;
|
||||||
|
selectedStudentId?: number;
|
||||||
|
onSelectStudent: (student: AdminStudentPanel) => void;
|
||||||
|
sortAttendanceRecords: (items: readonly AttendanceRecordItem[]) => AttendanceRecordItem[];
|
||||||
|
sessionMap: Record<string, string>;
|
||||||
|
records: AttendanceRecordItem[];
|
||||||
|
columns: any[];
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
total: number;
|
||||||
|
onPageChange: (page: number, pageSize: number) => void;
|
||||||
|
}> = ({
|
||||||
|
metricFilter,
|
||||||
|
studentSearch,
|
||||||
|
onSearchChange,
|
||||||
|
onExport,
|
||||||
|
visibleStudents,
|
||||||
|
loading,
|
||||||
|
selectedStudentId,
|
||||||
|
onSelectStudent,
|
||||||
|
sortAttendanceRecords,
|
||||||
|
sessionMap,
|
||||||
|
records,
|
||||||
|
columns,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
total,
|
||||||
|
onPageChange,
|
||||||
|
}) => {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<section className="student-workspace">
|
||||||
|
<header className="student-workspace-header">
|
||||||
|
<div>
|
||||||
|
<h3>班级学生考勤</h3>
|
||||||
|
<span>
|
||||||
|
{metricFilter === 'all'
|
||||||
|
? `显示全部 ${visibleStudents.length} 名学生`
|
||||||
|
: `筛出 ${
|
||||||
|
ADMIN_METRIC_META.find((item) => item.key === metricFilter)?.label || ''
|
||||||
|
}相关 ${visibleStudents.length} 名学生`}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="student-workspace-tools">
|
||||||
|
<Input.Search
|
||||||
|
allowClear
|
||||||
|
placeholder="搜索姓名或学号"
|
||||||
|
value={studentSearch}
|
||||||
|
onChange={(event) => onSearchChange(event.target.value)}
|
||||||
|
/>
|
||||||
|
<PermissionButton
|
||||||
|
permission="attendance:export"
|
||||||
|
icon={<ExportOutlined />}
|
||||||
|
onClick={onExport}
|
||||||
|
>
|
||||||
|
导出
|
||||||
|
</PermissionButton>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<div className="student-legend">
|
||||||
|
<span>
|
||||||
|
<i className="is-present" />
|
||||||
|
正常
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
<i className="is-leave" />
|
||||||
|
请假
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
<i className="is-absent" />
|
||||||
|
缺勤
|
||||||
|
</span>
|
||||||
|
<em>仅显示当天已生成考勤的课程/时段,不再为无课时段补默认缺勤</em>
|
||||||
|
</div>
|
||||||
|
<Spin spinning={loading}>
|
||||||
|
{visibleStudents.length === 0 ? (
|
||||||
|
<Empty
|
||||||
|
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||||
|
description="未找到匹配学生,请调整筛选条件或搜索关键词"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="student-card-grid">
|
||||||
|
{visibleStudents.map((student) => (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
key={student.key}
|
||||||
|
className={`student-attendance-card ${
|
||||||
|
selectedStudentId === student.studentId ? 'selected' : ''
|
||||||
|
}`}
|
||||||
|
onClick={() => onSelectStudent(student)}
|
||||||
|
>
|
||||||
|
<span className="student-attendance-head">
|
||||||
|
<strong>{student.studentName}</strong>
|
||||||
|
{student.studentNo && <small>学号 {student.studentNo}</small>}
|
||||||
|
</span>
|
||||||
|
<span className="student-status-blocks">
|
||||||
|
{sortAttendanceRecords(student.records).map((record) => {
|
||||||
|
const currentStatus = displayAttendanceStatus(record.status);
|
||||||
|
const meta = STATUS_META[currentStatus] ?? STATUS_META.absent;
|
||||||
|
const sessionLabel = sessionMap[record.session] || record.session;
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
key={record.id}
|
||||||
|
className={`student-status-block ${meta.className}`}
|
||||||
|
title={`${sessionLabel}:${meta.label}`}
|
||||||
|
>
|
||||||
|
{meta.label === '出勤' ? '正常' : meta.label}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Spin>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<Card className="student-record-card" variant="borderless" title="原始考勤明细">
|
||||||
|
<Table<AttendanceRecordItem>
|
||||||
|
rowKey="id"
|
||||||
|
columns={columns}
|
||||||
|
dataSource={records}
|
||||||
|
loading={loading}
|
||||||
|
scroll={{ x: 'max-content' }}
|
||||||
|
pagination={{
|
||||||
|
current: page,
|
||||||
|
pageSize,
|
||||||
|
total,
|
||||||
|
showSizeChanger: true,
|
||||||
|
showTotal: (value) => `共 ${value} 条历史记录`,
|
||||||
|
onChange: onPageChange,
|
||||||
|
}}
|
||||||
|
locale={{
|
||||||
|
emptyText: (
|
||||||
|
<Empty
|
||||||
|
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||||
|
description="当前条件下没有历史考勤记录"
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
272
apps/admin/src/pages/Attendance/LessonAttendanceDetail.tsx
Normal file
272
apps/admin/src/pages/Attendance/LessonAttendanceDetail.tsx
Normal file
@@ -0,0 +1,272 @@
|
|||||||
|
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';
|
||||||
|
import { getErrorMessage } from '../../utils/error';
|
||||||
|
|
||||||
|
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);
|
||||||
|
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(getErrorMessage(error, '加载本节课考勤失败'));
|
||||||
|
})
|
||||||
|
.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(getErrorMessage(error, '更新考勤失败'));
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
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">
|
||||||
|
<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;
|
||||||
577
apps/admin/src/pages/Attendance/admin.tsx
Normal file
577
apps/admin/src/pages/Attendance/admin.tsx
Normal file
@@ -0,0 +1,577 @@
|
|||||||
|
import React, { useCallback, useMemo, useState } from 'react';
|
||||||
|
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||||
|
import { validateResponse } from '../../utils/validate';
|
||||||
|
import {
|
||||||
|
attendanceAlertsSchema,
|
||||||
|
attendanceClassOptionsSchema,
|
||||||
|
attendanceRecordsResponseSchema,
|
||||||
|
attendanceScheduleOptionsSchema,
|
||||||
|
attendancePeriodsSchema,
|
||||||
|
attendanceSummarySchema,
|
||||||
|
dingTalkSyncStatusSchema,
|
||||||
|
} from '../../api/schemas';
|
||||||
|
import { Form, Grid } from 'antd';
|
||||||
|
import dayjs, { type Dayjs } from 'dayjs';
|
||||||
|
import api from '../../api';
|
||||||
|
import { message } from '../../ui/app-message';
|
||||||
|
import { useUserStore } from '../../store/user/userStore';
|
||||||
|
import type { AttendanceSummary } from './attendance-workspace';
|
||||||
|
import { getErrorMessage } from '../../utils/error';
|
||||||
|
import { AttendanceAdminHeader } from './AttendanceAdminHeader';
|
||||||
|
import { buildAttendanceAdminColumns } from './AttendanceAdminColumns';
|
||||||
|
import { PeriodConfigModal, StudentDetailDrawer } from './AttendanceAdminModals';
|
||||||
|
import { AttendanceAdminWorkspace } from './AttendanceAdminWorkspace';
|
||||||
|
import {
|
||||||
|
DEFAULT_ATTENDANCE_PERIODS,
|
||||||
|
EMPTY_SUMMARY,
|
||||||
|
buildAdminStudentPanels,
|
||||||
|
displayAttendanceStatus,
|
||||||
|
formatTeacherNames,
|
||||||
|
getTeacherDisplayName,
|
||||||
|
type AdminStudentPanel,
|
||||||
|
type AlertItem,
|
||||||
|
type AttendancePeriodConfigItem,
|
||||||
|
type AttendanceRecordItem,
|
||||||
|
type ClassOption,
|
||||||
|
type DingTalkSyncStatus,
|
||||||
|
type HistoryScheduleOption,
|
||||||
|
} from './AttendanceAdmin.helpers';
|
||||||
|
|
||||||
|
export const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) => {
|
||||||
|
const screens = Grid.useBreakpoint();
|
||||||
|
const isMobile = !screens.sm;
|
||||||
|
const [periodModalOpen, setPeriodModalOpen] = useState(false);
|
||||||
|
const [periodForm] = Form.useForm<{ periods: AttendancePeriodConfigItem[] }>();
|
||||||
|
const [refreshingDingTalk, setRefreshingDingTalk] = useState(false);
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [pageSize, setPageSize] = useState(48);
|
||||||
|
const [classId, setClassId] = useState<number>();
|
||||||
|
const [attendanceDate, setAttendanceDate] = useState<Dayjs | null>(dayjs());
|
||||||
|
const [status, setStatus] = useState<string>();
|
||||||
|
const [session, setSession] = useState<string>();
|
||||||
|
const [scheduleId, setScheduleId] = useState<number>();
|
||||||
|
const [metricFilter, setMetricFilter] = useState('all');
|
||||||
|
const [studentSearch, setStudentSearch] = useState('');
|
||||||
|
const [selectedStudent, setSelectedStudent] = useState<AdminStudentPanel | null>(null);
|
||||||
|
const [correctingRecordId, setCorrectingRecordId] = useState<number | null>(null);
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const recordQueryKey = [
|
||||||
|
'attendance',
|
||||||
|
'records',
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
classId,
|
||||||
|
attendanceDate,
|
||||||
|
status,
|
||||||
|
session,
|
||||||
|
scheduleId,
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const { data: classOptions = [] } = useQuery<ClassOption[]>({
|
||||||
|
queryKey: ['attendance', 'meta', 'classes'],
|
||||||
|
queryFn: async () => {
|
||||||
|
try {
|
||||||
|
return validateResponse<ClassOption[]>(
|
||||||
|
attendanceClassOptionsSchema,
|
||||||
|
await api.get<ClassOption[]>('/attendance-records/classes'),
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const { data: alerts = [] } = useQuery<AlertItem[]>({
|
||||||
|
queryKey: ['attendance', 'meta', 'alerts'],
|
||||||
|
queryFn: async () => {
|
||||||
|
try {
|
||||||
|
return validateResponse<AlertItem[]>(
|
||||||
|
attendanceAlertsSchema,
|
||||||
|
await api.get<AlertItem[]>('/attendance-records/alerts'),
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const { data: periods = DEFAULT_ATTENDANCE_PERIODS } = useQuery<AttendancePeriodConfigItem[]>({
|
||||||
|
queryKey: ['attendance', 'meta', 'periods'],
|
||||||
|
queryFn: async () => {
|
||||||
|
try {
|
||||||
|
return validateResponse<AttendancePeriodConfigItem[]>(
|
||||||
|
attendancePeriodsSchema,
|
||||||
|
await api.get<AttendancePeriodConfigItem[]>('/attendance-period-configs'),
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return DEFAULT_ATTENDANCE_PERIODS;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const {
|
||||||
|
data: scheduleOptions = [],
|
||||||
|
isFetching: scheduleOptionsFetching,
|
||||||
|
} = useQuery<HistoryScheduleOption[]>({
|
||||||
|
queryKey: ['attendance', 'schedules', classId, attendanceDate],
|
||||||
|
enabled: !!classId && !!attendanceDate,
|
||||||
|
queryFn: async () => {
|
||||||
|
try {
|
||||||
|
if (!attendanceDate) return [];
|
||||||
|
return validateResponse<HistoryScheduleOption[]>(
|
||||||
|
attendanceScheduleOptionsSchema,
|
||||||
|
await api.get<HistoryScheduleOption[]>('/attendance-records/schedules', {
|
||||||
|
params: { classId, date: attendanceDate.format('YYYY-MM-DD') },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
message.error(getErrorMessage(error, '加载班级科目失败'));
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const scheduleOptionsLoading = scheduleOptionsFetching;
|
||||||
|
const effectiveScheduleId =
|
||||||
|
scheduleId && scheduleOptions.some((schedule) => schedule.id === scheduleId)
|
||||||
|
? scheduleId
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const enabledPeriods = useMemo(
|
||||||
|
() => periods.filter((period) => period.enabled).sort((a, b) => a.sortOrder - b.sortOrder),
|
||||||
|
[periods],
|
||||||
|
);
|
||||||
|
const sessionOptions = useMemo(
|
||||||
|
() => enabledPeriods.map((period) => ({ value: period.periodKey, label: period.label })),
|
||||||
|
[enabledPeriods],
|
||||||
|
);
|
||||||
|
const sessionMap = useMemo(
|
||||||
|
() => Object.fromEntries(periods.map((period) => [period.periodKey, period.label])),
|
||||||
|
[periods],
|
||||||
|
);
|
||||||
|
const periodOrder = useMemo(
|
||||||
|
() => new Map(periods.map((period, index) => [period.periodKey, index])),
|
||||||
|
[periods],
|
||||||
|
);
|
||||||
|
const sortAttendanceRecords = useCallback(
|
||||||
|
(items: readonly AttendanceRecordItem[]) =>
|
||||||
|
[...items].sort((a, b) => {
|
||||||
|
const periodDiff =
|
||||||
|
(periodOrder.get(a.session) ?? Number.MAX_SAFE_INTEGER) -
|
||||||
|
(periodOrder.get(b.session) ?? Number.MAX_SAFE_INTEGER);
|
||||||
|
if (periodDiff !== 0) return periodDiff;
|
||||||
|
return (a.punchTime || a.createdAt || '').localeCompare(b.punchTime || b.createdAt || '');
|
||||||
|
}),
|
||||||
|
[periodOrder],
|
||||||
|
);
|
||||||
|
const openPeriodConfig = () => {
|
||||||
|
periodForm.setFieldsValue({ periods });
|
||||||
|
setPeriodModalOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const savePeriodConfig = async () => {
|
||||||
|
try {
|
||||||
|
const values = await periodForm.validateFields();
|
||||||
|
const payload = {
|
||||||
|
periods: values.periods.map((period, index) => ({
|
||||||
|
...period,
|
||||||
|
sortOrder: index + 1,
|
||||||
|
enabled: period.enabled ?? true,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
const data = await savePeriodConfigMutation.mutateAsync(payload);
|
||||||
|
setPeriodModalOpen(false);
|
||||||
|
message.success('考勤时段配置已保存');
|
||||||
|
if (session && !data.some((period) => period.enabled && period.periodKey === session)) {
|
||||||
|
setSession(undefined);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 校验错误静默,接口错误由 useApiMutation 统一提示
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const resetPeriodConfig = async () => {
|
||||||
|
try {
|
||||||
|
await resetPeriodConfigMutation.mutateAsync();
|
||||||
|
message.success('已恢复默认考勤时段');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildParams = useCallback(
|
||||||
|
(withPagination = true) => {
|
||||||
|
const params: Record<string, string | number> = {};
|
||||||
|
if (withPagination) Object.assign(params, { page, pageSize });
|
||||||
|
if (classId) params.classId = classId;
|
||||||
|
if (attendanceDate) {
|
||||||
|
const selectedDate = attendanceDate.format('YYYY-MM-DD');
|
||||||
|
params.dateFrom = selectedDate;
|
||||||
|
params.dateTo = selectedDate;
|
||||||
|
}
|
||||||
|
if (status) params.status = status;
|
||||||
|
if (session) params.session = session;
|
||||||
|
if (effectiveScheduleId) params.scheduleId = effectiveScheduleId;
|
||||||
|
return params;
|
||||||
|
},
|
||||||
|
[page, pageSize, classId, attendanceDate, status, session, effectiveScheduleId],
|
||||||
|
);
|
||||||
|
|
||||||
|
const { data: syncStatus = null, refetch: refetchSyncStatus } = useQuery<DingTalkSyncStatus | null>({
|
||||||
|
queryKey: ['attendance', 'sync-status'],
|
||||||
|
queryFn: async () => {
|
||||||
|
try {
|
||||||
|
return validateResponse<DingTalkSyncStatus>(
|
||||||
|
dingTalkSyncStatusSchema,
|
||||||
|
await api.get<DingTalkSyncStatus>('/attendance-records/dingtalk-sync-status'),
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const loadSyncStatus = useCallback(() => refetchSyncStatus(), [refetchSyncStatus]);
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: recordQuery = { records: [], total: 0, summary: EMPTY_SUMMARY },
|
||||||
|
isFetching: recordsFetching,
|
||||||
|
refetch: refetchRecords,
|
||||||
|
} = useQuery<{
|
||||||
|
records: AttendanceRecordItem[];
|
||||||
|
total: number;
|
||||||
|
summary: AttendanceSummary;
|
||||||
|
}>({
|
||||||
|
queryKey: recordQueryKey,
|
||||||
|
queryFn: async () => {
|
||||||
|
try {
|
||||||
|
const [recordData, summaryData] = await Promise.all([
|
||||||
|
api.get<{ list: AttendanceRecordItem[]; total: number }>('/attendance-records', {
|
||||||
|
params: buildParams(true),
|
||||||
|
}),
|
||||||
|
api.get<AttendanceSummary>('/attendance-records/summary', {
|
||||||
|
params: buildParams(false),
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
const validatedRecords = validateResponse<{
|
||||||
|
list: AttendanceRecordItem[];
|
||||||
|
total: number;
|
||||||
|
}>(attendanceRecordsResponseSchema, recordData);
|
||||||
|
const validatedSummary = validateResponse<AttendanceSummary>(
|
||||||
|
attendanceSummarySchema,
|
||||||
|
summaryData,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
records: validatedRecords.list,
|
||||||
|
total: validatedRecords.total,
|
||||||
|
summary: { ...EMPTY_SUMMARY, ...validatedSummary },
|
||||||
|
};
|
||||||
|
} catch (error: unknown) {
|
||||||
|
message.error(getErrorMessage(error, '加载学生考勤失败'));
|
||||||
|
return { records: [], total: 0, summary: EMPTY_SUMMARY };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const records = recordQuery.records;
|
||||||
|
const total = recordQuery.total;
|
||||||
|
const summary = recordQuery.summary;
|
||||||
|
const loading = recordsFetching;
|
||||||
|
const loadRecords = useCallback(() => refetchRecords(), [refetchRecords]);
|
||||||
|
|
||||||
|
const savePeriodConfigMutation = useApiMutation(
|
||||||
|
async (payload: Record<string, unknown>) =>
|
||||||
|
api.put<AttendancePeriodConfigItem[]>('/attendance-period-configs', payload),
|
||||||
|
{ invalidate: [['attendance', 'meta', 'periods']] },
|
||||||
|
);
|
||||||
|
const resetPeriodConfigMutation = useApiMutation(
|
||||||
|
async () => api.post<AttendancePeriodConfigItem[]>('/attendance-period-configs/reset'),
|
||||||
|
{ invalidate: [['attendance', 'meta', 'periods']] },
|
||||||
|
);
|
||||||
|
const refreshDingTalkMutation = useApiMutation(
|
||||||
|
async (payload: Record<string, unknown>) =>
|
||||||
|
api.post<{
|
||||||
|
refreshed: number;
|
||||||
|
imported: number;
|
||||||
|
matched: number;
|
||||||
|
errors: string[];
|
||||||
|
}>('/attendance-records/refresh-dingtalk', payload),
|
||||||
|
{ invalidate: [['attendance', 'records'], ['attendance', 'sync-status']] },
|
||||||
|
);
|
||||||
|
const updateStatusMutation = useApiMutation(
|
||||||
|
async ({ id, status }: { id: number; status: string }) =>
|
||||||
|
api.put(`/attendance-records/${id}`, { status }),
|
||||||
|
{ invalidate: [['attendance', 'records']] },
|
||||||
|
);
|
||||||
|
const saveRecordCellMutation = useApiMutation(
|
||||||
|
async ({ id, field, value }: { id: number; field: string; value: unknown }) =>
|
||||||
|
api.put(`/attendance-records/${id}`, { [field]: value }),
|
||||||
|
{ invalidate: [['attendance', 'records']] },
|
||||||
|
);
|
||||||
|
|
||||||
|
const refreshDingTalkAttendance = useCallback(async () => {
|
||||||
|
if (!attendanceDate) {
|
||||||
|
message.warning('请先选择日期');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (attendanceDate.isAfter(dayjs(), 'day')) {
|
||||||
|
message.warning('不能查看或刷新未来日期的考勤');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setRefreshingDingTalk(true);
|
||||||
|
try {
|
||||||
|
const result = await refreshDingTalkMutation.mutateAsync({
|
||||||
|
date: attendanceDate.format('YYYY-MM-DD'),
|
||||||
|
classId,
|
||||||
|
session,
|
||||||
|
});
|
||||||
|
if (result.errors.length > 0) {
|
||||||
|
message.warning(result.errors[0]);
|
||||||
|
} else {
|
||||||
|
message.success(`已刷新 ${result.refreshed} 节课程考勤`);
|
||||||
|
}
|
||||||
|
await Promise.all([loadRecords(), loadSyncStatus()]);
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
} finally {
|
||||||
|
setRefreshingDingTalk(false);
|
||||||
|
}
|
||||||
|
}, [attendanceDate, classId, loadRecords, loadSyncStatus, session, refreshDingTalkMutation]);
|
||||||
|
|
||||||
|
const resetFilters = () => {
|
||||||
|
setClassId(undefined);
|
||||||
|
setAttendanceDate(dayjs());
|
||||||
|
setStatus(undefined);
|
||||||
|
setSession(undefined);
|
||||||
|
setScheduleId(undefined);
|
||||||
|
setMetricFilter('all');
|
||||||
|
setStudentSearch('');
|
||||||
|
setPage(1);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleExport = useCallback(() => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
for (const [key, value] of Object.entries(buildParams(false))) params.set(key, String(value));
|
||||||
|
const token = useUserStore.getState().token;
|
||||||
|
fetch(`/api/attendance-records/export?${params.toString()}`, {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
})
|
||||||
|
.then((response) => {
|
||||||
|
if (!response.ok) throw new Error('导出失败');
|
||||||
|
return response.blob();
|
||||||
|
})
|
||||||
|
.then((blob) => {
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const anchor = document.createElement('a');
|
||||||
|
anchor.href = url;
|
||||||
|
anchor.download = `学生考勤-${dayjs().format('YYYYMMDD')}.xlsx`;
|
||||||
|
anchor.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
})
|
||||||
|
.catch(() => message.error('导出失败'));
|
||||||
|
}, [buildParams]);
|
||||||
|
|
||||||
|
const patchRecordStatus = (recordId: number, nextStatus: string) => {
|
||||||
|
queryClient.setQueryData<{
|
||||||
|
records: AttendanceRecordItem[];
|
||||||
|
total: number;
|
||||||
|
summary: AttendanceSummary;
|
||||||
|
}>(recordQueryKey, (prev) =>
|
||||||
|
prev
|
||||||
|
? {
|
||||||
|
...prev,
|
||||||
|
records: prev.records.map((item) =>
|
||||||
|
item.id === recordId ? { ...item, status: nextStatus } : item,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: prev,
|
||||||
|
);
|
||||||
|
setSelectedStudent((student) => {
|
||||||
|
if (!student) return student;
|
||||||
|
return {
|
||||||
|
...student,
|
||||||
|
records: student.records.map((item) =>
|
||||||
|
item.id === recordId ? { ...item, status: nextStatus } : item,
|
||||||
|
),
|
||||||
|
statusBySession: Object.fromEntries(
|
||||||
|
Object.entries(student.statusBySession).map(([key, item]) => [
|
||||||
|
key,
|
||||||
|
item?.id === recordId ? { ...item, status: nextStatus } : item,
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateAdminRecordStatus = async (record: AttendanceRecordItem, nextStatus: string) => {
|
||||||
|
const previousStatus = record.status;
|
||||||
|
const normalizedPrevious = displayAttendanceStatus(previousStatus);
|
||||||
|
if (normalizedPrevious === nextStatus && previousStatus !== 'pending') return;
|
||||||
|
|
||||||
|
patchRecordStatus(record.id, nextStatus);
|
||||||
|
setCorrectingRecordId(record.id);
|
||||||
|
try {
|
||||||
|
await updateStatusMutation.mutateAsync({ id: record.id, status: nextStatus });
|
||||||
|
message.success('考勤结果已更新');
|
||||||
|
} catch {
|
||||||
|
patchRecordStatus(record.id, previousStatus);
|
||||||
|
} finally {
|
||||||
|
setCorrectingRecordId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveAdminRecordCell = async (
|
||||||
|
record: AttendanceRecordItem,
|
||||||
|
field: 'status' | 'remark',
|
||||||
|
value: unknown,
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
await saveRecordCellMutation.mutateAsync({ id: record.id, field, value });
|
||||||
|
message.success('考勤记录已保存');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const studentPanels = useMemo(() => buildAdminStudentPanels(records), [records]);
|
||||||
|
const visibleStudents = useMemo(() => {
|
||||||
|
const query = studentSearch.trim().toLocaleLowerCase('zh-CN');
|
||||||
|
return studentPanels.filter((student) => {
|
||||||
|
const matchesQuery =
|
||||||
|
!query ||
|
||||||
|
student.studentName.toLocaleLowerCase('zh-CN').includes(query) ||
|
||||||
|
student.studentNo.toLocaleLowerCase('zh-CN').includes(query);
|
||||||
|
const matchesMetric =
|
||||||
|
metricFilter === 'all' ||
|
||||||
|
student.records.some((record) => displayAttendanceStatus(record.status) === metricFilter);
|
||||||
|
return matchesQuery && matchesMetric;
|
||||||
|
});
|
||||||
|
}, [metricFilter, studentPanels, studentSearch]);
|
||||||
|
|
||||||
|
const selectedClassOption = classId
|
||||||
|
? classOptions.find((item) => item.classId === classId)
|
||||||
|
: undefined;
|
||||||
|
const selectedClass =
|
||||||
|
selectedClassOption?.className || (classId ? `班级 ${classId}` : '全部班级');
|
||||||
|
const overviewTeachers = selectedClassOption?.teachers ?? [];
|
||||||
|
const headTeacherNames = classId
|
||||||
|
? formatTeacherNames(overviewTeachers.filter((teacher) => teacher.roleType === 'head_teacher'))
|
||||||
|
: '请选择班级';
|
||||||
|
const lifeTeacherNames = classId
|
||||||
|
? formatTeacherNames(overviewTeachers.filter((teacher) => teacher.roleType === 'life_teacher'))
|
||||||
|
: '请选择班级';
|
||||||
|
const currentSchedule = scheduleId
|
||||||
|
? scheduleOptions.find((item) => item.id === scheduleId)
|
||||||
|
: undefined;
|
||||||
|
const subjectTeacherNames = currentSchedule
|
||||||
|
? getTeacherDisplayName({
|
||||||
|
name: currentSchedule.teacherName,
|
||||||
|
username: currentSchedule.teacherUsername,
|
||||||
|
})
|
||||||
|
: classId
|
||||||
|
? formatTeacherNames(
|
||||||
|
overviewTeachers.filter((teacher) => teacher.roleType === 'subject_teacher'),
|
||||||
|
)
|
||||||
|
: '请选择班级';
|
||||||
|
const attendanceRate =
|
||||||
|
summary.total > 0 ? Math.round((summary.present / summary.total) * 100) : 0;
|
||||||
|
const dateLabel = attendanceDate?.format('YYYY-MM-DD') || '未选择日期';
|
||||||
|
|
||||||
|
const columns = buildAttendanceAdminColumns({
|
||||||
|
isMobile,
|
||||||
|
canEdit,
|
||||||
|
sessionMap,
|
||||||
|
correctingRecordId,
|
||||||
|
onSaveAdminRecordCell: saveAdminRecordCell,
|
||||||
|
onUpdateAdminRecordStatus: updateAdminRecordStatus,
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="attendance-page admin-attendance student-attendance-center">
|
||||||
|
<AttendanceAdminHeader
|
||||||
|
syncStatus={syncStatus}
|
||||||
|
canEdit={canEdit}
|
||||||
|
refreshingDingTalk={refreshingDingTalk}
|
||||||
|
onOpenPeriodConfig={openPeriodConfig}
|
||||||
|
onRefreshDingTalk={() => void refreshDingTalkAttendance()}
|
||||||
|
onExport={handleExport}
|
||||||
|
attendanceDate={attendanceDate}
|
||||||
|
onDateChange={(value) => {
|
||||||
|
setAttendanceDate(value);
|
||||||
|
setScheduleId(undefined);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
classId={classId}
|
||||||
|
onClassChange={(value) => {
|
||||||
|
setClassId(value);
|
||||||
|
setScheduleId(undefined);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
classOptions={classOptions}
|
||||||
|
effectiveScheduleId={effectiveScheduleId}
|
||||||
|
onScheduleChange={(value) => {
|
||||||
|
setScheduleId(value);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
scheduleOptions={scheduleOptions}
|
||||||
|
scheduleOptionsLoading={scheduleOptionsLoading}
|
||||||
|
session={session}
|
||||||
|
onSessionChange={(value) => {
|
||||||
|
setSession(value);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
sessionOptions={sessionOptions}
|
||||||
|
onReset={resetFilters}
|
||||||
|
onQuery={() => void loadRecords()}
|
||||||
|
selectedClass={selectedClass}
|
||||||
|
dateLabel={dateLabel}
|
||||||
|
visibleStudentCount={visibleStudents.length}
|
||||||
|
total={total}
|
||||||
|
headTeacherNames={headTeacherNames}
|
||||||
|
lifeTeacherNames={lifeTeacherNames}
|
||||||
|
subjectTeacherNames={subjectTeacherNames}
|
||||||
|
attendanceRate={attendanceRate}
|
||||||
|
summary={summary}
|
||||||
|
metricFilter={metricFilter}
|
||||||
|
onMetricFilterChange={setMetricFilter}
|
||||||
|
alerts={alerts}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<AttendanceAdminWorkspace
|
||||||
|
metricFilter={metricFilter}
|
||||||
|
studentSearch={studentSearch}
|
||||||
|
onSearchChange={setStudentSearch}
|
||||||
|
onExport={handleExport}
|
||||||
|
visibleStudents={visibleStudents}
|
||||||
|
loading={loading}
|
||||||
|
selectedStudentId={selectedStudent?.studentId}
|
||||||
|
onSelectStudent={setSelectedStudent}
|
||||||
|
sortAttendanceRecords={sortAttendanceRecords}
|
||||||
|
sessionMap={sessionMap}
|
||||||
|
records={records}
|
||||||
|
columns={columns}
|
||||||
|
page={page}
|
||||||
|
pageSize={pageSize}
|
||||||
|
total={total}
|
||||||
|
onPageChange={(nextPage, nextPageSize) => {
|
||||||
|
setPage(nextPage);
|
||||||
|
setPageSize(nextPageSize);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<StudentDetailDrawer
|
||||||
|
student={selectedStudent}
|
||||||
|
isMobile={isMobile}
|
||||||
|
canEdit={canEdit}
|
||||||
|
sessionMap={sessionMap}
|
||||||
|
correctingRecordId={correctingRecordId}
|
||||||
|
sortAttendanceRecords={sortAttendanceRecords}
|
||||||
|
onClose={() => setSelectedStudent(null)}
|
||||||
|
onUpdateAdminRecordStatus={updateAdminRecordStatus}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<PeriodConfigModal
|
||||||
|
open={periodModalOpen}
|
||||||
|
form={periodForm}
|
||||||
|
onOk={savePeriodConfig}
|
||||||
|
onCancel={() => setPeriodModalOpen(false)}
|
||||||
|
onReset={() => void resetPeriodConfig()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -761,7 +761,6 @@
|
|||||||
padding: 0 24px;
|
padding: 0 24px;
|
||||||
border-bottom: 1px solid var(--student-line);
|
border-bottom: 1px solid var(--student-line);
|
||||||
background: rgb(255 255 255 / 96%);
|
background: rgb(255 255 255 / 96%);
|
||||||
backdrop-filter: blur(10px);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.student-center-title {
|
.student-center-title {
|
||||||
@@ -911,21 +910,7 @@
|
|||||||
min-height: 176px;
|
min-height: 176px;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
padding: 20px;
|
padding: 20px;
|
||||||
background:
|
background: var(--student-surface);
|
||||||
radial-gradient(circle at 100% 0%, rgb(21 122 101 / 10%), transparent 34%),
|
|
||||||
linear-gradient(135deg, #ffffff 0%, #f8fcfa 100%);
|
|
||||||
}
|
|
||||||
|
|
||||||
.student-class-identity::after {
|
|
||||||
content: '';
|
|
||||||
position: absolute;
|
|
||||||
right: -36px;
|
|
||||||
bottom: -44px;
|
|
||||||
width: 118px;
|
|
||||||
height: 118px;
|
|
||||||
border: 18px solid rgb(21 122 101 / 7%);
|
|
||||||
border-radius: 999px;
|
|
||||||
pointer-events: none;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.student-class-heading {
|
.student-class-heading {
|
||||||
@@ -933,19 +918,6 @@
|
|||||||
z-index: 1;
|
z-index: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
.student-overview-kicker {
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
min-height: 24px;
|
|
||||||
margin-bottom: 8px;
|
|
||||||
padding: 0 9px;
|
|
||||||
border-radius: 999px;
|
|
||||||
background: rgb(21 122 101 / 10%);
|
|
||||||
color: var(--student-primary);
|
|
||||||
font-size: 12px;
|
|
||||||
font-weight: 700;
|
|
||||||
}
|
|
||||||
|
|
||||||
.student-class-identity h2 {
|
.student-class-identity h2 {
|
||||||
margin: 0 0 6px;
|
margin: 0 0 6px;
|
||||||
color: #111c18;
|
color: #111c18;
|
||||||
@@ -1335,22 +1307,6 @@
|
|||||||
color: var(--student-muted);
|
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) {
|
@media (max-width: 1280px) {
|
||||||
.student-filter-panel {
|
.student-filter-panel {
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
218
apps/admin/src/pages/Attendance/teacher.tsx
Normal file
218
apps/admin/src/pages/Attendance/teacher.tsx
Normal file
@@ -0,0 +1,218 @@
|
|||||||
|
import React, { useCallback, useMemo, useState } from 'react';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { Button, Card, Col, Empty, Row, Spin, Tag, Tooltip } from 'antd';
|
||||||
|
import {
|
||||||
|
ArrowRightOutlined,
|
||||||
|
CheckCircleFilled,
|
||||||
|
ClockCircleOutlined,
|
||||||
|
ReloadOutlined,
|
||||||
|
ScheduleOutlined,
|
||||||
|
TeamOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
import api from '../../api';
|
||||||
|
import { message } from '../../ui/app-message';
|
||||||
|
import { getErrorMessage } from '../../utils/error';
|
||||||
|
import {
|
||||||
|
canPullAttendance,
|
||||||
|
getSchedulePhase,
|
||||||
|
type SchedulePhase,
|
||||||
|
} from './attendance-workspace';
|
||||||
|
import LessonAttendanceDetail from './LessonAttendanceDetail';
|
||||||
|
import type { LessonAttendanceSchedule } from './types';
|
||||||
|
|
||||||
|
type TodaySchedule = LessonAttendanceSchedule;
|
||||||
|
|
||||||
|
interface AssignedClass {
|
||||||
|
classId: number;
|
||||||
|
className: string;
|
||||||
|
classCode: string;
|
||||||
|
roleType: string;
|
||||||
|
subject: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TeacherWorkspaceData {
|
||||||
|
assignedClasses: AssignedClass[];
|
||||||
|
todaySchedules: TodaySchedule[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const TeacherAttendanceWorkspace: React.FC<{ canCreate: boolean }> = ({ canCreate }) => {
|
||||||
|
const [selectedSchedule, setSelectedSchedule] = useState<TodaySchedule | null>(null);
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: workspace,
|
||||||
|
isLoading,
|
||||||
|
isFetching,
|
||||||
|
refetch,
|
||||||
|
} = useQuery<TeacherWorkspaceData | null>({
|
||||||
|
queryKey: ['attendance', 'workspace'],
|
||||||
|
queryFn: async () => {
|
||||||
|
try {
|
||||||
|
return await api.get<TeacherWorkspaceData>('/rbac/teacher-workspace');
|
||||||
|
} catch (error: unknown) {
|
||||||
|
message.error(getErrorMessage(error, '加载今日课程失败'));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const loading = isLoading || isFetching;
|
||||||
|
const loadWorkspace = useCallback(() => refetch(), [refetch]);
|
||||||
|
|
||||||
|
const classNameById = useMemo(
|
||||||
|
() => new Map(workspace?.assignedClasses.map((item) => [item.classId, item.className]) ?? []),
|
||||||
|
[workspace],
|
||||||
|
);
|
||||||
|
|
||||||
|
const openAttendance = useCallback((schedule: TodaySchedule) => {
|
||||||
|
setSelectedSchedule(schedule);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const schedules = workspace?.todaySchedules ?? [];
|
||||||
|
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',
|
||||||
|
);
|
||||||
|
|
||||||
|
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>
|
||||||
|
<h1>今天,从课程开始</h1>
|
||||||
|
<p>课程开始后可查看最新打卡结果;课程截止时系统自动拉取并结算缺勤。</p>
|
||||||
|
</div>
|
||||||
|
<Button icon={<ReloadOutlined />} onClick={() => void loadWorkspace()}>
|
||||||
|
刷新
|
||||||
|
</Button>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
</Col>
|
||||||
|
<Col xs={24} md={8}>
|
||||||
|
<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>
|
||||||
|
</Col>
|
||||||
|
</Row>
|
||||||
|
|
||||||
|
<div className="attendance-section-heading">
|
||||||
|
<div>
|
||||||
|
<span>今日教学节奏</span>
|
||||||
|
<h2>我的课程</h2>
|
||||||
|
</div>
|
||||||
|
<span className="attendance-section-note">课程开始后可拉取钉钉考勤记录</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Spin spinning={loading}>
|
||||||
|
{schedules.length === 0 ? (
|
||||||
|
<Card className="attendance-empty-card">
|
||||||
|
<Empty
|
||||||
|
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||||
|
description={
|
||||||
|
<div>
|
||||||
|
<strong>今天还没有课程</strong>
|
||||||
|
<p>请联系教务管理员安排课程。</p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
) : (
|
||||||
|
<div className="lesson-timeline">
|
||||||
|
{schedules.map((schedule, index) => {
|
||||||
|
const phase = getSchedulePhase(schedule.startTime, schedule.endTime, now);
|
||||||
|
return (
|
||||||
|
<LessonCard
|
||||||
|
key={schedule.id}
|
||||||
|
schedule={schedule}
|
||||||
|
phase={phase}
|
||||||
|
className={classNameById.get(schedule.classId) || `班级 ${schedule.classId}`}
|
||||||
|
index={index + 1}
|
||||||
|
onOpen={canCreate ? () => openAttendance(schedule) : undefined}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Spin>
|
||||||
|
|
||||||
|
{canCreate ? (
|
||||||
|
<LessonAttendanceDetail
|
||||||
|
key={selectedSchedule?.id ?? 'closed'}
|
||||||
|
schedule={selectedSchedule}
|
||||||
|
className={
|
||||||
|
selectedSchedule
|
||||||
|
? classNameById.get(selectedSchedule.classId) || `班级 ${selectedSchedule.classId}`
|
||||||
|
: ''
|
||||||
|
}
|
||||||
|
onClose={() => setSelectedSchedule(null)}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const LessonCard: React.FC<{
|
||||||
|
schedule: TodaySchedule;
|
||||||
|
phase: SchedulePhase;
|
||||||
|
className: string;
|
||||||
|
index: number;
|
||||||
|
onOpen?: () => void;
|
||||||
|
}> = ({ schedule, phase, className, index, onOpen }) => {
|
||||||
|
const phaseMeta = {
|
||||||
|
upcoming: { label: '待上课', icon: <ClockCircleOutlined />, tone: 'upcoming' },
|
||||||
|
ongoing: { label: '进行中', icon: <ScheduleOutlined />, tone: 'ongoing' },
|
||||||
|
ended: { label: '已结束', icon: <CheckCircleFilled />, tone: 'ended' },
|
||||||
|
}[phase];
|
||||||
|
|
||||||
|
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-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>
|
||||||
|
<div className="lesson-action">
|
||||||
|
{phase === 'upcoming' ? (
|
||||||
|
<Tooltip title="课程尚未开始">
|
||||||
|
<Button disabled>等待上课</Button>
|
||||||
|
</Tooltip>
|
||||||
|
) : onOpen ? (
|
||||||
|
<Button type="primary" onClick={onOpen}>
|
||||||
|
{phase === 'ongoing' ? '查看当前考勤' : '拉取 / 查看考勤'} <ArrowRightOutlined />
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
};
|
||||||
28
apps/admin/src/pages/Attendance/types.ts
Normal file
28
apps/admin/src/pages/Attendance/types.ts
Normal 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;
|
||||||
|
}
|
||||||
@@ -1,4 +1,8 @@
|
|||||||
import React, { useEffect, useMemo, useState } from 'react';
|
import React, { useMemo, useState } from 'react';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useApiMutation } from '../hooks/useApiMutation';
|
||||||
|
import { validateResponse } from '../utils/validate';
|
||||||
|
import { attendanceDevicesSchema, classroomOptionsSchema } from '../api/schemas';
|
||||||
import { Empty, Form, Input, Modal, Popconfirm, Select, Space, Table, Tag } from 'antd';
|
import { Empty, Form, Input, Modal, Popconfirm, Select, Space, Table, Tag } from 'antd';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import { PlusOutlined } from '@ant-design/icons';
|
import { PlusOutlined } from '@ant-design/icons';
|
||||||
@@ -30,34 +34,57 @@ const statusMeta = {
|
|||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
const AttendanceDevicesPage: React.FC = () => {
|
const AttendanceDevicesPage: React.FC = () => {
|
||||||
const [data, setData] = useState<AttendanceDeviceRow[]>([]);
|
|
||||||
const [classrooms, setClassrooms] = useState<ClassroomOption[]>([]);
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [modalOpen, setModalOpen] = useState(false);
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
const [editing, setEditing] = useState<AttendanceDeviceRow | null>(null);
|
const [editing, setEditing] = useState<AttendanceDeviceRow | null>(null);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [keyword, setKeyword] = useState('');
|
const [keyword, setKeyword] = useState('');
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
|
|
||||||
const loadData = async () => {
|
const {
|
||||||
setLoading(true);
|
data: fetchResult = { devices: [], classrooms: [] },
|
||||||
try {
|
isLoading,
|
||||||
const [devices, classroomList] = await Promise.all([
|
isFetching,
|
||||||
api.get<AttendanceDeviceRow[]>('/attendance-devices'),
|
} = useQuery<{ devices: AttendanceDeviceRow[]; classrooms: ClassroomOption[] }>({
|
||||||
api.get<ClassroomOption[]>('/classrooms'),
|
queryKey: ['attendance-devices'],
|
||||||
]);
|
queryFn: async () => {
|
||||||
setData(devices);
|
try {
|
||||||
setClassrooms(classroomList.filter((item: any) => item.status !== 'archived'));
|
const [devices, classroomList] = await Promise.all([
|
||||||
} catch (error: any) {
|
api.get<AttendanceDeviceRow[]>('/attendance-devices'),
|
||||||
message.error(error?.message || '加载考勤机绑定失败');
|
api.get<ClassroomOption[]>('/classrooms'),
|
||||||
} finally {
|
]);
|
||||||
setLoading(false);
|
return {
|
||||||
}
|
devices: validateResponse<AttendanceDeviceRow[]>(attendanceDevicesSchema, devices),
|
||||||
};
|
classrooms: validateResponse<ClassroomOption[]>(
|
||||||
|
classroomOptionsSchema,
|
||||||
|
classroomList,
|
||||||
|
).filter((item: any) => item.status !== 'archived'),
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
message.error(error?.message || '加载考勤机绑定失败');
|
||||||
|
return { devices: [], classrooms: [] };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const data = fetchResult.devices;
|
||||||
|
const classrooms = fetchResult.classrooms;
|
||||||
|
const loading = isLoading || isFetching;
|
||||||
|
|
||||||
useEffect(() => {
|
const saveMutation = useApiMutation(
|
||||||
void loadData();
|
async (values: Record<string, unknown>) =>
|
||||||
}, []);
|
editing
|
||||||
|
? api.put(`/attendance-devices/${editing.id}`, values)
|
||||||
|
: api.post('/attendance-devices', values),
|
||||||
|
{ invalidate: [['attendance-devices']] },
|
||||||
|
);
|
||||||
|
const saveCellMutation = useApiMutation(
|
||||||
|
async ({ record, field, value }: { record: AttendanceDeviceRow; field: string; value: unknown }) =>
|
||||||
|
api.put(`/attendance-devices/${record.id}`, { [field]: value }),
|
||||||
|
{ invalidate: [['attendance-devices']] },
|
||||||
|
);
|
||||||
|
const deleteMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/attendance-devices/${id}`),
|
||||||
|
{ invalidate: [['attendance-devices']] },
|
||||||
|
);
|
||||||
|
|
||||||
const classroomOptions = useMemo(
|
const classroomOptions = useMemo(
|
||||||
() =>
|
() =>
|
||||||
@@ -102,37 +129,33 @@ const AttendanceDevicesPage: React.FC = () => {
|
|||||||
const values = await form.validateFields();
|
const values = await form.validateFields();
|
||||||
setSaving(true);
|
setSaving(true);
|
||||||
try {
|
try {
|
||||||
if (editing) {
|
await saveMutation.mutateAsync(values);
|
||||||
await api.put(`/attendance-devices/${editing.id}`, values);
|
message.success(editing ? '考勤机绑定已更新' : '考勤机绑定已创建');
|
||||||
message.success('考勤机绑定已更新');
|
|
||||||
} else {
|
|
||||||
await api.post('/attendance-devices', values);
|
|
||||||
message.success('考勤机绑定已创建');
|
|
||||||
}
|
|
||||||
setModalOpen(false);
|
setModalOpen(false);
|
||||||
setEditing(null);
|
setEditing(null);
|
||||||
form.resetFields();
|
form.resetFields();
|
||||||
await loadData();
|
} catch {
|
||||||
} catch (error: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error(error?.message || '保存失败');
|
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false);
|
setSaving(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const saveCell = async (record: AttendanceDeviceRow, field: string, value: unknown) => {
|
const saveCell = async (record: AttendanceDeviceRow, field: string, value: unknown) => {
|
||||||
await api.put(`/attendance-devices/${record.id}`, { [field]: value });
|
try {
|
||||||
message.success('已保存');
|
await saveCellMutation.mutateAsync({ record, field, value });
|
||||||
await loadData();
|
message.success('已保存');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDelete = async (id: number) => {
|
const handleDelete = async (id: number) => {
|
||||||
try {
|
try {
|
||||||
await api.delete(`/attendance-devices/${id}`);
|
await deleteMutation.mutateAsync(id);
|
||||||
message.success('已停用绑定');
|
message.success('已停用绑定');
|
||||||
await loadData();
|
} catch {
|
||||||
} catch (error: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error(error?.message || '停用失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -27,13 +27,21 @@ const statusLabels: Record<string, string> = {
|
|||||||
cancelled: '已取消',
|
cancelled: '已取消',
|
||||||
};
|
};
|
||||||
|
|
||||||
const escapeHtml = (value: unknown) =>
|
const HTML_ESCAPE_PAIRS: ReadonlyArray<readonly [string, string]> = [
|
||||||
String(value ?? '')
|
['&', '&'],
|
||||||
.replaceAll('&', '&')
|
['<', '<'],
|
||||||
.replaceAll('<', '<')
|
['>', '>'],
|
||||||
.replaceAll('>', '>')
|
['"', '"'],
|
||||||
.replaceAll('"', '"')
|
["'", '''],
|
||||||
.replaceAll("'", ''');
|
];
|
||||||
|
|
||||||
|
const escapeHtml = (value: unknown) => {
|
||||||
|
let text = String(value ?? '');
|
||||||
|
for (const [from, to] of HTML_ESCAPE_PAIRS) {
|
||||||
|
text = text.replaceAll(from, to);
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
};
|
||||||
|
|
||||||
const money = (value: unknown) => `¥${Number(value || 0).toFixed(2)}`;
|
const money = (value: unknown) => `¥${Number(value || 0).toFixed(2)}`;
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import React, { useEffect, useState, useMemo, useCallback } from 'react';
|
import React, { useState, useMemo, useCallback } from 'react';
|
||||||
import {
|
import {
|
||||||
|
App,
|
||||||
Table,
|
Table,
|
||||||
|
Button,
|
||||||
Modal,
|
Modal,
|
||||||
Form,
|
Form,
|
||||||
DatePicker,
|
DatePicker,
|
||||||
@@ -26,6 +28,11 @@ import { downloadBlob } from '../../utils/download';
|
|||||||
import { message } from '../../ui/app-message';
|
import { message } from '../../ui/app-message';
|
||||||
import { buildBillPrintHtml, type BillPrintData } from './bill-print';
|
import { buildBillPrintHtml, type BillPrintData } from './bill-print';
|
||||||
import { newOperationId } from '../../utils/operation-id';
|
import { newOperationId } from '../../utils/operation-id';
|
||||||
|
import { usePermission } from '../../hooks/usePermission';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||||
|
import { validateResponse } from '../../utils/validate';
|
||||||
|
import { billsSchema } from '../../api/schemas';
|
||||||
|
|
||||||
const statusMap: Record<string, { text: string; color: string }> = {
|
const statusMap: Record<string, { text: string; color: string }> = {
|
||||||
unpaid: { text: '待支付', color: 'orange' },
|
unpaid: { text: '待支付', color: 'orange' },
|
||||||
@@ -44,8 +51,9 @@ const typeMap: Record<string, string> = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const BillsPage: React.FC = () => {
|
const BillsPage: React.FC = () => {
|
||||||
const [bills, setBills] = useState<any[]>([]);
|
const { modal } = App.useApp();
|
||||||
const [loading, setLoading] = useState(false);
|
const { hasPermission } = usePermission();
|
||||||
|
const canPurgeBill = hasPermission('bill:purge');
|
||||||
const [generateModal, setGenerateModal] = useState(false);
|
const [generateModal, setGenerateModal] = useState(false);
|
||||||
const [detailModal, setDetailModal] = useState<any>(null);
|
const [detailModal, setDetailModal] = useState<any>(null);
|
||||||
const [selectedRows, setSelectedRows] = useState<number[]>([]);
|
const [selectedRows, setSelectedRows] = useState<number[]>([]);
|
||||||
@@ -57,23 +65,48 @@ const BillsPage: React.FC = () => {
|
|||||||
const [detailLoading, setDetailLoading] = useState(false);
|
const [detailLoading, setDetailLoading] = useState(false);
|
||||||
const [batchLoading, setBatchLoading] = useState(false);
|
const [batchLoading, setBatchLoading] = useState(false);
|
||||||
|
|
||||||
const fetchData = useCallback(async () => {
|
const {
|
||||||
setLoading(true);
|
data: bills = [],
|
||||||
try {
|
isLoading,
|
||||||
const params: Record<string, string | undefined> = {};
|
isFetching,
|
||||||
if (filterStatus) params.status = filterStatus;
|
} = useQuery({
|
||||||
if (filterExpenseType) params.expenseType = filterExpenseType;
|
queryKey: ['bills', filterStatus, filterExpenseType],
|
||||||
const res = (await api.get('/bills', { params })) as unknown[];
|
queryFn: async () => {
|
||||||
setBills(res);
|
try {
|
||||||
} catch (e: any) {
|
const params: Record<string, string | undefined> = {};
|
||||||
message.error(e?.message || '加载失败,请稍后重试');
|
if (filterStatus) params.status = filterStatus;
|
||||||
}
|
if (filterExpenseType) params.expenseType = filterExpenseType;
|
||||||
setLoading(false);
|
return validateResponse<unknown[]>(billsSchema, await api.get('/bills', { params }));
|
||||||
}, [filterStatus, filterExpenseType]);
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '加载失败,请稍后重试');
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const loading = isLoading || isFetching;
|
||||||
|
|
||||||
useEffect(() => {
|
const generateMutation = useApiMutation(
|
||||||
fetchData();
|
async (payload: { operationId: string; billingMonth: string }) =>
|
||||||
}, [fetchData]);
|
api.post('/bills/generate', payload),
|
||||||
|
{ invalidate: [['bills']] },
|
||||||
|
);
|
||||||
|
const cancelMutation = useApiMutation(
|
||||||
|
async ({ id, reason }: { id: number; reason: string }) =>
|
||||||
|
api.post(`/bills/${id}/cancel`, { operationId: newOperationId(), reason }),
|
||||||
|
{ invalidate: [['bills']] },
|
||||||
|
);
|
||||||
|
const archiveMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/bills/${id}`),
|
||||||
|
{ invalidate: [['bills']] },
|
||||||
|
);
|
||||||
|
const purgeMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/bills/${id}/permanent`),
|
||||||
|
{ invalidate: [['bills']] },
|
||||||
|
);
|
||||||
|
const batchArchiveMutation = useApiMutation(
|
||||||
|
async (ids: number[]) => api.post('/bills/batch/delete', { ids }),
|
||||||
|
{ invalidate: [['bills']] },
|
||||||
|
);
|
||||||
|
|
||||||
const filteredBills = useMemo(() => {
|
const filteredBills = useMemo(() => {
|
||||||
return bills.filter((b: any) => {
|
return bills.filter((b: any) => {
|
||||||
@@ -92,22 +125,21 @@ const BillsPage: React.FC = () => {
|
|||||||
setSaving(true);
|
setSaving(true);
|
||||||
const values = await generateForm.validateFields();
|
const values = await generateForm.validateFields();
|
||||||
try {
|
try {
|
||||||
const res: any = await api.post('/bills/generate', {
|
const res: any = await generateMutation.mutateAsync({
|
||||||
operationId: newOperationId(),
|
operationId: newOperationId(),
|
||||||
billingMonth: values.billingMonth.format('YYYY-MM'),
|
billingMonth: values.billingMonth.format('YYYY-MM'),
|
||||||
});
|
});
|
||||||
message.success(res.message || '生成成功');
|
message.success(res.message || '生成成功');
|
||||||
setGenerateModal(false);
|
setGenerateModal(false);
|
||||||
generateForm.resetFields();
|
generateForm.resetFields();
|
||||||
fetchData();
|
} catch {
|
||||||
} catch (e: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error(e?.message || '生成失败');
|
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false);
|
setSaving(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const showDetail = async (id: number) => {
|
const showDetail = useCallback(async (id: number) => {
|
||||||
setDetailLoading(true);
|
setDetailLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await api.get(`/bills/${id}`);
|
const res = await api.get(`/bills/${id}`);
|
||||||
@@ -117,59 +149,80 @@ const BillsPage: React.FC = () => {
|
|||||||
} finally {
|
} finally {
|
||||||
setDetailLoading(false);
|
setDetailLoading(false);
|
||||||
}
|
}
|
||||||
};
|
}, []);
|
||||||
|
|
||||||
const handleCancel = async (id: number) => {
|
const handleCancel = useCallback(
|
||||||
let reason = '';
|
(id: number) => {
|
||||||
Modal.confirm({
|
let reason = '';
|
||||||
title: '取消账单并退回已扣余额',
|
modal.confirm({
|
||||||
content: (
|
title: '取消账单并退回已扣余额',
|
||||||
<Input.TextArea
|
content: (
|
||||||
placeholder="请输入取消原因"
|
<Input.TextArea
|
||||||
maxLength={300}
|
placeholder="请输入取消原因"
|
||||||
onChange={(event) => {
|
maxLength={300}
|
||||||
reason = event.target.value;
|
onChange={(event) => {
|
||||||
}}
|
reason = event.target.value;
|
||||||
/>
|
}}
|
||||||
),
|
/>
|
||||||
okText: '确认取消',
|
),
|
||||||
cancelText: '返回',
|
okText: '确认取消',
|
||||||
onOk: async () => {
|
cancelText: '返回',
|
||||||
if (!reason.trim()) {
|
onOk: async () => {
|
||||||
message.error('请输入取消原因');
|
if (!reason.trim()) {
|
||||||
throw new Error('reason required');
|
message.error('请输入取消原因');
|
||||||
}
|
throw new Error('reason required');
|
||||||
await api.post(`/bills/${id}/cancel`, {
|
}
|
||||||
operationId: newOperationId(),
|
await cancelMutation.mutateAsync({ id, reason: reason.trim() });
|
||||||
reason: reason.trim(),
|
message.success('账单已取消,已扣余额已冲正退回');
|
||||||
});
|
},
|
||||||
message.success('账单已取消,已扣余额已冲正退回');
|
});
|
||||||
fetchData();
|
},
|
||||||
},
|
[modal, cancelMutation],
|
||||||
});
|
);
|
||||||
};
|
|
||||||
|
|
||||||
const handleArchive = async (id: number) => {
|
const handleArchive = useCallback(
|
||||||
try {
|
async (id: number) => {
|
||||||
await api.delete(`/bills/${id}`);
|
try {
|
||||||
message.success('账单已归档');
|
await archiveMutation.mutateAsync(id);
|
||||||
fetchData();
|
message.success('账单已归档');
|
||||||
} catch (error: any) {
|
} catch {
|
||||||
message.error(error?.message || '归档失败');
|
// 错误提示由 useApiMutation 统一处理
|
||||||
}
|
}
|
||||||
};
|
},
|
||||||
|
[archiveMutation],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handlePurge = useCallback(
|
||||||
|
(id: number, studentName: string, period: string) => {
|
||||||
|
modal.confirm({
|
||||||
|
title: `永久删除账单(${studentName} ${period})?`,
|
||||||
|
content: '删除后不可恢复,该账单及其明细将被物理删除。确定继续?',
|
||||||
|
okText: '永久删除',
|
||||||
|
okButtonProps: { danger: true },
|
||||||
|
cancelText: '取消',
|
||||||
|
onOk: async () => {
|
||||||
|
try {
|
||||||
|
await purgeMutation.mutateAsync(id);
|
||||||
|
message.success('已永久删除(不可恢复)');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[modal, purgeMutation],
|
||||||
|
);
|
||||||
|
|
||||||
const batchArchive = async () => {
|
const batchArchive = async () => {
|
||||||
if (selectedRows.length === 0) return message.warning('请先选择账单');
|
if (selectedRows.length === 0) return message.warning('请先选择账单');
|
||||||
if (batchLoading) return;
|
if (batchLoading) return;
|
||||||
setBatchLoading(true);
|
setBatchLoading(true);
|
||||||
try {
|
try {
|
||||||
await api.post('/bills/batch/delete', { ids: selectedRows });
|
await batchArchiveMutation.mutateAsync(selectedRows);
|
||||||
message.success(`已归档 ${selectedRows.length} 条账单`);
|
message.success(`已归档 ${selectedRows.length} 条账单`);
|
||||||
setSelectedRows([]);
|
setSelectedRows([]);
|
||||||
fetchData();
|
} catch {
|
||||||
} catch (e: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error(e?.message || '操作失败');
|
|
||||||
} finally {
|
} finally {
|
||||||
setBatchLoading(false);
|
setBatchLoading(false);
|
||||||
}
|
}
|
||||||
@@ -182,7 +235,7 @@ const BillsPage: React.FC = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleExportPdf = async (billId: number) => {
|
const handleExportPdf = useCallback(async (billId: number) => {
|
||||||
const printWindow = window.open('', '_blank');
|
const printWindow = window.open('', '_blank');
|
||||||
if (!printWindow) {
|
if (!printWindow) {
|
||||||
message.error('浏览器阻止了打印窗口,请允许弹出窗口后重试');
|
message.error('浏览器阻止了打印窗口,请允许弹出窗口后重试');
|
||||||
@@ -201,7 +254,7 @@ const BillsPage: React.FC = () => {
|
|||||||
printWindow.close();
|
printWindow.close();
|
||||||
message.error(error?.message || '账单加载失败');
|
message.error(error?.message || '账单加载失败');
|
||||||
}
|
}
|
||||||
};
|
}, []);
|
||||||
|
|
||||||
const columns = useMemo(
|
const columns = useMemo(
|
||||||
() => [
|
() => [
|
||||||
@@ -216,28 +269,28 @@ const BillsPage: React.FC = () => {
|
|||||||
dataIndex: 'sharedAmount',
|
dataIndex: 'sharedAmount',
|
||||||
width: 120,
|
width: 120,
|
||||||
align: 'right' as const,
|
align: 'right' as const,
|
||||||
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
render: (v: number) => `¥${v.toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '个人费用',
|
title: '个人费用',
|
||||||
dataIndex: 'personalAmount',
|
dataIndex: 'personalAmount',
|
||||||
width: 120,
|
width: 120,
|
||||||
align: 'right' as const,
|
align: 'right' as const,
|
||||||
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
render: (v: number) => `¥${v.toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '总计',
|
title: '总计',
|
||||||
dataIndex: 'totalAmount',
|
dataIndex: 'totalAmount',
|
||||||
width: 100,
|
width: 100,
|
||||||
align: 'right' as const,
|
align: 'right' as const,
|
||||||
render: (v: number) => <strong>¥{Number(v).toFixed(2)}</strong>,
|
render: (v: number) => <strong>¥{v.toFixed(2)}</strong>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '已扣余额',
|
title: '已扣余额',
|
||||||
dataIndex: 'paidAmount',
|
dataIndex: 'paidAmount',
|
||||||
width: 110,
|
width: 110,
|
||||||
render: (value: number) => (
|
render: (value: number) => (
|
||||||
<span style={{ color: '#389e0d' }}>¥{Number(value || 0).toFixed(2)}</span>
|
<span style={{ color: '#389e0d' }}>¥{(value ?? 0).toFixed(2)}</span>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -245,8 +298,8 @@ const BillsPage: React.FC = () => {
|
|||||||
dataIndex: 'outstandingAmount',
|
dataIndex: 'outstandingAmount',
|
||||||
width: 110,
|
width: 110,
|
||||||
render: (value: number) => (
|
render: (value: number) => (
|
||||||
<strong style={{ color: Number(value) > 0 ? '#cf1322' : '#389e0d' }}>
|
<strong style={{ color: value > 0 ? '#cf1322' : '#389e0d' }}>
|
||||||
¥{Number(value || 0).toFixed(2)}
|
¥{(value ?? 0).toFixed(2)}
|
||||||
</strong>
|
</strong>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -289,6 +342,22 @@ const BillsPage: React.FC = () => {
|
|||||||
>
|
>
|
||||||
PDF
|
PDF
|
||||||
</PermissionButton>
|
</PermissionButton>
|
||||||
|
{record.status === 'cancelled' && canPurgeBill ? (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
danger
|
||||||
|
type="link"
|
||||||
|
onClick={() =>
|
||||||
|
handlePurge(
|
||||||
|
record.id,
|
||||||
|
record.student?.name || '-',
|
||||||
|
`${record.periodStart}~${record.periodEnd}`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
{record.status !== 'cancelled' && (
|
{record.status !== 'cancelled' && (
|
||||||
<PermissionButton
|
<PermissionButton
|
||||||
permission="bill:delete"
|
permission="bill:delete"
|
||||||
@@ -320,7 +389,7 @@ const BillsPage: React.FC = () => {
|
|||||||
),
|
),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
[showDetail, handleArchive, handleCancel, handleExportPdf],
|
[showDetail, handleArchive, handleCancel, handleExportPdf, canPurgeBill, handlePurge],
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -511,12 +580,12 @@ const BillsPage: React.FC = () => {
|
|||||||
{
|
{
|
||||||
title: '宿舍总费用',
|
title: '宿舍总费用',
|
||||||
dataIndex: 'roomTotalAmount',
|
dataIndex: 'roomTotalAmount',
|
||||||
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
render: (v: number) => `¥${v.toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '应分摊',
|
title: '应分摊',
|
||||||
dataIndex: 'studentAmount',
|
dataIndex: 'studentAmount',
|
||||||
render: (v: number) => <strong>¥{Number(v).toFixed(2)}</strong>,
|
render: (v: number) => <strong>¥{v.toFixed(2)}</strong>,
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
|
|||||||
557
apps/admin/src/pages/Classes/ClassDetailTabs.tsx
Normal file
557
apps/admin/src/pages/Classes/ClassDetailTabs.tsx
Normal file
@@ -0,0 +1,557 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Col,
|
||||||
|
DatePicker,
|
||||||
|
Descriptions,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
InputNumber,
|
||||||
|
Modal,
|
||||||
|
Popconfirm,
|
||||||
|
Row,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Statistic,
|
||||||
|
Table,
|
||||||
|
Tag,
|
||||||
|
} from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import { DownloadOutlined, PlusOutlined } from '@ant-design/icons';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
import { useUserStore } from '../../store/user/userStore';
|
||||||
|
import PermissionButton from '../../components/PermissionButton';
|
||||||
|
import { message } from '../../ui/app-message';
|
||||||
|
import { buildTeacherCandidateOptions, type TeacherCandidateUser } from './teacher-candidate';
|
||||||
|
|
||||||
|
export interface ClassStudent {
|
||||||
|
id: number;
|
||||||
|
studentId: number;
|
||||||
|
studentName: string;
|
||||||
|
studentNo: string;
|
||||||
|
joinDate: string;
|
||||||
|
leaveDate: string | null;
|
||||||
|
status: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClassTeacher {
|
||||||
|
id: number;
|
||||||
|
userId: number;
|
||||||
|
username: string;
|
||||||
|
roleType: string;
|
||||||
|
subject: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClassScheduleItem {
|
||||||
|
id: number;
|
||||||
|
classId: number;
|
||||||
|
classroomId: number;
|
||||||
|
classroomName: string;
|
||||||
|
weekDay: number;
|
||||||
|
startTime: string;
|
||||||
|
endTime: string;
|
||||||
|
attendanceAdvanceMinutes: number;
|
||||||
|
startDate: string;
|
||||||
|
endDate: string;
|
||||||
|
subject: string;
|
||||||
|
teacherId: number | null;
|
||||||
|
scheduleType: string;
|
||||||
|
status: string;
|
||||||
|
notes: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AttendanceSummary {
|
||||||
|
total: number;
|
||||||
|
present: number;
|
||||||
|
late: number;
|
||||||
|
absent: number;
|
||||||
|
leave: number;
|
||||||
|
presentRate: number;
|
||||||
|
absentRate: number;
|
||||||
|
lateRate: number;
|
||||||
|
leaveRate: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClassDetail {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
code: string;
|
||||||
|
classType: string;
|
||||||
|
startDate: string | null;
|
||||||
|
endDate: string | null;
|
||||||
|
status: string;
|
||||||
|
maxStudents: number;
|
||||||
|
notes: string | null;
|
||||||
|
studentCount: number;
|
||||||
|
students?: ClassStudent[];
|
||||||
|
teachers?: ClassTeacher[];
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StudentItem {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
studentNo?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const STATUS_MAP: Record<string, { color: string; text: string }> = {
|
||||||
|
enrolling: { color: 'blue', text: '招生中' },
|
||||||
|
active: { color: 'green', text: '在读' },
|
||||||
|
ended: { color: 'default', text: '结课' },
|
||||||
|
suspended: { color: 'orange', text: '停课' },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const TYPE_MAP: Record<string, string> = {
|
||||||
|
culture: '文化课',
|
||||||
|
professional: '专业课',
|
||||||
|
bootcamp: '集训营',
|
||||||
|
sprint: '冲刺营',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ROLE_MAP: Record<string, string> = {
|
||||||
|
subject_teacher: '任课老师',
|
||||||
|
head_teacher: '班主任',
|
||||||
|
life_teacher: '生活老师',
|
||||||
|
academic_teacher: '学服老师',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const WEEK_DAY_MAP: Record<number, string> = {
|
||||||
|
1: '周一',
|
||||||
|
2: '周二',
|
||||||
|
3: '周三',
|
||||||
|
4: '周四',
|
||||||
|
5: '周五',
|
||||||
|
6: '周六',
|
||||||
|
7: '周日',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const SCHEDULE_TYPE_MAP: Record<string, string> = {
|
||||||
|
INTERNAL: '内部排课',
|
||||||
|
RENTAL: '租赁',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ClassInfoTab: React.FC<{
|
||||||
|
detail: ClassDetail;
|
||||||
|
teachers: ClassTeacher[];
|
||||||
|
editingInfo: boolean;
|
||||||
|
editForm: ReturnType<typeof Form.useForm>[0];
|
||||||
|
onSave: () => void;
|
||||||
|
onEdit: () => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
getTeacherName: (teacher: ClassTeacher) => string;
|
||||||
|
}> = ({ detail, teachers, editingInfo, editForm, onSave, onEdit, onCancel, getTeacherName }) => {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{editingInfo ? (
|
||||||
|
<Form
|
||||||
|
form={editForm}
|
||||||
|
layout="vertical"
|
||||||
|
initialValues={{
|
||||||
|
name: detail.name,
|
||||||
|
code: detail.code,
|
||||||
|
classType: detail.classType,
|
||||||
|
startDate: detail.startDate ? dayjs(detail.startDate) : undefined,
|
||||||
|
endDate: detail.endDate ? dayjs(detail.endDate) : undefined,
|
||||||
|
maxStudents: detail.maxStudents,
|
||||||
|
status: detail.status,
|
||||||
|
notes: detail.notes,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Space wrap>
|
||||||
|
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
|
||||||
|
<Input />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="code" label="编码">
|
||||||
|
<Input />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="classType" label="班型">
|
||||||
|
<Select
|
||||||
|
options={Object.entries(TYPE_MAP).map(([k, v]) => ({
|
||||||
|
value: k,
|
||||||
|
label: v,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="startDate" label="开班">
|
||||||
|
<DatePicker />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="endDate" label="结课">
|
||||||
|
<DatePicker />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="maxStudents" label="人数上限">
|
||||||
|
<InputNumber min={1} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="status" label="状态">
|
||||||
|
<Select
|
||||||
|
options={Object.entries(STATUS_MAP).map(([k, v]) => ({
|
||||||
|
value: k,
|
||||||
|
label: v.text,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
</Space>
|
||||||
|
<Form.Item name="notes" label="备注">
|
||||||
|
<Input.TextArea rows={3} />
|
||||||
|
</Form.Item>
|
||||||
|
<Space>
|
||||||
|
<PermissionButton permission="class:edit" type="primary" onClick={onSave}>
|
||||||
|
保存
|
||||||
|
</PermissionButton>
|
||||||
|
<Button onClick={onCancel}>取消</Button>
|
||||||
|
</Space>
|
||||||
|
</Form>
|
||||||
|
) : (
|
||||||
|
<div>
|
||||||
|
<Descriptions column={3} bordered size="small">
|
||||||
|
<Descriptions.Item label="班型">{TYPE_MAP[detail.classType]}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="开班日期">
|
||||||
|
{detail.startDate ? dayjs(detail.startDate).format('YYYY-MM-DD') : '-'}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="结课日期">
|
||||||
|
{detail.endDate ? dayjs(detail.endDate).format('YYYY-MM-DD') : '-'}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="学员">
|
||||||
|
{detail.studentCount}/{detail.maxStudents || '-'}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="班主任">
|
||||||
|
{(() => {
|
||||||
|
const headTeacher = teachers.find(
|
||||||
|
(teacher) => teacher.roleType === 'head_teacher',
|
||||||
|
);
|
||||||
|
return headTeacher ? getTeacherName(headTeacher) : '-';
|
||||||
|
})()}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="备注">{detail.notes || '-'}</Descriptions.Item>
|
||||||
|
</Descriptions>
|
||||||
|
<PermissionButton permission="class:edit" style={{ marginTop: 16 }} onClick={onEdit}>
|
||||||
|
编辑
|
||||||
|
</PermissionButton>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ClassStudentsTab: React.FC<{
|
||||||
|
id?: string;
|
||||||
|
detail?: ClassDetail | null;
|
||||||
|
students: ClassStudent[];
|
||||||
|
allStudents: StudentItem[];
|
||||||
|
selectedStudentIds: number[];
|
||||||
|
modalOpen: boolean;
|
||||||
|
onOpen: () => void;
|
||||||
|
onAdd: () => void;
|
||||||
|
onClose: () => void;
|
||||||
|
onRemove: (studentId: number) => void;
|
||||||
|
onSelect: (ids: number[]) => void;
|
||||||
|
}> = ({
|
||||||
|
id,
|
||||||
|
detail,
|
||||||
|
students,
|
||||||
|
allStudents,
|
||||||
|
selectedStudentIds,
|
||||||
|
modalOpen,
|
||||||
|
onOpen,
|
||||||
|
onAdd,
|
||||||
|
onClose,
|
||||||
|
onRemove,
|
||||||
|
onSelect,
|
||||||
|
}) => {
|
||||||
|
const studentColumns: ColumnsType<ClassStudent> = [
|
||||||
|
{ title: '姓名', dataIndex: 'studentName' },
|
||||||
|
{ title: '学号', dataIndex: 'studentNo' },
|
||||||
|
{ title: '加入日期', dataIndex: 'joinDate' },
|
||||||
|
{ title: '离班日期', dataIndex: 'leaveDate', render: (v: string | null) => v || '-' },
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'status',
|
||||||
|
render: (v: string) => (
|
||||||
|
<Tag color={v === 'active' ? 'green' : 'default'}>{v === 'active' ? '在读' : '已离班'}</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
render: (_: unknown, r: ClassStudent) =>
|
||||||
|
r.status === 'active' ? (
|
||||||
|
<Popconfirm title="确认移除?" onConfirm={() => onRemove(r.studentId)}>
|
||||||
|
<PermissionButton permission="class:edit" size="small" danger>
|
||||||
|
移除
|
||||||
|
</PermissionButton>
|
||||||
|
</Popconfirm>
|
||||||
|
) : null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<PermissionButton
|
||||||
|
permission="class:edit"
|
||||||
|
icon={<PlusOutlined />}
|
||||||
|
type="primary"
|
||||||
|
onClick={onOpen}
|
||||||
|
style={{ marginBottom: 16, marginRight: 8 }}
|
||||||
|
>
|
||||||
|
添加学员
|
||||||
|
</PermissionButton>
|
||||||
|
<PermissionButton
|
||||||
|
permission="class:view"
|
||||||
|
icon={<DownloadOutlined />}
|
||||||
|
onClick={() => {
|
||||||
|
const token = useUserStore.getState().token;
|
||||||
|
fetch(`/api/classes/${id}/roster/export`, {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
})
|
||||||
|
.then((res) => {
|
||||||
|
if (!res.ok) throw new Error('导出失败');
|
||||||
|
return res.blob();
|
||||||
|
})
|
||||||
|
.then((blob) => {
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = `班级花名册-${detail?.name || id}.xlsx`;
|
||||||
|
a.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
message.success('花名册导出成功');
|
||||||
|
})
|
||||||
|
.catch(() => message.error('花名册导出失败'));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
导出花名册
|
||||||
|
</PermissionButton>
|
||||||
|
<Table<ClassStudent>
|
||||||
|
columns={studentColumns}
|
||||||
|
dataSource={students}
|
||||||
|
rowKey="id"
|
||||||
|
pagination={{
|
||||||
|
defaultPageSize: 20,
|
||||||
|
showSizeChanger: true,
|
||||||
|
pageSizeOptions: [20, 50, 100],
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Modal title="添加学员" open={modalOpen} onOk={onAdd} onCancel={onClose}>
|
||||||
|
<Select
|
||||||
|
mode="multiple"
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
placeholder="选择学员"
|
||||||
|
value={selectedStudentIds}
|
||||||
|
onChange={onSelect}
|
||||||
|
options={allStudents.map((s) => ({
|
||||||
|
value: s.id,
|
||||||
|
label: `${s.name} (${s.studentNo || s.id})`,
|
||||||
|
}))}
|
||||||
|
filterOption={(input, option) =>
|
||||||
|
(option?.label as string)?.toLowerCase().includes(input.toLowerCase())
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ClassTeachersTab: React.FC<{
|
||||||
|
teachers: ClassTeacher[];
|
||||||
|
allUsers: TeacherCandidateUser[];
|
||||||
|
teacherRole: string;
|
||||||
|
teacherSubject: string;
|
||||||
|
teacherUserId?: number;
|
||||||
|
modalOpen: boolean;
|
||||||
|
onOpen: () => void;
|
||||||
|
onAdd: () => void;
|
||||||
|
onClose: () => void;
|
||||||
|
onRemove: (userId: number) => void;
|
||||||
|
onRoleChange: (role: string) => void;
|
||||||
|
onSubjectChange: (subject: string) => void;
|
||||||
|
onUserChange: (userId?: number) => void;
|
||||||
|
getTeacherName: (teacher: ClassTeacher) => string;
|
||||||
|
}> = ({
|
||||||
|
teachers,
|
||||||
|
allUsers,
|
||||||
|
teacherRole,
|
||||||
|
teacherSubject,
|
||||||
|
teacherUserId,
|
||||||
|
modalOpen,
|
||||||
|
onOpen,
|
||||||
|
onAdd,
|
||||||
|
onClose,
|
||||||
|
onRemove,
|
||||||
|
onRoleChange,
|
||||||
|
onSubjectChange,
|
||||||
|
onUserChange,
|
||||||
|
getTeacherName,
|
||||||
|
}) => {
|
||||||
|
const teacherColumns: ColumnsType<ClassTeacher> = [
|
||||||
|
{ title: '姓名', render: (_: unknown, teacher) => getTeacherName(teacher) },
|
||||||
|
{
|
||||||
|
title: '角色',
|
||||||
|
dataIndex: 'roleType',
|
||||||
|
render: (v: string) => <Tag>{ROLE_MAP[v] || v}</Tag>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '科目',
|
||||||
|
dataIndex: 'subject',
|
||||||
|
render: (v: string | null) => v || '-',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
render: (_: unknown, r: ClassTeacher) => (
|
||||||
|
<Popconfirm title="确认移除?" onConfirm={() => onRemove(r.userId)}>
|
||||||
|
<PermissionButton permission="class:edit" size="small" danger>
|
||||||
|
移除
|
||||||
|
</PermissionButton>
|
||||||
|
</Popconfirm>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<PermissionButton
|
||||||
|
permission="class:edit"
|
||||||
|
icon={<PlusOutlined />}
|
||||||
|
type="primary"
|
||||||
|
onClick={onOpen}
|
||||||
|
style={{ marginBottom: 16 }}
|
||||||
|
>
|
||||||
|
添加教师
|
||||||
|
</PermissionButton>
|
||||||
|
<Table<ClassTeacher>
|
||||||
|
columns={teacherColumns}
|
||||||
|
dataSource={teachers}
|
||||||
|
rowKey="id"
|
||||||
|
pagination={{
|
||||||
|
defaultPageSize: 20,
|
||||||
|
showSizeChanger: true,
|
||||||
|
pageSizeOptions: [20, 50, 100],
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Modal title="添加教师" open={modalOpen} onOk={onAdd} onCancel={onClose}>
|
||||||
|
<Space orientation="vertical" style={{ width: '100%' }}>
|
||||||
|
<Select
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
showSearch
|
||||||
|
optionFilterProp="label"
|
||||||
|
placeholder="搜索姓名、用户名、角色或学科"
|
||||||
|
value={teacherUserId}
|
||||||
|
onChange={onUserChange}
|
||||||
|
options={buildTeacherCandidateOptions(allUsers)}
|
||||||
|
notFoundContent="没有可分配的工作人员账号"
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
value={teacherRole}
|
||||||
|
onChange={onRoleChange}
|
||||||
|
options={Object.entries(ROLE_MAP).map(([k, v]) => ({
|
||||||
|
value: k,
|
||||||
|
label: v,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
{teacherRole === 'subject_teacher' && (
|
||||||
|
<Input
|
||||||
|
placeholder="任教科目"
|
||||||
|
value={teacherSubject}
|
||||||
|
onChange={(e) => onSubjectChange(e.target.value)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Space>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ClassScheduleTab: React.FC<{
|
||||||
|
schedules: ClassScheduleItem[];
|
||||||
|
scheduleDateRange: [dayjs.Dayjs | null, dayjs.Dayjs | null];
|
||||||
|
onRangeChange: (dates: [dayjs.Dayjs | null, dayjs.Dayjs | null]) => void;
|
||||||
|
}> = ({ schedules, scheduleDateRange, onRangeChange }) => {
|
||||||
|
const scheduleColumns: ColumnsType<ClassScheduleItem> = [
|
||||||
|
{ title: '教室', dataIndex: 'classroomName', render: (v: string | null) => v || '-' },
|
||||||
|
{ title: '星期', dataIndex: 'weekDay', render: (v: number) => WEEK_DAY_MAP[v] || v },
|
||||||
|
{
|
||||||
|
title: '时间',
|
||||||
|
render: (_: unknown, r: ClassScheduleItem) => `${r.startTime} - ${r.endTime}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '签到窗口',
|
||||||
|
render: (_: unknown, r: ClassScheduleItem) =>
|
||||||
|
`课前 ${r.attendanceAdvanceMinutes ?? 30} 分钟至下课`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '日期范围',
|
||||||
|
render: (_: unknown, r: ClassScheduleItem) => `${r.startDate} ~ ${r.endDate}`,
|
||||||
|
},
|
||||||
|
{ title: '科目', dataIndex: 'subject' },
|
||||||
|
{ title: '类型', dataIndex: 'scheduleType', render: (v: string) => SCHEDULE_TYPE_MAP[v] || v },
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'status',
|
||||||
|
render: (v: string) => (
|
||||||
|
<Tag color={v === 'active' ? 'green' : 'default'}>{v === 'active' ? '启用' : v}</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Space style={{ marginBottom: 16, maxWidth: '100%' }} wrap>
|
||||||
|
<DatePicker.RangePicker
|
||||||
|
value={scheduleDateRange}
|
||||||
|
onChange={(dates) => onRangeChange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])}
|
||||||
|
placeholder={['开始日期', '结束日期']}
|
||||||
|
/>
|
||||||
|
</Space>
|
||||||
|
<Table<ClassScheduleItem>
|
||||||
|
columns={scheduleColumns}
|
||||||
|
dataSource={schedules}
|
||||||
|
rowKey="id"
|
||||||
|
scroll={{ x: 'max-content' }}
|
||||||
|
pagination={{
|
||||||
|
defaultPageSize: 20,
|
||||||
|
showSizeChanger: true,
|
||||||
|
pageSizeOptions: [20, 50, 100],
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ClassAttendanceTab: React.FC<{
|
||||||
|
attendanceSummary: AttendanceSummary | null;
|
||||||
|
attendanceDateRange: [dayjs.Dayjs | null, dayjs.Dayjs | null];
|
||||||
|
onRangeChange: (dates: [dayjs.Dayjs | null, dayjs.Dayjs | null]) => void;
|
||||||
|
}> = ({ attendanceSummary, attendanceDateRange, onRangeChange }) => {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Space style={{ marginBottom: 16, maxWidth: '100%' }} wrap>
|
||||||
|
<DatePicker.RangePicker
|
||||||
|
value={attendanceDateRange}
|
||||||
|
onChange={(dates) => onRangeChange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])}
|
||||||
|
placeholder={['开始日期', '结束日期']}
|
||||||
|
/>
|
||||||
|
</Space>
|
||||||
|
{attendanceSummary && (
|
||||||
|
<Row gutter={[16, 16]}>
|
||||||
|
<Col xs={12} md={6}>
|
||||||
|
<Card variant="borderless">
|
||||||
|
<Statistic title="总记录" value={attendanceSummary.total} />
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
|
<Col xs={12} md={6}>
|
||||||
|
<Card variant="borderless">
|
||||||
|
<Statistic title="出勤率" value={attendanceSummary.presentRate} suffix="%" />
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
|
<Col xs={12} md={6}>
|
||||||
|
<Card variant="borderless">
|
||||||
|
<Statistic title="缺勤率" value={attendanceSummary.absentRate} suffix="%" />
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
|
<Col xs={12} md={6}>
|
||||||
|
<Card variant="borderless">
|
||||||
|
<Statistic title="迟到率" value={attendanceSummary.lateRate} suffix="%" />
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
|
</Row>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,154 +1,30 @@
|
|||||||
import React, { useEffect, useState, useCallback } from 'react';
|
import React, { useState, useCallback } from 'react';
|
||||||
import { useParams, useNavigate } from 'react-router-dom';
|
import { useParams, useNavigate } from 'react-router';
|
||||||
import {
|
import { Button, Card, Form, Space, Tabs, Tag } from 'antd';
|
||||||
Card,
|
import { ArrowLeftOutlined } from '@ant-design/icons';
|
||||||
Tabs,
|
|
||||||
Descriptions,
|
|
||||||
Table,
|
|
||||||
Button,
|
|
||||||
Space,
|
|
||||||
Select,
|
|
||||||
Modal,
|
|
||||||
Tag,
|
|
||||||
Popconfirm,
|
|
||||||
Form,
|
|
||||||
Input,
|
|
||||||
DatePicker,
|
|
||||||
InputNumber,
|
|
||||||
Row,
|
|
||||||
Col,
|
|
||||||
Statistic,
|
|
||||||
} from 'antd';
|
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
|
||||||
import { ArrowLeftOutlined, PlusOutlined, DownloadOutlined } from '@ant-design/icons';
|
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import api from '../../api';
|
import api from '../../api';
|
||||||
import PermissionButton from '../../components/PermissionButton';
|
|
||||||
import { message } from '../../ui/app-message';
|
import { message } from '../../ui/app-message';
|
||||||
import { buildTeacherCandidateOptions, type TeacherCandidateUser } from './teacher-candidate';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import type { TeacherCandidateUser } from './teacher-candidate';
|
||||||
// ---- Types ----
|
import { getErrorMessage } from '../../utils/error';
|
||||||
|
import {
|
||||||
interface ClassStudent {
|
ClassAttendanceTab,
|
||||||
id: number;
|
ClassInfoTab,
|
||||||
studentId: number;
|
ClassScheduleTab,
|
||||||
studentName: string;
|
ClassStudentsTab,
|
||||||
studentNo: string;
|
ClassTeachersTab,
|
||||||
joinDate: string;
|
STATUS_MAP,
|
||||||
leaveDate: string | null;
|
type ClassDetail,
|
||||||
status: string;
|
type ClassTeacher,
|
||||||
}
|
type StudentItem,
|
||||||
|
type AttendanceSummary,
|
||||||
interface ClassTeacher {
|
type ClassScheduleItem,
|
||||||
id: number;
|
} from './ClassDetailTabs';
|
||||||
userId: number;
|
|
||||||
username: string;
|
|
||||||
roleType: string;
|
|
||||||
subject: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ClassScheduleItem {
|
|
||||||
id: number;
|
|
||||||
classId: number;
|
|
||||||
classroomId: number;
|
|
||||||
classroomName: string;
|
|
||||||
weekDay: number;
|
|
||||||
startTime: string;
|
|
||||||
endTime: string;
|
|
||||||
attendanceAdvanceMinutes: number;
|
|
||||||
startDate: string;
|
|
||||||
endDate: string;
|
|
||||||
subject: string;
|
|
||||||
teacherId: number | null;
|
|
||||||
scheduleType: string;
|
|
||||||
status: string;
|
|
||||||
notes: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AttendanceSummary {
|
|
||||||
total: number;
|
|
||||||
present: number;
|
|
||||||
late: number;
|
|
||||||
absent: number;
|
|
||||||
leave: number;
|
|
||||||
presentRate: number;
|
|
||||||
absentRate: number;
|
|
||||||
lateRate: number;
|
|
||||||
leaveRate: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ClassDetail {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
code: string;
|
|
||||||
classType: string;
|
|
||||||
startDate: string | null;
|
|
||||||
endDate: string | null;
|
|
||||||
status: string;
|
|
||||||
maxStudents: number;
|
|
||||||
notes: string | null;
|
|
||||||
studentCount: number;
|
|
||||||
students?: ClassStudent[];
|
|
||||||
teachers?: ClassTeacher[];
|
|
||||||
createdAt: string;
|
|
||||||
updatedAt: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface StudentItem {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
studentNo?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
type UserItem = TeacherCandidateUser;
|
|
||||||
|
|
||||||
// ---- Constants ----
|
|
||||||
|
|
||||||
const STATUS_MAP: Record<string, { color: string; text: string }> = {
|
|
||||||
enrolling: { color: 'blue', text: '招生中' },
|
|
||||||
active: { color: 'green', text: '在读' },
|
|
||||||
ended: { color: 'default', text: '结课' },
|
|
||||||
suspended: { color: 'orange', text: '停课' },
|
|
||||||
};
|
|
||||||
|
|
||||||
const TYPE_MAP: Record<string, string> = {
|
|
||||||
culture: '文化课',
|
|
||||||
professional: '专业课',
|
|
||||||
bootcamp: '集训营',
|
|
||||||
sprint: '冲刺营',
|
|
||||||
};
|
|
||||||
|
|
||||||
const ROLE_MAP: Record<string, string> = {
|
|
||||||
subject_teacher: '任课老师',
|
|
||||||
head_teacher: '班主任',
|
|
||||||
life_teacher: '生活老师',
|
|
||||||
academic_teacher: '学服老师',
|
|
||||||
};
|
|
||||||
|
|
||||||
const WEEK_DAY_MAP: Record<number, string> = {
|
|
||||||
1: '周一',
|
|
||||||
2: '周二',
|
|
||||||
3: '周三',
|
|
||||||
4: '周四',
|
|
||||||
5: '周五',
|
|
||||||
6: '周六',
|
|
||||||
7: '周日',
|
|
||||||
};
|
|
||||||
|
|
||||||
const SCHEDULE_TYPE_MAP: Record<string, string> = {
|
|
||||||
INTERNAL: '内部排课',
|
|
||||||
RENTAL: '租赁',
|
|
||||||
};
|
|
||||||
|
|
||||||
// ---- Component ----
|
|
||||||
|
|
||||||
const ClassDetailPage: React.FC = () => {
|
const ClassDetailPage: React.FC = () => {
|
||||||
const { id } = useParams<{ id: string }>();
|
const { id } = useParams<{ id: string }>();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [detail, setDetail] = useState<ClassDetail | null>(null);
|
|
||||||
const [students, setStudents] = useState<ClassStudent[]>([]);
|
|
||||||
const [teachers, setTeachers] = useState<ClassTeacher[]>([]);
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [editForm] = Form.useForm();
|
const [editForm] = Form.useForm();
|
||||||
const [editingInfo, setEditingInfo] = useState(false);
|
const [editingInfo, setEditingInfo] = useState(false);
|
||||||
|
|
||||||
@@ -159,75 +35,93 @@ const ClassDetailPage: React.FC = () => {
|
|||||||
|
|
||||||
// Teacher modal state
|
// Teacher modal state
|
||||||
const [teacherModalOpen, setTeacherModalOpen] = useState(false);
|
const [teacherModalOpen, setTeacherModalOpen] = useState(false);
|
||||||
const [allUsers, setAllUsers] = useState<UserItem[]>([]);
|
|
||||||
const [teacherRole, setTeacherRole] = useState('subject_teacher');
|
const [teacherRole, setTeacherRole] = useState('subject_teacher');
|
||||||
const [teacherSubject, setTeacherSubject] = useState('');
|
const [teacherSubject, setTeacherSubject] = useState('');
|
||||||
const [teacherUserId, setTeacherUserId] = useState<number>();
|
const [teacherUserId, setTeacherUserId] = useState<number>();
|
||||||
|
|
||||||
// Schedule & attendance state
|
// Schedule & attendance state
|
||||||
const [schedules, setSchedules] = useState<ClassScheduleItem[]>([]);
|
|
||||||
const [scheduleDateRange, setScheduleDateRange] = useState<
|
const [scheduleDateRange, setScheduleDateRange] = useState<
|
||||||
[dayjs.Dayjs | null, dayjs.Dayjs | null]
|
[dayjs.Dayjs | null, dayjs.Dayjs | null]
|
||||||
>([null, null]);
|
>([null, null]);
|
||||||
const [attendanceSummary, setAttendanceSummary] = useState<AttendanceSummary | null>(null);
|
|
||||||
const [attendanceDateRange, setAttendanceDateRange] = useState<
|
const [attendanceDateRange, setAttendanceDateRange] = useState<
|
||||||
[dayjs.Dayjs | null, dayjs.Dayjs | null]
|
[dayjs.Dayjs | null, dayjs.Dayjs | null]
|
||||||
>([null, null]);
|
>([null, null]);
|
||||||
|
|
||||||
const fetchDetail = useCallback(async () => {
|
const {
|
||||||
setLoading(true);
|
data: detailResult = { detail: null, students: [], teachers: [] },
|
||||||
try {
|
isLoading: detailLoading,
|
||||||
const res = (await api.get(`/classes/${id}`)) as ClassDetail;
|
isFetching: detailFetching,
|
||||||
setDetail(res);
|
refetch: refetchDetail,
|
||||||
setStudents(res.students || []);
|
} = useQuery<{
|
||||||
setTeachers(res.teachers || []);
|
detail: ClassDetail | null;
|
||||||
} catch (e: unknown) {
|
students: ClassDetail['students'];
|
||||||
const err = e as { message?: string };
|
teachers: ClassDetail['teachers'];
|
||||||
message.error(err?.message || '加载失败');
|
}>({
|
||||||
} finally {
|
queryKey: ['classes', 'detail', id],
|
||||||
setLoading(false);
|
queryFn: async () => {
|
||||||
}
|
try {
|
||||||
}, [id]);
|
const res = (await api.get(`/classes/${id}`)) as ClassDetail;
|
||||||
|
return { detail: res, students: res.students || [], teachers: res.teachers || [] };
|
||||||
|
} catch (e: unknown) {
|
||||||
|
message.error(getErrorMessage(e, '加载失败'));
|
||||||
|
return { detail: null, students: [], teachers: [] };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const detail = detailResult.detail;
|
||||||
|
const students = detailResult.students ?? [];
|
||||||
|
const teachers = detailResult.teachers ?? [];
|
||||||
|
const loading = detailLoading || detailFetching;
|
||||||
|
const fetchDetail = useCallback(() => refetchDetail(), [refetchDetail]);
|
||||||
|
|
||||||
useEffect(() => {
|
const { data: allUsers = [], refetch: refetchUsers } = useQuery<TeacherCandidateUser[]>({
|
||||||
fetchDetail();
|
queryKey: ['rbac', 'users', 'all'],
|
||||||
}, [fetchDetail]);
|
queryFn: async () => {
|
||||||
|
try {
|
||||||
|
return (await api.get('/rbac/users')) as TeacherCandidateUser[];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const fetchUsers = useCallback(() => refetchUsers(), [refetchUsers]);
|
||||||
|
|
||||||
const fetchSchedules = useCallback(async () => {
|
const { data: schedules = [] } = useQuery<ClassScheduleItem[]>({
|
||||||
if (!id) return;
|
queryKey: ['classes', 'schedule', id, scheduleDateRange],
|
||||||
try {
|
queryFn: async () => {
|
||||||
const params: Record<string, string> = {};
|
if (!id) return [];
|
||||||
if (scheduleDateRange?.[0]) params.startDate = scheduleDateRange[0].format('YYYY-MM-DD');
|
try {
|
||||||
if (scheduleDateRange?.[1]) params.endDate = scheduleDateRange[1].format('YYYY-MM-DD');
|
const params: Record<string, string> = {};
|
||||||
const res = await api.get<ClassScheduleItem[]>(`/classes/${id}/schedule`, { params });
|
if (scheduleDateRange?.[0]) params.startDate = scheduleDateRange[0].format('YYYY-MM-DD');
|
||||||
setSchedules(res || []);
|
if (scheduleDateRange?.[1]) params.endDate = scheduleDateRange[1].format('YYYY-MM-DD');
|
||||||
} catch (e: unknown) {
|
return (await api.get<ClassScheduleItem[]>(`/classes/${id}/schedule`, { params })) || [];
|
||||||
const err = e as { message?: string };
|
} catch (e: unknown) {
|
||||||
message.error(err?.message || '加载课表失败');
|
message.error(getErrorMessage(e, '加载课表失败'));
|
||||||
}
|
return [];
|
||||||
}, [id, scheduleDateRange]);
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
const { data: attendanceSummary = null } = useQuery<AttendanceSummary | null>({
|
||||||
fetchSchedules();
|
queryKey: ['classes', 'attendance-summary', id, attendanceDateRange],
|
||||||
}, [fetchSchedules]);
|
queryFn: async () => {
|
||||||
|
if (!id) return null;
|
||||||
const fetchAttendanceSummary = useCallback(async () => {
|
try {
|
||||||
if (!id) return;
|
const params: Record<string, string> = {};
|
||||||
try {
|
if (attendanceDateRange?.[0])
|
||||||
const params: Record<string, string> = {};
|
params.startDate = attendanceDateRange[0].format('YYYY-MM-DD');
|
||||||
if (attendanceDateRange?.[0]) params.startDate = attendanceDateRange[0].format('YYYY-MM-DD');
|
if (attendanceDateRange?.[1]) params.endDate = attendanceDateRange[1].format('YYYY-MM-DD');
|
||||||
if (attendanceDateRange?.[1]) params.endDate = attendanceDateRange[1].format('YYYY-MM-DD');
|
return (
|
||||||
const res = await api.get<AttendanceSummary>(`/classes/${id}/attendance-summary`, { params });
|
(await api.get<AttendanceSummary>(`/classes/${id}/attendance-summary`, {
|
||||||
setAttendanceSummary(res || null);
|
params,
|
||||||
} catch (e: unknown) {
|
})) || null
|
||||||
const err = e as { message?: string };
|
);
|
||||||
message.error(err?.message || '加载出勤汇总失败');
|
} catch (e: unknown) {
|
||||||
}
|
message.error(getErrorMessage(e, '加载出勤汇总失败'));
|
||||||
}, [id, attendanceDateRange]);
|
return null;
|
||||||
|
}
|
||||||
useEffect(() => {
|
},
|
||||||
fetchAttendanceSummary();
|
});
|
||||||
}, [fetchAttendanceSummary]);
|
|
||||||
|
|
||||||
const handleSaveInfo = async () => {
|
const handleSaveInfo = async () => {
|
||||||
try {
|
try {
|
||||||
@@ -246,8 +140,7 @@ const ClassDetailPage: React.FC = () => {
|
|||||||
fetchDetail();
|
fetchDetail();
|
||||||
message.success('已更新');
|
message.success('已更新');
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const err = e as { message?: string };
|
message.error(getErrorMessage(e, '更新失败'));
|
||||||
message.error(err?.message || '更新失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -257,8 +150,7 @@ const ClassDetailPage: React.FC = () => {
|
|||||||
fetchDetail();
|
fetchDetail();
|
||||||
message.success('已移除');
|
message.success('已移除');
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const err = e as { message?: string };
|
message.error(getErrorMessage(e, '移除失败'));
|
||||||
message.error(err?.message || '移除失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -271,8 +163,7 @@ const ClassDetailPage: React.FC = () => {
|
|||||||
fetchDetail();
|
fetchDetail();
|
||||||
message.success('已添加');
|
message.success('已添加');
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const err = e as { message?: string };
|
message.error(getErrorMessage(e, '添加失败'));
|
||||||
message.error(err?.message || '添加失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -288,8 +179,7 @@ const ClassDetailPage: React.FC = () => {
|
|||||||
fetchDetail();
|
fetchDetail();
|
||||||
message.success('已添加');
|
message.success('已添加');
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const err = e as { message?: string };
|
message.error(getErrorMessage(e, '添加失败'));
|
||||||
message.error(err?.message || '添加失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -299,8 +189,7 @@ const ClassDetailPage: React.FC = () => {
|
|||||||
fetchDetail();
|
fetchDetail();
|
||||||
message.success('已移除');
|
message.success('已移除');
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const err = e as { message?: string };
|
message.error(getErrorMessage(e, '移除失败'));
|
||||||
message.error(err?.message || '移除失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -313,103 +202,27 @@ const ClassDetailPage: React.FC = () => {
|
|||||||
setSelectedStudentIds([]);
|
setSelectedStudentIds([]);
|
||||||
setStudentModalOpen(true);
|
setStudentModalOpen(true);
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const err = e as { message?: string };
|
message.error(getErrorMessage(e, '加载学员列表失败'));
|
||||||
message.error(err?.message || '加载学员列表失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const openTeacherModal = async () => {
|
const openTeacherModal = async () => {
|
||||||
try {
|
try {
|
||||||
const res = (await api.get('/rbac/users')) as UserItem[];
|
await fetchUsers();
|
||||||
setAllUsers(res || []);
|
|
||||||
setTeacherUserId(undefined);
|
setTeacherUserId(undefined);
|
||||||
setTeacherRole('subject_teacher');
|
setTeacherRole('subject_teacher');
|
||||||
setTeacherSubject('');
|
setTeacherSubject('');
|
||||||
setTeacherModalOpen(true);
|
setTeacherModalOpen(true);
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const err = e as { message?: string };
|
message.error(getErrorMessage(e, '加载用户列表失败'));
|
||||||
message.error(err?.message || '加载用户列表失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getTeacherName = (teacher: ClassTeacher) =>
|
||||||
|
allUsers.find((user) => user.id === teacher.userId)?.name?.trim() || '-';
|
||||||
|
|
||||||
if (!detail) return null;
|
if (!detail) return null;
|
||||||
|
|
||||||
const studentColumns: ColumnsType<ClassStudent> = [
|
|
||||||
{ title: '姓名', dataIndex: 'studentName' },
|
|
||||||
{ title: '学号', dataIndex: 'studentNo' },
|
|
||||||
{ title: '加入日期', dataIndex: 'joinDate' },
|
|
||||||
{ title: '离班日期', dataIndex: 'leaveDate', render: (v: string | null) => v || '-' },
|
|
||||||
{
|
|
||||||
title: '状态',
|
|
||||||
dataIndex: 'status',
|
|
||||||
render: (v: string) => (
|
|
||||||
<Tag color={v === 'active' ? 'green' : 'default'}>{v === 'active' ? '在读' : '已离班'}</Tag>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '操作',
|
|
||||||
render: (_: unknown, r: ClassStudent) =>
|
|
||||||
r.status === 'active' ? (
|
|
||||||
<Popconfirm title="确认移除?" onConfirm={() => handleRemoveStudent(r.studentId)}>
|
|
||||||
<PermissionButton permission="class:edit" size="small" danger>
|
|
||||||
移除
|
|
||||||
</PermissionButton>
|
|
||||||
</Popconfirm>
|
|
||||||
) : null,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
const teacherColumns: ColumnsType<ClassTeacher> = [
|
|
||||||
{ title: '姓名', dataIndex: 'username' },
|
|
||||||
{
|
|
||||||
title: '角色',
|
|
||||||
dataIndex: 'roleType',
|
|
||||||
render: (v: string) => <Tag>{ROLE_MAP[v] || v}</Tag>,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '科目',
|
|
||||||
dataIndex: 'subject',
|
|
||||||
render: (v: string | null) => v || '-',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '操作',
|
|
||||||
render: (_: unknown, r: ClassTeacher) => (
|
|
||||||
<Popconfirm title="确认移除?" onConfirm={() => handleRemoveTeacher(r.userId)}>
|
|
||||||
<PermissionButton permission="class:edit" size="small" danger>
|
|
||||||
移除
|
|
||||||
</PermissionButton>
|
|
||||||
</Popconfirm>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
const scheduleColumns: ColumnsType<ClassScheduleItem> = [
|
|
||||||
{ title: '教室', dataIndex: 'classroomName', render: (v: string | null) => v || '-' },
|
|
||||||
{ title: '星期', dataIndex: 'weekDay', render: (v: number) => WEEK_DAY_MAP[v] || v },
|
|
||||||
{
|
|
||||||
title: '时间',
|
|
||||||
render: (_: unknown, r: ClassScheduleItem) => `${r.startTime} - ${r.endTime}`,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '签到窗口',
|
|
||||||
render: (_: unknown, r: ClassScheduleItem) =>
|
|
||||||
`课前 ${r.attendanceAdvanceMinutes ?? 30} 分钟至下课`,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '日期范围',
|
|
||||||
render: (_: unknown, r: ClassScheduleItem) => `${r.startDate} ~ ${r.endDate}`,
|
|
||||||
},
|
|
||||||
{ title: '科目', dataIndex: 'subject' },
|
|
||||||
{ title: '类型', dataIndex: 'scheduleType', render: (v: string) => SCHEDULE_TYPE_MAP[v] || v },
|
|
||||||
{
|
|
||||||
title: '状态',
|
|
||||||
dataIndex: 'status',
|
|
||||||
render: (v: string) => (
|
|
||||||
<Tag color={v === 'active' ? 'green' : 'default'}>{v === 'active' ? '启用' : v}</Tag>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card
|
<Card
|
||||||
title={
|
title={
|
||||||
@@ -430,320 +243,91 @@ const ClassDetailPage: React.FC = () => {
|
|||||||
key: 'info',
|
key: 'info',
|
||||||
label: '基本信息',
|
label: '基本信息',
|
||||||
children: (
|
children: (
|
||||||
<div>
|
<ClassInfoTab
|
||||||
{editingInfo ? (
|
detail={detail}
|
||||||
<Form
|
teachers={teachers}
|
||||||
form={editForm}
|
editingInfo={editingInfo}
|
||||||
layout="vertical"
|
editForm={editForm}
|
||||||
initialValues={{
|
onSave={handleSaveInfo}
|
||||||
name: detail.name,
|
onEdit={() => {
|
||||||
code: detail.code,
|
editForm.setFieldsValue({
|
||||||
classType: detail.classType,
|
name: detail.name,
|
||||||
startDate: detail.startDate ? dayjs(detail.startDate) : undefined,
|
code: detail.code,
|
||||||
endDate: detail.endDate ? dayjs(detail.endDate) : undefined,
|
classType: detail.classType,
|
||||||
maxStudents: detail.maxStudents,
|
startDate: detail.startDate ? dayjs(detail.startDate) : undefined,
|
||||||
status: detail.status,
|
endDate: detail.endDate ? dayjs(detail.endDate) : undefined,
|
||||||
notes: detail.notes,
|
maxStudents: detail.maxStudents,
|
||||||
}}
|
status: detail.status,
|
||||||
>
|
notes: detail.notes,
|
||||||
<Space wrap>
|
});
|
||||||
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
|
setEditingInfo(true);
|
||||||
<Input />
|
}}
|
||||||
</Form.Item>
|
onCancel={() => setEditingInfo(false)}
|
||||||
<Form.Item name="code" label="编码">
|
getTeacherName={getTeacherName}
|
||||||
<Input />
|
/>
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="classType" label="班型">
|
|
||||||
<Select
|
|
||||||
options={Object.entries(TYPE_MAP).map(([k, v]) => ({
|
|
||||||
value: k,
|
|
||||||
label: v,
|
|
||||||
}))}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="startDate" label="开班">
|
|
||||||
<DatePicker />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="endDate" label="结课">
|
|
||||||
<DatePicker />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="maxStudents" label="人数上限">
|
|
||||||
<InputNumber min={1} />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="status" label="状态">
|
|
||||||
<Select
|
|
||||||
options={Object.entries(STATUS_MAP).map(([k, v]) => ({
|
|
||||||
value: k,
|
|
||||||
label: v.text,
|
|
||||||
}))}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
</Space>
|
|
||||||
<Form.Item name="notes" label="备注">
|
|
||||||
<Input.TextArea rows={3} />
|
|
||||||
</Form.Item>
|
|
||||||
<Space>
|
|
||||||
<PermissionButton
|
|
||||||
permission="class:edit"
|
|
||||||
type="primary"
|
|
||||||
onClick={handleSaveInfo}
|
|
||||||
>
|
|
||||||
保存
|
|
||||||
</PermissionButton>
|
|
||||||
<Button onClick={() => setEditingInfo(false)}>取消</Button>
|
|
||||||
</Space>
|
|
||||||
</Form>
|
|
||||||
) : (
|
|
||||||
<div>
|
|
||||||
<Descriptions column={3} bordered size="small">
|
|
||||||
<Descriptions.Item label="班型">
|
|
||||||
{TYPE_MAP[detail.classType]}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="开班日期">
|
|
||||||
{detail.startDate ? dayjs(detail.startDate).format('YYYY-MM-DD') : '-'}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="结课日期">
|
|
||||||
{detail.endDate ? dayjs(detail.endDate).format('YYYY-MM-DD') : '-'}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="学员">
|
|
||||||
{detail.studentCount}/{detail.maxStudents || '-'}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="班主任">
|
|
||||||
{teachers.find((t) => t.roleType === 'head_teacher')?.username || '-'}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="备注">{detail.notes || '-'}</Descriptions.Item>
|
|
||||||
</Descriptions>
|
|
||||||
<PermissionButton
|
|
||||||
permission="class:edit"
|
|
||||||
style={{ marginTop: 16 }}
|
|
||||||
onClick={() => {
|
|
||||||
editForm.setFieldsValue({
|
|
||||||
name: detail.name,
|
|
||||||
code: detail.code,
|
|
||||||
classType: detail.classType,
|
|
||||||
startDate: detail.startDate ? dayjs(detail.startDate) : undefined,
|
|
||||||
endDate: detail.endDate ? dayjs(detail.endDate) : undefined,
|
|
||||||
maxStudents: detail.maxStudents,
|
|
||||||
status: detail.status,
|
|
||||||
notes: detail.notes,
|
|
||||||
});
|
|
||||||
setEditingInfo(true);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
编辑
|
|
||||||
</PermissionButton>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'students',
|
key: 'students',
|
||||||
label: `花名册 (${students.filter((s) => s.status === 'active').length})`,
|
label: `花名册 (${students.filter((s) => s.status === 'active').length})`,
|
||||||
children: (
|
children: (
|
||||||
<div>
|
<ClassStudentsTab
|
||||||
<PermissionButton
|
id={id}
|
||||||
permission="class:edit"
|
detail={detail}
|
||||||
icon={<PlusOutlined />}
|
students={students}
|
||||||
type="primary"
|
allStudents={allStudents}
|
||||||
onClick={openStudentModal}
|
selectedStudentIds={selectedStudentIds}
|
||||||
style={{ marginBottom: 16, marginRight: 8 }}
|
modalOpen={studentModalOpen}
|
||||||
>
|
onOpen={openStudentModal}
|
||||||
添加学员
|
onAdd={handleAddStudents}
|
||||||
</PermissionButton>
|
onClose={() => setStudentModalOpen(false)}
|
||||||
<PermissionButton
|
onRemove={handleRemoveStudent}
|
||||||
permission="class:view"
|
onSelect={setSelectedStudentIds}
|
||||||
icon={<DownloadOutlined />}
|
/>
|
||||||
onClick={() => {
|
|
||||||
const token = localStorage.getItem('token');
|
|
||||||
fetch(`/api/classes/${id}/roster/export`, {
|
|
||||||
headers: { Authorization: `Bearer ${token}` },
|
|
||||||
})
|
|
||||||
.then((res) => {
|
|
||||||
if (!res.ok) throw new Error('导出失败');
|
|
||||||
return res.blob();
|
|
||||||
})
|
|
||||||
.then((blob) => {
|
|
||||||
const url = URL.createObjectURL(blob);
|
|
||||||
const a = document.createElement('a');
|
|
||||||
a.href = url;
|
|
||||||
a.download = `班级花名册-${detail?.name || id}.xlsx`;
|
|
||||||
a.click();
|
|
||||||
URL.revokeObjectURL(url);
|
|
||||||
message.success('花名册导出成功');
|
|
||||||
})
|
|
||||||
.catch(() => message.error('花名册导出失败'));
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
导出花名册
|
|
||||||
</PermissionButton>
|
|
||||||
<Table<ClassStudent>
|
|
||||||
columns={studentColumns}
|
|
||||||
dataSource={students}
|
|
||||||
rowKey="id"
|
|
||||||
pagination={{
|
|
||||||
defaultPageSize: 20,
|
|
||||||
showSizeChanger: true,
|
|
||||||
pageSizeOptions: [20, 50, 100],
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<Modal
|
|
||||||
title="添加学员"
|
|
||||||
open={studentModalOpen}
|
|
||||||
onOk={handleAddStudents}
|
|
||||||
onCancel={() => setStudentModalOpen(false)}
|
|
||||||
>
|
|
||||||
<Select
|
|
||||||
mode="multiple"
|
|
||||||
style={{ width: '100%' }}
|
|
||||||
placeholder="选择学员"
|
|
||||||
value={selectedStudentIds}
|
|
||||||
onChange={setSelectedStudentIds}
|
|
||||||
options={allStudents.map((s) => ({
|
|
||||||
value: s.id,
|
|
||||||
label: `${s.name} (${s.studentNo || s.id})`,
|
|
||||||
}))}
|
|
||||||
filterOption={(input, option) =>
|
|
||||||
(option?.label as string)?.toLowerCase().includes(input.toLowerCase())
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</Modal>
|
|
||||||
</div>
|
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'teachers',
|
key: 'teachers',
|
||||||
label: `教师 (${teachers.length})`,
|
label: `教师 (${teachers.length})`,
|
||||||
children: (
|
children: (
|
||||||
<div>
|
<ClassTeachersTab
|
||||||
<PermissionButton
|
teachers={teachers}
|
||||||
permission="class:edit"
|
allUsers={allUsers}
|
||||||
icon={<PlusOutlined />}
|
teacherRole={teacherRole}
|
||||||
type="primary"
|
teacherSubject={teacherSubject}
|
||||||
onClick={openTeacherModal}
|
teacherUserId={teacherUserId}
|
||||||
style={{ marginBottom: 16 }}
|
modalOpen={teacherModalOpen}
|
||||||
>
|
onOpen={openTeacherModal}
|
||||||
添加教师
|
onAdd={handleAddTeacher}
|
||||||
</PermissionButton>
|
onClose={() => setTeacherModalOpen(false)}
|
||||||
<Table<ClassTeacher>
|
onRemove={handleRemoveTeacher}
|
||||||
columns={teacherColumns}
|
onRoleChange={setTeacherRole}
|
||||||
dataSource={teachers}
|
onSubjectChange={setTeacherSubject}
|
||||||
rowKey="id"
|
onUserChange={setTeacherUserId}
|
||||||
pagination={{
|
getTeacherName={getTeacherName}
|
||||||
defaultPageSize: 20,
|
/>
|
||||||
showSizeChanger: true,
|
|
||||||
pageSizeOptions: [20, 50, 100],
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<Modal
|
|
||||||
title="添加教师"
|
|
||||||
open={teacherModalOpen}
|
|
||||||
onOk={handleAddTeacher}
|
|
||||||
onCancel={() => setTeacherModalOpen(false)}
|
|
||||||
>
|
|
||||||
<Space direction="vertical" style={{ width: '100%' }}>
|
|
||||||
<Select
|
|
||||||
style={{ width: '100%' }}
|
|
||||||
showSearch
|
|
||||||
optionFilterProp="label"
|
|
||||||
placeholder="搜索姓名、用户名、角色或学科"
|
|
||||||
value={teacherUserId}
|
|
||||||
onChange={setTeacherUserId}
|
|
||||||
options={buildTeacherCandidateOptions(allUsers)}
|
|
||||||
notFoundContent="没有可分配的工作人员账号"
|
|
||||||
/>
|
|
||||||
<Select
|
|
||||||
style={{ width: '100%' }}
|
|
||||||
value={teacherRole}
|
|
||||||
onChange={setTeacherRole}
|
|
||||||
options={Object.entries(ROLE_MAP).map(([k, v]) => ({
|
|
||||||
value: k,
|
|
||||||
label: v,
|
|
||||||
}))}
|
|
||||||
/>
|
|
||||||
{teacherRole === 'subject_teacher' && (
|
|
||||||
<Input
|
|
||||||
placeholder="任教科目"
|
|
||||||
value={teacherSubject}
|
|
||||||
onChange={(e) => setTeacherSubject(e.target.value)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</Space>
|
|
||||||
</Modal>
|
|
||||||
</div>
|
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'schedule',
|
key: 'schedule',
|
||||||
label: '课表',
|
label: '课表',
|
||||||
children: (
|
children: (
|
||||||
<div>
|
<ClassScheduleTab
|
||||||
<Space style={{ marginBottom: 16, maxWidth: '100%' }} wrap>
|
schedules={schedules}
|
||||||
<DatePicker.RangePicker
|
scheduleDateRange={scheduleDateRange}
|
||||||
value={scheduleDateRange}
|
onRangeChange={setScheduleDateRange}
|
||||||
onChange={(dates) =>
|
/>
|
||||||
setScheduleDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])
|
|
||||||
}
|
|
||||||
placeholder={['开始日期', '结束日期']}
|
|
||||||
/>
|
|
||||||
</Space>
|
|
||||||
<Table<ClassScheduleItem>
|
|
||||||
columns={scheduleColumns}
|
|
||||||
dataSource={schedules}
|
|
||||||
rowKey="id"
|
|
||||||
scroll={{ x: 'max-content' }}
|
|
||||||
pagination={{
|
|
||||||
defaultPageSize: 20,
|
|
||||||
showSizeChanger: true,
|
|
||||||
pageSizeOptions: [20, 50, 100],
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'attendance-summary',
|
key: 'attendance-summary',
|
||||||
label: '出勤汇总',
|
label: '出勤汇总',
|
||||||
children: (
|
children: (
|
||||||
<div>
|
<ClassAttendanceTab
|
||||||
<Space style={{ marginBottom: 16, maxWidth: '100%' }} wrap>
|
attendanceSummary={attendanceSummary}
|
||||||
<DatePicker.RangePicker
|
attendanceDateRange={attendanceDateRange}
|
||||||
value={attendanceDateRange}
|
onRangeChange={setAttendanceDateRange}
|
||||||
onChange={(dates) =>
|
/>
|
||||||
setAttendanceDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])
|
|
||||||
}
|
|
||||||
placeholder={['开始日期', '结束日期']}
|
|
||||||
/>
|
|
||||||
</Space>
|
|
||||||
{attendanceSummary && (
|
|
||||||
<Row gutter={[16, 16]}>
|
|
||||||
<Col xs={12} md={6}>
|
|
||||||
<Card bordered={false}>
|
|
||||||
<Statistic title="总记录" value={attendanceSummary.total} />
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
<Col xs={12} md={6}>
|
|
||||||
<Card bordered={false}>
|
|
||||||
<Statistic
|
|
||||||
title="出勤率"
|
|
||||||
value={attendanceSummary.presentRate}
|
|
||||||
suffix="%"
|
|
||||||
/>
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
<Col xs={12} md={6}>
|
|
||||||
<Card bordered={false}>
|
|
||||||
<Statistic title="缺勤率" value={attendanceSummary.absentRate} suffix="%" />
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
<Col xs={12} md={6}>
|
|
||||||
<Card bordered={false}>
|
|
||||||
<Statistic title="迟到率" value={attendanceSummary.lateRate} suffix="%" />
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
</Row>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
import React, { useEffect, useState, useMemo, useCallback } from 'react';
|
// aislop-ignore-file: duplicate-block -- 表格/表单声明结构相似且参数不同,渲染逻辑已共享组件化
|
||||||
|
import React, { useState, useMemo, useCallback } from 'react';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||||
|
import { validateResponse } from '../../utils/validate';
|
||||||
|
import { classesSchema } from '../../api/schemas';
|
||||||
import {
|
import {
|
||||||
|
App,
|
||||||
Table,
|
Table,
|
||||||
Button,
|
Button,
|
||||||
Input,
|
Input,
|
||||||
@@ -17,14 +23,13 @@ import {
|
|||||||
} from 'antd';
|
} from 'antd';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import { PlusOutlined, SearchOutlined, TeamOutlined, InboxOutlined } from '@ant-design/icons';
|
import { PlusOutlined, SearchOutlined, TeamOutlined, InboxOutlined } from '@ant-design/icons';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import api from '../../api';
|
import api from '../../api';
|
||||||
import PermissionButton from '../../components/PermissionButton';
|
import PermissionButton from '../../components/PermissionButton';
|
||||||
import EditableCell from '../../components/EditableCell';
|
import EditableCell from '../../components/EditableCell';
|
||||||
import { message } from '../../ui/app-message';
|
import { message } from '../../ui/app-message';
|
||||||
|
import { usePermission } from '../../hooks/usePermission';
|
||||||
// ---- Types ----
|
|
||||||
|
|
||||||
interface ClassItem {
|
interface ClassItem {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -56,8 +61,6 @@ interface ClassFormValues {
|
|||||||
notes?: string;
|
notes?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- Constants ----
|
|
||||||
|
|
||||||
const STATUS_MAP: Record<string, { color: string; text: string }> = {
|
const STATUS_MAP: Record<string, { color: string; text: string }> = {
|
||||||
enrolling: { color: 'blue', text: '招生中' },
|
enrolling: { color: 'blue', text: '招生中' },
|
||||||
active: { color: 'green', text: '在读' },
|
active: { color: 'green', text: '在读' },
|
||||||
@@ -72,12 +75,11 @@ const TYPE_MAP: Record<string, string> = {
|
|||||||
sprint: '冲刺营',
|
sprint: '冲刺营',
|
||||||
};
|
};
|
||||||
|
|
||||||
// ---- Component ----
|
|
||||||
|
|
||||||
const ClassesPage: React.FC = () => {
|
const ClassesPage: React.FC = () => {
|
||||||
|
const { modal } = App.useApp();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [data, setData] = useState<ClassItem[]>([]);
|
const { hasPermission } = usePermission();
|
||||||
const [loading, setLoading] = useState(false);
|
const canPurgeClass = hasPermission('class:purge');
|
||||||
const [modalOpen, setModalOpen] = useState(false);
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
const [editing, setEditing] = useState<ClassItem | null>(null);
|
const [editing, setEditing] = useState<ClassItem | null>(null);
|
||||||
const [searchText, setSearchText] = useState('');
|
const [searchText, setSearchText] = useState('');
|
||||||
@@ -87,36 +89,82 @@ const ClassesPage: React.FC = () => {
|
|||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [showArchived, setShowArchived] = useState(false);
|
const [showArchived, setShowArchived] = useState(false);
|
||||||
|
|
||||||
const handleArchive = async (id: number, archive: boolean) => {
|
const {
|
||||||
try {
|
data = [],
|
||||||
await api.put(`/classes/${id}/${archive ? 'archive' : 'restore'}`);
|
isLoading,
|
||||||
message.success(archive ? '已归档' : '已恢复');
|
isFetching,
|
||||||
fetchData();
|
} = useQuery<ClassItem[]>({
|
||||||
} catch (e: unknown) {
|
queryKey: ['classes', filterStatus, filterType, showArchived],
|
||||||
const err = e as { message?: string };
|
queryFn: async () => {
|
||||||
message.error(err?.message || '操作失败');
|
try {
|
||||||
}
|
const params: Record<string, string | boolean | undefined> = {};
|
||||||
};
|
if (filterStatus) params.status = filterStatus;
|
||||||
|
if (filterType) params.classType = filterType;
|
||||||
|
params.isArchived = showArchived;
|
||||||
|
return validateResponse<ClassItem[]>(
|
||||||
|
classesSchema,
|
||||||
|
await api.get<ClassItem[]>('/classes', { params } as Record<string, unknown>),
|
||||||
|
);
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '加载失败,请稍后重试');
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const loading = isLoading || isFetching;
|
||||||
|
|
||||||
const fetchData = useCallback(async () => {
|
const saveMutation = useApiMutation(
|
||||||
setLoading(true);
|
async (payload: Record<string, unknown>) =>
|
||||||
try {
|
editing ? api.put(`/classes/${editing.id}`, payload) : api.post('/classes', payload),
|
||||||
const params: Record<string, string | boolean | undefined> = {};
|
{ invalidate: [['classes']] },
|
||||||
if (filterStatus) params.status = filterStatus;
|
);
|
||||||
if (filterType) params.classType = filterType;
|
const saveCellMutation = useApiMutation(
|
||||||
params.isArchived = showArchived;
|
async ({ record, field, value }: { record: ClassItem; field: string; value: unknown }) =>
|
||||||
const res = await api.get<ClassItem[]>('/classes', { params } as Record<string, unknown>);
|
api.put(`/classes/${record.id}`, { [field]: value }),
|
||||||
setData(res);
|
{ invalidate: [['classes']] },
|
||||||
} catch (e: any) {
|
);
|
||||||
message.error(e?.message || '加载失败,请稍后重试');
|
const archiveMutation = useApiMutation(
|
||||||
} finally {
|
async ({ id, archive }: { id: number; archive: boolean }) =>
|
||||||
setLoading(false);
|
api.put(`/classes/${id}/${archive ? 'archive' : 'restore'}`),
|
||||||
}
|
{ invalidate: [['classes']] },
|
||||||
}, [filterStatus, filterType, showArchived]);
|
);
|
||||||
|
const purgeMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/classes/${id}/permanent`),
|
||||||
|
{ invalidate: [['classes']] },
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
const handleArchive = useCallback(
|
||||||
fetchData();
|
async (id: number, archive: boolean) => {
|
||||||
}, [fetchData]);
|
try {
|
||||||
|
await archiveMutation.mutateAsync({ id, archive });
|
||||||
|
message.success(archive ? '已归档' : '已恢复');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[archiveMutation],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handlePurge = useCallback(
|
||||||
|
(record: ClassItem) => {
|
||||||
|
modal.confirm({
|
||||||
|
title: `永久删除班级「${record.name}」?`,
|
||||||
|
content: '删除后不可恢复,存在学生、教师、排课、考试或考勤关联时将无法删除。确定继续?',
|
||||||
|
okText: '永久删除',
|
||||||
|
okButtonProps: { danger: true },
|
||||||
|
cancelText: '取消',
|
||||||
|
onOk: async () => {
|
||||||
|
try {
|
||||||
|
await purgeMutation.mutateAsync(record.id);
|
||||||
|
message.success('已永久删除(不可恢复)');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[modal, purgeMutation],
|
||||||
|
);
|
||||||
|
|
||||||
const filtered = useMemo(() => {
|
const filtered = useMemo(() => {
|
||||||
if (!searchText) return data;
|
if (!searchText) return data;
|
||||||
@@ -132,16 +180,19 @@ const ClassesPage: React.FC = () => {
|
|||||||
setModalOpen(true);
|
setModalOpen(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleEdit = (record: ClassItem) => {
|
const handleEdit = useCallback(
|
||||||
setEditing(record);
|
(record: ClassItem) => {
|
||||||
form.setFieldsValue({
|
setEditing(record);
|
||||||
...record,
|
form.setFieldsValue({
|
||||||
notes: record.notes ?? undefined,
|
...record,
|
||||||
startDate: record.startDate ? dayjs(record.startDate) : undefined,
|
notes: record.notes ?? undefined,
|
||||||
endDate: record.endDate ? dayjs(record.endDate) : undefined,
|
startDate: record.startDate ? dayjs(record.startDate) : undefined,
|
||||||
});
|
endDate: record.endDate ? dayjs(record.endDate) : undefined,
|
||||||
setModalOpen(true);
|
});
|
||||||
};
|
setModalOpen(true);
|
||||||
|
},
|
||||||
|
[form],
|
||||||
|
);
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
setSaving(true);
|
setSaving(true);
|
||||||
@@ -152,17 +203,11 @@ const ClassesPage: React.FC = () => {
|
|||||||
startDate: values.startDate?.format('YYYY-MM-DD'),
|
startDate: values.startDate?.format('YYYY-MM-DD'),
|
||||||
endDate: values.endDate?.format('YYYY-MM-DD'),
|
endDate: values.endDate?.format('YYYY-MM-DD'),
|
||||||
};
|
};
|
||||||
if (editing) {
|
await saveMutation.mutateAsync(payload);
|
||||||
await api.put(`/classes/${editing.id}`, payload);
|
message.success(editing ? '更新成功' : '创建成功');
|
||||||
message.success('更新成功');
|
|
||||||
} else {
|
|
||||||
await api.post('/classes', payload);
|
|
||||||
message.success('创建成功');
|
|
||||||
}
|
|
||||||
setModalOpen(false);
|
setModalOpen(false);
|
||||||
fetchData();
|
} catch {
|
||||||
} catch (e: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error(e?.message || '操作失败');
|
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false);
|
setSaving(false);
|
||||||
}
|
}
|
||||||
@@ -170,11 +215,14 @@ const ClassesPage: React.FC = () => {
|
|||||||
|
|
||||||
const saveCell = useCallback(
|
const saveCell = useCallback(
|
||||||
async (record: ClassItem, field: string, value: unknown) => {
|
async (record: ClassItem, field: string, value: unknown) => {
|
||||||
await api.put(`/classes/${record.id}`, { [field]: value });
|
try {
|
||||||
message.success('已保存');
|
await saveCellMutation.mutateAsync({ record, field, value });
|
||||||
await fetchData();
|
message.success('已保存');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
},
|
},
|
||||||
[fetchData],
|
[saveCellMutation],
|
||||||
);
|
);
|
||||||
|
|
||||||
const columns: ColumnsType<ClassItem> = useMemo(
|
const columns: ColumnsType<ClassItem> = useMemo(
|
||||||
@@ -196,6 +244,7 @@ const ClassesPage: React.FC = () => {
|
|||||||
</EditableCell>
|
</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '编码',
|
title: '编码',
|
||||||
dataIndex: 'code',
|
dataIndex: 'code',
|
||||||
@@ -212,6 +261,7 @@ const ClassesPage: React.FC = () => {
|
|||||||
</EditableCell>
|
</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '班型',
|
title: '班型',
|
||||||
dataIndex: 'classType',
|
dataIndex: 'classType',
|
||||||
@@ -229,6 +279,7 @@ const ClassesPage: React.FC = () => {
|
|||||||
</EditableCell>
|
</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '开班日期',
|
title: '开班日期',
|
||||||
dataIndex: 'startDate',
|
dataIndex: 'startDate',
|
||||||
@@ -245,6 +296,7 @@ const ClassesPage: React.FC = () => {
|
|||||||
</EditableCell>
|
</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '学员',
|
title: '学员',
|
||||||
width: 100,
|
width: 100,
|
||||||
@@ -259,6 +311,7 @@ const ClassesPage: React.FC = () => {
|
|||||||
>{`${r.studentCount || 0}/${r.maxStudents || '-'}`}</EditableCell>
|
>{`${r.studentCount || 0}/${r.maxStudents || '-'}`}</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '状态',
|
title: '状态',
|
||||||
dataIndex: 'status',
|
dataIndex: 'status',
|
||||||
@@ -282,6 +335,7 @@ const ClassesPage: React.FC = () => {
|
|||||||
</EditableCell>
|
</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '操作',
|
title: '操作',
|
||||||
width: 280,
|
width: 280,
|
||||||
@@ -298,11 +352,18 @@ const ClassesPage: React.FC = () => {
|
|||||||
编辑
|
编辑
|
||||||
</PermissionButton>
|
</PermissionButton>
|
||||||
{r.isArchived ? (
|
{r.isArchived ? (
|
||||||
<Popconfirm title="确认恢复?" onConfirm={() => handleArchive(r.id, false)}>
|
<>
|
||||||
<PermissionButton permission="class:edit" size="small">
|
<Popconfirm title="确认恢复?" onConfirm={() => handleArchive(r.id, false)}>
|
||||||
恢复
|
<PermissionButton permission="class:edit" size="small">
|
||||||
</PermissionButton>
|
恢复
|
||||||
</Popconfirm>
|
</PermissionButton>
|
||||||
|
</Popconfirm>
|
||||||
|
{canPurgeClass ? (
|
||||||
|
<Button size="small" danger type="link" onClick={() => handlePurge(r)}>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
) : (
|
) : (
|
||||||
<Popconfirm
|
<Popconfirm
|
||||||
title="归档后可恢复,确认归档?"
|
title="归档后可恢复,确认归档?"
|
||||||
@@ -317,7 +378,7 @@ const ClassesPage: React.FC = () => {
|
|||||||
),
|
),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
[saveCell],
|
[saveCell, canPurgeClass, handlePurge, navigate, handleEdit, handleArchive],
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user