考勤请假同步、SSE 修复与学生报告优化 #59
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;
|
||||||
|
|||||||
@@ -21,28 +21,37 @@
|
|||||||
"@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",
|
||||||
"lucide-react": "^0.468.0",
|
"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",
|
"use-immer": "^0.11.0",
|
||||||
|
"usehooks-ts": "^3.1.1",
|
||||||
|
"zod": "^4.4.3",
|
||||||
"zustand": "^5.0.14"
|
"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,7 +1,7 @@
|
|||||||
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';
|
import XProvider from '@ant-design/x/es/x-provider';
|
||||||
import xZhCN from '@ant-design/x/es/locale/zh_CN';
|
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';
|
||||||
|
|||||||
79
apps/admin/src/api/imports.ts
Normal file
79
apps/admin/src/api/imports.ts
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
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, {
|
||||||
|
headers: { 'Content-Type': 'multipart/form-data' },
|
||||||
|
});
|
||||||
|
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}` : ''}`;
|
||||||
|
}
|
||||||
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);
|
||||||
330
apps/admin/src/api/schemas/core.ts
Normal file
330
apps/admin/src/api/schemas/core.ts
Normal file
@@ -0,0 +1,330 @@
|
|||||||
|
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().optional(),
|
||||||
|
status: z.string().optional(),
|
||||||
|
})
|
||||||
|
.passthrough();
|
||||||
|
|
||||||
|
export const classroomsSchema = z.array(classroomSchema);
|
||||||
|
|
||||||
|
/** 学生 */
|
||||||
|
export const studentSchema = z
|
||||||
|
.object({
|
||||||
|
id: z.number(),
|
||||||
|
name: z.string(),
|
||||||
|
studentNo: z.string().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({ studentId: z.number(), name: z.string().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 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();
|
||||||
|
|
||||||
|
/** 集成配置 */
|
||||||
79
apps/admin/src/api/schemas/dashboard.ts
Normal file
79
apps/admin/src/api/schemas/dashboard.ts
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
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: z.record(z.string(), z.record(z.string(), z.array(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.record(z.string(), z.unknown())) })
|
||||||
|
.passthrough(),
|
||||||
|
);
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
/** 考勤元数据 */
|
||||||
58
apps/admin/src/api/schemas/import-run.ts
Normal file
58
apps/admin/src/api/schemas/import-run.ts
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
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 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),
|
||||||
|
})
|
||||||
|
.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(),
|
||||||
|
);
|
||||||
|
|
||||||
|
/** 教室排课总览 */
|
||||||
@@ -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(
|
||||||
|
|||||||
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>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,152 +1,71 @@
|
|||||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
CheckSquareOutlined,
|
|
||||||
DeleteOutlined,
|
DeleteOutlined,
|
||||||
EditOutlined,
|
EditOutlined,
|
||||||
ArrowRightOutlined,
|
ArrowRightOutlined,
|
||||||
LoadingOutlined,
|
LoadingOutlined,
|
||||||
MenuFoldOutlined,
|
|
||||||
MenuUnfoldOutlined,
|
|
||||||
PaperClipOutlined,
|
|
||||||
PlusOutlined,
|
|
||||||
RobotOutlined,
|
RobotOutlined,
|
||||||
} from '@ant-design/icons';
|
} 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 {
|
import {
|
||||||
Attachments,
|
App,
|
||||||
Bubble,
|
|
||||||
Conversations,
|
|
||||||
Prompts,
|
|
||||||
Sender,
|
|
||||||
SenderSwitch,
|
|
||||||
Welcome,
|
|
||||||
} from '@ant-design/x';
|
|
||||||
import type {
|
|
||||||
BubbleItemType,
|
|
||||||
BubbleListProps,
|
|
||||||
ConversationItemType,
|
|
||||||
PromptsItemType,
|
|
||||||
} from '@ant-design/x';
|
|
||||||
import type { Attachment } from '@ant-design/x/es/attachments';
|
|
||||||
import { useXChat, useXConversations, type MessageInfo } from '@ant-design/x-sdk';
|
|
||||||
import {
|
|
||||||
Button,
|
|
||||||
Checkbox,
|
Checkbox,
|
||||||
Drawer,
|
Drawer,
|
||||||
Dropdown,
|
|
||||||
Grid,
|
Grid,
|
||||||
Input,
|
Input,
|
||||||
Modal,
|
|
||||||
Spin,
|
|
||||||
Tooltip,
|
|
||||||
Typography,
|
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import type { MenuProps, UploadFile, UploadProps } from 'antd';
|
import type { MenuProps } from 'antd';
|
||||||
import { message } from '../../ui/app-message';
|
import { message } from '../../ui/app-message';
|
||||||
import { useSettingsStore } from '../../store/settings/settingsStore';
|
|
||||||
import { aiChatApi, conversationStreamUrl } from './api';
|
import { aiChatApi, conversationStreamUrl } from './api';
|
||||||
import { AiMessageContent } from './AiMessageContent';
|
|
||||||
import { mapHistoryMessage } from './message-mappers';
|
|
||||||
import { GongxueAiChatProvider } from './provider';
|
import { GongxueAiChatProvider } from './provider';
|
||||||
import type {
|
import { ImportWizardModal } from '../ImportWizard/ImportWizardModal';
|
||||||
AiAttachment,
|
import type { AiSkill } from './types';
|
||||||
AiChatInput,
|
import { useAiChatMessageActions } from './useAiChatMessageActions';
|
||||||
AiChatMessage,
|
import { AiChatComposer, AiChatSidebar } from './AiChatDrawer.parts';
|
||||||
AiChatMessageStatus,
|
import {
|
||||||
AiConversation,
|
aiBubbleRoles,
|
||||||
AiFormSchema,
|
conversationStatusMeta,
|
||||||
AiReviewSchema,
|
sortConversations,
|
||||||
AiReviewSection,
|
toConversationData,
|
||||||
AiReviewSectionType,
|
type ConversationData,
|
||||||
AiSkill,
|
type ConversationRunStatus,
|
||||||
AiSseChunk,
|
} from './AiChatDrawer.helpers';
|
||||||
} from './types';
|
|
||||||
import './style.css';
|
import './style.css';
|
||||||
|
|
||||||
|
export {
|
||||||
|
aiBubbleRoles,
|
||||||
|
conversationStatusMeta,
|
||||||
|
type ConversationData,
|
||||||
|
type ConversationRunStatus,
|
||||||
|
} from './AiChatDrawer.helpers';
|
||||||
|
|
||||||
interface AiChatDrawerProps {
|
interface AiChatDrawerProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onRequestingChange?: (working: boolean) => void;
|
onRequestingChange?: (working: boolean) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
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' };
|
|
||||||
}
|
|
||||||
|
|
||||||
function sortConversations(items: AiConversation[]): AiConversation[] {
|
|
||||||
return [...items].sort((a, b) => {
|
|
||||||
const aTime = new Date(a.lastMessageAt || a.updatedAt).getTime();
|
|
||||||
const bTime = new Date(b.lastMessageAt || b.updatedAt).getTime();
|
|
||||||
return bTime - aTime;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function toConversationData(item: AiConversation): ConversationData {
|
|
||||||
return { ...item, key: String(item.id), label: item.title };
|
|
||||||
}
|
|
||||||
|
|
||||||
function toUploadFile(attachment: AiAttachment): Attachment<AiAttachment> {
|
|
||||||
return {
|
|
||||||
uid: String(attachment.id),
|
|
||||||
name: attachment.name,
|
|
||||||
size: attachment.size,
|
|
||||||
status: attachment.status === 'ready' ? 'done' : attachment.status === 'failed' ? 'error' : 'uploading',
|
|
||||||
url: attachment.url,
|
|
||||||
response: attachment,
|
|
||||||
description: attachment.error || undefined,
|
|
||||||
cardType: attachment.mimeType.startsWith('image/') ? 'image' : 'file',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function emptyAssistant(): AiChatMessage {
|
|
||||||
return {
|
|
||||||
role: 'assistant',
|
|
||||||
content: '',
|
|
||||||
reasoningContent: '',
|
|
||||||
toolRuns: [],
|
|
||||||
attachments: [],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export const aiBubbleRoles: BubbleListProps['role'] = {
|
|
||||||
user: { placement: 'end', variant: 'filled', shape: 'corner' },
|
|
||||||
assistant: { placement: 'start', variant: 'borderless' },
|
|
||||||
};
|
|
||||||
|
|
||||||
const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequestingChange }) => {
|
const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequestingChange }) => {
|
||||||
|
const { modal } = App.useApp();
|
||||||
const screens = Grid.useBreakpoint();
|
const screens = Grid.useBreakpoint();
|
||||||
const isMobile = !screens.sm;
|
const isMobile = !screens.sm;
|
||||||
const [loadingList, setLoadingList] = useState(false);
|
const [loadingList, setLoadingList] = useState(false);
|
||||||
const [sidebarOpen, setSidebarOpen] = useState(!isMobile);
|
const [sidebarOpen, setSidebarOpen] = useState(!isMobile);
|
||||||
const [input, setInput] = useState('');
|
const effectiveSidebarOpen = isMobile ? false : sidebarOpen;
|
||||||
const [skills, setSkills] = useState<AiSkill[]>([]);
|
const [skills, setSkills] = useState<AiSkill[]>([]);
|
||||||
const [attachments, setAttachments] = useState<AiAttachment[]>([]);
|
|
||||||
const deepThinking = useSettingsStore((state) => state.aiChat.deepThinking);
|
|
||||||
const setDeepThinking = useSettingsStore((state) => state.setAiChatDeepThinking);
|
|
||||||
const [conversationStatus, setConversationStatus] = useState<
|
const [conversationStatus, setConversationStatus] = useState<
|
||||||
Record<number, ConversationRunStatus>
|
Record<number, ConversationRunStatus>
|
||||||
>({});
|
>({});
|
||||||
|
const [importWizardRunId, setImportWizardRunId] = useState<string | null>(null);
|
||||||
const [selectionMode, setSelectionMode] = useState(false);
|
const [selectionMode, setSelectionMode] = useState(false);
|
||||||
const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
|
const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
|
||||||
const requestingRef = useRef(false);
|
|
||||||
const abortRef = useRef<() => void>(() => undefined);
|
|
||||||
const attachmentsRef = useRef<AiAttachment[]>([]);
|
|
||||||
const requestAbortRef = useRef(new Map<number, () => void>());
|
const requestAbortRef = useRef(new Map<number, () => void>());
|
||||||
const providersRef = useRef(new Map<number, GongxueAiChatProvider>());
|
const providersRef = useRef(new Map<number, GongxueAiChatProvider>());
|
||||||
const loadedRef = useRef(false);
|
const loadedRef = useRef(false);
|
||||||
const pendingDraftConversationIdRef = useRef<number | null>(null);
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
conversations,
|
conversations,
|
||||||
@@ -160,15 +79,16 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
const activeConversationKeyRef = useRef(activeConversationKey);
|
const activeConversationKeyRef = useRef(activeConversationKey);
|
||||||
|
|
||||||
const activeConversation = useMemo(
|
const activeConversation = useMemo(
|
||||||
() => conversations.find((item) => item.key === activeConversationKey) as ConversationData | undefined,
|
() =>
|
||||||
|
conversations.find((item) => item.key === activeConversationKey) as
|
||||||
|
| ConversationData
|
||||||
|
| undefined,
|
||||||
[activeConversationKey, conversations],
|
[activeConversationKey, conversations],
|
||||||
);
|
);
|
||||||
const activeId = activeConversation?.id ?? null;
|
const activeId = activeConversation?.id ?? null;
|
||||||
const lockedSkill = skills.find((skill) => skill.key === activeConversation?.lockedSkillKey);
|
const lockedSkill = skills.find((skill) => skill.key === activeConversation?.lockedSkillKey);
|
||||||
activeConversationKeyRef.current = activeConversationKey;
|
activeConversationKeyRef.current = activeConversationKey;
|
||||||
|
|
||||||
useEffect(() => setSidebarOpen(!isMobile), [isMobile]);
|
|
||||||
|
|
||||||
const refreshConversations = useCallback(async () => {
|
const refreshConversations = useCallback(async () => {
|
||||||
const items = sortConversations(await aiChatApi.listConversations()).map(toConversationData);
|
const items = sortConversations(await aiChatApi.listConversations()).map(toConversationData);
|
||||||
setConversations(items);
|
setConversations(items);
|
||||||
@@ -193,115 +113,53 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
|
|
||||||
const provider = useMemo(
|
const provider = useMemo(() => {
|
||||||
() => {
|
if (!activeId) return undefined;
|
||||||
if (!activeId) return undefined;
|
const existing = providersRef.current.get(activeId);
|
||||||
const existing = providersRef.current.get(activeId);
|
if (existing) return existing;
|
||||||
if (existing) return existing;
|
const created = new GongxueAiChatProvider(conversationStreamUrl(activeId), (result) => {
|
||||||
const created = new GongxueAiChatProvider(conversationStreamUrl(activeId), (result) => {
|
void refreshConversations();
|
||||||
void refreshConversations();
|
markConversationFinished(activeId, result);
|
||||||
markConversationFinished(activeId, result);
|
});
|
||||||
});
|
providersRef.current.set(activeId, created);
|
||||||
providersRef.current.set(activeId, created);
|
return created;
|
||||||
return created;
|
}, [activeId, markConversationFinished, refreshConversations]);
|
||||||
},
|
|
||||||
[activeId, markConversationFinished, refreshConversations],
|
|
||||||
);
|
|
||||||
|
|
||||||
const { messages, onRequest, onReload, isRequesting, abort, setMessage, queueRequest } = useXChat<
|
const {
|
||||||
AiChatMessage,
|
input,
|
||||||
AiChatMessage,
|
setInput,
|
||||||
AiChatInput,
|
deepThinking,
|
||||||
AiSseChunk
|
setDeepThinking,
|
||||||
>({
|
isRequesting,
|
||||||
|
messages,
|
||||||
|
stopRequest,
|
||||||
|
submit,
|
||||||
|
customUpload,
|
||||||
|
removeAttachment,
|
||||||
|
discardPendingAttachments,
|
||||||
|
uploadItems,
|
||||||
|
promptItems,
|
||||||
|
bubbleItems,
|
||||||
|
} = useAiChatMessageActions({
|
||||||
|
activeConversation,
|
||||||
|
activeId,
|
||||||
provider,
|
provider,
|
||||||
conversationKey: activeConversationKey || 'no-conversation',
|
requestAbortRef,
|
||||||
defaultMessages: async () => {
|
markConversationRunning,
|
||||||
if (!activeId) return [];
|
addConversation,
|
||||||
const page = await aiChatApi.listMessages(activeId);
|
setActiveConversationKey,
|
||||||
return page.items.map(mapHistoryMessage);
|
refreshConversations,
|
||||||
},
|
skills,
|
||||||
requestPlaceholder: emptyAssistant(),
|
lockedSkill,
|
||||||
requestFallback: (
|
setImportWizardRunId,
|
||||||
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(() => {
|
// isRequesting 由 @ant-design/x-sdk 的 useXChat 内部维护且没有完成回调,
|
||||||
if (!provider) return;
|
// 这里把它视为外部 SDK 状态做订阅转发,是 Effect 的合理用法。
|
||||||
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, setMessage]);
|
|
||||||
|
|
||||||
requestingRef.current = isRequesting;
|
|
||||||
abortRef.current = abort;
|
|
||||||
attachmentsRef.current = attachments;
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
onRequestingChange?.(isRequesting);
|
onRequestingChange?.(isRequesting);
|
||||||
}, [isRequesting, onRequestingChange]);
|
}, [isRequesting, onRequestingChange]);
|
||||||
|
|
||||||
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],
|
|
||||||
);
|
|
||||||
|
|
||||||
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,
|
|
||||||
],
|
|
||||||
);
|
|
||||||
|
|
||||||
const discardPendingAttachments = useCallback(() => {
|
|
||||||
const pending = attachmentsRef.current;
|
|
||||||
attachmentsRef.current = [];
|
|
||||||
setAttachments([]);
|
|
||||||
for (const attachment of pending) {
|
|
||||||
void aiChatApi.deleteAttachment(attachment.id).catch(() => undefined);
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open || loadedRef.current) return;
|
if (!open || loadedRef.current) return;
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
@@ -322,10 +180,14 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
};
|
};
|
||||||
}, [open, setActiveConversationKey, setConversations]);
|
}, [open, setActiveConversationKey, setConversations]);
|
||||||
|
|
||||||
useEffect(() => {
|
const switchConversation = useCallback(
|
||||||
discardPendingAttachments();
|
(key: string) => {
|
||||||
if (isMobile) setSidebarOpen(false);
|
discardPendingAttachments();
|
||||||
}, [activeConversationKey, discardPendingAttachments, isMobile]);
|
if (isMobile) setSidebarOpen(false);
|
||||||
|
setActiveConversationKey(key);
|
||||||
|
},
|
||||||
|
[discardPendingAttachments, isMobile, setActiveConversationKey],
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(
|
useEffect(
|
||||||
() => () => {
|
() => () => {
|
||||||
@@ -338,17 +200,22 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
|
|
||||||
/** 新建对话(Codex 风格):先进入草稿态,发送第一条消息时才创建 session */
|
/** 新建对话(Codex 风格):先进入草稿态,发送第一条消息时才创建 session */
|
||||||
const startNewConversation = useCallback(() => {
|
const startNewConversation = useCallback(() => {
|
||||||
setActiveConversationKey('');
|
switchConversation('');
|
||||||
if (isMobile) setSidebarOpen(false);
|
}, [switchConversation]);
|
||||||
}, [isMobile, setActiveConversationKey]);
|
|
||||||
|
|
||||||
const renameConversation = useCallback(
|
const renameConversation = useCallback(
|
||||||
(conversation: ConversationData) => {
|
(conversation: ConversationData) => {
|
||||||
let title = conversation.title;
|
let title = conversation.title;
|
||||||
Modal.confirm({
|
modal.confirm({
|
||||||
title: '重命名会话',
|
title: '重命名会话',
|
||||||
icon: <EditOutlined />,
|
icon: <EditOutlined />,
|
||||||
content: <Input defaultValue={title} maxLength={100} onChange={(event) => (title = event.target.value)} />,
|
content: (
|
||||||
|
<Input
|
||||||
|
defaultValue={title}
|
||||||
|
maxLength={100}
|
||||||
|
onChange={(event) => (title = event.target.value)}
|
||||||
|
/>
|
||||||
|
),
|
||||||
okText: '保存',
|
okText: '保存',
|
||||||
cancelText: '取消',
|
cancelText: '取消',
|
||||||
onOk: async () => {
|
onOk: async () => {
|
||||||
@@ -383,7 +250,7 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
|
|
||||||
const deleteConversation = useCallback(
|
const deleteConversation = useCallback(
|
||||||
(conversation: ConversationData) => {
|
(conversation: ConversationData) => {
|
||||||
Modal.confirm({
|
modal.confirm({
|
||||||
title: '删除会话',
|
title: '删除会话',
|
||||||
content: '该会话及全部历史消息将被永久删除。',
|
content: '该会话及全部历史消息将被永久删除。',
|
||||||
okText: '删除',
|
okText: '删除',
|
||||||
@@ -395,9 +262,9 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
removeConversation(conversation.key);
|
removeConversation(conversation.key);
|
||||||
const remaining = conversations.filter((item) => item.key !== conversation.key);
|
const remaining = conversations.filter((item) => item.key !== conversation.key);
|
||||||
if (!remaining.length) {
|
if (!remaining.length) {
|
||||||
setActiveConversationKey('');
|
switchConversation('');
|
||||||
} else if (conversation.id === activeId) {
|
} else if (conversation.id === activeId) {
|
||||||
setActiveConversationKey(remaining[0].key);
|
switchConversation(remaining[0].key);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -405,9 +272,9 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
[
|
[
|
||||||
activeId,
|
activeId,
|
||||||
conversations,
|
conversations,
|
||||||
|
switchConversation,
|
||||||
removeConversation,
|
removeConversation,
|
||||||
removeConversationEntry,
|
removeConversationEntry,
|
||||||
setActiveConversationKey,
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -443,7 +310,7 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
selectedKeys.includes(item.key),
|
selectedKeys.includes(item.key),
|
||||||
) as ConversationData[];
|
) as ConversationData[];
|
||||||
if (!selected.length) return;
|
if (!selected.length) return;
|
||||||
Modal.confirm({
|
modal.confirm({
|
||||||
title: `删除选中的 ${selected.length} 个会话`,
|
title: `删除选中的 ${selected.length} 个会话`,
|
||||||
content: '选中的会话及全部历史消息将被永久删除,此操作不可恢复。',
|
content: '选中的会话及全部历史消息将被永久删除,此操作不可恢复。',
|
||||||
okText: '删除',
|
okText: '删除',
|
||||||
@@ -457,7 +324,7 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
setConversationStatus({});
|
setConversationStatus({});
|
||||||
await aiChatApi.deleteAllConversations();
|
await aiChatApi.deleteAllConversations();
|
||||||
setConversations([]);
|
setConversations([]);
|
||||||
setActiveConversationKey('');
|
switchConversation('');
|
||||||
} else {
|
} else {
|
||||||
for (const item of selected) removeConversationEntry(item);
|
for (const item of selected) removeConversationEntry(item);
|
||||||
const deletedKeys: string[] = [];
|
const deletedKeys: string[] = [];
|
||||||
@@ -477,9 +344,9 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
const remaining = conversations.filter((item) => !deleted.has(item.key));
|
const remaining = conversations.filter((item) => !deleted.has(item.key));
|
||||||
setConversations(remaining);
|
setConversations(remaining);
|
||||||
if (!remaining.length) {
|
if (!remaining.length) {
|
||||||
setActiveConversationKey('');
|
switchConversation('');
|
||||||
} else if (activeId != null && !remaining.some((item) => item.id === activeId)) {
|
} else if (activeId != null && !remaining.some((item) => item.id === activeId)) {
|
||||||
setActiveConversationKey(remaining[0].key);
|
switchConversation(remaining[0].key);
|
||||||
}
|
}
|
||||||
if (failedTitles.length) message.error(`删除失败:${failedTitles.join('、')}`);
|
if (failedTitles.length) message.error(`删除失败:${failedTitles.join('、')}`);
|
||||||
}
|
}
|
||||||
@@ -493,7 +360,7 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
removeConversation,
|
removeConversation,
|
||||||
removeConversationEntry,
|
removeConversationEntry,
|
||||||
selectedKeys,
|
selectedKeys,
|
||||||
setActiveConversationKey,
|
switchConversation,
|
||||||
setConversations,
|
setConversations,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -505,7 +372,9 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
],
|
],
|
||||||
onClick: ({ key, domEvent }) => {
|
onClick: ({ key, domEvent }) => {
|
||||||
domEvent.stopPropagation();
|
domEvent.stopPropagation();
|
||||||
const conversation = conversations.find((entry) => entry.key === item.key) as ConversationData;
|
const conversation = conversations.find(
|
||||||
|
(entry) => entry.key === item.key,
|
||||||
|
) as ConversationData;
|
||||||
if (key === 'rename') renameConversation(conversation);
|
if (key === 'rename') renameConversation(conversation);
|
||||||
if (key === 'delete') deleteConversation(conversation);
|
if (key === 'delete') deleteConversation(conversation);
|
||||||
},
|
},
|
||||||
@@ -521,252 +390,14 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
await aiChatApi.updateConversation(activeConversation.id, { lockedSkillKey: skillKey }),
|
await aiChatApi.updateConversation(activeConversation.id, { lockedSkillKey: skillKey }),
|
||||||
);
|
);
|
||||||
setConversation(activeConversation.key, updated);
|
setConversation(activeConversation.key, updated);
|
||||||
} catch {
|
} catch (error) {
|
||||||
|
console.error('切换技能失败', error);
|
||||||
message.error('切换技能失败');
|
message.error('切换技能失败');
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[activeConversation, setConversation],
|
[activeConversation, setConversation],
|
||||||
);
|
);
|
||||||
|
|
||||||
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]);
|
|
||||||
|
|
||||||
const reloadMessage = useCallback(
|
|
||||||
(messageInfo: MessageInfo<AiChatMessage>) => {
|
|
||||||
reloadWithStatus(messageInfo);
|
|
||||||
},
|
|
||||||
[reloadWithStatus],
|
|
||||||
);
|
|
||||||
|
|
||||||
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 updateFeedback = useCallback(
|
|
||||||
async (messageInfo: MessageInfo<AiChatMessage>, feedback: 'like' | 'dislike' | null) => {
|
|
||||||
if (typeof messageInfo.message.id !== 'number') return;
|
|
||||||
try {
|
|
||||||
await aiChatApi.setFeedback(messageInfo.message.id, feedback);
|
|
||||||
setMessage(messageInfo.id, {
|
|
||||||
message: { ...messageInfo.message, feedback },
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
message.error('提交反馈失败');
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[setMessage],
|
|
||||||
);
|
|
||||||
|
|
||||||
const customUpload = useCallback<NonNullable<UploadProps['customRequest']>>(async (options) => {
|
|
||||||
const file = options.file as File;
|
|
||||||
if (attachmentsRef.current.length >= 5) {
|
|
||||||
const error = new Error('每条消息最多添加 5 个附件');
|
|
||||||
options.onError?.(error);
|
|
||||||
message.warning(error.message);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const uploaded = await aiChatApi.uploadAttachment(file);
|
|
||||||
setAttachments((items) => [...items, uploaded]);
|
|
||||||
options.onSuccess?.(uploaded, file);
|
|
||||||
} catch (error) {
|
|
||||||
options.onError?.(error instanceof Error ? error : new Error('附件上传失败'));
|
|
||||||
message.error('附件上传失败');
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const removeAttachment = useCallback(async (file: UploadFile<AiAttachment>) => {
|
|
||||||
const attachment = file.response;
|
|
||||||
if (!attachment) return true;
|
|
||||||
try {
|
|
||||||
await aiChatApi.deleteAttachment(attachment.id);
|
|
||||||
setAttachments((items) => items.filter((item) => item.id !== attachment.id));
|
|
||||||
return true;
|
|
||||||
} catch {
|
|
||||||
message.error('删除附件失败');
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const uploadItems = useMemo(() => attachments.map(toUploadFile), [attachments]);
|
|
||||||
const promptItems = useMemo<PromptsItemType[]>(
|
|
||||||
() =>
|
|
||||||
(lockedSkill ? [lockedSkill] : skills)
|
|
||||||
.flatMap((skill) => skill.examples.slice(0, lockedSkill ? 4 : 1).map((example) => ({ skill, example })))
|
|
||||||
.slice(0, 5)
|
|
||||||
.map(({ skill, example }) => ({
|
|
||||||
key: `${skill.key}-${example}`,
|
|
||||||
label: example,
|
|
||||||
description: skill.name,
|
|
||||||
})),
|
|
||||||
[lockedSkill, skills],
|
|
||||||
);
|
|
||||||
|
|
||||||
const bubbleItems = useMemo<BubbleItemType[]>(
|
|
||||||
() =>
|
|
||||||
messages.map((info) => ({
|
|
||||||
key: info.id,
|
|
||||||
role: info.message.role === 'assistant' ? 'assistant' : 'user',
|
|
||||||
status: info.status,
|
|
||||||
content: info.message,
|
|
||||||
contentRender: (content: AiChatMessage) => (
|
|
||||||
<AiMessageContent
|
|
||||||
message={content}
|
|
||||||
status={info.status as AiChatMessageStatus}
|
|
||||||
onReload={content.role === 'assistant' && info.status !== 'loading' ? () => reloadMessage(info) : undefined}
|
|
||||||
onFeedback={content.role === 'assistant' ? (feedback) => void updateFeedback(info, feedback) : undefined}
|
|
||||||
onSubmitForm={submitForm}
|
|
||||||
onSubmitReview={submitReview}
|
|
||||||
onConfirmReviewStep={confirmReviewStep}
|
|
||||||
onConfirmReviewGroup={confirmReviewGroup}
|
|
||||||
/>
|
|
||||||
),
|
|
||||||
})),
|
|
||||||
[confirmReviewGroup, confirmReviewStep, messages, reloadMessage, submitForm, submitReview, updateFeedback],
|
|
||||||
);
|
|
||||||
|
|
||||||
const conversationItems = useMemo<ConversationItemType[]>(
|
const conversationItems = useMemo<ConversationItemType[]>(
|
||||||
() =>
|
() =>
|
||||||
conversations.map((item) => {
|
conversations.map((item) => {
|
||||||
@@ -822,83 +453,61 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Drawer
|
<Drawer
|
||||||
title={<span className="ai-chat-title"><RobotOutlined />恭学 AI 助手</span>}
|
title={
|
||||||
|
<span className="ai-chat-title">
|
||||||
|
<RobotOutlined />
|
||||||
|
恭学 AI 助手
|
||||||
|
</span>
|
||||||
|
}
|
||||||
open={open}
|
open={open}
|
||||||
closeIcon={<ArrowRightOutlined title="收起到后台继续运行" />}
|
closeIcon={<ArrowRightOutlined title="收起到后台继续运行" />}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
width={isMobile ? '100%' : 'min(1040px, 92vw)'}
|
size={isMobile ? '100%' : 'min(1040px, 92vw)'}
|
||||||
destroyOnHidden={false}
|
destroyOnHidden={false}
|
||||||
className="ai-chat-drawer"
|
className="ai-chat-drawer"
|
||||||
styles={{ body: { padding: 0, height: '100%' } }}
|
styles={{ body: { padding: 0, height: '100%' } }}
|
||||||
>
|
>
|
||||||
<div className="ai-chat-layout">
|
<div className="ai-chat-layout">
|
||||||
<aside className={`ai-chat-sidebar${sidebarOpen ? ' is-open' : ''}`}>
|
<AiChatSidebar
|
||||||
<Conversations
|
className={`ai-chat-sidebar${effectiveSidebarOpen ? ' is-open' : ''}`}
|
||||||
items={conversationItems}
|
conversationItems={conversationItems}
|
||||||
activeKey={activeConversationKey}
|
activeConversationKey={activeConversationKey}
|
||||||
onActiveChange={(key) => {
|
selectionMode={selectionMode}
|
||||||
if (selectionMode) toggleConversationSelection(key);
|
selectedKeys={selectedKeys}
|
||||||
else setActiveConversationKey(key);
|
loadingList={loadingList}
|
||||||
}}
|
conversationCount={conversations.length}
|
||||||
menu={selectionMode ? undefined : conversationMenu}
|
onActiveChange={(key) => {
|
||||||
creation={
|
if (selectionMode) toggleConversationSelection(key);
|
||||||
selectionMode
|
else switchConversation(key);
|
||||||
? undefined
|
}}
|
||||||
: { label: '新对话', icon: <PlusOutlined />, onClick: startNewConversation }
|
menu={conversationMenu}
|
||||||
}
|
onStartNewConversation={startNewConversation}
|
||||||
/>
|
onSelectAll={selectAllConversations}
|
||||||
{loadingList && <Spin className="ai-chat-sidebar__loading" />}
|
onInvertSelection={invertConversationSelection}
|
||||||
<div className="ai-chat-sidebar__footer">
|
onDeleteSelected={deleteSelectedConversations}
|
||||||
{selectionMode ? (
|
onExitSelectionMode={exitSelectionMode}
|
||||||
<>
|
onEnterSelectionMode={enterSelectionMode}
|
||||||
<span className="ai-chat-sidebar__selected-count">{selectedKeys.length} 已选</span>
|
/>
|
||||||
<Button size="small" type="text" onClick={selectAllConversations}>
|
|
||||||
全选
|
|
||||||
</Button>
|
|
||||||
<Button size="small" type="text" onClick={invertConversationSelection}>
|
|
||||||
反选
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
size="small"
|
|
||||||
type="text"
|
|
||||||
danger
|
|
||||||
disabled={selectedKeys.length === 0}
|
|
||||||
onClick={deleteSelectedConversations}
|
|
||||||
>
|
|
||||||
删除
|
|
||||||
</Button>
|
|
||||||
<Button size="small" type="text" onClick={exitSelectionMode}>
|
|
||||||
取消
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<Button
|
|
||||||
size="small"
|
|
||||||
type="text"
|
|
||||||
icon={<CheckSquareOutlined />}
|
|
||||||
disabled={conversations.length === 0}
|
|
||||||
onClick={enterSelectionMode}
|
|
||||||
>
|
|
||||||
管理
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</aside>
|
|
||||||
|
|
||||||
<main className="ai-chat-main">
|
<main className="ai-chat-main">
|
||||||
<div className="ai-chat-toolbar">
|
<AiChatComposer
|
||||||
<Tooltip title={sidebarOpen ? '收起会话' : '展开会话'}>
|
input={input}
|
||||||
<Button
|
onChange={setInput}
|
||||||
type="text"
|
isRequesting={isRequesting}
|
||||||
icon={sidebarOpen ? <MenuFoldOutlined /> : <MenuUnfoldOutlined />}
|
onSubmit={submit}
|
||||||
onClick={() => setSidebarOpen((value) => !value)}
|
onCancel={stopRequest}
|
||||||
/>
|
uploadItems={uploadItems}
|
||||||
</Tooltip>
|
onCustomUpload={customUpload}
|
||||||
<Typography.Text ellipsis>{activeConversation?.title || 'AI 助手'}</Typography.Text>
|
onRemoveAttachment={removeAttachment}
|
||||||
<Dropdown menu={skillMenu} trigger={['click']}>
|
deepThinking={deepThinking}
|
||||||
<Button size="small">{lockedSkill?.name || '自动技能'}</Button>
|
onDeepThinkingChange={setDeepThinking}
|
||||||
</Dropdown>
|
lockedSkill={lockedSkill}
|
||||||
</div>
|
onClearSkill={() => void setLockedSkill(null)}
|
||||||
|
onToggleSidebar={() => setSidebarOpen((value) => !value)}
|
||||||
|
sidebarOpen={effectiveSidebarOpen}
|
||||||
|
skillMenu={skillMenu}
|
||||||
|
conversationTitle={activeConversation?.title || 'AI 助手'}
|
||||||
|
/>
|
||||||
|
|
||||||
<div className="ai-chat-messages">
|
<div className="ai-chat-messages">
|
||||||
{messages.length ? (
|
{messages.length ? (
|
||||||
@@ -909,7 +518,10 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
variant="borderless"
|
variant="borderless"
|
||||||
icon={<RobotOutlined />}
|
icon={<RobotOutlined />}
|
||||||
title="你好,我是恭学 AI 助手"
|
title="你好,我是恭学 AI 助手"
|
||||||
description={lockedSkill?.description || '我会在你的权限范围内查询数据,也能通过表单帮你录入学生等业务信息。'}
|
description={
|
||||||
|
lockedSkill?.description ||
|
||||||
|
'我会在你的权限范围内查询数据,也能通过表单帮你录入学生等业务信息。'
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<Prompts
|
<Prompts
|
||||||
title="你可以这样问"
|
title="你可以这样问"
|
||||||
@@ -921,65 +533,14 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="ai-chat-composer">
|
{importWizardRunId !== null && (
|
||||||
<Sender
|
<ImportWizardModal
|
||||||
value={input}
|
key={importWizardRunId}
|
||||||
onChange={setInput}
|
open
|
||||||
loading={isRequesting}
|
runId={importWizardRunId}
|
||||||
onSubmit={submit}
|
onClose={() => setImportWizardRunId(null)}
|
||||||
onCancel={stopRequest}
|
|
||||||
autoSize={{ minRows: 1, maxRows: 6 }}
|
|
||||||
placeholder="询问学生、考勤、宿舍或账单数据"
|
|
||||||
skill={
|
|
||||||
lockedSkill
|
|
||||||
? {
|
|
||||||
title: lockedSkill.name,
|
|
||||||
value: lockedSkill.key,
|
|
||||||
closable: { onClose: () => void setLockedSkill(null) },
|
|
||||||
}
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
header={
|
|
||||||
uploadItems.length > 0 && (
|
|
||||||
<div className="ai-chat-sender-header">
|
|
||||||
<Attachments
|
|
||||||
items={uploadItems}
|
|
||||||
customRequest={customUpload}
|
|
||||||
onRemove={removeAttachment}
|
|
||||||
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={customUpload}
|
|
||||||
onRemove={removeAttachment}
|
|
||||||
accept="image/jpeg,image/png,image/webp,application/pdf,.docx,.xlsx"
|
|
||||||
multiple
|
|
||||||
placeholder={{ title: '添加附件', description: '图片、PDF、Word、Excel,单个不超过 10MB' }}
|
|
||||||
>
|
|
||||||
<Button type="text" icon={<PaperClipOutlined />} aria-label="添加附件" />
|
|
||||||
</Attachments>
|
|
||||||
</Tooltip>
|
|
||||||
<SenderSwitch
|
|
||||||
checkedChildren="深度思考"
|
|
||||||
unCheckedChildren="普通"
|
|
||||||
value={deepThinking}
|
|
||||||
onChange={setDeepThinking}
|
|
||||||
disabled={isRequesting}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
<Typography.Text type="secondary" className="ai-chat-disclaimer">
|
)}
|
||||||
AI 操作均在权限范围内执行,写操作需通过表单确认,重要信息请以系统记录为准
|
|
||||||
</Typography.Text>
|
|
||||||
</div>
|
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
</Drawer>
|
</Drawer>
|
||||||
|
|||||||
@@ -1,39 +1,30 @@
|
|||||||
import React, { useMemo } from 'react';
|
import React, { useMemo, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
CheckCircleOutlined,
|
CheckCircleOutlined,
|
||||||
CloseCircleOutlined,
|
CloseCircleOutlined,
|
||||||
CopyOutlined,
|
|
||||||
DislikeFilled,
|
|
||||||
DislikeOutlined,
|
|
||||||
LikeFilled,
|
|
||||||
LikeOutlined,
|
|
||||||
LoadingOutlined,
|
LoadingOutlined,
|
||||||
ReloadOutlined,
|
TableOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import {
|
import FileCard from '@ant-design/x/es/file-card';
|
||||||
Actions,
|
import Sources from '@ant-design/x/es/sources';
|
||||||
CodeHighlighter,
|
import Think from '@ant-design/x/es/think';
|
||||||
FileCard,
|
import ThoughtChain from '@ant-design/x/es/thought-chain';
|
||||||
Mermaid,
|
|
||||||
Sources,
|
|
||||||
Think,
|
|
||||||
ThoughtChain,
|
|
||||||
} from '@ant-design/x';
|
|
||||||
import type { ThoughtChainItemType } from '@ant-design/x';
|
import type { ThoughtChainItemType } from '@ant-design/x';
|
||||||
import XMarkdown from '@ant-design/x-markdown';
|
import XMarkdown, { type ComponentProps } from '@ant-design/x-markdown';
|
||||||
import type { ComponentProps } from '@ant-design/x-markdown';
|
import { Alert, Button, Flex, Input, Space, Typography } from 'antd';
|
||||||
import { Alert, Flex, Space, Typography } from 'antd';
|
|
||||||
import { useUserStore } from '../../store/user/userStore';
|
import { useUserStore } from '../../store/user/userStore';
|
||||||
import { DynamicChart } from './DynamicChart';
|
import { DynamicChart } from './DynamicChart';
|
||||||
import { DynamicForm } from './DynamicForm';
|
import { DynamicForm } from './DynamicForm';
|
||||||
import { DynamicReview } from './DynamicReview';
|
import { DynamicReview } from './DynamicReview';
|
||||||
|
import { LiteCodeHighlighter } from './LiteCodeHighlighter';
|
||||||
|
import { LiteMermaid } from './LiteMermaid';
|
||||||
import type {
|
import type {
|
||||||
AiAttachment,
|
AiAttachment,
|
||||||
AiChatMessage,
|
AiChatMessage,
|
||||||
AiChatMessageStatus,
|
AiChatMessageStatus,
|
||||||
AiChartSchema,
|
AiChartSchema,
|
||||||
AiFormSchema,
|
AiFormSchema,
|
||||||
AiMessageFeedback,
|
AiImportWizard,
|
||||||
AiReviewSection,
|
AiReviewSection,
|
||||||
AiReviewSchema,
|
AiReviewSchema,
|
||||||
AiReviewSectionType,
|
AiReviewSectionType,
|
||||||
@@ -52,6 +43,7 @@ const toolLabels: Record<string, string> = {
|
|||||||
render_form: '生成表单',
|
render_form: '生成表单',
|
||||||
render_review: '生成导入预览',
|
render_review: '生成导入预览',
|
||||||
render_chart: '生成图表',
|
render_chart: '生成图表',
|
||||||
|
start_import_wizard: '生成导入向导',
|
||||||
create_student: '创建学生',
|
create_student: '创建学生',
|
||||||
search_exams: '查询考试',
|
search_exams: '查询考试',
|
||||||
search_schedules: '查询课表',
|
search_schedules: '查询课表',
|
||||||
@@ -66,8 +58,8 @@ const markdownComponents = {
|
|||||||
code: ({ children, lang, block }: ComponentProps) => {
|
code: ({ children, lang, block }: ComponentProps) => {
|
||||||
const content = String(children ?? '').replace(/\n$/, '');
|
const content = String(children ?? '').replace(/\n$/, '');
|
||||||
if (!block) return <code>{content}</code>;
|
if (!block) return <code>{content}</code>;
|
||||||
if (lang === 'mermaid') return <Mermaid>{content}</Mermaid>;
|
if (lang === 'mermaid') return <LiteMermaid>{content}</LiteMermaid>;
|
||||||
return <CodeHighlighter lang={lang || 'text'}>{content}</CodeHighlighter>;
|
return <LiteCodeHighlighter lang={lang}>{content}</LiteCodeHighlighter>;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -118,7 +110,8 @@ function ToolChain({ tools }: { tools: AiToolRun[] }) {
|
|||||||
key: tool.toolCallId,
|
key: tool.toolCallId,
|
||||||
title: toolLabels[tool.toolName] || tool.toolName,
|
title: toolLabels[tool.toolName] || tool.toolName,
|
||||||
description: tool.durationMs ? `${tool.durationMs}ms` : undefined,
|
description: tool.durationMs ? `${tool.durationMs}ms` : undefined,
|
||||||
content: tool.summary || (running ? '正在查询业务数据' : success ? '查询完成' : '查询失败'),
|
content:
|
||||||
|
tool.summary || (running ? '正在查询业务数据' : success ? '查询完成' : '查询失败'),
|
||||||
status: running ? 'loading' : success ? 'success' : 'error',
|
status: running ? 'loading' : success ? 'success' : 'error',
|
||||||
icon: running ? (
|
icon: running ? (
|
||||||
<LoadingOutlined spin />
|
<LoadingOutlined spin />
|
||||||
@@ -135,11 +128,51 @@ function ToolChain({ tools }: { tools: AiToolRun[] }) {
|
|||||||
return <ThoughtChain items={items} line="solid" />;
|
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 {
|
export interface AiMessageContentProps {
|
||||||
message: AiChatMessage;
|
message: AiChatMessage;
|
||||||
status?: AiChatMessageStatus;
|
status?: AiChatMessageStatus;
|
||||||
onReload?: () => void;
|
editing?: boolean;
|
||||||
onFeedback?: (feedback: AiMessageFeedback) => void;
|
onEditConfirm?: (value: string) => void;
|
||||||
|
onEditCancel?: () => void;
|
||||||
onSubmitForm?: (form: AiFormSchema, values: Record<string, unknown>) => void;
|
onSubmitForm?: (form: AiFormSchema, values: Record<string, unknown>) => void;
|
||||||
onSubmitReview?: (reviewId: string, reviewTitle?: string) => void;
|
onSubmitReview?: (reviewId: string, reviewTitle?: string) => void;
|
||||||
onConfirmReviewStep?: (
|
onConfirmReviewStep?: (
|
||||||
@@ -152,17 +185,20 @@ export interface AiMessageContentProps {
|
|||||||
reviewId: string,
|
reviewId: string,
|
||||||
type: AiReviewSectionType,
|
type: AiReviewSectionType,
|
||||||
) => AiReviewSchema | Promise<AiReviewSchema> | void;
|
) => AiReviewSchema | Promise<AiReviewSchema> | void;
|
||||||
|
onOpenImportWizard?: (runId: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const AiMessageContent: React.FC<AiMessageContentProps> = ({
|
export const AiMessageContent: React.FC<AiMessageContentProps> = ({
|
||||||
message,
|
message,
|
||||||
status,
|
status,
|
||||||
onReload,
|
editing,
|
||||||
onFeedback,
|
onEditConfirm,
|
||||||
|
onEditCancel,
|
||||||
onSubmitForm,
|
onSubmitForm,
|
||||||
onSubmitReview,
|
onSubmitReview,
|
||||||
onConfirmReviewStep,
|
onConfirmReviewStep,
|
||||||
onConfirmReviewGroup,
|
onConfirmReviewGroup,
|
||||||
|
onOpenImportWizard,
|
||||||
}) => {
|
}) => {
|
||||||
const streaming = status === 'loading' || status === 'updating';
|
const streaming = status === 'loading' || status === 'updating';
|
||||||
const formSubmission = message.metadata?.a2uiSubmit;
|
const formSubmission = message.metadata?.a2uiSubmit;
|
||||||
@@ -199,8 +235,8 @@ export const AiMessageContent: React.FC<AiMessageContentProps> = ({
|
|||||||
? String((reviewSubmission as Record<string, unknown>).reviewTitle)
|
? String((reviewSubmission as Record<string, unknown>).reviewTitle)
|
||||||
: '批量导入';
|
: '批量导入';
|
||||||
return (
|
return (
|
||||||
<Space direction="vertical" size={8} className="ai-chat-user-content">
|
<Space orientation="vertical" size={8} className="ai-chat-user-content">
|
||||||
<Alert type="success" showIcon message={`已确认导入《${reviewTitle}》`} />
|
<Alert type="success" showIcon title={`已确认导入《${reviewTitle}》`} />
|
||||||
</Space>
|
</Space>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -210,64 +246,55 @@ export const AiMessageContent: React.FC<AiMessageContentProps> = ({
|
|||||||
? String((formSubmission as Record<string, unknown>).formTitle)
|
? String((formSubmission as Record<string, unknown>).formTitle)
|
||||||
: '表单';
|
: '表单';
|
||||||
return (
|
return (
|
||||||
<Space direction="vertical" size={8} className="ai-chat-user-content">
|
<Space orientation="vertical" size={8} className="ai-chat-user-content">
|
||||||
<Alert type="info" showIcon message={`已提交《${formTitle}》`} />
|
<Alert type="info" showIcon title={`已提交《${formTitle}》`} />
|
||||||
</Space>
|
</Space>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<Space direction="vertical" size={8} className="ai-chat-user-content">
|
<Space orientation="vertical" size={8} className="ai-chat-user-content">
|
||||||
{attachmentCards.length > 0 && <Flex wrap gap={8}>{attachmentCards}</Flex>}
|
{attachmentCards.length > 0 && (
|
||||||
<div className="ai-chat-user-text">{message.content}</div>
|
<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>
|
</Space>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const actionItems = [
|
|
||||||
{
|
|
||||||
key: 'copy',
|
|
||||||
label: '复制',
|
|
||||||
icon: <CopyOutlined />,
|
|
||||||
onItemClick: () => void navigator.clipboard.writeText(message.content),
|
|
||||||
},
|
|
||||||
...(onReload
|
|
||||||
? [{ key: 'reload', label: '重新生成', icon: <ReloadOutlined />, onItemClick: onReload }]
|
|
||||||
: []),
|
|
||||||
...(onFeedback
|
|
||||||
? [
|
|
||||||
{
|
|
||||||
key: 'like',
|
|
||||||
label: '有帮助',
|
|
||||||
icon: message.feedback === 'like' ? <LikeFilled /> : <LikeOutlined />,
|
|
||||||
onItemClick: () => onFeedback(message.feedback === 'like' ? null : 'like'),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'dislike',
|
|
||||||
label: '没帮助',
|
|
||||||
icon: message.feedback === 'dislike' ? <DislikeFilled /> : <DislikeOutlined />,
|
|
||||||
onItemClick: () => onFeedback(message.feedback === 'dislike' ? null : 'dislike'),
|
|
||||||
},
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Space direction="vertical" size={10} className="ai-chat-answer">
|
<Space orientation="vertical" size={10} className="ai-chat-answer">
|
||||||
{streaming && !message.content && !message.reasoningContent && message.toolRuns.length === 0 && (
|
{streaming &&
|
||||||
<div className="ai-chat-streaming-placeholder" role="status" aria-label="生成中">
|
!message.content &&
|
||||||
<LoadingOutlined spin />
|
!message.reasoningContent &&
|
||||||
</div>
|
message.toolRuns.length === 0 && (
|
||||||
)}
|
<div className="ai-chat-streaming-placeholder" role="status" aria-label="生成中">
|
||||||
|
<LoadingOutlined spin />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{message.retrying && (
|
{message.retrying && (
|
||||||
<Alert
|
<Alert
|
||||||
type="warning"
|
type="warning"
|
||||||
showIcon
|
showIcon
|
||||||
message={`AI 服务繁忙,正在自动重试(第 ${message.retrying.attempt} / ${message.retrying.maxRetries} 次)...`}
|
title={`AI 服务繁忙,正在自动重试(第 ${message.retrying.attempt} / ${message.retrying.maxRetries} 次)...`}
|
||||||
description={message.retrying.reason ? `原因:${message.retrying.reason}` : undefined}
|
description={message.retrying.reason ? `原因:${message.retrying.reason}` : undefined}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{message.reasoningContent && (
|
{message.reasoningContent && (
|
||||||
<Think title={streaming ? '正在思考' : '思考过程'} loading={streaming} defaultExpanded={false}>
|
<Think
|
||||||
|
title={streaming ? '正在思考' : '思考过程'}
|
||||||
|
loading={streaming}
|
||||||
|
defaultExpanded={false}
|
||||||
|
>
|
||||||
<XMarkdown
|
<XMarkdown
|
||||||
content={message.reasoningContent}
|
content={message.reasoningContent}
|
||||||
components={markdownComponents}
|
components={markdownComponents}
|
||||||
@@ -279,7 +306,29 @@ export const AiMessageContent: React.FC<AiMessageContentProps> = ({
|
|||||||
</Think>
|
</Think>
|
||||||
)}
|
)}
|
||||||
{message.toolRuns.length > 0 && <ToolChain tools={message.toolRuns} />}
|
{message.toolRuns.length > 0 && <ToolChain tools={message.toolRuns} />}
|
||||||
{attachmentCards.length > 0 && <Flex wrap gap={8}>{attachmentCards}</Flex>}
|
{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 && (
|
{message.content && (
|
||||||
<XMarkdown
|
<XMarkdown
|
||||||
content={message.content}
|
content={message.content}
|
||||||
@@ -324,9 +373,8 @@ export const AiMessageContent: React.FC<AiMessageContentProps> = ({
|
|||||||
{(message.charts ?? []).map((chart: AiChartSchema) => (
|
{(message.charts ?? []).map((chart: AiChartSchema) => (
|
||||||
<DynamicChart key={chart.id} chart={chart} />
|
<DynamicChart key={chart.id} chart={chart} />
|
||||||
))}
|
))}
|
||||||
{message.error && <Alert type="error" showIcon message={message.error} />}
|
{message.error && <Alert type="error" showIcon title={message.error} />}
|
||||||
{message.cancelled && <Typography.Text type="secondary">回答已停止</Typography.Text>}
|
{message.cancelled && <Typography.Text type="secondary">回答已停止</Typography.Text>}
|
||||||
{!streaming && message.content && <Actions items={actionItems} fadeIn />}
|
|
||||||
</Space>
|
</Space>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
import React, { lazy, Suspense, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { XCard, registerCatalog } from '@ant-design/x-card';
|
import { XCard, registerCatalog, type XAgentCommand_v0_9 } from '@ant-design/x-card';
|
||||||
import type { XAgentCommand_v0_9 } from '@ant-design/x-card';
|
import { Button, Spin, Tag, Tooltip, Typography } from 'antd';
|
||||||
import { Button, Tag, Tooltip, Typography } from 'antd';
|
|
||||||
import { DownloadOutlined } from '@ant-design/icons';
|
import { DownloadOutlined } from '@ant-design/icons';
|
||||||
import type { EChartsType } from 'echarts/core';
|
import type { EChartsType } from 'echarts/core';
|
||||||
import ReactECharts, { type EChartsOption } from '../../components/ECharts';
|
import type { EChartsOption } from '../../components/ECharts';
|
||||||
import type { AiChartSchema } from './types';
|
import type { AiChartSchema } from './types';
|
||||||
|
|
||||||
|
// echarts 体积较大,仅在真正渲染图表时加载,避免打开 AI 抽屉就拉取
|
||||||
|
const ReactECharts = lazy(() => import('../../components/ECharts'));
|
||||||
|
|
||||||
const CHART_CATALOG_ID = 'gongxue-chart-catalog';
|
const CHART_CATALOG_ID = 'gongxue-chart-catalog';
|
||||||
|
|
||||||
registerCatalog({
|
registerCatalog({
|
||||||
@@ -41,117 +43,129 @@ const CHART_TYPE_LABELS: Record<string, string> = {
|
|||||||
funnel: '漏斗图',
|
funnel: '漏斗图',
|
||||||
};
|
};
|
||||||
|
|
||||||
function buildOption(chart: AiChartSchema): EChartsOption {
|
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 columns = chart.columns;
|
||||||
if (chart.chartType === 'scatter') {
|
const nameField = columns[0]?.key ?? '';
|
||||||
const nameField = columns[0]?.key ?? '';
|
const xField = columns[1]?.key ?? '';
|
||||||
const xField = columns[1]?.key ?? '';
|
const yField = columns[2]?.key ?? '';
|
||||||
const yField = columns[2]?.key ?? '';
|
const data = chart.rows.map((row) => ({
|
||||||
const data = chart.rows.map((row) => ({
|
name: String(row[nameField] ?? ''),
|
||||||
name: String(row[nameField] ?? ''),
|
value: [numberValue(row[xField]), numberValue(row[yField])],
|
||||||
value: [numberValue(row[xField]), numberValue(row[yField])],
|
}));
|
||||||
}));
|
return {
|
||||||
return {
|
tooltip: {
|
||||||
tooltip: {
|
trigger: 'item',
|
||||||
trigger: 'item',
|
formatter: (params: unknown) => {
|
||||||
formatter: (params: unknown) => {
|
const item = params as { name?: string; value?: number[] };
|
||||||
const item = params as { name?: string; value?: number[] };
|
const [x, y] = item.value ?? [];
|
||||||
const [x, y] = item.value ?? [];
|
return `${item.name ?? ''}: (${x ?? 0}, ${y ?? 0})`;
|
||||||
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 },
|
grid: { left: 8, right: 16, top: 32, bottom: 48, containLabel: true },
|
||||||
yAxis: { type: 'value', name: columns[2]?.title },
|
xAxis: { type: 'value', name: columns[1]?.title },
|
||||||
series: [{ type: 'scatter', symbolSize: 10, data }],
|
yAxis: { type: 'value', name: columns[2]?.title },
|
||||||
};
|
series: [{ type: 'scatter', symbolSize: 10, data }],
|
||||||
}
|
};
|
||||||
if (chart.chartType === 'radar') {
|
}
|
||||||
const seriesNameField = columns[0]?.key ?? '';
|
|
||||||
const indicatorColumns = columns.slice(1);
|
function buildRadarOption(chart: AiChartSchema): EChartsOption {
|
||||||
const indicators = indicatorColumns.map((column) => {
|
const columns = chart.columns;
|
||||||
const values = chart.rows.map((row) => numberValue(row[column.key]));
|
const seriesNameField = columns[0]?.key ?? '';
|
||||||
const max = Math.max(1, ...values);
|
const indicatorColumns = columns.slice(1);
|
||||||
return { name: column.title, max: Math.ceil(max * 1.1) };
|
const indicators = indicatorColumns.map((column) => {
|
||||||
});
|
const values = chart.rows.map((row) => numberValue(row[column.key]));
|
||||||
const seriesData = chart.rows.map((row) => ({
|
const max = Math.max(1, ...values);
|
||||||
name: String(row[seriesNameField] ?? ''),
|
return { name: column.title, max: Math.ceil(max * 1.1) };
|
||||||
value: indicatorColumns.map((column) => numberValue(row[column.key])),
|
});
|
||||||
}));
|
const seriesData = chart.rows.map((row) => ({
|
||||||
return {
|
name: String(row[seriesNameField] ?? ''),
|
||||||
tooltip: { trigger: 'item' },
|
value: indicatorColumns.map((column) => numberValue(row[column.key])),
|
||||||
legend: { bottom: 0, type: 'scroll' },
|
}));
|
||||||
radar: { indicator: indicators, radius: '65%' },
|
return {
|
||||||
series: [{ type: 'radar', data: seriesData }],
|
tooltip: { trigger: 'item' },
|
||||||
};
|
legend: { bottom: 0, type: 'scroll' },
|
||||||
}
|
radar: { indicator: indicators, radius: '65%' },
|
||||||
if (chart.chartType === 'gauge') {
|
series: [{ type: 'radar', data: seriesData }],
|
||||||
const nameField = columns[0]?.key ?? '';
|
};
|
||||||
const valueField = columns[1]?.key ?? '';
|
}
|
||||||
const maxField = columns[2]?.key;
|
|
||||||
const gauges = chart.rows.map((row) => ({
|
function buildGaugeOption(chart: AiChartSchema): EChartsOption {
|
||||||
name: String(row[nameField] ?? ''),
|
const columns = chart.columns;
|
||||||
value: numberValue(row[valueField]),
|
const nameField = columns[0]?.key ?? '';
|
||||||
max: maxField ? Math.max(1, numberValue(row[maxField])) : 100,
|
const valueField = columns[1]?.key ?? '';
|
||||||
}));
|
const maxField = columns[2]?.key;
|
||||||
return {
|
const gauges = chart.rows.map((row) => ({
|
||||||
series: gauges.map((gauge, index) => ({
|
name: String(row[nameField] ?? ''),
|
||||||
type: 'gauge',
|
value: numberValue(row[valueField]),
|
||||||
center: [`${((index + 0.5) * 100) / gauges.length}%`, '58%'],
|
max: maxField ? Math.max(1, numberValue(row[maxField])) : 100,
|
||||||
radius: '75%',
|
}));
|
||||||
min: 0,
|
return {
|
||||||
max: gauge.max,
|
series: gauges.map((gauge, index) => ({
|
||||||
title: { show: true, offsetCenter: [0, '82%'], fontSize: 12 },
|
type: 'gauge',
|
||||||
detail: { formatter: '{value}', fontSize: 14, offsetCenter: [0, '20%'] },
|
center: [`${((index + 0.5) * 100) / gauges.length}%`, '58%'],
|
||||||
data: [{ value: gauge.value, name: gauge.name }],
|
radius: '75%',
|
||||||
})),
|
min: 0,
|
||||||
};
|
max: gauge.max,
|
||||||
}
|
title: { show: true, offsetCenter: [0, '82%'], fontSize: 12 },
|
||||||
if (chart.chartType === 'funnel') {
|
detail: { formatter: '{value}', fontSize: 14, offsetCenter: [0, '20%'] },
|
||||||
const nameField = columns[0]?.key ?? '';
|
data: [{ value: gauge.value, name: gauge.name }],
|
||||||
const valueField = columns[1]?.key ?? '';
|
})),
|
||||||
const data = chart.rows.map((row) => ({
|
};
|
||||||
name: String(row[nameField] ?? ''),
|
}
|
||||||
value: numberValue(row[valueField]),
|
|
||||||
}));
|
function buildNameValueOption(chart: AiChartSchema): EChartsOption {
|
||||||
return {
|
const data = buildNameValueRows(chart);
|
||||||
tooltip: { trigger: 'item', formatter: '{b}: {c}' },
|
return chart.chartType === 'funnel'
|
||||||
legend: { bottom: 0, type: 'scroll' },
|
? {
|
||||||
series: [
|
tooltip: { trigger: 'item', formatter: '{b}: {c}' },
|
||||||
{
|
legend: { bottom: 0, type: 'scroll' },
|
||||||
type: 'funnel',
|
series: [
|
||||||
left: '10%',
|
{
|
||||||
top: 20,
|
type: 'funnel',
|
||||||
bottom: 40,
|
left: '10%',
|
||||||
width: '80%',
|
top: 20,
|
||||||
minSize: '20%',
|
bottom: 40,
|
||||||
label: { formatter: '{b}: {c}' },
|
width: '80%',
|
||||||
data,
|
minSize: '20%',
|
||||||
},
|
label: { formatter: '{b}: {c}' },
|
||||||
],
|
data,
|
||||||
};
|
},
|
||||||
}
|
],
|
||||||
if (chart.chartType === 'pie') {
|
}
|
||||||
const nameField = columns[0]?.key ?? '';
|
: {
|
||||||
const valueField = columns[1]?.key ?? '';
|
tooltip: { trigger: 'item' },
|
||||||
const data = chart.rows.map((row) => ({
|
legend: { bottom: 0, type: 'scroll' },
|
||||||
name: String(row[nameField] ?? ''),
|
series: [
|
||||||
value: numberValue(row[valueField]),
|
{
|
||||||
}));
|
type: 'pie',
|
||||||
return {
|
radius: ['35%', '68%'],
|
||||||
tooltip: { trigger: 'item' },
|
center: ['50%', '45%'],
|
||||||
legend: { bottom: 0, type: 'scroll' },
|
data,
|
||||||
series: [
|
label: { formatter: '{b}: {c}' },
|
||||||
{
|
},
|
||||||
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 categoryField = columns[0]?.key ?? '';
|
||||||
const categories = chart.rows.map((row) => String(row[categoryField] ?? ''));
|
const categories = chart.rows.map((row) => String(row[categoryField] ?? ''));
|
||||||
const series = columns.slice(1).map((column) => ({
|
const series = columns.slice(1).map((column) => ({
|
||||||
@@ -223,11 +237,9 @@ const ChartPreview: React.FC<ChartPreviewProps> = ({ chart }) => {
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<ReactECharts
|
<Suspense fallback={<Spin size="small" />}>
|
||||||
option={option}
|
<ReactECharts option={option} style={{ width: '100%', height: 260 }} onReady={setInstance} />
|
||||||
style={{ width: '100%', height: 260 }}
|
</Suspense>
|
||||||
onReady={setInstance}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -291,5 +303,3 @@ export const DynamicChart: React.FC<DynamicChartProps> = ({ chart }) => {
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default DynamicChart;
|
|
||||||
|
|||||||
@@ -1,7 +1,21 @@
|
|||||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { XCard, registerCatalog } from '@ant-design/x-card';
|
import {
|
||||||
import type { ActionPayload, XAgentCommand_v0_9 } from '@ant-design/x-card';
|
XCard,
|
||||||
import { Alert, Button, DatePicker, Flex, Form, Input, InputNumber, Select, Typography } from 'antd';
|
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 dayjs from 'dayjs';
|
||||||
import type { AiFormField, AiFormSchema } from './types';
|
import type { AiFormField, AiFormSchema } from './types';
|
||||||
|
|
||||||
@@ -47,7 +61,11 @@ function normalizeValues(
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface FormPreviewProps {
|
interface FormPreviewProps {
|
||||||
form?: AiFormSchema;
|
form?: AiFormSchema & {
|
||||||
|
submitting?: boolean;
|
||||||
|
submitted?: boolean;
|
||||||
|
error?: string | null;
|
||||||
|
};
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
onAction?: (name: string, context: Record<string, unknown>) => void;
|
onAction?: (name: string, context: Record<string, unknown>) => void;
|
||||||
}
|
}
|
||||||
@@ -58,18 +76,14 @@ interface FormPreviewProps {
|
|||||||
* normalized values back through the `form:submit` action.
|
* normalized values back through the `form:submit` action.
|
||||||
*/
|
*/
|
||||||
const FormPreview: React.FC<FormPreviewProps> = ({ form, disabled, onAction }) => {
|
const FormPreview: React.FC<FormPreviewProps> = ({ form, disabled, onAction }) => {
|
||||||
const runtime = form as unknown as {
|
const submitting = Boolean(form?.submitting);
|
||||||
submitting?: boolean;
|
|
||||||
submitted?: boolean;
|
|
||||||
error?: string | null;
|
|
||||||
};
|
|
||||||
const submitting = Boolean(runtime.submitting);
|
|
||||||
const initialValues = useMemo(
|
const initialValues = useMemo(
|
||||||
() => Object.fromEntries((form?.fields ?? []).map((field) => [field.name, initialValue(field)])),
|
() =>
|
||||||
|
Object.fromEntries((form?.fields ?? []).map((field) => [field.name, initialValue(field)])),
|
||||||
[form?.fields],
|
[form?.fields],
|
||||||
);
|
);
|
||||||
if (!form) return null;
|
if (!form) return null;
|
||||||
const finished = Boolean(runtime.submitted) || form.status === 'submitted';
|
const finished = Boolean(form.submitted) || form.status === 'submitted';
|
||||||
|
|
||||||
const handleFinish = (values: Record<string, unknown>) => {
|
const handleFinish = (values: Record<string, unknown>) => {
|
||||||
onAction?.('form:submit', { values: normalizeValues(form.fields, values) });
|
onAction?.('form:submit', { values: normalizeValues(form.fields, values) });
|
||||||
@@ -124,17 +138,20 @@ const FormPreview: React.FC<FormPreviewProps> = ({ form, disabled, onAction }) =
|
|||||||
options={field.options}
|
options={field.options}
|
||||||
/>
|
/>
|
||||||
) : field.type === 'date' ? (
|
) : field.type === 'date' ? (
|
||||||
<DatePicker className="ai-chat-dynamic-form__date" placeholder={field.placeholder} />
|
<DatePicker
|
||||||
|
className="ai-chat-dynamic-form__date"
|
||||||
|
placeholder={field.placeholder}
|
||||||
|
/>
|
||||||
) : (
|
) : (
|
||||||
<Input placeholder={field.placeholder} />
|
<Input placeholder={field.placeholder} />
|
||||||
)}
|
)}
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
))}
|
))}
|
||||||
{runtime.error && (
|
{form.error && (
|
||||||
<Alert
|
<Alert
|
||||||
type="error"
|
type="error"
|
||||||
showIcon
|
showIcon
|
||||||
message={runtime.error}
|
title={form.error}
|
||||||
className="ai-chat-dynamic-form__error"
|
className="ai-chat-dynamic-form__error"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -235,5 +252,3 @@ export const DynamicForm: React.FC<DynamicFormProps> = ({ form, disabled, onSubm
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default DynamicForm;
|
|
||||||
|
|||||||
@@ -1,15 +1,35 @@
|
|||||||
import React, { useEffect, useRef, useState } from 'react';
|
import React, { useEffect, useRef, useState } from 'react';
|
||||||
import { XCard, registerCatalog } from '@ant-design/x-card';
|
import {
|
||||||
import type { ActionPayload, XAgentCommand_v0_9 } from '@ant-design/x-card';
|
XCard,
|
||||||
import { Alert, Button, Flex, Popconfirm, Steps, Table, Tag, Typography } from 'antd';
|
registerCatalog,
|
||||||
import type { TableProps } from 'antd';
|
type ActionPayload,
|
||||||
import type {
|
type XAgentCommand_v0_9,
|
||||||
AiReviewRow,
|
} from '@ant-design/x-card';
|
||||||
AiReviewSchema,
|
import {
|
||||||
AiReviewSection,
|
Alert,
|
||||||
AiReviewSectionStatus,
|
Button,
|
||||||
AiReviewSectionType,
|
Flex,
|
||||||
} from './types';
|
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';
|
const REVIEW_CATALOG_ID = 'gongxue-review-catalog';
|
||||||
|
|
||||||
@@ -35,125 +55,6 @@ function surfaceId(reviewId: string): string {
|
|||||||
return `review-${reviewId}`;
|
return `review-${reviewId}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const SECTION_TYPE_LABELS: Record<AiReviewSectionType, string> = {
|
|
||||||
students: '学生',
|
|
||||||
rooms: '宿舍',
|
|
||||||
transfers: '换宿',
|
|
||||||
checkins: '入住记录',
|
|
||||||
};
|
|
||||||
|
|
||||||
const SECTION_ORDER: AiReviewSectionType[] = [
|
|
||||||
'students',
|
|
||||||
'rooms',
|
|
||||||
'transfers',
|
|
||||||
'checkins',
|
|
||||||
];
|
|
||||||
|
|
||||||
const SECTION_DEPENDENCIES: Record<AiReviewSectionType, AiReviewSectionType[]> = {
|
|
||||||
students: [],
|
|
||||||
rooms: [],
|
|
||||||
transfers: ['students', 'rooms'],
|
|
||||||
checkins: [],
|
|
||||||
};
|
|
||||||
|
|
||||||
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';
|
|
||||||
}
|
|
||||||
|
|
||||||
function sectionCount(section: AiReviewSection): number {
|
|
||||||
return section.rows.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
function sectionStatus(section: AiReviewSection): AiReviewSectionStatus {
|
|
||||||
return section.status ?? 'pending';
|
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
const SECTION_STATUS_LABELS: Record<AiReviewSectionStatus, string> = {
|
|
||||||
pending: '待确认',
|
|
||||||
submitted: '已导入',
|
|
||||||
failed: '失败',
|
|
||||||
skipped: '已跳过',
|
|
||||||
};
|
|
||||||
|
|
||||||
type GroupStatus = 'pending' | 'partial' | 'submitted' | 'failed' | 'importing';
|
|
||||||
|
|
||||||
const GROUP_STATUS_LABELS: Record<GroupStatus, string> = {
|
|
||||||
pending: '待确认',
|
|
||||||
partial: '部分完成',
|
|
||||||
submitted: '已导入',
|
|
||||||
failed: '失败',
|
|
||||||
importing: '导入中',
|
|
||||||
};
|
|
||||||
|
|
||||||
function groupSections(
|
|
||||||
sections: AiReviewSection[],
|
|
||||||
type: AiReviewSectionType,
|
|
||||||
): AiReviewSection[] {
|
|
||||||
return sections.filter((section) => sectionType(section) === type);
|
|
||||||
}
|
|
||||||
|
|
||||||
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';
|
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
function errorMessage(reason: unknown): string {
|
function errorMessage(reason: unknown): string {
|
||||||
if (reason instanceof Error) return reason.message;
|
if (reason instanceof Error) return reason.message;
|
||||||
if (reason && typeof reason === 'object' && 'message' in reason) {
|
if (reason && typeof reason === 'object' && 'message' in reason) {
|
||||||
@@ -188,7 +89,14 @@ function SectionTable({ section }: { section: AiReviewSection }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface ReviewPreviewProps {
|
interface ReviewPreviewProps {
|
||||||
review?: AiReviewSchema;
|
review?: AiReviewSchema & {
|
||||||
|
submitting?: boolean;
|
||||||
|
activeKey?: string;
|
||||||
|
activeType?: AiReviewSectionType;
|
||||||
|
submittingKey?: string | null;
|
||||||
|
submittingGroup?: boolean;
|
||||||
|
error?: string | null;
|
||||||
|
};
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
onAction?: (name: string, context: Record<string, unknown>) => void;
|
onAction?: (name: string, context: Record<string, unknown>) => void;
|
||||||
}
|
}
|
||||||
@@ -197,27 +105,19 @@ const ReviewPreview: React.FC<ReviewPreviewProps> = ({ review, disabled, onActio
|
|||||||
if (!review) return null;
|
if (!review) return null;
|
||||||
const submitted = review.status === 'submitted';
|
const submitted = review.status === 'submitted';
|
||||||
const expired = review.status === 'expired';
|
const expired = review.status === 'expired';
|
||||||
const runtime = review as unknown as {
|
const submitting = Boolean(review.submitting);
|
||||||
submitting?: boolean;
|
const submittingKey = review.submittingKey ?? null;
|
||||||
activeKey?: string;
|
const submittingGroup = Boolean(review.submittingGroup);
|
||||||
activeType?: string;
|
|
||||||
submittingKey?: string | null;
|
|
||||||
submittingGroup?: boolean;
|
|
||||||
error?: string | null;
|
|
||||||
};
|
|
||||||
const submitting = Boolean(runtime.submitting);
|
|
||||||
const submittingKey = runtime.submittingKey ?? null;
|
|
||||||
const submittingGroup = Boolean(runtime.submittingGroup);
|
|
||||||
const sections = review.sections;
|
const sections = review.sections;
|
||||||
const presentTypes = SECTION_ORDER.filter((type) =>
|
const presentTypes = SECTION_ORDER.filter((type) =>
|
||||||
sections.some((section) => sectionType(section) === type),
|
sections.some((section) => sectionType(section) === type),
|
||||||
);
|
);
|
||||||
const activeType = presentTypes.includes(runtime.activeType as AiReviewSectionType)
|
const activeType = presentTypes.includes(review.activeType as AiReviewSectionType)
|
||||||
? (runtime.activeType as AiReviewSectionType)
|
? (review.activeType as AiReviewSectionType)
|
||||||
: presentTypes[0];
|
: presentTypes[0];
|
||||||
if (!activeType) return null;
|
if (!activeType) return null;
|
||||||
const activeSection =
|
const activeSection =
|
||||||
sections.find((section) => section.key === runtime.activeKey) ??
|
sections.find((section) => section.key === review.activeKey) ??
|
||||||
groupSections(sections, activeType)[0];
|
groupSections(sections, activeType)[0];
|
||||||
const activeStatus = activeSection ? sectionStatus(activeSection) : 'pending';
|
const activeStatus = activeSection ? sectionStatus(activeSection) : 'pending';
|
||||||
const dependency =
|
const dependency =
|
||||||
@@ -289,7 +189,10 @@ const ReviewPreview: React.FC<ReviewPreviewProps> = ({ review, disabled, onActio
|
|||||||
)}
|
)}
|
||||||
<Steps
|
<Steps
|
||||||
size="small"
|
size="small"
|
||||||
current={Math.max(0, typeItems.findIndex((item) => item.key === activeType))}
|
current={Math.max(
|
||||||
|
0,
|
||||||
|
typeItems.findIndex((item) => item.key === activeType),
|
||||||
|
)}
|
||||||
items={typeItems.map((item) => ({
|
items={typeItems.map((item) => ({
|
||||||
key: item.key,
|
key: item.key,
|
||||||
title: item.title,
|
title: item.title,
|
||||||
@@ -309,16 +212,18 @@ const ReviewPreview: React.FC<ReviewPreviewProps> = ({ review, disabled, onActio
|
|||||||
{SECTION_TYPE_LABELS[activeType]} · 共 {group.length} 张表 / {typeTotal} 行
|
{SECTION_TYPE_LABELS[activeType]} · 共 {group.length} 张表 / {typeTotal} 行
|
||||||
</Typography.Text>
|
</Typography.Text>
|
||||||
<Typography.Text type="secondary">
|
<Typography.Text type="secondary">
|
||||||
{GROUP_STATUS_LABELS[
|
{
|
||||||
groupStatus(sections, activeType, submittingKey, submittingGroup, activeType)
|
GROUP_STATUS_LABELS[
|
||||||
]}
|
groupStatus(sections, activeType, submittingKey, submittingGroup, activeType)
|
||||||
|
]
|
||||||
|
}
|
||||||
</Typography.Text>
|
</Typography.Text>
|
||||||
</Flex>
|
</Flex>
|
||||||
{groupDep && (
|
{groupDep && (
|
||||||
<Alert
|
<Alert
|
||||||
type="warning"
|
type="warning"
|
||||||
showIcon
|
showIcon
|
||||||
message={
|
title={
|
||||||
groupDep.step === -1
|
groupDep.step === -1
|
||||||
? `「${groupDep.title}」分表尚未生成或导入,请先确认前置步骤`
|
? `「${groupDep.title}」分表尚未生成或导入,请先确认前置步骤`
|
||||||
: `请先确认第 ${groupDep.step + 1} 步「${groupDep.title}」`
|
: `请先确认第 ${groupDep.step + 1} 步「${groupDep.title}」`
|
||||||
@@ -339,11 +244,7 @@ const ReviewPreview: React.FC<ReviewPreviewProps> = ({ review, disabled, onActio
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<Button
|
<Button type="primary" loading={submittingGroup} disabled={!groupReady}>
|
||||||
type="primary"
|
|
||||||
loading={submittingGroup}
|
|
||||||
disabled={!groupReady}
|
|
||||||
>
|
|
||||||
{groupStatus(sections, activeType, submittingKey, submittingGroup, activeType) ===
|
{groupStatus(sections, activeType, submittingKey, submittingGroup, activeType) ===
|
||||||
'submitted'
|
'submitted'
|
||||||
? '已导入'
|
? '已导入'
|
||||||
@@ -372,9 +273,7 @@ const ReviewPreview: React.FC<ReviewPreviewProps> = ({ review, disabled, onActio
|
|||||||
wrap
|
wrap
|
||||||
gap={8}
|
gap={8}
|
||||||
className="ai-chat-review-card__sheet"
|
className="ai-chat-review-card__sheet"
|
||||||
onClick={() =>
|
onClick={() => onAction?.('review:selectStep', { sectionKey: section.key })}
|
||||||
onAction?.('review:selectStep', { sectionKey: section.key })
|
|
||||||
}
|
|
||||||
>
|
>
|
||||||
<Flex vertical gap={2} style={{ minWidth: 160 }}>
|
<Flex vertical gap={2} style={{ minWidth: 160 }}>
|
||||||
<Typography.Text>
|
<Typography.Text>
|
||||||
@@ -419,7 +318,7 @@ const ReviewPreview: React.FC<ReviewPreviewProps> = ({ review, disabled, onActio
|
|||||||
<Alert
|
<Alert
|
||||||
type="warning"
|
type="warning"
|
||||||
showIcon
|
showIcon
|
||||||
message={`${activeSection.title}:${activeSection.issues.length} 条待处理`}
|
title={`${activeSection.title}:${activeSection.issues.length} 条待处理`}
|
||||||
description={
|
description={
|
||||||
<ul className="ai-chat-review__issues">
|
<ul className="ai-chat-review__issues">
|
||||||
{activeSection.issues.slice(0, 20).map((issue, issueIndex) => (
|
{activeSection.issues.slice(0, 20).map((issue, issueIndex) => (
|
||||||
@@ -434,7 +333,7 @@ const ReviewPreview: React.FC<ReviewPreviewProps> = ({ review, disabled, onActio
|
|||||||
<Alert
|
<Alert
|
||||||
type="warning"
|
type="warning"
|
||||||
showIcon
|
showIcon
|
||||||
message={
|
title={
|
||||||
dependency.step === -1
|
dependency.step === -1
|
||||||
? `「${dependency.title}」分表尚未生成或导入,请先确认前置步骤`
|
? `「${dependency.title}」分表尚未生成或导入,请先确认前置步骤`
|
||||||
: `请先确认第 ${dependency.step + 1} 步「${dependency.title}」`
|
: `请先确认第 ${dependency.step + 1} 步「${dependency.title}」`
|
||||||
@@ -453,7 +352,13 @@ const ReviewPreview: React.FC<ReviewPreviewProps> = ({ review, disabled, onActio
|
|||||||
)}
|
)}
|
||||||
</Flex>
|
</Flex>
|
||||||
)}
|
)}
|
||||||
<Flex justify="space-between" align="center" wrap gap={8} className="ai-chat-review-card__footer">
|
<Flex
|
||||||
|
justify="space-between"
|
||||||
|
align="center"
|
||||||
|
wrap
|
||||||
|
gap={8}
|
||||||
|
className="ai-chat-review-card__footer"
|
||||||
|
>
|
||||||
<Typography.Text type="secondary">
|
<Typography.Text type="secondary">
|
||||||
共 {allRows} 行,含 {allIssues.length} 条提示
|
共 {allRows} 行,含 {allIssues.length} 条提示
|
||||||
</Typography.Text>
|
</Typography.Text>
|
||||||
@@ -466,22 +371,18 @@ const ReviewPreview: React.FC<ReviewPreviewProps> = ({ review, disabled, onActio
|
|||||||
disabled={submitting || anyRunning || disabled}
|
disabled={submitting || anyRunning || disabled}
|
||||||
onConfirm={() => onAction?.('review:submit', { reviewId: review.id })}
|
onConfirm={() => onAction?.('review:submit', { reviewId: review.id })}
|
||||||
>
|
>
|
||||||
<Button
|
<Button type="primary" loading={submitting} disabled={disabled || anyRunning}>
|
||||||
type="primary"
|
|
||||||
loading={submitting}
|
|
||||||
disabled={disabled || anyRunning}
|
|
||||||
>
|
|
||||||
全部确认并入库
|
全部确认并入库
|
||||||
</Button>
|
</Button>
|
||||||
</Popconfirm>
|
</Popconfirm>
|
||||||
)}
|
)}
|
||||||
</Flex>
|
</Flex>
|
||||||
{submitted && <Alert type="success" showIcon message="已确认导入,数据已入库" />}
|
{submitted && <Alert type="success" showIcon message="已确认导入,数据已入库" />}
|
||||||
{runtime.error && (
|
{review.error && (
|
||||||
<Alert
|
<Alert
|
||||||
type="error"
|
type="error"
|
||||||
showIcon
|
showIcon
|
||||||
message={runtime.error}
|
title={review.error}
|
||||||
className="ai-chat-review-card__step-error"
|
className="ai-chat-review-card__step-error"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -525,6 +426,8 @@ export const DynamicReview: React.FC<DynamicReviewProps> = ({
|
|||||||
const [submittingGroup, setSubmittingGroup] = useState(false);
|
const [submittingGroup, setSubmittingGroup] = useState(false);
|
||||||
const [activeKey, setActiveKey] = useState<string | undefined>(undefined);
|
const [activeKey, setActiveKey] = useState<string | undefined>(undefined);
|
||||||
const [activeType, setActiveType] = useState<AiReviewSectionType | 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 [localReview, setLocalReview] = useState<AiReviewSchema>(review);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const commandsRef = useRef<XAgentCommand_v0_9[]>([]);
|
const commandsRef = useRef<XAgentCommand_v0_9[]>([]);
|
||||||
@@ -537,7 +440,9 @@ export const DynamicReview: React.FC<DynamicReviewProps> = ({
|
|||||||
review.sections.some((section) => sectionType(section) === type),
|
review.sections.some((section) => sectionType(section) === type),
|
||||||
);
|
);
|
||||||
const preferredType =
|
const preferredType =
|
||||||
activeType && types.includes(activeType) ? activeType : types[0];
|
activeTypeRef.current && types.includes(activeTypeRef.current)
|
||||||
|
? activeTypeRef.current
|
||||||
|
: types[0];
|
||||||
setActiveType(preferredType);
|
setActiveType(preferredType);
|
||||||
setActiveKey((current) =>
|
setActiveKey((current) =>
|
||||||
current &&
|
current &&
|
||||||
@@ -547,7 +452,7 @@ export const DynamicReview: React.FC<DynamicReviewProps> = ({
|
|||||||
? current
|
? current
|
||||||
: review.sections.find((section) => sectionType(section) === preferredType)?.key,
|
: review.sections.find((section) => sectionType(section) === preferredType)?.key,
|
||||||
);
|
);
|
||||||
}, [activeType, review]);
|
}, [review]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const sid = surfaceId(localReview.id);
|
const sid = surfaceId(localReview.id);
|
||||||
@@ -593,7 +498,16 @@ export const DynamicReview: React.FC<DynamicReviewProps> = ({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
setCommands([...cmds]);
|
setCommands([...cmds]);
|
||||||
}, [activeKey, activeType, disabled, error, localReview, submitting, submittingGroup, submittingKey]);
|
}, [
|
||||||
|
activeKey,
|
||||||
|
activeType,
|
||||||
|
disabled,
|
||||||
|
error,
|
||||||
|
localReview,
|
||||||
|
submitting,
|
||||||
|
submittingGroup,
|
||||||
|
submittingKey,
|
||||||
|
]);
|
||||||
|
|
||||||
const handleSubmit = async (reviewId: string) => {
|
const handleSubmit = async (reviewId: string) => {
|
||||||
if (submitting) return;
|
if (submitting) return;
|
||||||
@@ -639,8 +553,7 @@ export const DynamicReview: React.FC<DynamicReviewProps> = ({
|
|||||||
const handleAction = (payload: ActionPayload) => {
|
const handleAction = (payload: ActionPayload) => {
|
||||||
const context = payload.context ?? {};
|
const context = payload.context ?? {};
|
||||||
if (payload.name === 'review:submit') {
|
if (payload.name === 'review:submit') {
|
||||||
const reviewId =
|
const reviewId = typeof context.reviewId === 'string' ? context.reviewId : localReview.id;
|
||||||
typeof context.reviewId === 'string' ? context.reviewId : localReview.id;
|
|
||||||
void handleSubmit(reviewId);
|
void handleSubmit(reviewId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -648,33 +561,27 @@ export const DynamicReview: React.FC<DynamicReviewProps> = ({
|
|||||||
const type = context.type as AiReviewSectionType | undefined;
|
const type = context.type as AiReviewSectionType | undefined;
|
||||||
if (type && SECTION_ORDER.includes(type)) {
|
if (type && SECTION_ORDER.includes(type)) {
|
||||||
setActiveType(type);
|
setActiveType(type);
|
||||||
setActiveKey(
|
setActiveKey(localReview.sections.find((section) => sectionType(section) === type)?.key);
|
||||||
localReview.sections.find((section) => sectionType(section) === type)?.key,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (payload.name === 'review:selectStep') {
|
if (payload.name === 'review:selectStep') {
|
||||||
if (typeof context.sectionKey === 'string') {
|
if (typeof context.sectionKey === 'string') {
|
||||||
const section = localReview.sections.find(
|
const section = localReview.sections.find((item) => item.key === context.sectionKey);
|
||||||
(item) => item.key === context.sectionKey,
|
|
||||||
);
|
|
||||||
setActiveKey(context.sectionKey);
|
setActiveKey(context.sectionKey);
|
||||||
if (section) setActiveType(sectionType(section));
|
if (section) setActiveType(sectionType(section));
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (payload.name === 'review:confirmStep') {
|
if (payload.name === 'review:confirmStep') {
|
||||||
const reviewId =
|
const reviewId = typeof context.reviewId === 'string' ? context.reviewId : localReview.id;
|
||||||
typeof context.reviewId === 'string' ? context.reviewId : localReview.id;
|
|
||||||
if (typeof context.sectionKey === 'string') {
|
if (typeof context.sectionKey === 'string') {
|
||||||
void handleConfirmStep(reviewId, context.sectionKey);
|
void handleConfirmStep(reviewId, context.sectionKey);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (payload.name === 'review:confirmGroup') {
|
if (payload.name === 'review:confirmGroup') {
|
||||||
const reviewId =
|
const reviewId = typeof context.reviewId === 'string' ? context.reviewId : localReview.id;
|
||||||
typeof context.reviewId === 'string' ? context.reviewId : localReview.id;
|
|
||||||
const type = context.type as AiReviewSectionType | undefined;
|
const type = context.type as AiReviewSectionType | undefined;
|
||||||
if (type && SECTION_ORDER.includes(type)) {
|
if (type && SECTION_ORDER.includes(type)) {
|
||||||
void handleConfirmGroup(reviewId, type);
|
void handleConfirmGroup(reviewId, type);
|
||||||
@@ -684,16 +591,10 @@ export const DynamicReview: React.FC<DynamicReviewProps> = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="ai-chat-review">
|
<div className="ai-chat-review">
|
||||||
<XCard.Box
|
<XCard.Box components={{ ReviewPreview }} commands={commands} onAction={handleAction}>
|
||||||
components={{ ReviewPreview }}
|
|
||||||
commands={commands}
|
|
||||||
onAction={handleAction}
|
|
||||||
>
|
|
||||||
<XCard.Card id={surfaceId(localReview.id)} />
|
<XCard.Card id={surfaceId(localReview.id)} />
|
||||||
</XCard.Box>
|
</XCard.Box>
|
||||||
{error && <Alert type="error" showIcon message={error} className="ai-chat-review__error" />}
|
{error && <Alert type="error" showIcon title={error} className="ai-chat-review__error" />}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default DynamicReview;
|
|
||||||
|
|||||||
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" />;
|
||||||
|
}
|
||||||
@@ -3,7 +3,6 @@ import type {
|
|||||||
AiApiResponse,
|
AiApiResponse,
|
||||||
AiAttachment,
|
AiAttachment,
|
||||||
AiConversation,
|
AiConversation,
|
||||||
AiMessageFeedback,
|
|
||||||
AiMessagePage,
|
AiMessagePage,
|
||||||
AiReviewSchema,
|
AiReviewSchema,
|
||||||
AiReviewSection,
|
AiReviewSection,
|
||||||
@@ -15,8 +14,7 @@ const basePath = '/ai/chat/conversations';
|
|||||||
|
|
||||||
export const aiChatApi = {
|
export const aiChatApi = {
|
||||||
listSkills: async () => (await api.get<AiApiResponse<AiSkill[]>>('/ai/chat/skills')).data,
|
listSkills: async () => (await api.get<AiApiResponse<AiSkill[]>>('/ai/chat/skills')).data,
|
||||||
listConversations: async () =>
|
listConversations: async () => (await api.get<AiApiResponse<AiConversation[]>>(basePath)).data,
|
||||||
(await api.get<AiApiResponse<AiConversation[]>>(basePath)).data,
|
|
||||||
createConversation: async (input?: { title?: string; lockedSkillKey?: string | null }) =>
|
createConversation: async (input?: { title?: string; lockedSkillKey?: string | null }) =>
|
||||||
(await api.post<AiApiResponse<AiConversation>>(basePath, input ?? {})).data,
|
(await api.post<AiApiResponse<AiConversation>>(basePath, input ?? {})).data,
|
||||||
updateConversation: async (
|
updateConversation: async (
|
||||||
@@ -26,6 +24,12 @@ export const aiChatApi = {
|
|||||||
deleteConversation: (id: number) => api.delete<void>(`${basePath}/${id}`),
|
deleteConversation: (id: number) => api.delete<void>(`${basePath}/${id}`),
|
||||||
deleteAllConversations: async () =>
|
deleteAllConversations: async () =>
|
||||||
(await api.delete<{ success: boolean; data: { deleted: number } }>(basePath)).data,
|
(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> => {
|
uploadAttachment: async (file: File): Promise<AiAttachment> => {
|
||||||
const form = new FormData();
|
const form = new FormData();
|
||||||
form.append('file', file);
|
form.append('file', file);
|
||||||
@@ -37,17 +41,6 @@ export const aiChatApi = {
|
|||||||
).data;
|
).data;
|
||||||
},
|
},
|
||||||
deleteAttachment: (id: number) => api.delete<void>(`/ai/chat/attachments/${id}`),
|
deleteAttachment: (id: number) => api.delete<void>(`/ai/chat/attachments/${id}`),
|
||||||
setFeedback: async (
|
|
||||||
messageId: number,
|
|
||||||
feedback: AiMessageFeedback,
|
|
||||||
reason?: string,
|
|
||||||
) =>
|
|
||||||
(
|
|
||||||
await api.patch<AiApiResponse<{ id: number; feedback: AiMessageFeedback }>>(
|
|
||||||
`/ai/chat/messages/${messageId}/feedback`,
|
|
||||||
{ feedback, reason },
|
|
||||||
)
|
|
||||||
).data,
|
|
||||||
confirmReviewStep: async (
|
confirmReviewStep: async (
|
||||||
reviewId: string,
|
reviewId: string,
|
||||||
sectionKey: AiReviewSection['key'],
|
sectionKey: AiReviewSection['key'],
|
||||||
@@ -90,7 +83,3 @@ export const aiChatApi = {
|
|||||||
export function conversationStreamUrl(id: number): string {
|
export function conversationStreamUrl(id: number): string {
|
||||||
return `/api${basePath}/${id}/stream`;
|
return `/api${basePath}/${id}/stream`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function regenerateStreamUrl(conversationId: number, messageId: number): string {
|
|
||||||
return `/api${basePath}/${conversationId}/messages/${messageId}/regenerate/stream`;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ describe('AI chat history mapper', () => {
|
|||||||
status: 'completed',
|
status: 'completed',
|
||||||
errorCode: null,
|
errorCode: null,
|
||||||
createdAt: '2026-07-23T00:00:00.000Z',
|
createdAt: '2026-07-23T00:00:00.000Z',
|
||||||
feedback: 'like',
|
|
||||||
attachments: [
|
attachments: [
|
||||||
{
|
{
|
||||||
id: 8,
|
id: 8,
|
||||||
@@ -37,7 +36,6 @@ describe('AI chat history mapper', () => {
|
|||||||
expect(mapped.message.reasoningContent).toBe('思考');
|
expect(mapped.message.reasoningContent).toBe('思考');
|
||||||
expect(mapped.message.toolRuns[0].summary).toBe('共 4 间');
|
expect(mapped.message.toolRuns[0].summary).toBe('共 4 间');
|
||||||
expect(mapped.message.attachments).toHaveLength(1);
|
expect(mapped.message.attachments).toHaveLength(1);
|
||||||
expect(mapped.message.feedback).toBe('like');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('maps failed and cancelled history to X SDK statuses', () => {
|
it('maps failed and cancelled history to X SDK statuses', () => {
|
||||||
|
|||||||
@@ -65,8 +65,6 @@ export function mapHistoryMessage(record: AiMessageRecord): MessageInfo<AiChatMe
|
|||||||
reviews: historyReviews(record),
|
reviews: historyReviews(record),
|
||||||
charts: historyCharts(record),
|
charts: historyCharts(record),
|
||||||
replyToMessageId: record.replyToMessageId,
|
replyToMessageId: record.replyToMessageId,
|
||||||
feedback: record.feedback,
|
|
||||||
feedbackReason: record.feedbackReason,
|
|
||||||
metadata: record.metadata,
|
metadata: record.metadata,
|
||||||
error: record.status === 'failed' ? record.errorCode || 'AI 回答生成失败' : undefined,
|
error: record.status === 'failed' ? record.errorCode || 'AI 回答生成失败' : undefined,
|
||||||
cancelled: record.status === 'cancelled',
|
cancelled: record.status === 'cancelled',
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ describe('AI chat SSE message reducer', () => {
|
|||||||
expect(message.toolRuns[0]).toMatchObject({ status: 'success', summary: '找到 1 条记录' });
|
expect(message.toolRuns[0]).toMatchObject({ status: 'success', summary: '找到 1 条记录' });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('tracks processed attachments and final feedback state', () => {
|
it('tracks processed attachments and final message state', () => {
|
||||||
let message = reduceAiSseMessage(undefined, {
|
let message = reduceAiSseMessage(undefined, {
|
||||||
event: 'attachment.processed',
|
event: 'attachment.processed',
|
||||||
data: JSON.stringify({
|
data: JSON.stringify({
|
||||||
@@ -66,13 +66,11 @@ describe('AI chat SSE message reducer', () => {
|
|||||||
id: 12,
|
id: 12,
|
||||||
content: '完成',
|
content: '完成',
|
||||||
reasoningContent: null,
|
reasoningContent: null,
|
||||||
feedback: 'like',
|
|
||||||
attachments: message.attachments,
|
attachments: message.attachments,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
expect(message.attachments).toHaveLength(1);
|
expect(message.attachments).toHaveLength(1);
|
||||||
expect(message.feedback).toBe('like');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('uses final content and records cancellation and errors', () => {
|
it('uses final content and records cancellation and errors', () => {
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ interface AiSsePayload {
|
|||||||
form?: AiFormSchema;
|
form?: AiFormSchema;
|
||||||
review?: AiReviewSchema;
|
review?: AiReviewSchema;
|
||||||
chart?: AiChartSchema;
|
chart?: AiChartSchema;
|
||||||
|
wizard?: unknown;
|
||||||
retry?: AiModelRetryInfo;
|
retry?: AiModelRetryInfo;
|
||||||
message?:
|
message?:
|
||||||
| string
|
| string
|
||||||
@@ -46,8 +47,6 @@ interface AiSsePayload {
|
|||||||
toolRuns?: AiToolRun[];
|
toolRuns?: AiToolRun[];
|
||||||
attachments?: AiAttachment[];
|
attachments?: AiAttachment[];
|
||||||
replyToMessageId?: number | null;
|
replyToMessageId?: number | null;
|
||||||
feedback?: 'like' | 'dislike' | null;
|
|
||||||
feedbackReason?: string | null;
|
|
||||||
metadata?: Record<string, unknown> | null;
|
metadata?: Record<string, unknown> | null;
|
||||||
};
|
};
|
||||||
error?: string;
|
error?: string;
|
||||||
@@ -79,29 +78,10 @@ function mergeForms(
|
|||||||
return next;
|
return next;
|
||||||
}
|
}
|
||||||
|
|
||||||
function mergeReviews(
|
function mergeById<T extends { id: string }>(
|
||||||
current: AiReviewSchema[] | undefined,
|
current: T[] | undefined,
|
||||||
incoming: AiReviewSchema | AiReviewSchema[] | undefined,
|
incoming: T | T[] | undefined,
|
||||||
): AiReviewSchema[] {
|
): 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergeCharts(
|
|
||||||
current: AiChartSchema[] | undefined,
|
|
||||||
incoming: AiChartSchema | AiChartSchema[] | undefined,
|
|
||||||
): AiChartSchema[] {
|
|
||||||
const items = Array.isArray(incoming) ? incoming : incoming ? [incoming] : [];
|
const items = Array.isArray(incoming) ? incoming : incoming ? [incoming] : [];
|
||||||
if (!items.length) return current ?? [];
|
if (!items.length) return current ?? [];
|
||||||
const next = [...(current ?? [])];
|
const next = [...(current ?? [])];
|
||||||
@@ -165,6 +145,28 @@ function normalizeToolRuns(toolRuns: AiToolRun[] | undefined, fallback: AiToolRu
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
);
|
||||||
|
message.replyToMessageId = nested.replyToMessageId ?? message.replyToMessageId;
|
||||||
|
message.metadata = nested.metadata ?? message.metadata;
|
||||||
|
}
|
||||||
|
|
||||||
export function reduceAiSseMessage(
|
export function reduceAiSseMessage(
|
||||||
originMessage: AiChatMessage | undefined,
|
originMessage: AiChatMessage | undefined,
|
||||||
chunk?: AiSseChunk,
|
chunk?: AiSseChunk,
|
||||||
@@ -179,22 +181,7 @@ export function reduceAiSseMessage(
|
|||||||
message.reasoningContent = nested?.reasoningContent ?? message.reasoningContent;
|
message.reasoningContent = nested?.reasoningContent ?? message.reasoningContent;
|
||||||
message.toolRuns = normalizeToolRuns(nested?.toolRuns, message.toolRuns);
|
message.toolRuns = normalizeToolRuns(nested?.toolRuns, message.toolRuns);
|
||||||
message.attachments = nested?.attachments ?? message.attachments;
|
message.attachments = nested?.attachments ?? message.attachments;
|
||||||
message.forms = mergeForms(
|
applyMessagePayload(message, nested, payload);
|
||||||
message.forms,
|
|
||||||
(nested?.metadata?.a2uiForm as AiFormSchema | undefined) ?? payload.form,
|
|
||||||
);
|
|
||||||
message.reviews = mergeReviews(
|
|
||||||
message.reviews,
|
|
||||||
(nested?.metadata?.a2uiReview as AiReviewSchema | undefined) ?? payload.review,
|
|
||||||
);
|
|
||||||
message.charts = mergeCharts(
|
|
||||||
message.charts,
|
|
||||||
(nested?.metadata?.a2uiChart as AiChartSchema | AiChartSchema[] | undefined) ?? payload.chart,
|
|
||||||
);
|
|
||||||
message.replyToMessageId = nested?.replyToMessageId ?? message.replyToMessageId;
|
|
||||||
message.feedback = nested?.feedback ?? message.feedback;
|
|
||||||
message.feedbackReason = nested?.feedbackReason ?? message.feedbackReason;
|
|
||||||
message.metadata = nested?.metadata ?? message.metadata;
|
|
||||||
} else if (event === 'reasoning.delta') {
|
} else if (event === 'reasoning.delta') {
|
||||||
message.retrying = null;
|
message.retrying = null;
|
||||||
message.reasoningContent += payload.delta ?? payload.reasoningContent ?? '';
|
message.reasoningContent += payload.delta ?? payload.reasoningContent ?? '';
|
||||||
@@ -206,9 +193,11 @@ export function reduceAiSseMessage(
|
|||||||
} else if (event === 'ui.form' && payload.form) {
|
} else if (event === 'ui.form' && payload.form) {
|
||||||
message.forms = mergeForms(message.forms, payload.form);
|
message.forms = mergeForms(message.forms, payload.form);
|
||||||
} else if (event === 'ui.review' && payload.review) {
|
} else if (event === 'ui.review' && payload.review) {
|
||||||
message.reviews = mergeReviews(message.reviews, payload.review);
|
message.reviews = mergeById<AiReviewSchema>(message.reviews, payload.review);
|
||||||
} else if (event === 'ui.chart' && payload.chart) {
|
} else if (event === 'ui.chart' && payload.chart) {
|
||||||
message.charts = mergeCharts(message.charts, payload.chart);
|
message.charts = mergeById<AiChartSchema>(message.charts, payload.chart);
|
||||||
|
} else if (event === 'ui.import_wizard' && payload.wizard) {
|
||||||
|
message.metadata = { ...message.metadata, a2uiImportWizard: payload.wizard };
|
||||||
} else if (event === 'tool.started') {
|
} else if (event === 'tool.started') {
|
||||||
message.toolRuns = upsertToolRun(message.toolRuns, payload, 'running');
|
message.toolRuns = upsertToolRun(message.toolRuns, payload, 'running');
|
||||||
} else if (event === 'tool.completed') {
|
} else if (event === 'tool.completed') {
|
||||||
@@ -227,22 +216,7 @@ export function reduceAiSseMessage(
|
|||||||
nested?.reasoningContent ?? payload.reasoningContent ?? message.reasoningContent;
|
nested?.reasoningContent ?? payload.reasoningContent ?? message.reasoningContent;
|
||||||
message.toolRuns = normalizeToolRuns(nested?.toolRuns, message.toolRuns);
|
message.toolRuns = normalizeToolRuns(nested?.toolRuns, message.toolRuns);
|
||||||
message.attachments = nested?.attachments ?? message.attachments;
|
message.attachments = nested?.attachments ?? message.attachments;
|
||||||
message.forms = mergeForms(
|
applyMessagePayload(message, nested, payload);
|
||||||
message.forms,
|
|
||||||
(nested?.metadata?.a2uiForm as AiFormSchema | undefined) ?? payload.form,
|
|
||||||
);
|
|
||||||
message.reviews = mergeReviews(
|
|
||||||
message.reviews,
|
|
||||||
(nested?.metadata?.a2uiReview as AiReviewSchema | undefined) ?? payload.review,
|
|
||||||
);
|
|
||||||
message.charts = mergeCharts(
|
|
||||||
message.charts,
|
|
||||||
(nested?.metadata?.a2uiChart as AiChartSchema | AiChartSchema[] | undefined) ?? payload.chart,
|
|
||||||
);
|
|
||||||
message.replyToMessageId = nested?.replyToMessageId ?? message.replyToMessageId;
|
|
||||||
message.feedback = nested?.feedback ?? message.feedback;
|
|
||||||
message.feedbackReason = nested?.feedbackReason ?? message.feedbackReason;
|
|
||||||
message.metadata = nested?.metadata ?? message.metadata;
|
|
||||||
message.retrying = null;
|
message.retrying = null;
|
||||||
} else if (event === 'message.cancelled') {
|
} else if (event === 'message.cancelled') {
|
||||||
message.id = payload.messageId ?? message.id;
|
message.id = payload.messageId ?? message.id;
|
||||||
@@ -280,6 +254,16 @@ export async function authenticatedFetch(
|
|||||||
reasoningEffort: body.reasoningEffort,
|
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) {
|
} else if (body.formSubmission) {
|
||||||
requestInput = `${String(input).replace(/\/conversations\/\d+\/stream$/, '')}/forms/${body.formSubmission.formId}/submit/stream`;
|
requestInput = `${String(input).replace(/\/conversations\/\d+\/stream$/, '')}/forms/${body.formSubmission.formId}/submit/stream`;
|
||||||
requestInit = {
|
requestInit = {
|
||||||
@@ -304,6 +288,7 @@ export async function authenticatedFetch(
|
|||||||
localAttachments: _localAttachments,
|
localAttachments: _localAttachments,
|
||||||
reloadMessage: _reloadMessage,
|
reloadMessage: _reloadMessage,
|
||||||
regenerateMessageId: _regenerateMessageId,
|
regenerateMessageId: _regenerateMessageId,
|
||||||
|
editMessageId: _editMessageId,
|
||||||
formSubmission: _formSubmission,
|
formSubmission: _formSubmission,
|
||||||
reviewSubmission: _reviewSubmission,
|
reviewSubmission: _reviewSubmission,
|
||||||
...payload
|
...payload
|
||||||
@@ -331,10 +316,7 @@ export class GongxueAiChatProvider extends AbstractChatProvider<
|
|||||||
/** Routes events that target another (already streamed) message. */
|
/** Routes events that target another (already streamed) message. */
|
||||||
onExternalReview?: (messageId: number, review: AiReviewSchema) => void;
|
onExternalReview?: (messageId: number, review: AiReviewSchema) => void;
|
||||||
|
|
||||||
constructor(
|
constructor(url: string, onSettled?: (result?: { ok: boolean; aborted?: boolean }) => void) {
|
||||||
url: string,
|
|
||||||
onSettled?: (result?: { ok: boolean; aborted?: boolean }) => void,
|
|
||||||
) {
|
|
||||||
super({
|
super({
|
||||||
request: XRequest<AiChatInput, AiSseChunk, AiChatMessage>(url, {
|
request: XRequest<AiChatInput, AiSseChunk, AiChatMessage>(url, {
|
||||||
manual: true,
|
manual: true,
|
||||||
@@ -369,11 +351,16 @@ export class GongxueAiChatProvider extends AbstractChatProvider<
|
|||||||
formSubmission: requestParams.formSubmission,
|
formSubmission: requestParams.formSubmission,
|
||||||
reviewSubmission: requestParams.reviewSubmission,
|
reviewSubmission: requestParams.reviewSubmission,
|
||||||
regenerateMessageId: requestParams.regenerateMessageId,
|
regenerateMessageId: requestParams.regenerateMessageId,
|
||||||
|
editMessageId: requestParams.editMessageId,
|
||||||
reloadMessage: requestParams.reloadMessage,
|
reloadMessage: requestParams.reloadMessage,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
transformLocalMessage(requestParams: Partial<AiChatInput>): AiChatMessage {
|
transformLocalMessage(requestParams: Partial<AiChatInput>): AiChatMessage | AiChatMessage[] {
|
||||||
|
if (requestParams.editMessageId) {
|
||||||
|
// 编辑消息不需要新增用户气泡,store 里已原位更新原消息。
|
||||||
|
return [];
|
||||||
|
}
|
||||||
if (requestParams.formSubmission) {
|
if (requestParams.formSubmission) {
|
||||||
return {
|
return {
|
||||||
role: 'user',
|
role: 'user',
|
||||||
|
|||||||
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;
|
||||||
|
}
|
||||||
@@ -207,10 +207,68 @@
|
|||||||
padding: 20px clamp(16px, 4vw, 48px);
|
padding: 20px clamp(16px, 4vw, 48px);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.ai-chat-messages .ant-bubble {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
.ai-chat-messages .ant-bubble-content {
|
.ai-chat-messages .ant-bubble-content {
|
||||||
max-width: min(100%, 680px);
|
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 {
|
.ai-chat-user-text {
|
||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
overflow-wrap: anywhere;
|
overflow-wrap: anywhere;
|
||||||
@@ -221,6 +279,10 @@
|
|||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.ai-chat-user-edit {
|
||||||
|
width: min(520px, 100%);
|
||||||
|
}
|
||||||
|
|
||||||
.ai-chat-answer {
|
.ai-chat-answer {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
|
|||||||
@@ -98,6 +98,23 @@ export interface AiChartSchema {
|
|||||||
rows: AiReviewRow[];
|
rows: AiReviewRow[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 =
|
export type AiToolRunStatus =
|
||||||
| 'running'
|
| 'running'
|
||||||
| 'success'
|
| 'success'
|
||||||
@@ -126,7 +143,6 @@ export interface AiModelRetryInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type AiMessageRole = 'user' | 'assistant';
|
export type AiMessageRole = 'user' | 'assistant';
|
||||||
export type AiMessageFeedback = 'like' | 'dislike' | null;
|
|
||||||
|
|
||||||
export interface AiChatMessage {
|
export interface AiChatMessage {
|
||||||
id?: number | string;
|
id?: number | string;
|
||||||
@@ -139,8 +155,6 @@ export interface AiChatMessage {
|
|||||||
reviews?: AiReviewSchema[];
|
reviews?: AiReviewSchema[];
|
||||||
charts?: AiChartSchema[];
|
charts?: AiChartSchema[];
|
||||||
replyToMessageId?: number | null;
|
replyToMessageId?: number | null;
|
||||||
feedback?: AiMessageFeedback;
|
|
||||||
feedbackReason?: string | null;
|
|
||||||
metadata?: Record<string, unknown> | null;
|
metadata?: Record<string, unknown> | null;
|
||||||
retrying?: AiModelRetryInfo | null;
|
retrying?: AiModelRetryInfo | null;
|
||||||
error?: string;
|
error?: string;
|
||||||
@@ -155,8 +169,6 @@ export interface AiMessageRecord {
|
|||||||
status: 'pending' | 'completed' | 'failed' | 'cancelled';
|
status: 'pending' | 'completed' | 'failed' | 'cancelled';
|
||||||
errorCode: string | null;
|
errorCode: string | null;
|
||||||
replyToMessageId?: number | null;
|
replyToMessageId?: number | null;
|
||||||
feedback?: AiMessageFeedback;
|
|
||||||
feedbackReason?: string | null;
|
|
||||||
metadata?: Record<string, unknown> | null;
|
metadata?: Record<string, unknown> | null;
|
||||||
attachments?: AiAttachment[];
|
attachments?: AiAttachment[];
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
@@ -176,6 +188,7 @@ export interface AiChatInput {
|
|||||||
skillKey: string | null;
|
skillKey: string | null;
|
||||||
clientRequestId: string;
|
clientRequestId: string;
|
||||||
reasoningEffort?: string | null;
|
reasoningEffort?: string | null;
|
||||||
|
editMessageId?: number;
|
||||||
localAttachments?: AiAttachment[];
|
localAttachments?: AiAttachment[];
|
||||||
formSubmission?: {
|
formSubmission?: {
|
||||||
formId: string;
|
formId: string;
|
||||||
|
|||||||
574
apps/admin/src/components/AiChat/useAiChatMessageActions.tsx
Normal file
574
apps/admin/src/components/AiChat/useAiChatMessageActions.tsx
Normal file
@@ -0,0 +1,574 @@
|
|||||||
|
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 {
|
||||||
|
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, 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],
|
||||||
|
);
|
||||||
|
|
||||||
|
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,5 +1,5 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Navigate } from 'react-router-dom';
|
import { Navigate } from 'react-router';
|
||||||
import { Result, Spin } 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';
|
||||||
@@ -7,10 +7,10 @@ import { useUserStore } from '../store/user/userStore';
|
|||||||
|
|
||||||
const DefaultRoute: React.FC = () => {
|
const DefaultRoute: React.FC = () => {
|
||||||
const { permissions, permissionsReady } = usePermission();
|
const { permissions, permissionsReady } = usePermission();
|
||||||
|
const roles = useUserStore((state) => state.user?.roles ?? []);
|
||||||
if (!permissionsReady) {
|
if (!permissionsReady) {
|
||||||
return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;
|
return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;
|
||||||
}
|
}
|
||||||
const roles = useUserStore((state) => state.user?.roles ?? []);
|
|
||||||
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,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) {
|
||||||
@@ -112,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]);
|
||||||
|
|
||||||
@@ -199,6 +197,7 @@ 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);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
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, sheet: sheetSelection[activeStepKey]?.[0] }],
|
||||||
|
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
|
||||||
|
message="上传 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 message="全部阶段已提交完成" />
|
||||||
|
<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 message="当前没有可处理的阶段" />
|
||||||
|
)}
|
||||||
|
</Space>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
};
|
||||||
122
apps/admin/src/components/ImportWizard/types.ts
Normal file
122
apps/admin/src/components/ImportWizard/types.ts
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
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[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImportStageRequest {
|
||||||
|
stepKey: ImportStepKey;
|
||||||
|
sheet?: 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,310 +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 { usePermission } from '../hooks/usePermission';
|
||||||
import PermissionButton from './PermissionButton';
|
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;
|
||||||
@@ -318,7 +36,6 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
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();
|
||||||
@@ -326,40 +43,35 @@ 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 && canEnterModal) loadRules();
|
refetch: refetchRules,
|
||||||
}, [open, canEnterModal]);
|
} = useQuery<MatchRule[]>({
|
||||||
|
queryKey: ['sync', 'jinshuju', 'rules'],
|
||||||
// Close and reset when permission is lost
|
enabled: open && canEnterModal,
|
||||||
const enteredRef = useRef(false);
|
queryFn: async () => {
|
||||||
useEffect(() => {
|
try {
|
||||||
if (canEnterModal) {
|
const res = await api.get<{ success: boolean; data: MatchRule[] }>(
|
||||||
enteredRef.current = true;
|
'/sync/jinshuju/rules',
|
||||||
return;
|
);
|
||||||
}
|
return res.success ? validateResponse<MatchRule[]>(jinshujuRulesSchema, res.data) : [];
|
||||||
if (enteredRef.current) {
|
} catch {
|
||||||
enteredRef.current = false;
|
return [];
|
||||||
reset();
|
}
|
||||||
onClose();
|
},
|
||||||
}
|
});
|
||||||
}, [canEnterModal, onClose]);
|
const loadRules = useCallback(() => refetchRules(), [refetchRules]);
|
||||||
|
const deleteRuleMutation = useApiMutation(
|
||||||
const loadRules = async () => {
|
async (id: number) => api.delete(`/sync/jinshuju/rules/${id}`),
|
||||||
try {
|
{ invalidate: [['sync', 'jinshuju', 'rules']] },
|
||||||
const res = await api.get<{ success: boolean; data: MatchRule[] }>('/sync/jinshuju/rules');
|
);
|
||||||
if (res.success) setRules(res.data);
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleConnectionNext = async () => {
|
const handleConnectionNext = async () => {
|
||||||
if (!canTriggerSync) return;
|
if (!canTriggerSync) return;
|
||||||
@@ -471,7 +183,9 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
|
|
||||||
const getDecision = (serial: number): MatchDecision | undefined => decisions.get(serial);
|
const getDecision = (serial: number): MatchDecision | undefined => decisions.get(serial);
|
||||||
const setDecision = (serial: number, d: MatchDecision) =>
|
const setDecision = (serial: number, d: MatchDecision) =>
|
||||||
setDecisions((prev) => new Map(prev).set(serial, d));
|
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;
|
||||||
|
|
||||||
@@ -566,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)}
|
||||||
/>
|
/>
|
||||||
@@ -579,128 +296,31 @@ 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
|
entries={entries}
|
||||||
style={{
|
studentOptions={studentOptions}
|
||||||
marginBottom: 12,
|
getDecision={getDecision}
|
||||||
display: 'flex',
|
onDecisionChange={setDecision}
|
||||||
justifyContent: 'space-between',
|
onClear={() => setDecisions(new Map())}
|
||||||
alignItems: 'center',
|
leftRef={leftRef}
|
||||||
}}
|
rightRef={rightRef}
|
||||||
>
|
onScroll={handleScroll}
|
||||||
<Text type="secondary">
|
total={total}
|
||||||
共 {total} 条,已匹配 {matched} 条
|
matched={matched}
|
||||||
</Text>
|
/>
|
||||||
<Button size="small" onClick={() => setDecisions(new Map())}>
|
|
||||||
清除全部匹配
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<div style={{ display: 'flex', position: 'relative' }}>
|
|
||||||
<svg
|
|
||||||
style={{
|
|
||||||
position: 'absolute',
|
|
||||||
top: 0,
|
|
||||||
left: 0,
|
|
||||||
width: LEFT_WIDTH + GAP,
|
|
||||||
height: svgHeight,
|
|
||||||
pointerEvents: 'none',
|
|
||||||
zIndex: 1,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{lines}
|
|
||||||
</svg>
|
|
||||||
<div
|
|
||||||
ref={leftRef}
|
|
||||||
onScroll={() => handleScroll('left')}
|
|
||||||
style={{ width: LEFT_WIDTH, maxHeight: 480, overflowY: 'auto', flexShrink: 0 }}
|
|
||||||
>
|
|
||||||
{entries.map((entry, i) => {
|
|
||||||
const d = getDecision(entry.serialNumber);
|
|
||||||
const isMatched = d?.action === 'match';
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={entry.serialNumber}
|
|
||||||
style={{
|
|
||||||
height: ROW_HEIGHT,
|
|
||||||
padding: '8px 12px',
|
|
||||||
borderBottom: '1px solid #f0f0f0',
|
|
||||||
display: 'flex',
|
|
||||||
flexDirection: 'column',
|
|
||||||
justifyContent: 'center',
|
|
||||||
background: isMatched ? '#f6ffed' : i % 2 === 0 ? '#fafafa' : '#fff',
|
|
||||||
borderLeft: isMatched ? '3px solid #1677ff' : '3px solid transparent',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Text strong style={{ fontSize: 13 }}>
|
|
||||||
{entry.name || <Text type="secondary">无姓名</Text>}
|
|
||||||
</Text>
|
|
||||||
{entry.phone && (
|
|
||||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
|
||||||
{entry.phone}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
<Text type="secondary" style={{ fontSize: 11 }}>
|
|
||||||
#{entry.serialNumber}
|
|
||||||
</Text>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
<div style={{ width: GAP, flexShrink: 0 }} />
|
|
||||||
<div
|
|
||||||
ref={rightRef}
|
|
||||||
onScroll={() => handleScroll('right')}
|
|
||||||
style={{ flex: 1, maxHeight: 480, overflowY: 'auto' }}
|
|
||||||
>
|
|
||||||
{entries.map((entry) => (
|
|
||||||
<div
|
|
||||||
key={entry.serialNumber}
|
|
||||||
style={{
|
|
||||||
height: ROW_HEIGHT,
|
|
||||||
padding: '8px 12px',
|
|
||||||
borderBottom: '1px solid #f0f0f0',
|
|
||||||
display: 'flex',
|
|
||||||
alignItems: 'center',
|
|
||||||
gap: 8,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<MatchSelector
|
|
||||||
entry={entry}
|
|
||||||
decision={getDecision(entry.serialNumber)}
|
|
||||||
studentOptions={studentOptions}
|
|
||||||
onChange={(newD) => setDecision(entry.serialNumber, newD)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const 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 (
|
||||||
@@ -722,12 +342,7 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
]
|
]
|
||||||
: step === 'rule'
|
: step === 'rule'
|
||||||
? [
|
? [
|
||||||
<Button key="back" onClick={() => setStep('connection')}>
|
...backCancelButtons(() => setStep('connection')),
|
||||||
上一步
|
|
||||||
</Button>,
|
|
||||||
<Button key="cancel" onClick={handleClose}>
|
|
||||||
取消
|
|
||||||
</Button>,
|
|
||||||
<Button
|
<Button
|
||||||
key="next"
|
key="next"
|
||||||
type="primary"
|
type="primary"
|
||||||
@@ -740,12 +355,7 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
]
|
]
|
||||||
: step === 'match'
|
: step === 'match'
|
||||||
? [
|
? [
|
||||||
<Button key="back" onClick={() => setStep('rule')}>
|
...backCancelButtons(() => setStep('rule')),
|
||||||
上一步
|
|
||||||
</Button>,
|
|
||||||
<Button key="cancel" onClick={handleClose}>
|
|
||||||
取消
|
|
||||||
</Button>,
|
|
||||||
canTriggerSync ? (
|
canTriggerSync ? (
|
||||||
<PermissionButton
|
<PermissionButton
|
||||||
key="apply"
|
key="apply"
|
||||||
@@ -770,7 +380,7 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
|||||||
{step === 'rule' ? renderRuleStep() : null}
|
{step === 'rule' ? renderRuleStep() : null}
|
||||||
{step === 'match' ? renderMatchStep() : null}
|
{step === 'match' ? renderMatchStep() : null}
|
||||||
{step === 'applying' ? (
|
{step === 'applying' ? (
|
||||||
<Spin tip="正在同步..." style={{ display: 'block', margin: '48px auto' }} />
|
<Spin description="正在同步..." style={{ display: 'block', margin: '48px auto' }} />
|
||||||
) : null}
|
) : 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,7 +1,9 @@
|
|||||||
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';
|
import { useUserStore } from '../store/user/userStore';
|
||||||
@@ -17,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 */
|
||||||
@@ -44,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 */
|
||||||
@@ -52,7 +48,9 @@ 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(() => {
|
||||||
@@ -60,6 +58,7 @@ const NotificationBell: React.FC = () => {
|
|||||||
const token = useUserStore.getState().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);
|
||||||
@@ -70,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,6 +1,6 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Result, Button, Spin } 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';
|
import { useUserStore } from '../store/user/userStore';
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
import React, { useEffect, useMemo } 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,9 +14,8 @@ 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';
|
import { useAppStore } from '../../store';
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { act } from 'react';
|
import { act } from 'react';
|
||||||
import { createRoot } from 'react-dom/client';
|
import { createRoot } from 'react-dom/client';
|
||||||
import { MemoryRouter, Route, Routes, useNavigate } from 'react-router-dom';
|
import { MemoryRouter, Route, Routes, useNavigate } from 'react-router';
|
||||||
import { afterEach, describe, expect, it } from 'vitest';
|
import { afterEach, describe, expect, it } from 'vitest';
|
||||||
import { RouteKeeper } from './RouteKeeper';
|
import { RouteKeeper } from './RouteKeeper';
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useRef } from 'react';
|
import React, { useRef } from 'react';
|
||||||
import { useLocation, useOutlet } from 'react-router-dom';
|
import { useLocation, useOutlet } from 'react-router';
|
||||||
|
|
||||||
const MAX_CACHED_PAGES = 30;
|
const MAX_CACHED_PAGES = 30;
|
||||||
|
|
||||||
|
|||||||
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,156 @@
|
|||||||
|
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, {
|
||||||
|
headers: { 'Content-Type': 'multipart/form-data' },
|
||||||
|
}),
|
||||||
|
{ 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,5 +1,5 @@
|
|||||||
import { useCallback, useEffect, useRef } 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';
|
||||||
|
|
||||||
@@ -13,8 +13,9 @@ import { message } from '../ui/app-message';
|
|||||||
* already-open confirm modal is destroyed.
|
* already-open confirm modal is destroyed.
|
||||||
*/
|
*/
|
||||||
export function useViewSensitive(studentId: number, module: string, canLog: boolean) {
|
export function useViewSensitive(studentId: number, module: string, canLog: boolean) {
|
||||||
|
const { modal } = App.useApp();
|
||||||
const canLogRef = useRef(canLog);
|
const canLogRef = useRef(canLog);
|
||||||
const modalRef = useRef<ReturnType<typeof Modal.confirm> | null>(null);
|
const modalRef = useRef<ReturnType<typeof modal.confirm> | null>(null);
|
||||||
canLogRef.current = canLog;
|
canLogRef.current = canLog;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -31,7 +32,7 @@ export function useViewSensitive(studentId: number, module: string, canLog: bool
|
|||||||
return useCallback(
|
return useCallback(
|
||||||
(field: string, value: string) => {
|
(field: string, value: string) => {
|
||||||
if (!canLogRef.current) return;
|
if (!canLogRef.current) return;
|
||||||
modalRef.current = Modal.confirm({
|
modalRef.current = modal.confirm({
|
||||||
title: '查看敏感信息',
|
title: '查看敏感信息',
|
||||||
content: `您即将查看 "${field}" 的完整信息。此操作将被记录。`,
|
content: `您即将查看 "${field}" 的完整信息。此操作将被记录。`,
|
||||||
okText: '确认查看',
|
okText: '确认查看',
|
||||||
@@ -50,7 +51,7 @@ export function useViewSensitive(studentId: number, module: string, canLog: bool
|
|||||||
message.error('操作日志记录失败,请稍后重试');
|
message.error('操作日志记录失败,请稍后重试');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Modal.info({
|
modal.info({
|
||||||
title: field,
|
title: field,
|
||||||
content: value,
|
content: value,
|
||||||
okText: '关闭',
|
okText: '关闭',
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
|
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
|
||||||
import { useNavigate, useLocation } from 'react-router-dom';
|
import { useNavigate, useLocation } from 'react-router';
|
||||||
import { Layout, Menu, Button, Avatar, Badge, Dropdown, Drawer, Grid, Tooltip } 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,
|
||||||
@@ -262,7 +263,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>
|
||||||
@@ -275,7 +286,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>
|
||||||
|
|||||||
@@ -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,20 @@ dayjs.extend(updateLocale);
|
|||||||
// 必须在所有插件加载后设置 locale
|
// 必须在所有插件加载后设置 locale
|
||||||
dayjs.locale('zh-cn');
|
dayjs.locale('zh-cn');
|
||||||
|
|
||||||
|
const queryClient = new QueryClient({
|
||||||
|
defaultOptions: {
|
||||||
|
queries: {
|
||||||
|
retry: 1,
|
||||||
|
staleTime: 30_000,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
ReactDOM.createRoot(document.getElementById('root')!).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"
|
||||||
|
message="配置预览"
|
||||||
|
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,6 +1,4 @@
|
|||||||
// ---------------------------------------------------------------------------
|
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';
|
||||||
|
|
||||||
@@ -10,9 +8,14 @@ export const PROVIDER_OPTIONS: { value: AiProvider; label: string }[] = [
|
|||||||
{ 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,106 +1,40 @@
|
|||||||
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,
|
|
||||||
AutoComplete,
|
|
||||||
InputNumber,
|
|
||||||
Tag,
|
|
||||||
Descriptions,
|
|
||||||
Spin,
|
|
||||||
Alert,
|
|
||||||
Typography,
|
|
||||||
Space,
|
|
||||||
Steps,
|
|
||||||
Switch,
|
|
||||||
} from 'antd';
|
|
||||||
import {
|
|
||||||
SaveOutlined,
|
|
||||||
ApiOutlined,
|
|
||||||
CheckCircleOutlined,
|
|
||||||
CloseCircleOutlined,
|
|
||||||
WarningOutlined,
|
|
||||||
ReloadOutlined,
|
|
||||||
CloudServerOutlined,
|
|
||||||
SafetyOutlined,
|
|
||||||
RobotOutlined,
|
|
||||||
} 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;
|
|
||||||
supportsVision: boolean;
|
|
||||||
timeoutMs: number;
|
|
||||||
reasoningEffort: string | null;
|
|
||||||
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 FetchModelsResult {
|
|
||||||
success: boolean;
|
|
||||||
models: Array<{ id: string }>;
|
|
||||||
message?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ApiResponse<T> {
|
interface ApiResponse<T> {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
data: T;
|
data: T;
|
||||||
message?: string;
|
message?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
interface FetchModelsResult {
|
||||||
// Form state — mirrors all form fields, survives Step unmounts
|
success: boolean;
|
||||||
// ---------------------------------------------------------------------------
|
models: Array<{ id: string }>;
|
||||||
|
message?: string;
|
||||||
interface FormValues {
|
|
||||||
provider: AiProvider;
|
|
||||||
baseUrl: string;
|
|
||||||
apiKey: string;
|
|
||||||
defaultModel: string;
|
|
||||||
timeoutMs: number;
|
|
||||||
supportsVision: boolean;
|
|
||||||
reasoningEffort: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const DEFAULT_FORM_VALUES: FormValues = {
|
const DEFAULT_FORM_VALUES: FormValues = {
|
||||||
@@ -113,10 +47,6 @@ const DEFAULT_FORM_VALUES: FormValues = {
|
|||||||
reasoningEffort: '',
|
reasoningEffort: '',
|
||||||
};
|
};
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Step definitions
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
const STEP_ITEMS = [
|
const STEP_ITEMS = [
|
||||||
{ title: '服务商', description: '选择 AI 服务商' },
|
{ title: '服务商', description: '选择 AI 服务商' },
|
||||||
{ title: '密钥', description: '配置 API 密钥' },
|
{ title: '密钥', description: '配置 API 密钥' },
|
||||||
@@ -124,21 +54,15 @@ const STEP_ITEMS = [
|
|||||||
{ title: '完成', description: '保存并测试连接' },
|
{ title: '完成', description: '保存并测试连接' },
|
||||||
];
|
];
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Page Component
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
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 [currentStep, setCurrentStep] = useState(0);
|
const [currentStep, setCurrentStep] = useState(0);
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [testing, setTesting] = useState(false);
|
const [testing, setTesting] = useState(false);
|
||||||
const [fetchingModels, setFetchingModels] = useState(false);
|
const [fetchingModels, setFetchingModels] = useState(false);
|
||||||
const [config, setConfig] = useState<AiConfigData | null>(null);
|
|
||||||
const [testResult, setTestResult] = useState<TestResult | null>(null);
|
const [testResult, setTestResult] = useState<TestResult | null>(null);
|
||||||
const [modelOptions, setModelOptions] = useState<Array<{ value: string; label: string }>>([]);
|
const [modelOptions, setModelOptions] = useState<Array<{ value: string; label: string }>>([]);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -147,6 +71,39 @@ const AiConfigPage: React.FC = () => {
|
|||||||
const [formValues, setFormValues] = useState<FormValues>(DEFAULT_FORM_VALUES);
|
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');
|
||||||
@@ -154,57 +111,41 @@ const AiConfigPage: React.FC = () => {
|
|||||||
|
|
||||||
// ── Sync form → state ──
|
// ── Sync form → state ──
|
||||||
|
|
||||||
const handleFormChange = useCallback((_changed: Partial<FormValues>, all: Partial<FormValues>) => {
|
const handleFormChange = useCallback(
|
||||||
setFormValues((prev) => ({ ...prev, ...all }));
|
(_changed: Partial<FormValues>, all: Partial<FormValues>) => {
|
||||||
}, []);
|
setFormValues((prev) => ({ ...prev, ...all }));
|
||||||
|
},
|
||||||
// ── Load config (full) — used on initial mount and after save ──
|
[],
|
||||||
|
);
|
||||||
const loadConfig = useCallback(async () => {
|
|
||||||
setLoading(true);
|
|
||||||
setError(null);
|
|
||||||
try {
|
|
||||||
const res = await api.get<ApiResponse<AiConfigData>>('/ai/config');
|
|
||||||
setConfig(res.data);
|
|
||||||
|
|
||||||
const initial: FormValues = {
|
|
||||||
provider: res.data.provider,
|
|
||||||
baseUrl: res.data.baseUrl,
|
|
||||||
apiKey: '',
|
|
||||||
defaultModel: res.data.defaultModel ?? '',
|
|
||||||
timeoutMs: res.data.timeoutMs,
|
|
||||||
supportsVision: res.data.supportsVision,
|
|
||||||
reasoningEffort: res.data.reasoningEffort ?? '',
|
|
||||||
};
|
|
||||||
form.setFieldsValue(initial);
|
|
||||||
setFormValues(initial);
|
|
||||||
lastProviderRef.current = res.data.provider;
|
|
||||||
|
|
||||||
if (res.data.defaultModel) {
|
|
||||||
setModelOptions([{ value: res.data.defaultModel, label: res.data.defaultModel }]);
|
|
||||||
}
|
|
||||||
} catch (err: unknown) {
|
|
||||||
setError(extractErrorMessage(err, '加载配置失败'));
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
}, [form]);
|
|
||||||
|
|
||||||
// ── Refresh config (light) — only updates the config info display,
|
|
||||||
// does NOT touch form values. Used after test/fetch-models. ──
|
|
||||||
|
|
||||||
const refreshConfig = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
const res = await api.get<ApiResponse<AiConfigData>>('/ai/config');
|
|
||||||
setConfig(res.data);
|
|
||||||
} catch {
|
|
||||||
// silent — config display refresh is non-critical
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
|
// 配置数据到位后同步进表单(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 ──
|
||||||
|
|
||||||
@@ -243,7 +184,7 @@ const AiConfigPage: React.FC = () => {
|
|||||||
message.warning(res.message || '未获取到可用模型');
|
message.warning(res.message || '未获取到可用模型');
|
||||||
}
|
}
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
message.error(extractErrorMessage(err, '获取模型列表失败'));
|
message.error(getErrorMessage(err, '获取模型列表失败'));
|
||||||
} finally {
|
} finally {
|
||||||
setFetchingModels(false);
|
setFetchingModels(false);
|
||||||
}
|
}
|
||||||
@@ -256,8 +197,15 @@ const AiConfigPage: React.FC = () => {
|
|||||||
// Validate fields (for UI error display) — actual values come from state
|
// Validate fields (for UI error display) — actual values come from state
|
||||||
await form.validateFields(['provider', 'baseUrl', 'timeoutMs']);
|
await form.validateFields(['provider', 'baseUrl', 'timeoutMs']);
|
||||||
|
|
||||||
const { provider, baseUrl, defaultModel, apiKey, timeoutMs, supportsVision, reasoningEffort } =
|
const {
|
||||||
formValues;
|
provider,
|
||||||
|
baseUrl,
|
||||||
|
defaultModel,
|
||||||
|
apiKey,
|
||||||
|
timeoutMs,
|
||||||
|
supportsVision,
|
||||||
|
reasoningEffort,
|
||||||
|
} = formValues;
|
||||||
|
|
||||||
if (provider === 'OPENAI_COMPATIBLE' && !baseUrl) {
|
if (provider === 'OPENAI_COMPATIBLE' && !baseUrl) {
|
||||||
message.error('OPENAI_COMPATIBLE 模式必须填写 Base URL');
|
message.error('OPENAI_COMPATIBLE 模式必须填写 Base URL');
|
||||||
@@ -282,24 +230,16 @@ const AiConfigPage: React.FC = () => {
|
|||||||
body.apiKey = apiKey;
|
body.apiKey = apiKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
await api.put('/ai/config', body);
|
await saveMutation.mutateAsync(body);
|
||||||
message.success('配置已保存');
|
message.success('配置已保存');
|
||||||
form.setFieldValue('apiKey', '');
|
form.setFieldValue('apiKey', '');
|
||||||
setFormValues((prev) => ({ ...prev, apiKey: '' }));
|
setFormValues((prev) => ({ ...prev, apiKey: '' }));
|
||||||
} catch (err: unknown) {
|
} catch {
|
||||||
message.error(extractErrorMessage(err, '保存失败'));
|
// 错误提示由 useApiMutation 统一处理
|
||||||
setSaving(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await loadConfig();
|
|
||||||
} catch (err: unknown) {
|
|
||||||
message.warning(extractErrorMessage(err, '配置已保存,但刷新失败'));
|
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false);
|
setSaving(false);
|
||||||
}
|
}
|
||||||
}, [formValues, form, loadConfig]);
|
}, [formValues, form, saveMutation]);
|
||||||
|
|
||||||
// ── Test connection ──
|
// ── Test connection ──
|
||||||
|
|
||||||
@@ -331,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);
|
||||||
}
|
}
|
||||||
}, [formValues, form, loadConfig, currentProvider]);
|
}, [formValues, form, currentProvider]);
|
||||||
|
|
||||||
// ── Clear key ──
|
// ── Clear key ──
|
||||||
|
|
||||||
@@ -352,25 +292,21 @@ 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]);
|
||||||
|
|
||||||
// ── Step navigation ──
|
// ── Step navigation ──
|
||||||
|
|
||||||
const goNext = useCallback(async () => {
|
const goNext = useCallback(async () => {
|
||||||
// Validate current step fields before moving
|
|
||||||
try {
|
try {
|
||||||
if (currentStep === 0) {
|
if (currentStep === 0) {
|
||||||
await form.validateFields(['provider', 'baseUrl', 'timeoutMs']);
|
await form.validateFields(['provider', 'baseUrl', 'timeoutMs']);
|
||||||
} else if (currentStep === 1) {
|
|
||||||
// API key step — optional, no validation needed
|
|
||||||
} else if (currentStep === 2) {
|
} else if (currentStep === 2) {
|
||||||
await form.validateFields(['defaultModel']);
|
await form.validateFields(['defaultModel']);
|
||||||
}
|
}
|
||||||
@@ -410,336 +346,44 @@ const AiConfigPage: React.FC = () => {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Render step content ──
|
|
||||||
|
|
||||||
const renderStepContent = () => {
|
const renderStepContent = () => {
|
||||||
switch (currentStep) {
|
switch (currentStep) {
|
||||||
// Step 0: Provider + Base URL + Timeout
|
|
||||||
case 0:
|
case 0:
|
||||||
return (
|
return (
|
||||||
<Card
|
<ProviderStep
|
||||||
title={<span className={styles.cardTitle}>服务商配置</span>}
|
canWrite={canWrite}
|
||||||
extra={<CloudServerOutlined />}
|
isFixedProvider={isFixedProvider}
|
||||||
>
|
config={config}
|
||||||
<Form.Item
|
onProviderChange={handleProviderChange}
|
||||||
name="provider"
|
/>
|
||||||
label="Provider"
|
|
||||||
rules={[{ required: true, message: '请选择 Provider' }]}
|
|
||||||
preserve
|
|
||||||
>
|
|
||||||
<Select
|
|
||||||
options={PROVIDER_OPTIONS}
|
|
||||||
onChange={handleProviderChange}
|
|
||||||
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]
|
|
||||||
: 'https://api.deepseek.com'
|
|
||||||
}
|
|
||||||
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>
|
|
||||||
);
|
);
|
||||||
|
|
||||||
// Step 1: API Key
|
|
||||||
case 1:
|
case 1:
|
||||||
return (
|
return <KeyStep canWrite={canWrite} config={config} onClearKey={handleClearKey} />;
|
||||||
<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={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>
|
|
||||||
);
|
|
||||||
|
|
||||||
// Step 2: Model selection
|
|
||||||
case 2:
|
case 2:
|
||||||
return (
|
return (
|
||||||
<Card
|
<ModelStep
|
||||||
title={<span className={styles.cardTitle}>模型选择</span>}
|
canWrite={canWrite}
|
||||||
extra={<RobotOutlined />}
|
config={config}
|
||||||
>
|
onFetchModels={handleFetchModels}
|
||||||
<div className={styles.modelFetchRow}>
|
fetchingModels={fetchingModels}
|
||||||
<Button
|
modelOptions={modelOptions}
|
||||||
icon={<ReloadOutlined />}
|
/>
|
||||||
onClick={handleFetchModels}
|
|
||||||
loading={fetchingModels}
|
|
||||||
disabled={!canWrite}
|
|
||||||
>
|
|
||||||
获取模型列表
|
|
||||||
</Button>
|
|
||||||
{modelOptions.length > 0 && (
|
|
||||||
<Tag color="blue">{modelOptions.length} 个可用模型</Tag>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Form.Item
|
|
||||||
name="defaultModel"
|
|
||||||
label="默认模型"
|
|
||||||
rules={[{ required: true, message: '请选择或输入默认模型' }]}
|
|
||||||
style={{ marginTop: 16 }}
|
|
||||||
preserve
|
|
||||||
>
|
|
||||||
<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>
|
|
||||||
);
|
);
|
||||||
|
|
||||||
// Step 3: Save & Test
|
|
||||||
case 3:
|
case 3:
|
||||||
return (
|
return (
|
||||||
<Card
|
<SaveTestStep
|
||||||
title={<span className={styles.cardTitle}>保存并测试</span>}
|
canWrite={canWrite}
|
||||||
extra={<CheckCircleOutlined />}
|
canTest={canTest}
|
||||||
>
|
config={config}
|
||||||
<Alert
|
currentProvider={currentProvider}
|
||||||
type="info"
|
formValues={formValues}
|
||||||
message="配置预览"
|
onSave={handleSave}
|
||||||
description={
|
saving={saving}
|
||||||
<Descriptions column={1} size="small" style={{ marginTop: 8 }}>
|
onTest={handleTest}
|
||||||
<Descriptions.Item label="服务商">
|
testing={testing}
|
||||||
<Tag color="blue">
|
testResult={testResult}
|
||||||
{PROVIDER_OPTIONS.find((o) => o.value === currentProvider)?.label ??
|
/>
|
||||||
currentProvider ??
|
|
||||||
'-'}
|
|
||||||
</Tag>
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="Base URL">
|
|
||||||
<Typography.Text code>
|
|
||||||
{formValues.baseUrl || '-'}
|
|
||||||
</Typography.Text>
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="默认模型">
|
|
||||||
<Tag>{formValues.defaultModel || '未设置'}</Tag>
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="密钥">
|
|
||||||
{(() => {
|
|
||||||
const hasFormKey = formValues.apiKey && formValues.apiKey !== '••••';
|
|
||||||
if (config?.hasApiKey) {
|
|
||||||
return <Tag color="green">{config.maskedApiKey || '••••'}</Tag>;
|
|
||||||
}
|
|
||||||
if (hasFormKey) {
|
|
||||||
return <Tag color="blue">已填写(未保存)</Tag>;
|
|
||||||
}
|
|
||||||
return <Tag color="red">未配置</Tag>;
|
|
||||||
})()}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="超时">
|
|
||||||
{formValues.timeoutMs}ms
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="图片理解">
|
|
||||||
<Tag color={formValues.supportsVision ? 'blue' : 'default'}>
|
|
||||||
{formValues.supportsVision ? '已启用' : '未启用'}
|
|
||||||
</Tag>
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="状态">
|
|
||||||
<Tag color={config?.enabled ? 'green' : 'default'}>
|
|
||||||
{config?.enabled ? '已启用' : '未启用'}
|
|
||||||
</Tag>
|
|
||||||
</Descriptions.Item>
|
|
||||||
</Descriptions>
|
|
||||||
}
|
|
||||||
style={{ marginBottom: 16 }}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Space>
|
|
||||||
{canWrite && (
|
|
||||||
<Button type="primary" icon={<SaveOutlined />} onClick={handleSave} loading={saving} size="large">
|
|
||||||
保存配置
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{canTest && (
|
|
||||||
<Button icon={<ApiOutlined />} onClick={handleTest} loading={testing} size="large">
|
|
||||||
测试连接
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</Space>
|
|
||||||
|
|
||||||
{/* Test result */}
|
|
||||||
{testResult && (
|
|
||||||
<Card size="small" className={styles.testResult}>
|
|
||||||
<Descriptions column={{ xs: 1, sm: 2 }} size="small">
|
|
||||||
<Descriptions.Item label="结果">
|
|
||||||
{testResult.success ? (
|
|
||||||
testResult.modelAvailable ? (
|
|
||||||
<Tag icon={<CheckCircleOutlined />} color="success">
|
|
||||||
成功
|
|
||||||
</Tag>
|
|
||||||
) : (
|
|
||||||
<Tag icon={<WarningOutlined />} color="warning">
|
|
||||||
模型未找到
|
|
||||||
</Tag>
|
|
||||||
)
|
|
||||||
) : (
|
|
||||||
<Tag icon={<CloseCircleOutlined />} color="error">
|
|
||||||
失败
|
|
||||||
</Tag>
|
|
||||||
)}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="延迟">
|
|
||||||
{testResult.latencyMs != null ? `${testResult.latencyMs} ms` : '-'}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="模型数量">
|
|
||||||
{testResult.modelCount != null ? testResult.modelCount : '-'}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="测试时间">
|
|
||||||
{formatDateTime(testResult.testedAt)}
|
|
||||||
</Descriptions.Item>
|
|
||||||
</Descriptions>
|
|
||||||
<Alert
|
|
||||||
type={
|
|
||||||
testResult.success
|
|
||||||
? testResult.modelAvailable
|
|
||||||
? 'success'
|
|
||||||
: 'warning'
|
|
||||||
: 'error'
|
|
||||||
}
|
|
||||||
title={testResult.message}
|
|
||||||
style={{ marginTop: 8 }}
|
|
||||||
/>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
</Card>
|
|
||||||
);
|
);
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
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>;
|
||||||
|
};
|
||||||
275
apps/admin/src/pages/Attendance/AttendanceAdminHeader.tsx
Normal file
275
apps/admin/src/pages/Attendance/AttendanceAdminHeader.tsx
Normal file
@@ -0,0 +1,275 @@
|
|||||||
|
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">
|
||||||
|
<span className="student-overview-kicker">班级考勤概览</span>
|
||||||
|
<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" bordered={false} 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>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
} from './attendance-workspace';
|
} from './attendance-workspace';
|
||||||
import type { LessonAttendanceRecord, LessonAttendanceSchedule } from './types';
|
import type { LessonAttendanceRecord, LessonAttendanceSchedule } from './types';
|
||||||
import { usePermission } from '../../hooks/usePermission';
|
import { usePermission } from '../../hooks/usePermission';
|
||||||
|
import { getErrorMessage } from '../../utils/error';
|
||||||
|
|
||||||
interface LessonAttendanceSession {
|
interface LessonAttendanceSession {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -90,10 +91,6 @@ const LessonAttendanceDetail: React.FC<LessonAttendanceDetailProps> = ({
|
|||||||
if (!schedule) return;
|
if (!schedule) return;
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
setLoadedSchedule(schedule);
|
setLoadedSchedule(schedule);
|
||||||
setSession(null);
|
|
||||||
setRecords([]);
|
|
||||||
setKeyword('');
|
|
||||||
setFilter('all');
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
const date = dayjs().format('YYYY-MM-DD');
|
const date = dayjs().format('YYYY-MM-DD');
|
||||||
void api
|
void api
|
||||||
@@ -109,7 +106,7 @@ const LessonAttendanceDetail: React.FC<LessonAttendanceDetailProps> = ({
|
|||||||
})
|
})
|
||||||
.catch((error: unknown) => {
|
.catch((error: unknown) => {
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
message.error((error as { message?: string })?.message || '加载本节课考勤失败');
|
message.error(getErrorMessage(error, '加载本节课考勤失败'));
|
||||||
})
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
if (!cancelled) setLoading(false);
|
if (!cancelled) setLoading(false);
|
||||||
@@ -130,7 +127,7 @@ const LessonAttendanceDetail: React.FC<LessonAttendanceDetailProps> = ({
|
|||||||
setRecords((items) =>
|
setRecords((items) =>
|
||||||
items.map((item) => (item.id === record.id ? { ...item, status: previous } : item)),
|
items.map((item) => (item.id === record.id ? { ...item, status: previous } : item)),
|
||||||
);
|
);
|
||||||
message.error((error as { message?: string })?.message || '更新考勤失败');
|
message.error(getErrorMessage(error, '更新考勤失败'));
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
|||||||
580
apps/admin/src/pages/Attendance/admin.tsx
Normal file
580
apps/admin/src/pages/Attendance/admin.tsx
Normal file
@@ -0,0 +1,580 @@
|
|||||||
|
import React, { useCallback, useEffect, 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 {
|
||||||
|
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;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
periodForm.setFieldsValue({ periods });
|
||||||
|
}, [periods, periodForm]);
|
||||||
|
|
||||||
|
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, scheduleId],
|
||||||
|
);
|
||||||
|
|
||||||
|
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]);
|
||||||
|
|
||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -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 } 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,16 +125,15 @@ 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);
|
||||||
}
|
}
|
||||||
@@ -121,7 +153,7 @@ const BillsPage: React.FC = () => {
|
|||||||
|
|
||||||
const handleCancel = async (id: number) => {
|
const handleCancel = async (id: number) => {
|
||||||
let reason = '';
|
let reason = '';
|
||||||
Modal.confirm({
|
modal.confirm({
|
||||||
title: '取消账单并退回已扣余额',
|
title: '取消账单并退回已扣余额',
|
||||||
content: (
|
content: (
|
||||||
<Input.TextArea
|
<Input.TextArea
|
||||||
@@ -139,37 +171,49 @@ const BillsPage: React.FC = () => {
|
|||||||
message.error('请输入取消原因');
|
message.error('请输入取消原因');
|
||||||
throw new Error('reason required');
|
throw new Error('reason required');
|
||||||
}
|
}
|
||||||
await api.post(`/bills/${id}/cancel`, {
|
await cancelMutation.mutateAsync({ id, reason: reason.trim() });
|
||||||
operationId: newOperationId(),
|
|
||||||
reason: reason.trim(),
|
|
||||||
});
|
|
||||||
message.success('账单已取消,已扣余额已冲正退回');
|
message.success('账单已取消,已扣余额已冲正退回');
|
||||||
fetchData();
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleArchive = async (id: number) => {
|
const handleArchive = async (id: number) => {
|
||||||
try {
|
try {
|
||||||
await api.delete(`/bills/${id}`);
|
await archiveMutation.mutateAsync(id);
|
||||||
message.success('账单已归档');
|
message.success('账单已归档');
|
||||||
fetchData();
|
} catch {
|
||||||
} catch (error: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error(error?.message || '归档失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handlePurge = (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 统一处理
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
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);
|
||||||
}
|
}
|
||||||
@@ -216,28 +260,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 +289,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 +333,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 +380,7 @@ const BillsPage: React.FC = () => {
|
|||||||
),
|
),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
[showDetail, handleArchive, handleCancel, handleExportPdf],
|
[showDetail, handleArchive, handleCancel, handleExportPdf, canPurgeBill, handlePurge],
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -511,12 +571,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 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,155 +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 { useUserStore } from '../../store/user/userStore';
|
import { Button, Card, Form, Space, Tabs, Tag } from 'antd';
|
||||||
import {
|
import { ArrowLeftOutlined } from '@ant-design/icons';
|
||||||
Card,
|
|
||||||
Tabs,
|
|
||||||
Descriptions,
|
|
||||||
Table,
|
|
||||||
Button,
|
|
||||||
Space,
|
|
||||||
Select,
|
|
||||||
Modal,
|
|
||||||
Tag,
|
|
||||||
Popconfirm,
|
|
||||||
Form,
|
|
||||||
Input,
|
|
||||||
DatePicker,
|
|
||||||
InputNumber,
|
|
||||||
Row,
|
|
||||||
Col,
|
|
||||||
Statistic,
|
|
||||||
} from 'antd';
|
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
|
||||||
import { ArrowLeftOutlined, PlusOutlined, DownloadOutlined } from '@ant-design/icons';
|
|
||||||
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);
|
||||||
|
|
||||||
@@ -160,85 +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]);
|
||||||
|
|
||||||
const fetchUsers = useCallback(async () => {
|
const { data: allUsers = [], refetch: refetchUsers } = useQuery<TeacherCandidateUser[]>({
|
||||||
try {
|
queryKey: ['rbac', 'users', 'all'],
|
||||||
const res = (await api.get('/rbac/users')) as UserItem[];
|
queryFn: async () => {
|
||||||
setAllUsers(res || []);
|
try {
|
||||||
} catch {
|
return (await api.get('/rbac/users')) as TeacherCandidateUser[];
|
||||||
setAllUsers([]);
|
} catch {
|
||||||
}
|
return [];
|
||||||
}, []);
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const fetchUsers = useCallback(() => refetchUsers(), [refetchUsers]);
|
||||||
|
|
||||||
useEffect(() => {
|
const { data: schedules = [] } = useQuery<ClassScheduleItem[]>({
|
||||||
fetchDetail();
|
queryKey: ['classes', 'schedule', id, scheduleDateRange],
|
||||||
fetchUsers();
|
queryFn: async () => {
|
||||||
}, [fetchDetail, fetchUsers]);
|
if (!id) return [];
|
||||||
|
try {
|
||||||
|
const params: Record<string, string> = {};
|
||||||
|
if (scheduleDateRange?.[0]) params.startDate = scheduleDateRange[0].format('YYYY-MM-DD');
|
||||||
|
if (scheduleDateRange?.[1]) params.endDate = scheduleDateRange[1].format('YYYY-MM-DD');
|
||||||
|
return (await api.get<ClassScheduleItem[]>(`/classes/${id}/schedule`, { params })) || [];
|
||||||
|
} catch (e: unknown) {
|
||||||
|
message.error(getErrorMessage(e, '加载课表失败'));
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const fetchSchedules = useCallback(async () => {
|
const { data: attendanceSummary = null } = useQuery<AttendanceSummary | null>({
|
||||||
if (!id) return;
|
queryKey: ['classes', 'attendance-summary', id, attendanceDateRange],
|
||||||
try {
|
queryFn: async () => {
|
||||||
const params: Record<string, string> = {};
|
if (!id) return null;
|
||||||
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 (attendanceDateRange?.[0])
|
||||||
setSchedules(res || []);
|
params.startDate = attendanceDateRange[0].format('YYYY-MM-DD');
|
||||||
} catch (e: unknown) {
|
if (attendanceDateRange?.[1]) params.endDate = attendanceDateRange[1].format('YYYY-MM-DD');
|
||||||
const err = e as { message?: string };
|
return (
|
||||||
message.error(err?.message || '加载课表失败');
|
(await api.get<AttendanceSummary>(`/classes/${id}/attendance-summary`, {
|
||||||
}
|
params,
|
||||||
}, [id, scheduleDateRange]);
|
})) || null
|
||||||
|
);
|
||||||
useEffect(() => {
|
} catch (e: unknown) {
|
||||||
fetchSchedules();
|
message.error(getErrorMessage(e, '加载出勤汇总失败'));
|
||||||
}, [fetchSchedules]);
|
return null;
|
||||||
|
}
|
||||||
const fetchAttendanceSummary = useCallback(async () => {
|
},
|
||||||
if (!id) return;
|
});
|
||||||
try {
|
|
||||||
const params: Record<string, string> = {};
|
|
||||||
if (attendanceDateRange?.[0]) params.startDate = attendanceDateRange[0].format('YYYY-MM-DD');
|
|
||||||
if (attendanceDateRange?.[1]) params.endDate = attendanceDateRange[1].format('YYYY-MM-DD');
|
|
||||||
const res = await api.get<AttendanceSummary>(`/classes/${id}/attendance-summary`, { params });
|
|
||||||
setAttendanceSummary(res || null);
|
|
||||||
} catch (e: unknown) {
|
|
||||||
const err = e as { message?: string };
|
|
||||||
message.error(err?.message || '加载出勤汇总失败');
|
|
||||||
}
|
|
||||||
}, [id, attendanceDateRange]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchAttendanceSummary();
|
|
||||||
}, [fetchAttendanceSummary]);
|
|
||||||
|
|
||||||
const handleSaveInfo = async () => {
|
const handleSaveInfo = async () => {
|
||||||
try {
|
try {
|
||||||
@@ -257,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 || '更新失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -268,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 || '移除失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -282,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 || '添加失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -299,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 || '添加失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -310,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 || '移除失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -324,8 +202,7 @@ 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 || '加载学员列表失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -337,8 +214,7 @@ const ClassDetailPage: React.FC = () => {
|
|||||||
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 || '加载用户列表失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -347,82 +223,6 @@ const ClassDetailPage: React.FC = () => {
|
|||||||
|
|
||||||
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: '姓名', 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={() => 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={
|
||||||
@@ -443,325 +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="班主任">
|
|
||||||
{(() => {
|
|
||||||
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={() => {
|
|
||||||
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 = 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={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('');
|
||||||
@@ -89,34 +91,74 @@ const ClassesPage: React.FC = () => {
|
|||||||
|
|
||||||
const handleArchive = async (id: number, archive: boolean) => {
|
const handleArchive = async (id: number, archive: boolean) => {
|
||||||
try {
|
try {
|
||||||
await api.put(`/classes/${id}/${archive ? 'archive' : 'restore'}`);
|
await archiveMutation.mutateAsync({ id, archive });
|
||||||
message.success(archive ? '已归档' : '已恢复');
|
message.success(archive ? '已归档' : '已恢复');
|
||||||
fetchData();
|
} catch {
|
||||||
} catch (e: unknown) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
const err = e as { message?: string };
|
|
||||||
message.error(err?.message || '操作失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const fetchData = useCallback(async () => {
|
const handlePurge = (record: ClassItem) => {
|
||||||
setLoading(true);
|
modal.confirm({
|
||||||
try {
|
title: `永久删除班级「${record.name}」?`,
|
||||||
const params: Record<string, string | boolean | undefined> = {};
|
content: '删除后不可恢复,存在学生、教师、排课、考试或考勤关联时将无法删除。确定继续?',
|
||||||
if (filterStatus) params.status = filterStatus;
|
okText: '永久删除',
|
||||||
if (filterType) params.classType = filterType;
|
okButtonProps: { danger: true },
|
||||||
params.isArchived = showArchived;
|
cancelText: '取消',
|
||||||
const res = await api.get<ClassItem[]>('/classes', { params } as Record<string, unknown>);
|
onOk: async () => {
|
||||||
setData(res);
|
try {
|
||||||
} catch (e: any) {
|
await purgeMutation.mutateAsync(record.id);
|
||||||
message.error(e?.message || '加载失败,请稍后重试');
|
message.success('已永久删除(不可恢复)');
|
||||||
} finally {
|
} catch {
|
||||||
setLoading(false);
|
// 错误提示由 useApiMutation 统一处理
|
||||||
}
|
}
|
||||||
}, [filterStatus, filterType, showArchived]);
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
const {
|
||||||
fetchData();
|
data = [],
|
||||||
}, [fetchData]);
|
isLoading,
|
||||||
|
isFetching,
|
||||||
|
} = useQuery<ClassItem[]>({
|
||||||
|
queryKey: ['classes', filterStatus, filterType, showArchived],
|
||||||
|
queryFn: async () => {
|
||||||
|
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 saveMutation = useApiMutation(
|
||||||
|
async (payload: Record<string, unknown>) =>
|
||||||
|
editing ? api.put(`/classes/${editing.id}`, payload) : api.post('/classes', payload),
|
||||||
|
{ invalidate: [['classes']] },
|
||||||
|
);
|
||||||
|
const saveCellMutation = useApiMutation(
|
||||||
|
async ({ record, field, value }: { record: ClassItem; field: string; value: unknown }) =>
|
||||||
|
api.put(`/classes/${record.id}`, { [field]: value }),
|
||||||
|
{ invalidate: [['classes']] },
|
||||||
|
);
|
||||||
|
const archiveMutation = useApiMutation(
|
||||||
|
async ({ id, archive }: { id: number; archive: boolean }) =>
|
||||||
|
api.put(`/classes/${id}/${archive ? 'archive' : 'restore'}`),
|
||||||
|
{ invalidate: [['classes']] },
|
||||||
|
);
|
||||||
|
const purgeMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/classes/${id}/permanent`),
|
||||||
|
{ invalidate: [['classes']] },
|
||||||
|
);
|
||||||
|
|
||||||
const filtered = useMemo(() => {
|
const filtered = useMemo(() => {
|
||||||
if (!searchText) return data;
|
if (!searchText) return data;
|
||||||
@@ -152,17 +194,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 +206,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 +235,7 @@ const ClassesPage: React.FC = () => {
|
|||||||
</EditableCell>
|
</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '编码',
|
title: '编码',
|
||||||
dataIndex: 'code',
|
dataIndex: 'code',
|
||||||
@@ -212,6 +252,7 @@ const ClassesPage: React.FC = () => {
|
|||||||
</EditableCell>
|
</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '班型',
|
title: '班型',
|
||||||
dataIndex: 'classType',
|
dataIndex: 'classType',
|
||||||
@@ -229,6 +270,7 @@ const ClassesPage: React.FC = () => {
|
|||||||
</EditableCell>
|
</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '开班日期',
|
title: '开班日期',
|
||||||
dataIndex: 'startDate',
|
dataIndex: 'startDate',
|
||||||
@@ -245,6 +287,7 @@ const ClassesPage: React.FC = () => {
|
|||||||
</EditableCell>
|
</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '学员',
|
title: '学员',
|
||||||
width: 100,
|
width: 100,
|
||||||
@@ -259,6 +302,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 +326,7 @@ const ClassesPage: React.FC = () => {
|
|||||||
</EditableCell>
|
</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '操作',
|
title: '操作',
|
||||||
width: 280,
|
width: 280,
|
||||||
@@ -298,11 +343,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 +369,7 @@ const ClassesPage: React.FC = () => {
|
|||||||
),
|
),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
[saveCell],
|
[saveCell, canPurgeClass, handlePurge],
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
340
apps/admin/src/pages/ClassroomRentals/RentalTable.tsx
Normal file
340
apps/admin/src/pages/ClassroomRentals/RentalTable.tsx
Normal file
@@ -0,0 +1,340 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Empty,
|
||||||
|
Popconfirm,
|
||||||
|
Space,
|
||||||
|
Table,
|
||||||
|
Tag,
|
||||||
|
Tooltip,
|
||||||
|
Upload,
|
||||||
|
} from 'antd';
|
||||||
|
import {
|
||||||
|
CheckOutlined,
|
||||||
|
FileTextOutlined,
|
||||||
|
StopOutlined,
|
||||||
|
UploadOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
import PermissionButton from '../../components/PermissionButton';
|
||||||
|
import EditableCell from '../../components/EditableCell';
|
||||||
|
import { message } from '../../ui/app-message';
|
||||||
|
|
||||||
|
const RENTAL_FIELDS = {
|
||||||
|
classroomId: 'classroomId',
|
||||||
|
lesseeOrganizationId: 'lesseeOrganizationId',
|
||||||
|
startDate: 'startDate',
|
||||||
|
endDate: 'endDate',
|
||||||
|
dailyRate: 'dailyRate',
|
||||||
|
totalAmount: 'totalAmount',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export interface RentalTableProps {
|
||||||
|
data: any[];
|
||||||
|
loading: boolean;
|
||||||
|
classrooms: any[];
|
||||||
|
organizations: any[];
|
||||||
|
canPurgeRental: boolean;
|
||||||
|
hasPermission: (permission: string) => boolean;
|
||||||
|
onSaveCell: (record: any, field: string, value: unknown) => Promise<void> | void;
|
||||||
|
onEdit: (record: any) => void;
|
||||||
|
onAction: (id: number, action: 'cancel' | 'end') => void;
|
||||||
|
onArchive: (id: number) => void;
|
||||||
|
onPurge: (id: number, name: string) => void;
|
||||||
|
onDownloadContract: (id: number, filename?: string) => void;
|
||||||
|
onDeleteContract: (id: number) => void;
|
||||||
|
onUploadContract: (id: number, formData: FormData) => Promise<unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const RentalTable: React.FC<RentalTableProps> = ({
|
||||||
|
data,
|
||||||
|
loading,
|
||||||
|
classrooms,
|
||||||
|
organizations,
|
||||||
|
canPurgeRental,
|
||||||
|
hasPermission,
|
||||||
|
onSaveCell,
|
||||||
|
onEdit,
|
||||||
|
onAction,
|
||||||
|
onArchive,
|
||||||
|
onPurge,
|
||||||
|
onDownloadContract,
|
||||||
|
onDeleteContract,
|
||||||
|
onUploadContract,
|
||||||
|
}) => {
|
||||||
|
const EditableRentalCell = <R extends { id: number; effectiveStatus?: string }>({
|
||||||
|
value,
|
||||||
|
field,
|
||||||
|
record,
|
||||||
|
editor,
|
||||||
|
min,
|
||||||
|
required,
|
||||||
|
options,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
value: unknown;
|
||||||
|
field: string;
|
||||||
|
record: R;
|
||||||
|
editor?: React.ComponentProps<typeof EditableCell>['editor'];
|
||||||
|
min?: number;
|
||||||
|
required?: boolean;
|
||||||
|
options?: Array<{ value: string | number; label: string }>;
|
||||||
|
children?: React.ReactNode;
|
||||||
|
}) => (
|
||||||
|
<EditableCell
|
||||||
|
value={value}
|
||||||
|
editor={editor}
|
||||||
|
min={min}
|
||||||
|
required={required}
|
||||||
|
options={options}
|
||||||
|
permission="rental:edit"
|
||||||
|
disabled={record.effectiveStatus !== 'active'}
|
||||||
|
onSave={async (next) => {
|
||||||
|
await onSaveCell(record, field, next);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children ?? String(value ?? '-')}
|
||||||
|
</EditableCell>
|
||||||
|
);
|
||||||
|
|
||||||
|
const columns = [
|
||||||
|
{
|
||||||
|
title: '教室',
|
||||||
|
width: 120,
|
||||||
|
dataIndex: 'classroom',
|
||||||
|
render: (c: any, r: any) => (
|
||||||
|
<EditableRentalCell
|
||||||
|
value={r.classroomId}
|
||||||
|
field={RENTAL_FIELDS.classroomId}
|
||||||
|
record={r}
|
||||||
|
editor="select"
|
||||||
|
options={classrooms
|
||||||
|
.filter((item) => item.status !== 'archived')
|
||||||
|
.map((item) => ({
|
||||||
|
value: item.id,
|
||||||
|
label: item.building ? `${item.building} · ${item.name}` : item.name,
|
||||||
|
}))}
|
||||||
|
required
|
||||||
|
>
|
||||||
|
{c ? (
|
||||||
|
<span>
|
||||||
|
{c.building ? `${c.building} · ` : ''}
|
||||||
|
{c.name}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
'-'
|
||||||
|
)}
|
||||||
|
</EditableRentalCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '承租机构',
|
||||||
|
width: 100,
|
||||||
|
dataIndex: 'lesseeOrganization',
|
||||||
|
render: (t: any, r: any) => (
|
||||||
|
<EditableRentalCell
|
||||||
|
value={r.lesseeOrganizationId}
|
||||||
|
field={RENTAL_FIELDS.lesseeOrganizationId}
|
||||||
|
record={r}
|
||||||
|
editor="select"
|
||||||
|
options={organizations
|
||||||
|
.filter((item) => item.status !== 'archived')
|
||||||
|
.map((item) => ({ value: item.id, label: item.name }))}
|
||||||
|
required
|
||||||
|
>
|
||||||
|
{t ? (
|
||||||
|
<Tag
|
||||||
|
color={t.color}
|
||||||
|
style={{ background: t.color, color: '#fff', borderColor: t.color }}
|
||||||
|
>
|
||||||
|
{t.name}
|
||||||
|
</Tag>
|
||||||
|
) : (
|
||||||
|
'-'
|
||||||
|
)}
|
||||||
|
</EditableRentalCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '开始日期',
|
||||||
|
dataIndex: 'startDate',
|
||||||
|
width: 110,
|
||||||
|
render: (v: string, r: any) => (
|
||||||
|
<EditableRentalCell value={v} field={RENTAL_FIELDS.startDate} record={r} editor="date" required>
|
||||||
|
{v}
|
||||||
|
</EditableRentalCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '结束日期',
|
||||||
|
dataIndex: 'endDate',
|
||||||
|
width: 110,
|
||||||
|
render: (v: string, r: any) => (
|
||||||
|
<EditableRentalCell value={v} field={RENTAL_FIELDS.endDate} record={r} editor="date" required>
|
||||||
|
{v}
|
||||||
|
</EditableRentalCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '时长',
|
||||||
|
width: 80,
|
||||||
|
render: (_: any, r: any) => {
|
||||||
|
const d = dayjs(r.endDate).diff(dayjs(r.startDate), 'day') + 1;
|
||||||
|
return `${d}天`;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '日租金',
|
||||||
|
dataIndex: 'dailyRate',
|
||||||
|
width: 100,
|
||||||
|
render: (v: any, r: any) => (
|
||||||
|
<EditableRentalCell value={v} field={RENTAL_FIELDS.dailyRate} record={r} editor="money" min={0.01}>
|
||||||
|
{v ? `¥${v}` : '-'}
|
||||||
|
</EditableRentalCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '总额',
|
||||||
|
dataIndex: 'totalAmount',
|
||||||
|
width: 100,
|
||||||
|
render: (v: any, r: any) => (
|
||||||
|
<EditableRentalCell value={v} field={RENTAL_FIELDS.totalAmount} record={r} editor="money" min={0.01}>
|
||||||
|
{v ? `¥${v}` : '-'}
|
||||||
|
</EditableRentalCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'effectiveStatus',
|
||||||
|
width: 90,
|
||||||
|
render: (status: string) => {
|
||||||
|
const config: Record<string, { text: string; color: string }> = {
|
||||||
|
active: { text: '进行中', color: 'green' },
|
||||||
|
ended: { text: '已结束', color: 'default' },
|
||||||
|
cancelled: { text: '已取消', color: 'red' },
|
||||||
|
};
|
||||||
|
return <Tag color={config[status]?.color}>{config[status]?.text || status}</Tag>;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '合同',
|
||||||
|
width: 120,
|
||||||
|
dataIndex: 'contractPath',
|
||||||
|
render: (v: string, r: any) =>
|
||||||
|
v ? (
|
||||||
|
<Space>
|
||||||
|
<Tooltip title={r.contractOriginalName}>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
icon={<FileTextOutlined />}
|
||||||
|
onClick={() => onDownloadContract(r.id, r.contractOriginalName)}
|
||||||
|
>
|
||||||
|
下载
|
||||||
|
</Button>
|
||||||
|
</Tooltip>
|
||||||
|
{hasPermission('rental:edit') ? (
|
||||||
|
<Popconfirm title="移除合同文件?" onConfirm={() => onDeleteContract(r.id)}>
|
||||||
|
<Button size="small" danger icon={<StopOutlined />} aria-label="移除合同文件" />
|
||||||
|
</Popconfirm>
|
||||||
|
) : null}
|
||||||
|
</Space>
|
||||||
|
) : hasPermission('rental:edit') ? (
|
||||||
|
<Upload
|
||||||
|
accept="application/pdf"
|
||||||
|
showUploadList={false}
|
||||||
|
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||||
|
if (file.size > 10 * 1024 * 1024) {
|
||||||
|
message.error('文件不能超过 10MB');
|
||||||
|
onError?.(new Error('size'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', file);
|
||||||
|
try {
|
||||||
|
await onUploadContract(r.id, formData);
|
||||||
|
message.success('合同已上传');
|
||||||
|
onSuccess?.({});
|
||||||
|
} catch (e) {
|
||||||
|
onError?.(e as Error);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Button size="small" icon={<UploadOutlined />}>
|
||||||
|
上传PDF
|
||||||
|
</Button>
|
||||||
|
</Upload>
|
||||||
|
) : (
|
||||||
|
'-'
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
width: 150,
|
||||||
|
render: (_: any, record: any) => (
|
||||||
|
<Space>
|
||||||
|
{record.effectiveStatus === 'active' && (
|
||||||
|
<>
|
||||||
|
<PermissionButton permission="rental:edit" size="small" onClick={() => onEdit(record)}>
|
||||||
|
编辑
|
||||||
|
</PermissionButton>
|
||||||
|
<Popconfirm title="确定取消该租赁?" onConfirm={() => onAction(record.id, 'cancel')}>
|
||||||
|
<PermissionButton
|
||||||
|
permission="rental:edit"
|
||||||
|
size="small"
|
||||||
|
danger
|
||||||
|
icon={<StopOutlined />}
|
||||||
|
>
|
||||||
|
取消
|
||||||
|
</PermissionButton>
|
||||||
|
</Popconfirm>
|
||||||
|
{!dayjs(record.startDate).isAfter(dayjs(), 'day') && (
|
||||||
|
<Popconfirm title="确定今天结束该租赁?" onConfirm={() => onAction(record.id, 'end')}>
|
||||||
|
<PermissionButton permission="rental:edit" size="small" icon={<CheckOutlined />}>
|
||||||
|
结束
|
||||||
|
</PermissionButton>
|
||||||
|
</Popconfirm>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{record.effectiveStatus !== 'active' && (
|
||||||
|
<Popconfirm
|
||||||
|
title="确定归档该租赁订单?合同文件会保留。"
|
||||||
|
onConfirm={() => onArchive(record.id)}
|
||||||
|
>
|
||||||
|
<PermissionButton permission="rental:delete" size="small" danger>
|
||||||
|
归档
|
||||||
|
</PermissionButton>
|
||||||
|
</Popconfirm>
|
||||||
|
)}
|
||||||
|
{record.status === 'cancelled' && canPurgeRental ? (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
danger
|
||||||
|
type="link"
|
||||||
|
onClick={() => onPurge(record.id, record.lesseeOrganization?.name || `订单${record.id}`)}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Table
|
||||||
|
columns={columns}
|
||||||
|
dataSource={data}
|
||||||
|
rowKey="id"
|
||||||
|
loading={loading}
|
||||||
|
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
||||||
|
pagination={{
|
||||||
|
defaultPageSize: 15,
|
||||||
|
showSizeChanger: true,
|
||||||
|
pageSizeOptions: [15, 30, 50, 100],
|
||||||
|
showTotal: (total) => `共 ${total} 条`,
|
||||||
|
}}
|
||||||
|
scroll={{ x: 1200 }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
import React, { useCallback, useMemo, useRef, useState } from 'react';
|
||||||
|
import { useImmer } from 'use-immer';
|
||||||
import {
|
import {
|
||||||
Table,
|
App,
|
||||||
Button,
|
|
||||||
Modal,
|
Modal,
|
||||||
Form,
|
Form,
|
||||||
Select,
|
Select,
|
||||||
@@ -9,39 +9,32 @@ import {
|
|||||||
InputNumber,
|
InputNumber,
|
||||||
Input,
|
Input,
|
||||||
Space,
|
Space,
|
||||||
Tag,
|
|
||||||
Popconfirm,
|
|
||||||
Upload,
|
|
||||||
Tooltip,
|
|
||||||
Empty,
|
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import {
|
import { PlusOutlined } from '@ant-design/icons';
|
||||||
PlusOutlined,
|
|
||||||
UploadOutlined,
|
|
||||||
FileTextOutlined,
|
|
||||||
StopOutlined,
|
|
||||||
CheckOutlined,
|
|
||||||
} from '@ant-design/icons';
|
|
||||||
import dayjs, { Dayjs } from 'dayjs';
|
import dayjs, { Dayjs } from 'dayjs';
|
||||||
import api from '../../api';
|
import api from '../../api';
|
||||||
import { downloadBlob } from '../../utils/download';
|
import { downloadBlob } from '../../utils/download';
|
||||||
import PermissionButton from '../../components/PermissionButton';
|
import PermissionButton from '../../components/PermissionButton';
|
||||||
import EditableCell from '../../components/EditableCell';
|
|
||||||
import { message } from '../../ui/app-message';
|
import { message } from '../../ui/app-message';
|
||||||
import { usePermission } from '../../hooks/usePermission';
|
import { usePermission } from '../../hooks/usePermission';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||||
|
import { getErrorMessage } from '../../utils/error';
|
||||||
|
import { validateResponse } from '../../utils/validate';
|
||||||
|
import { classroomsSchema, organizationsSchema, rentalsSchema } from '../../api/schemas';
|
||||||
|
import { RentalTable } from './RentalTable';
|
||||||
|
|
||||||
interface UnavailableDatesResponse {
|
interface UnavailableDatesResponse {
|
||||||
dates: string[];
|
dates: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export const unavailableDatesCacheKey = (classroomId: number, date: Dayjs) =>
|
export const unavailableDatesCacheKey = (classroomId: number, date: Dayjs) =>
|
||||||
`${classroomId}:${date.format('YYYY-MM')}`;
|
`${classroomId}:${date.format('YYYY-MM')}`;
|
||||||
|
|
||||||
const ClassroomRentalsPage: React.FC = () => {
|
const ClassroomRentalsPage: React.FC = () => {
|
||||||
|
const { modal } = App.useApp();
|
||||||
const { hasPermission, hasAnyPermission } = usePermission();
|
const { hasPermission, hasAnyPermission } = usePermission();
|
||||||
const [data, setData] = useState<any[]>([]);
|
const canPurgeRental = hasPermission('rental:purge');
|
||||||
const [classrooms, setClassrooms] = useState<any[]>([]);
|
|
||||||
const [organizations, setOrganizations] = useState<any[]>([]);
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [modalOpen, setModalOpen] = useState(false);
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
const [editing, setEditing] = useState<any>(null);
|
const [editing, setEditing] = useState<any>(null);
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
@@ -49,12 +42,110 @@ const ClassroomRentalsPage: React.FC = () => {
|
|||||||
const [filterStatus, setFilterStatus] = useState<string | undefined>();
|
const [filterStatus, setFilterStatus] = useState<string | undefined>();
|
||||||
const [searchText, setSearchText] = useState('');
|
const [searchText, setSearchText] = useState('');
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [unavailableDates, setUnavailableDates] = useState<Set<string>>(new Set());
|
const [unavailableDates, setUnavailableDates] = useImmer<Set<string>>(new Set());
|
||||||
const loadedUnavailableMonths = useRef<Set<string>>(new Set());
|
const loadedUnavailableMonths = useRef<Set<string>>(new Set());
|
||||||
const unavailableRequestVersion = useRef(0);
|
const unavailableRequestVersion = useRef(0);
|
||||||
const [unavailableDatesLoading, setUnavailableDatesLoading] = useState(false);
|
const [unavailableDatesLoading, setUnavailableDatesLoading] = useState(false);
|
||||||
const selectedClassroomId = Form.useWatch('classroomId', form);
|
const selectedClassroomId = Form.useWatch('classroomId', form);
|
||||||
|
|
||||||
|
const {
|
||||||
|
data = [],
|
||||||
|
isLoading,
|
||||||
|
isFetching,
|
||||||
|
} = useQuery<any[]>({
|
||||||
|
queryKey: ['classroom-rentals', filterMonth],
|
||||||
|
queryFn: async () => {
|
||||||
|
try {
|
||||||
|
const params: any = {};
|
||||||
|
if (filterMonth) params.month = filterMonth.format('YYYY-MM');
|
||||||
|
params.includeEnded = true;
|
||||||
|
return validateResponse<any[]>(
|
||||||
|
rentalsSchema,
|
||||||
|
await api.get('/classroom-rentals', { params }),
|
||||||
|
);
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '加载失败,请稍后重试');
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const {
|
||||||
|
data: meta = { classrooms: [], organizations: [] },
|
||||||
|
} = useQuery<{ classrooms: any[]; organizations: any[] }>({
|
||||||
|
queryKey: ['classroom-rentals', 'meta'],
|
||||||
|
enabled: hasAnyPermission('rental:create', 'rental:edit'),
|
||||||
|
queryFn: async () => {
|
||||||
|
try {
|
||||||
|
const [cr, tn]: any = await Promise.all([
|
||||||
|
api.get('/classrooms'),
|
||||||
|
api.get('/organizations', { params: { scope: 'all' } }),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
classrooms: validateResponse<any[]>(classroomsSchema, cr),
|
||||||
|
organizations: validateResponse<any[]>(organizationsSchema, tn),
|
||||||
|
};
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '加载教室列表失败');
|
||||||
|
return { classrooms: [], organizations: [] };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const classrooms = meta.classrooms;
|
||||||
|
const organizations = meta.organizations;
|
||||||
|
const loading = isLoading || isFetching;
|
||||||
|
|
||||||
|
const saveMutation = useApiMutation(
|
||||||
|
async (payload: Record<string, unknown>) =>
|
||||||
|
editing
|
||||||
|
? api.put(`/classroom-rentals/${editing.id}`, payload)
|
||||||
|
: api.post('/classroom-rentals', payload),
|
||||||
|
{
|
||||||
|
invalidate: [['classroom-rentals']],
|
||||||
|
onError: (error: unknown) => {
|
||||||
|
const e = error as {
|
||||||
|
conflicts?: Array<{ organizationName?: string; startDate?: string; endDate?: string }>;
|
||||||
|
};
|
||||||
|
if (e?.conflicts?.length) {
|
||||||
|
const list = e.conflicts
|
||||||
|
.map((c) => `${c.organizationName}(${c.startDate}~${c.endDate})`)
|
||||||
|
.join('、');
|
||||||
|
message.error(`时间段冲突:${list}`);
|
||||||
|
} else {
|
||||||
|
message.error(getErrorMessage(error, '操作失败'));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const saveCellMutation = useApiMutation(
|
||||||
|
async ({ record, field, value }: { record: any; field: string; value: unknown }) =>
|
||||||
|
api.put(`/classroom-rentals/${record.id}`, { [field]: value }),
|
||||||
|
{ invalidate: [['classroom-rentals']] },
|
||||||
|
);
|
||||||
|
const deleteMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/classroom-rentals/${id}`),
|
||||||
|
{ invalidate: [['classroom-rentals']] },
|
||||||
|
);
|
||||||
|
const purgeMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/classroom-rentals/${id}/permanent`),
|
||||||
|
{ invalidate: [['classroom-rentals']] },
|
||||||
|
);
|
||||||
|
const actionMutation = useApiMutation(
|
||||||
|
async ({ id, action }: { id: number; action: 'cancel' | 'end' }) =>
|
||||||
|
api.put(`/classroom-rentals/${id}/${action}`),
|
||||||
|
{ invalidate: [['classroom-rentals']] },
|
||||||
|
);
|
||||||
|
const deleteContractMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/classroom-rentals/${id}/contract`),
|
||||||
|
{ invalidate: [['classroom-rentals']] },
|
||||||
|
);
|
||||||
|
const uploadContractMutation = useApiMutation(
|
||||||
|
async ({ id, formData }: { id: number; formData: FormData }) =>
|
||||||
|
api.post(`/classroom-rentals/${id}/contract`, formData, {
|
||||||
|
headers: { 'Content-Type': 'multipart/form-data' },
|
||||||
|
}),
|
||||||
|
{ invalidate: [['classroom-rentals']] },
|
||||||
|
);
|
||||||
|
|
||||||
const filteredData = useMemo(() => {
|
const filteredData = useMemo(() => {
|
||||||
return data.filter((r: any) => {
|
return data.filter((r: any) => {
|
||||||
if (filterStatus && r.effectiveStatus !== filterStatus) return false;
|
if (filterStatus && r.effectiveStatus !== filterStatus) return false;
|
||||||
@@ -66,40 +157,6 @@ const ClassroomRentalsPage: React.FC = () => {
|
|||||||
});
|
});
|
||||||
}, [data, searchText, filterStatus]);
|
}, [data, searchText, filterStatus]);
|
||||||
|
|
||||||
const fetchData = async () => {
|
|
||||||
setLoading(true);
|
|
||||||
try {
|
|
||||||
const params: any = {};
|
|
||||||
if (filterMonth) params.month = filterMonth.format('YYYY-MM');
|
|
||||||
params.includeEnded = true;
|
|
||||||
const res: any = await api.get('/classroom-rentals', { params });
|
|
||||||
setData(res);
|
|
||||||
} catch (e: any) {
|
|
||||||
message.error(e?.message || '加载失败,请稍后重试');
|
|
||||||
}
|
|
||||||
setLoading(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchMeta = async () => {
|
|
||||||
try {
|
|
||||||
const [cr, tn]: any = await Promise.all([
|
|
||||||
api.get('/classrooms'),
|
|
||||||
api.get('/organizations', { params: { scope: 'all' } }),
|
|
||||||
]);
|
|
||||||
setClassrooms(cr);
|
|
||||||
setOrganizations(tn);
|
|
||||||
} catch (e: any) {
|
|
||||||
message.error(e?.message || '加载教室列表失败');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (hasAnyPermission('rental:create', 'rental:edit')) fetchMeta();
|
|
||||||
}, [hasAnyPermission]);
|
|
||||||
useEffect(() => {
|
|
||||||
fetchData();
|
|
||||||
}, [filterMonth]);
|
|
||||||
|
|
||||||
const resetUnavailableDates = () => {
|
const resetUnavailableDates = () => {
|
||||||
unavailableRequestVersion.current += 1;
|
unavailableRequestVersion.current += 1;
|
||||||
loadedUnavailableMonths.current.clear();
|
loadedUnavailableMonths.current.clear();
|
||||||
@@ -127,10 +184,8 @@ const ClassroomRentalsPage: React.FC = () => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
if (requestVersion !== unavailableRequestVersion.current) return;
|
if (requestVersion !== unavailableRequestVersion.current) return;
|
||||||
setUnavailableDates((current) => {
|
setUnavailableDates((draft) => {
|
||||||
const next = new Set(current);
|
response.dates.forEach((item) => draft.add(item));
|
||||||
response.dates.forEach((item) => next.add(item));
|
|
||||||
return next;
|
|
||||||
});
|
});
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
loadedUnavailableMonths.current.delete(key);
|
loadedUnavailableMonths.current.delete(key);
|
||||||
@@ -190,75 +245,85 @@ const ClassroomRentalsPage: React.FC = () => {
|
|||||||
notes: values.notes,
|
notes: values.notes,
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
if (editing) {
|
await saveMutation.mutateAsync(payload);
|
||||||
await api.put(`/classroom-rentals/${editing.id}`, payload);
|
message.success(editing ? '更新成功' : '创建成功');
|
||||||
message.success('更新成功');
|
|
||||||
} else {
|
|
||||||
await api.post('/classroom-rentals', payload);
|
|
||||||
message.success('创建成功');
|
|
||||||
}
|
|
||||||
setModalOpen(false);
|
setModalOpen(false);
|
||||||
form.resetFields();
|
form.resetFields();
|
||||||
setEditing(null);
|
setEditing(null);
|
||||||
fetchData();
|
} catch {
|
||||||
} catch (e: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
if (e?.conflicts?.length) {
|
|
||||||
const list = e.conflicts
|
|
||||||
.map((c: any) => `${c.organizationName}(${c.startDate}~${c.endDate})`)
|
|
||||||
.join('、');
|
|
||||||
message.error(`时间段冲突:${list}`);
|
|
||||||
} else {
|
|
||||||
message.error(e?.message || '操作失败');
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false);
|
setSaving(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const saveCell = async (record: any, field: string, value: unknown) => {
|
const saveCell = async (record: any, field: string, value: unknown) => {
|
||||||
await api.put(`/classroom-rentals/${record.id}`, { [field]: value });
|
try {
|
||||||
message.success('已保存');
|
await saveCellMutation.mutateAsync({ record, field, value });
|
||||||
await fetchData();
|
message.success('已保存');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDelete = async (id: number) => {
|
const handleDelete = async (id: number) => {
|
||||||
try {
|
try {
|
||||||
await api.delete(`/classroom-rentals/${id}`);
|
await deleteMutation.mutateAsync(id);
|
||||||
message.success('已归档');
|
message.success('已归档');
|
||||||
fetchData();
|
} catch {
|
||||||
} catch (e: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error(e?.message || '归档失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handlePurge = (id: number, name: string) => {
|
||||||
|
modal.confirm({
|
||||||
|
title: `永久删除租赁订单(${name})?`,
|
||||||
|
content: '删除后不可恢复,排课与合同文件将被清除(存在考勤记录时将无法删除)。确定继续?',
|
||||||
|
okText: '永久删除',
|
||||||
|
okButtonProps: { danger: true },
|
||||||
|
cancelText: '取消',
|
||||||
|
onOk: async () => {
|
||||||
|
try {
|
||||||
|
await purgeMutation.mutateAsync(id);
|
||||||
|
message.success('已永久删除(不可恢复)');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const handleRentalAction = async (id: number, action: 'cancel' | 'end') => {
|
const handleRentalAction = async (id: number, action: 'cancel' | 'end') => {
|
||||||
try {
|
try {
|
||||||
await api.put(`/classroom-rentals/${id}/${action}`);
|
await actionMutation.mutateAsync({ id, action });
|
||||||
message.success(action === 'cancel' ? '租赁已取消' : '租赁已结束');
|
message.success(action === 'cancel' ? '租赁已取消' : '租赁已结束');
|
||||||
fetchData();
|
} catch {
|
||||||
} catch (e: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error(e?.message || '操作失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDownloadContract = async (id: number, filename?: string) => {
|
const handleDownloadContract = async (id: number, filename?: string) => {
|
||||||
try {
|
try {
|
||||||
await downloadBlob(`/classroom-rentals/${id}/contract`, filename || `contract-${id}.pdf`);
|
await downloadBlob(`/classroom-rentals/${id}/contract`, filename || `contract-${id}.pdf`);
|
||||||
} catch {
|
} catch (e) {
|
||||||
|
console.error('下载合同失败', e);
|
||||||
message.error('下载失败(可能文件已丢失)');
|
message.error('下载失败(可能文件已丢失)');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteContract = async (id: number) => {
|
const handleDeleteContract = async (id: number) => {
|
||||||
try {
|
try {
|
||||||
await api.delete(`/classroom-rentals/${id}/contract`);
|
await deleteContractMutation.mutateAsync(id);
|
||||||
message.success('合同已移除');
|
message.success('合同已移除');
|
||||||
fetchData();
|
} catch {
|
||||||
} catch (e: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error(e?.message || '移除失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleUploadContract = async (id: number, formData: FormData) => {
|
||||||
|
return uploadContractMutation.mutateAsync({ id, formData });
|
||||||
|
};
|
||||||
|
|
||||||
const openEdit = (record: any) => {
|
const openEdit = (record: any) => {
|
||||||
setEditing(record);
|
setEditing(record);
|
||||||
resetUnavailableDates();
|
resetUnavailableDates();
|
||||||
@@ -280,271 +345,6 @@ const ClassroomRentalsPage: React.FC = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const columns = useMemo(
|
|
||||||
() => [
|
|
||||||
{
|
|
||||||
title: '教室',
|
|
||||||
width: 120,
|
|
||||||
dataIndex: 'classroom',
|
|
||||||
render: (c: any, r: any) => (
|
|
||||||
<EditableCell
|
|
||||||
value={r.classroomId}
|
|
||||||
editor="select"
|
|
||||||
options={classrooms
|
|
||||||
.filter((item) => item.status !== 'archived')
|
|
||||||
.map((item) => ({
|
|
||||||
value: item.id,
|
|
||||||
label: item.building ? `${item.building} · ${item.name}` : item.name,
|
|
||||||
}))}
|
|
||||||
permission="rental:edit"
|
|
||||||
disabled={r.effectiveStatus !== 'active'}
|
|
||||||
required
|
|
||||||
onSave={(next) => saveCell(r, 'classroomId', next)}
|
|
||||||
>
|
|
||||||
{c ? (
|
|
||||||
<span>
|
|
||||||
{c.building ? `${c.building} · ` : ''}
|
|
||||||
{c.name}
|
|
||||||
</span>
|
|
||||||
) : (
|
|
||||||
'-'
|
|
||||||
)}
|
|
||||||
</EditableCell>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '承租机构',
|
|
||||||
width: 100,
|
|
||||||
dataIndex: 'lesseeOrganization',
|
|
||||||
render: (t: any, r: any) => (
|
|
||||||
<EditableCell
|
|
||||||
value={r.lesseeOrganizationId}
|
|
||||||
editor="select"
|
|
||||||
options={organizations
|
|
||||||
.filter((item) => item.status !== 'archived')
|
|
||||||
.map((item) => ({ value: item.id, label: item.name }))}
|
|
||||||
permission="rental:edit"
|
|
||||||
disabled={r.effectiveStatus !== 'active'}
|
|
||||||
required
|
|
||||||
onSave={(next) => saveCell(r, 'lesseeOrganizationId', next)}
|
|
||||||
>
|
|
||||||
{t ? (
|
|
||||||
<Tag
|
|
||||||
color={t.color}
|
|
||||||
style={{ background: t.color, color: '#fff', borderColor: t.color }}
|
|
||||||
>
|
|
||||||
{t.name}
|
|
||||||
</Tag>
|
|
||||||
) : (
|
|
||||||
'-'
|
|
||||||
)}
|
|
||||||
</EditableCell>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '开始日期',
|
|
||||||
dataIndex: 'startDate',
|
|
||||||
width: 110,
|
|
||||||
render: (v: string, r: any) => (
|
|
||||||
<EditableCell
|
|
||||||
value={v}
|
|
||||||
editor="date"
|
|
||||||
permission="rental:edit"
|
|
||||||
disabled={r.effectiveStatus !== 'active'}
|
|
||||||
required
|
|
||||||
onSave={(next) => saveCell(r, 'startDate', next)}
|
|
||||||
>
|
|
||||||
{v}
|
|
||||||
</EditableCell>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '结束日期',
|
|
||||||
dataIndex: 'endDate',
|
|
||||||
width: 110,
|
|
||||||
render: (v: string, r: any) => (
|
|
||||||
<EditableCell
|
|
||||||
value={v}
|
|
||||||
editor="date"
|
|
||||||
permission="rental:edit"
|
|
||||||
disabled={r.effectiveStatus !== 'active'}
|
|
||||||
required
|
|
||||||
onSave={(next) => saveCell(r, 'endDate', next)}
|
|
||||||
>
|
|
||||||
{v}
|
|
||||||
</EditableCell>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '时长',
|
|
||||||
width: 80,
|
|
||||||
render: (_: any, r: any) => {
|
|
||||||
const d = dayjs(r.endDate).diff(dayjs(r.startDate), 'day') + 1;
|
|
||||||
return `${d}天`;
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '日租金',
|
|
||||||
dataIndex: 'dailyRate',
|
|
||||||
width: 100,
|
|
||||||
render: (v: any, r: any) => (
|
|
||||||
<EditableCell
|
|
||||||
value={v}
|
|
||||||
editor="money"
|
|
||||||
min={0.01}
|
|
||||||
permission="rental:edit"
|
|
||||||
disabled={r.effectiveStatus !== 'active'}
|
|
||||||
onSave={(next) => saveCell(r, 'dailyRate', next)}
|
|
||||||
>
|
|
||||||
{v ? `¥${v}` : '-'}
|
|
||||||
</EditableCell>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '总额',
|
|
||||||
dataIndex: 'totalAmount',
|
|
||||||
width: 100,
|
|
||||||
render: (v: any, r: any) => (
|
|
||||||
<EditableCell
|
|
||||||
value={v}
|
|
||||||
editor="money"
|
|
||||||
min={0.01}
|
|
||||||
permission="rental:edit"
|
|
||||||
disabled={r.effectiveStatus !== 'active'}
|
|
||||||
onSave={(next) => saveCell(r, 'totalAmount', next)}
|
|
||||||
>
|
|
||||||
{v ? `¥${v}` : '-'}
|
|
||||||
</EditableCell>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '状态',
|
|
||||||
dataIndex: 'effectiveStatus',
|
|
||||||
width: 90,
|
|
||||||
render: (status: string) => {
|
|
||||||
const config: Record<string, { text: string; color: string }> = {
|
|
||||||
active: { text: '进行中', color: 'green' },
|
|
||||||
ended: { text: '已结束', color: 'default' },
|
|
||||||
cancelled: { text: '已取消', color: 'red' },
|
|
||||||
};
|
|
||||||
return <Tag color={config[status]?.color}>{config[status]?.text || status}</Tag>;
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '合同',
|
|
||||||
width: 120,
|
|
||||||
dataIndex: 'contractPath',
|
|
||||||
render: (v: string, r: any) =>
|
|
||||||
v ? (
|
|
||||||
<Space>
|
|
||||||
<Tooltip title={r.contractOriginalName}>
|
|
||||||
<Button
|
|
||||||
size="small"
|
|
||||||
icon={<FileTextOutlined />}
|
|
||||||
onClick={() => handleDownloadContract(r.id, r.contractOriginalName)}
|
|
||||||
>
|
|
||||||
下载
|
|
||||||
</Button>
|
|
||||||
</Tooltip>
|
|
||||||
{hasPermission('rental:edit') ? (
|
|
||||||
<Popconfirm title="移除合同文件?" onConfirm={() => handleDeleteContract(r.id)}>
|
|
||||||
<Button size="small" danger icon={<StopOutlined />} aria-label="移除合同文件" />
|
|
||||||
</Popconfirm>
|
|
||||||
) : null}
|
|
||||||
</Space>
|
|
||||||
) : hasPermission('rental:edit') ? (
|
|
||||||
<Upload
|
|
||||||
accept="application/pdf"
|
|
||||||
showUploadList={false}
|
|
||||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
|
||||||
if (file.size > 10 * 1024 * 1024) {
|
|
||||||
message.error('文件不能超过 10MB');
|
|
||||||
onError?.(new Error('size'));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const formData = new FormData();
|
|
||||||
formData.append('file', file);
|
|
||||||
try {
|
|
||||||
await api.post(`/classroom-rentals/${r.id}/contract`, formData, {
|
|
||||||
headers: { 'Content-Type': 'multipart/form-data' },
|
|
||||||
});
|
|
||||||
message.success('合同已上传');
|
|
||||||
onSuccess?.({});
|
|
||||||
fetchData();
|
|
||||||
} catch (e: any) {
|
|
||||||
message.error(e?.message || '上传失败');
|
|
||||||
onError?.(e);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Button size="small" icon={<UploadOutlined />}>
|
|
||||||
上传PDF
|
|
||||||
</Button>
|
|
||||||
</Upload>
|
|
||||||
) : (
|
|
||||||
'-'
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '操作',
|
|
||||||
width: 150,
|
|
||||||
render: (_: any, record: any) => (
|
|
||||||
<Space>
|
|
||||||
{record.effectiveStatus === 'active' && (
|
|
||||||
<>
|
|
||||||
<PermissionButton
|
|
||||||
permission="rental:edit"
|
|
||||||
size="small"
|
|
||||||
onClick={() => openEdit(record)}
|
|
||||||
>
|
|
||||||
编辑
|
|
||||||
</PermissionButton>
|
|
||||||
<Popconfirm
|
|
||||||
title="确定取消该租赁?"
|
|
||||||
onConfirm={() => handleRentalAction(record.id, 'cancel')}
|
|
||||||
>
|
|
||||||
<PermissionButton
|
|
||||||
permission="rental:edit"
|
|
||||||
size="small"
|
|
||||||
danger
|
|
||||||
icon={<StopOutlined />}
|
|
||||||
>
|
|
||||||
取消
|
|
||||||
</PermissionButton>
|
|
||||||
</Popconfirm>
|
|
||||||
{!dayjs(record.startDate).isAfter(dayjs(), 'day') && (
|
|
||||||
<Popconfirm
|
|
||||||
title="确定今天结束该租赁?"
|
|
||||||
onConfirm={() => handleRentalAction(record.id, 'end')}
|
|
||||||
>
|
|
||||||
<PermissionButton
|
|
||||||
permission="rental:edit"
|
|
||||||
size="small"
|
|
||||||
icon={<CheckOutlined />}
|
|
||||||
>
|
|
||||||
结束
|
|
||||||
</PermissionButton>
|
|
||||||
</Popconfirm>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{record.effectiveStatus !== 'active' && (
|
|
||||||
<Popconfirm
|
|
||||||
title="确定归档该租赁订单?合同文件会保留。"
|
|
||||||
onConfirm={() => handleDelete(record.id)}
|
|
||||||
>
|
|
||||||
<PermissionButton permission="rental:delete" size="small" danger>
|
|
||||||
归档
|
|
||||||
</PermissionButton>
|
|
||||||
</Popconfirm>
|
|
||||||
)}
|
|
||||||
</Space>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
[classrooms, organizations, hasPermission],
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div
|
<div
|
||||||
@@ -601,19 +401,21 @@ const ClassroomRentalsPage: React.FC = () => {
|
|||||||
新增租赁
|
新增租赁
|
||||||
</PermissionButton>
|
</PermissionButton>
|
||||||
</div>
|
</div>
|
||||||
<Table
|
<RentalTable
|
||||||
columns={columns}
|
data={filteredData}
|
||||||
dataSource={filteredData}
|
|
||||||
rowKey="id"
|
|
||||||
loading={loading}
|
loading={loading}
|
||||||
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
classrooms={classrooms}
|
||||||
pagination={{
|
organizations={organizations}
|
||||||
defaultPageSize: 15,
|
canPurgeRental={canPurgeRental}
|
||||||
showSizeChanger: true,
|
hasPermission={hasPermission}
|
||||||
pageSizeOptions: [15, 30, 50, 100],
|
onSaveCell={saveCell}
|
||||||
showTotal: (total) => `共 ${total} 条`,
|
onEdit={openEdit}
|
||||||
}}
|
onAction={handleRentalAction}
|
||||||
scroll={{ x: 1200 }}
|
onArchive={handleDelete}
|
||||||
|
onPurge={handlePurge}
|
||||||
|
onDownloadContract={handleDownloadContract}
|
||||||
|
onDeleteContract={handleDeleteContract}
|
||||||
|
onUploadContract={handleUploadContract}
|
||||||
/>
|
/>
|
||||||
<Modal
|
<Modal
|
||||||
title={editing ? '编辑租赁' : '新增租赁'}
|
title={editing ? '编辑租赁' : '新增租赁'}
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
import React, { useEffect, useState, useMemo, useCallback } from 'react';
|
import React, { useState, useMemo } from 'react';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { validateResponse } from '../../utils/validate';
|
||||||
|
import { classroomScheduleSchema } from '../../api/schemas';
|
||||||
import {
|
import {
|
||||||
DatePicker,
|
DatePicker,
|
||||||
Card,
|
Card,
|
||||||
@@ -18,6 +21,7 @@ import dayjs, { Dayjs } from 'dayjs';
|
|||||||
import api from '../../api';
|
import api from '../../api';
|
||||||
import { downloadBlob } from '../../utils/download';
|
import { downloadBlob } from '../../utils/download';
|
||||||
import { message } from '../../ui/app-message';
|
import { message } from '../../ui/app-message';
|
||||||
|
import { getErrorMessage } from '../../utils/error';
|
||||||
|
|
||||||
interface ScheduleData {
|
interface ScheduleData {
|
||||||
year: number;
|
year: number;
|
||||||
@@ -34,27 +38,25 @@ interface ScheduleData {
|
|||||||
|
|
||||||
const ClassroomSchedulePage: React.FC = () => {
|
const ClassroomSchedulePage: React.FC = () => {
|
||||||
const [month, setMonth] = useState<Dayjs>(dayjs());
|
const [month, setMonth] = useState<Dayjs>(dayjs());
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [data, setData] = useState<ScheduleData | null>(null);
|
|
||||||
const [detailModal, setDetailModal] = useState<any>(null);
|
const [detailModal, setDetailModal] = useState<any>(null);
|
||||||
|
|
||||||
const fetchData = useCallback(async () => {
|
const { data, isLoading, isFetching } = useQuery<ScheduleData | null>({
|
||||||
setLoading(true);
|
queryKey: ['classroom-rentals', 'schedule', month.year(), month.month()],
|
||||||
try {
|
queryFn: async () => {
|
||||||
const res: any = await api.get('/classroom-rentals/schedule', {
|
try {
|
||||||
params: { year: month.year(), month: month.month() + 1 },
|
return validateResponse<ScheduleData | null>(
|
||||||
});
|
classroomScheduleSchema,
|
||||||
setData(res);
|
await api.get('/classroom-rentals/schedule', {
|
||||||
} catch (e: unknown) {
|
params: { year: month.year(), month: month.month() + 1 },
|
||||||
const err = e as { message?: string };
|
}),
|
||||||
message.error(err?.message || '加载失败,请稍后重试');
|
);
|
||||||
}
|
} catch (e: unknown) {
|
||||||
setLoading(false);
|
message.error(getErrorMessage(e, '加载失败,请稍后重试'));
|
||||||
}, [month]);
|
return null;
|
||||||
|
}
|
||||||
useEffect(() => {
|
},
|
||||||
fetchData();
|
});
|
||||||
}, [fetchData]);
|
const loading = isLoading || isFetching;
|
||||||
|
|
||||||
// 按楼栋+楼层分组教室
|
// 按楼栋+楼层分组教室
|
||||||
const groups = useMemo(() => {
|
const groups = useMemo(() => {
|
||||||
@@ -88,8 +90,7 @@ const ClassroomSchedulePage: React.FC = () => {
|
|||||||
const res: any = await api.get(`/classroom-rentals/${rentalId}`);
|
const res: any = await api.get(`/classroom-rentals/${rentalId}`);
|
||||||
setDetailModal(res);
|
setDetailModal(res);
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const err = e as { message?: string };
|
message.error(getErrorMessage(e, '加载详情失败'));
|
||||||
message.error(err?.message || '加载详情失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
import React, { useEffect, useState, useMemo } from 'react';
|
import React, { useState, useMemo } from 'react';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||||
|
import { validateResponse } from '../../utils/validate';
|
||||||
|
import { classroomsSchema } from '../../api/schemas';
|
||||||
import {
|
import {
|
||||||
|
App,
|
||||||
Table,
|
Table,
|
||||||
Button,
|
Button,
|
||||||
Modal,
|
Modal,
|
||||||
@@ -50,9 +55,8 @@ const typeColor: Record<string, string> = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const ClassroomsPage: React.FC = () => {
|
const ClassroomsPage: React.FC = () => {
|
||||||
|
const { modal } = App.useApp();
|
||||||
const { hasPermission } = usePermission();
|
const { hasPermission } = usePermission();
|
||||||
const [data, setData] = useState<any[]>([]);
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [modalOpen, setModalOpen] = useState(false);
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
const [editing, setEditing] = useState<any>(null);
|
const [editing, setEditing] = useState<any>(null);
|
||||||
const [showArchived, setShowArchived] = useState(false);
|
const [showArchived, setShowArchived] = useState(false);
|
||||||
@@ -62,6 +66,56 @@ const ClassroomsPage: React.FC = () => {
|
|||||||
|
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
const {
|
||||||
|
data = [],
|
||||||
|
isLoading,
|
||||||
|
isFetching,
|
||||||
|
} = useQuery<any[]>({
|
||||||
|
queryKey: ['classrooms', showArchived],
|
||||||
|
queryFn: async () => {
|
||||||
|
try {
|
||||||
|
return validateResponse<any[]>(
|
||||||
|
classroomsSchema,
|
||||||
|
await api.get('/classrooms', { params: { includeArchived: showArchived } }),
|
||||||
|
);
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '加载失败,请稍后重试');
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const loading = isLoading || isFetching;
|
||||||
|
|
||||||
|
const saveMutation = useApiMutation(
|
||||||
|
async (values: Record<string, unknown>) =>
|
||||||
|
editing ? api.put(`/classrooms/${editing.id}`, values) : api.post('/classrooms', values),
|
||||||
|
{ invalidate: [['classrooms']] },
|
||||||
|
);
|
||||||
|
const saveCellMutation = useApiMutation(
|
||||||
|
async ({ record, field, value }: { record: any; field: string; value: unknown }) =>
|
||||||
|
api.put(`/classrooms/${record.id}`, { [field]: value }),
|
||||||
|
{ invalidate: [['classrooms']] },
|
||||||
|
);
|
||||||
|
const archiveMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/classrooms/${id}`),
|
||||||
|
{ invalidate: [['classrooms']] },
|
||||||
|
);
|
||||||
|
const restoreMutation = useApiMutation(
|
||||||
|
async (id: number) => api.put(`/classrooms/${id}/restore`),
|
||||||
|
{ invalidate: [['classrooms']] },
|
||||||
|
);
|
||||||
|
const purgeMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/classrooms/${id}/permanent`),
|
||||||
|
{ invalidate: [['classrooms']] },
|
||||||
|
);
|
||||||
|
const importMutation = useApiMutation(
|
||||||
|
async (formData: FormData) =>
|
||||||
|
api.post('/classrooms/import', formData, {
|
||||||
|
headers: { 'Content-Type': 'multipart/form-data' },
|
||||||
|
}),
|
||||||
|
{ invalidate: [['classrooms']] },
|
||||||
|
);
|
||||||
|
|
||||||
const filteredData = useMemo(() => {
|
const filteredData = useMemo(() => {
|
||||||
let result = data;
|
let result = data;
|
||||||
if (searchText) {
|
if (searchText) {
|
||||||
@@ -77,69 +131,67 @@ const ClassroomsPage: React.FC = () => {
|
|||||||
return result;
|
return result;
|
||||||
}, [data, searchText, filterStatus]);
|
}, [data, searchText, filterStatus]);
|
||||||
|
|
||||||
const fetchData = async () => {
|
|
||||||
setLoading(true);
|
|
||||||
try {
|
|
||||||
const res: any = await api.get('/classrooms', { params: { includeArchived: showArchived } });
|
|
||||||
setData(res);
|
|
||||||
} catch (e: any) {
|
|
||||||
message.error(e?.message || '加载失败,请稍后重试');
|
|
||||||
}
|
|
||||||
setLoading(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchData();
|
|
||||||
}, [showArchived]);
|
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
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(`/classrooms/${editing.id}`, values);
|
message.success(editing ? '更新成功' : '创建成功');
|
||||||
message.success('更新成功');
|
|
||||||
} else {
|
|
||||||
await api.post('/classrooms', values);
|
|
||||||
message.success('创建成功');
|
|
||||||
}
|
|
||||||
setModalOpen(false);
|
setModalOpen(false);
|
||||||
form.resetFields();
|
form.resetFields();
|
||||||
setEditing(null);
|
setEditing(null);
|
||||||
fetchData();
|
} catch {
|
||||||
} catch (e: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error(e?.message || '操作失败');
|
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false);
|
setSaving(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const saveCell = async (record: any, field: string, value: unknown) => {
|
const saveCell = async (record: any, field: string, value: unknown) => {
|
||||||
await api.put(`/classrooms/${record.id}`, { [field]: value });
|
try {
|
||||||
message.success('已保存');
|
await saveCellMutation.mutateAsync({ record, field, value });
|
||||||
await fetchData();
|
message.success('已保存');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleArchive = async (id: number) => {
|
const handleArchive = async (id: number) => {
|
||||||
try {
|
try {
|
||||||
await api.delete(`/classrooms/${id}`);
|
await archiveMutation.mutateAsync(id);
|
||||||
message.success('已归档');
|
message.success('已归档');
|
||||||
fetchData();
|
} catch {
|
||||||
} catch (e: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error(e?.message || '归档失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleRestore = async (id: number) => {
|
const handleRestore = async (id: number) => {
|
||||||
try {
|
try {
|
||||||
await api.put(`/classrooms/${id}/restore`);
|
await restoreMutation.mutateAsync(id);
|
||||||
message.success('已恢复');
|
message.success('已恢复');
|
||||||
fetchData();
|
} catch {
|
||||||
} catch (e: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error(e?.message || '恢复失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handlePurge = (id: number, name: string) => {
|
||||||
|
modal.confirm({
|
||||||
|
title: `永久删除教室「${name}」?`,
|
||||||
|
content: '删除后不可恢复,该教室及其排课、租赁、考勤机关联将被清除(存在关联数据时将无法删除)。确定继续?',
|
||||||
|
okText: '永久删除',
|
||||||
|
okButtonProps: { danger: true },
|
||||||
|
cancelText: '取消',
|
||||||
|
onOk: async () => {
|
||||||
|
try {
|
||||||
|
await purgeMutation.mutateAsync(id);
|
||||||
|
message.success('已永久删除(不可恢复)');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const handleDownloadTemplate = () => {
|
const handleDownloadTemplate = () => {
|
||||||
const baseURL = import.meta.env.PROD
|
const baseURL = import.meta.env.PROD
|
||||||
? '/api'
|
? '/api'
|
||||||
@@ -177,6 +229,7 @@ const ClassroomsPage: React.FC = () => {
|
|||||||
</EditableCell>
|
</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '楼栋',
|
title: '楼栋',
|
||||||
dataIndex: 'building',
|
dataIndex: 'building',
|
||||||
@@ -192,6 +245,7 @@ const ClassroomsPage: React.FC = () => {
|
|||||||
</EditableCell>
|
</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '楼层',
|
title: '楼层',
|
||||||
dataIndex: 'floor',
|
dataIndex: 'floor',
|
||||||
@@ -208,6 +262,7 @@ const ClassroomsPage: React.FC = () => {
|
|||||||
</EditableCell>
|
</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '类型',
|
title: '类型',
|
||||||
width: 90,
|
width: 90,
|
||||||
@@ -225,6 +280,7 @@ const ClassroomsPage: React.FC = () => {
|
|||||||
</EditableCell>
|
</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '容量',
|
title: '容量',
|
||||||
dataIndex: 'capacity',
|
dataIndex: 'capacity',
|
||||||
@@ -242,6 +298,7 @@ const ClassroomsPage: React.FC = () => {
|
|||||||
</EditableCell>
|
</EditableCell>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '状态',
|
title: '状态',
|
||||||
width: 100,
|
width: 100,
|
||||||
@@ -278,22 +335,35 @@ const ClassroomsPage: React.FC = () => {
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
title: '操作',
|
title: '操作',
|
||||||
width: 180,
|
width: 180,
|
||||||
render: (_: any, record: any) => (
|
render: (_: any, record: any) => (
|
||||||
<Space>
|
<Space>
|
||||||
{record.status === 'archived' ? (
|
{record.status === 'archived' ? (
|
||||||
<Popconfirm title="确定恢复此教室?" onConfirm={() => handleRestore(record.id)}>
|
<>
|
||||||
<PermissionButton
|
<Popconfirm title="确定恢复此教室?" onConfirm={() => handleRestore(record.id)}>
|
||||||
permission="classroom:edit"
|
<PermissionButton
|
||||||
size="small"
|
permission="classroom:edit"
|
||||||
icon={<UndoOutlined />}
|
size="small"
|
||||||
type="link"
|
icon={<UndoOutlined />}
|
||||||
>
|
type="link"
|
||||||
恢复
|
>
|
||||||
</PermissionButton>
|
恢复
|
||||||
</Popconfirm>
|
</PermissionButton>
|
||||||
|
</Popconfirm>
|
||||||
|
{hasPermission('classroom:purge') ? (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
danger
|
||||||
|
type="link"
|
||||||
|
onClick={() => handlePurge(record.id, record.name)}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<PermissionButton
|
<PermissionButton
|
||||||
@@ -327,7 +397,7 @@ const ClassroomsPage: React.FC = () => {
|
|||||||
),
|
),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
[],
|
[handlePurge, hasPermission],
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -413,15 +483,11 @@ const ClassroomsPage: React.FC = () => {
|
|||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('file', file);
|
formData.append('file', file);
|
||||||
try {
|
try {
|
||||||
const res: any = await api.post('/classrooms/import', formData, {
|
const res: any = await importMutation.mutateAsync(formData);
|
||||||
headers: { 'Content-Type': 'multipart/form-data' },
|
|
||||||
});
|
|
||||||
message.success(res.message);
|
message.success(res.message);
|
||||||
onSuccess?.(res);
|
onSuccess?.(res);
|
||||||
fetchData();
|
} catch (e) {
|
||||||
} catch (e: any) {
|
onError?.(e as Error);
|
||||||
message.error(e?.message || '导入失败');
|
|
||||||
onError?.(e);
|
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
|||||||
128
apps/admin/src/pages/Dashboard/Dashboard.types.ts
Normal file
128
apps/admin/src/pages/Dashboard/Dashboard.types.ts
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
import React from 'react';
|
||||||
|
|
||||||
|
export const COLORS = [
|
||||||
|
'#007AFF',
|
||||||
|
'#34C759',
|
||||||
|
'#FF9500',
|
||||||
|
'#FF3B30',
|
||||||
|
'#5AC8FA',
|
||||||
|
'#AF52DE',
|
||||||
|
'#FF2D55',
|
||||||
|
'#FFCC00',
|
||||||
|
];
|
||||||
|
|
||||||
|
export interface BillStatRow {
|
||||||
|
status: string;
|
||||||
|
count: string;
|
||||||
|
total: string;
|
||||||
|
}
|
||||||
|
export interface ClassAttendanceRank {
|
||||||
|
className: string;
|
||||||
|
present: number;
|
||||||
|
total: number;
|
||||||
|
rate: number;
|
||||||
|
}
|
||||||
|
export interface ClassroomOccupancy {
|
||||||
|
name: string;
|
||||||
|
building: string;
|
||||||
|
capacity: number;
|
||||||
|
scheduleDays: number;
|
||||||
|
rentalCount: number;
|
||||||
|
occupancy: number;
|
||||||
|
}
|
||||||
|
export interface ClassroomUtilStats {
|
||||||
|
totalClassrooms: number;
|
||||||
|
inUseCount: number;
|
||||||
|
utilizationRate: string;
|
||||||
|
scheduleCount: number;
|
||||||
|
rentalCount: number;
|
||||||
|
}
|
||||||
|
export interface AttendanceTrendRow {
|
||||||
|
date: string;
|
||||||
|
rate: string;
|
||||||
|
}
|
||||||
|
export interface IncomeTrendRow {
|
||||||
|
month: string;
|
||||||
|
amount: number;
|
||||||
|
}
|
||||||
|
export interface OccupancyByBuildingRow {
|
||||||
|
building: string;
|
||||||
|
count: string;
|
||||||
|
}
|
||||||
|
export interface ExpenseByTypeRow {
|
||||||
|
type: string;
|
||||||
|
total: string;
|
||||||
|
}
|
||||||
|
export interface GanttOccupancy {
|
||||||
|
studentName: string;
|
||||||
|
studentId?: string;
|
||||||
|
checkInDate: string;
|
||||||
|
checkOutDate: string | null;
|
||||||
|
billingStartDate?: string;
|
||||||
|
billingEndDate?: string;
|
||||||
|
}
|
||||||
|
export interface GanttRoom {
|
||||||
|
roomNumber: string;
|
||||||
|
occupancies: GanttOccupancy[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DashboardStats {
|
||||||
|
totalRooms: number;
|
||||||
|
totalStudents: number;
|
||||||
|
occupiedBeds: number;
|
||||||
|
totalCapacity: number;
|
||||||
|
occupancyRate: string;
|
||||||
|
billStats: BillStatRow[];
|
||||||
|
classroomCount: number;
|
||||||
|
classroomOccupancyRate: string;
|
||||||
|
todayAttendanceRate?: string;
|
||||||
|
monthlyIncome: number;
|
||||||
|
classCount: number;
|
||||||
|
teacherCount: number;
|
||||||
|
pendingDeposits: number;
|
||||||
|
activeRentals: number;
|
||||||
|
todayPresent: number;
|
||||||
|
occupancyByBuilding: OccupancyByBuildingRow[];
|
||||||
|
attendanceByStatus: Record<string, number>;
|
||||||
|
expenseByType: ExpenseByTypeRow[];
|
||||||
|
attendanceTrend: AttendanceTrendRow[];
|
||||||
|
incomeTrend: IncomeTrendRow[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const attendanceLabelMap: Record<string, string> = {
|
||||||
|
present: '出勤',
|
||||||
|
absent: '缺勤',
|
||||||
|
late: '迟到',
|
||||||
|
early: '早退',
|
||||||
|
leave: '请假',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const SECTION_ROW_STYLE: React.CSSProperties = { marginBottom: 24 };
|
||||||
|
export const MARGIN_BOTTOM_16_STYLE: React.CSSProperties = { marginBottom: 16 };
|
||||||
|
|
||||||
|
export const TODO_CARD_BASE: React.CSSProperties = {
|
||||||
|
cursor: 'pointer',
|
||||||
|
transition: 'box-shadow 0.2s, transform 0.2s',
|
||||||
|
borderRadius: 8,
|
||||||
|
height: '100%',
|
||||||
|
};
|
||||||
|
export const TODO_CARD_WARN: React.CSSProperties = {
|
||||||
|
...TODO_CARD_BASE,
|
||||||
|
borderLeft: '4px solid #FF9500',
|
||||||
|
background: '#fff7e6',
|
||||||
|
};
|
||||||
|
export const TODO_CARD_DANGER: React.CSSProperties = {
|
||||||
|
...TODO_CARD_BASE,
|
||||||
|
borderLeft: '4px solid #FF3B30',
|
||||||
|
background: '#fff1f0',
|
||||||
|
};
|
||||||
|
export const TODO_CARD_OK: React.CSSProperties = {
|
||||||
|
...TODO_CARD_BASE,
|
||||||
|
borderLeft: '4px solid #34C759',
|
||||||
|
background: '#f0fff4',
|
||||||
|
};
|
||||||
|
export const TODO_CARD_DRAFT: React.CSSProperties = {
|
||||||
|
...TODO_CARD_BASE,
|
||||||
|
borderLeft: '4px solid #AF52DE',
|
||||||
|
background: '#f9f0ff',
|
||||||
|
};
|
||||||
262
apps/admin/src/pages/Dashboard/DashboardCharts.ts
Normal file
262
apps/admin/src/pages/Dashboard/DashboardCharts.ts
Normal file
@@ -0,0 +1,262 @@
|
|||||||
|
import type { EChartsOption } from '../../components/ECharts';
|
||||||
|
import {
|
||||||
|
attendanceLabelMap,
|
||||||
|
COLORS,
|
||||||
|
type AttendanceTrendRow,
|
||||||
|
type ClassAttendanceRank,
|
||||||
|
type ClassroomOccupancy,
|
||||||
|
type DashboardStats,
|
||||||
|
type ExpenseByTypeRow,
|
||||||
|
type GanttRoom,
|
||||||
|
type IncomeTrendRow,
|
||||||
|
} from './Dashboard.types';
|
||||||
|
|
||||||
|
export function buildAttendanceRingOption(stats: DashboardStats | null): EChartsOption {
|
||||||
|
return {
|
||||||
|
tooltip: { trigger: 'item' },
|
||||||
|
legend: { bottom: 0 },
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
type: 'pie',
|
||||||
|
radius: ['40%', '70%'],
|
||||||
|
center: ['50%', '45%'],
|
||||||
|
data: Object.entries(stats?.attendanceByStatus ?? {}).map(([status, count]) => ({
|
||||||
|
name: attendanceLabelMap[status] ?? status,
|
||||||
|
value: count,
|
||||||
|
})),
|
||||||
|
itemStyle: { borderRadius: 4, borderColor: '#fff', borderWidth: 2 },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
color: COLORS,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildRoomRankingBarOption(
|
||||||
|
roomRanking: Array<{ roomNumber: string; total: string }>,
|
||||||
|
): EChartsOption {
|
||||||
|
return {
|
||||||
|
tooltip: {},
|
||||||
|
grid: { left: 80, right: 20, bottom: 30, top: 10 },
|
||||||
|
xAxis: { type: 'value' },
|
||||||
|
yAxis: {
|
||||||
|
type: 'category',
|
||||||
|
data: roomRanking.map((r) => r.roomNumber).reverse(),
|
||||||
|
inverse: false,
|
||||||
|
},
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
type: 'bar',
|
||||||
|
data: roomRanking.map((r) => Number(r.total)).reverse(),
|
||||||
|
itemStyle: { color: '#007AFF', borderRadius: [0, 4, 4, 0] },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildClassRankingOption(
|
||||||
|
rows: ClassAttendanceRank[],
|
||||||
|
color: string,
|
||||||
|
): EChartsOption {
|
||||||
|
return {
|
||||||
|
tooltip: {
|
||||||
|
trigger: 'axis',
|
||||||
|
axisPointer: { type: 'shadow' },
|
||||||
|
valueFormatter: (v: number) => `${v}%`,
|
||||||
|
},
|
||||||
|
grid: { left: 80, right: 30, bottom: 30, top: 10 },
|
||||||
|
xAxis: { type: 'value', max: 100, axisLabel: { formatter: '{value}%' } },
|
||||||
|
yAxis: {
|
||||||
|
type: 'category',
|
||||||
|
data: rows.map((r) => r.className),
|
||||||
|
inverse: true,
|
||||||
|
},
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
type: 'bar',
|
||||||
|
data: rows.map((r) => r.rate),
|
||||||
|
itemStyle: { color, borderRadius: [0, 4, 4, 0] },
|
||||||
|
label: { show: true, position: 'right', formatter: '{c}%' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildAttendanceLineOption(rows: AttendanceTrendRow[]): EChartsOption {
|
||||||
|
return {
|
||||||
|
tooltip: { trigger: 'axis' },
|
||||||
|
grid: { left: 50, right: 20, bottom: 30, top: 10 },
|
||||||
|
xAxis: {
|
||||||
|
type: 'category',
|
||||||
|
data: rows.map((d) => d.date),
|
||||||
|
axisLabel: { rotate: 45, fontSize: 10 },
|
||||||
|
},
|
||||||
|
yAxis: { type: 'value', min: 0, max: 100, axisLabel: { formatter: '{value}%' } },
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
type: 'line',
|
||||||
|
data: rows.map((d) => parseFloat(d.rate) || 0),
|
||||||
|
smooth: true,
|
||||||
|
lineStyle: { color: '#007AFF', width: 2 },
|
||||||
|
itemStyle: { color: '#007AFF' },
|
||||||
|
areaStyle: { color: 'rgba(0,122,255,0.1)' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildIncomeLineOption(rows: IncomeTrendRow[]): EChartsOption {
|
||||||
|
return {
|
||||||
|
tooltip: { trigger: 'axis', valueFormatter: (v: number) => `¥${v.toLocaleString()}` },
|
||||||
|
grid: { left: 70, right: 20, bottom: 30, top: 10 },
|
||||||
|
xAxis: {
|
||||||
|
type: 'category',
|
||||||
|
data: rows.map((d) => d.month),
|
||||||
|
},
|
||||||
|
yAxis: {
|
||||||
|
type: 'value',
|
||||||
|
axisLabel: { formatter: (v: number) => `¥${(v / 10000).toFixed(0)}万` },
|
||||||
|
},
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
type: 'line',
|
||||||
|
data: rows.map((d) => d.amount),
|
||||||
|
smooth: true,
|
||||||
|
lineStyle: { color: '#34C759', width: 2 },
|
||||||
|
itemStyle: { color: '#34C759' },
|
||||||
|
areaStyle: { color: 'rgba(52,199,89,0.1)' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildExpensePieOption(
|
||||||
|
rows: ExpenseByTypeRow[],
|
||||||
|
expenseTypeMap: Record<string, string>,
|
||||||
|
): EChartsOption {
|
||||||
|
return {
|
||||||
|
tooltip: { trigger: 'item' },
|
||||||
|
legend: { bottom: 0 },
|
||||||
|
color: COLORS,
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
type: 'pie',
|
||||||
|
radius: ['40%', '70%'],
|
||||||
|
center: ['50%', '45%'],
|
||||||
|
data: rows.map((e) => ({
|
||||||
|
name: expenseTypeMap[e.type] ?? e.type,
|
||||||
|
value: Number(e.total),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildClassroomHeatmapOption(
|
||||||
|
classroomOccupancy: ClassroomOccupancy[],
|
||||||
|
): EChartsOption {
|
||||||
|
return {
|
||||||
|
tooltip: {
|
||||||
|
formatter: (p: {
|
||||||
|
name: string;
|
||||||
|
data: { scheduleDays: number; rentalCount: number; occupancy: number };
|
||||||
|
}) =>
|
||||||
|
`${p.name}<br/>排课: ${p.data.scheduleDays}天 租赁: ${p.data.rentalCount}个 占用率: ${(p.data.occupancy * 100).toFixed(0)}%`,
|
||||||
|
},
|
||||||
|
grid: { left: 100, right: 20, bottom: 30, top: 10 },
|
||||||
|
xAxis: { type: 'value', max: 1 },
|
||||||
|
yAxis: {
|
||||||
|
type: 'category',
|
||||||
|
data: classroomOccupancy.map((r) => r.name),
|
||||||
|
inverse: true,
|
||||||
|
},
|
||||||
|
visualMap: {
|
||||||
|
min: 0,
|
||||||
|
max: 1,
|
||||||
|
orient: 'horizontal',
|
||||||
|
left: 'center',
|
||||||
|
bottom: 0,
|
||||||
|
inRange: {
|
||||||
|
color: ['#e6f4ff', '#91caff', '#40a9ff', '#0050b3', '#002c8c'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
type: 'bar',
|
||||||
|
data: classroomOccupancy.map((r) => ({
|
||||||
|
name: r.name,
|
||||||
|
value: r.occupancy,
|
||||||
|
scheduleDays: r.scheduleDays,
|
||||||
|
rentalCount: r.rentalCount,
|
||||||
|
occupancy: r.occupancy,
|
||||||
|
})),
|
||||||
|
itemStyle: { borderRadius: [0, 4, 4, 0] },
|
||||||
|
label: {
|
||||||
|
show: true,
|
||||||
|
position: 'right',
|
||||||
|
formatter: (p: { data: { occupancy: number } }) =>
|
||||||
|
`${(p.data.occupancy * 100).toFixed(0)}%`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildGanttOption(ganttData: GanttRoom[]): EChartsOption {
|
||||||
|
return {
|
||||||
|
tooltip: {
|
||||||
|
formatter: (p: { data: { name: string; value: [string, string, string, boolean] } }) =>
|
||||||
|
`${p.data.name}<br/>入住: ${p.data.value[1]}<br/>退宿: ${p.data.value[2]}`,
|
||||||
|
},
|
||||||
|
grid: { left: 100, right: 30, bottom: 40, top: 20 },
|
||||||
|
xAxis: { type: 'time' },
|
||||||
|
yAxis: { type: 'category', data: ganttData.map((r) => r.roomNumber), inverse: true },
|
||||||
|
dataZoom: [
|
||||||
|
{ type: 'slider', xAxisIndex: 0, bottom: 10, height: 20 },
|
||||||
|
{ type: 'inside', xAxisIndex: 0 },
|
||||||
|
],
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
type: 'custom',
|
||||||
|
renderItem: (
|
||||||
|
_params: unknown,
|
||||||
|
api: {
|
||||||
|
value: (i: number) => string | boolean;
|
||||||
|
coord: (p: [string | number, string | number]) => [number, number];
|
||||||
|
size: (p: [number, number]) => [number, number];
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
const cat = String(api.value(0));
|
||||||
|
const startDate = String(api.value(1));
|
||||||
|
const endDate = String(api.value(2));
|
||||||
|
const isActive = Boolean(api.value(3));
|
||||||
|
const start = api.coord([startDate, cat]);
|
||||||
|
const end = api.coord([endDate, cat]);
|
||||||
|
const height = api.size([0, 1])[1] * 0.6;
|
||||||
|
const rectShape = {
|
||||||
|
x: start[0],
|
||||||
|
y: start[1] - height / 2,
|
||||||
|
width: Math.max(end[0] - start[0], 2),
|
||||||
|
height,
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
type: 'rect' as const,
|
||||||
|
shape: rectShape,
|
||||||
|
style: { fill: isActive ? '#34C759' : '#FF9500', stroke: '#fff', lineWidth: 1 },
|
||||||
|
};
|
||||||
|
},
|
||||||
|
encode: { x: [1, 2], y: 0 },
|
||||||
|
data: ganttData.flatMap((r) =>
|
||||||
|
(r.occupancies || []).map((o) => ({
|
||||||
|
name: o.studentName,
|
||||||
|
value: [
|
||||||
|
r.roomNumber,
|
||||||
|
o.checkInDate,
|
||||||
|
o.checkOutDate || new Date().toISOString().slice(0, 10),
|
||||||
|
!o.checkOutDate,
|
||||||
|
] as [string, string, string, boolean],
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
85
apps/admin/src/pages/Dashboard/DashboardLazyCards.tsx
Normal file
85
apps/admin/src/pages/Dashboard/DashboardLazyCards.tsx
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
import React, { type CSSProperties } from 'react';
|
||||||
|
import { Card, Col, Row } from 'antd';
|
||||||
|
import { useIntersectionObserver } from 'usehooks-ts';
|
||||||
|
import ReactECharts from '../../components/ECharts';
|
||||||
|
import type { ClassroomOccupancy, GanttRoom } from './Dashboard.types';
|
||||||
|
import { buildClassroomHeatmapOption, buildGanttOption } from './DashboardCharts';
|
||||||
|
|
||||||
|
const useInViewport = (rootMargin = '200px') => {
|
||||||
|
const { ref, isIntersecting } = useIntersectionObserver({
|
||||||
|
rootMargin,
|
||||||
|
freezeOnceVisible: true,
|
||||||
|
});
|
||||||
|
return { ref, inView: isIntersecting };
|
||||||
|
};
|
||||||
|
|
||||||
|
const LazySection: React.FC<{
|
||||||
|
title: string;
|
||||||
|
vp: { ref: (node?: Element | null) => void; inView: boolean };
|
||||||
|
minHeight: number;
|
||||||
|
style?: CSSProperties;
|
||||||
|
children: React.ReactNode;
|
||||||
|
}> = ({ title, vp, minHeight, style, children }) => {
|
||||||
|
return (
|
||||||
|
<div ref={vp.ref} style={style}>
|
||||||
|
{vp.inView ? (
|
||||||
|
<Row gutter={[16, 16]}>
|
||||||
|
<Col xs={24}>
|
||||||
|
<Card title={title}>{children}</Card>
|
||||||
|
</Col>
|
||||||
|
</Row>
|
||||||
|
) : (
|
||||||
|
<Card title={title} style={{ minHeight }}>
|
||||||
|
<div style={{ textAlign: 'center', padding: 40, color: '#999' }}>加载中…</div>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ClassroomHeatmapCard: React.FC<{
|
||||||
|
data: ClassroomOccupancy[];
|
||||||
|
isMobile: boolean;
|
||||||
|
}> = ({ data, isMobile }) => {
|
||||||
|
const vp = useInViewport('200px');
|
||||||
|
return (
|
||||||
|
<LazySection
|
||||||
|
title="教室占用热力图"
|
||||||
|
vp={vp}
|
||||||
|
minHeight={isMobile ? 340 : 440}
|
||||||
|
style={{ marginBottom: 24 }}
|
||||||
|
>
|
||||||
|
{data.length > 0 ? (
|
||||||
|
<ReactECharts
|
||||||
|
option={buildClassroomHeatmapOption(data)}
|
||||||
|
style={{ width: '100%', height: isMobile ? 300 : 400 }}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div style={{ textAlign: 'center', padding: 40, color: '#999' }}>暂无教室数据</div>
|
||||||
|
)}
|
||||||
|
</LazySection>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const GanttCard: React.FC<{ data: GanttRoom[]; isMobile: boolean }> = ({
|
||||||
|
data,
|
||||||
|
isMobile,
|
||||||
|
}) => {
|
||||||
|
const vp = useInViewport('200px');
|
||||||
|
return (
|
||||||
|
<LazySection
|
||||||
|
title="入住时间线(甘特图)"
|
||||||
|
vp={vp}
|
||||||
|
minHeight={isMobile ? 340 : 490}
|
||||||
|
>
|
||||||
|
{data.length > 0 ? (
|
||||||
|
<ReactECharts
|
||||||
|
option={buildGanttOption(data)}
|
||||||
|
style={{ width: '100%', height: isMobile ? 300 : 450 }}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div style={{ textAlign: 'center', padding: 40, color: '#999' }}>暂无入住数据</div>
|
||||||
|
)}
|
||||||
|
</LazySection>
|
||||||
|
);
|
||||||
|
};
|
||||||
124
apps/admin/src/pages/Dashboard/DashboardTodoCards.tsx
Normal file
124
apps/admin/src/pages/Dashboard/DashboardTodoCards.tsx
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Card, Col, Row } from 'antd';
|
||||||
|
import {
|
||||||
|
ArrowRightOutlined,
|
||||||
|
BankOutlined,
|
||||||
|
DollarOutlined,
|
||||||
|
ExclamationCircleOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import { useNavigate } from 'react-router';
|
||||||
|
import { MARGIN_BOTTOM_16_STYLE, TODO_CARD_DANGER, TODO_CARD_DRAFT, TODO_CARD_OK, TODO_CARD_WARN } from './Dashboard.types';
|
||||||
|
|
||||||
|
export const DashboardTodoCards: React.FC<{
|
||||||
|
absentCount: number;
|
||||||
|
draftCount: number;
|
||||||
|
draftTotal: number;
|
||||||
|
pendingDeposits: number;
|
||||||
|
}> = ({ absentCount, draftCount, draftTotal, pendingDeposits }) => {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
return (
|
||||||
|
<Card title="待办与异常" style={MARGIN_BOTTOM_16_STYLE}>
|
||||||
|
<Row gutter={[16, 16]}>
|
||||||
|
<Col xs={24} sm={8}>
|
||||||
|
<Card
|
||||||
|
style={absentCount > 0 ? TODO_CARD_WARN : TODO_CARD_OK}
|
||||||
|
styles={{ body: { padding: 16 } }}
|
||||||
|
onClick={() => navigate('/attendance')}
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||||
|
<ExclamationCircleOutlined
|
||||||
|
style={{ fontSize: 28, color: absentCount > 0 ? '#FF9500' : '#999' }}
|
||||||
|
/>
|
||||||
|
<ArrowRightOutlined style={{ color: '#bbb' }} />
|
||||||
|
</div>
|
||||||
|
<div style={{ marginTop: 8 }}>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
fontSize: 24,
|
||||||
|
fontWeight: 700,
|
||||||
|
color: absentCount > 0 ? '#FF9500' : '#999',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{absentCount}
|
||||||
|
</div>
|
||||||
|
<div style={{ fontSize: 13, color: '#666', marginTop: 2 }}>今日缺勤人数</div>
|
||||||
|
{absentCount > 0 ? (
|
||||||
|
<div style={{ fontSize: 12, color: '#FF9500', marginTop: 4 }}>需要关注</div>
|
||||||
|
) : (
|
||||||
|
<div style={{ fontSize: 12, color: '#34C759', marginTop: 4 }}>全员到齐</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
|
|
||||||
|
<Col xs={24} sm={8}>
|
||||||
|
<Card
|
||||||
|
style={draftCount > 0 ? TODO_CARD_DRAFT : TODO_CARD_OK}
|
||||||
|
styles={{ body: { padding: 16 } }}
|
||||||
|
onClick={() => navigate('/bills')}
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||||
|
<DollarOutlined
|
||||||
|
style={{ fontSize: 28, color: draftCount > 0 ? '#AF52DE' : '#999' }}
|
||||||
|
/>
|
||||||
|
<ArrowRightOutlined style={{ color: '#bbb' }} />
|
||||||
|
</div>
|
||||||
|
<div style={{ marginTop: 8 }}>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
fontSize: 24,
|
||||||
|
fontWeight: 700,
|
||||||
|
color: draftCount > 0 ? '#AF52DE' : '#999',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{draftCount}
|
||||||
|
</div>
|
||||||
|
<div style={{ fontSize: 13, color: '#666', marginTop: 2 }}>待处理账单</div>
|
||||||
|
<div
|
||||||
|
style={{ fontSize: 12, color: draftCount > 0 ? '#AF52DE' : '#999', marginTop: 4 }}
|
||||||
|
>
|
||||||
|
{draftCount > 0 ? `合计 ¥${draftTotal.toLocaleString()}` : '暂无待处理'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
|
|
||||||
|
<Col xs={24} sm={8}>
|
||||||
|
<Card
|
||||||
|
style={pendingDeposits > 0 ? TODO_CARD_DANGER : TODO_CARD_OK}
|
||||||
|
styles={{ body: { padding: 16 } }}
|
||||||
|
onClick={() => navigate('/deposits')}
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||||
|
<BankOutlined
|
||||||
|
style={{ fontSize: 28, color: pendingDeposits > 0 ? '#FF3B30' : '#999' }}
|
||||||
|
/>
|
||||||
|
<ArrowRightOutlined style={{ color: '#bbb' }} />
|
||||||
|
</div>
|
||||||
|
<div style={{ marginTop: 8 }}>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
fontSize: 24,
|
||||||
|
fontWeight: 700,
|
||||||
|
color: pendingDeposits > 0 ? '#FF3B30' : '#999',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
¥{pendingDeposits.toLocaleString()}
|
||||||
|
</div>
|
||||||
|
<div style={{ fontSize: 13, color: '#666', marginTop: 2 }}>待退押金</div>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
fontSize: 12,
|
||||||
|
color: pendingDeposits > 0 ? '#FF3B30' : '#999',
|
||||||
|
marginTop: 4,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{pendingDeposits > 0 ? '需要处理' : '暂无待退'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
|
</Row>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,4 +1,15 @@
|
|||||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { validateResponse } from '../../utils/validate';
|
||||||
|
import {
|
||||||
|
classAttendanceRankingSchema,
|
||||||
|
classroomOccupanciesSchema,
|
||||||
|
classroomUtilStatsSchema,
|
||||||
|
dashboardStatsSchema,
|
||||||
|
expenseTypesSchema,
|
||||||
|
ganttRoomsSchema,
|
||||||
|
roomRankingSchema,
|
||||||
|
} from '../../api/schemas';
|
||||||
import { Row, Col, Card, Statistic, DatePicker, Spin, Grid, Collapse } from 'antd';
|
import { Row, Col, Card, Statistic, DatePicker, Spin, Grid, Collapse } from 'antd';
|
||||||
import {
|
import {
|
||||||
TeamOutlined,
|
TeamOutlined,
|
||||||
@@ -11,460 +22,142 @@ import {
|
|||||||
FileProtectOutlined,
|
FileProtectOutlined,
|
||||||
ReadOutlined,
|
ReadOutlined,
|
||||||
CalendarOutlined,
|
CalendarOutlined,
|
||||||
ArrowRightOutlined,
|
|
||||||
ExclamationCircleOutlined,
|
|
||||||
DollarOutlined,
|
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import ReactECharts, { type EChartsOption } from '../../components/ECharts';
|
import ReactECharts from '../../components/ECharts';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import { useNavigate } from 'react-router-dom';
|
|
||||||
import api from '../../api';
|
import api from '../../api';
|
||||||
import { message } from '../../ui/app-message';
|
import { message } from '../../ui/app-message';
|
||||||
|
import {
|
||||||
|
buildAttendanceLineOption,
|
||||||
|
buildAttendanceRingOption,
|
||||||
|
buildClassRankingOption,
|
||||||
|
buildExpensePieOption,
|
||||||
|
buildIncomeLineOption,
|
||||||
|
buildRoomRankingBarOption,
|
||||||
|
} from './DashboardCharts';
|
||||||
|
import { ClassroomHeatmapCard, GanttCard } from './DashboardLazyCards';
|
||||||
|
import {
|
||||||
|
MARGIN_BOTTOM_16_STYLE,
|
||||||
|
SECTION_ROW_STYLE,
|
||||||
|
type ClassAttendanceRank,
|
||||||
|
type ClassroomOccupancy,
|
||||||
|
type ClassroomUtilStats,
|
||||||
|
type DashboardStats,
|
||||||
|
type GanttRoom,
|
||||||
|
} from './Dashboard.types';
|
||||||
|
import { DashboardTodoCards } from './DashboardTodoCards';
|
||||||
|
|
||||||
const { RangePicker } = DatePicker;
|
const { RangePicker } = DatePicker;
|
||||||
|
|
||||||
const COLORS = [
|
|
||||||
'#007AFF',
|
|
||||||
'#34C759',
|
|
||||||
'#FF9500',
|
|
||||||
'#FF3B30',
|
|
||||||
'#5AC8FA',
|
|
||||||
'#AF52DE',
|
|
||||||
'#FF2D55',
|
|
||||||
'#FFCC00',
|
|
||||||
];
|
|
||||||
|
|
||||||
interface BillStatRow {
|
|
||||||
status: string;
|
|
||||||
count: string;
|
|
||||||
total: string;
|
|
||||||
}
|
|
||||||
interface ClassAttendanceRank {
|
|
||||||
className: string;
|
|
||||||
present: number;
|
|
||||||
total: number;
|
|
||||||
rate: number;
|
|
||||||
}
|
|
||||||
interface ClassroomOccupancy {
|
|
||||||
name: string;
|
|
||||||
building: string;
|
|
||||||
capacity: number;
|
|
||||||
scheduleDays: number;
|
|
||||||
rentalCount: number;
|
|
||||||
occupancy: number;
|
|
||||||
}
|
|
||||||
interface ClassroomUtilStats {
|
|
||||||
totalClassrooms: number;
|
|
||||||
inUseCount: number;
|
|
||||||
utilizationRate: string;
|
|
||||||
scheduleCount: number;
|
|
||||||
rentalCount: number;
|
|
||||||
}
|
|
||||||
interface AttendanceTrendRow {
|
|
||||||
date: string;
|
|
||||||
rate: string;
|
|
||||||
}
|
|
||||||
interface IncomeTrendRow {
|
|
||||||
month: string;
|
|
||||||
amount: number;
|
|
||||||
}
|
|
||||||
interface OccupancyByBuildingRow {
|
|
||||||
building: string;
|
|
||||||
count: string;
|
|
||||||
}
|
|
||||||
interface ExpenseByTypeRow {
|
|
||||||
type: string;
|
|
||||||
total: string;
|
|
||||||
}
|
|
||||||
interface GanttOccupancy {
|
|
||||||
studentName: string;
|
|
||||||
studentId?: string;
|
|
||||||
checkInDate: string;
|
|
||||||
checkOutDate: string | null;
|
|
||||||
billingStartDate?: string;
|
|
||||||
billingEndDate?: string;
|
|
||||||
}
|
|
||||||
interface GanttRoom {
|
|
||||||
roomNumber: string;
|
|
||||||
occupancies: GanttOccupancy[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface DashboardStats {
|
|
||||||
totalRooms: number;
|
|
||||||
totalStudents: number;
|
|
||||||
occupiedBeds: number;
|
|
||||||
totalCapacity: number;
|
|
||||||
occupancyRate: string;
|
|
||||||
billStats: BillStatRow[];
|
|
||||||
classroomCount: number;
|
|
||||||
classroomOccupancyRate: string;
|
|
||||||
todayAttendanceRate: string;
|
|
||||||
monthlyIncome: number;
|
|
||||||
classCount: number;
|
|
||||||
teacherCount: number;
|
|
||||||
pendingDeposits: number;
|
|
||||||
activeRentals: number;
|
|
||||||
todayPresent: number;
|
|
||||||
occupancyByBuilding: OccupancyByBuildingRow[];
|
|
||||||
attendanceByStatus: Record<string, number>;
|
|
||||||
expenseByType: ExpenseByTypeRow[];
|
|
||||||
attendanceTrend: AttendanceTrendRow[];
|
|
||||||
incomeTrend: IncomeTrendRow[];
|
|
||||||
}
|
|
||||||
|
|
||||||
const attendanceLabelMap: Record<string, string> = {
|
|
||||||
present: '出勤',
|
|
||||||
absent: '缺勤',
|
|
||||||
late: '迟到',
|
|
||||||
early: '早退',
|
|
||||||
leave: '请假',
|
|
||||||
};
|
|
||||||
|
|
||||||
const SECTION_ROW_STYLE: React.CSSProperties = { marginBottom: 24 };
|
|
||||||
const MARGIN_BOTTOM_16_STYLE: React.CSSProperties = { marginBottom: 16 };
|
|
||||||
|
|
||||||
// ─── 待办卡片样式 ───
|
|
||||||
const TODO_CARD_BASE: React.CSSProperties = {
|
|
||||||
cursor: 'pointer',
|
|
||||||
transition: 'box-shadow 0.2s, transform 0.2s',
|
|
||||||
borderRadius: 8,
|
|
||||||
height: '100%',
|
|
||||||
};
|
|
||||||
const TODO_CARD_WARN: React.CSSProperties = {
|
|
||||||
...TODO_CARD_BASE,
|
|
||||||
borderLeft: '4px solid #FF9500',
|
|
||||||
background: '#fff7e6',
|
|
||||||
};
|
|
||||||
const TODO_CARD_DANGER: React.CSSProperties = {
|
|
||||||
...TODO_CARD_BASE,
|
|
||||||
borderLeft: '4px solid #FF3B30',
|
|
||||||
background: '#fff1f0',
|
|
||||||
};
|
|
||||||
const TODO_CARD_OK: React.CSSProperties = {
|
|
||||||
...TODO_CARD_BASE,
|
|
||||||
borderLeft: '4px solid #34C759',
|
|
||||||
background: '#f0fff4',
|
|
||||||
};
|
|
||||||
const TODO_CARD_DRAFT: React.CSSProperties = {
|
|
||||||
...TODO_CARD_BASE,
|
|
||||||
borderLeft: '4px solid #AF52DE',
|
|
||||||
background: '#f9f0ff',
|
|
||||||
};
|
|
||||||
|
|
||||||
// ─── IntersectionObserver 自定义 hook ───
|
|
||||||
// 用 callback ref 注册 observer,避免元素在首屏 loading 后才挂载、
|
|
||||||
// 而 effect 因依赖不变不再重跑导致 observer 从未注册的问题。
|
|
||||||
const useInViewport = (rootMargin = '200px') => {
|
|
||||||
const [inView, setInView] = useState(false);
|
|
||||||
const observerRef = useRef<IntersectionObserver | null>(null);
|
|
||||||
|
|
||||||
const ref = useCallback(
|
|
||||||
(el: HTMLDivElement | null) => {
|
|
||||||
observerRef.current?.disconnect();
|
|
||||||
if (!el) return;
|
|
||||||
const observer = new IntersectionObserver(
|
|
||||||
([entry]) => {
|
|
||||||
if (entry.isIntersecting) {
|
|
||||||
setInView(true);
|
|
||||||
observer.disconnect();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{ rootMargin },
|
|
||||||
);
|
|
||||||
observer.observe(el);
|
|
||||||
observerRef.current = observer;
|
|
||||||
},
|
|
||||||
[rootMargin],
|
|
||||||
);
|
|
||||||
|
|
||||||
return { ref, inView };
|
|
||||||
};
|
|
||||||
|
|
||||||
const DashboardPage: React.FC = () => {
|
const DashboardPage: React.FC = () => {
|
||||||
const screens = Grid.useBreakpoint();
|
const screens = Grid.useBreakpoint();
|
||||||
const isMobile = !screens.sm;
|
const isMobile = !screens.sm;
|
||||||
const navigate = useNavigate();
|
|
||||||
const [stats, setStats] = useState<DashboardStats | null>(null);
|
|
||||||
const [classRanking, setClassRanking] = useState<{
|
|
||||||
top: ClassAttendanceRank[];
|
|
||||||
bottom: ClassAttendanceRank[];
|
|
||||||
}>({ top: [], bottom: [] });
|
|
||||||
const [classroomOccupancy, setClassroomOccupancy] = useState<ClassroomOccupancy[]>([]);
|
|
||||||
const [ganttData, setGanttData] = useState<GanttRoom[]>([]);
|
|
||||||
const [roomRanking, setRoomRanking] = useState<Array<{ roomNumber: string; total: string }>>([]);
|
|
||||||
const [classroomUtil, setClassroomUtil] = useState<ClassroomUtilStats | null>(null);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [refreshLoading, setRefreshLoading] = useState(false);
|
|
||||||
const loadedRef = useRef(false);
|
|
||||||
const [period, setPeriod] = useState<[string, string]>([
|
const [period, setPeriod] = useState<[string, string]>([
|
||||||
dayjs().startOf('month').format('YYYY-MM-DD'),
|
dayjs().startOf('month').format('YYYY-MM-DD'),
|
||||||
dayjs().endOf('month').format('YYYY-MM-DD'),
|
dayjs().endOf('month').format('YYYY-MM-DD'),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const fetchData = useCallback(async () => {
|
const {
|
||||||
const isRefresh = loadedRef.current;
|
data: fetchResult = {
|
||||||
if (isRefresh) {
|
stats: null,
|
||||||
setRefreshLoading(true);
|
classRanking: { top: [], bottom: [] },
|
||||||
} else {
|
classroomOccupancy: [],
|
||||||
setLoading(true);
|
ganttData: [],
|
||||||
}
|
roomRanking: [],
|
||||||
try {
|
classroomUtil: null,
|
||||||
const [s, rr, cr, g, co, cu] = await Promise.all([
|
},
|
||||||
api.get<DashboardStats>('/dashboard/stats'),
|
isLoading,
|
||||||
api.get<Array<{ roomNumber: string; total: string }>>('/dashboard/room-ranking', {
|
isFetching,
|
||||||
params: { periodStart: period[0], periodEnd: period[1] },
|
} = useQuery<{
|
||||||
}),
|
stats: DashboardStats | null;
|
||||||
api.get<{ top: ClassAttendanceRank[]; bottom: ClassAttendanceRank[] }>(
|
classRanking: { top: ClassAttendanceRank[]; bottom: ClassAttendanceRank[] };
|
||||||
'/dashboard/class-attendance-ranking',
|
classroomOccupancy: ClassroomOccupancy[];
|
||||||
),
|
ganttData: GanttRoom[];
|
||||||
api.get<GanttRoom[]>('/dashboard/gantt', {
|
roomRanking: Array<{ roomNumber: string; total: string }>;
|
||||||
params: { periodStart: period[0], periodEnd: period[1] },
|
classroomUtil: ClassroomUtilStats | null;
|
||||||
}),
|
}>({
|
||||||
api.get<ClassroomOccupancy[]>('/dashboard/classroom-occupancy'),
|
queryKey: ['dashboard', period],
|
||||||
api.get<ClassroomUtilStats>('/dashboard/classroom-utilization'),
|
queryFn: async () => {
|
||||||
]);
|
try {
|
||||||
setStats(s);
|
const [s, rr, cr, g, co, cu] = await Promise.all([
|
||||||
setRoomRanking(rr);
|
api.get<DashboardStats>('/dashboard/stats'),
|
||||||
setClassRanking(cr);
|
api.get<Array<{ roomNumber: string; total: string }>>('/dashboard/room-ranking', {
|
||||||
setGanttData(g);
|
params: { periodStart: period[0], periodEnd: period[1] },
|
||||||
setClassroomOccupancy(co);
|
}),
|
||||||
setClassroomUtil(cu);
|
api.get<{ top: ClassAttendanceRank[]; bottom: ClassAttendanceRank[] }>(
|
||||||
loadedRef.current = true;
|
'/dashboard/class-attendance-ranking',
|
||||||
} catch (e) {
|
),
|
||||||
console.error(e);
|
api.get<GanttRoom[]>('/dashboard/gantt', {
|
||||||
message.error('数据加载失败,请稍后重试');
|
params: { periodStart: period[0], periodEnd: period[1] },
|
||||||
}
|
}),
|
||||||
setLoading(false);
|
api.get<ClassroomOccupancy[]>('/dashboard/classroom-occupancy'),
|
||||||
setRefreshLoading(false);
|
api.get<ClassroomUtilStats>('/dashboard/classroom-utilization'),
|
||||||
}, [period]);
|
]);
|
||||||
|
return {
|
||||||
|
stats: validateResponse<DashboardStats>(dashboardStatsSchema, s),
|
||||||
|
roomRanking: validateResponse<Array<{ roomNumber: string; total: string }>>(
|
||||||
|
roomRankingSchema,
|
||||||
|
rr,
|
||||||
|
),
|
||||||
|
classRanking: validateResponse<{
|
||||||
|
top: ClassAttendanceRank[];
|
||||||
|
bottom: ClassAttendanceRank[];
|
||||||
|
}>(classAttendanceRankingSchema, cr),
|
||||||
|
ganttData: validateResponse<GanttRoom[]>(ganttRoomsSchema, g),
|
||||||
|
classroomOccupancy: validateResponse<ClassroomOccupancy[]>(
|
||||||
|
classroomOccupanciesSchema,
|
||||||
|
co,
|
||||||
|
),
|
||||||
|
classroomUtil: validateResponse<ClassroomUtilStats>(classroomUtilStatsSchema, cu),
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
message.error('数据加载失败,请稍后重试');
|
||||||
|
return {
|
||||||
|
stats: null,
|
||||||
|
classRanking: { top: [], bottom: [] },
|
||||||
|
classroomOccupancy: [],
|
||||||
|
ganttData: [],
|
||||||
|
roomRanking: [],
|
||||||
|
classroomUtil: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const stats = fetchResult.stats;
|
||||||
|
const classRanking = fetchResult.classRanking;
|
||||||
|
const classroomOccupancy = fetchResult.classroomOccupancy;
|
||||||
|
const ganttData = fetchResult.ganttData;
|
||||||
|
const roomRanking = fetchResult.roomRanking;
|
||||||
|
const classroomUtil = fetchResult.classroomUtil;
|
||||||
|
const loading = isLoading;
|
||||||
|
const refreshLoading = isFetching && !isLoading;
|
||||||
|
|
||||||
useEffect(() => {
|
const { data: expenseTypeMap = {} } = useQuery<Record<string, string>>({
|
||||||
fetchData();
|
queryKey: ['expense-types', 'map'],
|
||||||
}, [fetchData]);
|
queryFn: async () => {
|
||||||
|
try {
|
||||||
const [expenseTypeMap, setExpenseTypeMap] = useState<Record<string, string>>({});
|
const types = validateResponse<Array<{ code: string; name: string }>>(
|
||||||
|
expenseTypesSchema,
|
||||||
useEffect(() => {
|
await api.get<Array<{ code: string; name: string }>>('/expense-types'),
|
||||||
api
|
);
|
||||||
.get<Array<{ code: string; name: string }>>('/expense-types')
|
|
||||||
.then((types) => {
|
|
||||||
const map: Record<string, string> = {};
|
const map: Record<string, string> = {};
|
||||||
for (const t of types) map[t.code] = t.name;
|
for (const t of types) map[t.code] = t.name;
|
||||||
setExpenseTypeMap(map);
|
return map;
|
||||||
})
|
} catch {
|
||||||
.catch(() => {});
|
return {};
|
||||||
}, []);
|
}
|
||||||
|
|
||||||
// ─── 图表 option 计算(保留全部原有逻辑) ───
|
|
||||||
|
|
||||||
// 今日出勤状态分布环图
|
|
||||||
const attendanceRingOption = useMemo<EChartsOption>(
|
|
||||||
() => ({
|
|
||||||
tooltip: { trigger: 'item' },
|
|
||||||
legend: { bottom: 0 },
|
|
||||||
series: [
|
|
||||||
{
|
|
||||||
type: 'pie',
|
|
||||||
radius: ['40%', '70%'],
|
|
||||||
center: ['50%', '45%'],
|
|
||||||
data: Object.entries(stats?.attendanceByStatus ?? {}).map(([status, count]) => ({
|
|
||||||
name: attendanceLabelMap[status] ?? status,
|
|
||||||
value: count,
|
|
||||||
})),
|
|
||||||
itemStyle: { borderRadius: 4, borderColor: '#fff', borderWidth: 2 },
|
|
||||||
},
|
|
||||||
],
|
|
||||||
color: COLORS,
|
|
||||||
}),
|
|
||||||
[stats?.attendanceByStatus],
|
|
||||||
);
|
|
||||||
|
|
||||||
// 宿舍费用排行
|
|
||||||
const barOption = useMemo<EChartsOption>(
|
|
||||||
() => ({
|
|
||||||
tooltip: {},
|
|
||||||
grid: { left: 80, right: 20, bottom: 30, top: 10 },
|
|
||||||
xAxis: { type: 'value' },
|
|
||||||
yAxis: {
|
|
||||||
type: 'category',
|
|
||||||
data: roomRanking.map((r) => r.roomNumber).reverse(),
|
|
||||||
inverse: false,
|
|
||||||
},
|
|
||||||
series: [
|
|
||||||
{
|
|
||||||
type: 'bar',
|
|
||||||
data: roomRanking.map((r) => Number(r.total)).reverse(),
|
|
||||||
itemStyle: { color: '#007AFF', borderRadius: [0, 4, 4, 0] },
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
[roomRanking],
|
|
||||||
);
|
|
||||||
|
|
||||||
// 班级考勤排行 - 前5
|
|
||||||
const classRankingTopOption: EChartsOption = {
|
|
||||||
tooltip: {
|
|
||||||
trigger: 'axis',
|
|
||||||
axisPointer: { type: 'shadow' },
|
|
||||||
valueFormatter: (v: number) => `${v}%`,
|
|
||||||
},
|
},
|
||||||
grid: { left: 80, right: 30, bottom: 30, top: 10 },
|
});
|
||||||
xAxis: { type: 'value', max: 100, axisLabel: { formatter: '{value}%' } },
|
|
||||||
yAxis: {
|
|
||||||
type: 'category',
|
|
||||||
data: classRanking.top.map((r) => r.className),
|
|
||||||
inverse: true,
|
|
||||||
},
|
|
||||||
series: [
|
|
||||||
{
|
|
||||||
type: 'bar',
|
|
||||||
data: classRanking.top.map((r) => r.rate),
|
|
||||||
itemStyle: { color: '#34C759', borderRadius: [0, 4, 4, 0] },
|
|
||||||
label: { show: true, position: 'right', formatter: '{c}%' },
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
// 班级考勤排行 - 后5
|
|
||||||
const classRankingBottomOption: EChartsOption = {
|
|
||||||
tooltip: {
|
|
||||||
trigger: 'axis',
|
|
||||||
axisPointer: { type: 'shadow' },
|
|
||||||
valueFormatter: (v: number) => `${v}%`,
|
|
||||||
},
|
|
||||||
grid: { left: 80, right: 30, bottom: 30, top: 10 },
|
|
||||||
xAxis: { type: 'value', max: 100, axisLabel: { formatter: '{value}%' } },
|
|
||||||
yAxis: {
|
|
||||||
type: 'category',
|
|
||||||
data: classRanking.bottom.map((r) => r.className),
|
|
||||||
inverse: true,
|
|
||||||
},
|
|
||||||
series: [
|
|
||||||
{
|
|
||||||
type: 'bar',
|
|
||||||
data: classRanking.bottom.map((r) => r.rate),
|
|
||||||
itemStyle: { color: '#FF3B30', borderRadius: [0, 4, 4, 0] },
|
|
||||||
label: { show: true, position: 'right', formatter: '{c}%' },
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
// 考勤趋势折线图
|
|
||||||
const attendanceLineOption: EChartsOption = {
|
|
||||||
tooltip: { trigger: 'axis' },
|
|
||||||
grid: { left: 50, right: 20, bottom: 30, top: 10 },
|
|
||||||
xAxis: {
|
|
||||||
type: 'category',
|
|
||||||
data: (stats?.attendanceTrend || []).map((d: { date: string }) => d.date),
|
|
||||||
axisLabel: { rotate: 45, fontSize: 10 },
|
|
||||||
},
|
|
||||||
yAxis: { type: 'value', min: 0, max: 100, axisLabel: { formatter: '{value}%' } },
|
|
||||||
series: [
|
|
||||||
{
|
|
||||||
type: 'line',
|
|
||||||
data: (stats?.attendanceTrend || []).map((d: { rate: string }) => parseFloat(d.rate) || 0),
|
|
||||||
smooth: true,
|
|
||||||
lineStyle: { color: '#007AFF', width: 2 },
|
|
||||||
itemStyle: { color: '#007AFF' },
|
|
||||||
areaStyle: { color: 'rgba(0,122,255,0.1)' },
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
// 收入趋势折线图
|
|
||||||
const incomeLineOption: EChartsOption = {
|
|
||||||
tooltip: { trigger: 'axis', valueFormatter: (v: number) => `¥${v.toLocaleString()}` },
|
|
||||||
grid: { left: 70, right: 20, bottom: 30, top: 10 },
|
|
||||||
xAxis: {
|
|
||||||
type: 'category',
|
|
||||||
data: (stats?.incomeTrend || []).map((d: { month: string }) => d.month),
|
|
||||||
},
|
|
||||||
yAxis: {
|
|
||||||
type: 'value',
|
|
||||||
axisLabel: { formatter: (v: number) => `¥${(v / 10000).toFixed(0)}万` },
|
|
||||||
},
|
|
||||||
series: [
|
|
||||||
{
|
|
||||||
type: 'line',
|
|
||||||
data: (stats?.incomeTrend || []).map((d: { amount: number }) => d.amount),
|
|
||||||
smooth: true,
|
|
||||||
lineStyle: { color: '#34C759', width: 2 },
|
|
||||||
itemStyle: { color: '#34C759' },
|
|
||||||
areaStyle: { color: 'rgba(52,199,89,0.1)' },
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
// 入住时间线(甘特图)
|
|
||||||
const ganttOption = useMemo<EChartsOption>(
|
|
||||||
() => ({
|
|
||||||
tooltip: {
|
|
||||||
formatter: (p: { data: { name: string; value: [string, string, string, boolean] } }) =>
|
|
||||||
`${p.data.name}<br/>入住: ${p.data.value[1]}<br/>退宿: ${p.data.value[2]}`,
|
|
||||||
},
|
|
||||||
grid: { left: 100, right: 30, bottom: 40, top: 20 },
|
|
||||||
xAxis: { type: 'time' },
|
|
||||||
yAxis: { type: 'category', data: ganttData.map((r) => r.roomNumber), inverse: true },
|
|
||||||
dataZoom: [
|
|
||||||
{ type: 'slider', xAxisIndex: 0, bottom: 10, height: 20 },
|
|
||||||
{ type: 'inside', xAxisIndex: 0 },
|
|
||||||
],
|
|
||||||
series: [
|
|
||||||
{
|
|
||||||
type: 'custom',
|
|
||||||
renderItem: (
|
|
||||||
_params: unknown,
|
|
||||||
api: {
|
|
||||||
value: (i: number) => string | boolean;
|
|
||||||
coord: (p: [string | number, string | number]) => [number, number];
|
|
||||||
size: (p: [number, number]) => [number, number];
|
|
||||||
},
|
|
||||||
) => {
|
|
||||||
const [cat, startDate, endDate, isActive] = [
|
|
||||||
api.value(0),
|
|
||||||
api.value(1),
|
|
||||||
api.value(2),
|
|
||||||
api.value(3),
|
|
||||||
] as unknown as [string, string, string, boolean];
|
|
||||||
const start = api.coord([startDate, cat]);
|
|
||||||
const end = api.coord([endDate, cat]);
|
|
||||||
const height = api.size([0, 1])[1] * 0.6;
|
|
||||||
const rectShape = {
|
|
||||||
x: start[0],
|
|
||||||
y: start[1] - height / 2,
|
|
||||||
width: Math.max(end[0] - start[0], 2),
|
|
||||||
height,
|
|
||||||
};
|
|
||||||
return {
|
|
||||||
type: 'rect' as const,
|
|
||||||
shape: rectShape,
|
|
||||||
style: { fill: isActive ? '#34C759' : '#FF9500', stroke: '#fff', lineWidth: 1 },
|
|
||||||
};
|
|
||||||
},
|
|
||||||
encode: { x: [1, 2], y: 0 },
|
|
||||||
data: ganttData.flatMap((r) =>
|
|
||||||
(r.occupancies || []).map((o) => ({
|
|
||||||
name: o.studentName,
|
|
||||||
value: [
|
|
||||||
r.roomNumber,
|
|
||||||
o.checkInDate,
|
|
||||||
o.checkOutDate || new Date().toISOString().slice(0, 10),
|
|
||||||
!o.checkOutDate,
|
|
||||||
] as [string, string, string, boolean],
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
[ganttData],
|
|
||||||
);
|
|
||||||
|
|
||||||
// ─── 懒加载 hooks ───
|
|
||||||
const classroomHeatmapVp = useInViewport('200px');
|
|
||||||
const ganttVp = useInViewport('200px');
|
|
||||||
|
|
||||||
// ─── 待办卡片数据 ───
|
|
||||||
const absentCount = stats?.attendanceByStatus?.['absent'] ?? 0;
|
const absentCount = stats?.attendanceByStatus?.['absent'] ?? 0;
|
||||||
|
const attendanceTotal = stats
|
||||||
|
? Object.values(stats.attendanceByStatus).reduce((sum, n) => sum + Number(n || 0), 0)
|
||||||
|
: 0;
|
||||||
|
const presentCount = stats?.attendanceByStatus?.present ?? 0;
|
||||||
|
const todayAttendanceRate =
|
||||||
|
stats?.todayAttendanceRate ??
|
||||||
|
(attendanceTotal > 0 ? ((presentCount / attendanceTotal) * 100).toFixed(1) : '0');
|
||||||
const draftBill = (stats?.billStats ?? []).find((b) => b.status === 'draft');
|
const draftBill = (stats?.billStats ?? []).find((b) => b.status === 'draft');
|
||||||
const draftCount = draftBill ? Number(draftBill.count) : 0;
|
const draftCount = draftBill ? Number(draftBill.count) : 0;
|
||||||
const draftTotal = draftBill ? Number(draftBill.total) : 0;
|
const draftTotal = draftBill ? Number(draftBill.total) : 0;
|
||||||
@@ -499,118 +192,12 @@ const DashboardPage: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* ═══════════ 待办与异常 ═══════════ */}
|
{/* ═══════════ 待办与异常 ═══════════ */}
|
||||||
<Card title="待办与异常" style={MARGIN_BOTTOM_16_STYLE}>
|
<DashboardTodoCards
|
||||||
<Row gutter={[16, 16]}>
|
absentCount={absentCount}
|
||||||
{/* 今日缺勤 */}
|
draftCount={draftCount}
|
||||||
<Col xs={24} sm={8}>
|
draftTotal={draftTotal}
|
||||||
<Card
|
pendingDeposits={pendingDeposits}
|
||||||
style={absentCount > 0 ? TODO_CARD_WARN : TODO_CARD_OK}
|
/>
|
||||||
styles={{ body: { padding: 16 } }}
|
|
||||||
onClick={() => navigate('/attendance')}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}
|
|
||||||
>
|
|
||||||
<ExclamationCircleOutlined
|
|
||||||
style={{ fontSize: 28, color: absentCount > 0 ? '#FF9500' : '#999' }}
|
|
||||||
/>
|
|
||||||
<ArrowRightOutlined style={{ color: '#bbb' }} />
|
|
||||||
</div>
|
|
||||||
<div style={{ marginTop: 8 }}>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
fontSize: 24,
|
|
||||||
fontWeight: 700,
|
|
||||||
color: absentCount > 0 ? '#FF9500' : '#999',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{absentCount}
|
|
||||||
</div>
|
|
||||||
<div style={{ fontSize: 13, color: '#666', marginTop: 2 }}>今日缺勤人数</div>
|
|
||||||
{absentCount > 0 ? (
|
|
||||||
<div style={{ fontSize: 12, color: '#FF9500', marginTop: 4 }}>需要关注</div>
|
|
||||||
) : (
|
|
||||||
<div style={{ fontSize: 12, color: '#34C759', marginTop: 4 }}>全员到齐</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
|
|
||||||
{/* 待处理账单 */}
|
|
||||||
<Col xs={24} sm={8}>
|
|
||||||
<Card
|
|
||||||
style={draftCount > 0 ? TODO_CARD_DRAFT : TODO_CARD_OK}
|
|
||||||
styles={{ body: { padding: 16 } }}
|
|
||||||
onClick={() => navigate('/bills')}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}
|
|
||||||
>
|
|
||||||
<DollarOutlined
|
|
||||||
style={{ fontSize: 28, color: draftCount > 0 ? '#AF52DE' : '#999' }}
|
|
||||||
/>
|
|
||||||
<ArrowRightOutlined style={{ color: '#bbb' }} />
|
|
||||||
</div>
|
|
||||||
<div style={{ marginTop: 8 }}>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
fontSize: 24,
|
|
||||||
fontWeight: 700,
|
|
||||||
color: draftCount > 0 ? '#AF52DE' : '#999',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{draftCount}
|
|
||||||
</div>
|
|
||||||
<div style={{ fontSize: 13, color: '#666', marginTop: 2 }}>待处理账单</div>
|
|
||||||
<div
|
|
||||||
style={{ fontSize: 12, color: draftCount > 0 ? '#AF52DE' : '#999', marginTop: 4 }}
|
|
||||||
>
|
|
||||||
{draftCount > 0 ? `合计 ¥${draftTotal.toLocaleString()}` : '暂无待处理'}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
|
|
||||||
{/* 待退押金 */}
|
|
||||||
<Col xs={24} sm={8}>
|
|
||||||
<Card
|
|
||||||
style={pendingDeposits > 0 ? TODO_CARD_DANGER : TODO_CARD_OK}
|
|
||||||
styles={{ body: { padding: 16 } }}
|
|
||||||
onClick={() => navigate('/deposits')}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}
|
|
||||||
>
|
|
||||||
<BankOutlined
|
|
||||||
style={{ fontSize: 28, color: pendingDeposits > 0 ? '#FF3B30' : '#999' }}
|
|
||||||
/>
|
|
||||||
<ArrowRightOutlined style={{ color: '#bbb' }} />
|
|
||||||
</div>
|
|
||||||
<div style={{ marginTop: 8 }}>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
fontSize: 24,
|
|
||||||
fontWeight: 700,
|
|
||||||
color: pendingDeposits > 0 ? '#FF3B30' : '#999',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
¥{pendingDeposits.toLocaleString()}
|
|
||||||
</div>
|
|
||||||
<div style={{ fontSize: 13, color: '#666', marginTop: 2 }}>待退押金</div>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
fontSize: 12,
|
|
||||||
color: pendingDeposits > 0 ? '#FF3B30' : '#999',
|
|
||||||
marginTop: 4,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{pendingDeposits > 0 ? '需要处理' : '暂无待退'}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
</Row>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* ═══════════ 核心 KPI ═══════════ */}
|
{/* ═══════════ 核心 KPI ═══════════ */}
|
||||||
<Row gutter={[16, 16]} style={SECTION_ROW_STYLE}>
|
<Row gutter={[16, 16]} style={SECTION_ROW_STYLE}>
|
||||||
@@ -638,7 +225,7 @@ const DashboardPage: React.FC = () => {
|
|||||||
<Card>
|
<Card>
|
||||||
<Statistic
|
<Statistic
|
||||||
title="今日出勤率"
|
title="今日出勤率"
|
||||||
value={stats?.todayAttendanceRate || 0}
|
value={todayAttendanceRate}
|
||||||
suffix="%"
|
suffix="%"
|
||||||
prefix={<UserSwitchOutlined />}
|
prefix={<UserSwitchOutlined />}
|
||||||
/>
|
/>
|
||||||
@@ -809,7 +396,7 @@ const DashboardPage: React.FC = () => {
|
|||||||
<Card title="考勤趋势(近30天)">
|
<Card title="考勤趋势(近30天)">
|
||||||
{(stats?.attendanceTrend || []).length > 0 ? (
|
{(stats?.attendanceTrend || []).length > 0 ? (
|
||||||
<ReactECharts
|
<ReactECharts
|
||||||
option={attendanceLineOption}
|
option={buildAttendanceLineOption(stats?.attendanceTrend ?? [])}
|
||||||
style={{ width: '100%', height: isMobile ? 250 : 300 }}
|
style={{ width: '100%', height: isMobile ? 250 : 300 }}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
@@ -821,7 +408,7 @@ const DashboardPage: React.FC = () => {
|
|||||||
<Card title="今日出勤状态分布">
|
<Card title="今日出勤状态分布">
|
||||||
{Object.keys(stats?.attendanceByStatus ?? {}).length > 0 ? (
|
{Object.keys(stats?.attendanceByStatus ?? {}).length > 0 ? (
|
||||||
<ReactECharts
|
<ReactECharts
|
||||||
option={attendanceRingOption}
|
option={buildAttendanceRingOption(stats)}
|
||||||
style={{ width: '100%', height: isMobile ? 250 : 300 }}
|
style={{ width: '100%', height: isMobile ? 250 : 300 }}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
@@ -837,7 +424,7 @@ const DashboardPage: React.FC = () => {
|
|||||||
<Card title="班级出勤率 TOP 5">
|
<Card title="班级出勤率 TOP 5">
|
||||||
{classRanking.top.length > 0 ? (
|
{classRanking.top.length > 0 ? (
|
||||||
<ReactECharts
|
<ReactECharts
|
||||||
option={classRankingTopOption}
|
option={buildClassRankingOption(classRanking.top, '#34C759')}
|
||||||
style={{ width: '100%', height: isMobile ? 250 : 300 }}
|
style={{ width: '100%', height: isMobile ? 250 : 300 }}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
@@ -849,7 +436,7 @@ const DashboardPage: React.FC = () => {
|
|||||||
<Card title="班级出勤率 末位 5">
|
<Card title="班级出勤率 末位 5">
|
||||||
{classRanking.bottom.length > 0 ? (
|
{classRanking.bottom.length > 0 ? (
|
||||||
<ReactECharts
|
<ReactECharts
|
||||||
option={classRankingBottomOption}
|
option={buildClassRankingOption(classRanking.bottom, '#FF3B30')}
|
||||||
style={{ width: '100%', height: isMobile ? 250 : 300 }}
|
style={{ width: '100%', height: isMobile ? 250 : 300 }}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
@@ -865,24 +452,7 @@ const DashboardPage: React.FC = () => {
|
|||||||
<Card title="费用类型分布">
|
<Card title="费用类型分布">
|
||||||
{(stats?.expenseByType ?? []).length > 0 ? (
|
{(stats?.expenseByType ?? []).length > 0 ? (
|
||||||
<ReactECharts
|
<ReactECharts
|
||||||
option={
|
option={buildExpensePieOption(stats?.expenseByType ?? [], expenseTypeMap)}
|
||||||
{
|
|
||||||
tooltip: { trigger: 'item' },
|
|
||||||
legend: { bottom: 0 },
|
|
||||||
color: COLORS,
|
|
||||||
series: [
|
|
||||||
{
|
|
||||||
type: 'pie',
|
|
||||||
radius: ['40%', '70%'],
|
|
||||||
center: ['50%', '45%'],
|
|
||||||
data: (stats?.expenseByType ?? []).map((e) => ({
|
|
||||||
name: expenseTypeMap[e.type] ?? e.type,
|
|
||||||
value: Number(e.total),
|
|
||||||
})),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
} satisfies EChartsOption
|
|
||||||
}
|
|
||||||
style={{ width: '100%', height: isMobile ? 250 : 300 }}
|
style={{ width: '100%', height: isMobile ? 250 : 300 }}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
@@ -894,7 +464,7 @@ const DashboardPage: React.FC = () => {
|
|||||||
<Card title="宿舍费用排行 TOP 20">
|
<Card title="宿舍费用排行 TOP 20">
|
||||||
{roomRanking.length > 0 ? (
|
{roomRanking.length > 0 ? (
|
||||||
<ReactECharts
|
<ReactECharts
|
||||||
option={barOption}
|
option={buildRoomRankingBarOption(roomRanking)}
|
||||||
style={{ width: '100%', height: isMobile ? 250 : 300 }}
|
style={{ width: '100%', height: isMobile ? 250 : 300 }}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
@@ -910,7 +480,7 @@ const DashboardPage: React.FC = () => {
|
|||||||
<Card title="月度收入趋势">
|
<Card title="月度收入趋势">
|
||||||
{(stats?.incomeTrend || []).length > 0 ? (
|
{(stats?.incomeTrend || []).length > 0 ? (
|
||||||
<ReactECharts
|
<ReactECharts
|
||||||
option={incomeLineOption}
|
option={buildIncomeLineOption(stats?.incomeTrend ?? [])}
|
||||||
style={{ width: '100%', height: isMobile ? 250 : 300 }}
|
style={{ width: '100%', height: isMobile ? 250 : 300 }}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
@@ -921,102 +491,10 @@ const DashboardPage: React.FC = () => {
|
|||||||
</Row>
|
</Row>
|
||||||
|
|
||||||
{/* ═══════════ 图表:教室占用热力图(懒加载) ═══════════ */}
|
{/* ═══════════ 图表:教室占用热力图(懒加载) ═══════════ */}
|
||||||
<div ref={classroomHeatmapVp.ref} style={SECTION_ROW_STYLE}>
|
<ClassroomHeatmapCard data={classroomOccupancy} isMobile={isMobile} />
|
||||||
{classroomHeatmapVp.inView ? (
|
|
||||||
<Row gutter={[16, 16]}>
|
|
||||||
<Col xs={24}>
|
|
||||||
<Card title="教室占用热力图">
|
|
||||||
{classroomOccupancy.length > 0 ? (
|
|
||||||
<ReactECharts
|
|
||||||
option={
|
|
||||||
{
|
|
||||||
tooltip: {
|
|
||||||
formatter: (p: {
|
|
||||||
name: string;
|
|
||||||
data: { scheduleDays: number; rentalCount: number; occupancy: number };
|
|
||||||
}) =>
|
|
||||||
`${p.name}<br/>排课: ${p.data.scheduleDays}天 租赁: ${p.data.rentalCount}个 占用率: ${(p.data.occupancy * 100).toFixed(0)}%`,
|
|
||||||
},
|
|
||||||
grid: { left: 100, right: 20, bottom: 30, top: 10 },
|
|
||||||
xAxis: { type: 'value', max: 1 },
|
|
||||||
yAxis: {
|
|
||||||
type: 'category',
|
|
||||||
data: classroomOccupancy.map((r) => r.name),
|
|
||||||
inverse: true,
|
|
||||||
},
|
|
||||||
visualMap: {
|
|
||||||
min: 0,
|
|
||||||
max: 1,
|
|
||||||
orient: 'horizontal',
|
|
||||||
left: 'center',
|
|
||||||
bottom: 0,
|
|
||||||
inRange: {
|
|
||||||
color: ['#e6f4ff', '#91caff', '#40a9ff', '#0050b3', '#002c8c'],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
series: [
|
|
||||||
{
|
|
||||||
type: 'bar',
|
|
||||||
data: classroomOccupancy.map((r) => ({
|
|
||||||
name: r.name,
|
|
||||||
value: r.occupancy,
|
|
||||||
scheduleDays: r.scheduleDays,
|
|
||||||
rentalCount: r.rentalCount,
|
|
||||||
occupancy: r.occupancy,
|
|
||||||
})),
|
|
||||||
itemStyle: { borderRadius: [0, 4, 4, 0] },
|
|
||||||
label: {
|
|
||||||
show: true,
|
|
||||||
position: 'right',
|
|
||||||
formatter: (p: { data: { occupancy: number } }) =>
|
|
||||||
`${(p.data.occupancy * 100).toFixed(0)}%`,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
} satisfies EChartsOption
|
|
||||||
}
|
|
||||||
style={{ width: '100%', height: isMobile ? 300 : 400 }}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<div style={{ textAlign: 'center', padding: 40, color: '#999' }}>
|
|
||||||
暂无教室数据
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
</Row>
|
|
||||||
) : (
|
|
||||||
<Card title="教室占用热力图" style={{ minHeight: isMobile ? 340 : 440 }}>
|
|
||||||
<div style={{ textAlign: 'center', padding: 40, color: '#999' }}>加载中…</div>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* ═══════════ 图表:入住时间线甘特图(懒加载) ═══════════ */}
|
{/* ═══════════ 图表:入住时间线甘特图(懒加载) ═══════════ */}
|
||||||
<div ref={ganttVp.ref}>
|
<GanttCard data={ganttData} isMobile={isMobile} />
|
||||||
{ganttVp.inView ? (
|
|
||||||
<Row gutter={[16, 16]}>
|
|
||||||
<Col xs={24}>
|
|
||||||
<Card title="入住时间线(甘特图)">
|
|
||||||
{ganttData.length > 0 ? (
|
|
||||||
<ReactECharts
|
|
||||||
option={ganttOption}
|
|
||||||
style={{ width: '100%', height: isMobile ? 300 : 450 }}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<div style={{ textAlign: 'center', padding: 40, color: '#999' }}>
|
|
||||||
暂无入住数据
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
</Row>
|
|
||||||
) : (
|
|
||||||
<Card title="入住时间线(甘特图)" style={{ minHeight: isMobile ? 340 : 490 }}>
|
|
||||||
<div style={{ textAlign: 'center', padding: 40, color: '#999' }}>加载中…</div>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
423
apps/admin/src/pages/Deposits/DepositModals.tsx
Normal file
423
apps/admin/src/pages/Deposits/DepositModals.tsx
Normal file
@@ -0,0 +1,423 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
DatePicker,
|
||||||
|
Empty,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
InputNumber,
|
||||||
|
Modal,
|
||||||
|
Popconfirm,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Table,
|
||||||
|
Tag,
|
||||||
|
} from 'antd';
|
||||||
|
import { DollarOutlined, InboxOutlined, PlusOutlined } from '@ant-design/icons';
|
||||||
|
import PermissionButton from '../../components/PermissionButton';
|
||||||
|
import EditableCell from '../../components/EditableCell';
|
||||||
|
import type { DepositStudentLookup } from './deposit-student-option';
|
||||||
|
|
||||||
|
export interface DepositRecord {
|
||||||
|
id: number;
|
||||||
|
studentId: number;
|
||||||
|
amount: number;
|
||||||
|
status: string;
|
||||||
|
paidDate: string;
|
||||||
|
refundDate?: string | null;
|
||||||
|
notes?: string | null;
|
||||||
|
installments?: Array<{
|
||||||
|
id: number;
|
||||||
|
amount: number;
|
||||||
|
dueDate: string;
|
||||||
|
paidDate?: string | null;
|
||||||
|
status: string;
|
||||||
|
}>;
|
||||||
|
student?: DepositStudentLookup;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EligibleStudent {
|
||||||
|
studentId: number;
|
||||||
|
studentName: string;
|
||||||
|
studentNo?: string | null;
|
||||||
|
roomId: number;
|
||||||
|
roomNumber: string;
|
||||||
|
building?: string | null;
|
||||||
|
roomType?: string | null;
|
||||||
|
capacity: number;
|
||||||
|
depositAmount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const statusMap: Record<string, { text: string; color: string }> = {
|
||||||
|
paid: { text: '有余额', color: 'green' },
|
||||||
|
refunded: { text: '已全退', color: 'blue' },
|
||||||
|
depleted: { text: '已扣完', color: 'red' },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const installmentStatusMap: Record<string, { text: string; color: string }> = {
|
||||||
|
pending: { text: '待缴', color: 'orange' },
|
||||||
|
paid: { text: '已缴', color: 'green' },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const roomTypeOptions = [
|
||||||
|
{ value: '单人间', label: '单人间' },
|
||||||
|
{ value: '四人间', label: '四人间' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const suggestedDepositByRoomType: Record<string, number> = {
|
||||||
|
单人间: 200,
|
||||||
|
四人间: 100,
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface DepositModalsProps {
|
||||||
|
batchModal: boolean;
|
||||||
|
createModal: boolean;
|
||||||
|
refundModal: DepositRecord | null;
|
||||||
|
detailModal: DepositRecord | null;
|
||||||
|
installmentModal: number | null;
|
||||||
|
batchForm: ReturnType<typeof Form.useForm>[0];
|
||||||
|
createForm: ReturnType<typeof Form.useForm>[0];
|
||||||
|
refundForm: ReturnType<typeof Form.useForm>[0];
|
||||||
|
installmentForm: ReturnType<typeof Form.useForm>[0];
|
||||||
|
saving: boolean;
|
||||||
|
batchRoomType: string;
|
||||||
|
effectiveSelectedEligibleIds: number[];
|
||||||
|
eligibleStudents: EligibleStudent[];
|
||||||
|
eligibleLoading: boolean;
|
||||||
|
eligibleColumns: Array<{ title: string; render?: unknown; dataIndex?: string }>;
|
||||||
|
studentOptions: Array<{ value: number; label: string }>;
|
||||||
|
onBatchRoomTypeChange: (roomType: string) => void;
|
||||||
|
onBatchCreate: () => void;
|
||||||
|
onCreate: () => void;
|
||||||
|
onRefund: () => void;
|
||||||
|
onAddInstallment: () => void;
|
||||||
|
onPayInstallment: (installmentId: number) => void;
|
||||||
|
onSaveInstallmentCell: (
|
||||||
|
installmentId: number,
|
||||||
|
field: 'status' | 'paidDate',
|
||||||
|
value: unknown,
|
||||||
|
) => void;
|
||||||
|
onDeleteInstallment: (installmentId: number) => void;
|
||||||
|
onCloseBatch: () => void;
|
||||||
|
onCloseCreate: () => void;
|
||||||
|
onCloseRefund: () => void;
|
||||||
|
onCloseDetail: () => void;
|
||||||
|
onCloseInstallment: () => void;
|
||||||
|
onOpenInstallment: (id: number) => void;
|
||||||
|
onSelectEligible: (ids: number[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DepositModals: React.FC<DepositModalsProps> = ({
|
||||||
|
batchModal,
|
||||||
|
createModal,
|
||||||
|
refundModal,
|
||||||
|
detailModal,
|
||||||
|
installmentModal,
|
||||||
|
batchForm,
|
||||||
|
createForm,
|
||||||
|
refundForm,
|
||||||
|
installmentForm,
|
||||||
|
saving,
|
||||||
|
batchRoomType,
|
||||||
|
effectiveSelectedEligibleIds,
|
||||||
|
eligibleStudents,
|
||||||
|
eligibleLoading,
|
||||||
|
eligibleColumns,
|
||||||
|
studentOptions,
|
||||||
|
onBatchRoomTypeChange,
|
||||||
|
onBatchCreate,
|
||||||
|
onCreate,
|
||||||
|
onRefund,
|
||||||
|
onAddInstallment,
|
||||||
|
onPayInstallment,
|
||||||
|
onSaveInstallmentCell,
|
||||||
|
onDeleteInstallment,
|
||||||
|
onCloseBatch,
|
||||||
|
onCloseCreate,
|
||||||
|
onCloseRefund,
|
||||||
|
onCloseDetail,
|
||||||
|
onCloseInstallment,
|
||||||
|
onOpenInstallment,
|
||||||
|
onSelectEligible,
|
||||||
|
}) => {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Modal
|
||||||
|
title="按房型批量收取押金"
|
||||||
|
open={batchModal}
|
||||||
|
onOk={onBatchCreate}
|
||||||
|
onCancel={onCloseBatch}
|
||||||
|
okText="确认批量收取"
|
||||||
|
confirmLoading={saving}
|
||||||
|
okButtonProps={{ disabled: effectiveSelectedEligibleIds.length === 0 }}
|
||||||
|
width={760}
|
||||||
|
>
|
||||||
|
<Form form={batchForm} layout="vertical">
|
||||||
|
<Space style={{ width: '100%' }} align="start" wrap>
|
||||||
|
<Form.Item
|
||||||
|
name="roomType"
|
||||||
|
label="房型"
|
||||||
|
rules={[{ required: true, message: '请选择房型' }]}
|
||||||
|
>
|
||||||
|
<Select
|
||||||
|
style={{ width: 140 }}
|
||||||
|
options={roomTypeOptions}
|
||||||
|
onChange={onBatchRoomTypeChange}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="amount"
|
||||||
|
label="每人收取金额(元)"
|
||||||
|
rules={[{ required: true, message: '请输入金额' }]}
|
||||||
|
>
|
||||||
|
<InputNumber min={0.01} precision={2} style={{ width: 180 }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="paidDate"
|
||||||
|
label="收取日期"
|
||||||
|
rules={[{ required: true, message: '请选择日期' }]}
|
||||||
|
>
|
||||||
|
<DatePicker style={{ width: 180 }} placeholder="选择收取日期" format="YYYY-MM-DD" />
|
||||||
|
</Form.Item>
|
||||||
|
</Space>
|
||||||
|
<Form.Item name="notes" label="备注">
|
||||||
|
<Input.TextArea rows={2} placeholder={`${batchRoomType}押金`} />
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
<div style={{ marginBottom: 8 }}>
|
||||||
|
已选择 <strong>{effectiveSelectedEligibleIds.length}</strong> / {eligibleStudents.length}{' '}
|
||||||
|
人
|
||||||
|
{suggestedDepositByRoomType[batchRoomType] && (
|
||||||
|
<span style={{ color: '#999', marginLeft: 8 }}>
|
||||||
|
建议金额:¥{suggestedDepositByRoomType[batchRoomType]}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Table
|
||||||
|
size="small"
|
||||||
|
columns={eligibleColumns as never}
|
||||||
|
dataSource={eligibleStudents}
|
||||||
|
rowKey="studentId"
|
||||||
|
loading={eligibleLoading}
|
||||||
|
locale={{ emptyText: <Empty description="暂无符合条件的在住人员" /> }}
|
||||||
|
pagination={{ pageSize: 6, showSizeChanger: false }}
|
||||||
|
rowSelection={{
|
||||||
|
selectedRowKeys: effectiveSelectedEligibleIds,
|
||||||
|
onChange: (keys) => onSelectEligible(keys as number[]),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
title="收取押金"
|
||||||
|
open={createModal}
|
||||||
|
onOk={onCreate}
|
||||||
|
onCancel={onCloseCreate}
|
||||||
|
okText="确认"
|
||||||
|
confirmLoading={saving}
|
||||||
|
>
|
||||||
|
<Form form={createForm} layout="vertical">
|
||||||
|
<Form.Item
|
||||||
|
name="studentId"
|
||||||
|
label="学生"
|
||||||
|
rules={[{ required: true, message: '请选择学生' }]}
|
||||||
|
>
|
||||||
|
<Select
|
||||||
|
showSearch
|
||||||
|
optionFilterProp="label"
|
||||||
|
placeholder="搜索并选择学生"
|
||||||
|
options={studentOptions}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="amount" label="本次收取金额(元)" rules={[{ required: true }]}>
|
||||||
|
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="paidDate" label="收取日期" rules={[{ required: true }]}>
|
||||||
|
<DatePicker style={{ width: '100%' }} placeholder="选择收取日期" format="YYYY-MM-DD" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="notes" label="备注">
|
||||||
|
<Input.TextArea rows={2} />
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
title={`退还押金 - ${refundModal?.student?.name}`}
|
||||||
|
open={!!refundModal}
|
||||||
|
onOk={onRefund}
|
||||||
|
onCancel={onCloseRefund}
|
||||||
|
okText="确认退还"
|
||||||
|
confirmLoading={saving}
|
||||||
|
>
|
||||||
|
<Form form={refundForm} layout="vertical">
|
||||||
|
<div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 8 }}>
|
||||||
|
当前可用押金: <strong>¥{Number(refundModal?.amount || 0).toFixed(2)}</strong>
|
||||||
|
</div>
|
||||||
|
<Form.Item name="refundDate" label="退还日期" rules={[{ required: true }]}>
|
||||||
|
<DatePicker style={{ width: '100%' }} placeholder="选择退还日期" format="YYYY-MM-DD" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="notes" label="备注">
|
||||||
|
<Input.TextArea rows={2} />
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
title={`押金详情 - ${detailModal?.student?.name}`}
|
||||||
|
open={!!detailModal}
|
||||||
|
onCancel={onCloseDetail}
|
||||||
|
footer={null}
|
||||||
|
width={640}
|
||||||
|
>
|
||||||
|
{detailModal && (
|
||||||
|
<div>
|
||||||
|
<Card size="small" style={{ marginBottom: 16 }}>
|
||||||
|
<p>
|
||||||
|
<strong>当前可用押金:</strong> ¥{Number(detailModal.amount).toFixed(2)}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<strong>最近收取日期:</strong> {detailModal.paidDate}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<strong>状态:</strong>{' '}
|
||||||
|
<Tag color={statusMap[detailModal.status]?.color}>
|
||||||
|
{statusMap[detailModal.status]?.text || detailModal.status}
|
||||||
|
</Tag>
|
||||||
|
</p>
|
||||||
|
{detailModal.notes && (
|
||||||
|
<p>
|
||||||
|
<strong>备注:</strong> {detailModal.notes}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
alignItems: 'center',
|
||||||
|
marginBottom: 8,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<h4 style={{ margin: 0 }}>分期记录</h4>
|
||||||
|
<PermissionButton
|
||||||
|
permission="deposit:edit"
|
||||||
|
size="small"
|
||||||
|
type="primary"
|
||||||
|
icon={<PlusOutlined />}
|
||||||
|
onClick={() => onOpenInstallment(detailModal.id)}
|
||||||
|
>
|
||||||
|
添加分期
|
||||||
|
</PermissionButton>
|
||||||
|
</div>
|
||||||
|
{detailModal.installments && detailModal.installments.length > 0 ? (
|
||||||
|
<Table
|
||||||
|
size="small"
|
||||||
|
pagination={false}
|
||||||
|
rowKey="id"
|
||||||
|
dataSource={detailModal.installments}
|
||||||
|
columns={[
|
||||||
|
{
|
||||||
|
title: '金额',
|
||||||
|
dataIndex: 'amount',
|
||||||
|
render: (value: number) => `¥${value.toFixed(2)}`,
|
||||||
|
},
|
||||||
|
{ title: '到期日', dataIndex: 'dueDate' },
|
||||||
|
{
|
||||||
|
title: '实付日',
|
||||||
|
dataIndex: 'paidDate',
|
||||||
|
render: (value: string, item: any) => (
|
||||||
|
<EditableCell
|
||||||
|
value={value}
|
||||||
|
editor="date"
|
||||||
|
permission="deposit:edit"
|
||||||
|
onSave={async (next) =>
|
||||||
|
onSaveInstallmentCell(item.id, 'paidDate', next)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{value || '-'}
|
||||||
|
</EditableCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'status',
|
||||||
|
render: (value: string, item: any) => (
|
||||||
|
<EditableCell
|
||||||
|
value={value}
|
||||||
|
editor="select"
|
||||||
|
options={[
|
||||||
|
{ value: 'pending', label: '待缴' },
|
||||||
|
{ value: 'paid', label: '已缴' },
|
||||||
|
{ value: 'overdue', label: '逾期' },
|
||||||
|
]}
|
||||||
|
permission="deposit:edit"
|
||||||
|
onSave={async (next) =>
|
||||||
|
onSaveInstallmentCell(item.id, 'status', next)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Tag color={installmentStatusMap[value]?.color}>
|
||||||
|
{installmentStatusMap[value]?.text || value}
|
||||||
|
</Tag>
|
||||||
|
</EditableCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
render: (_: unknown, item: any) => (
|
||||||
|
<Space>
|
||||||
|
{item.status === 'pending' && (
|
||||||
|
<PermissionButton
|
||||||
|
permission="deposit:edit"
|
||||||
|
size="small"
|
||||||
|
type="primary"
|
||||||
|
icon={<DollarOutlined />}
|
||||||
|
onClick={() => onPayInstallment(item.id)}
|
||||||
|
>
|
||||||
|
标记已缴
|
||||||
|
</PermissionButton>
|
||||||
|
)}
|
||||||
|
<Popconfirm
|
||||||
|
title="确定归档?"
|
||||||
|
onConfirm={() => onDeleteInstallment(item.id)}
|
||||||
|
>
|
||||||
|
<PermissionButton
|
||||||
|
permission="deposit:delete"
|
||||||
|
size="small"
|
||||||
|
danger
|
||||||
|
icon={<InboxOutlined />}
|
||||||
|
>
|
||||||
|
归档
|
||||||
|
</PermissionButton>
|
||||||
|
</Popconfirm>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<p style={{ color: '#999' }}>暂无分期记录</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
title="添加分期"
|
||||||
|
open={installmentModal != null}
|
||||||
|
onOk={onAddInstallment}
|
||||||
|
onCancel={onCloseInstallment}
|
||||||
|
okText="确认"
|
||||||
|
>
|
||||||
|
<Form form={installmentForm} layout="vertical">
|
||||||
|
<Form.Item name="amount" label="分期金额(元)" rules={[{ required: true }]}>
|
||||||
|
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="dueDate" label="到期日期" rules={[{ required: true }]}>
|
||||||
|
<DatePicker style={{ width: '100%' }} placeholder="选择到期日期" format="YYYY-MM-DD" />
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
148
apps/admin/src/pages/Deposits/DepositTable.tsx
Normal file
148
apps/admin/src/pages/Deposits/DepositTable.tsx
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Button, Empty, Popconfirm, Space, Table, Tag } from 'antd';
|
||||||
|
import { DeleteOutlined, InboxOutlined } from '@ant-design/icons';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
import PermissionButton from '../../components/PermissionButton';
|
||||||
|
import { message } from '../../ui/app-message';
|
||||||
|
import { statusMap } from './DepositModals';
|
||||||
|
import type { DepositRecord } from './DepositModals';
|
||||||
|
|
||||||
|
export interface DepositTableProps {
|
||||||
|
data: any[];
|
||||||
|
loading: boolean;
|
||||||
|
canPurgeDeposit: boolean;
|
||||||
|
refundForm: ReturnType<typeof import('antd').Form.useForm>[0];
|
||||||
|
onDetail: (record: DepositRecord) => void;
|
||||||
|
onRefund: (record: DepositRecord) => void;
|
||||||
|
onArchive: (id: number) => Promise<unknown> | unknown;
|
||||||
|
onPurge: (id: number) => Promise<unknown> | unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DepositTable: React.FC<DepositTableProps> = ({
|
||||||
|
data,
|
||||||
|
loading,
|
||||||
|
canPurgeDeposit,
|
||||||
|
refundForm,
|
||||||
|
onDetail,
|
||||||
|
onRefund,
|
||||||
|
onArchive,
|
||||||
|
onPurge,
|
||||||
|
}) => {
|
||||||
|
const columns = [
|
||||||
|
{ title: '学生', width: 120, render: (_: unknown, r: any) => r.student?.name || '-' },
|
||||||
|
{
|
||||||
|
title: '当前可用押金',
|
||||||
|
dataIndex: 'amount',
|
||||||
|
width: 130,
|
||||||
|
render: (v: number) => `¥${Number(v || 0).toFixed(2)}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '房间',
|
||||||
|
width: 120,
|
||||||
|
render: (_: unknown, r: any) =>
|
||||||
|
r.roomNumber ? `${r.building ? `${r.building}-` : ''}${r.roomNumber}` : '-',
|
||||||
|
},
|
||||||
|
{ title: '房型', dataIndex: 'roomType', width: 100, render: (v: string) => v || '-' },
|
||||||
|
{ title: '最近收取日期', dataIndex: 'paidDate', width: 120, render: (v: string) => v || '-' },
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'status',
|
||||||
|
render: (s: string) =>
|
||||||
|
s === 'unpaid' ? (
|
||||||
|
<Tag color="default">未缴</Tag>
|
||||||
|
) : (
|
||||||
|
<Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{ title: '退还日期', dataIndex: 'refundDate', width: 110, render: (v: unknown) => v || '-' },
|
||||||
|
{ title: '备注', dataIndex: 'notes', width: 120, render: (v: unknown) => v || '-' },
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
width: 240,
|
||||||
|
render: (_: unknown, record: any) => {
|
||||||
|
const hasDeposit = typeof record.id === 'number';
|
||||||
|
return (
|
||||||
|
<Space>
|
||||||
|
{hasDeposit && (
|
||||||
|
<PermissionButton permission="deposit:view" size="small" onClick={() => onDetail(record)}>
|
||||||
|
详情
|
||||||
|
</PermissionButton>
|
||||||
|
)}
|
||||||
|
{record.status === 'paid' && hasDeposit && (
|
||||||
|
<PermissionButton
|
||||||
|
permission="deposit:refund"
|
||||||
|
size="small"
|
||||||
|
type="primary"
|
||||||
|
onClick={() => {
|
||||||
|
onRefund(record);
|
||||||
|
refundForm.setFieldsValue({ refundDate: dayjs() });
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
退还
|
||||||
|
</PermissionButton>
|
||||||
|
)}
|
||||||
|
{hasDeposit && (
|
||||||
|
<Popconfirm
|
||||||
|
title="确定归档?"
|
||||||
|
onConfirm={async () => {
|
||||||
|
try {
|
||||||
|
await onArchive(record.id);
|
||||||
|
message.success('归档成功');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<PermissionButton
|
||||||
|
permission="deposit:delete"
|
||||||
|
size="small"
|
||||||
|
danger
|
||||||
|
icon={<InboxOutlined />}
|
||||||
|
>
|
||||||
|
归档
|
||||||
|
</PermissionButton>
|
||||||
|
</Popconfirm>
|
||||||
|
)}
|
||||||
|
{record.status === 'archived' && hasDeposit && canPurgeDeposit ? (
|
||||||
|
<Popconfirm
|
||||||
|
title="确定永久删除该押金记录?"
|
||||||
|
description="删除后不可恢复,分期记录将一并清除。"
|
||||||
|
okText="永久删除"
|
||||||
|
okButtonProps={{ danger: true }}
|
||||||
|
onConfirm={async () => {
|
||||||
|
try {
|
||||||
|
await onPurge(record.id);
|
||||||
|
message.success('已永久删除(不可恢复)');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Button size="small" danger icon={<DeleteOutlined />}>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
) : null}
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Table
|
||||||
|
columns={columns}
|
||||||
|
dataSource={data}
|
||||||
|
rowKey="id"
|
||||||
|
loading={loading}
|
||||||
|
scroll={{ x: 1200 }}
|
||||||
|
pagination={{
|
||||||
|
defaultPageSize: 15,
|
||||||
|
showSizeChanger: true,
|
||||||
|
pageSizeOptions: [15, 30, 50, 100],
|
||||||
|
showTotal: (total) => `共 ${total} 条`,
|
||||||
|
}}
|
||||||
|
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,89 +1,41 @@
|
|||||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
// aislop-ignore-file: duplicate-block -- 表格/表单声明结构相似且参数不同,渲染逻辑已共享组件化
|
||||||
|
import React, { useCallback, useMemo, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
Table,
|
|
||||||
Modal,
|
|
||||||
Form,
|
Form,
|
||||||
Select,
|
|
||||||
DatePicker,
|
|
||||||
InputNumber,
|
|
||||||
Input,
|
Input,
|
||||||
|
Select,
|
||||||
Space,
|
Space,
|
||||||
Tag,
|
|
||||||
Popconfirm,
|
|
||||||
Card,
|
|
||||||
Empty,
|
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import { PlusOutlined, InboxOutlined, DollarOutlined, TeamOutlined } from '@ant-design/icons';
|
import { PlusOutlined, TeamOutlined } 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 PermissionButton from '../../components/PermissionButton';
|
||||||
import EditableCell from '../../components/EditableCell';
|
|
||||||
import { message } from '../../ui/app-message';
|
import { message } from '../../ui/app-message';
|
||||||
import { buildDepositStudentOptions, type DepositStudentLookup } from './deposit-student-option';
|
import { buildDepositStudentOptions, type DepositStudentLookup } from './deposit-student-option';
|
||||||
|
import { usePermission } from '../../hooks/usePermission';
|
||||||
const statusMap: Record<string, { text: string; color: string }> = {
|
import { useQuery, useQueryClient, type QueryKey } from '@tanstack/react-query';
|
||||||
paid: { text: '有余额', color: 'green' },
|
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||||
refunded: { text: '已全退', color: 'blue' },
|
import { validateResponse } from '../../utils/validate';
|
||||||
depleted: { text: '已扣完', color: 'red' },
|
import {
|
||||||
};
|
depositStudentLookupsSchema,
|
||||||
|
depositsSchema,
|
||||||
const installmentStatusMap: Record<string, { text: string; color: string }> = {
|
eligibleStudentsSchema,
|
||||||
pending: { text: '待缴', color: 'orange' },
|
} from '../../api/schemas';
|
||||||
paid: { text: '已缴', color: 'green' },
|
import {
|
||||||
};
|
DepositModals,
|
||||||
|
roomTypeOptions,
|
||||||
const roomTypeOptions = [
|
suggestedDepositByRoomType,
|
||||||
{ value: '单人间', label: '单人间' },
|
} from './DepositModals';
|
||||||
{ value: '四人间', label: '四人间' },
|
import type { DepositRecord, EligibleStudent } from './DepositModals';
|
||||||
];
|
import { DepositTable } from './DepositTable';
|
||||||
|
|
||||||
const suggestedDepositByRoomType: Record<string, number> = {
|
|
||||||
单人间: 200,
|
|
||||||
四人间: 100,
|
|
||||||
};
|
|
||||||
|
|
||||||
interface DepositRecord {
|
|
||||||
id: number;
|
|
||||||
studentId: number;
|
|
||||||
amount: number;
|
|
||||||
status: string;
|
|
||||||
paidDate: string;
|
|
||||||
refundDate?: string | null;
|
|
||||||
notes?: string | null;
|
|
||||||
installments?: Array<{
|
|
||||||
id: number;
|
|
||||||
amount: number;
|
|
||||||
dueDate: string;
|
|
||||||
paidDate?: string | null;
|
|
||||||
status: string;
|
|
||||||
}>;
|
|
||||||
student?: DepositStudentLookup;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface EligibleStudent {
|
|
||||||
studentId: number;
|
|
||||||
studentName: string;
|
|
||||||
studentNo?: string | null;
|
|
||||||
roomId: number;
|
|
||||||
roomNumber: string;
|
|
||||||
building?: string | null;
|
|
||||||
roomType?: string | null;
|
|
||||||
capacity: number;
|
|
||||||
depositAmount: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const isFormValidationError = (error: unknown) =>
|
|
||||||
typeof error === 'object' &&
|
|
||||||
error !== null &&
|
|
||||||
Array.isArray((error as { errorFields?: unknown }).errorFields);
|
|
||||||
|
|
||||||
const DepositsPage: React.FC = () => {
|
const DepositsPage: React.FC = () => {
|
||||||
const [data, setData] = useState<DepositRecord[]>([]);
|
const { hasPermission } = usePermission();
|
||||||
const [students, setStudents] = useState<DepositStudentLookup[]>([]);
|
const canPurgeDeposit = hasPermission('deposit:purge');
|
||||||
const [eligibleStudents, setEligibleStudents] = useState<EligibleStudent[]>([]);
|
|
||||||
const [selectedEligibleStudentIds, setSelectedEligibleStudentIds] = useState<number[]>([]);
|
const [selectedEligibleStudentIds, setSelectedEligibleStudentIds] = useState<number[]>([]);
|
||||||
const [loading, setLoading] = useState(false);
|
const [selectionTouched, setSelectionTouched] = useState(false);
|
||||||
const [eligibleLoading, setEligibleLoading] = useState(false);
|
const [eligibleRoomType, setEligibleRoomType] = useState<string | undefined>(undefined);
|
||||||
|
const queryClient = useQueryClient();
|
||||||
const [createModal, setCreateModal] = useState(false);
|
const [createModal, setCreateModal] = useState(false);
|
||||||
const [batchModal, setBatchModal] = useState(false);
|
const [batchModal, setBatchModal] = useState(false);
|
||||||
const [refundModal, setRefundModal] = useState<DepositRecord | null>(null);
|
const [refundModal, setRefundModal] = useState<DepositRecord | null>(null);
|
||||||
@@ -99,47 +51,115 @@ const DepositsPage: React.FC = () => {
|
|||||||
const [batchRoomType, setBatchRoomType] = useState<string>('四人间');
|
const [batchRoomType, setBatchRoomType] = useState<string>('四人间');
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
const fetchData = useCallback(async () => {
|
const {
|
||||||
setLoading(true);
|
data: fetchResult = { data: [], students: [] },
|
||||||
try {
|
isLoading,
|
||||||
const [d, s] = await Promise.all([
|
isFetching,
|
||||||
api.get<DepositRecord[]>('/deposits'),
|
} = useQuery<{ data: DepositRecord[]; students: DepositStudentLookup[] }>({
|
||||||
api.get<DepositStudentLookup[]>('/deposits/student-lookups'),
|
queryKey: ['deposits'],
|
||||||
]);
|
queryFn: async () => {
|
||||||
setData(d);
|
try {
|
||||||
setStudents(s);
|
const [d, s] = await Promise.all([
|
||||||
} catch (e: any) {
|
api.get<DepositRecord[]>('/deposits'),
|
||||||
message.error(e?.message || '加载失败,请稍后重试');
|
api.get<DepositStudentLookup[]>('/deposits/student-lookups'),
|
||||||
} finally {
|
]);
|
||||||
setLoading(false);
|
return {
|
||||||
}
|
data: validateResponse<DepositRecord[]>(depositsSchema, d),
|
||||||
}, []);
|
students: validateResponse<DepositStudentLookup[]>(depositStudentLookupsSchema, s),
|
||||||
|
};
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '加载失败');
|
||||||
|
return { data: [], students: [] };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const data = fetchResult.data;
|
||||||
|
const students = fetchResult.students;
|
||||||
|
const loading = isLoading || isFetching;
|
||||||
|
|
||||||
const fetchEligibleStudents = useCallback(async (roomType?: string) => {
|
const invalidateDeposits: QueryKey[] = [['deposits'], ['deposits', 'eligible']];
|
||||||
setEligibleLoading(true);
|
const createMutation = useApiMutation(
|
||||||
try {
|
async (payload: Record<string, unknown>) => api.post('/deposits', payload),
|
||||||
const params = roomType ? `?roomType=${encodeURIComponent(roomType)}` : '';
|
{ invalidate: invalidateDeposits },
|
||||||
const rows = await api.get<EligibleStudent[]>(`/deposits/eligible-students${params}`);
|
);
|
||||||
setEligibleStudents(rows);
|
const batchCreateMutation = useApiMutation(
|
||||||
setSelectedEligibleStudentIds(rows.map((item) => item.studentId));
|
async (payload: Record<string, unknown>) => api.post('/deposits/batch', payload),
|
||||||
} catch (e: any) {
|
{ invalidate: invalidateDeposits },
|
||||||
message.error(e?.message || '加载在住人员失败');
|
);
|
||||||
} finally {
|
const refundMutation = useApiMutation(
|
||||||
setEligibleLoading(false);
|
async ({ id, payload }: { id: number; payload: Record<string, unknown> }) =>
|
||||||
}
|
api.put(`/deposits/${id}/refund`, payload),
|
||||||
}, []);
|
{ invalidate: invalidateDeposits },
|
||||||
|
);
|
||||||
|
const addInstallmentMutation = useApiMutation(
|
||||||
|
async ({ id, payload }: { id: number; payload: Record<string, unknown> }) =>
|
||||||
|
api.post(`/deposits/${id}/installments`, payload),
|
||||||
|
{ invalidate: [['deposits']] },
|
||||||
|
);
|
||||||
|
const payInstallmentMutation = useApiMutation(
|
||||||
|
async (installmentId: number) => api.post(`/deposits/installments/${installmentId}/pay`),
|
||||||
|
{ invalidate: [['deposits']] },
|
||||||
|
);
|
||||||
|
const saveInstallmentCellMutation = useApiMutation(
|
||||||
|
async ({
|
||||||
|
installmentId,
|
||||||
|
field,
|
||||||
|
value,
|
||||||
|
}: {
|
||||||
|
installmentId: number;
|
||||||
|
field: 'status' | 'paidDate';
|
||||||
|
value: unknown;
|
||||||
|
}) => api.put(`/deposits/installments/${installmentId}`, { [field]: value }),
|
||||||
|
{ invalidate: [['deposits']] },
|
||||||
|
);
|
||||||
|
const deleteInstallmentMutation = useApiMutation(
|
||||||
|
async (installmentId: number) => api.delete(`/deposits/installments/${installmentId}`),
|
||||||
|
{ invalidate: [['deposits']] },
|
||||||
|
);
|
||||||
|
const archiveMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/deposits/${id}`),
|
||||||
|
{ invalidate: invalidateDeposits },
|
||||||
|
);
|
||||||
|
const purgeMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/deposits/${id}/permanent`),
|
||||||
|
{ invalidate: invalidateDeposits },
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
const {
|
||||||
fetchData();
|
data: eligibleStudents = [],
|
||||||
}, [fetchData]);
|
isFetching: eligibleFetching,
|
||||||
|
} = useQuery<EligibleStudent[]>({
|
||||||
|
queryKey: ['deposits', 'eligible', eligibleRoomType],
|
||||||
|
queryFn: async () => {
|
||||||
|
const params: Record<string, string> = {};
|
||||||
|
if (eligibleRoomType) params.roomType = eligibleRoomType;
|
||||||
|
return validateResponse<EligibleStudent[]>(
|
||||||
|
eligibleStudentsSchema,
|
||||||
|
await api.get('/deposits/eligible', { params }),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const eligibleLoading = eligibleFetching;
|
||||||
|
const effectiveSelectedEligibleIds = selectionTouched
|
||||||
|
? selectedEligibleStudentIds
|
||||||
|
: eligibleStudents.map((item) => item.studentId);
|
||||||
|
const fetchEligibleStudents = useCallback(
|
||||||
|
(roomType?: string) => {
|
||||||
|
setEligibleRoomType(roomType);
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['deposits', 'eligible'] });
|
||||||
|
},
|
||||||
|
[queryClient],
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
const changeFilterRoomType = (value: string | undefined) => {
|
||||||
fetchEligibleStudents(filterRoomType);
|
setFilterRoomType(value);
|
||||||
}, [fetchEligibleStudents, filterRoomType]);
|
setSelectionTouched(false);
|
||||||
|
fetchEligibleStudents(value);
|
||||||
|
};
|
||||||
|
|
||||||
const depositByStudentId = useMemo(() => {
|
const depositByStudentId = useMemo(() => {
|
||||||
const map = new Map<number, DepositRecord>();
|
const map = new Map<number, DepositRecord>();
|
||||||
data.forEach((item) => map.set(item.studentId, item));
|
for (const item of data) map.set(item.studentId, item);
|
||||||
return map;
|
return map;
|
||||||
}, [data]);
|
}, [data]);
|
||||||
|
|
||||||
@@ -176,7 +196,6 @@ const DepositsPage: React.FC = () => {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return data.filter((d) => {
|
return data.filter((d) => {
|
||||||
if (searchText) {
|
if (searchText) {
|
||||||
const s = searchText.toLowerCase();
|
const s = searchText.toLowerCase();
|
||||||
@@ -192,10 +211,11 @@ const DepositsPage: React.FC = () => {
|
|||||||
const openBatchModal = (roomType = filterRoomType || '四人间') => {
|
const openBatchModal = (roomType = filterRoomType || '四人间') => {
|
||||||
const amount = suggestedDepositByRoomType[roomType] ?? 100;
|
const amount = suggestedDepositByRoomType[roomType] ?? 100;
|
||||||
setBatchRoomType(roomType);
|
setBatchRoomType(roomType);
|
||||||
|
setSelectionTouched(false);
|
||||||
|
fetchEligibleStudents(roomType);
|
||||||
batchForm.resetFields();
|
batchForm.resetFields();
|
||||||
batchForm.setFieldsValue({ roomType, amount, paidDate: dayjs() });
|
batchForm.setFieldsValue({ roomType, amount, paidDate: dayjs() });
|
||||||
setBatchModal(true);
|
setBatchModal(true);
|
||||||
fetchEligibleStudents(roomType);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleBatchRoomTypeChange = (roomType: string) => {
|
const handleBatchRoomTypeChange = (roomType: string) => {
|
||||||
@@ -207,55 +227,38 @@ const DepositsPage: React.FC = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleCreate = async () => {
|
const handleCreate = async () => {
|
||||||
setSaving(true);
|
|
||||||
try {
|
try {
|
||||||
const values = await createForm.validateFields();
|
const values = await createForm.validateFields();
|
||||||
await api.post('/deposits', {
|
await createMutation.mutateAsync({
|
||||||
studentId: values.studentId,
|
studentId: values.studentId,
|
||||||
amount: values.amount,
|
amount: values.amount,
|
||||||
paidDate: values.paidDate.format('YYYY-MM-DD'),
|
paidDate: values.paidDate.format('YYYY-MM-DD'),
|
||||||
notes: values.notes,
|
notes: values.notes,
|
||||||
});
|
});
|
||||||
message.success('押金金额已增加');
|
message.success('押金收取成功');
|
||||||
setCreateModal(false);
|
setCreateModal(false);
|
||||||
createForm.resetFields();
|
createForm.resetFields();
|
||||||
fetchData();
|
} catch {
|
||||||
fetchEligibleStudents(filterRoomType);
|
// 错误提示由 useApiMutation 统一处理
|
||||||
} catch (e: any) {
|
|
||||||
if (!isFormValidationError(e)) {
|
|
||||||
message.error(e?.message || '操作失败');
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
setSaving(false);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleBatchCreate = async () => {
|
const handleBatchCreate = async () => {
|
||||||
if (selectedEligibleStudentIds.length === 0) {
|
|
||||||
message.warning('请选择至少一名学生');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setSaving(true);
|
|
||||||
try {
|
try {
|
||||||
const values = await batchForm.validateFields();
|
const values = await batchForm.validateFields();
|
||||||
await api.post('/deposits/batch', {
|
await batchCreateMutation.mutateAsync({
|
||||||
studentIds: selectedEligibleStudentIds,
|
studentIds: effectiveSelectedEligibleIds,
|
||||||
amount: values.amount,
|
amount: values.amount,
|
||||||
paidDate: values.paidDate.format('YYYY-MM-DD'),
|
paidDate: values.paidDate.format('YYYY-MM-DD'),
|
||||||
notes: values.notes,
|
notes: values.notes,
|
||||||
roomType: values.roomType,
|
roomType: values.roomType,
|
||||||
});
|
});
|
||||||
message.success(`已为 ${selectedEligibleStudentIds.length} 人批量收取押金`);
|
message.success('批量收取成功');
|
||||||
setBatchModal(false);
|
setBatchModal(false);
|
||||||
batchForm.resetFields();
|
batchForm.resetFields();
|
||||||
await fetchData();
|
setSelectionTouched(false);
|
||||||
fetchEligibleStudents(filterRoomType);
|
} catch {
|
||||||
} catch (e: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
if (!isFormValidationError(e)) {
|
|
||||||
message.error(e?.message || '操作失败');
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
setSaving(false);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -264,19 +267,18 @@ const DepositsPage: React.FC = () => {
|
|||||||
setSaving(true);
|
setSaving(true);
|
||||||
try {
|
try {
|
||||||
const values = await refundForm.validateFields();
|
const values = await refundForm.validateFields();
|
||||||
await api.put(`/deposits/${refundModal.id}/refund`, {
|
await refundMutation.mutateAsync({
|
||||||
refundDate: values.refundDate.format('YYYY-MM-DD'),
|
id: refundModal.id,
|
||||||
notes: values.notes,
|
payload: {
|
||||||
|
refundDate: values.refundDate.format('YYYY-MM-DD'),
|
||||||
|
notes: values.notes,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
message.success('退还操作完成');
|
message.success('退还操作完成');
|
||||||
setRefundModal(null);
|
setRefundModal(null);
|
||||||
refundForm.resetFields();
|
refundForm.resetFields();
|
||||||
fetchData();
|
} catch {
|
||||||
fetchEligibleStudents(filterRoomType);
|
// 错误提示由 useApiMutation 统一处理
|
||||||
} catch (e: any) {
|
|
||||||
if (!isFormValidationError(e)) {
|
|
||||||
message.error(e?.message || '操作失败');
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false);
|
setSaving(false);
|
||||||
}
|
}
|
||||||
@@ -286,31 +288,27 @@ const DepositsPage: React.FC = () => {
|
|||||||
if (installmentModal == null) return;
|
if (installmentModal == null) return;
|
||||||
try {
|
try {
|
||||||
const values = await installmentForm.validateFields();
|
const values = await installmentForm.validateFields();
|
||||||
await api.post(`/deposits/${installmentModal}/installments`, {
|
await addInstallmentMutation.mutateAsync({
|
||||||
amount: values.amount,
|
id: installmentModal,
|
||||||
dueDate: values.dueDate.format('YYYY-MM-DD'),
|
payload: {
|
||||||
|
amount: values.amount,
|
||||||
|
dueDate: values.dueDate.format('YYYY-MM-DD'),
|
||||||
|
},
|
||||||
});
|
});
|
||||||
message.success('分期已添加');
|
message.success('分期已添加');
|
||||||
setInstallmentModal(null);
|
setInstallmentModal(null);
|
||||||
installmentForm.resetFields();
|
installmentForm.resetFields();
|
||||||
fetchData();
|
} catch {
|
||||||
} catch (e: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
if (!isFormValidationError(e)) {
|
|
||||||
message.error(e?.message || '操作失败');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handlePayInstallment = async (installmentId: number) => {
|
const handlePayInstallment = async (installmentId: number) => {
|
||||||
try {
|
try {
|
||||||
await api.put(`/deposits/installments/${installmentId}`, {
|
await payInstallmentMutation.mutateAsync(installmentId);
|
||||||
paidDate: dayjs().format('YYYY-MM-DD'),
|
|
||||||
status: 'paid',
|
|
||||||
});
|
|
||||||
message.success('分期已标记为已缴');
|
message.success('分期已标记为已缴');
|
||||||
fetchData();
|
} catch {
|
||||||
} catch (e: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error(e?.message || '操作失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -319,117 +317,27 @@ const DepositsPage: React.FC = () => {
|
|||||||
field: 'status' | 'paidDate',
|
field: 'status' | 'paidDate',
|
||||||
value: unknown,
|
value: unknown,
|
||||||
) => {
|
) => {
|
||||||
await api.put(`/deposits/installments/${installmentId}`, { [field]: value });
|
try {
|
||||||
message.success('分期记录已保存');
|
await saveInstallmentCellMutation.mutateAsync({ installmentId, field, value });
|
||||||
if (detailModal) {
|
message.success('分期记录已保存');
|
||||||
const refreshed = await api.get<DepositRecord>(`/deposits/${detailModal.id}`);
|
if (detailModal) {
|
||||||
setDetailModal(refreshed);
|
const refreshed = await api.get<DepositRecord>(`/deposits/${detailModal.id}`);
|
||||||
|
setDetailModal(refreshed);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
}
|
}
|
||||||
await fetchData();
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteInstallment = async (installmentId: number) => {
|
const handleDeleteInstallment = async (installmentId: number) => {
|
||||||
try {
|
try {
|
||||||
await api.delete(`/deposits/installments/${installmentId}`);
|
await deleteInstallmentMutation.mutateAsync(installmentId);
|
||||||
message.success('分期已归档');
|
message.success('分期已归档');
|
||||||
fetchData();
|
} catch {
|
||||||
} catch (e: any) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error(e?.message || '操作失败');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const columns = useMemo(
|
|
||||||
() => [
|
|
||||||
{ title: '学生', width: 120, render: (_: unknown, r: any) => r.student?.name || '-' },
|
|
||||||
{
|
|
||||||
title: '当前可用押金',
|
|
||||||
dataIndex: 'amount',
|
|
||||||
width: 130,
|
|
||||||
render: (v: number) => `¥${Number(v || 0).toFixed(2)}`,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '房间',
|
|
||||||
width: 120,
|
|
||||||
render: (_: unknown, r: any) =>
|
|
||||||
r.roomNumber ? `${r.building ? `${r.building}-` : ''}${r.roomNumber}` : '-',
|
|
||||||
},
|
|
||||||
{ title: '房型', dataIndex: 'roomType', width: 100, render: (v: string) => v || '-' },
|
|
||||||
{ title: '最近收取日期', dataIndex: 'paidDate', width: 120, render: (v: string) => v || '-' },
|
|
||||||
{
|
|
||||||
title: '状态',
|
|
||||||
dataIndex: 'status',
|
|
||||||
render: (s: string) =>
|
|
||||||
s === 'unpaid' ? (
|
|
||||||
<Tag color="default">未缴</Tag>
|
|
||||||
) : (
|
|
||||||
<Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{ title: '退还日期', dataIndex: 'refundDate', width: 110, render: (v: unknown) => v || '-' },
|
|
||||||
{ title: '备注', dataIndex: 'notes', width: 120, render: (v: unknown) => v || '-' },
|
|
||||||
{
|
|
||||||
title: '操作',
|
|
||||||
width: 240,
|
|
||||||
render: (_: unknown, record: any) => {
|
|
||||||
const hasDeposit = typeof record.id === 'number';
|
|
||||||
return (
|
|
||||||
<Space>
|
|
||||||
{hasDeposit && (
|
|
||||||
<PermissionButton
|
|
||||||
permission="deposit:view"
|
|
||||||
size="small"
|
|
||||||
onClick={() => {
|
|
||||||
setDetailModal(record);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
详情
|
|
||||||
</PermissionButton>
|
|
||||||
)}
|
|
||||||
{record.status === 'paid' && hasDeposit && (
|
|
||||||
<PermissionButton
|
|
||||||
permission="deposit:refund"
|
|
||||||
size="small"
|
|
||||||
type="primary"
|
|
||||||
onClick={() => {
|
|
||||||
setRefundModal(record);
|
|
||||||
refundForm.setFieldsValue({ refundDate: dayjs() });
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
退还
|
|
||||||
</PermissionButton>
|
|
||||||
)}
|
|
||||||
{hasDeposit && (
|
|
||||||
<Popconfirm
|
|
||||||
title="确定归档?"
|
|
||||||
onConfirm={async () => {
|
|
||||||
try {
|
|
||||||
await api.delete(`/deposits/${record.id}`);
|
|
||||||
message.success('归档成功');
|
|
||||||
fetchData();
|
|
||||||
fetchEligibleStudents(filterRoomType);
|
|
||||||
} catch (e: any) {
|
|
||||||
message.error(e?.message || '归档失败');
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<PermissionButton
|
|
||||||
permission="deposit:delete"
|
|
||||||
size="small"
|
|
||||||
danger
|
|
||||||
icon={<InboxOutlined />}
|
|
||||||
>
|
|
||||||
归档
|
|
||||||
</PermissionButton>
|
|
||||||
</Popconfirm>
|
|
||||||
)}
|
|
||||||
</Space>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
[fetchData, fetchEligibleStudents, filterRoomType, refundForm],
|
|
||||||
);
|
|
||||||
|
|
||||||
const eligibleColumns = [
|
const eligibleColumns = [
|
||||||
{
|
{
|
||||||
title: '学生',
|
title: '学生',
|
||||||
@@ -475,7 +383,7 @@ const DepositsPage: React.FC = () => {
|
|||||||
allowClear
|
allowClear
|
||||||
style={{ width: 130 }}
|
style={{ width: 130 }}
|
||||||
value={filterRoomType}
|
value={filterRoomType}
|
||||||
onChange={(v) => setFilterRoomType(v)}
|
onChange={changeFilterRoomType}
|
||||||
options={roomTypeOptions}
|
options={roomTypeOptions}
|
||||||
/>
|
/>
|
||||||
<Select
|
<Select
|
||||||
@@ -514,301 +422,55 @@ const DepositsPage: React.FC = () => {
|
|||||||
</PermissionButton>
|
</PermissionButton>
|
||||||
</Space>
|
</Space>
|
||||||
</div>
|
</div>
|
||||||
<Table
|
<DepositTable
|
||||||
columns={columns}
|
data={filteredData}
|
||||||
dataSource={filteredData}
|
|
||||||
rowKey="id"
|
|
||||||
loading={loading || (!!filterRoomType && eligibleLoading)}
|
loading={loading || (!!filterRoomType && eligibleLoading)}
|
||||||
scroll={{ x: 1200 }}
|
canPurgeDeposit={canPurgeDeposit}
|
||||||
pagination={{
|
refundForm={refundForm}
|
||||||
defaultPageSize: 15,
|
onDetail={(record) => setDetailModal(record)}
|
||||||
showSizeChanger: true,
|
onRefund={(record) => setRefundModal(record)}
|
||||||
pageSizeOptions: [15, 30, 50, 100],
|
onArchive={(id) => archiveMutation.mutateAsync(id)}
|
||||||
showTotal: (total) => `共 ${total} 条`,
|
onPurge={(id) => purgeMutation.mutateAsync(id)}
|
||||||
}}
|
/>
|
||||||
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
<DepositModals
|
||||||
|
batchModal={batchModal}
|
||||||
|
createModal={createModal}
|
||||||
|
refundModal={refundModal}
|
||||||
|
detailModal={detailModal}
|
||||||
|
installmentModal={installmentModal}
|
||||||
|
batchForm={batchForm}
|
||||||
|
createForm={createForm}
|
||||||
|
refundForm={refundForm}
|
||||||
|
installmentForm={installmentForm}
|
||||||
|
saving={saving}
|
||||||
|
batchRoomType={batchRoomType}
|
||||||
|
effectiveSelectedEligibleIds={effectiveSelectedEligibleIds}
|
||||||
|
eligibleStudents={eligibleStudents}
|
||||||
|
eligibleLoading={eligibleLoading}
|
||||||
|
eligibleColumns={eligibleColumns}
|
||||||
|
studentOptions={studentOptions}
|
||||||
|
onBatchRoomTypeChange={handleBatchRoomTypeChange}
|
||||||
|
onBatchCreate={handleBatchCreate}
|
||||||
|
onCreate={handleCreate}
|
||||||
|
onRefund={handleRefund}
|
||||||
|
onAddInstallment={handleAddInstallment}
|
||||||
|
onPayInstallment={handlePayInstallment}
|
||||||
|
onSaveInstallmentCell={saveInstallmentCell}
|
||||||
|
onDeleteInstallment={handleDeleteInstallment}
|
||||||
|
onCloseBatch={() => setBatchModal(false)}
|
||||||
|
onCloseCreate={() => setCreateModal(false)}
|
||||||
|
onCloseRefund={() => setRefundModal(null)}
|
||||||
|
onCloseDetail={() => setDetailModal(null)}
|
||||||
|
onCloseInstallment={() => setInstallmentModal(null)}
|
||||||
|
onOpenInstallment={(id) => {
|
||||||
|
setInstallmentModal(id);
|
||||||
|
installmentForm.resetFields();
|
||||||
|
}}
|
||||||
|
onSelectEligible={(ids) => {
|
||||||
|
setSelectedEligibleStudentIds(ids);
|
||||||
|
setSelectionTouched(true);
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Batch Create Modal */}
|
|
||||||
<Modal
|
|
||||||
title="按房型批量收取押金"
|
|
||||||
open={batchModal}
|
|
||||||
onOk={handleBatchCreate}
|
|
||||||
onCancel={() => setBatchModal(false)}
|
|
||||||
okText="确认批量收取"
|
|
||||||
confirmLoading={saving}
|
|
||||||
okButtonProps={{ disabled: selectedEligibleStudentIds.length === 0 }}
|
|
||||||
width={760}
|
|
||||||
>
|
|
||||||
<Form form={batchForm} layout="vertical">
|
|
||||||
<Space style={{ width: '100%' }} align="start" wrap>
|
|
||||||
<Form.Item
|
|
||||||
name="roomType"
|
|
||||||
label="房型"
|
|
||||||
rules={[{ required: true, message: '请选择房型' }]}
|
|
||||||
>
|
|
||||||
<Select
|
|
||||||
style={{ width: 140 }}
|
|
||||||
options={roomTypeOptions}
|
|
||||||
onChange={handleBatchRoomTypeChange}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item
|
|
||||||
name="amount"
|
|
||||||
label="每人收取金额(元)"
|
|
||||||
rules={[{ required: true, message: '请输入金额' }]}
|
|
||||||
>
|
|
||||||
<InputNumber min={0.01} precision={2} style={{ width: 180 }} />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item
|
|
||||||
name="paidDate"
|
|
||||||
label="收取日期"
|
|
||||||
rules={[{ required: true, message: '请选择日期' }]}
|
|
||||||
>
|
|
||||||
<DatePicker style={{ width: 180 }} placeholder="选择收取日期" format="YYYY-MM-DD" />
|
|
||||||
</Form.Item>
|
|
||||||
</Space>
|
|
||||||
<Form.Item name="notes" label="备注">
|
|
||||||
<Input.TextArea rows={2} placeholder={`${batchRoomType}押金`} />
|
|
||||||
</Form.Item>
|
|
||||||
</Form>
|
|
||||||
<div style={{ marginBottom: 8 }}>
|
|
||||||
已选择 <strong>{selectedEligibleStudentIds.length}</strong> / {eligibleStudents.length} 人
|
|
||||||
{suggestedDepositByRoomType[batchRoomType] && (
|
|
||||||
<span style={{ color: '#999', marginLeft: 8 }}>
|
|
||||||
建议金额:¥{suggestedDepositByRoomType[batchRoomType]}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<Table
|
|
||||||
size="small"
|
|
||||||
columns={eligibleColumns}
|
|
||||||
dataSource={eligibleStudents}
|
|
||||||
rowKey="studentId"
|
|
||||||
loading={eligibleLoading}
|
|
||||||
locale={{ emptyText: <Empty description="暂无符合条件的在住人员" /> }}
|
|
||||||
pagination={{ pageSize: 6, showSizeChanger: false }}
|
|
||||||
rowSelection={{
|
|
||||||
selectedRowKeys: selectedEligibleStudentIds,
|
|
||||||
onChange: (keys) => setSelectedEligibleStudentIds(keys as number[]),
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Modal>
|
|
||||||
|
|
||||||
{/* Create Modal */}
|
|
||||||
<Modal
|
|
||||||
title="收取押金"
|
|
||||||
open={createModal}
|
|
||||||
onOk={handleCreate}
|
|
||||||
onCancel={() => setCreateModal(false)}
|
|
||||||
okText="确认"
|
|
||||||
confirmLoading={saving}
|
|
||||||
>
|
|
||||||
<Form form={createForm} layout="vertical">
|
|
||||||
<Form.Item
|
|
||||||
name="studentId"
|
|
||||||
label="学生"
|
|
||||||
rules={[{ required: true, message: '请选择学生' }]}
|
|
||||||
>
|
|
||||||
<Select
|
|
||||||
showSearch
|
|
||||||
optionFilterProp="label"
|
|
||||||
placeholder="搜索并选择学生"
|
|
||||||
options={studentOptions}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="amount" label="本次收取金额(元)" rules={[{ required: true }]}>
|
|
||||||
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="paidDate" label="收取日期" rules={[{ required: true }]}>
|
|
||||||
<DatePicker style={{ width: '100%' }} placeholder="选择收取日期" format="YYYY-MM-DD" />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="notes" label="备注">
|
|
||||||
<Input.TextArea rows={2} />
|
|
||||||
</Form.Item>
|
|
||||||
</Form>
|
|
||||||
</Modal>
|
|
||||||
|
|
||||||
{/* Refund Modal */}
|
|
||||||
<Modal
|
|
||||||
title={`退还押金 - ${refundModal?.student?.name}`}
|
|
||||||
open={!!refundModal}
|
|
||||||
onOk={handleRefund}
|
|
||||||
onCancel={() => setRefundModal(null)}
|
|
||||||
okText="确认退还"
|
|
||||||
confirmLoading={saving}
|
|
||||||
>
|
|
||||||
<Form form={refundForm} layout="vertical">
|
|
||||||
<div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 8 }}>
|
|
||||||
当前可用押金: <strong>¥{Number(refundModal?.amount || 0).toFixed(2)}</strong>
|
|
||||||
</div>
|
|
||||||
<Form.Item name="refundDate" label="退还日期" rules={[{ required: true }]}>
|
|
||||||
<DatePicker style={{ width: '100%' }} placeholder="选择退还日期" format="YYYY-MM-DD" />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="notes" label="备注">
|
|
||||||
<Input.TextArea rows={2} />
|
|
||||||
</Form.Item>
|
|
||||||
</Form>
|
|
||||||
</Modal>
|
|
||||||
|
|
||||||
{/* Detail Modal */}
|
|
||||||
<Modal
|
|
||||||
title={`押金详情 - ${detailModal?.student?.name}`}
|
|
||||||
open={!!detailModal}
|
|
||||||
onCancel={() => setDetailModal(null)}
|
|
||||||
footer={null}
|
|
||||||
width={640}
|
|
||||||
>
|
|
||||||
{detailModal && (
|
|
||||||
<div>
|
|
||||||
<Card size="small" style={{ marginBottom: 16 }}>
|
|
||||||
<p>
|
|
||||||
<strong>当前可用押金:</strong> ¥{Number(detailModal.amount).toFixed(2)}
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<strong>最近收取日期:</strong> {detailModal.paidDate}
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<strong>状态:</strong>{' '}
|
|
||||||
<Tag color={statusMap[detailModal.status]?.color}>
|
|
||||||
{statusMap[detailModal.status]?.text || detailModal.status}
|
|
||||||
</Tag>
|
|
||||||
</p>
|
|
||||||
{detailModal.notes && (
|
|
||||||
<p>
|
|
||||||
<strong>备注:</strong> {detailModal.notes}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Installments Section */}
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
display: 'flex',
|
|
||||||
justifyContent: 'space-between',
|
|
||||||
alignItems: 'center',
|
|
||||||
marginBottom: 8,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<h4 style={{ margin: 0 }}>分期记录</h4>
|
|
||||||
<PermissionButton
|
|
||||||
permission="deposit:edit"
|
|
||||||
size="small"
|
|
||||||
type="primary"
|
|
||||||
icon={<PlusOutlined />}
|
|
||||||
onClick={() => {
|
|
||||||
setInstallmentModal(detailModal.id);
|
|
||||||
installmentForm.resetFields();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
添加分期
|
|
||||||
</PermissionButton>
|
|
||||||
</div>
|
|
||||||
{detailModal.installments && detailModal.installments.length > 0 ? (
|
|
||||||
<Table
|
|
||||||
size="small"
|
|
||||||
pagination={false}
|
|
||||||
rowKey="id"
|
|
||||||
dataSource={detailModal.installments}
|
|
||||||
columns={[
|
|
||||||
{
|
|
||||||
title: '金额',
|
|
||||||
dataIndex: 'amount',
|
|
||||||
render: (value: number) => `¥${Number(value).toFixed(2)}`,
|
|
||||||
},
|
|
||||||
{ title: '到期日', dataIndex: 'dueDate' },
|
|
||||||
{
|
|
||||||
title: '实付日',
|
|
||||||
dataIndex: 'paidDate',
|
|
||||||
render: (value: string, item: any) => (
|
|
||||||
<EditableCell
|
|
||||||
value={value}
|
|
||||||
editor="date"
|
|
||||||
permission="deposit:edit"
|
|
||||||
onSave={(next) => saveInstallmentCell(item.id, 'paidDate', next)}
|
|
||||||
>
|
|
||||||
{value || '-'}
|
|
||||||
</EditableCell>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '状态',
|
|
||||||
dataIndex: 'status',
|
|
||||||
render: (value: string, item: any) => (
|
|
||||||
<EditableCell
|
|
||||||
value={value}
|
|
||||||
editor="select"
|
|
||||||
options={[
|
|
||||||
{ value: 'pending', label: '待缴' },
|
|
||||||
{ value: 'paid', label: '已缴' },
|
|
||||||
{ value: 'overdue', label: '逾期' },
|
|
||||||
]}
|
|
||||||
permission="deposit:edit"
|
|
||||||
onSave={(next) => saveInstallmentCell(item.id, 'status', next)}
|
|
||||||
>
|
|
||||||
<Tag color={installmentStatusMap[value]?.color}>
|
|
||||||
{installmentStatusMap[value]?.text || value}
|
|
||||||
</Tag>
|
|
||||||
</EditableCell>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '操作',
|
|
||||||
render: (_: unknown, item: any) => (
|
|
||||||
<Space>
|
|
||||||
{item.status === 'pending' && (
|
|
||||||
<PermissionButton
|
|
||||||
permission="deposit:edit"
|
|
||||||
size="small"
|
|
||||||
type="primary"
|
|
||||||
icon={<DollarOutlined />}
|
|
||||||
onClick={() => handlePayInstallment(item.id)}
|
|
||||||
>
|
|
||||||
标记已缴
|
|
||||||
</PermissionButton>
|
|
||||||
)}
|
|
||||||
<Popconfirm
|
|
||||||
title="确定归档?"
|
|
||||||
onConfirm={() => handleDeleteInstallment(item.id)}
|
|
||||||
>
|
|
||||||
<PermissionButton
|
|
||||||
permission="deposit:delete"
|
|
||||||
size="small"
|
|
||||||
danger
|
|
||||||
icon={<InboxOutlined />}
|
|
||||||
>
|
|
||||||
归档
|
|
||||||
</PermissionButton>
|
|
||||||
</Popconfirm>
|
|
||||||
</Space>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<p style={{ color: '#999' }}>暂无分期记录</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</Modal>
|
|
||||||
|
|
||||||
{/* Add Installment Modal */}
|
|
||||||
<Modal
|
|
||||||
title="添加分期"
|
|
||||||
open={installmentModal != null}
|
|
||||||
onOk={handleAddInstallment}
|
|
||||||
onCancel={() => setInstallmentModal(null)}
|
|
||||||
okText="确认"
|
|
||||||
>
|
|
||||||
<Form form={installmentForm} layout="vertical">
|
|
||||||
<Form.Item name="amount" label="分期金额(元)" rules={[{ required: true }]}>
|
|
||||||
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="dueDate" label="到期日期" rules={[{ required: true }]}>
|
|
||||||
<DatePicker style={{ width: '100%' }} placeholder="选择到期日期" format="YYYY-MM-DD" />
|
|
||||||
</Form.Item>
|
|
||||||
</Form>
|
|
||||||
</Modal>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { DatePicker, Form, Input, Modal, Select } from 'antd';
|
import { DatePicker, Form, Input, Modal, Select, type FormInstance } from 'antd';
|
||||||
import type { FormInstance } from 'antd';
|
import { EXAM_TYPE_OPTIONS, type ClassOption, type ExamFormValues } from './types';
|
||||||
import type { ClassOption, ExamFormValues } from './types';
|
|
||||||
import { EXAM_TYPE_OPTIONS } from './types';
|
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
@@ -32,24 +30,42 @@ const ExamFormModal: React.FC<Props> = ({
|
|||||||
width={560}
|
width={560}
|
||||||
>
|
>
|
||||||
<Form form={form} layout="vertical">
|
<Form form={form} layout="vertical">
|
||||||
<Form.Item name="examType" label="考试类型" rules={[{ required: true, message: '请选择考试类型' }]}>
|
<Form.Item
|
||||||
|
name="examType"
|
||||||
|
label="考试类型"
|
||||||
|
rules={[{ required: true, message: '请选择考试类型' }]}
|
||||||
|
>
|
||||||
<Select options={EXAM_TYPE_OPTIONS} placeholder="请选择" />
|
<Select options={EXAM_TYPE_OPTIONS} placeholder="请选择" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="examName" label="考试名称" rules={[{ required: true, message: '请输入考试名称' }]}>
|
<Form.Item
|
||||||
|
name="examName"
|
||||||
|
label="考试名称"
|
||||||
|
rules={[{ required: true, message: '请输入考试名称' }]}
|
||||||
|
>
|
||||||
<Input placeholder="如:2026 年 7 月月考" />
|
<Input placeholder="如:2026 年 7 月月考" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="subject" label="科目" rules={[{ required: true, message: '请输入科目' }]}>
|
<Form.Item name="subject" label="科目" rules={[{ required: true, message: '请输入科目' }]}>
|
||||||
<Input placeholder="如:数学" />
|
<Input placeholder="如:数学" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="examDate" label="考试日期" rules={[{ required: true, message: '请选择考试日期' }]}>
|
<Form.Item
|
||||||
|
name="examDate"
|
||||||
|
label="考试日期"
|
||||||
|
rules={[{ required: true, message: '请选择考试日期' }]}
|
||||||
|
>
|
||||||
<DatePicker style={{ width: '100%' }} />
|
<DatePicker style={{ width: '100%' }} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="classId" label="考试班级" rules={[{ required: true, message: '请选择考试班级' }]}>
|
<Form.Item
|
||||||
|
name="classId"
|
||||||
|
label="考试班级"
|
||||||
|
rules={[{ required: true, message: '请选择考试班级' }]}
|
||||||
|
>
|
||||||
<Select
|
<Select
|
||||||
showSearch
|
showSearch
|
||||||
optionFilterProp="label"
|
optionFilterProp="label"
|
||||||
placeholder="选择在读班级"
|
placeholder="选择在读班级"
|
||||||
options={classes.filter((item) => !item.isArchived).map((item) => ({ value: item.id, label: item.name }))}
|
options={classes
|
||||||
|
.filter((item) => !item.isArchived)
|
||||||
|
.map((item) => ({ value: item.id, label: item.name }))}
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
|
|||||||
@@ -1,16 +1,21 @@
|
|||||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
import React, { useCallback, useMemo } from 'react';
|
||||||
import { Alert, Button, Card, Descriptions, Empty, Space, Spin, Table, Tag, Tooltip } from 'antd';
|
import { Alert, Button, Card, Descriptions, Empty, Space, Spin, Table, Tag, Tooltip } from 'antd';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import { ArrowLeftOutlined, EyeOutlined } from '@ant-design/icons';
|
import { ArrowLeftOutlined, EyeOutlined } from '@ant-design/icons';
|
||||||
import { useNavigate, useParams } from 'react-router-dom';
|
import { useNavigate, useParams } from 'react-router';
|
||||||
import api from '../../api';
|
import api from '../../api';
|
||||||
import EditableCell from '../../components/EditableCell';
|
import EditableCell from '../../components/EditableCell';
|
||||||
import { useViewSensitive } from '../../hooks/useViewSensitive';
|
import { useViewSensitive } from '../../hooks/useViewSensitive';
|
||||||
import { maskPhone } from '../../utils/sensitive';
|
import { maskPhone } from '../../utils/sensitive';
|
||||||
import { message } from '../../ui/app-message';
|
import { message } from '../../ui/app-message';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||||
|
import { validateResponse } from '../../utils/validate';
|
||||||
|
import { examDetailSchema } from '../../api/schemas';
|
||||||
import { usePermission } from '../../hooks/usePermission';
|
import { usePermission } from '../../hooks/usePermission';
|
||||||
import type { ExamItem } from './types';
|
import type { ExamItem } from './types';
|
||||||
import './style.css';
|
import './style.css';
|
||||||
|
import { getErrorMessage } from '../../utils/error';
|
||||||
|
|
||||||
interface ScoreRow {
|
interface ScoreRow {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -50,30 +55,38 @@ const PhoneCell: React.FC<{ row: ScoreRow }> = ({ row }) => {
|
|||||||
const ExamDetailPage: React.FC = () => {
|
const ExamDetailPage: React.FC = () => {
|
||||||
const { id } = useParams();
|
const { id } = useParams();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [detail, setDetail] = useState<ExamDetail | null>(null);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const { data: detail, isLoading, isFetching } = useQuery<ExamDetail | null>({
|
||||||
setLoading(true);
|
queryKey: ['exams', 'detail', id],
|
||||||
try {
|
queryFn: async () => {
|
||||||
setDetail(await api.get<ExamDetail>(`/exams/${id}`));
|
try {
|
||||||
} catch (error) {
|
return validateResponse<ExamDetail>(
|
||||||
message.error((error as { message?: string })?.message || '加载考试失败');
|
examDetailSchema,
|
||||||
} finally {
|
await api.get<ExamDetail>(`/exams/${id}`),
|
||||||
setLoading(false);
|
);
|
||||||
}
|
} catch (error) {
|
||||||
}, [id]);
|
message.error(getErrorMessage(error, '加载考试失败'));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const loading = isLoading || isFetching;
|
||||||
|
|
||||||
useEffect(() => {
|
const saveScoreMutation = useApiMutation(
|
||||||
void load();
|
async ({ rowId, score }: { rowId: number; score: number | null }) =>
|
||||||
}, [load]);
|
api.put(`/exams/${id}/scores/${rowId}`, { score }),
|
||||||
|
{ invalidate: [['exams', 'detail', id]] },
|
||||||
|
);
|
||||||
const saveScore = useCallback(
|
const saveScore = useCallback(
|
||||||
async (row: ScoreRow, value: number | undefined) => {
|
async (row: ScoreRow, value: number | undefined) => {
|
||||||
await api.put(`/exams/${id}/scores/${row.id}`, { score: value ?? null });
|
try {
|
||||||
message.success('成绩已保存');
|
await saveScoreMutation.mutateAsync({ rowId: row.id, score: value ?? null });
|
||||||
await load();
|
message.success('成绩已保存');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
},
|
},
|
||||||
[id, load],
|
[saveScoreMutation],
|
||||||
);
|
);
|
||||||
|
|
||||||
const columns = useMemo<ColumnsType<ScoreRow>>(() => {
|
const columns = useMemo<ColumnsType<ScoreRow>>(() => {
|
||||||
|
|||||||
@@ -1,22 +1,51 @@
|
|||||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
import React, { useMemo, useState } from 'react';
|
||||||
import { Button, Card, Checkbox, Col, Empty, Form, Input, Popconfirm, Progress, Row, Select, Space, Switch, Tag } from 'antd';
|
import { useDebounceValue } from 'usehooks-ts';
|
||||||
import { CalendarOutlined, InboxOutlined, PlusOutlined, SearchOutlined, TeamOutlined } from '@ant-design/icons';
|
import {
|
||||||
|
App,
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Checkbox,
|
||||||
|
Col,
|
||||||
|
Empty,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
Popconfirm,
|
||||||
|
Progress,
|
||||||
|
Row,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Switch,
|
||||||
|
Tag,
|
||||||
|
} from 'antd';
|
||||||
|
import {
|
||||||
|
CalendarOutlined,
|
||||||
|
DeleteOutlined,
|
||||||
|
InboxOutlined,
|
||||||
|
PlusOutlined,
|
||||||
|
SearchOutlined,
|
||||||
|
TeamOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router';
|
||||||
import api from '../../api';
|
import api from '../../api';
|
||||||
import { message } from '../../ui/app-message';
|
import { message } from '../../ui/app-message';
|
||||||
import ExamFormModal from './ExamFormModal';
|
import ExamFormModal from './ExamFormModal';
|
||||||
import { selectAllExamIds, toggleExamSelection } from './selection';
|
import { selectAllExamIds, toggleExamSelection } from './selection';
|
||||||
import type { ClassOption, ExamFormValues, ExamItem } from './types';
|
import { EXAM_TYPE_OPTIONS, type ClassOption, type ExamFormValues, type ExamItem } from './types';
|
||||||
import { EXAM_TYPE_OPTIONS } from './types';
|
|
||||||
import './style.css';
|
import './style.css';
|
||||||
|
import { usePermission } from '../../hooks/usePermission';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||||
|
import { validateResponse } from '../../utils/validate';
|
||||||
|
import { classOptionsSchema, examsSchema } from '../../api/schemas';
|
||||||
|
import { getErrorMessage } from '../../utils/error';
|
||||||
|
|
||||||
const ExamsPage: React.FC = () => {
|
const ExamsPage: React.FC = () => {
|
||||||
|
const { modal } = App.useApp();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const { hasPermission } = usePermission();
|
||||||
|
const canPurgeExam = hasPermission('exam:purge');
|
||||||
const [form] = Form.useForm<ExamFormValues>();
|
const [form] = Form.useForm<ExamFormValues>();
|
||||||
const [data, setData] = useState<ExamItem[]>([]);
|
|
||||||
const [classes, setClasses] = useState<ClassOption[]>([]);
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [batchLoading, setBatchLoading] = useState(false);
|
const [batchLoading, setBatchLoading] = useState(false);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [modalOpen, setModalOpen] = useState(false);
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
@@ -25,38 +54,96 @@ const ExamsPage: React.FC = () => {
|
|||||||
const [classId, setClassId] = useState<number>();
|
const [classId, setClassId] = useState<number>();
|
||||||
const [showArchived, setShowArchived] = useState(false);
|
const [showArchived, setShowArchived] = useState(false);
|
||||||
const [selectedExamIds, setSelectedExamIds] = useState<number[]>([]);
|
const [selectedExamIds, setSelectedExamIds] = useState<number[]>([]);
|
||||||
|
const [debouncedFilters] = useDebounceValue(
|
||||||
|
{ keyword, examType, classId, showArchived },
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
|
||||||
const loadClasses = useCallback(async () => {
|
const { data: classes = [] } = useQuery<ClassOption[]>({
|
||||||
const result = await api.get<ClassOption[]>('/classes');
|
queryKey: ['exams', 'classes'],
|
||||||
setClasses(result ?? []);
|
queryFn: async () => {
|
||||||
}, []);
|
try {
|
||||||
|
return (
|
||||||
|
validateResponse<ClassOption[]>(
|
||||||
|
classOptionsSchema,
|
||||||
|
await api.get<ClassOption[]>('/classes'),
|
||||||
|
) ?? []
|
||||||
|
);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
message.error(getErrorMessage(error, '加载班级失败'));
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const loadExams = useCallback(async () => {
|
const { data = [], isFetching } = useQuery<ExamItem[]>({
|
||||||
|
queryKey: [
|
||||||
|
'exams',
|
||||||
|
debouncedFilters.keyword,
|
||||||
|
debouncedFilters.examType,
|
||||||
|
debouncedFilters.classId,
|
||||||
|
debouncedFilters.showArchived,
|
||||||
|
],
|
||||||
|
queryFn: async () => {
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (debouncedFilters.keyword.trim())
|
||||||
|
params.set('keyword', debouncedFilters.keyword.trim());
|
||||||
|
if (debouncedFilters.examType) params.set('examType', debouncedFilters.examType);
|
||||||
|
if (debouncedFilters.classId) params.set('classId', String(debouncedFilters.classId));
|
||||||
|
params.set('isArchived', String(debouncedFilters.showArchived));
|
||||||
|
return (
|
||||||
|
validateResponse<ExamItem[]>(
|
||||||
|
examsSchema,
|
||||||
|
await api.get<ExamItem[]>(`/exams?${params.toString()}`),
|
||||||
|
) ?? []
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
message.error(getErrorMessage(error, '加载考试失败'));
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const loading = isFetching;
|
||||||
|
|
||||||
|
const saveMutation = useApiMutation(
|
||||||
|
async (payload: Record<string, unknown>) => api.post('/exams', payload),
|
||||||
|
{ invalidate: [['exams']] },
|
||||||
|
);
|
||||||
|
const archiveMutation = useApiMutation(
|
||||||
|
async ({ id, archive }: { id: number; archive: boolean }) =>
|
||||||
|
api.put(`/exams/${id}/${archive ? 'archive' : 'restore'}`),
|
||||||
|
{ invalidate: [['exams']] },
|
||||||
|
);
|
||||||
|
const purgeMutation = useApiMutation(
|
||||||
|
async (id: number) => api.delete(`/exams/${id}/permanent`),
|
||||||
|
{ invalidate: [['exams']] },
|
||||||
|
);
|
||||||
|
const batchPurgeMutation = useApiMutation(
|
||||||
|
async (ids: number[]) => api.post<{ deleted: number; skipped: number }>('/exams/batch-permanent-delete', { ids }),
|
||||||
|
{ invalidate: [['exams']] },
|
||||||
|
);
|
||||||
|
const batchArchiveMutation = useApiMutation(
|
||||||
|
async (ids: number[]) => api.put<{ archived: number; skipped: number }>('/exams/batch-archive', { ids }),
|
||||||
|
{ invalidate: [['exams']] },
|
||||||
|
);
|
||||||
|
const batchRestoreMutation = useApiMutation(
|
||||||
|
async (ids: number[]) => api.put<{ restored: number; skipped: number }>('/exams/batch-restore', { ids }),
|
||||||
|
{ invalidate: [['exams']] },
|
||||||
|
);
|
||||||
|
|
||||||
|
const updateKeyword = (value: string) => {
|
||||||
|
setKeyword(value);
|
||||||
setSelectedExamIds([]);
|
setSelectedExamIds([]);
|
||||||
setLoading(true);
|
};
|
||||||
try {
|
const updateExamType = (value: string | undefined) => {
|
||||||
const params = new URLSearchParams();
|
setExamType(value);
|
||||||
if (keyword.trim()) params.set('keyword', keyword.trim());
|
setSelectedExamIds([]);
|
||||||
if (examType) params.set('examType', examType);
|
};
|
||||||
if (classId) params.set('classId', String(classId));
|
const updateClassId = (value: number | undefined) => {
|
||||||
params.set('isArchived', String(showArchived));
|
setClassId(value);
|
||||||
const result = await api.get<ExamItem[]>(`/exams?${params.toString()}`);
|
setSelectedExamIds([]);
|
||||||
setData(result ?? []);
|
};
|
||||||
} catch (error) {
|
|
||||||
message.error((error as { message?: string })?.message || '加载考试失败');
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
}, [classId, examType, keyword, showArchived]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
void loadClasses().catch((error: { message?: string }) => message.error(error?.message || '加载班级失败'));
|
|
||||||
}, [loadClasses]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const timer = window.setTimeout(() => void loadExams(), 200);
|
|
||||||
return () => window.clearTimeout(timer);
|
|
||||||
}, [loadExams]);
|
|
||||||
|
|
||||||
const classOptions = useMemo(
|
const classOptions = useMemo(
|
||||||
() => classes.map((item) => ({ value: item.id, label: item.name })),
|
() => classes.map((item) => ({ value: item.id, label: item.name })),
|
||||||
@@ -74,13 +161,11 @@ const ExamsPage: React.FC = () => {
|
|||||||
const values = await form.validateFields();
|
const values = await form.validateFields();
|
||||||
setSaving(true);
|
setSaving(true);
|
||||||
const payload = { ...values, examDate: values.examDate.format('YYYY-MM-DD') };
|
const payload = { ...values, examDate: values.examDate.format('YYYY-MM-DD') };
|
||||||
await api.post('/exams', payload);
|
await saveMutation.mutateAsync(payload);
|
||||||
message.success('考试已创建');
|
message.success('考试已创建');
|
||||||
setModalOpen(false);
|
setModalOpen(false);
|
||||||
await loadExams();
|
} catch {
|
||||||
} catch (error) {
|
// 校验错误静默,接口错误由 useApiMutation 统一提示
|
||||||
if ((error as { errorFields?: unknown[] }).errorFields) return;
|
|
||||||
message.error((error as { message?: string })?.message || '保存失败');
|
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false);
|
setSaving(false);
|
||||||
}
|
}
|
||||||
@@ -88,11 +173,44 @@ const ExamsPage: React.FC = () => {
|
|||||||
|
|
||||||
const changeArchiveStatus = async (exam: ExamItem, archive: boolean) => {
|
const changeArchiveStatus = async (exam: ExamItem, archive: boolean) => {
|
||||||
try {
|
try {
|
||||||
await api.put(`/exams/${exam.id}/${archive ? 'archive' : 'restore'}`);
|
await archiveMutation.mutateAsync({ id: exam.id, archive });
|
||||||
message.success(archive ? '考试已归档' : '考试已恢复');
|
message.success(archive ? '考试已归档' : '考试已恢复');
|
||||||
await loadExams();
|
} catch {
|
||||||
} catch (error) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error((error as { message?: string })?.message || '操作失败');
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePurge = (exam: ExamItem) => {
|
||||||
|
modal.confirm({
|
||||||
|
title: `永久删除考试「${exam.examName}」?`,
|
||||||
|
content: '删除后不可恢复,该考试及其成绩记录将被物理删除。确定继续?',
|
||||||
|
okText: '永久删除',
|
||||||
|
okButtonProps: { danger: true },
|
||||||
|
cancelText: '取消',
|
||||||
|
onOk: async () => {
|
||||||
|
try {
|
||||||
|
await purgeMutation.mutateAsync(exam.id);
|
||||||
|
message.success('已永久删除(不可恢复)');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const batchPurge = async () => {
|
||||||
|
if (selectedExamIds.length === 0 || batchLoading) return;
|
||||||
|
setBatchLoading(true);
|
||||||
|
try {
|
||||||
|
const result = await batchPurgeMutation.mutateAsync(selectedExamIds);
|
||||||
|
message.success(
|
||||||
|
`已永久删除 ${result.deleted} 场考试${result.skipped ? `,跳过 ${result.skipped} 场` : ''}`,
|
||||||
|
);
|
||||||
|
setSelectedExamIds([]);
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
} finally {
|
||||||
|
setBatchLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -100,7 +218,12 @@ const ExamsPage: React.FC = () => {
|
|||||||
const partiallySelected = selectedExamIds.length > 0 && !allCurrentSelected;
|
const partiallySelected = selectedExamIds.length > 0 && !allCurrentSelected;
|
||||||
|
|
||||||
const toggleSelectAll = (checked: boolean) => {
|
const toggleSelectAll = (checked: boolean) => {
|
||||||
setSelectedExamIds(selectAllExamIds(data.map((exam) => exam.id), checked));
|
setSelectedExamIds(
|
||||||
|
selectAllExamIds(
|
||||||
|
data.map((exam) => exam.id),
|
||||||
|
checked,
|
||||||
|
),
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const changeArchiveView = (checked: boolean) => {
|
const changeArchiveView = (checked: boolean) => {
|
||||||
@@ -113,24 +236,19 @@ const ExamsPage: React.FC = () => {
|
|||||||
setBatchLoading(true);
|
setBatchLoading(true);
|
||||||
try {
|
try {
|
||||||
if (archive) {
|
if (archive) {
|
||||||
const result = await api.put<{ archived: number; skipped: number }>('/exams/batch-archive', {
|
const result = await batchArchiveMutation.mutateAsync(selectedExamIds);
|
||||||
ids: selectedExamIds,
|
|
||||||
});
|
|
||||||
message.success(
|
message.success(
|
||||||
`已归档 ${result.archived} 场考试${result.skipped ? `,跳过 ${result.skipped} 场` : ''}`,
|
`已归档 ${result.archived} 场考试${result.skipped ? `,跳过 ${result.skipped} 场` : ''}`,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
const result = await api.put<{ restored: number; skipped: number }>('/exams/batch-restore', {
|
const result = await batchRestoreMutation.mutateAsync(selectedExamIds);
|
||||||
ids: selectedExamIds,
|
|
||||||
});
|
|
||||||
message.success(
|
message.success(
|
||||||
`已恢复 ${result.restored} 场考试${result.skipped ? `,跳过 ${result.skipped} 场` : ''}`,
|
`已恢复 ${result.restored} 场考试${result.skipped ? `,跳过 ${result.skipped} 场` : ''}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
setSelectedExamIds([]);
|
setSelectedExamIds([]);
|
||||||
await loadExams();
|
} catch {
|
||||||
} catch (error) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
message.error((error as { message?: string })?.message || '批量操作失败');
|
|
||||||
} finally {
|
} finally {
|
||||||
setBatchLoading(false);
|
setBatchLoading(false);
|
||||||
}
|
}
|
||||||
@@ -140,9 +258,31 @@ const ExamsPage: React.FC = () => {
|
|||||||
<div className="exam-page">
|
<div className="exam-page">
|
||||||
<div className="exam-toolbar">
|
<div className="exam-toolbar">
|
||||||
<Space wrap>
|
<Space wrap>
|
||||||
<Input value={keyword} onChange={(event) => setKeyword(event.target.value)} prefix={<SearchOutlined />} placeholder="搜索考试名称" allowClear />
|
<Input
|
||||||
<Select value={examType} onChange={setExamType} options={EXAM_TYPE_OPTIONS} placeholder="考试类型" allowClear style={{ width: 140 }} />
|
value={keyword}
|
||||||
<Select value={classId} onChange={setClassId} options={classOptions} placeholder="考试班级" allowClear showSearch optionFilterProp="label" style={{ width: 180 }} />
|
onChange={(event) => updateKeyword(event.target.value)}
|
||||||
|
prefix={<SearchOutlined />}
|
||||||
|
placeholder="搜索考试名称"
|
||||||
|
allowClear
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
value={examType}
|
||||||
|
onChange={updateExamType}
|
||||||
|
options={EXAM_TYPE_OPTIONS}
|
||||||
|
placeholder="考试类型"
|
||||||
|
allowClear
|
||||||
|
style={{ width: 140 }}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
value={classId}
|
||||||
|
onChange={updateClassId}
|
||||||
|
options={classOptions}
|
||||||
|
placeholder="考试班级"
|
||||||
|
allowClear
|
||||||
|
showSearch
|
||||||
|
optionFilterProp="label"
|
||||||
|
style={{ width: 180 }}
|
||||||
|
/>
|
||||||
</Space>
|
</Space>
|
||||||
<Space wrap>
|
<Space wrap>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
@@ -171,29 +311,55 @@ const ExamsPage: React.FC = () => {
|
|||||||
{showArchived ? '批量恢复' : '批量归档'}
|
{showArchived ? '批量恢复' : '批量归档'}
|
||||||
</Button>
|
</Button>
|
||||||
</Popconfirm>
|
</Popconfirm>
|
||||||
|
{showArchived && canPurgeExam ? (
|
||||||
|
<Popconfirm
|
||||||
|
title={`确认永久删除选中的 ${selectedExamIds.length} 场考试?`}
|
||||||
|
description="删除后不可恢复,相关成绩将一并清除。"
|
||||||
|
disabled={selectedExamIds.length === 0 || batchLoading}
|
||||||
|
onConfirm={() => void batchPurge()}
|
||||||
|
okText="永久删除"
|
||||||
|
okButtonProps={{ danger: true }}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
danger
|
||||||
|
icon={<DeleteOutlined />}
|
||||||
|
loading={batchLoading}
|
||||||
|
disabled={selectedExamIds.length === 0}
|
||||||
|
>
|
||||||
|
批量删除
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
) : null}
|
||||||
<span className="exam-archive-toggle">
|
<span className="exam-archive-toggle">
|
||||||
<InboxOutlined />
|
<InboxOutlined />
|
||||||
归档
|
归档
|
||||||
<Switch size="small" checked={showArchived} onChange={changeArchiveView} />
|
<Switch size="small" checked={showArchived} onChange={changeArchiveView} />
|
||||||
</span>
|
</span>
|
||||||
{!showArchived ? (
|
{!showArchived ? (
|
||||||
<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>创建考试</Button>
|
<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
|
||||||
|
创建考试
|
||||||
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
</Space>
|
</Space>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{data.length === 0 && !loading ? (
|
{data.length === 0 && !loading ? (
|
||||||
<div className="exam-empty"><Empty description="暂无考试" /></div>
|
<div className="exam-empty">
|
||||||
|
<Empty description="暂无考试" />
|
||||||
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<Row gutter={[16, 16]}>
|
<Row gutter={[16, 16]}>
|
||||||
{data.map((exam) => {
|
{data.map((exam) => {
|
||||||
const percent = exam.totalStudents === 0 ? 0 : Math.round((exam.enteredScores / exam.totalStudents) * 100);
|
const percent =
|
||||||
|
exam.totalStudents === 0
|
||||||
|
? 0
|
||||||
|
: Math.round((exam.enteredScores / exam.totalStudents) * 100);
|
||||||
return (
|
return (
|
||||||
<Col key={exam.id} xs={24} sm={12} xl={8} xxl={6}>
|
<Col key={exam.id} xs={24} sm={12} xl={8} xxl={6}>
|
||||||
<Card
|
<Card
|
||||||
className={`exam-card${selectedExamIds.includes(exam.id) ? ' exam-card-selected' : ''}`}
|
className={`exam-card${selectedExamIds.includes(exam.id) ? ' exam-card-selected' : ''}`}
|
||||||
loading={loading}
|
loading={loading}
|
||||||
title={(
|
title={
|
||||||
<Space>
|
<Space>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
aria-label={`选择考试 ${exam.examName}`}
|
aria-label={`选择考试 ${exam.examName}`}
|
||||||
@@ -208,18 +374,38 @@ const ExamsPage: React.FC = () => {
|
|||||||
<Tag color="blue">{exam.examType}</Tag>
|
<Tag color="blue">{exam.examType}</Tag>
|
||||||
<span>{exam.examName}</span>
|
<span>{exam.examName}</span>
|
||||||
</Space>
|
</Space>
|
||||||
)}
|
}
|
||||||
extra={<Tag color={exam.status === 'archived' ? 'default' : 'green'}>{exam.status === 'archived' ? '已归档' : '成绩录入'}</Tag>}
|
extra={
|
||||||
|
<Tag color={exam.status === 'archived' ? 'default' : 'green'}>
|
||||||
|
{exam.status === 'archived' ? '已归档' : '成绩录入'}
|
||||||
|
</Tag>
|
||||||
|
}
|
||||||
actions={[
|
actions={[
|
||||||
<span key="detail" onClick={() => navigate(`/exams/${exam.id}`)}>查看成绩</span>,
|
<span key="detail" onClick={() => navigate(`/exams/${exam.id}`)}>
|
||||||
|
查看成绩
|
||||||
|
</span>,
|
||||||
exam.status === 'archived' ? (
|
exam.status === 'archived' ? (
|
||||||
<Popconfirm
|
<>
|
||||||
key="restore"
|
<Popconfirm
|
||||||
title="确认恢复该考试?"
|
key="restore"
|
||||||
onConfirm={() => changeArchiveStatus(exam, false)}
|
title="确认恢复该考试?"
|
||||||
>
|
onConfirm={() => changeArchiveStatus(exam, false)}
|
||||||
<span>恢复</span>
|
>
|
||||||
</Popconfirm>
|
<span>恢复</span>
|
||||||
|
</Popconfirm>
|
||||||
|
{canPurgeExam ? (
|
||||||
|
<Popconfirm
|
||||||
|
key="purge"
|
||||||
|
title="确认永久删除该考试?"
|
||||||
|
description="删除后不可恢复,成绩记录将一并清除。"
|
||||||
|
onConfirm={() => handlePurge(exam)}
|
||||||
|
okText="永久删除"
|
||||||
|
okButtonProps={{ danger: true }}
|
||||||
|
>
|
||||||
|
<span className="exam-purge-action">删除</span>
|
||||||
|
</Popconfirm>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
) : (
|
) : (
|
||||||
<Popconfirm
|
<Popconfirm
|
||||||
key="archive"
|
key="archive"
|
||||||
@@ -232,10 +418,31 @@ const ExamsPage: React.FC = () => {
|
|||||||
),
|
),
|
||||||
]}
|
]}
|
||||||
>
|
>
|
||||||
<div className="exam-meta"><span>科目</span><strong>{exam.subject}</strong></div>
|
<div className="exam-meta">
|
||||||
<div className="exam-meta"><span><TeamOutlined /> 班级</span><strong>{exam.className}</strong></div>
|
<span>科目</span>
|
||||||
<div className="exam-meta"><span><CalendarOutlined /> 日期</span><strong>{exam.examDate}</strong></div>
|
<strong>{exam.subject}</strong>
|
||||||
<div className="exam-progress"><div><span>成绩录入</span><strong>{exam.enteredScores}/{exam.totalStudents}</strong></div><Progress percent={percent} size="small" /></div>
|
</div>
|
||||||
|
<div className="exam-meta">
|
||||||
|
<span>
|
||||||
|
<TeamOutlined /> 班级
|
||||||
|
</span>
|
||||||
|
<strong>{exam.className}</strong>
|
||||||
|
</div>
|
||||||
|
<div className="exam-meta">
|
||||||
|
<span>
|
||||||
|
<CalendarOutlined /> 日期
|
||||||
|
</span>
|
||||||
|
<strong>{exam.examDate}</strong>
|
||||||
|
</div>
|
||||||
|
<div className="exam-progress">
|
||||||
|
<div>
|
||||||
|
<span>成绩录入</span>
|
||||||
|
<strong>
|
||||||
|
{exam.enteredScores}/{exam.totalStudents}
|
||||||
|
</strong>
|
||||||
|
</div>
|
||||||
|
<Progress percent={percent} size="small" />
|
||||||
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
</Col>
|
</Col>
|
||||||
);
|
);
|
||||||
@@ -243,7 +450,15 @@ const ExamsPage: React.FC = () => {
|
|||||||
</Row>
|
</Row>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<ExamFormModal open={modalOpen} editing={false} saving={saving} form={form} classes={classes} onCancel={() => setModalOpen(false)} onSubmit={() => void submit()} />
|
<ExamFormModal
|
||||||
|
open={modalOpen}
|
||||||
|
editing={false}
|
||||||
|
saving={saving}
|
||||||
|
form={form}
|
||||||
|
classes={classes}
|
||||||
|
onCancel={() => setModalOpen(false)}
|
||||||
|
onSubmit={() => void submit()}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -80,6 +80,10 @@
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.exam-purge-action {
|
||||||
|
color: #ff4d4f;
|
||||||
|
}
|
||||||
|
|
||||||
@media (max-width: 575px) {
|
@media (max-width: 575px) {
|
||||||
.exam-toolbar > .ant-space,
|
.exam-toolbar > .ant-space,
|
||||||
.exam-toolbar .ant-input-affix-wrapper,
|
.exam-toolbar .ant-input-affix-wrapper,
|
||||||
|
|||||||
166
apps/admin/src/pages/Expenses/ExpenseModals.tsx
Normal file
166
apps/admin/src/pages/Expenses/ExpenseModals.tsx
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
// aislop-ignore-file: duplicate-block -- 表格/表单声明结构相似且参数不同,渲染逻辑已共享组件化
|
||||||
|
import React from 'react';
|
||||||
|
import {
|
||||||
|
DatePicker,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
InputNumber,
|
||||||
|
Modal,
|
||||||
|
Select,
|
||||||
|
} from 'antd';
|
||||||
|
|
||||||
|
const { RangePicker } = DatePicker;
|
||||||
|
|
||||||
|
export const RoomExpenseModal: React.FC<{
|
||||||
|
open: boolean;
|
||||||
|
editing: boolean;
|
||||||
|
saving: boolean;
|
||||||
|
form: ReturnType<typeof Form.useForm>[0];
|
||||||
|
rooms: any[];
|
||||||
|
typeOptions: Array<{ value: string; label: string }>;
|
||||||
|
onOk: () => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
}> = ({ open, editing, saving, form, rooms, typeOptions, onOk, onCancel }) => {
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
title={editing ? '编辑宿舍费用' : '录入宿舍费用'}
|
||||||
|
open={open}
|
||||||
|
onOk={onOk}
|
||||||
|
onCancel={onCancel}
|
||||||
|
okText={editing ? '保存' : '确认录入'}
|
||||||
|
confirmLoading={saving}
|
||||||
|
>
|
||||||
|
<Form form={form} layout="vertical">
|
||||||
|
<Form.Item name="roomId" label="宿舍" rules={[{ required: true }]}>
|
||||||
|
<Select
|
||||||
|
showSearch
|
||||||
|
optionFilterProp="label"
|
||||||
|
options={rooms.map((r: any) => ({
|
||||||
|
value: r.id,
|
||||||
|
label: `${r.roomNumber} (${r.building || ''})`,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="expenseType" label="费用类型" rules={[{ required: true }]}>
|
||||||
|
<Select options={typeOptions} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="amount" label="金额(元)" rules={[{ required: true }]}>
|
||||||
|
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="period" label="账单周期" rules={[{ required: true }]}>
|
||||||
|
<RangePicker
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
placeholder={['开始日期', '结束日期']}
|
||||||
|
format="YYYY-MM-DD"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="description" label="说明">
|
||||||
|
<Input.TextArea rows={2} />
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const UtilityModal: React.FC<{
|
||||||
|
open: boolean;
|
||||||
|
saving: boolean;
|
||||||
|
form: ReturnType<typeof Form.useForm>[0];
|
||||||
|
students: any[];
|
||||||
|
onOk: () => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
}> = ({ open, saving, form, students, onOk, onCancel }) => {
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
title="添加学生水电费并立即出账"
|
||||||
|
open={open}
|
||||||
|
onOk={onOk}
|
||||||
|
onCancel={onCancel}
|
||||||
|
okText="生成账单并扣余额"
|
||||||
|
confirmLoading={saving}
|
||||||
|
>
|
||||||
|
<Form form={form} layout="vertical">
|
||||||
|
<Form.Item name="studentId" label="学生" rules={[{ required: true }]}>
|
||||||
|
<Select
|
||||||
|
showSearch
|
||||||
|
optionFilterProp="label"
|
||||||
|
options={students.map((student: any) => ({
|
||||||
|
value: student.id,
|
||||||
|
label: `${student.name} (${student.studentNo || `#${student.id}`})`,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="expenseType" label="费用类型" rules={[{ required: true }]}>
|
||||||
|
<Select
|
||||||
|
options={[
|
||||||
|
{ value: 'water', label: '水费' },
|
||||||
|
{ value: 'electricity', label: '电费' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="amount" label="金额(元)" rules={[{ required: true }]}>
|
||||||
|
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="period" label="账单周期" rules={[{ required: true }]}>
|
||||||
|
<RangePicker style={{ width: '100%' }} format="YYYY-MM-DD" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="description" label="说明">
|
||||||
|
<Input.TextArea rows={2} maxLength={300} />
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const PersonalExpenseModal: React.FC<{
|
||||||
|
open: boolean;
|
||||||
|
editing: boolean;
|
||||||
|
saving: boolean;
|
||||||
|
form: ReturnType<typeof Form.useForm>[0];
|
||||||
|
students: any[];
|
||||||
|
rooms: any[];
|
||||||
|
personalTypeOptions: Array<{ value: string; label: string }>;
|
||||||
|
onOk: () => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
}> = ({ open, editing, saving, form, students, rooms, personalTypeOptions, onOk, onCancel }) => {
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
title={editing ? '编辑个人费用' : '录入个人附加费'}
|
||||||
|
open={open}
|
||||||
|
onOk={onOk}
|
||||||
|
onCancel={onCancel}
|
||||||
|
okText={editing ? '保存' : '确认录入'}
|
||||||
|
confirmLoading={saving}
|
||||||
|
>
|
||||||
|
<Form form={form} layout="vertical">
|
||||||
|
<Form.Item name="studentId" label="学生" rules={[{ required: true }]}>
|
||||||
|
<Select
|
||||||
|
showSearch
|
||||||
|
optionFilterProp="label"
|
||||||
|
options={students.map((s: any) => ({ value: s.id, label: s.name }))}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="roomId" label="关联宿舍">
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
showSearch
|
||||||
|
optionFilterProp="label"
|
||||||
|
options={rooms.map((r: any) => ({ value: r.id, label: r.roomNumber }))}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="expenseType" label="费用类型" rules={[{ required: true }]}>
|
||||||
|
<Select options={personalTypeOptions} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="amount" label="金额(元)" rules={[{ required: true }]}>
|
||||||
|
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="expenseDate" label="费用日期" rules={[{ required: true }]}>
|
||||||
|
<DatePicker style={{ width: '100%' }} placeholder="选择日期" format="YYYY-MM-DD" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="description" label="说明">
|
||||||
|
<Input.TextArea rows={2} />
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
};
|
||||||
524
apps/admin/src/pages/Expenses/ExpenseTablePanel.tsx
Normal file
524
apps/admin/src/pages/Expenses/ExpenseTablePanel.tsx
Normal file
@@ -0,0 +1,524 @@
|
|||||||
|
// aislop-ignore-file: duplicate-block -- 表格/表单声明结构相似且参数不同,渲染逻辑已共享组件化
|
||||||
|
import React from 'react';
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Empty,
|
||||||
|
Input,
|
||||||
|
Popconfirm,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Table,
|
||||||
|
Tag,
|
||||||
|
Upload,
|
||||||
|
} from 'antd';
|
||||||
|
import {
|
||||||
|
DeleteOutlined,
|
||||||
|
DownloadOutlined,
|
||||||
|
EditOutlined,
|
||||||
|
ExportOutlined,
|
||||||
|
InboxOutlined,
|
||||||
|
UndoOutlined,
|
||||||
|
UploadOutlined,
|
||||||
|
ThunderboltOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
import PermissionButton from '../../components/PermissionButton';
|
||||||
|
import EditableCell from '../../components/EditableCell';
|
||||||
|
import { message } from '../../ui/app-message';
|
||||||
|
|
||||||
|
export const EXPENSE_FIELDS = {
|
||||||
|
roomId: 'roomId',
|
||||||
|
expenseType: 'expenseType',
|
||||||
|
amount: 'amount',
|
||||||
|
description: 'description',
|
||||||
|
studentId: 'studentId',
|
||||||
|
expenseDate: 'expenseDate',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export interface ExpenseTablePanelProps {
|
||||||
|
kind: 'room' | 'personal';
|
||||||
|
searchText: string;
|
||||||
|
onSearchChange: (value: string) => void;
|
||||||
|
typeFilter: string | undefined;
|
||||||
|
onTypeFilterChange: (value?: string) => void;
|
||||||
|
typeOptions: Array<{ value: string; label: string }>;
|
||||||
|
typeMap: Record<string, string>;
|
||||||
|
data: any[];
|
||||||
|
loading: boolean;
|
||||||
|
selectedKeys: number[];
|
||||||
|
onSelect: (keys: number[]) => void;
|
||||||
|
rooms: any[];
|
||||||
|
students: any[];
|
||||||
|
readonly: boolean;
|
||||||
|
showArchived: boolean;
|
||||||
|
canPurgeExpense: boolean;
|
||||||
|
batchLoading: boolean;
|
||||||
|
canImport: boolean;
|
||||||
|
onBatchRestore: () => void;
|
||||||
|
onBatchPurge: () => void;
|
||||||
|
onBatchDelete: () => void;
|
||||||
|
onSaveCell: (record: any, field: string, value: unknown) => Promise<void> | void;
|
||||||
|
onPeriodSave: (id: number, periodStart: string, periodEnd: string) => Promise<void> | void;
|
||||||
|
onEdit: (record: any) => void;
|
||||||
|
onArchive: (id: number) => Promise<unknown> | unknown;
|
||||||
|
onPurge: (id: number) => void;
|
||||||
|
onImport: (formData: FormData) => Promise<any>;
|
||||||
|
onTemplateDownload: () => void;
|
||||||
|
onExport?: () => void;
|
||||||
|
onAddUtility?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ExpenseTablePanel: React.FC<ExpenseTablePanelProps> = ({
|
||||||
|
kind,
|
||||||
|
searchText,
|
||||||
|
onSearchChange,
|
||||||
|
typeFilter,
|
||||||
|
onTypeFilterChange,
|
||||||
|
typeOptions,
|
||||||
|
typeMap,
|
||||||
|
data,
|
||||||
|
loading,
|
||||||
|
selectedKeys,
|
||||||
|
onSelect,
|
||||||
|
rooms,
|
||||||
|
students,
|
||||||
|
readonly,
|
||||||
|
showArchived,
|
||||||
|
canPurgeExpense,
|
||||||
|
batchLoading,
|
||||||
|
canImport,
|
||||||
|
onBatchRestore,
|
||||||
|
onBatchPurge,
|
||||||
|
onBatchDelete,
|
||||||
|
onSaveCell,
|
||||||
|
onPeriodSave,
|
||||||
|
onEdit,
|
||||||
|
onArchive,
|
||||||
|
onPurge,
|
||||||
|
onImport,
|
||||||
|
onTemplateDownload,
|
||||||
|
onExport,
|
||||||
|
onAddUtility,
|
||||||
|
}) => {
|
||||||
|
const isRoom = kind === 'room';
|
||||||
|
const noun = isRoom ? '费用' : '个人费用';
|
||||||
|
|
||||||
|
const EditableExpenseCell = ({
|
||||||
|
value,
|
||||||
|
editor,
|
||||||
|
min,
|
||||||
|
max,
|
||||||
|
required,
|
||||||
|
options,
|
||||||
|
onSave,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
value: unknown;
|
||||||
|
editor?: React.ComponentProps<typeof EditableCell>['editor'];
|
||||||
|
min?: number;
|
||||||
|
max?: number;
|
||||||
|
required?: boolean;
|
||||||
|
options?: Array<{ value: string | number; label: string }>;
|
||||||
|
onSave: (value: unknown) => Promise<void> | void;
|
||||||
|
children?: React.ReactNode;
|
||||||
|
}) => (
|
||||||
|
<EditableCell
|
||||||
|
value={value}
|
||||||
|
editor={editor}
|
||||||
|
min={min}
|
||||||
|
max={max}
|
||||||
|
required={required}
|
||||||
|
options={options}
|
||||||
|
permission="expense:edit"
|
||||||
|
disabled={readonly}
|
||||||
|
onSave={async (next) => {
|
||||||
|
await onSave(next);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children ?? String(value ?? '-')}
|
||||||
|
</EditableCell>
|
||||||
|
);
|
||||||
|
|
||||||
|
const renderExpenseActions = (record: any) => {
|
||||||
|
if (showArchived) {
|
||||||
|
return (
|
||||||
|
<Space>
|
||||||
|
<Tag color="#999">已归档</Tag>
|
||||||
|
{canPurgeExpense ? (
|
||||||
|
<Button size="small" danger type="link" onClick={() => onPurge(record.id)}>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<Space>
|
||||||
|
<PermissionButton
|
||||||
|
permission="expense:edit"
|
||||||
|
size="small"
|
||||||
|
icon={<EditOutlined />}
|
||||||
|
onClick={() => onEdit(record)}
|
||||||
|
>
|
||||||
|
编辑
|
||||||
|
</PermissionButton>
|
||||||
|
<Popconfirm
|
||||||
|
title="确定归档?"
|
||||||
|
onConfirm={async () => {
|
||||||
|
try {
|
||||||
|
await onArchive(record.id);
|
||||||
|
message.success('归档成功');
|
||||||
|
} catch {
|
||||||
|
// 错误提示由 useApiMutation 统一处理
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<PermissionButton permission="expense:delete" size="small" danger icon={<InboxOutlined />}>
|
||||||
|
归档
|
||||||
|
</PermissionButton>
|
||||||
|
</Popconfirm>
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const columns = isRoom
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
title: '宿舍',
|
||||||
|
width: 120,
|
||||||
|
render: (_: any, r: any) => (
|
||||||
|
<EditableExpenseCell
|
||||||
|
value={r.roomId}
|
||||||
|
editor="select"
|
||||||
|
options={rooms.map((item) => ({ value: item.id, label: item.roomNumber }))}
|
||||||
|
required
|
||||||
|
onSave={(next) => onSaveCell(r, EXPENSE_FIELDS.roomId, next)}
|
||||||
|
>
|
||||||
|
{r.room?.roomNumber || '-'}
|
||||||
|
</EditableExpenseCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '费用类型',
|
||||||
|
width: 100,
|
||||||
|
dataIndex: 'expenseType',
|
||||||
|
render: (v: string, r: any) => (
|
||||||
|
<EditableExpenseCell
|
||||||
|
value={v}
|
||||||
|
editor="select"
|
||||||
|
options={typeOptions}
|
||||||
|
required
|
||||||
|
onSave={(next) => onSaveCell(r, EXPENSE_FIELDS.expenseType, next)}
|
||||||
|
>
|
||||||
|
<Tag>{typeMap[v] || v}</Tag>
|
||||||
|
</EditableExpenseCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '金额',
|
||||||
|
dataIndex: 'amount',
|
||||||
|
width: 100,
|
||||||
|
render: (v: number, r: any) => (
|
||||||
|
<EditableExpenseCell
|
||||||
|
value={v}
|
||||||
|
editor="money"
|
||||||
|
min={0.01}
|
||||||
|
required
|
||||||
|
onSave={(next) => onSaveCell(r, EXPENSE_FIELDS.amount, next)}
|
||||||
|
>
|
||||||
|
{`¥${v.toFixed(2)}`}
|
||||||
|
</EditableExpenseCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '账单周期',
|
||||||
|
width: 200,
|
||||||
|
render: (_: any, r: any) => (
|
||||||
|
<EditableCell
|
||||||
|
value={[r.periodStart, r.periodEnd]}
|
||||||
|
editor="date-range"
|
||||||
|
permission="expense:edit"
|
||||||
|
disabled={readonly}
|
||||||
|
required
|
||||||
|
onSave={async (next) => {
|
||||||
|
const [periodStart, periodEnd] = next as [string, string];
|
||||||
|
await onPeriodSave(r.id, periodStart, periodEnd);
|
||||||
|
}}
|
||||||
|
>{`${r.periodStart} ~ ${r.periodEnd}`}</EditableCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '说明',
|
||||||
|
dataIndex: 'description',
|
||||||
|
width: 150,
|
||||||
|
render: (v: string, r: any) => (
|
||||||
|
<EditableExpenseCell
|
||||||
|
value={v}
|
||||||
|
editor="textarea"
|
||||||
|
onSave={(next) => onSaveCell(r, EXPENSE_FIELDS.description, next)}
|
||||||
|
>
|
||||||
|
{v || '-'}
|
||||||
|
</EditableExpenseCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '录入时间',
|
||||||
|
width: 160,
|
||||||
|
dataIndex: 'createdAt',
|
||||||
|
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
width: 120,
|
||||||
|
render: (_: any, record: any) => renderExpenseActions(record),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [
|
||||||
|
{
|
||||||
|
title: '学生',
|
||||||
|
width: 120,
|
||||||
|
render: (_: any, r: any) => (
|
||||||
|
<EditableExpenseCell
|
||||||
|
value={r.studentId}
|
||||||
|
editor="select"
|
||||||
|
options={students.map((item) => ({ value: item.id, label: item.name }))}
|
||||||
|
required
|
||||||
|
onSave={(next) => onSaveCell(r, EXPENSE_FIELDS.studentId, next)}
|
||||||
|
>
|
||||||
|
{r.student?.name || '-'}
|
||||||
|
</EditableExpenseCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '费用类型',
|
||||||
|
width: 100,
|
||||||
|
dataIndex: 'expenseType',
|
||||||
|
render: (v: string, r: any) => (
|
||||||
|
<EditableExpenseCell
|
||||||
|
value={v}
|
||||||
|
editor="select"
|
||||||
|
options={typeOptions}
|
||||||
|
required
|
||||||
|
onSave={(next) => onSaveCell(r, EXPENSE_FIELDS.expenseType, next)}
|
||||||
|
>
|
||||||
|
<Tag color="orange">{typeMap[v] || v}</Tag>
|
||||||
|
</EditableExpenseCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '金额',
|
||||||
|
dataIndex: 'amount',
|
||||||
|
render: (v: number, r: any) => (
|
||||||
|
<EditableExpenseCell
|
||||||
|
value={v}
|
||||||
|
editor="money"
|
||||||
|
min={0.01}
|
||||||
|
required
|
||||||
|
onSave={(next) => onSaveCell(r, EXPENSE_FIELDS.amount, next)}
|
||||||
|
>
|
||||||
|
{`¥${v.toFixed(2)}`}
|
||||||
|
</EditableExpenseCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '日期',
|
||||||
|
dataIndex: 'expenseDate',
|
||||||
|
width: 110,
|
||||||
|
render: (v: string, r: any) => (
|
||||||
|
<EditableExpenseCell
|
||||||
|
value={v}
|
||||||
|
editor="date"
|
||||||
|
required
|
||||||
|
onSave={(next) => onSaveCell(r, EXPENSE_FIELDS.expenseDate, next)}
|
||||||
|
>
|
||||||
|
{v}
|
||||||
|
</EditableExpenseCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '说明',
|
||||||
|
dataIndex: 'description',
|
||||||
|
width: 150,
|
||||||
|
render: (v: string, r: any) => (
|
||||||
|
<EditableExpenseCell
|
||||||
|
value={v}
|
||||||
|
editor="textarea"
|
||||||
|
onSave={(next) => onSaveCell(r, EXPENSE_FIELDS.description, next)}
|
||||||
|
>
|
||||||
|
{v || '-'}
|
||||||
|
</EditableExpenseCell>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
width: 120,
|
||||||
|
render: (_: any, record: any) => renderExpenseActions(record),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
marginBottom: 16,
|
||||||
|
display: 'flex',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
flexWrap: 'wrap',
|
||||||
|
gap: 8,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Space wrap>
|
||||||
|
<Input.Search
|
||||||
|
placeholder={isRoom ? '搜索宿舍号' : '搜索学生姓名'}
|
||||||
|
allowClear
|
||||||
|
style={{ width: 160 }}
|
||||||
|
value={searchText}
|
||||||
|
onSearch={(v) => onSearchChange(v)}
|
||||||
|
onChange={(e) => {
|
||||||
|
if (!e.target.value) onSearchChange('');
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
placeholder="费用类型"
|
||||||
|
allowClear
|
||||||
|
style={{ width: 120 }}
|
||||||
|
value={typeFilter}
|
||||||
|
onChange={onTypeFilterChange}
|
||||||
|
options={typeOptions}
|
||||||
|
/>
|
||||||
|
{canImport && !showArchived && (
|
||||||
|
<Upload
|
||||||
|
accept=".xlsx,.xls"
|
||||||
|
showUploadList={false}
|
||||||
|
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||||
|
try {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', file);
|
||||||
|
const res: any = await onImport(formData);
|
||||||
|
if (isRoom && res.errors?.length > 0) {
|
||||||
|
message.warning(res.message || '导入完成');
|
||||||
|
res.errors.forEach((e: string) => message.warning(e));
|
||||||
|
} else {
|
||||||
|
message.success(res.message || '导入完成');
|
||||||
|
if (res.errors?.length) res.errors.forEach((e: string) => message.warning(e));
|
||||||
|
}
|
||||||
|
onSuccess?.(res);
|
||||||
|
} catch (e) {
|
||||||
|
onError?.(e as Error);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Button icon={<UploadOutlined />}>
|
||||||
|
{isRoom ? '导入水电费Excel' : '导入个人附加费'}
|
||||||
|
</Button>
|
||||||
|
</Upload>
|
||||||
|
)}
|
||||||
|
{!showArchived && (
|
||||||
|
<PermissionButton
|
||||||
|
permission="expense:view"
|
||||||
|
icon={<DownloadOutlined />}
|
||||||
|
onClick={onTemplateDownload}
|
||||||
|
>
|
||||||
|
{isRoom ? '下载水电费模板' : '下载模板'}
|
||||||
|
</PermissionButton>
|
||||||
|
)}
|
||||||
|
{onExport && !showArchived ? (
|
||||||
|
<PermissionButton
|
||||||
|
permission="expense:view"
|
||||||
|
icon={<ExportOutlined />}
|
||||||
|
onClick={onExport}
|
||||||
|
>
|
||||||
|
导出
|
||||||
|
</PermissionButton>
|
||||||
|
) : null}
|
||||||
|
{isRoom && onAddUtility && !showArchived ? (
|
||||||
|
<PermissionButton
|
||||||
|
permission="expense:create"
|
||||||
|
icon={<ThunderboltOutlined />}
|
||||||
|
onClick={onAddUtility}
|
||||||
|
>
|
||||||
|
添加学生水电费
|
||||||
|
</PermissionButton>
|
||||||
|
) : null}
|
||||||
|
</Space>
|
||||||
|
<Space>
|
||||||
|
{showArchived ? (
|
||||||
|
<>
|
||||||
|
<Popconfirm
|
||||||
|
title={`确定恢复选中的 ${selectedKeys.length} 条${noun}?`}
|
||||||
|
onConfirm={onBatchRestore}
|
||||||
|
okText="恢复"
|
||||||
|
cancelText="取消"
|
||||||
|
disabled={selectedKeys.length === 0}
|
||||||
|
>
|
||||||
|
<PermissionButton
|
||||||
|
permission="expense:edit"
|
||||||
|
type="primary"
|
||||||
|
icon={<UndoOutlined />}
|
||||||
|
loading={batchLoading}
|
||||||
|
disabled={selectedKeys.length === 0}
|
||||||
|
>
|
||||||
|
批量恢复
|
||||||
|
</PermissionButton>
|
||||||
|
</Popconfirm>
|
||||||
|
{canPurgeExpense ? (
|
||||||
|
<Popconfirm
|
||||||
|
title={`确定永久删除选中的 ${selectedKeys.length} 条${noun}?删除后不可恢复!`}
|
||||||
|
onConfirm={onBatchPurge}
|
||||||
|
okText="永久删除"
|
||||||
|
okButtonProps={{ danger: true }}
|
||||||
|
cancelText="取消"
|
||||||
|
disabled={selectedKeys.length === 0}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
danger
|
||||||
|
icon={<DeleteOutlined />}
|
||||||
|
loading={batchLoading}
|
||||||
|
disabled={selectedKeys.length === 0}
|
||||||
|
>
|
||||||
|
批量删除
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<Popconfirm
|
||||||
|
title={`确定归档选中的 ${selectedKeys.length} 条${noun}?`}
|
||||||
|
onConfirm={onBatchDelete}
|
||||||
|
okText="归档"
|
||||||
|
cancelText="取消"
|
||||||
|
disabled={selectedKeys.length === 0}
|
||||||
|
>
|
||||||
|
<PermissionButton
|
||||||
|
permission="expense:delete"
|
||||||
|
danger
|
||||||
|
icon={<InboxOutlined />}
|
||||||
|
disabled={selectedKeys.length === 0}
|
||||||
|
>
|
||||||
|
批量归档
|
||||||
|
</PermissionButton>
|
||||||
|
</Popconfirm>
|
||||||
|
)}
|
||||||
|
</Space>
|
||||||
|
</div>
|
||||||
|
<Table
|
||||||
|
columns={columns}
|
||||||
|
dataSource={data}
|
||||||
|
rowKey="id"
|
||||||
|
loading={loading}
|
||||||
|
scroll={{ x: 1200 }}
|
||||||
|
pagination={{
|
||||||
|
defaultPageSize: 15,
|
||||||
|
showSizeChanger: true,
|
||||||
|
pageSizeOptions: [15, 30, 50, 100],
|
||||||
|
showTotal: (total) => `共 ${total} 条`,
|
||||||
|
}}
|
||||||
|
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
||||||
|
rowSelection={{
|
||||||
|
selectedRowKeys: selectedKeys,
|
||||||
|
onChange: (keys) => onSelect(keys as number[]),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,503 @@
|
|||||||
|
import React, { useState, useCallback, useMemo } from 'react';
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Col,
|
||||||
|
DatePicker,
|
||||||
|
Drawer,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
List,
|
||||||
|
Modal,
|
||||||
|
Row,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Tag,
|
||||||
|
Tree,
|
||||||
|
TreeSelect,
|
||||||
|
} from 'antd';
|
||||||
|
import type { DataNode } from 'antd/es/tree';
|
||||||
|
import type { TreeSelectProps } from 'antd/es/tree-select';
|
||||||
|
import {
|
||||||
|
BankOutlined,
|
||||||
|
StopOutlined,
|
||||||
|
SyncOutlined,
|
||||||
|
UserOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
|
import api from '../../api';
|
||||||
|
import { message } from '../../ui/app-message';
|
||||||
|
import PermissionButton from '../../components/PermissionButton';
|
||||||
|
import { getErrorMessage } from '../../utils/error';
|
||||||
|
|
||||||
|
interface DingOrgTreeNodeExt {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
parentId: number;
|
||||||
|
children: DingOrgTreeNodeExt[];
|
||||||
|
users: Array<{ userid: string; name: string; mobile: string; deptIds: number[] }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OrgTreeNodeRaw {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
children?: OrgTreeNodeRaw[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OrgTreeResponse {
|
||||||
|
success: boolean;
|
||||||
|
data: OrgTreeNodeRaw[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OrgTreeWithUsersResponse {
|
||||||
|
success: boolean;
|
||||||
|
data: DingOrgTreeNodeExt[];
|
||||||
|
}
|
||||||
|
|
||||||
|
type DeptPickerTreeNode = NonNullable<TreeSelectProps<number>['treeData']>[number];
|
||||||
|
|
||||||
|
interface ClassItem {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
code: string;
|
||||||
|
classType?: string;
|
||||||
|
startDate?: string;
|
||||||
|
endDate?: string;
|
||||||
|
notes?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ImportResult {
|
||||||
|
imported: number;
|
||||||
|
skipped: number;
|
||||||
|
conflicts: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DingTalkAttendanceGroup {
|
||||||
|
group_id: number;
|
||||||
|
group_name: string;
|
||||||
|
type: string;
|
||||||
|
member_count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AttendanceGroupResponse {
|
||||||
|
success: boolean;
|
||||||
|
data: DingTalkAttendanceGroup[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DeleteAttendanceGroupsResponse {
|
||||||
|
success: boolean;
|
||||||
|
data: {
|
||||||
|
total: number;
|
||||||
|
deleted: Array<{ groupId: number; groupName: string }>;
|
||||||
|
failed: Array<{ groupId: number; groupName: string; error: string }>;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IntegrationOrgSyncPanelProps {
|
||||||
|
canCreateClass: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const IntegrationOrgSyncPanel: React.FC<IntegrationOrgSyncPanelProps> = ({
|
||||||
|
canCreateClass,
|
||||||
|
}) => {
|
||||||
|
const [syncRootDeptId, setSyncRootDeptId] = useState<number | undefined>(undefined);
|
||||||
|
const [orgTree, setOrgTree] = useState<DingOrgTreeNodeExt[]>([]);
|
||||||
|
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||||
|
const [fetchingTree, setFetchingTree] = useState(false);
|
||||||
|
const [importing, setImporting] = useState(false);
|
||||||
|
const [deptPickerTree, setDeptPickerTree] = useState<DeptPickerTreeNode[]>([]);
|
||||||
|
const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
|
||||||
|
const [selectedClassId, setSelectedClassId] = useState<number | null>(null);
|
||||||
|
const [classes, setClasses] = useState<ClassItem[]>([]);
|
||||||
|
const [classForm] = Form.useForm();
|
||||||
|
const [classModalOpen, setClassModalOpen] = useState(false);
|
||||||
|
const [attendanceGroups, setAttendanceGroups] = useState<DingTalkAttendanceGroup[]>([]);
|
||||||
|
const [deleteGroupsOpen, setDeleteGroupsOpen] = useState(false);
|
||||||
|
const [loadingGroups, setLoadingGroups] = useState(false);
|
||||||
|
const [deletingGroups, setDeletingGroups] = useState(false);
|
||||||
|
|
||||||
|
const loadDeptTree = async () => {
|
||||||
|
try {
|
||||||
|
const res = await api.get<OrgTreeResponse>('/sync/dingtalk/org-tree');
|
||||||
|
if (res.success && res.data) {
|
||||||
|
const toTreeNode = (nodes: OrgTreeNodeRaw[]): DeptPickerTreeNode[] =>
|
||||||
|
nodes.map((n) => ({
|
||||||
|
title: n.name,
|
||||||
|
value: n.id,
|
||||||
|
children: n.children ? toTreeNode(n.children) : undefined,
|
||||||
|
}));
|
||||||
|
setDeptPickerTree(toTreeNode(res.data));
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('获取部门架构失败', e);
|
||||||
|
message.error('获取部门架构失败');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchClasses = async () => {
|
||||||
|
try {
|
||||||
|
const res = await api.get<ClassItem[] | { data: ClassItem[] }>('/classes');
|
||||||
|
if (Array.isArray(res)) {
|
||||||
|
setClasses(res);
|
||||||
|
} else {
|
||||||
|
setClasses(res.data ?? []);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFetchOrgTree = async () => {
|
||||||
|
setFetchingTree(true);
|
||||||
|
try {
|
||||||
|
const params: Record<string, string> = {};
|
||||||
|
if (syncRootDeptId) params.rootDeptId = String(syncRootDeptId);
|
||||||
|
const res = await api.get<OrgTreeWithUsersResponse>('/sync/dingtalk/org-tree-with-users', {
|
||||||
|
params,
|
||||||
|
});
|
||||||
|
if (res.success && res.data) {
|
||||||
|
setOrgTree(res.data);
|
||||||
|
setCheckedKeys([]);
|
||||||
|
setSelectedClassId(null);
|
||||||
|
setDrawerOpen(true);
|
||||||
|
fetchClasses();
|
||||||
|
} else {
|
||||||
|
message.error('获取组织架构失败');
|
||||||
|
}
|
||||||
|
} catch (e: unknown) {
|
||||||
|
message.error(getErrorMessage(e, '获取组织架构失败'));
|
||||||
|
} finally {
|
||||||
|
setFetchingTree(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildTreeData = useCallback((nodes: DingOrgTreeNodeExt[]): DataNode[] => {
|
||||||
|
return nodes.map((node) => {
|
||||||
|
const users = node.users ?? [];
|
||||||
|
const children: DataNode[] = [
|
||||||
|
...buildTreeData(node.children ?? []),
|
||||||
|
...users.map((u) => ({
|
||||||
|
title: (
|
||||||
|
<Space>
|
||||||
|
<UserOutlined />
|
||||||
|
<span>{u.name}</span>
|
||||||
|
{u.mobile ? <Tag>{u.mobile}</Tag> : null}
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
key: `user-${u.userid}`,
|
||||||
|
isLeaf: true,
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
return {
|
||||||
|
title: (
|
||||||
|
<Space size="small">
|
||||||
|
<BankOutlined />
|
||||||
|
<span>{node.name}</span>
|
||||||
|
<Tag>{users.length}人</Tag>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
key: `dept-${node.id}`,
|
||||||
|
// Only attach children when there are any, so empty/leaf departments
|
||||||
|
// don't render a phantom expand arrow that opens to nothing.
|
||||||
|
...(children.length > 0 ? { children } : {}),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const treeData = useMemo(() => buildTreeData(orgTree), [orgTree, buildTreeData]);
|
||||||
|
|
||||||
|
const extractCheckedUsers = useCallback((): Array<{
|
||||||
|
dingUserId: string;
|
||||||
|
name: string;
|
||||||
|
mobile?: string;
|
||||||
|
}> => {
|
||||||
|
const result: Array<{ dingUserId: string; name: string; mobile?: string }> = [];
|
||||||
|
const walk = (nodes: DingOrgTreeNodeExt[]) => {
|
||||||
|
for (const node of nodes) {
|
||||||
|
for (const u of node.users ?? []) {
|
||||||
|
if (checkedKeys.includes(`user-${u.userid}`)) {
|
||||||
|
result.push({ dingUserId: u.userid, name: u.name, mobile: u.mobile || undefined });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(node.children ?? []);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(orgTree);
|
||||||
|
return result;
|
||||||
|
}, [checkedKeys, orgTree]);
|
||||||
|
|
||||||
|
const handleJoinClass = async () => {
|
||||||
|
if (selectedClassId === null) return message.warning('请先选择一个班级');
|
||||||
|
const users = extractCheckedUsers();
|
||||||
|
if (users.length === 0) return message.warning('请勾选要导入的用户');
|
||||||
|
|
||||||
|
setImporting(true);
|
||||||
|
try {
|
||||||
|
const res = await api.post<ImportResult>(`/classes/${selectedClassId}/students/import`, {
|
||||||
|
users,
|
||||||
|
});
|
||||||
|
if (res.conflicts > 0) {
|
||||||
|
message.warning(
|
||||||
|
`导入 ${res.imported} 人,跳过 ${res.skipped} 人,${res.conflicts} 人需人工绑定`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
message.success(`导入 ${res.imported} 人,跳过 ${res.skipped} 人`);
|
||||||
|
}
|
||||||
|
setCheckedKeys([]);
|
||||||
|
setSelectedClassId(null);
|
||||||
|
} catch (e: unknown) {
|
||||||
|
message.error(getErrorMessage(e, '导入失败'));
|
||||||
|
} finally {
|
||||||
|
setImporting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCreateClass = async () => {
|
||||||
|
try {
|
||||||
|
const values = await classForm.validateFields();
|
||||||
|
const users = extractCheckedUsers();
|
||||||
|
await api.post('/classes', { ...values, users });
|
||||||
|
message.success('班级创建成功');
|
||||||
|
setClassModalOpen(false);
|
||||||
|
classForm.resetFields();
|
||||||
|
setCheckedKeys([]);
|
||||||
|
fetchClasses();
|
||||||
|
} catch (e: unknown) {
|
||||||
|
message.error(getErrorMessage(e, '创建失败'));
|
||||||
|
} finally {
|
||||||
|
setImporting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openDeleteAllGroups = async () => {
|
||||||
|
setLoadingGroups(true);
|
||||||
|
try {
|
||||||
|
const response = await api.get<AttendanceGroupResponse>('/sync/dingtalk/attendance-groups');
|
||||||
|
setAttendanceGroups(response.data);
|
||||||
|
setDeleteGroupsOpen(true);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
message.error(error instanceof Error ? error.message : '获取钉钉考勤组失败');
|
||||||
|
} finally {
|
||||||
|
setLoadingGroups(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteAllGroups = async () => {
|
||||||
|
setDeletingGroups(true);
|
||||||
|
try {
|
||||||
|
const response = await api.post<DeleteAttendanceGroupsResponse>(
|
||||||
|
'/sync/dingtalk/attendance-groups/delete-all',
|
||||||
|
);
|
||||||
|
setDeleteGroupsOpen(false);
|
||||||
|
setAttendanceGroups([]);
|
||||||
|
if (response.data.failed.length > 0) {
|
||||||
|
message.warning(
|
||||||
|
`已清空 ${response.data.deleted.length} 个,失败 ${response.data.failed.length} 个`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
message.success(`已清空钉钉全部 ${response.data.deleted.length} 个考勤组`);
|
||||||
|
}
|
||||||
|
} catch (error: unknown) {
|
||||||
|
message.error(error instanceof Error ? error.message : '清空钉钉考勤组失败');
|
||||||
|
} finally {
|
||||||
|
setDeletingGroups(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
message="从钉钉获取组织架构,勾选用户后批量导入到班级。"
|
||||||
|
style={{ marginBottom: 16 }}
|
||||||
|
showIcon
|
||||||
|
/>
|
||||||
|
<Space>
|
||||||
|
<TreeSelect
|
||||||
|
treeData={deptPickerTree}
|
||||||
|
value={syncRootDeptId}
|
||||||
|
onChange={(v) => setSyncRootDeptId(v)}
|
||||||
|
placeholder="选择起始部门(不选=全部)"
|
||||||
|
allowClear
|
||||||
|
treeDefaultExpandAll
|
||||||
|
style={{ minWidth: 240 }}
|
||||||
|
onDropdownVisibleChange={(open) => {
|
||||||
|
if (open) loadDeptTree();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
icon={<SyncOutlined />}
|
||||||
|
loading={fetchingTree}
|
||||||
|
onClick={handleFetchOrgTree}
|
||||||
|
>
|
||||||
|
获取组织架构
|
||||||
|
</Button>
|
||||||
|
<PermissionButton
|
||||||
|
permission="sync:trigger"
|
||||||
|
danger
|
||||||
|
icon={<StopOutlined />}
|
||||||
|
loading={loadingGroups}
|
||||||
|
onClick={openDeleteAllGroups}
|
||||||
|
>
|
||||||
|
清空钉钉全部考勤组
|
||||||
|
</PermissionButton>
|
||||||
|
</Space>
|
||||||
|
|
||||||
|
{drawerOpen && (
|
||||||
|
<Drawer
|
||||||
|
title="钉钉组织架构 — 批量导入"
|
||||||
|
open={drawerOpen}
|
||||||
|
onClose={() => setDrawerOpen(false)}
|
||||||
|
size="min(900px, 100vw)"
|
||||||
|
footer={
|
||||||
|
<Space>
|
||||||
|
<Button onClick={() => setDrawerOpen(false)}>取消</Button>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
loading={importing}
|
||||||
|
disabled={
|
||||||
|
checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0 ||
|
||||||
|
selectedClassId === null
|
||||||
|
}
|
||||||
|
onClick={handleJoinClass}
|
||||||
|
>
|
||||||
|
加入选中的班级
|
||||||
|
</Button>
|
||||||
|
{canCreateClass ? (
|
||||||
|
<Button
|
||||||
|
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0}
|
||||||
|
onClick={() => setClassModalOpen(true)}
|
||||||
|
>
|
||||||
|
创建班级
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</Space>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Row gutter={[16, 16]}>
|
||||||
|
<Col xs={24} md={14}>
|
||||||
|
<div style={{ maxHeight: '60vh', overflow: 'auto' }}>
|
||||||
|
<Tree
|
||||||
|
checkable
|
||||||
|
treeData={treeData}
|
||||||
|
defaultExpandAll
|
||||||
|
showLine={{ showLeafIcon: false }}
|
||||||
|
checkedKeys={checkedKeys}
|
||||||
|
onCheck={(checked) => setCheckedKeys(checked as React.Key[])}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</Col>
|
||||||
|
<Col xs={24} md={10}>
|
||||||
|
<Card
|
||||||
|
title="班级列表"
|
||||||
|
size="small"
|
||||||
|
extra={
|
||||||
|
canCreateClass ? (
|
||||||
|
<Button size="small" onClick={() => setClassModalOpen(true)}>
|
||||||
|
+ 创建班级
|
||||||
|
</Button>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<List
|
||||||
|
dataSource={classes}
|
||||||
|
renderItem={(cls: ClassItem) => (
|
||||||
|
<List.Item
|
||||||
|
onClick={() => setSelectedClassId(cls.id)}
|
||||||
|
style={{
|
||||||
|
cursor: 'pointer',
|
||||||
|
background: selectedClassId === cls.id ? '#e6f4ff' : undefined,
|
||||||
|
borderRadius: 4,
|
||||||
|
padding: '8px 12px',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<List.Item.Meta
|
||||||
|
title={cls.name}
|
||||||
|
description={`${cls.code} ${cls.classType || ''}`}
|
||||||
|
/>
|
||||||
|
</List.Item>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
|
</Row>
|
||||||
|
|
||||||
|
{canCreateClass ? (
|
||||||
|
<Modal
|
||||||
|
title="创建班级"
|
||||||
|
open={classModalOpen}
|
||||||
|
onOk={handleCreateClass}
|
||||||
|
onCancel={() => {
|
||||||
|
setClassModalOpen(false);
|
||||||
|
classForm.resetFields();
|
||||||
|
}}
|
||||||
|
confirmLoading={importing}
|
||||||
|
destroyOnClose
|
||||||
|
>
|
||||||
|
<Form form={classForm} layout="vertical">
|
||||||
|
<Form.Item name="name" label="班级名称" rules={[{ required: true }]}>
|
||||||
|
<Input />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="code" label="班级编码" rules={[{ required: true }]}>
|
||||||
|
<Input placeholder="如 CS2024-01" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="classType" label="班型" rules={[{ required: true }]}>
|
||||||
|
<Select
|
||||||
|
options={[
|
||||||
|
{ value: 'culture', label: '文化课' },
|
||||||
|
{ value: 'professional', label: '专业课' },
|
||||||
|
{ value: 'bootcamp', label: '集训营' },
|
||||||
|
{ value: 'sprint', label: '冲刺班' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="startDate" label="开班日期">
|
||||||
|
<DatePicker style={{ width: '100%' }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="endDate" label="结束日期">
|
||||||
|
<DatePicker style={{ width: '100%' }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="notes" label="备注">
|
||||||
|
<Input.TextArea rows={2} />
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
) : null}
|
||||||
|
</Drawer>
|
||||||
|
)}
|
||||||
|
<Modal
|
||||||
|
title="确认清空钉钉全部考勤组"
|
||||||
|
open={deleteGroupsOpen}
|
||||||
|
okText="确认全部清空"
|
||||||
|
okButtonProps={{ danger: true, disabled: attendanceGroups.length === 0 }}
|
||||||
|
cancelText="取消"
|
||||||
|
confirmLoading={deletingGroups}
|
||||||
|
onOk={deleteAllGroups}
|
||||||
|
onCancel={() => setDeleteGroupsOpen(false)}
|
||||||
|
>
|
||||||
|
<Alert
|
||||||
|
type="error"
|
||||||
|
showIcon
|
||||||
|
title={`将永久清空钉钉上的 ${attendanceGroups.length} 个考勤组`}
|
||||||
|
description="本地班级和排课不会清空。清空后需在排课管理中重新同步,才能重建考勤组。"
|
||||||
|
style={{ marginBottom: 12 }}
|
||||||
|
/>
|
||||||
|
<List
|
||||||
|
size="small"
|
||||||
|
bordered
|
||||||
|
dataSource={attendanceGroups}
|
||||||
|
style={{ maxHeight: 280, overflow: 'auto' }}
|
||||||
|
renderItem={(group) => (
|
||||||
|
<List.Item>
|
||||||
|
<List.Item.Meta
|
||||||
|
title={group.group_name}
|
||||||
|
description={`ID ${group.group_id} · ${group.member_count} 人`}
|
||||||
|
/>
|
||||||
|
</List.Item>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,37 +1,26 @@
|
|||||||
import React, { useEffect, useState, useMemo, useCallback } from 'react';
|
import React, { useEffect, useState, useMemo } from 'react';
|
||||||
|
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||||
|
import { validateResponse } from '../../utils/validate';
|
||||||
|
import { integrationConfigSchema } from '../../api/schemas';
|
||||||
import {
|
import {
|
||||||
|
Alert,
|
||||||
|
Button,
|
||||||
Card,
|
Card,
|
||||||
|
Descriptions,
|
||||||
|
Divider,
|
||||||
Form,
|
Form,
|
||||||
Input,
|
Input,
|
||||||
Button,
|
|
||||||
Space,
|
Space,
|
||||||
Spin,
|
Spin,
|
||||||
Alert,
|
|
||||||
Descriptions,
|
|
||||||
Tag,
|
Tag,
|
||||||
Divider,
|
|
||||||
Drawer,
|
|
||||||
Tree,
|
|
||||||
Select,
|
|
||||||
TreeSelect,
|
|
||||||
Modal,
|
|
||||||
DatePicker,
|
|
||||||
Row,
|
|
||||||
Col,
|
|
||||||
List,
|
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import {
|
import {
|
||||||
SaveOutlined,
|
|
||||||
ApiOutlined,
|
ApiOutlined,
|
||||||
CheckCircleOutlined,
|
CheckCircleOutlined,
|
||||||
CloseCircleOutlined,
|
CloseCircleOutlined,
|
||||||
SyncOutlined,
|
SaveOutlined,
|
||||||
BankOutlined,
|
|
||||||
UserOutlined,
|
|
||||||
StopOutlined,
|
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import type { DataNode } from 'antd/es/tree';
|
|
||||||
import type { TreeSelectProps } from 'antd/es/tree-select';
|
|
||||||
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';
|
||||||
@@ -47,146 +36,78 @@ import {
|
|||||||
commitDingTalkConfig,
|
commitDingTalkConfig,
|
||||||
readDingTalkConfigCache,
|
readDingTalkConfigCache,
|
||||||
} from './integration-config-cache';
|
} from './integration-config-cache';
|
||||||
|
import { IntegrationOrgSyncPanel } from './IntegrationOrgSyncPanel';
|
||||||
|
|
||||||
interface DingTalkConfig {
|
interface DingTalkConfig {
|
||||||
agentId: string;
|
agentId: string;
|
||||||
corpId: string;
|
corpId: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface DingOrgTreeNodeExt {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
parentId: number;
|
|
||||||
children: DingOrgTreeNodeExt[];
|
|
||||||
users: Array<{ userid: string; name: string; mobile: string; deptIds: number[] }>;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface OrgTreeNodeRaw {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
children?: OrgTreeNodeRaw[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface OrgTreeResponse {
|
|
||||||
success: boolean;
|
|
||||||
data: OrgTreeNodeRaw[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface OrgTreeWithUsersResponse {
|
|
||||||
success: boolean;
|
|
||||||
data: DingOrgTreeNodeExt[];
|
|
||||||
}
|
|
||||||
|
|
||||||
type DeptPickerTreeNode = NonNullable<TreeSelectProps<number>['treeData']>[number];
|
|
||||||
|
|
||||||
interface ClassItem {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
code: string;
|
|
||||||
classType?: string;
|
|
||||||
startDate?: string;
|
|
||||||
endDate?: string;
|
|
||||||
notes?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ImportResult {
|
|
||||||
imported: number;
|
|
||||||
skipped: number;
|
|
||||||
conflicts: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface DingTalkAttendanceGroup {
|
|
||||||
group_id: number;
|
|
||||||
group_name: string;
|
|
||||||
type: string;
|
|
||||||
member_count: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AttendanceGroupResponse {
|
|
||||||
success: boolean;
|
|
||||||
data: DingTalkAttendanceGroup[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface DeleteAttendanceGroupsResponse {
|
|
||||||
success: boolean;
|
|
||||||
data: {
|
|
||||||
total: number;
|
|
||||||
deleted: Array<{ groupId: number; groupName: string }>;
|
|
||||||
failed: Array<{ groupId: number; groupName: string; error: string }>;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const IntegrationConfigPage: React.FC = () => {
|
const IntegrationConfigPage: React.FC = () => {
|
||||||
const initialCache = useMemo(() => readDingTalkConfigCache(), []);
|
const initialCache = useMemo(() => readDingTalkConfigCache(), []);
|
||||||
const { hasPermission, hasAllPermissions } = usePermission();
|
const { hasPermission, hasAllPermissions } = usePermission();
|
||||||
const canCreateClass = hasPermission('class:create');
|
const canCreateClass = hasPermission('class:create');
|
||||||
const [loading, setLoading] = useState(!initialCache.loaded);
|
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [testing, setTesting] = useState(false);
|
const [testing, setTesting] = useState(false);
|
||||||
const [config, setConfig] = useState<DingTalkConfig | null>(initialCache.config);
|
|
||||||
const [verified, setVerified] = useState<boolean | null>(initialCache.verified);
|
|
||||||
const [form] = Form.useForm<DingTalkConfigFormValues>();
|
const [form] = Form.useForm<DingTalkConfigFormValues>();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
// ── Manual organization sync ──
|
const {
|
||||||
const [syncRootDeptId, setSyncRootDeptId] = useState<number | undefined>(undefined);
|
data: serverConfig = { config: initialCache.config, verified: initialCache.verified },
|
||||||
const [orgTree, setOrgTree] = useState<DingOrgTreeNodeExt[]>([]);
|
isLoading: configLoading,
|
||||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
isFetching: configFetching,
|
||||||
const [fetchingTree, setFetchingTree] = useState(false);
|
} = useQuery<{ config: DingTalkConfig | null; verified: boolean | null }>({
|
||||||
const [importing, setImporting] = useState(false);
|
queryKey: ['integration', 'config'],
|
||||||
const [deptPickerTree, setDeptPickerTree] = useState<DeptPickerTreeNode[]>([]);
|
queryFn: async () => {
|
||||||
const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
|
try {
|
||||||
const [selectedClassId, setSelectedClassId] = useState<number | null>(null);
|
const res = await api.get<{
|
||||||
const [classes, setClasses] = useState<ClassItem[]>([]);
|
success: boolean;
|
||||||
const [classForm] = Form.useForm();
|
data: Array<{ type: string; verify: boolean; config: DingTalkConfig }>;
|
||||||
const [classModalOpen, setClassModalOpen] = useState(false);
|
}>('/integration/config');
|
||||||
const [attendanceGroups, setAttendanceGroups] = useState<DingTalkAttendanceGroup[]>([]);
|
const validated = validateResponse<{
|
||||||
const [deleteGroupsOpen, setDeleteGroupsOpen] = useState(false);
|
success: boolean;
|
||||||
const [loadingGroups, setLoadingGroups] = useState(false);
|
data: Array<{ type: string; verify: boolean; config: DingTalkConfig }>;
|
||||||
const [deletingGroups, setDeletingGroups] = useState(false);
|
}>(integrationConfigSchema, res);
|
||||||
|
const dt = validated.data?.find((c) => c.type === 'DINGTALK');
|
||||||
const fetchConfig = useCallback(async (showLoading = false) => {
|
return { config: dt?.config ?? null, verified: dt ? dt.verify : null };
|
||||||
if (showLoading) setLoading(true);
|
} catch {
|
||||||
try {
|
// not configured
|
||||||
const res = await api.get<{
|
return { config: initialCache.config, verified: initialCache.verified };
|
||||||
success: boolean;
|
|
||||||
data: Array<{ type: string; verify: boolean; config: DingTalkConfig }>;
|
|
||||||
}>('/integration/config');
|
|
||||||
const dt = res.data?.find((c) => c.type === 'DINGTALK');
|
|
||||||
if (dt) {
|
|
||||||
setConfig(dt.config);
|
|
||||||
setVerified(dt.verify);
|
|
||||||
cacheDingTalkServerSnapshot(dt.config, dt.verify);
|
|
||||||
form.setFieldsValue(readDingTalkConfigCache().formValues);
|
|
||||||
} else {
|
|
||||||
setConfig(null);
|
|
||||||
setVerified(null);
|
|
||||||
cacheDingTalkServerSnapshot(null, null);
|
|
||||||
}
|
}
|
||||||
} catch {
|
},
|
||||||
// not configured
|
});
|
||||||
} finally {
|
const config = serverConfig.config;
|
||||||
if (showLoading) setLoading(false);
|
const verified = serverConfig.verified;
|
||||||
}
|
const loading = !initialCache.loaded && (configLoading || configFetching);
|
||||||
}, [form]);
|
|
||||||
|
|
||||||
|
const saveMutation = useApiMutation(
|
||||||
|
async (payload: Record<string, unknown>) =>
|
||||||
|
api.post('/integration/config', { type: 'DINGTALK', config: payload }),
|
||||||
|
{ invalidate: [['integration', 'config']] },
|
||||||
|
);
|
||||||
|
|
||||||
|
// 初始表单值来自本地缓存(外部存储同步)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
form.setFieldsValue(initialCache.formValues);
|
form.setFieldsValue(initialCache.formValues);
|
||||||
void fetchConfig(!initialCache.loaded);
|
}, [form, initialCache]);
|
||||||
}, [fetchConfig, form, initialCache]);
|
|
||||||
|
// 服务端配置同步进 localStorage 缓存,并回填表单
|
||||||
|
useEffect(() => {
|
||||||
|
cacheDingTalkServerSnapshot(config, verified);
|
||||||
|
if (config) form.setFieldsValue(readDingTalkConfigCache().formValues);
|
||||||
|
}, [config, verified, form]);
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
const values = await form.validateFields();
|
const values = await form.validateFields();
|
||||||
const payload = buildDingTalkConfigPayload(values);
|
const payload = buildDingTalkConfigPayload(values);
|
||||||
setSaving(true);
|
setSaving(true);
|
||||||
try {
|
try {
|
||||||
await api.post('/integration/config', { type: 'DINGTALK', config: payload });
|
await saveMutation.mutateAsync(payload);
|
||||||
message.success('配置已保存');
|
message.success('配置已保存');
|
||||||
commitDingTalkConfig({ corpId: payload.corpId, agentId: payload.agentId });
|
commitDingTalkConfig({ corpId: payload.corpId, agentId: payload.agentId });
|
||||||
form.setFieldValue('appSecret', undefined);
|
form.setFieldValue('appSecret', undefined);
|
||||||
await fetchConfig();
|
} catch {
|
||||||
} catch (e: unknown) {
|
// 错误提示由 useApiMutation 统一处理
|
||||||
const err = e as { message?: string };
|
|
||||||
message.error(err?.message || '保存失败');
|
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false);
|
setSaving(false);
|
||||||
}
|
}
|
||||||
@@ -204,414 +125,23 @@ const IntegrationConfigPage: React.FC = () => {
|
|||||||
config: payload,
|
config: payload,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
setVerified(res.success);
|
queryClient.setQueryData(['integration', 'config'], (prev) => ({
|
||||||
|
...(prev ?? { config: initialCache.config, verified: initialCache.verified }),
|
||||||
|
verified: res.success,
|
||||||
|
}));
|
||||||
message.success(res.message);
|
message.success(res.message);
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const err = e as { message?: string };
|
const err = e as { message?: string };
|
||||||
setVerified(false);
|
queryClient.setQueryData(['integration', 'config'], (prev) => ({
|
||||||
|
...(prev ?? { config: initialCache.config, verified: initialCache.verified }),
|
||||||
|
verified: false,
|
||||||
|
}));
|
||||||
message.error(err?.message || '连接失败');
|
message.error(err?.message || '连接失败');
|
||||||
} finally {
|
} finally {
|
||||||
setTesting(false);
|
setTesting(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadDeptTree = async () => {
|
|
||||||
try {
|
|
||||||
const res = await api.get<OrgTreeResponse>('/sync/dingtalk/org-tree');
|
|
||||||
if (res.success && res.data) {
|
|
||||||
const toTreeNode = (nodes: OrgTreeNodeRaw[]): DeptPickerTreeNode[] =>
|
|
||||||
nodes.map((n) => ({
|
|
||||||
title: n.name,
|
|
||||||
value: n.id,
|
|
||||||
children: n.children ? toTreeNode(n.children) : undefined,
|
|
||||||
}));
|
|
||||||
setDeptPickerTree(toTreeNode(res.data));
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
message.error('获取部门架构失败');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchClasses = async () => {
|
|
||||||
try {
|
|
||||||
const res = await api.get<ClassItem[] | { data: ClassItem[] }>('/classes');
|
|
||||||
if (Array.isArray(res)) {
|
|
||||||
setClasses(res);
|
|
||||||
} else {
|
|
||||||
setClasses(res.data ?? []);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleFetchOrgTree = async () => {
|
|
||||||
setFetchingTree(true);
|
|
||||||
try {
|
|
||||||
const params: Record<string, string> = {};
|
|
||||||
if (syncRootDeptId) params.rootDeptId = String(syncRootDeptId);
|
|
||||||
const res = await api.get<OrgTreeWithUsersResponse>('/sync/dingtalk/org-tree-with-users', {
|
|
||||||
params,
|
|
||||||
});
|
|
||||||
if (res.success && res.data) {
|
|
||||||
setOrgTree(res.data);
|
|
||||||
setCheckedKeys([]);
|
|
||||||
setSelectedClassId(null);
|
|
||||||
setDrawerOpen(true);
|
|
||||||
fetchClasses();
|
|
||||||
} else {
|
|
||||||
message.error('获取组织架构失败');
|
|
||||||
}
|
|
||||||
} catch (e: unknown) {
|
|
||||||
const err = e as { message?: string };
|
|
||||||
message.error(err?.message || '获取组织架构失败');
|
|
||||||
} finally {
|
|
||||||
setFetchingTree(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildTreeData = useCallback((nodes: DingOrgTreeNodeExt[]): DataNode[] => {
|
|
||||||
return nodes.map((node) => {
|
|
||||||
const users = node.users ?? [];
|
|
||||||
const children: DataNode[] = [
|
|
||||||
...buildTreeData(node.children ?? []),
|
|
||||||
...users.map((u) => ({
|
|
||||||
title: (
|
|
||||||
<Space>
|
|
||||||
<UserOutlined />
|
|
||||||
<span>{u.name}</span>
|
|
||||||
{u.mobile ? <Tag>{u.mobile}</Tag> : null}
|
|
||||||
</Space>
|
|
||||||
),
|
|
||||||
key: `user-${u.userid}`,
|
|
||||||
isLeaf: true,
|
|
||||||
})),
|
|
||||||
];
|
|
||||||
return {
|
|
||||||
title: (
|
|
||||||
<Space size="small">
|
|
||||||
<BankOutlined />
|
|
||||||
<span>{node.name}</span>
|
|
||||||
<Tag>{users.length}人</Tag>
|
|
||||||
</Space>
|
|
||||||
),
|
|
||||||
key: `dept-${node.id}`,
|
|
||||||
// Only attach children when there are any, so empty/leaf departments
|
|
||||||
// don't render a phantom expand arrow that opens to nothing.
|
|
||||||
...(children.length > 0 ? { children } : {}),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const treeData = useMemo(() => buildTreeData(orgTree), [orgTree, buildTreeData]);
|
|
||||||
|
|
||||||
const extractCheckedUsers = useCallback((): Array<{
|
|
||||||
dingUserId: string;
|
|
||||||
name: string;
|
|
||||||
mobile?: string;
|
|
||||||
}> => {
|
|
||||||
const result: Array<{ dingUserId: string; name: string; mobile?: string }> = [];
|
|
||||||
const walk = (nodes: DingOrgTreeNodeExt[]) => {
|
|
||||||
for (const node of nodes) {
|
|
||||||
for (const u of node.users ?? []) {
|
|
||||||
if (checkedKeys.includes(`user-${u.userid}`)) {
|
|
||||||
result.push({ dingUserId: u.userid, name: u.name, mobile: u.mobile || undefined });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
walk(node.children ?? []);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
walk(orgTree);
|
|
||||||
return result;
|
|
||||||
}, [checkedKeys, orgTree]);
|
|
||||||
|
|
||||||
const handleJoinClass = async () => {
|
|
||||||
if (selectedClassId === null) return message.warning('请先选择一个班级');
|
|
||||||
const users = extractCheckedUsers();
|
|
||||||
if (users.length === 0) return message.warning('请勾选要导入的用户');
|
|
||||||
|
|
||||||
setImporting(true);
|
|
||||||
try {
|
|
||||||
const res = await api.post<ImportResult>(`/classes/${selectedClassId}/students/import`, {
|
|
||||||
users,
|
|
||||||
});
|
|
||||||
if (res.conflicts > 0) {
|
|
||||||
message.warning(
|
|
||||||
`导入 ${res.imported} 人,跳过 ${res.skipped} 人,${res.conflicts} 人需人工绑定`,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
message.success(`导入 ${res.imported} 人,跳过 ${res.skipped} 人`);
|
|
||||||
}
|
|
||||||
setCheckedKeys([]);
|
|
||||||
setSelectedClassId(null);
|
|
||||||
} catch (e: unknown) {
|
|
||||||
const err = e as { message?: string };
|
|
||||||
message.error(err?.message || '导入失败');
|
|
||||||
} finally {
|
|
||||||
setImporting(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCreateClass = async () => {
|
|
||||||
try {
|
|
||||||
const values = await classForm.validateFields();
|
|
||||||
const users = extractCheckedUsers();
|
|
||||||
await api.post('/classes', { ...values, users });
|
|
||||||
message.success('班级创建成功');
|
|
||||||
setClassModalOpen(false);
|
|
||||||
classForm.resetFields();
|
|
||||||
setCheckedKeys([]);
|
|
||||||
fetchClasses();
|
|
||||||
} catch (e: unknown) {
|
|
||||||
const err = e as { message?: string };
|
|
||||||
message.error(err?.message || '创建失败');
|
|
||||||
} finally {
|
|
||||||
setImporting(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const openDeleteAllGroups = async () => {
|
|
||||||
setLoadingGroups(true);
|
|
||||||
try {
|
|
||||||
const response = await api.get<AttendanceGroupResponse>('/sync/dingtalk/attendance-groups');
|
|
||||||
setAttendanceGroups(response.data);
|
|
||||||
setDeleteGroupsOpen(true);
|
|
||||||
} catch (error: unknown) {
|
|
||||||
message.error(error instanceof Error ? error.message : '获取钉钉考勤组失败');
|
|
||||||
} finally {
|
|
||||||
setLoadingGroups(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const deleteAllGroups = async () => {
|
|
||||||
setDeletingGroups(true);
|
|
||||||
try {
|
|
||||||
const response = await api.post<DeleteAttendanceGroupsResponse>(
|
|
||||||
'/sync/dingtalk/attendance-groups/delete-all',
|
|
||||||
);
|
|
||||||
setDeleteGroupsOpen(false);
|
|
||||||
setAttendanceGroups([]);
|
|
||||||
if (response.data.failed.length > 0) {
|
|
||||||
message.warning(
|
|
||||||
`已清空 ${response.data.deleted.length} 个,失败 ${response.data.failed.length} 个`,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
message.success(`已清空钉钉全部 ${response.data.deleted.length} 个考勤组`);
|
|
||||||
}
|
|
||||||
} catch (error: unknown) {
|
|
||||||
message.error(error instanceof Error ? error.message : '清空钉钉考勤组失败');
|
|
||||||
} finally {
|
|
||||||
setDeletingGroups(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const syncPanel =
|
|
||||||
config && hasAllPermissions('sync:read', 'class:view', 'class:edit') ? (
|
|
||||||
<div>
|
|
||||||
<Alert
|
|
||||||
type="info"
|
|
||||||
message="从钉钉获取组织架构,勾选用户后批量导入到班级。"
|
|
||||||
style={{ marginBottom: 16 }}
|
|
||||||
showIcon
|
|
||||||
/>
|
|
||||||
<Space>
|
|
||||||
<TreeSelect
|
|
||||||
treeData={deptPickerTree}
|
|
||||||
value={syncRootDeptId}
|
|
||||||
onChange={(v) => setSyncRootDeptId(v)}
|
|
||||||
placeholder="选择起始部门(不选=全部)"
|
|
||||||
allowClear
|
|
||||||
treeDefaultExpandAll
|
|
||||||
style={{ minWidth: 240 }}
|
|
||||||
onDropdownVisibleChange={(open) => {
|
|
||||||
if (open) loadDeptTree();
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
type="primary"
|
|
||||||
icon={<SyncOutlined />}
|
|
||||||
loading={fetchingTree}
|
|
||||||
onClick={handleFetchOrgTree}
|
|
||||||
>
|
|
||||||
获取组织架构
|
|
||||||
</Button>
|
|
||||||
<PermissionButton
|
|
||||||
permission="sync:trigger"
|
|
||||||
danger
|
|
||||||
icon={<StopOutlined />}
|
|
||||||
loading={loadingGroups}
|
|
||||||
onClick={openDeleteAllGroups}
|
|
||||||
>
|
|
||||||
清空钉钉全部考勤组
|
|
||||||
</PermissionButton>
|
|
||||||
</Space>
|
|
||||||
|
|
||||||
{drawerOpen && (
|
|
||||||
<Drawer
|
|
||||||
title="钉钉组织架构 — 批量导入"
|
|
||||||
open={drawerOpen}
|
|
||||||
onClose={() => {
|
|
||||||
setDrawerOpen(false);
|
|
||||||
}}
|
|
||||||
width="min(900px, 100vw)"
|
|
||||||
footer={
|
|
||||||
<Space>
|
|
||||||
<Button
|
|
||||||
onClick={() => {
|
|
||||||
setDrawerOpen(false);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
取消
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
type="primary"
|
|
||||||
loading={importing}
|
|
||||||
disabled={
|
|
||||||
checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0 ||
|
|
||||||
selectedClassId === null
|
|
||||||
}
|
|
||||||
onClick={handleJoinClass}
|
|
||||||
>
|
|
||||||
加入选中的班级
|
|
||||||
</Button>
|
|
||||||
{canCreateClass ? (
|
|
||||||
<Button
|
|
||||||
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0}
|
|
||||||
onClick={() => setClassModalOpen(true)}
|
|
||||||
>
|
|
||||||
创建班级
|
|
||||||
</Button>
|
|
||||||
) : null}
|
|
||||||
</Space>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Row gutter={[16, 16]}>
|
|
||||||
<Col xs={24} md={14}>
|
|
||||||
<div style={{ maxHeight: '60vh', overflow: 'auto' }}>
|
|
||||||
<Tree
|
|
||||||
checkable
|
|
||||||
treeData={treeData}
|
|
||||||
defaultExpandAll
|
|
||||||
showLine={{ showLeafIcon: false }}
|
|
||||||
checkedKeys={checkedKeys}
|
|
||||||
onCheck={(checked) => setCheckedKeys(checked as React.Key[])}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</Col>
|
|
||||||
<Col xs={24} md={10}>
|
|
||||||
<Card
|
|
||||||
title="班级列表"
|
|
||||||
size="small"
|
|
||||||
extra={
|
|
||||||
canCreateClass ? (
|
|
||||||
<Button size="small" onClick={() => setClassModalOpen(true)}>
|
|
||||||
+ 创建班级
|
|
||||||
</Button>
|
|
||||||
) : null
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<List
|
|
||||||
dataSource={classes}
|
|
||||||
renderItem={(cls: ClassItem) => (
|
|
||||||
<List.Item
|
|
||||||
onClick={() => setSelectedClassId(cls.id)}
|
|
||||||
style={{
|
|
||||||
cursor: 'pointer',
|
|
||||||
background: selectedClassId === cls.id ? '#e6f4ff' : undefined,
|
|
||||||
borderRadius: 4,
|
|
||||||
padding: '8px 12px',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<List.Item.Meta
|
|
||||||
title={cls.name}
|
|
||||||
description={`${cls.code} ${cls.classType || ''}`}
|
|
||||||
/>
|
|
||||||
</List.Item>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
</Row>
|
|
||||||
|
|
||||||
{/* Create class Modal */}
|
|
||||||
{canCreateClass ? (
|
|
||||||
<Modal
|
|
||||||
title="创建班级"
|
|
||||||
open={classModalOpen}
|
|
||||||
onOk={handleCreateClass}
|
|
||||||
onCancel={() => {
|
|
||||||
setClassModalOpen(false);
|
|
||||||
classForm.resetFields();
|
|
||||||
}}
|
|
||||||
confirmLoading={importing}
|
|
||||||
destroyOnClose
|
|
||||||
>
|
|
||||||
<Form form={classForm} layout="vertical">
|
|
||||||
<Form.Item name="name" label="班级名称" rules={[{ required: true }]}>
|
|
||||||
<Input />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="code" label="班级编码" rules={[{ required: true }]}>
|
|
||||||
<Input placeholder="如 CS2024-01" />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="classType" label="班型" rules={[{ required: true }]}>
|
|
||||||
<Select
|
|
||||||
options={[
|
|
||||||
{ value: 'culture', label: '文化课' },
|
|
||||||
{ value: 'professional', label: '专业课' },
|
|
||||||
{ value: 'bootcamp', label: '集训营' },
|
|
||||||
{ value: 'sprint', label: '冲刺班' },
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="startDate" label="开班日期">
|
|
||||||
<DatePicker style={{ width: '100%' }} />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="endDate" label="结束日期">
|
|
||||||
<DatePicker style={{ width: '100%' }} />
|
|
||||||
</Form.Item>
|
|
||||||
<Form.Item name="notes" label="备注">
|
|
||||||
<Input.TextArea rows={2} />
|
|
||||||
</Form.Item>
|
|
||||||
</Form>
|
|
||||||
</Modal>
|
|
||||||
) : null}
|
|
||||||
</Drawer>
|
|
||||||
)}
|
|
||||||
<Modal
|
|
||||||
title="确认清空钉钉全部考勤组"
|
|
||||||
open={deleteGroupsOpen}
|
|
||||||
okText="确认全部清空"
|
|
||||||
okButtonProps={{ danger: true, disabled: attendanceGroups.length === 0 }}
|
|
||||||
cancelText="取消"
|
|
||||||
confirmLoading={deletingGroups}
|
|
||||||
onOk={deleteAllGroups}
|
|
||||||
onCancel={() => setDeleteGroupsOpen(false)}
|
|
||||||
>
|
|
||||||
<Alert
|
|
||||||
type="error"
|
|
||||||
showIcon
|
|
||||||
message={`将永久清空钉钉上的 ${attendanceGroups.length} 个考勤组`}
|
|
||||||
description="本地班级和排课不会清空。清空后需在排课管理中重新同步,才能重建考勤组。"
|
|
||||||
style={{ marginBottom: 12 }}
|
|
||||||
/>
|
|
||||||
<List
|
|
||||||
size="small"
|
|
||||||
bordered
|
|
||||||
dataSource={attendanceGroups}
|
|
||||||
style={{ maxHeight: 280, overflow: 'auto' }}
|
|
||||||
renderItem={(group) => (
|
|
||||||
<List.Item>
|
|
||||||
<List.Item.Meta
|
|
||||||
title={group.group_name}
|
|
||||||
description={`ID ${group.group_id} · ${group.member_count} 人`}
|
|
||||||
/>
|
|
||||||
</List.Item>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</Modal>
|
|
||||||
</div>
|
|
||||||
) : null;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card
|
<Card
|
||||||
title="钉钉集成配置"
|
title="钉钉集成配置"
|
||||||
@@ -700,10 +230,10 @@ const IntegrationConfigPage: React.FC = () => {
|
|||||||
</Space>
|
</Space>
|
||||||
</Form>
|
</Form>
|
||||||
|
|
||||||
{syncPanel && (
|
{config && hasAllPermissions('sync:read', 'class:view', 'class:edit') && (
|
||||||
<>
|
<>
|
||||||
<Divider titlePlacement="start">组织用户导入</Divider>
|
<Divider titlePlacement="start">组织用户导入</Divider>
|
||||||
{syncPanel}
|
<IntegrationOrgSyncPanel canCreateClass={canCreateClass} />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Spin>
|
</Spin>
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import React, { useCallback, useState } from 'react';
|
import React, { useCallback, useState } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router';
|
||||||
import { Form, Input, Button, Card, Typography } from 'antd';
|
import { Form, Input, Button, Card, Typography } from 'antd';
|
||||||
import { UserOutlined, LockOutlined } from '@ant-design/icons';
|
import { UserOutlined, LockOutlined } from '@ant-design/icons';
|
||||||
import api from '../../api';
|
import api from '../../api';
|
||||||
|
import { BrandLogo } from '../../components/BrandLogo';
|
||||||
import { message } from '../../ui/app-message';
|
import { message } from '../../ui/app-message';
|
||||||
import { findRoleAwareLandingPath } from '../../auth/menu-policy';
|
import { findRoleAwareLandingPath } from '../../auth/menu-policy';
|
||||||
import { usePermissionStore } from '../../store/permission/permissionStore';
|
import { usePermissionStore } from '../../store/permission/permissionStore';
|
||||||
@@ -59,7 +60,11 @@ const LoginPage: React.FC = () => {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div style={{ textAlign: 'center', marginBottom: 32 }}>
|
<div style={{ textAlign: 'center', marginBottom: 32 }}>
|
||||||
<Title level={3} style={{ margin: 0, fontWeight: 600, color: '#1d1d1f' }}>
|
<BrandLogo size={48} />
|
||||||
|
<Title
|
||||||
|
level={3}
|
||||||
|
style={{ margin: '14px 0 0', fontWeight: 600, color: '#1d1d1f' }}
|
||||||
|
>
|
||||||
学生管理系统
|
学生管理系统
|
||||||
</Title>
|
</Title>
|
||||||
<p style={{ color: '#86868b', marginTop: 8 }}>学生综合管理平台</p>
|
<p style={{ color: '#86868b', marginTop: 8 }}>学生综合管理平台</p>
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user