fix: OCR 审查驱动的全库修复(安全/正确性/部署/前端) #64
@@ -33,3 +33,11 @@ AI_CONFIG_ENCRYPTION_KEY=
|
||||
|
||||
# 允许内网地址作为 OPENAI_COMPATIBLE 的 baseUrl(仅内网部署使用)
|
||||
# AI_ALLOW_PRIVATE_BASE_URL=true
|
||||
|
||||
# ---- 安全 ----
|
||||
# 是否信任反向代理的 X-Forwarded-For / X-Real-IP(仅当部署在可信代理/Nginx 后时才设 true;
|
||||
# 不设置时服务端只用 TCP socket 地址,防止伪造客户端 IP)
|
||||
# TRUST_PROXY=true
|
||||
|
||||
# 说明:第三方集成配置(钉钉/企微 appSecret)的静态加密复用 AI_CONFIG_ENCRYPTION_KEY,
|
||||
# 存量明文可用 `cd apps/server && npm run encrypt:integration-secrets` 一次性加密。
|
||||
|
||||
@@ -16,6 +16,10 @@ name: PM2 部署
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: deploy
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -37,7 +41,10 @@ jobs:
|
||||
- name: 配置 SSH
|
||||
run: |
|
||||
mkdir -p ~/.ssh
|
||||
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/deploy_key
|
||||
# 单引号 EOF 防止 key 中的 $ / 反引号被 shell 插值(YAML 会剥掉缩进,bash 实际收到列首 EOF)
|
||||
cat > ~/.ssh/deploy_key <<'EOF'
|
||||
${{ secrets.SSH_PRIVATE_KEY }}
|
||||
EOF
|
||||
chmod 600 ~/.ssh/deploy_key
|
||||
cat >> ~/.ssh/config <<'EOF'
|
||||
Host deploy-server
|
||||
@@ -59,17 +66,20 @@ jobs:
|
||||
--exclude='.turbo/' \
|
||||
--exclude='.claude/' \
|
||||
--exclude='.codegraph/' \
|
||||
--exclude='.env*' \
|
||||
--exclude='data.sql' \
|
||||
--exclude='uploads/' \
|
||||
./ deploy-server:${{ secrets.REMOTE_DIR }}/
|
||||
|
||||
- name: 安装依赖 → 迁移 → PM2 重载
|
||||
run: |
|
||||
ssh deploy-server "
|
||||
set -e
|
||||
cd ${{ secrets.REMOTE_DIR }}
|
||||
mkdir -p logs
|
||||
if [ ! -d node_modules ]; then
|
||||
echo '首次部署,安装生产依赖...'
|
||||
npm ci --omit=dev
|
||||
fi
|
||||
echo '安装依赖...'
|
||||
# 注意:migration:run 依赖 ts-node/tsconfig-paths(devDependencies),不能 --omit=dev
|
||||
npm ci
|
||||
echo '执行数据库迁移...'
|
||||
npm run migration:run -w @gongxue/server
|
||||
echo 'PM2 重载...'
|
||||
|
||||
35
README.md
35
README.md
@@ -16,6 +16,11 @@
|
||||
| 账单导出 | Excel(汇总+明细双Sheet)、单条PDF账单 |
|
||||
| 教室管理 | 教室信息维护、教室租赁记录 |
|
||||
| 押金管理 | 押金收取与退还 |
|
||||
| 班级/排课 | 班级档案、分班、教室日程与排课 |
|
||||
| 考勤管理 | 手工考勤、钉钉考勤同步、自动匹配 |
|
||||
| 教室租赁 | 租赁订单、合同、租赁日程 |
|
||||
| AI 助手 | 对话式查询、表单/导入向导/图表、业务待办引导 |
|
||||
| 组织/校区 | 组织机构与数据范围 |
|
||||
| 操作日志 | 所有涉及钱的操作自动审计留痕 |
|
||||
| 账号管理 | 用户增删改查、角色区分、启用/禁用、重置密码 |
|
||||
|
||||
@@ -42,7 +47,7 @@
|
||||
### 后端启动
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
cd apps/server
|
||||
cp .env.example .env # 复制并修改环境配置
|
||||
npm install
|
||||
npm run start:dev # 开发模式启动,默认端口 3000
|
||||
@@ -51,46 +56,48 @@ npm run start:dev # 开发模式启动,默认端口 3000
|
||||
### 前端启动
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
cd apps/admin
|
||||
npm install
|
||||
npm run dev # 开发模式启动,默认端口 5173
|
||||
```
|
||||
|
||||
### Docker 部署
|
||||
### 常用命令
|
||||
|
||||
```bash
|
||||
docker-compose up -d # 一键启动 MySQL + 后端 + 前端
|
||||
npm run typecheck # 全仓类型检查
|
||||
npm run lint # 全仓 lint
|
||||
npm run test # 全仓测试
|
||||
npm run build # 全仓构建
|
||||
```
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
├── backend/ # 后端 NestJS 服务
|
||||
├── apps/server/ # 后端 NestJS 服务
|
||||
│ ├── src/
|
||||
│ │ ├── auth/ # 认证模块 (JWT)
|
||||
│ │ ├── ai-chat/ # AI 对话、表单/导入向导/图表
|
||||
│ │ ├── attendance/ # 考勤与钉钉同步
|
||||
│ │ ├── bills/ # 账单模块
|
||||
│ │ ├── classrooms/ # 教室管理
|
||||
│ │ ├── dashboard/ # 数据面板
|
||||
│ │ ├── deposits/ # 押金管理
|
||||
│ │ ├── entities/ # 数据实体
|
||||
│ │ ├── expenses/ # 费用录入
|
||||
│ │ ├── occupancies/# 入住管理
|
||||
│ │ ├── rbac/ # 角色权限
|
||||
│ │ ├── rooms/ # 宿舍管理
|
||||
│ │ ├── students/ # 学生管理
|
||||
│ │ └── tenants/ # 租户管理
|
||||
│ │ └── students/ # 学生管理
|
||||
│ └── .env.example # 环境配置模板
|
||||
├── frontend/ # 前端 React 应用
|
||||
├── apps/admin/ # 前端 React 应用
|
||||
│ └── src/
|
||||
│ ├── api/ # API 请求封装
|
||||
│ ├── components/ # 通用组件
|
||||
│ ├── layouts/ # 布局组件
|
||||
│ └── pages/ # 页面组件
|
||||
├── docker-compose.yml # Docker 编排配置
|
||||
├── packages/ # 共享配置包
|
||||
└── 技术文档.md # 详细技术文档
|
||||
```
|
||||
|
||||
## 环境配置
|
||||
|
||||
复制 `backend/.env.example` 为 `backend/.env`,按需修改:
|
||||
复制 `apps/server/.env.example` 为 `apps/server/.env`,按需修改:
|
||||
|
||||
| 配置项 | 说明 | 默认值 |
|
||||
|--------|------|--------|
|
||||
|
||||
@@ -7,6 +7,7 @@ import zhCN from 'antd/es/locale/zh_CN';
|
||||
import MainLayout from './layouts/MainLayout';
|
||||
import PermissionRoute from './components/PermissionRoute';
|
||||
import DefaultRoute from './components/DefaultRoute';
|
||||
import ScrollToTop from './components/ScrollToTop';
|
||||
import AppMessageBridge from './ui/AppMessageBridge';
|
||||
import { useUserStore } from './store/user/userStore';
|
||||
|
||||
@@ -74,6 +75,7 @@ const App: React.FC = () => {
|
||||
<AntdApp>
|
||||
<AppMessageBridge />
|
||||
<BrowserRouter>
|
||||
<ScrollToTop />
|
||||
<Suspense
|
||||
fallback={
|
||||
<div style={{ minHeight: '40vh', display: 'grid', placeItems: 'center' }}>
|
||||
|
||||
@@ -21,6 +21,8 @@ export async function createImportRun(
|
||||
conversationId?: number;
|
||||
stages?: ImportStageRequest[];
|
||||
mapping?: Record<string, Record<string, string>>;
|
||||
/** 上传进度回调(0-100) */
|
||||
onProgress?: (percent: number) => void;
|
||||
},
|
||||
): Promise<ImportRunDetail> {
|
||||
const form = new FormData();
|
||||
@@ -31,7 +33,12 @@ export async function createImportRun(
|
||||
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);
|
||||
const res = await api.post<ApiEnvelope<ImportRunDetail>>('/imports/runs', form, {
|
||||
onUploadProgress: (event) => {
|
||||
if (!options.onProgress || !event.total) return;
|
||||
options.onProgress(Math.min(Math.round((event.loaded / event.total) * 100), 100));
|
||||
},
|
||||
});
|
||||
return res.data;
|
||||
}
|
||||
|
||||
|
||||
20
apps/admin/src/api/queryClient.ts
Normal file
20
apps/admin/src/api/queryClient.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { QueryClient } from '@tanstack/react-query';
|
||||
|
||||
/**
|
||||
* 全局 QueryClient:统一缓存/重试策略。
|
||||
* - retry 1:接口失败最多重试 1 次,避免瞬时错误直接白屏
|
||||
* - staleTime 30s:30 秒内重复请求走缓存
|
||||
* - gcTime 5min:不活跃缓存 5 分钟后回收
|
||||
* - refetchOnWindowFocus false:切回窗口不自动全量刷新,
|
||||
* 保活页面由 useVisibleRefetch 按需刷新,避免重复请求
|
||||
*/
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: 1,
|
||||
staleTime: 30_000,
|
||||
gcTime: 5 * 60_000,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
145
apps/admin/src/api/queryKeys.ts
Normal file
145
apps/admin/src/api/queryKeys.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* 统一 QueryKey 工厂。
|
||||
*
|
||||
* 每个模块一个命名空间,key 由工厂函数生成:
|
||||
* - 避免散落字符串字面量导致拼写不一致、缓存串扰
|
||||
* - invalidate / refetch / prefetch 与 useQuery 使用同一来源,不会对不上
|
||||
*
|
||||
* 约定:
|
||||
* - `all` 是该模块的「根 key」,用于整体失效(invalidateQueries 会匹配前缀)
|
||||
* - 列表 key 按过滤条件展开;详情/子资源用固定段 + 参数
|
||||
*/
|
||||
export const queryKeys = {
|
||||
students: {
|
||||
all: ['students'] as const,
|
||||
list: (filters: {
|
||||
search?: string;
|
||||
status?: string;
|
||||
archived?: boolean;
|
||||
organizationId?: number;
|
||||
classId?: number;
|
||||
teacherId?: number;
|
||||
}) => ['students', filters] as const,
|
||||
organizations: (canView: boolean) => ['students', 'organizations', canView] as const,
|
||||
filterLookups: () => ['students', 'filter-lookups'] as const,
|
||||
},
|
||||
classes: {
|
||||
all: ['classes'] as const,
|
||||
list: (filters: { status?: string; type?: string; archived?: boolean }) =>
|
||||
['classes', filters] as const,
|
||||
detail: (id: number) => ['classes', 'detail', id] as const,
|
||||
schedule: (id: number, dateRange: unknown) => ['classes', 'schedule', id, dateRange] as const,
|
||||
attendanceSummary: (id: number, dateRange: unknown) =>
|
||||
['classes', 'attendance-summary', id, dateRange] as const,
|
||||
},
|
||||
classSchedules: {
|
||||
all: ['class-schedules'] as const,
|
||||
list: (params: { startDate?: string; endDate?: string; classroomIds?: unknown[] }) =>
|
||||
['class-schedules', params] as const,
|
||||
},
|
||||
classrooms: {
|
||||
all: ['classrooms'] as const,
|
||||
list: (archived: boolean) => ['classrooms', archived] as const,
|
||||
},
|
||||
classroomRentals: {
|
||||
all: ['classroom-rentals'] as const,
|
||||
list: (month?: string) => ['classroom-rentals', month] as const,
|
||||
schedule: (year: number, month: number) =>
|
||||
['classroom-rentals', 'schedule', year, month] as const,
|
||||
meta: () => ['classroom-rentals', 'meta'] as const,
|
||||
},
|
||||
organizations: {
|
||||
all: ['organizations'] as const,
|
||||
list: () => ['organizations'] as const,
|
||||
options: () => ['organizations', 'options'] as const,
|
||||
},
|
||||
rbac: {
|
||||
all: ['rbac'] as const,
|
||||
users: (archived: boolean) => ['rbac', 'users', archived] as const,
|
||||
allUsers: () => ['rbac', 'users', 'all'] as const,
|
||||
teachers: (params: { page: number; pageSize: number; search?: string }) =>
|
||||
['rbac', 'teachers', params] as const,
|
||||
teacherWorkspace: () => ['rbac', 'teacher-workspace'] as const,
|
||||
roles: () => ['rbac', 'roles'] as const,
|
||||
permissionTree: () => ['rbac', 'roles', 'permission-tree'] as const,
|
||||
permissionsTree: () => ['rbac', 'permissions', 'tree'] as const,
|
||||
},
|
||||
expenses: {
|
||||
all: ['expenses'] as const,
|
||||
list: (archived: boolean) => ['expenses', archived ? 'archived' : 'active'] as const,
|
||||
},
|
||||
expenseTypes: {
|
||||
map: () => ['expense-types', 'map'] as const,
|
||||
},
|
||||
expenseLookups: {
|
||||
all: ['expense-lookups'] as const,
|
||||
},
|
||||
bills: {
|
||||
all: ['bills'] as const,
|
||||
list: (filters: { status?: string; expenseType?: string }) => ['bills', filters] as const,
|
||||
},
|
||||
wallets: {
|
||||
all: ['wallets'] as const,
|
||||
list: (params: { keyword?: string; debtOnly?: boolean; roomType?: string }) =>
|
||||
['wallets', params] as const,
|
||||
transactions: (studentId: number) => ['wallets', 'transactions', studentId] as const,
|
||||
roomTypes: () => ['wallets', 'room-types'] as const,
|
||||
},
|
||||
deposits: {
|
||||
all: ['deposits'] as const,
|
||||
list: () => ['deposits'] as const,
|
||||
eligible: (roomType?: string) => ['deposits', 'eligible', roomType] as const,
|
||||
},
|
||||
occupancies: {
|
||||
all: ['occupancies'] as const,
|
||||
list: (params: { viewMode?: string; dateRange?: unknown }) => ['occupancies', params] as const,
|
||||
},
|
||||
rooms: {
|
||||
all: ['rooms'] as const,
|
||||
overview: (archived: boolean) => ['rooms', 'overview', archived] as const,
|
||||
visual: (params: { historical: boolean; asOf?: unknown }) =>
|
||||
['rooms', 'visual', params] as const,
|
||||
},
|
||||
exams: {
|
||||
all: ['exams'] as const,
|
||||
detail: (id: number) => ['exams', 'detail', id] as const,
|
||||
classes: () => ['exams', 'classes'] as const,
|
||||
},
|
||||
operationLogs: {
|
||||
all: ['operation-logs'] as const,
|
||||
list: (params: { page: number; pageSize: number; module?: string; dateRange?: unknown }) =>
|
||||
['operation-logs', params] as const,
|
||||
},
|
||||
attendance: {
|
||||
all: ['attendance'] as const,
|
||||
workspace: () => ['attendance', 'workspace'] as const,
|
||||
syncStatus: () => ['attendance', 'sync-status'] as const,
|
||||
schedules: (classId: number, date: string) => ['attendance', 'schedules', classId, date] as const,
|
||||
meta: {
|
||||
periods: () => ['attendance', 'meta', 'periods'] as const,
|
||||
classes: () => ['attendance', 'meta', 'classes'] as const,
|
||||
alerts: () => ['attendance', 'meta', 'alerts'] as const,
|
||||
},
|
||||
},
|
||||
attendanceDevices: {
|
||||
all: ['attendance-devices'] as const,
|
||||
},
|
||||
dashboard: {
|
||||
all: ['dashboard'] as const,
|
||||
summary: (period: unknown) => ['dashboard', period] as const,
|
||||
},
|
||||
integration: {
|
||||
config: () => ['integration', 'config'] as const,
|
||||
},
|
||||
sync: {
|
||||
jinshujuRules: () => ['sync', 'jinshuju', 'rules'] as const,
|
||||
},
|
||||
archive: {
|
||||
detail: (studentId: number) => ['archive', studentId] as const,
|
||||
},
|
||||
ai: {
|
||||
config: () => ['ai', 'config'] as const,
|
||||
},
|
||||
} as const;
|
||||
|
||||
export type QueryKeys = typeof queryKeys;
|
||||
@@ -64,6 +64,14 @@ export const AiChatSidebar: React.FC<AiChatSidebarProps> = ({
|
||||
}
|
||||
/>
|
||||
{loadingList && <Spin className="ai-chat-sidebar__loading" />}
|
||||
{!loadingList && !selectionMode && conversationCount === 0 ? (
|
||||
<div className="ai-chat-sidebar__empty">
|
||||
<Typography.Text type="secondary">暂无会话</Typography.Text>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
点击「新对话」开始提问
|
||||
</Typography.Text>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="ai-chat-sidebar__footer">
|
||||
{selectionMode ? (
|
||||
<>
|
||||
|
||||
@@ -20,8 +20,11 @@ import {
|
||||
} from 'antd';
|
||||
import type { MenuProps } from 'antd';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { useUserStore } from '../../store/user/userStore';
|
||||
import { usePermissionStore } from '../../store/permission/permissionStore';
|
||||
import { aiChatApi, conversationStreamUrl } from './api';
|
||||
import { GongxueAiChatProvider } from './provider';
|
||||
import { welcomeDescription, workflowPromptExamples } from './welcomeCopy';
|
||||
import { ImportWizardModal } from '../ImportWizard/ImportWizardModal';
|
||||
import type { AiSkill } from './types';
|
||||
import { useAiChatMessageActions } from './useAiChatMessageActions';
|
||||
@@ -51,6 +54,8 @@ interface AiChatDrawerProps {
|
||||
|
||||
const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequestingChange }) => {
|
||||
const { modal } = App.useApp();
|
||||
const user = useUserStore((state) => state.user);
|
||||
const permissions = usePermissionStore((state) => state.permissions);
|
||||
const screens = Grid.useBreakpoint();
|
||||
const isMobile = !screens.sm;
|
||||
const [loadingList, setLoadingList] = useState(false);
|
||||
@@ -184,11 +189,32 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
||||
|
||||
const switchConversation = useCallback(
|
||||
(key: string) => {
|
||||
discardPendingAttachments();
|
||||
if (isMobile) setSidebarOpen(false);
|
||||
setActiveConversationKey(key);
|
||||
const doSwitch = () => {
|
||||
discardPendingAttachments();
|
||||
if (isMobile) setSidebarOpen(false);
|
||||
setActiveConversationKey(key);
|
||||
};
|
||||
// 有待发送的附件时先确认,避免静默删除已上传文件
|
||||
if (uploadItems.length > 0) {
|
||||
modal.confirm({
|
||||
title: '切换会话将丢弃未发送的附件',
|
||||
content: `当前有 ${uploadItems.length} 个已上传但未发送的附件,切换会话后将被删除,此操作不可恢复。`,
|
||||
okText: '切换并丢弃',
|
||||
okButtonProps: { danger: true },
|
||||
cancelText: '留在当前会话',
|
||||
onOk: doSwitch,
|
||||
});
|
||||
return;
|
||||
}
|
||||
doSwitch();
|
||||
},
|
||||
[discardPendingAttachments, isMobile, setActiveConversationKey],
|
||||
[
|
||||
discardPendingAttachments,
|
||||
isMobile,
|
||||
modal,
|
||||
setActiveConversationKey,
|
||||
uploadItems.length,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(
|
||||
@@ -524,12 +550,21 @@ const AiChatDrawer: React.FC<AiChatDrawerProps> = ({ open, onClose, onRequesting
|
||||
title="你好,我是恭学 AI 助手"
|
||||
description={
|
||||
lockedSkill?.description ||
|
||||
'我会在你的权限范围内查询数据,也能通过表单帮你录入学生等业务信息。'
|
||||
welcomeDescription(user?.roles ?? [], permissions)
|
||||
}
|
||||
/>
|
||||
<Prompts
|
||||
title="你可以这样问"
|
||||
items={promptItems}
|
||||
items={[
|
||||
...promptItems,
|
||||
...workflowPromptExamples(user?.roles ?? [], permissions).map(
|
||||
(item, index) => ({
|
||||
key: `workflow-${index}`,
|
||||
label: item.label,
|
||||
description: item.description,
|
||||
}),
|
||||
),
|
||||
]}
|
||||
wrap
|
||||
onItemClick={({ data }) => submit(String(data.label || ''))}
|
||||
/>
|
||||
|
||||
@@ -13,9 +13,12 @@ import type { ThoughtChainItemType } from '@ant-design/x';
|
||||
import XMarkdown, { type ComponentProps } from '@ant-design/x-markdown';
|
||||
import { Alert, Button, Flex, Input, Space, Typography } from 'antd';
|
||||
import { useUserStore } from '../../store/user/userStore';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { DynamicChart } from './DynamicChart';
|
||||
import { DynamicForm } from './DynamicForm';
|
||||
import { DynamicReview } from './DynamicReview';
|
||||
import { deriveCharts, deriveForms, deriveReviews } from './uiArtifacts';
|
||||
import { ArtifactErrorBoundary } from './ArtifactErrorBoundary';
|
||||
import { LiteCodeHighlighter } from './LiteCodeHighlighter';
|
||||
import { LiteMermaid } from './LiteMermaid';
|
||||
import type {
|
||||
@@ -41,7 +44,6 @@ const toolLabels: Record<string, string> = {
|
||||
search_bills: '查询账单',
|
||||
get_dashboard_stats: '读取经营概览',
|
||||
render_form: '生成表单',
|
||||
render_review: '生成导入预览',
|
||||
render_chart: '生成图表',
|
||||
start_import_wizard: '生成导入向导',
|
||||
create_student: '创建学生',
|
||||
@@ -103,6 +105,24 @@ async function openSourceUrl(item: { url?: string }): Promise<void> {
|
||||
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 60_000);
|
||||
}
|
||||
|
||||
/** 打开附件,失败时给出明确提示(避免「点了没反应」) */
|
||||
async function handleOpenAttachment(attachment: AiAttachment): Promise<void> {
|
||||
try {
|
||||
await openAttachment(attachment);
|
||||
} catch (error: unknown) {
|
||||
message.error(error instanceof Error ? error.message : '附件打开失败,请重试');
|
||||
}
|
||||
}
|
||||
|
||||
/** 打出来源链接,失败时给出明确提示 */
|
||||
async function handleOpenSource(item: { url?: string }): Promise<void> {
|
||||
try {
|
||||
await openSourceUrl(item);
|
||||
} catch (error: unknown) {
|
||||
message.error(error instanceof Error ? error.message : '来源打开失败,请重试');
|
||||
}
|
||||
}
|
||||
|
||||
function ToolChain({ tools }: { tools: AiToolRun[] }) {
|
||||
const items = useMemo<ThoughtChainItemType[]>(
|
||||
() =>
|
||||
@@ -206,6 +226,11 @@ export const AiMessageContent: React.FC<AiMessageContentProps> = ({
|
||||
const streaming = status === 'loading' || status === 'updating';
|
||||
const formSubmission = message.metadata?.a2uiSubmit;
|
||||
const reviewSubmission = message.metadata?.a2uiReviewSubmit;
|
||||
// 统一 artifact 优先,历史消息(仅 legacy 字段)回退
|
||||
const forms = deriveForms(message).length > 0 ? deriveForms(message) : (message.forms ?? []);
|
||||
const reviews =
|
||||
deriveReviews(message).length > 0 ? deriveReviews(message) : (message.reviews ?? []);
|
||||
const charts = deriveCharts(message).length > 0 ? deriveCharts(message) : (message.charts ?? []);
|
||||
const sourceMeta = message.metadata?.a2uiSources;
|
||||
const sourceItems = Array.isArray(sourceMeta)
|
||||
? sourceMeta
|
||||
@@ -227,7 +252,7 @@ export const AiMessageContent: React.FC<AiMessageContentProps> = ({
|
||||
byte={attachment.size}
|
||||
size="small"
|
||||
icon={attachmentIcon(attachment)}
|
||||
onClick={() => void openAttachment(attachment)}
|
||||
onClick={() => void handleOpenAttachment(attachment)}
|
||||
/>
|
||||
));
|
||||
|
||||
@@ -351,30 +376,34 @@ export const AiMessageContent: React.FC<AiMessageContentProps> = ({
|
||||
<Sources
|
||||
items={sourceItems}
|
||||
title="引用来源"
|
||||
onClick={(item) => void openSourceUrl(item as { url?: string })}
|
||||
onClick={(item) => void handleOpenSource(item as { url?: string })}
|
||||
/>
|
||||
)}
|
||||
{(message.forms ?? []).map((form) => (
|
||||
<DynamicForm
|
||||
key={form.id}
|
||||
form={form}
|
||||
disabled={streaming}
|
||||
onSubmit={(values) => onSubmitForm?.(form, values)}
|
||||
/>
|
||||
{(forms ?? []).map((form) => (
|
||||
<ArtifactErrorBoundary key={form.id} title="表单">
|
||||
<DynamicForm
|
||||
form={form}
|
||||
disabled={streaming}
|
||||
onSubmit={(values) => onSubmitForm?.(form, values)}
|
||||
/>
|
||||
</ArtifactErrorBoundary>
|
||||
))}
|
||||
{(message.reviews ?? []).map((review: AiReviewSchema) => (
|
||||
<DynamicReview
|
||||
key={review.id}
|
||||
review={review}
|
||||
messageId={typeof message.id === 'number' ? message.id : undefined}
|
||||
disabled={streaming}
|
||||
onSubmit={(reviewId) => onSubmitReview?.(reviewId, review.title)}
|
||||
onConfirmStep={onConfirmReviewStep}
|
||||
onConfirmGroup={onConfirmReviewGroup}
|
||||
/>
|
||||
{(reviews ?? []).map((review: AiReviewSchema) => (
|
||||
<ArtifactErrorBoundary key={review.id} title="导入预览">
|
||||
<DynamicReview
|
||||
review={review}
|
||||
messageId={typeof message.id === 'number' ? message.id : undefined}
|
||||
disabled={streaming}
|
||||
onSubmit={(reviewId) => onSubmitReview?.(reviewId, review.title)}
|
||||
onConfirmStep={onConfirmReviewStep}
|
||||
onConfirmGroup={onConfirmReviewGroup}
|
||||
/>
|
||||
</ArtifactErrorBoundary>
|
||||
))}
|
||||
{(message.charts ?? []).map((chart: AiChartSchema) => (
|
||||
<DynamicChart key={chart.id} chart={chart} />
|
||||
{(charts ?? []).map((chart: AiChartSchema) => (
|
||||
<ArtifactErrorBoundary key={chart.id} title="图表">
|
||||
<DynamicChart chart={chart} />
|
||||
</ArtifactErrorBoundary>
|
||||
))}
|
||||
{message.error && <Alert type="error" showIcon title={message.error} />}
|
||||
{message.cancelled && <Typography.Text type="secondary">回答已停止</Typography.Text>}
|
||||
|
||||
47
apps/admin/src/components/AiChat/ArtifactErrorBoundary.tsx
Normal file
47
apps/admin/src/components/AiChat/ArtifactErrorBoundary.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import React from 'react';
|
||||
import { Alert } from 'antd';
|
||||
|
||||
interface ArtifactErrorBoundaryProps {
|
||||
children: React.ReactNode;
|
||||
/** 制品标题(用于错误提示文案) */
|
||||
title?: string;
|
||||
}
|
||||
|
||||
interface ArtifactErrorBoundaryState {
|
||||
hasError: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A2UI 制品(表单/审查卡/图表)渲染错误兜底:单个制品渲染失败只降级为
|
||||
* 错误占位卡片,不影响同气泡内其他消息与制品。
|
||||
*/
|
||||
export class ArtifactErrorBoundary extends React.Component<
|
||||
ArtifactErrorBoundaryProps,
|
||||
ArtifactErrorBoundaryState
|
||||
> {
|
||||
state: ArtifactErrorBoundaryState = { hasError: false };
|
||||
|
||||
static getDerivedStateFromError(): ArtifactErrorBoundaryState {
|
||||
return { hasError: true };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: React.ErrorInfo): void {
|
||||
console.error('[ArtifactErrorBoundary] 制品渲染异常:', error, info.componentStack);
|
||||
}
|
||||
|
||||
render(): React.ReactNode {
|
||||
if (this.state.hasError) {
|
||||
return (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
title={this.props.title ? `${this.props.title}渲染失败` : '此内容渲染失败'}
|
||||
description="请让 AI 重新生成,或刷新后重试。"
|
||||
/>
|
||||
);
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
export default ArtifactErrorBoundary;
|
||||
@@ -1,10 +1,12 @@
|
||||
import React, { lazy, Suspense, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import React, { lazy, Suspense, useEffect, useMemo, useState } from 'react';
|
||||
import { saveAs } from 'file-saver';
|
||||
import { XCard, registerCatalog, type XAgentCommand_v0_9 } from '@ant-design/x-card';
|
||||
import { Button, Spin, Tag, Tooltip, Typography } from 'antd';
|
||||
import { DownloadOutlined } from '@ant-design/icons';
|
||||
import type { EChartsType } from 'echarts/core';
|
||||
import type { EChartsOption } from '../../components/ECharts';
|
||||
import type { AiChartSchema } from './types';
|
||||
import { useXCardSurface } from './useSubmissionState';
|
||||
|
||||
// echarts 体积较大,仅在真正渲染图表时加载,避免打开 AI 抽屉就拉取
|
||||
const ReactECharts = lazy(() => import('../../components/ECharts'));
|
||||
@@ -199,9 +201,35 @@ interface ChartPreviewProps {
|
||||
* renders an ECharts option built from it.
|
||||
*/
|
||||
const ChartPreview: React.FC<ChartPreviewProps> = ({ chart }) => {
|
||||
const option = useMemo<EChartsOption>(() => (chart ? buildOption(chart) : {}), [chart]);
|
||||
// 空/无数据时先短路,避免 buildOption 在空数据集上执行
|
||||
const hasData = !!chart && !!chart.rows && chart.rows.length > 0;
|
||||
const option = useMemo<EChartsOption>(
|
||||
() => (chart && hasData ? buildOption(chart) : {}),
|
||||
[chart, hasData],
|
||||
);
|
||||
const [instance, setInstance] = useState<EChartsType | null>(null);
|
||||
if (!chart) return null;
|
||||
// 空数据集:渲染明确占位,而不是一张空白图
|
||||
if (!hasData) {
|
||||
return (
|
||||
<div className="ai-chat-chart-card">
|
||||
<div className="ai-chat-chart-card__header">
|
||||
<Typography.Text strong>{chart.title}</Typography.Text>
|
||||
<Tag color="blue">{CHART_TYPE_LABELS[chart.chartType] ?? chart.chartType}</Tag>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
height: 120,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
<Typography.Text type="secondary">暂无数据</Typography.Text>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const downloadImage = () => {
|
||||
if (!instance) return;
|
||||
@@ -210,12 +238,7 @@ const ChartPreview: React.FC<ChartPreviewProps> = ({ chart }) => {
|
||||
pixelRatio: 2,
|
||||
backgroundColor: '#fff',
|
||||
});
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `${chart.title || '图表'}.png`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
saveAs(url, `${chart.title || '图表'}.png`);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -254,46 +277,39 @@ export interface DynamicChartProps {
|
||||
* so history replays identically.
|
||||
*/
|
||||
export const DynamicChart: React.FC<DynamicChartProps> = ({ chart }) => {
|
||||
const commandsRef = useRef<XAgentCommand_v0_9[]>([]);
|
||||
const [commands, setCommands] = useState<XAgentCommand_v0_9[]>([]);
|
||||
const idRef = useRef<string>('');
|
||||
const sid = surfaceId(chart.id);
|
||||
const { commands, pushCommands } = useXCardSurface(sid);
|
||||
|
||||
useEffect(() => {
|
||||
const sid = surfaceId(chart.id);
|
||||
if (idRef.current !== sid) {
|
||||
commandsRef.current = [];
|
||||
idRef.current = sid;
|
||||
}
|
||||
const cmds = commandsRef.current;
|
||||
if (cmds.length === 0) {
|
||||
cmds.push({
|
||||
const cmds: XAgentCommand_v0_9[] = [
|
||||
{
|
||||
version: 'v0.9',
|
||||
createSurface: { surfaceId: sid, catalogId: CHART_CATALOG_ID },
|
||||
});
|
||||
}
|
||||
cmds.push({
|
||||
version: 'v0.9',
|
||||
updateDataModel: {
|
||||
surfaceId: sid,
|
||||
path: '/chart',
|
||||
value: chart,
|
||||
},
|
||||
});
|
||||
cmds.push({
|
||||
version: 'v0.9',
|
||||
updateComponents: {
|
||||
surfaceId: sid,
|
||||
components: [
|
||||
{
|
||||
id: 'root',
|
||||
component: 'ChartPreview',
|
||||
chart: { path: '/chart' },
|
||||
},
|
||||
],
|
||||
{
|
||||
version: 'v0.9',
|
||||
updateDataModel: {
|
||||
surfaceId: sid,
|
||||
path: '/chart',
|
||||
value: chart,
|
||||
},
|
||||
},
|
||||
});
|
||||
setCommands([...cmds]);
|
||||
}, [chart]);
|
||||
{
|
||||
version: 'v0.9',
|
||||
updateComponents: {
|
||||
surfaceId: sid,
|
||||
components: [
|
||||
{
|
||||
id: 'root',
|
||||
component: 'ChartPreview',
|
||||
chart: { path: '/chart' },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
];
|
||||
pushCommands(cmds);
|
||||
}, [chart, pushCommands, sid]);
|
||||
|
||||
return (
|
||||
<div className="ai-chat-chart">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import React, { useEffect, useMemo } from 'react';
|
||||
import {
|
||||
XCard,
|
||||
registerCatalog,
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
} from 'antd';
|
||||
import dayjs from 'dayjs';
|
||||
import type { AiFormField, AiFormSchema } from './types';
|
||||
import { useSubmissionState, useXCardSurface } from './useSubmissionState';
|
||||
|
||||
const FORM_CATALOG_ID = 'gongxue-form-catalog';
|
||||
|
||||
@@ -179,63 +180,46 @@ export interface DynamicFormProps {
|
||||
* success/failure/loading transitions are pushed as incremental commands.
|
||||
*/
|
||||
export const DynamicForm: React.FC<DynamicFormProps> = ({ form, disabled, onSubmit }) => {
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [submitted, setSubmitted] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const commandsRef = useRef<XAgentCommand_v0_9[]>([]);
|
||||
const [commands, setCommands] = useState<XAgentCommand_v0_9[]>([]);
|
||||
const idRef = useRef<string>('');
|
||||
const sid = surfaceId(form.id);
|
||||
const { submitting, submitted, error, run } = useSubmissionState();
|
||||
const { commands, pushCommands } = useXCardSurface(sid);
|
||||
|
||||
useEffect(() => {
|
||||
const sid = surfaceId(form.id);
|
||||
if (idRef.current !== sid) {
|
||||
commandsRef.current = [];
|
||||
idRef.current = sid;
|
||||
}
|
||||
const cmds = commandsRef.current;
|
||||
if (cmds.length === 0) {
|
||||
cmds.push({
|
||||
const cmds: XAgentCommand_v0_9[] = [
|
||||
{
|
||||
version: 'v0.9',
|
||||
createSurface: { surfaceId: sid, catalogId: FORM_CATALOG_ID },
|
||||
});
|
||||
}
|
||||
cmds.push({
|
||||
version: 'v0.9',
|
||||
updateDataModel: {
|
||||
surfaceId: sid,
|
||||
path: '/form',
|
||||
value: { ...form, submitting, submitted, error },
|
||||
},
|
||||
});
|
||||
cmds.push({
|
||||
version: 'v0.9',
|
||||
updateComponents: {
|
||||
surfaceId: sid,
|
||||
components: [
|
||||
{
|
||||
id: 'root',
|
||||
component: 'FormPreview',
|
||||
form: { path: '/form' },
|
||||
disabled: Boolean(disabled),
|
||||
},
|
||||
],
|
||||
{
|
||||
version: 'v0.9',
|
||||
updateDataModel: {
|
||||
surfaceId: sid,
|
||||
path: '/form',
|
||||
value: { ...form, submitting, submitted, error },
|
||||
},
|
||||
},
|
||||
});
|
||||
setCommands([...cmds]);
|
||||
}, [disabled, error, form, submitted, submitting]);
|
||||
{
|
||||
version: 'v0.9',
|
||||
updateComponents: {
|
||||
surfaceId: sid,
|
||||
components: [
|
||||
{
|
||||
id: 'root',
|
||||
component: 'FormPreview',
|
||||
form: { path: '/form' },
|
||||
disabled: Boolean(disabled),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
];
|
||||
pushCommands(cmds);
|
||||
}, [disabled, error, form, pushCommands, sid, submitted, submitting]);
|
||||
|
||||
const handleSubmit = async (values: Record<string, unknown>) => {
|
||||
if (submitting) return;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const handleSubmit = (values: Record<string, unknown>) => {
|
||||
void run(async () => {
|
||||
await onSubmit(values);
|
||||
setSubmitted(true);
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : '提交失败,请稍后重试');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleAction = (payload: ActionPayload) => {
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
type TableProps,
|
||||
} from 'antd';
|
||||
import type { AiReviewRow, AiReviewSchema, AiReviewSection, AiReviewSectionType } from './types';
|
||||
import { useXCardSurface } from './useSubmissionState';
|
||||
import {
|
||||
GROUP_STATUS_LABELS,
|
||||
SECTION_ORDER,
|
||||
@@ -430,9 +431,8 @@ export const DynamicReview: React.FC<DynamicReviewProps> = ({
|
||||
activeTypeRef.current = activeType;
|
||||
const [localReview, setLocalReview] = useState<AiReviewSchema>(review);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const commandsRef = useRef<XAgentCommand_v0_9[]>([]);
|
||||
const [commands, setCommands] = useState<XAgentCommand_v0_9[]>([]);
|
||||
const idRef = useRef<string>('');
|
||||
const sid = surfaceId(localReview.id);
|
||||
const { commands, pushCommands } = useXCardSurface(sid);
|
||||
|
||||
useEffect(() => {
|
||||
setLocalReview(review);
|
||||
@@ -455,55 +455,51 @@ export const DynamicReview: React.FC<DynamicReviewProps> = ({
|
||||
}, [review]);
|
||||
|
||||
useEffect(() => {
|
||||
const sid = surfaceId(localReview.id);
|
||||
if (idRef.current !== sid) {
|
||||
commandsRef.current = [];
|
||||
idRef.current = sid;
|
||||
}
|
||||
const cmds = commandsRef.current;
|
||||
if (cmds.length === 0) {
|
||||
cmds.push({
|
||||
const cmds: XAgentCommand_v0_9[] = [
|
||||
{
|
||||
version: 'v0.9',
|
||||
createSurface: { surfaceId: sid, catalogId: REVIEW_CATALOG_ID },
|
||||
});
|
||||
}
|
||||
cmds.push({
|
||||
version: 'v0.9',
|
||||
updateDataModel: {
|
||||
surfaceId: sid,
|
||||
path: '/review',
|
||||
value: {
|
||||
...localReview,
|
||||
submitting,
|
||||
activeKey,
|
||||
activeType,
|
||||
submittingKey,
|
||||
submittingGroup,
|
||||
error,
|
||||
},
|
||||
{
|
||||
version: 'v0.9',
|
||||
updateDataModel: {
|
||||
surfaceId: sid,
|
||||
path: '/review',
|
||||
value: {
|
||||
...localReview,
|
||||
submitting,
|
||||
activeKey,
|
||||
activeType,
|
||||
submittingKey,
|
||||
submittingGroup,
|
||||
error,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
cmds.push({
|
||||
version: 'v0.9',
|
||||
updateComponents: {
|
||||
surfaceId: sid,
|
||||
components: [
|
||||
{
|
||||
id: 'root',
|
||||
component: 'ReviewPreview',
|
||||
review: { path: '/review' },
|
||||
disabled: Boolean(disabled),
|
||||
},
|
||||
],
|
||||
{
|
||||
version: 'v0.9',
|
||||
updateComponents: {
|
||||
surfaceId: sid,
|
||||
components: [
|
||||
{
|
||||
id: 'root',
|
||||
component: 'ReviewPreview',
|
||||
review: { path: '/review' },
|
||||
disabled: Boolean(disabled),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
setCommands([...cmds]);
|
||||
];
|
||||
pushCommands(cmds);
|
||||
}, [
|
||||
activeKey,
|
||||
activeType,
|
||||
disabled,
|
||||
error,
|
||||
localReview,
|
||||
pushCommands,
|
||||
sid,
|
||||
submitting,
|
||||
submittingGroup,
|
||||
submittingKey,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useIsMounted } from 'usehooks-ts';
|
||||
|
||||
interface LiteMermaidProps {
|
||||
children: string;
|
||||
@@ -11,9 +12,9 @@ interface LiteMermaidProps {
|
||||
export function LiteMermaid({ children }: LiteMermaidProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const isMounted = useIsMounted();
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const container = containerRef.current;
|
||||
if (!container) return;
|
||||
|
||||
@@ -22,21 +23,17 @@ export function LiteMermaid({ children }: LiteMermaidProps) {
|
||||
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) {
|
||||
if (isMounted()) {
|
||||
const doc = new DOMParser().parseFromString(svg, 'image/svg+xml');
|
||||
container.replaceChildren(doc.documentElement);
|
||||
setError(null);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!cancelled) {
|
||||
if (isMounted()) {
|
||||
setError(e instanceof Error ? e.message : '图表渲染失败');
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [children]);
|
||||
|
||||
if (error) {
|
||||
|
||||
@@ -30,12 +30,19 @@ export const aiChatApi = {
|
||||
`${basePath}/${conversationId}/messages/${messageId}`,
|
||||
)
|
||||
).data,
|
||||
uploadAttachment: async (file: File): Promise<AiAttachment> => {
|
||||
uploadAttachment: async (
|
||||
file: File,
|
||||
onProgress?: (percent: number) => void,
|
||||
): Promise<AiAttachment> => {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
return (
|
||||
await api.post<AiApiResponse<AiAttachment>>('/ai/chat/attachments', form, {
|
||||
timeout: 120_000,
|
||||
onUploadProgress: (event) => {
|
||||
if (!onProgress || !event.total) return;
|
||||
onProgress(Math.min(Math.round((event.loaded / event.total) * 100), 100));
|
||||
},
|
||||
})
|
||||
).data;
|
||||
},
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Bubble } from '@ant-design/x';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { aiBubbleRoles, conversationStatusMeta } from './AiChatDrawer';
|
||||
import { AiMessageContent } from './AiMessageContent';
|
||||
import { ArtifactErrorBoundary } from './ArtifactErrorBoundary';
|
||||
import { DynamicChart } from './DynamicChart';
|
||||
import { DynamicForm } from './DynamicForm';
|
||||
import { DynamicReview } from './DynamicReview';
|
||||
@@ -504,4 +505,49 @@ describe('AI chat bubble rendering', () => {
|
||||
expect(container.textContent).toContain(label);
|
||||
expect(container.querySelector('.ai-chat-chart-card canvas')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('renders an empty-data placeholder instead of a blank chart', async () => {
|
||||
const chart: AiChartSchema = {
|
||||
id: 'chart-empty',
|
||||
title: '空图表',
|
||||
chartType: 'bar',
|
||||
columns: [{ key: 'name', title: '名称' }],
|
||||
rows: [],
|
||||
};
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root?.render(<DynamicChart chart={chart} />);
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain('空图表');
|
||||
expect(container.textContent).toContain('暂无数据');
|
||||
expect(container.querySelector('canvas')).toBeNull();
|
||||
});
|
||||
|
||||
it('degrades a single failing artifact to an error card without crashing the bubble', async () => {
|
||||
const Bomb: React.FC = () => {
|
||||
throw new Error('boom');
|
||||
};
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
|
||||
// 用无错误边界的兄弟节点 + 错误边界内的炸弹组件验证隔离
|
||||
await act(async () => {
|
||||
root?.render(
|
||||
<div>
|
||||
<div className="neighbor">正常内容</div>
|
||||
<ArtifactErrorBoundary title="表单">
|
||||
<Bomb />
|
||||
</ArtifactErrorBoundary>
|
||||
</div>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(container.querySelector('.neighbor')?.textContent).toContain('正常内容');
|
||||
expect(container.textContent).toContain('表单渲染失败');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -78,7 +78,7 @@ describe('AI chat history mapper', () => {
|
||||
expect(mapped.message.forms?.[0]).toMatchObject({ id: 'form-9', title: '新增学生' });
|
||||
});
|
||||
|
||||
it('restores uiArtifacts from message metadata and derives legacy lists', () => {
|
||||
it('restores uiArtifacts from message metadata (统一协议)', () => {
|
||||
const mapped = mapHistoryMessage({
|
||||
id: 8,
|
||||
role: 'assistant',
|
||||
@@ -120,8 +120,14 @@ describe('AI chat history mapper', () => {
|
||||
});
|
||||
|
||||
expect(mapped.message.uiArtifacts).toHaveLength(2);
|
||||
expect(mapped.message.forms?.[0]).toMatchObject({ id: 'form-10', status: 'submitted' });
|
||||
expect(mapped.message.reviews?.[0]).toMatchObject({ id: 'review-10', status: 'expired' });
|
||||
expect(mapped.message.uiArtifacts?.[0].payload).toMatchObject({
|
||||
id: 'form-10',
|
||||
status: 'submitted',
|
||||
});
|
||||
expect(mapped.message.uiArtifacts?.[1].payload).toMatchObject({
|
||||
id: 'review-10',
|
||||
status: 'expired',
|
||||
});
|
||||
});
|
||||
|
||||
it('restores a persisted A2UI review from message metadata', () => {
|
||||
|
||||
@@ -123,38 +123,7 @@ describe('AI chat SSE message reducer', () => {
|
||||
expect(message.id).toBe(9);
|
||||
});
|
||||
|
||||
it('merges ui.form events into the assistant message by id', () => {
|
||||
const form = {
|
||||
id: 'form-1',
|
||||
title: '新增学生',
|
||||
submitLabel: '提交创建',
|
||||
fields: [
|
||||
{ name: 'name', label: '姓名', type: 'input', required: true },
|
||||
{ name: 'gender', label: '性别', type: 'select', options: [{ label: '男', value: 'male' }] },
|
||||
],
|
||||
};
|
||||
let message = reduceAiSseMessage(undefined, {
|
||||
event: 'ui.form',
|
||||
data: JSON.stringify({ messageId: 8, form }),
|
||||
});
|
||||
message = reduceAiSseMessage(message, {
|
||||
event: 'ui.form',
|
||||
data: JSON.stringify({ messageId: 8, form: { ...form, id: 'form-1' } }),
|
||||
});
|
||||
message = reduceAiSseMessage(message, {
|
||||
event: 'ui.form',
|
||||
data: JSON.stringify({
|
||||
messageId: 8,
|
||||
form: { id: 'form-2', title: '入住确认', fields: [] },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(message.forms).toHaveLength(2);
|
||||
expect(message.forms?.[0]).toMatchObject({ id: 'form-1', title: '新增学生' });
|
||||
expect(message.forms?.[1]).toMatchObject({ id: 'form-2' });
|
||||
});
|
||||
|
||||
it('merges ui.artifact events into uiArtifacts and legacy lists by id', () => {
|
||||
it('merges ui.artifact events into uiArtifacts by id', () => {
|
||||
let message = reduceAiSseMessage(undefined, {
|
||||
event: 'ui.artifact',
|
||||
data: JSON.stringify({
|
||||
@@ -185,8 +154,8 @@ describe('AI chat SSE message reducer', () => {
|
||||
});
|
||||
|
||||
expect(message.uiArtifacts).toHaveLength(2);
|
||||
expect(message.forms?.[0]).toMatchObject({ id: 'form-1', title: '新增学生' });
|
||||
expect(message.reviews?.[0]).toMatchObject({ id: 'review-1', status: 'expired' });
|
||||
expect(message.uiArtifacts?.[0].payload).toMatchObject({ id: 'form-1', title: '新增学生' });
|
||||
expect(message.uiArtifacts?.[1].payload).toMatchObject({ id: 'review-1', status: 'expired' });
|
||||
});
|
||||
|
||||
|
||||
@@ -213,43 +182,6 @@ describe('AI chat SSE message reducer', () => {
|
||||
expect(message.forms?.[0].id).toBe('form-9');
|
||||
});
|
||||
|
||||
it('merges ui.review events into the assistant message and updates by id', () => {
|
||||
const review = {
|
||||
id: 'review-1',
|
||||
title: '开学导入',
|
||||
summary: '来自报名 Excel',
|
||||
status: 'pending',
|
||||
sections: [
|
||||
{
|
||||
key: 'students',
|
||||
type: 'students',
|
||||
title: '学生',
|
||||
kind: 'table',
|
||||
columns: [
|
||||
{ key: 'name', title: '姓名' },
|
||||
{ key: 'phone', title: '手机号' },
|
||||
],
|
||||
rows: [{ name: '张三', phone: '13800138000' }],
|
||||
issues: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
let message = reduceAiSseMessage(undefined, {
|
||||
event: 'ui.review',
|
||||
data: JSON.stringify({ messageId: 8, review }),
|
||||
});
|
||||
message = reduceAiSseMessage(message, {
|
||||
event: 'ui.review',
|
||||
data: JSON.stringify({
|
||||
messageId: 8,
|
||||
review: { ...review, status: 'submitted', resultSummary: '{"students":{"created":1}}' },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(message.reviews).toHaveLength(1);
|
||||
expect(message.reviews?.[0]).toMatchObject({ id: 'review-1', status: 'submitted' });
|
||||
});
|
||||
|
||||
it('shows model retrying state and clears it when content starts', () => {
|
||||
let message = reduceAiSseMessage(undefined, {
|
||||
event: 'model.retrying',
|
||||
@@ -301,37 +233,6 @@ describe('AI chat SSE message reducer', () => {
|
||||
expect(message.reviews?.[0]).toMatchObject({ id: 'review-9', title: '批量导入' });
|
||||
});
|
||||
|
||||
it('merges ui.chart events into the assistant message by id', () => {
|
||||
const chart = {
|
||||
id: 'chart-1',
|
||||
title: '各班级人数',
|
||||
chartType: 'bar',
|
||||
columns: [
|
||||
{ key: 'className', title: '班级' },
|
||||
{ key: 'count', title: '人数' },
|
||||
],
|
||||
rows: [
|
||||
{ className: '一班', count: 20 },
|
||||
{ className: '二班', count: 15 },
|
||||
],
|
||||
};
|
||||
let message = reduceAiSseMessage(undefined, {
|
||||
event: 'ui.chart',
|
||||
data: JSON.stringify({ messageId: 8, chart }),
|
||||
});
|
||||
message = reduceAiSseMessage(message, {
|
||||
event: 'ui.chart',
|
||||
data: JSON.stringify({
|
||||
messageId: 8,
|
||||
chart: { ...chart, id: 'chart-2', title: '女生人数' },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(message.charts).toHaveLength(2);
|
||||
expect(message.charts?.[0]).toMatchObject({ id: 'chart-1', chartType: 'bar' });
|
||||
expect(message.charts?.[1]).toMatchObject({ id: 'chart-2' });
|
||||
});
|
||||
|
||||
it('restores persisted charts from message.completed metadata', () => {
|
||||
const message = reduceAiSseMessage(undefined, {
|
||||
event: 'message.completed',
|
||||
@@ -459,15 +360,16 @@ describe('AI chat SSE message reducer', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('routes submit-time ui.review to the original message instead of the streaming one', () => {
|
||||
it('routes ui.artifact targeting another message to the external handler', () => {
|
||||
const provider = new GongxueAiChatProvider('http://x/api/ai/chat/conversations/3/stream');
|
||||
const onExternalReview = vi.fn();
|
||||
provider.onExternalReview = onExternalReview;
|
||||
const review = {
|
||||
id: 'review-1',
|
||||
title: '批量导入',
|
||||
const onExternalArtifact = vi.fn();
|
||||
provider.onExternalArtifact = onExternalArtifact;
|
||||
const artifact = {
|
||||
id: 'artifact-1',
|
||||
type: 'form',
|
||||
status: 'submitted',
|
||||
sections: [],
|
||||
messageId: 12,
|
||||
payload: { id: 'form-1', title: '批量导入', status: 'submitted' },
|
||||
};
|
||||
const origin = {
|
||||
id: 13,
|
||||
@@ -476,31 +378,37 @@ describe('AI chat SSE message reducer', () => {
|
||||
reasoningContent: '',
|
||||
toolRuns: [],
|
||||
attachments: [],
|
||||
reviews: [],
|
||||
uiArtifacts: [],
|
||||
};
|
||||
const next = provider.transformMessage({
|
||||
originMessage: origin,
|
||||
chunk: { event: 'ui.review', data: JSON.stringify({ messageId: 12, review }) },
|
||||
chunk: { event: 'ui.artifact', data: JSON.stringify({ messageId: 12, artifact }) },
|
||||
status: 'updating',
|
||||
chunks: [],
|
||||
responseHeaders: {} as Headers,
|
||||
});
|
||||
|
||||
expect(onExternalReview).toHaveBeenCalledWith(12, review);
|
||||
expect(onExternalArtifact).toHaveBeenCalledWith(12, artifact);
|
||||
expect(next).toBe(origin);
|
||||
expect(next.reviews ?? []).toHaveLength(0);
|
||||
expect(next.uiArtifacts ?? []).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('routes ui.review without an origin message to the external handler', () => {
|
||||
it('routes ui.artifact without an origin message to the external handler', () => {
|
||||
const provider = new GongxueAiChatProvider('http://x/api/ai/chat/conversations/3/stream');
|
||||
const onExternalReview = vi.fn();
|
||||
provider.onExternalReview = onExternalReview;
|
||||
const onExternalArtifact = vi.fn();
|
||||
provider.onExternalArtifact = onExternalArtifact;
|
||||
const next = provider.transformMessage({
|
||||
chunk: {
|
||||
event: 'ui.review',
|
||||
event: 'ui.artifact',
|
||||
data: JSON.stringify({
|
||||
messageId: 12,
|
||||
review: { id: 'review-1', title: '批量导入', status: 'submitted', sections: [] },
|
||||
artifact: {
|
||||
id: 'artifact-1',
|
||||
type: 'review',
|
||||
status: 'submitted',
|
||||
messageId: 12,
|
||||
payload: { id: 'review-1', title: '批量导入', status: 'submitted', sections: [] },
|
||||
},
|
||||
}),
|
||||
},
|
||||
status: 'updating',
|
||||
@@ -508,11 +416,11 @@ describe('AI chat SSE message reducer', () => {
|
||||
responseHeaders: {} as Headers,
|
||||
});
|
||||
|
||||
expect(onExternalReview).toHaveBeenCalledWith(
|
||||
expect(onExternalArtifact).toHaveBeenCalledWith(
|
||||
12,
|
||||
expect.objectContaining({ id: 'review-1' }),
|
||||
expect.objectContaining({ id: 'artifact-1' }),
|
||||
);
|
||||
expect(next.reviews ?? []).toHaveLength(0);
|
||||
expect(next.uiArtifacts ?? []).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('tolerates non-JSON event data', () => {
|
||||
|
||||
@@ -80,6 +80,8 @@ export async function authenticatedFetch(
|
||||
}
|
||||
const response = await fetch(requestInput, { ...requestInit, headers });
|
||||
if (response.status === 401) {
|
||||
// 提示由登录页读取展示:直接弹 toast 会被跳转销毁
|
||||
sessionStorage.setItem('login_expired_hint', '1');
|
||||
useUserStore.getState().logout();
|
||||
usePermissionStore.getState().clearPermissions();
|
||||
window.location.href = '/login';
|
||||
@@ -189,32 +191,6 @@ export class GongxueAiChatProvider extends AbstractChatProvider<
|
||||
this.onExternalArtifact?.(payload.messageId, payload.artifact);
|
||||
return info.originMessage ?? emptyAssistant();
|
||||
}
|
||||
if (
|
||||
event === 'ui.form' &&
|
||||
payload.form &&
|
||||
typeof payload.messageId === 'number' &&
|
||||
info.originMessage?.id !== payload.messageId
|
||||
) {
|
||||
this.onExternalArtifact?.(payload.messageId, {
|
||||
id: payload.form.id,
|
||||
type: 'form',
|
||||
status: payload.form.status ?? 'pending',
|
||||
messageId: payload.messageId,
|
||||
payload: payload.form,
|
||||
});
|
||||
return info.originMessage ?? emptyAssistant();
|
||||
}
|
||||
if (
|
||||
event === 'ui.review' &&
|
||||
payload.review &&
|
||||
typeof payload.messageId === 'number' &&
|
||||
info.originMessage?.id !== payload.messageId
|
||||
) {
|
||||
// The submitted review belongs to the original assistant message;
|
||||
// do not merge it into the message currently being streamed.
|
||||
this.onExternalReview?.(payload.messageId, payload.review);
|
||||
return info.originMessage ?? emptyAssistant();
|
||||
}
|
||||
return reduceAiSseMessage(info.originMessage, info.chunk);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import type {
|
||||
AiSseChunk,
|
||||
AiToolRun,
|
||||
} from './types';
|
||||
import { mergeArtifactIntoMessage, mergeById, mergeForms } from './uiArtifacts';
|
||||
import { mergeArtifactIntoMessage, mergeById } from './uiArtifacts';
|
||||
|
||||
export interface AiSsePayload {
|
||||
messageId?: number;
|
||||
@@ -25,10 +25,7 @@ export interface AiSsePayload {
|
||||
summary?: string | null;
|
||||
durationMs?: number | null;
|
||||
attachment?: AiAttachment;
|
||||
form?: AiFormSchema;
|
||||
artifact?: AiArtifactSchema;
|
||||
review?: AiReviewSchema;
|
||||
chart?: AiChartSchema;
|
||||
wizard?: unknown;
|
||||
retry?: AiModelRetryInfo;
|
||||
message?:
|
||||
@@ -109,20 +106,21 @@ 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(
|
||||
// 历史消息兼容:老数据只有 metadata.a2uiForm/a2uiReview/a2uiChart,
|
||||
// 恢复为 legacy 字段供渲染层在 uiArtifacts 为空时回退使用。
|
||||
message.forms = mergeById<AiFormSchema>(
|
||||
message.forms,
|
||||
(nested.metadata?.a2uiForm as AiFormSchema | undefined) ?? payload.form,
|
||||
nested.metadata?.a2uiForm as AiFormSchema | undefined,
|
||||
);
|
||||
message.reviews = mergeById<AiReviewSchema>(
|
||||
message.reviews,
|
||||
(nested.metadata?.a2uiReview as AiReviewSchema | undefined) ?? payload.review,
|
||||
nested.metadata?.a2uiReview as AiReviewSchema | undefined,
|
||||
);
|
||||
message.charts = mergeById<AiChartSchema>(
|
||||
message.charts,
|
||||
(nested.metadata?.a2uiChart as AiChartSchema | AiChartSchema[] | undefined) ?? payload.chart,
|
||||
nested.metadata?.a2uiChart as AiChartSchema | AiChartSchema[] | undefined,
|
||||
);
|
||||
const artifacts = nested.metadata?.uiArtifacts;
|
||||
if (Array.isArray(artifacts)) {
|
||||
@@ -150,7 +148,7 @@ export function reduceAiSseMessage(
|
||||
message.reasoningContent = nested?.reasoningContent ?? message.reasoningContent;
|
||||
message.toolRuns = normalizeToolRuns(nested?.toolRuns, message.toolRuns);
|
||||
message.attachments = nested?.attachments ?? message.attachments;
|
||||
applyMessagePayload(message, nested, payload);
|
||||
applyMessagePayload(message, nested);
|
||||
} else if (event === 'reasoning.delta') {
|
||||
message.retrying = null;
|
||||
message.reasoningContent += payload.delta ?? payload.reasoningContent ?? '';
|
||||
@@ -159,13 +157,8 @@ export function reduceAiSseMessage(
|
||||
message.content += payload.delta ?? payload.content ?? '';
|
||||
} else if (event === 'model.retrying' && payload.retry) {
|
||||
message.retrying = payload.retry;
|
||||
} else if (event === 'ui.form' && payload.form) {
|
||||
message.forms = mergeForms(message.forms, payload.form);
|
||||
} else if (event === 'ui.review' && payload.review) {
|
||||
message.reviews = mergeById<AiReviewSchema>(message.reviews, payload.review);
|
||||
} else if (event === 'ui.chart' && payload.chart) {
|
||||
message.charts = mergeById<AiChartSchema>(message.charts, payload.chart);
|
||||
} else if (event === 'ui.artifact' && payload.artifact) {
|
||||
// 统一 artifact 事件;legacy 列表由渲染层从 uiArtifacts 派生。
|
||||
mergeArtifactIntoMessage(message, payload.artifact);
|
||||
} else if (event === 'ui.import_wizard' && payload.wizard) {
|
||||
message.metadata = { ...message.metadata, a2uiImportWizard: payload.wizard };
|
||||
@@ -187,7 +180,7 @@ export function reduceAiSseMessage(
|
||||
nested?.reasoningContent ?? payload.reasoningContent ?? message.reasoningContent;
|
||||
message.toolRuns = normalizeToolRuns(nested?.toolRuns, message.toolRuns);
|
||||
message.attachments = nested?.attachments ?? message.attachments;
|
||||
applyMessagePayload(message, nested, payload);
|
||||
applyMessagePayload(message, nested);
|
||||
message.retrying = null;
|
||||
} else if (event === 'message.cancelled') {
|
||||
message.id = payload.messageId ?? message.id;
|
||||
|
||||
@@ -138,6 +138,16 @@
|
||||
inset: 68px 0 auto;
|
||||
}
|
||||
|
||||
.ai-chat-sidebar__empty {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
padding: 24px 16px;
|
||||
}
|
||||
|
||||
.ai-chat-sidebar__footer {
|
||||
flex: none;
|
||||
display: flex;
|
||||
|
||||
@@ -171,9 +171,13 @@ export interface AiChatMessage {
|
||||
reasoningContent: string;
|
||||
toolRuns: AiToolRun[];
|
||||
attachments: AiAttachment[];
|
||||
/** @deprecated 仅历史消息兼容读取(metadata.a2uiForm);新数据统一走 uiArtifacts */
|
||||
forms?: AiFormSchema[];
|
||||
/** @deprecated 仅历史消息兼容读取(metadata.a2uiReview);新数据统一走 uiArtifacts */
|
||||
reviews?: AiReviewSchema[];
|
||||
/** @deprecated 仅历史消息兼容读取(metadata.a2uiChart);新数据统一走 uiArtifacts */
|
||||
charts?: AiChartSchema[];
|
||||
/** 统一 A2UI 制品协议(唯一事实源) */
|
||||
uiArtifacts?: AiArtifactSchema[];
|
||||
replyToMessageId?: number | null;
|
||||
metadata?: Record<string, unknown> | null;
|
||||
|
||||
@@ -25,43 +25,44 @@ export function mergeById<T extends { id: string }>(
|
||||
return next;
|
||||
}
|
||||
|
||||
export function mergeForms(
|
||||
current: AiFormSchema[] | undefined,
|
||||
incoming: AiFormSchema | AiFormSchema[] | undefined,
|
||||
): AiFormSchema[] {
|
||||
const items = Array.isArray(incoming) ? incoming : incoming ? [incoming] : [];
|
||||
if (!items.length) return current ?? [];
|
||||
const next = [...(current ?? [])];
|
||||
for (const item of items) {
|
||||
if (item && typeof item === 'object' && !next.some((existing) => existing.id === item.id)) {
|
||||
next.push(item);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function payloadOf(artifact: AiArtifactSchema): unknown {
|
||||
return artifact.payload && typeof artifact.payload === 'object' ? artifact.payload : {};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将统一 artifact 归入 uiArtifacts,并按类型派发到 legacy 列表。
|
||||
* payload 来自服务端契约(表单/审阅/图表/预检/向导),按类型做单次断言。
|
||||
* 将统一 artifact 归入 uiArtifacts。
|
||||
*
|
||||
* 注意:不再派发到 legacy 列表(forms/reviews/charts)——渲染层从
|
||||
* uiArtifacts 派生,legacy 字段仅保留给历史消息(metadata 中只有
|
||||
* a2uiForm/a2uiReview/a2uiChart 的老数据)作兼容读取。
|
||||
*/
|
||||
export function mergeArtifactIntoMessage(
|
||||
message: AiChatMessage,
|
||||
artifact: AiArtifactSchema,
|
||||
): AiChatMessage {
|
||||
message.uiArtifacts = mergeById<AiArtifactSchema>(message.uiArtifacts, artifact);
|
||||
const payload = payloadOf(artifact);
|
||||
if (artifact.type === 'form') {
|
||||
message.forms = mergeForms(message.forms, payload as AiFormSchema);
|
||||
} else if (artifact.type === 'review') {
|
||||
message.reviews = mergeById<AiReviewSchema>(message.reviews, payload as AiReviewSchema);
|
||||
} else if (artifact.type === 'chart') {
|
||||
message.charts = mergeById<AiChartSchema>(message.charts, payload as AiChartSchema);
|
||||
} else if (artifact.type === 'import_wizard') {
|
||||
message.metadata = { ...message.metadata, a2uiImportWizard: payload };
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 uiArtifacts 派生 legacy 列表(渲染用)。
|
||||
* 仅当 message 上没有显式 legacy 数据(历史消息)时,渲染层回退到 message.forms 等。
|
||||
*/
|
||||
export function deriveForms(message: AiChatMessage): AiFormSchema[] {
|
||||
return (message.uiArtifacts ?? [])
|
||||
.filter((artifact) => artifact.type === 'form')
|
||||
.map((artifact) => artifact.payload)
|
||||
.filter((payload): payload is AiFormSchema => Boolean(payload) && typeof payload === 'object');
|
||||
}
|
||||
|
||||
export function deriveReviews(message: AiChatMessage): AiReviewSchema[] {
|
||||
return (message.uiArtifacts ?? [])
|
||||
.filter((artifact) => artifact.type === 'review')
|
||||
.map((artifact) => artifact.payload)
|
||||
.filter(
|
||||
(payload): payload is AiReviewSchema => Boolean(payload) && typeof payload === 'object',
|
||||
);
|
||||
}
|
||||
|
||||
export function deriveCharts(message: AiChatMessage): AiChartSchema[] {
|
||||
return (message.uiArtifacts ?? [])
|
||||
.filter((artifact) => artifact.type === 'chart')
|
||||
.map((artifact) => artifact.payload)
|
||||
.filter((payload): payload is AiChartSchema => Boolean(payload) && typeof payload === 'object');
|
||||
}
|
||||
|
||||
@@ -296,30 +296,46 @@ export function useAiChatMessageActions({
|
||||
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);
|
||||
const followingCount = index >= 0 ? messagesRef.current.length - index - 1 : 0;
|
||||
const doEdit = () => {
|
||||
setMessage(messageInfo.id, (info) => ({
|
||||
message: {
|
||||
...info.message,
|
||||
content,
|
||||
metadata: { ...info.message.metadata, edited: true },
|
||||
},
|
||||
}));
|
||||
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,
|
||||
});
|
||||
};
|
||||
if (followingCount > 0) {
|
||||
modal.confirm({
|
||||
title: '编辑消息将删除后续内容',
|
||||
content: `编辑这条消息会删除其后的 ${followingCount} 条消息并重新生成回答,此操作不可恢复。`,
|
||||
okText: '继续编辑',
|
||||
cancelText: '取消',
|
||||
onOk: doEdit,
|
||||
});
|
||||
return;
|
||||
}
|
||||
requestWithStatus({
|
||||
message: content,
|
||||
attachmentIds: [],
|
||||
skillKey: activeConversation?.lockedSkillKey ?? null,
|
||||
clientRequestId: crypto.randomUUID(),
|
||||
reasoningEffort: deepThinking ? 'high' : null,
|
||||
editMessageId: messageId,
|
||||
});
|
||||
doEdit();
|
||||
},
|
||||
[
|
||||
activeConversation?.lockedSkillKey,
|
||||
activeId,
|
||||
deepThinking,
|
||||
modal,
|
||||
removeMessage,
|
||||
requestWithStatus,
|
||||
setMessage,
|
||||
@@ -327,8 +343,9 @@ export function useAiChatMessageActions({
|
||||
);
|
||||
|
||||
const submitForm = useCallback(
|
||||
(form: AiFormSchema, values: Record<string, unknown>) => {
|
||||
if (!activeId || isRequesting) return;
|
||||
async (form: AiFormSchema, values: Record<string, unknown>): Promise<void> => {
|
||||
if (!activeId) throw new Error('当前会话不可用,请稍后重试');
|
||||
if (isRequesting) throw new Error('请等待当前 AI 回复完成后再提交表单');
|
||||
requestWithStatus({
|
||||
message: '表单提交',
|
||||
attachmentIds: [],
|
||||
@@ -342,8 +359,9 @@ export function useAiChatMessageActions({
|
||||
);
|
||||
|
||||
const submitReview = useCallback(
|
||||
(reviewId: string, reviewTitle?: string) => {
|
||||
if (!activeId || isRequesting) return;
|
||||
async (reviewId: string, reviewTitle?: string): Promise<void> => {
|
||||
if (!activeId) throw new Error('当前会话不可用,请稍后重试');
|
||||
if (isRequesting) throw new Error('请等待当前 AI 回复完成后再确认导入');
|
||||
requestWithStatus({
|
||||
message: '确认批量导入',
|
||||
attachmentIds: [],
|
||||
@@ -424,7 +442,9 @@ export function useAiChatMessageActions({
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const uploaded = await aiChatApi.uploadAttachment(file);
|
||||
const uploaded = await aiChatApi.uploadAttachment(file, (percent) => {
|
||||
options.onProgress?.({ percent });
|
||||
});
|
||||
setAttachments((items) => [...items, uploaded]);
|
||||
options.onSuccess?.(uploaded, file);
|
||||
} catch (error) {
|
||||
|
||||
161
apps/admin/src/components/AiChat/useSubmissionState.test.tsx
Normal file
161
apps/admin/src/components/AiChat/useSubmissionState.test.tsx
Normal file
@@ -0,0 +1,161 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { useSubmissionState, useXCardSurface } from './useSubmissionState';
|
||||
|
||||
// 项目未安装 @testing-library/react,用 createRoot + harness 组件暴露 hook API
|
||||
let container: HTMLDivElement | null = null;
|
||||
let root: ReturnType<typeof createRoot> | null = null;
|
||||
let api: ReturnType<typeof useSubmissionState> | null = null;
|
||||
let surface: ReturnType<typeof useXCardSurface> | null = null;
|
||||
let surfaceId = 'surface-test';
|
||||
|
||||
function Harness() {
|
||||
api = useSubmissionState();
|
||||
surface = useXCardSurface(surfaceId);
|
||||
return null;
|
||||
}
|
||||
|
||||
function renderHarness(): void {
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(<Harness />);
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
if (root) await act(async () => root?.unmount());
|
||||
container?.remove();
|
||||
root = null;
|
||||
container = null;
|
||||
api = null;
|
||||
surface = null;
|
||||
surfaceId = 'surface-test';
|
||||
});
|
||||
|
||||
describe('useSubmissionState', () => {
|
||||
it('tracks submitting during the task and succeeds afterwards', async () => {
|
||||
renderHarness();
|
||||
let resolveTask: () => void = () => undefined;
|
||||
const task = () =>
|
||||
new Promise<void>((resolve) => {
|
||||
resolveTask = resolve;
|
||||
});
|
||||
|
||||
let promise: Promise<void> | undefined;
|
||||
act(() => {
|
||||
promise = api?.run(task);
|
||||
});
|
||||
expect(api?.submitting).toBe(true);
|
||||
expect(api?.error).toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
resolveTask();
|
||||
await promise;
|
||||
});
|
||||
expect(api?.submitting).toBe(false);
|
||||
expect(api?.submitted).toBe(true);
|
||||
expect(api?.error).toBeNull();
|
||||
});
|
||||
|
||||
it('captures the error message and keeps submitted false on failure', async () => {
|
||||
renderHarness();
|
||||
const failing = () => {
|
||||
throw new Error('接口 500');
|
||||
};
|
||||
|
||||
await act(async () => {
|
||||
await api?.run(failing);
|
||||
});
|
||||
expect(api?.submitting).toBe(false);
|
||||
expect(api?.submitted).toBe(false);
|
||||
expect(api?.error).toBe('接口 500');
|
||||
});
|
||||
|
||||
it('normalizes non-Error rejections to a generic message', async () => {
|
||||
renderHarness();
|
||||
const failing = () => Promise.reject('raw string');
|
||||
|
||||
await act(async () => {
|
||||
await api?.run(failing);
|
||||
});
|
||||
expect(api?.error).toBe('提交失败,请稍后重试');
|
||||
});
|
||||
|
||||
it('ignores re-entrant calls while a task is in flight', async () => {
|
||||
renderHarness();
|
||||
let resolveTask: () => void = () => undefined;
|
||||
const task = () =>
|
||||
new Promise<void>((resolve) => {
|
||||
resolveTask = resolve;
|
||||
});
|
||||
let secondRan = false;
|
||||
|
||||
act(() => {
|
||||
void api?.run(task);
|
||||
void api?.run(() => {
|
||||
secondRan = true;
|
||||
});
|
||||
});
|
||||
expect(secondRan).toBe(false);
|
||||
|
||||
await act(async () => {
|
||||
resolveTask();
|
||||
});
|
||||
expect(api?.submitted).toBe(true);
|
||||
});
|
||||
|
||||
it('reset clears submitted and error states', async () => {
|
||||
renderHarness();
|
||||
await act(async () => {
|
||||
await api?.run(() => undefined);
|
||||
});
|
||||
expect(api?.submitted).toBe(true);
|
||||
|
||||
act(() => {
|
||||
api?.reset();
|
||||
});
|
||||
expect(api?.submitted).toBe(false);
|
||||
expect(api?.error).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('useXCardSurface', () => {
|
||||
it('deduplicates createSurface commands for the same surface id', () => {
|
||||
renderHarness();
|
||||
act(() => {
|
||||
surface?.pushCommands([
|
||||
{ version: 'v0.9', createSurface: { surfaceId: 'surface-test', catalogId: 'catalog' } },
|
||||
{ version: 'v0.9', updateDataModel: { surfaceId: 'surface-test', path: '/x', value: 1 } },
|
||||
]);
|
||||
surface?.pushCommands([
|
||||
{ version: 'v0.9', createSurface: { surfaceId: 'surface-test', catalogId: 'catalog' } },
|
||||
{ version: 'v0.9', updateDataModel: { surfaceId: 'surface-test', path: '/x', value: 2 } },
|
||||
]);
|
||||
});
|
||||
const createCommands = surface?.commands.filter((command) => 'createSurface' in command);
|
||||
expect(createCommands).toHaveLength(1);
|
||||
expect(surface?.commands).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('resets the command stream when the surface id changes', () => {
|
||||
renderHarness();
|
||||
act(() => {
|
||||
surface?.pushCommands([
|
||||
{ version: 'v0.9', createSurface: { surfaceId: 'surface-test', catalogId: 'c' } },
|
||||
]);
|
||||
});
|
||||
expect(surface?.commands).toHaveLength(1);
|
||||
|
||||
surfaceId = 'surface-other';
|
||||
act(() => {
|
||||
root?.render(<Harness />);
|
||||
surface?.pushCommands([
|
||||
{ version: 'v0.9', createSurface: { surfaceId: 'surface-other', catalogId: 'c' } },
|
||||
]);
|
||||
});
|
||||
expect(surface?.commands).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
89
apps/admin/src/components/AiChat/useSubmissionState.ts
Normal file
89
apps/admin/src/components/AiChat/useSubmissionState.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
import { useLayoutEffect } from 'react';
|
||||
import type { XAgentCommand_v0_9 } from '@ant-design/x-card';
|
||||
|
||||
/**
|
||||
* 提交状态管理:收敛 DynamicForm / DynamicReview 中重复的
|
||||
* submitting / submitted / error 状态与「防重复提交 + 失败可重试」逻辑。
|
||||
*
|
||||
* 用法:
|
||||
* const { submitting, submitted, error, run } = useSubmissionState();
|
||||
* const handleSubmit = (values) => run(async () => { await onSubmit(values); });
|
||||
*/
|
||||
export function useSubmissionState() {
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [submitted, setSubmitted] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const submittingRef = useRef(false);
|
||||
|
||||
const run = useCallback(async (task: () => Promise<void> | void) => {
|
||||
if (submittingRef.current) return;
|
||||
submittingRef.current = true;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await task();
|
||||
setSubmitted(true);
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : '提交失败,请稍后重试');
|
||||
} finally {
|
||||
submittingRef.current = false;
|
||||
setSubmitting(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setSubmitted(false);
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
return { submitting, submitted, error, run, reset };
|
||||
}
|
||||
|
||||
/**
|
||||
* A2UI surface 的 XCard commands 增量更新生命周期:
|
||||
* 每个 surface 只创建一次,后续通过 updateDataModel / updateComponents 增量更新。
|
||||
*
|
||||
* 用法:
|
||||
* const { pushCommands } = useXCardSurface(surfaceId);
|
||||
* useEffect(() => {
|
||||
* pushCommands([
|
||||
* { version: 'v0.9', createSurface: { surfaceId, catalogId } },
|
||||
* { version: 'v0.9', updateDataModel: { surfaceId, path: '/x', value } },
|
||||
* { version: 'v0.9', updateComponents: { surfaceId, components } },
|
||||
* ]);
|
||||
* }, [value]);
|
||||
*/
|
||||
export function useXCardSurface(surfaceId: string) {
|
||||
const commandsRef = useRef<XAgentCommand_v0_9[]>([]);
|
||||
const [commands, setCommands] = useState<XAgentCommand_v0_9[]>([]);
|
||||
const idRef = useRef<string>('');
|
||||
|
||||
const pushCommands = useCallback(
|
||||
(cmds: XAgentCommand_v0_9[]) => {
|
||||
if (cmds.length === 0) return;
|
||||
// 同一 surface 的 createSurface 命令只允许出现一次,自动去重
|
||||
const hasSurface = commandsRef.current.some(
|
||||
(c) => 'createSurface' in c && c.createSurface.surfaceId === surfaceId,
|
||||
);
|
||||
const filtered = hasSurface
|
||||
? cmds.filter((c) => !('createSurface' in c))
|
||||
: cmds;
|
||||
commandsRef.current = [...commandsRef.current, ...filtered];
|
||||
setCommands([...commandsRef.current]);
|
||||
},
|
||||
[surfaceId],
|
||||
);
|
||||
|
||||
const surfaceKey = surfaceId;
|
||||
// 渲染期保持纯函数:ref 变更放到 layout effect 里
|
||||
useLayoutEffect(() => {
|
||||
if (idRef.current !== surfaceKey) {
|
||||
// 组件复用到新 surface 时,清空历史命令重新初始化
|
||||
commandsRef.current = [];
|
||||
idRef.current = surfaceKey;
|
||||
}
|
||||
}, [surfaceKey]);
|
||||
|
||||
return { commands, pushCommands };
|
||||
}
|
||||
69
apps/admin/src/components/AiChat/welcomeCopy.ts
Normal file
69
apps/admin/src/components/AiChat/welcomeCopy.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { getRoleDomains } from '../../auth/menu-policy';
|
||||
|
||||
/**
|
||||
* 按用户角色生成 AI 助手欢迎语,引导用户使用与其岗位匹配的业务闭环。
|
||||
* 优先级:教师 > 住宿运营 > 教务 > 教室运营 > 系统/超管 > 兜底。
|
||||
*/
|
||||
export function welcomeDescription(roles: readonly string[], permissions: readonly string[]): string {
|
||||
const domains = getRoleDomains(roles, permissions);
|
||||
|
||||
if (domains.has('teacher')) {
|
||||
return '我可以帮你查询今日课程、拉取钉钉考勤、查看排课。课程开始后就能看到打卡结果。';
|
||||
}
|
||||
if (domains.has('accommodation')) {
|
||||
return '我可以帮你完成「宿舍档案 → 学生 → 入住 → 费用 → 账单」的住宿计费闭环,先告诉我你手头有什么数据。';
|
||||
}
|
||||
if (domains.has('academic')) {
|
||||
return '我可以帮你完成「学生档案 → 分班 → 排课 → 考勤」的教学闭环,支持 Excel 批量导入与预览确认。';
|
||||
}
|
||||
if (domains.has('classroom')) {
|
||||
return '我可以帮你管理教室排期与租赁订单,查询占用情况,避免时间冲突。';
|
||||
}
|
||||
if (domains.has('system') || domains.has('super')) {
|
||||
return '我是恭学 AI 助手。我可以查询经营数据、管理业务数据、生成批量导入预览——所有写操作都会先经你确认。';
|
||||
}
|
||||
return '我会在你的权限范围内查询数据,也能通过表单帮你录入学生等业务信息。';
|
||||
}
|
||||
|
||||
/**
|
||||
* 与角色匹配的业务闭环引导示例(用于 Prompts 建议话术)。
|
||||
* 返回空数组表示当前角色无匹配示例。
|
||||
*/
|
||||
export function workflowPromptExamples(
|
||||
roles: readonly string[],
|
||||
permissions: readonly string[],
|
||||
): { label: string; description: string }[] {
|
||||
const domains = getRoleDomains(roles, permissions);
|
||||
const examples: { label: string; description: string }[] = [];
|
||||
|
||||
if (domains.has('academic')) {
|
||||
examples.push(
|
||||
{ label: '帮我从 Excel 导入学生并完成分班', description: '教学闭环' },
|
||||
{ label: '查一下这周有哪些班级还没排课', description: '教学闭环' },
|
||||
);
|
||||
}
|
||||
if (domains.has('accommodation')) {
|
||||
examples.push(
|
||||
{ label: '帮我从 Excel 导入学生并安排入住', description: '住宿计费闭环' },
|
||||
{ label: '查一下本月还没生成账单的入住学生', description: '住宿计费闭环' },
|
||||
);
|
||||
}
|
||||
if (domains.has('classroom')) {
|
||||
examples.push(
|
||||
{ label: '查一下这间教室本周的占用情况', description: '教室运营' },
|
||||
);
|
||||
}
|
||||
if (domains.has('teacher')) {
|
||||
examples.push(
|
||||
{ label: '今天我有哪几节课?', description: '今日教学' },
|
||||
);
|
||||
}
|
||||
if (domains.has('system') || domains.has('super')) {
|
||||
examples.push(
|
||||
{ label: '看一下本月的经营概览', description: '数据面板' },
|
||||
{ label: '帮我梳理宿舍计费的完整流程', description: '业务流程' },
|
||||
);
|
||||
}
|
||||
|
||||
return examples;
|
||||
}
|
||||
52
apps/admin/src/components/AppErrorBoundary.tsx
Normal file
52
apps/admin/src/components/AppErrorBoundary.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
import React from 'react';
|
||||
import { Button, Result } from 'antd';
|
||||
|
||||
interface AppErrorBoundaryProps {
|
||||
children: React.ReactNode;
|
||||
/** 自定义降级内容;不传则使用默认错误卡片 */
|
||||
fallback?: React.ReactNode;
|
||||
}
|
||||
|
||||
interface AppErrorBoundaryState {
|
||||
hasError: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 全局渲染错误兜底:捕获子树内的渲染异常,展示可恢复的错误卡片,
|
||||
* 避免单个页面/组件崩溃导致整个应用白屏。
|
||||
*/
|
||||
export class AppErrorBoundary extends React.Component<
|
||||
AppErrorBoundaryProps,
|
||||
AppErrorBoundaryState
|
||||
> {
|
||||
state: AppErrorBoundaryState = { hasError: false };
|
||||
|
||||
static getDerivedStateFromError(): AppErrorBoundaryState {
|
||||
return { hasError: true };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: React.ErrorInfo): void {
|
||||
console.error('[AppErrorBoundary] 渲染异常:', error, info.componentStack);
|
||||
}
|
||||
|
||||
render(): React.ReactNode {
|
||||
if (this.state.hasError) {
|
||||
if (this.props.fallback) return this.props.fallback;
|
||||
return (
|
||||
<Result
|
||||
status="error"
|
||||
title="页面出现异常"
|
||||
subTitle="请刷新页面重试;若问题持续,请联系管理员。"
|
||||
extra={
|
||||
<Button type="primary" onClick={() => window.location.reload()}>
|
||||
刷新页面
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
export default AppErrorBoundary;
|
||||
41
apps/admin/src/components/BackTop.tsx
Normal file
41
apps/admin/src/components/BackTop.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Button, Tooltip } from 'antd';
|
||||
import { VerticalAlignTopOutlined } from '@ant-design/icons';
|
||||
import { useEventCallback, useEventListener } from 'usehooks-ts';
|
||||
|
||||
/**
|
||||
* 全局「回到顶部」浮动按钮:长列表滚动超过 400px 后出现。
|
||||
* 尊重系统「减少动态效果」偏好,平滑滚动仅在未开启该偏好时使用。
|
||||
*/
|
||||
export const BackTop: React.FC<{ threshold?: number }> = ({ threshold = 400 }) => {
|
||||
const [visible, setVisible] = useState(false);
|
||||
const updateVisible = useEventCallback(() => setVisible(window.scrollY > threshold));
|
||||
|
||||
useEffect(() => {
|
||||
updateVisible();
|
||||
}, [threshold, updateVisible]);
|
||||
|
||||
useEventListener('scroll', updateVisible, undefined, { passive: true });
|
||||
|
||||
if (!visible) return null;
|
||||
|
||||
const scrollToTop = () => {
|
||||
const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
window.scrollTo({ top: 0, behavior: reduceMotion ? 'auto' : 'smooth' });
|
||||
};
|
||||
|
||||
return (
|
||||
<Tooltip title="回到顶部">
|
||||
<Button
|
||||
type="primary"
|
||||
shape="circle"
|
||||
icon={<VerticalAlignTopOutlined />}
|
||||
aria-label="回到顶部"
|
||||
onClick={scrollToTop}
|
||||
style={{ position: 'fixed', right: 24, bottom: 48, zIndex: 1000 }}
|
||||
/>
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
|
||||
export default BackTop;
|
||||
@@ -3,6 +3,8 @@ import { DatePicker, Input, InputNumber, Select, Spin, Tooltip } from 'antd';
|
||||
import dayjs, { type Dayjs } from 'dayjs';
|
||||
import equal from 'fast-deep-equal';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
import { useTimeout } from 'usehooks-ts';
|
||||
import { useEditableCellStore } from '../../store/editableCell/editableCellStore';
|
||||
import { message } from '../../ui/app-message';
|
||||
import './style.css';
|
||||
import { getErrorMessage } from '../../utils/error';
|
||||
@@ -39,9 +41,6 @@ export interface EditableCellProps<Value = unknown> {
|
||||
onSave: (value: Value) => Promise<void>;
|
||||
}
|
||||
|
||||
let activeCell: { id: string; save: () => Promise<boolean> } | null = null;
|
||||
let replayingOutsideAction = false;
|
||||
|
||||
export function normalizeEditableValue(value: unknown, editor: EditableCellEditor) {
|
||||
if (editor === 'date') return value ? dayjs(value as string) : null;
|
||||
if (editor === 'date-range')
|
||||
@@ -102,6 +101,10 @@ const EditableCell = <Value,>({
|
||||
const [draft, setDraft] = useState<unknown>(() =>
|
||||
normalizeEditableValue(formatValue ? formatValue(value) : value, editor),
|
||||
);
|
||||
// 保存成功后短暂显示「撤销」入口:记录保存前的序列化旧值
|
||||
const [undoMeta, setUndoMeta] = useState<{ serializedPrevious: unknown } | null>(null);
|
||||
// 撤销入口 6 秒后自动消失;useTimeout 在 undoMeta 置空/组件卸载时自动清理
|
||||
useTimeout(() => setUndoMeta(null), undoMeta ? 6_000 : null);
|
||||
const enabled = !disabled && (!permission || hasPermission(permission));
|
||||
|
||||
const original = useMemo(
|
||||
@@ -115,7 +118,7 @@ const EditableCell = <Value,>({
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
setDraft(normalizeEditableValue(formatValue ? formatValue(value) : value, editor));
|
||||
if (activeCell?.id === idRef.current) activeCell = null;
|
||||
useEditableCellStore.getState().clearIfActive(idRef.current);
|
||||
setEditing(false);
|
||||
}, [editor, formatValue, value]);
|
||||
|
||||
@@ -128,15 +131,18 @@ const EditableCell = <Value,>({
|
||||
return false;
|
||||
}
|
||||
if (editableValuesEqual(serialized, original)) {
|
||||
if (activeCell?.id === idRef.current) activeCell = null;
|
||||
useEditableCellStore.getState().clearIfActive(idRef.current);
|
||||
setEditing(false);
|
||||
return true;
|
||||
}
|
||||
setSaving(true);
|
||||
const previousValue = original;
|
||||
try {
|
||||
await onSave(parseValue ? parseValue(serialized) : (serialized as Value));
|
||||
if (activeCell?.id === idRef.current) activeCell = null;
|
||||
useEditableCellStore.getState().clearIfActive(idRef.current);
|
||||
setEditing(false);
|
||||
// 提供 6 秒内的撤销入口(把旧值再保存一次);useTimeout 负责到时自动清除
|
||||
setUndoMeta({ serializedPrevious: previousValue });
|
||||
return true;
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error, '保存失败'));
|
||||
@@ -152,16 +158,14 @@ const EditableCell = <Value,>({
|
||||
|
||||
useEffect(() => {
|
||||
const cellId = idRef.current;
|
||||
if (editing && activeCell?.id === cellId) activeCell.save = save;
|
||||
return () => {
|
||||
if (activeCell?.id === cellId) activeCell = null;
|
||||
};
|
||||
if (editing) useEditableCellStore.getState().updateActiveSave(cellId, save);
|
||||
return () => useEditableCellStore.getState().clearIfActive(cellId);
|
||||
}, [editing, save]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!editing) return;
|
||||
const onPointerDown = (event: PointerEvent) => {
|
||||
if (replayingOutsideAction) return;
|
||||
if (useEditableCellStore.getState().replayingOutsideAction) return;
|
||||
if (rootRef.current?.contains(event.target as Node) || isEditorOverlay(event.target)) return;
|
||||
const actionTarget =
|
||||
event.target instanceof Element
|
||||
@@ -177,10 +181,10 @@ const EditableCell = <Value,>({
|
||||
event.stopPropagation();
|
||||
void save().then((saved) => {
|
||||
if (!saved) return;
|
||||
replayingOutsideAction = true;
|
||||
useEditableCellStore.getState().setReplayingOutsideAction(true);
|
||||
actionTarget.click();
|
||||
queueMicrotask(() => {
|
||||
replayingOutsideAction = false;
|
||||
useEditableCellStore.getState().setReplayingOutsideAction(false);
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -192,15 +196,33 @@ const EditableCell = <Value,>({
|
||||
|
||||
const beginEdit = async () => {
|
||||
if (!enabled || saving) return;
|
||||
const { activeCell } = useEditableCellStore.getState();
|
||||
if (activeCell && activeCell.id !== idRef.current) {
|
||||
const saved = await activeCell.save();
|
||||
if (!saved) return;
|
||||
}
|
||||
activeCell = { id: idRef.current, save };
|
||||
useEditableCellStore.getState().setActiveCell({ id: idRef.current, save });
|
||||
// 重新进入编辑时清掉上一次的撤销入口
|
||||
setUndoMeta(null);
|
||||
setDraft(normalizeEditableValue(formatValue ? formatValue(value) : value, editor));
|
||||
setEditing(true);
|
||||
};
|
||||
|
||||
const handleUndo = async () => {
|
||||
if (!undoMeta) return;
|
||||
setUndoMeta(null);
|
||||
try {
|
||||
await onSave(
|
||||
parseValue
|
||||
? parseValue(undoMeta.serializedPrevious)
|
||||
: (undoMeta.serializedPrevious as Value),
|
||||
);
|
||||
message.success('已撤销修改');
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error, '撤销失败'));
|
||||
}
|
||||
};
|
||||
|
||||
const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (event.pointerType !== 'touch' || editing) return;
|
||||
touchStartRef.current = {
|
||||
@@ -241,6 +263,16 @@ const EditableCell = <Value,>({
|
||||
return;
|
||||
}
|
||||
if (event.key === 'Enter' && editor !== 'textarea') {
|
||||
// 这些编辑器会自己消费 Enter(确认/提交选中值),不重复触发单元格保存
|
||||
if (
|
||||
editor === 'select' ||
|
||||
editor === 'multi-select' ||
|
||||
editor === 'tags' ||
|
||||
editor === 'date' ||
|
||||
editor === 'date-range'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
await save();
|
||||
return;
|
||||
@@ -308,7 +340,23 @@ const EditableCell = <Value,>({
|
||||
{editing ? (
|
||||
<Spin spinning={saving}>{control}</Spin>
|
||||
) : (
|
||||
<Tooltip title={enabled ? '双击编辑,触屏双击编辑' : undefined}>{children}</Tooltip>
|
||||
<Tooltip title={enabled ? '双击编辑,触屏双击编辑' : undefined}>
|
||||
<span className="editable-cell-display">
|
||||
{children}
|
||||
{undoMeta ? (
|
||||
<button
|
||||
type="button"
|
||||
className="editable-cell-undo"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
void handleUndo();
|
||||
}}
|
||||
>
|
||||
撤销
|
||||
</button>
|
||||
) : null}
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -5,6 +5,29 @@
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.editable-cell-display {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.editable-cell-undo {
|
||||
flex: none;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: #1677ff;
|
||||
font-size: 12px;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.editable-cell-undo:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.editable-cell--enabled {
|
||||
cursor: cell;
|
||||
touch-action: manipulation;
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
Descriptions,
|
||||
Flex,
|
||||
Modal,
|
||||
Progress,
|
||||
Select,
|
||||
Space,
|
||||
Spin,
|
||||
@@ -34,11 +35,13 @@ import {
|
||||
importErrorReportUrl,
|
||||
previewImportStep,
|
||||
} from '../../api/imports';
|
||||
import { saveAs } from 'file-saver';
|
||||
import {
|
||||
STEP_FIELDS,
|
||||
type ImportPreviewResult,
|
||||
type ImportReceipt,
|
||||
type ImportRunDetail,
|
||||
type ImportStageRequest,
|
||||
type ImportStepKey,
|
||||
} from './types';
|
||||
|
||||
@@ -99,12 +102,7 @@ async function downloadErrorReport(runId: string, stepKey?: ImportStepKey): Prom
|
||||
});
|
||||
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);
|
||||
saveAs(blob, `导入错误报告-${runId.slice(0, 8)}.csv`);
|
||||
}
|
||||
|
||||
export const ImportWizardModal: React.FC<ImportWizardModalProps> = ({
|
||||
@@ -115,6 +113,7 @@ export const ImportWizardModal: React.FC<ImportWizardModalProps> = ({
|
||||
const [run, setRun] = useState<ImportRunDetail | null>(null);
|
||||
const [loadingRun, setLoadingRun] = useState(false);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [uploadPercent, setUploadPercent] = useState(0);
|
||||
const [activeStepKey, setActiveStepKey] = useState<ImportStepKey | null>(null);
|
||||
const [sheetSelection, setSheetSelection] = useState<Record<string, string[]>>({});
|
||||
const [mappingDraft, setMappingDraft] = useState<Record<string, Record<string, string>>>({});
|
||||
@@ -185,20 +184,41 @@ export const ImportWizardModal: React.FC<ImportWizardModalProps> = ({
|
||||
return [...headers];
|
||||
}, [run, activeStepKey, sheetSelection]);
|
||||
|
||||
const handleUpload: UploadProps['customRequest'] = async (options) => {
|
||||
const file = options.file as File;
|
||||
/** 创建导入任务并加载详情:统一处理上传进度与 loading 状态。成功返回 run 详情,失败返回 null */
|
||||
const uploadRun = async (
|
||||
file: File,
|
||||
options: {
|
||||
source: 'ai' | 'manual';
|
||||
conversationId?: number;
|
||||
stages?: ImportStageRequest[];
|
||||
mapping?: Record<string, Record<string, string>>;
|
||||
},
|
||||
errorMessage: string,
|
||||
): Promise<ImportRunDetail | null> => {
|
||||
setUploading(true);
|
||||
setUploadPercent(0);
|
||||
try {
|
||||
const detail = await createImportRun(file, { source: 'manual' });
|
||||
const detail = await createImportRun(file, {
|
||||
...options,
|
||||
onProgress: (percent) => setUploadPercent(percent),
|
||||
});
|
||||
await loadRun(detail.id);
|
||||
message.success(`已识别 ${detail.sheets.length} 个工作表`);
|
||||
return detail;
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : '文件上传失败');
|
||||
message.error(error instanceof Error ? error.message : errorMessage);
|
||||
return null;
|
||||
} finally {
|
||||
setUploading(false);
|
||||
setUploadPercent(0);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpload: UploadProps['customRequest'] = async (options) => {
|
||||
const file = options.file as File;
|
||||
const detail = await uploadRun(file, { source: 'manual' }, '文件上传失败');
|
||||
if (detail) message.success(`已识别 ${detail.sheets.length} 个工作表`);
|
||||
};
|
||||
|
||||
const handlePreview = async () => {
|
||||
if (!run || !activeStepKey || !activeStep) return;
|
||||
const mapping = mappingDraft[activeStepKey] ?? {};
|
||||
@@ -255,20 +275,16 @@ export const ImportWizardModal: React.FC<ImportWizardModalProps> = ({
|
||||
|
||||
const handleReupload = async (file: File) => {
|
||||
if (!run || !activeStepKey) return;
|
||||
setUploading(true);
|
||||
try {
|
||||
const detail = await createImportRun(file, {
|
||||
const detail = await uploadRun(
|
||||
file,
|
||||
{
|
||||
source: 'manual',
|
||||
stages: [{ stepKey: activeStepKey, sheets: sheetSelection[activeStepKey] ?? [] }],
|
||||
mapping: { [activeStepKey]: mappingDraft[activeStepKey] ?? {} },
|
||||
});
|
||||
await loadRun(detail.id);
|
||||
message.success('已重新上传,并保留原列映射');
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : '重新上传失败');
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
},
|
||||
'重新上传失败',
|
||||
);
|
||||
if (detail) message.success('已重新上传,并保留原列映射');
|
||||
};
|
||||
|
||||
const previewRows = useMemo(() => {
|
||||
@@ -405,6 +421,20 @@ export const ImportWizardModal: React.FC<ImportWizardModalProps> = ({
|
||||
<p className="ant-upload-text">点击或拖拽 .xlsx / .csv 文件到此区域</p>
|
||||
<p className="ant-upload-hint">单文件不超过 10MB;.xls 请先另存为 .xlsx</p>
|
||||
</Upload.Dragger>
|
||||
{uploading ? (
|
||||
<Flex vertical gap={4} style={{ marginTop: 8 }}>
|
||||
<Progress
|
||||
percent={uploadPercent}
|
||||
size="small"
|
||||
status={uploadPercent > 0 && uploadPercent < 100 ? 'active' : 'normal'}
|
||||
/>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12, textAlign: 'center' }}>
|
||||
{uploadPercent > 0 && uploadPercent < 100
|
||||
? `正在上传 ${uploadPercent}%...`
|
||||
: '正在上传并解析文件...'}
|
||||
</Typography.Text>
|
||||
</Flex>
|
||||
) : null}
|
||||
</Space>
|
||||
) : (
|
||||
<Space orientation="vertical" size={16} style={{ width: '100%' }}>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useImmer } from 'use-immer';
|
||||
import { Button, Form, Input, Modal, Select, Spin, Steps, Typography } from 'antd';
|
||||
import { App, Button, Form, Input, Modal, Select, Spin, Steps, Typography } from 'antd';
|
||||
import { CloudUploadOutlined, EditOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons';
|
||||
import api from '../api';
|
||||
import { message } from '../ui/app-message';
|
||||
@@ -30,6 +30,7 @@ interface MatchModalProps {
|
||||
}
|
||||
|
||||
const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplied }) => {
|
||||
const { modal } = App.useApp();
|
||||
const { hasPermission, hasAllPermissions, permissionsReady } = usePermission();
|
||||
const canTriggerSync = hasPermission('sync:trigger');
|
||||
const canEnterModal = permissionsReady && hasAllPermissions('sync:read', 'sync:trigger');
|
||||
@@ -145,6 +146,10 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
message.success(res.log.message || `处理 ${res.log.recordsCount} 条记录`);
|
||||
onApplied();
|
||||
reset();
|
||||
} else {
|
||||
// 接口返回 success:false 时也要结束「处理中」并给出错误提示
|
||||
message.error(res.log?.message || '处理失败,请检查后重试');
|
||||
setStep('match');
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
@@ -168,6 +173,22 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
// 已进入匹配步骤且存在待处理数据时,关闭会丢失全部决策,需先确认
|
||||
const hasPendingWork = step === 'match' && (entries.length > 0 || decisions.size > 0);
|
||||
if (hasPendingWork) {
|
||||
modal.confirm({
|
||||
title: '放弃当前匹配?',
|
||||
content: '已确认的匹配决策将全部丢失,且不会写入系统。',
|
||||
okText: '放弃',
|
||||
okButtonProps: { danger: true },
|
||||
cancelText: '继续匹配',
|
||||
onOk: () => {
|
||||
reset();
|
||||
onClose();
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
reset();
|
||||
onClose();
|
||||
};
|
||||
@@ -330,6 +351,7 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
onCancel={handleClose}
|
||||
width={step === 'match' || step === 'applying' ? 900 : 640}
|
||||
mask={{ closable: false }}
|
||||
closable={step !== 'applying'}
|
||||
footer={
|
||||
step === 'connection'
|
||||
? [
|
||||
@@ -380,7 +402,12 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
{step === 'rule' ? renderRuleStep() : null}
|
||||
{step === 'match' ? renderMatchStep() : null}
|
||||
{step === 'applying' ? (
|
||||
<Spin description="正在同步..." style={{ display: 'block', margin: '48px auto' }} />
|
||||
<>
|
||||
<Spin description="正在同步,请勿关闭窗口..." style={{ display: 'block', margin: '48px auto' }} />
|
||||
<Typography.Text type="secondary" style={{ display: 'block', textAlign: 'center' }}>
|
||||
数据正在写入,关闭窗口不会中断同步
|
||||
</Typography.Text>
|
||||
</>
|
||||
) : null}
|
||||
</Modal>
|
||||
);
|
||||
|
||||
69
apps/admin/src/components/NextStepHint.tsx
Normal file
69
apps/admin/src/components/NextStepHint.tsx
Normal file
@@ -0,0 +1,69 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Button, Card, Flex, Typography } from 'antd';
|
||||
import { CloseOutlined, RightOutlined, StepForwardOutlined } from '@ant-design/icons';
|
||||
|
||||
export interface NextStepHintProps {
|
||||
/** 提示标题,如「下一步:分班」 */
|
||||
title: string;
|
||||
/** 补充说明 */
|
||||
description?: string;
|
||||
/** 主操作按钮(跳转到下一步) */
|
||||
action?: { label: string; onClick: () => void };
|
||||
/** 是否可关闭,默认 true */
|
||||
closable?: boolean;
|
||||
/** 关闭回调 */
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 「下一步」引导卡片:在操作成功后或空状态下提示用户业务闭环的下一步,
|
||||
* 让用户始终知道接下来该做什么。
|
||||
*/
|
||||
export const NextStepHint: React.FC<NextStepHintProps> = ({
|
||||
title,
|
||||
description,
|
||||
action,
|
||||
closable = true,
|
||||
onClose,
|
||||
}) => {
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
if (dismissed) return null;
|
||||
|
||||
return (
|
||||
<Card
|
||||
size="small"
|
||||
className="next-step-hint"
|
||||
style={{ marginBottom: 16, borderColor: '#b7d4ff', background: '#f0f7ff' }}
|
||||
styles={{ body: { padding: '10px 16px' } }}
|
||||
>
|
||||
<Flex align="center" justify="space-between" gap={8} wrap>
|
||||
<Flex align="center" gap={8} wrap>
|
||||
<StepForwardOutlined style={{ color: '#1677ff' }} />
|
||||
<Typography.Text strong>{title}</Typography.Text>
|
||||
{description ? <Typography.Text type="secondary">{description}</Typography.Text> : null}
|
||||
</Flex>
|
||||
<Flex gap={4} align="center">
|
||||
{action ? (
|
||||
<Button type="primary" size="small" onClick={action.onClick}>
|
||||
{action.label} <RightOutlined />
|
||||
</Button>
|
||||
) : null}
|
||||
{closable ? (
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
icon={<CloseOutlined />}
|
||||
aria-label="关闭提示"
|
||||
onClick={() => {
|
||||
setDismissed(true);
|
||||
onClose?.();
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</Flex>
|
||||
</Flex>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default NextStepHint;
|
||||
@@ -5,6 +5,7 @@ import { useNavigate } from 'react-router';
|
||||
import dayjs from 'dayjs';
|
||||
import { useInterval } from 'usehooks-ts';
|
||||
import api from '../api';
|
||||
import { message } from '../ui/app-message';
|
||||
import { formatNotificationText, notificationTypeLabels } from '../utils/notification-display';
|
||||
import { useUserStore } from '../store/user/userStore';
|
||||
|
||||
@@ -33,8 +34,9 @@ const NotificationBell: React.FC = () => {
|
||||
try {
|
||||
const data = await api.get<NotificationItem[]>('/notifications?limit=20');
|
||||
setNotifications(data);
|
||||
} catch {
|
||||
/* ignore */
|
||||
} catch (error) {
|
||||
console.error('全部已读失败', error);
|
||||
message.error('全部已读失败,请重试');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -118,7 +120,7 @@ const NotificationBell: React.FC = () => {
|
||||
}}
|
||||
>
|
||||
<Typography.Text strong>通知中心</Typography.Text>
|
||||
<Button type="link" size="small" onClick={handleMarkAll}>
|
||||
<Button type="link" size="small" disabled={unreadCount === 0} onClick={handleMarkAll}>
|
||||
全部已读
|
||||
</Button>
|
||||
</div>
|
||||
@@ -199,7 +201,12 @@ const NotificationBell: React.FC = () => {
|
||||
placement="bottomRight"
|
||||
>
|
||||
<Badge count={unreadCount} size="small" offset={[-2, 2]}>
|
||||
<BellOutlined style={{ fontSize: 18, cursor: 'pointer' }} />
|
||||
<Button
|
||||
type="text"
|
||||
shape="circle"
|
||||
icon={<BellOutlined />}
|
||||
aria-label="通知中心"
|
||||
/>
|
||||
</Badge>
|
||||
</Popover>
|
||||
);
|
||||
|
||||
35
apps/admin/src/components/QueryState/QueryEmpty.tsx
Normal file
35
apps/admin/src/components/QueryState/QueryEmpty.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import React from 'react';
|
||||
import { Button, Empty } from 'antd';
|
||||
|
||||
export interface QueryEmptyAction {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
type?: 'primary' | 'default';
|
||||
icon?: React.ReactNode;
|
||||
}
|
||||
|
||||
export interface QueryEmptyProps {
|
||||
/** 空状态描述,默认「暂无数据」 */
|
||||
description?: string;
|
||||
/** 主操作按钮(如「添加学生」「导入 Excel」) */
|
||||
action?: QueryEmptyAction;
|
||||
/** 自定义空态插图 */
|
||||
image?: React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一空状态:数据确实为空时渲染本组件,并附带主操作按钮引导用户开始。
|
||||
*/
|
||||
export const QueryEmpty: React.FC<QueryEmptyProps> = ({ description = '暂无数据', action, image }) => {
|
||||
return (
|
||||
<Empty image={image} description={description}>
|
||||
{action ? (
|
||||
<Button type={action.type ?? 'primary'} icon={action.icon} onClick={action.onClick}>
|
||||
{action.label}
|
||||
</Button>
|
||||
) : null}
|
||||
</Empty>
|
||||
);
|
||||
};
|
||||
|
||||
export default QueryEmpty;
|
||||
56
apps/admin/src/components/QueryState/QueryErrorState.tsx
Normal file
56
apps/admin/src/components/QueryState/QueryErrorState.tsx
Normal file
@@ -0,0 +1,56 @@
|
||||
import React from 'react';
|
||||
import { Button, Result, Typography } from 'antd';
|
||||
|
||||
export interface QueryErrorStateProps {
|
||||
/** 错误标题,默认「数据加载失败」 */
|
||||
title?: string;
|
||||
/** 错误描述,默认「请检查网络后重试」 */
|
||||
description?: string;
|
||||
/** 点击重试回调;不传则不显示重试按钮 */
|
||||
onRetry?: () => void;
|
||||
/** 紧凑模式:用于表格内部、弹窗等空间受限场景 */
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一查询错误态:任何数据加载失败都应渲染本组件(而非伪装成空状态),
|
||||
* 并提供重试入口,让用户明确知道「加载失败」而非「没有数据」。
|
||||
*/
|
||||
export const QueryErrorState: React.FC<QueryErrorStateProps> = ({
|
||||
title = '数据加载失败',
|
||||
description = '请检查网络后重试。',
|
||||
onRetry,
|
||||
compact = false,
|
||||
}) => {
|
||||
if (compact) {
|
||||
return (
|
||||
<div style={{ padding: '32px 16px', textAlign: 'center' }}>
|
||||
<Typography.Text type="secondary">{title}</Typography.Text>
|
||||
{description ? (
|
||||
<div>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{description}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
) : null}
|
||||
{onRetry ? (
|
||||
<div style={{ marginTop: 12 }}>
|
||||
<Button size="small" onClick={onRetry}>
|
||||
重试
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Result
|
||||
status="warning"
|
||||
title={title}
|
||||
subTitle={description}
|
||||
extra={onRetry ? <Button type="primary" onClick={onRetry}>重试</Button> : undefined}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default QueryErrorState;
|
||||
4
apps/admin/src/components/QueryState/index.ts
Normal file
4
apps/admin/src/components/QueryState/index.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export { QueryErrorState } from './QueryErrorState';
|
||||
export type { QueryErrorStateProps } from './QueryErrorState';
|
||||
export { QueryEmpty } from './QueryEmpty';
|
||||
export type { QueryEmptyProps, QueryEmptyAction } from './QueryEmpty';
|
||||
17
apps/admin/src/components/RefreshButton.tsx
Normal file
17
apps/admin/src/components/RefreshButton.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import React from 'react';
|
||||
import { Button, Tooltip } from 'antd';
|
||||
import { ReloadOutlined } from '@ant-design/icons';
|
||||
|
||||
interface RefreshButtonProps {
|
||||
onRefresh: () => void;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
/** 列表工具栏刷新入口:手动重新拉取当前数据,带加载反馈。 */
|
||||
export const RefreshButton: React.FC<RefreshButtonProps> = ({ onRefresh, loading }) => (
|
||||
<Tooltip title="刷新">
|
||||
<Button icon={<ReloadOutlined />} loading={loading} onClick={onRefresh} aria-label="刷新" />
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
export default RefreshButton;
|
||||
41
apps/admin/src/components/RouteDock/dockTabs.test.ts
Normal file
41
apps/admin/src/components/RouteDock/dockTabs.test.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { DockTab } from '../../store/app/appTypes';
|
||||
import { MAX_DOCK_TABS, upsertDockTab } from './dockTabs';
|
||||
|
||||
const tab = (key: string, label = key): DockTab => ({ key, label });
|
||||
|
||||
describe('upsertDockTab', () => {
|
||||
it('追加新页签', () => {
|
||||
expect(upsertDockTab([], '/students', '学生管理')).toEqual([tab('/students', '学生管理')]);
|
||||
});
|
||||
|
||||
it('标题未变时保持原引用,避免无谓渲染', () => {
|
||||
const tabs = [tab('/students', '学生管理')];
|
||||
expect(upsertDockTab(tabs, '/students', '学生管理')).toBe(tabs);
|
||||
});
|
||||
|
||||
it('菜单标题变化时更新页签标题', () => {
|
||||
const tabs = [tab('/students', '学生管理')];
|
||||
expect(upsertDockTab(tabs, '/students', '学生档案')).toEqual([tab('/students', '学生档案')]);
|
||||
});
|
||||
|
||||
it('超过上限时保留当前页签 + 最新页签(LRU 淘汰最旧)', () => {
|
||||
const tabs = Array.from({ length: MAX_DOCK_TABS }, (_, i) => tab(`/p${i + 1}`));
|
||||
const next = upsertDockTab(tabs, '/new', '新页');
|
||||
expect(next).toHaveLength(MAX_DOCK_TABS);
|
||||
expect(next[0]).toEqual(tab('/new', '新页'));
|
||||
expect(next[next.length - 1]).toEqual(tab(`/p${MAX_DOCK_TABS}`));
|
||||
expect(next.some((t) => t.key === '/p1')).toBe(false);
|
||||
});
|
||||
|
||||
it('恢复持久化的超量页签时压缩到上限,并保留当前页', () => {
|
||||
const tabs = Array.from({ length: 25 }, (_, i) => tab(`/p${i + 1}`));
|
||||
tabs.push(tab('/wallets', '学生余额'));
|
||||
const next = upsertDockTab(tabs, '/wallets', '学生余额');
|
||||
expect(next).toHaveLength(MAX_DOCK_TABS);
|
||||
expect(next[0]).toEqual(tab('/wallets', '学生余额'));
|
||||
expect(next.some((t) => t.key === '/p1')).toBe(false);
|
||||
expect(next.some((t) => t.key === '/p6')).toBe(false);
|
||||
expect(next.some((t) => t.key === '/p7')).toBe(true);
|
||||
});
|
||||
});
|
||||
31
apps/admin/src/components/RouteDock/dockTabs.ts
Normal file
31
apps/admin/src/components/RouteDock/dockTabs.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import type { DockTab } from '../../store/app/appTypes';
|
||||
|
||||
/** 页签数量上限:超出后淘汰最旧的非当前页签(LRU 式),避免无限堆积。 */
|
||||
export const MAX_DOCK_TABS = 20;
|
||||
|
||||
function clampToLimit(list: readonly DockTab[], activeKey: string): DockTab[] {
|
||||
// 未超限时保留原引用,避免触发无谓的 tab 列表重渲染
|
||||
if (list.length <= MAX_DOCK_TABS) return list as DockTab[];
|
||||
// 恢复/迁移或新增后超出上限:保留当前页签 + 最新的其余页签(LRU 式淘汰)
|
||||
const active = list.find((tab) => tab.key === activeKey);
|
||||
const rest = list.filter((tab) => tab.key !== activeKey);
|
||||
const keptRest = rest.slice(rest.length - (MAX_DOCK_TABS - 1));
|
||||
return active ? [active, ...keptRest] : keptRest.slice(-MAX_DOCK_TABS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 路由页签合并:按 pathname 建 tab,重复时更新标题,并始终把列表压回上限。
|
||||
*/
|
||||
export function upsertDockTab(
|
||||
tabs: readonly DockTab[],
|
||||
activeKey: string,
|
||||
label: string,
|
||||
): DockTab[] {
|
||||
const existing = tabs.find((tab) => tab.key === activeKey);
|
||||
if (existing) {
|
||||
const updated =
|
||||
existing.label === label ? tabs : tabs.map((tab) => (tab.key === activeKey ? { ...tab, label } : tab));
|
||||
return clampToLimit(updated, activeKey);
|
||||
}
|
||||
return clampToLimit([...tabs, { key: activeKey, label }], activeKey);
|
||||
}
|
||||
@@ -14,10 +14,12 @@ import {
|
||||
useSortable,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import { Tabs, type TabsProps } from 'antd';
|
||||
import { Button, Dropdown, Tabs, type TabsProps } from 'antd';
|
||||
import { DownOutlined } from '@ant-design/icons';
|
||||
import type { Location } from 'react-router';
|
||||
import type { AppMenuItem } from '../../auth/menu-policy';
|
||||
import { useAppStore } from '../../store';
|
||||
import { upsertDockTab } from './dockTabs';
|
||||
|
||||
interface RouteDockProps {
|
||||
location: Location;
|
||||
@@ -72,20 +74,16 @@ const DraggableTabNode: React.FC<Readonly<DraggableTabNodeProps>> = ({ ...props
|
||||
};
|
||||
|
||||
const RouteDock: React.FC<RouteDockProps> = ({ location, menuItems, onNavigate, draggable }) => {
|
||||
const activeKey = `${location.pathname}${location.search}`;
|
||||
// 与 RouteKeeper 缓存 key 保持一致:只按 pathname 建 tab,避免 query 变化产生重复页签。
|
||||
const activeKey = location.pathname;
|
||||
const tabs = useAppStore((state) => state.routeDockTabs);
|
||||
const setRouteDockTabs = useAppStore((state) => state.setRouteDockTabs);
|
||||
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }));
|
||||
|
||||
useEffect(() => {
|
||||
if (location.pathname === '/') return;
|
||||
setRouteDockTabs((currentTabs) => {
|
||||
const label = getRouteLabel(menuItems, location.pathname);
|
||||
const existing = currentTabs.find((tab) => tab.key === activeKey);
|
||||
if (!existing) return [...currentTabs, { key: activeKey, label }];
|
||||
if (existing.label === label) return currentTabs;
|
||||
return currentTabs.map((tab) => (tab.key === activeKey ? { ...tab, label } : tab));
|
||||
});
|
||||
const label = getRouteLabel(menuItems, location.pathname);
|
||||
setRouteDockTabs((currentTabs) => upsertDockTab(currentTabs, activeKey, label));
|
||||
}, [activeKey, location.pathname, menuItems, setRouteDockTabs]);
|
||||
|
||||
const tabItems = useMemo<NonNullable<TabsProps['items']>>(
|
||||
@@ -109,6 +107,27 @@ const RouteDock: React.FC<RouteDockProps> = ({ location, menuItems, onNavigate,
|
||||
}
|
||||
};
|
||||
|
||||
const closeOthers = () => {
|
||||
setRouteDockTabs(tabs.filter((tab) => tab.key === activeKey));
|
||||
};
|
||||
|
||||
const closeLeft = () => {
|
||||
const index = tabs.findIndex((tab) => tab.key === activeKey);
|
||||
if (index <= 0) return;
|
||||
setRouteDockTabs(tabs.filter((_, i) => i >= index));
|
||||
};
|
||||
|
||||
const closeRight = () => {
|
||||
const index = tabs.findIndex((tab) => tab.key === activeKey);
|
||||
if (index < 0 || index === tabs.length - 1) return;
|
||||
setRouteDockTabs(tabs.filter((_, i) => i <= index));
|
||||
};
|
||||
|
||||
const closeAll = () => {
|
||||
setRouteDockTabs([]);
|
||||
onNavigate('/dashboard');
|
||||
};
|
||||
|
||||
const handleDragEnd = ({ active, over }: DragEndEvent) => {
|
||||
if (!over || active.id === over.id) return;
|
||||
setRouteDockTabs((currentTabs) => {
|
||||
@@ -166,6 +185,32 @@ const RouteDock: React.FC<RouteDockProps> = ({ location, menuItems, onNavigate,
|
||||
if (action === 'remove') closeTab(String(targetKey));
|
||||
}}
|
||||
renderTabBar={renderTabBar}
|
||||
tabBarExtraContent={
|
||||
tabs.length > 1 ? (
|
||||
<Dropdown
|
||||
trigger={['click']}
|
||||
menu={{
|
||||
items: [
|
||||
{ key: 'close-others', label: '关闭其他' },
|
||||
{ key: 'close-left', label: '关闭左侧' },
|
||||
{ key: 'close-right', label: '关闭右侧' },
|
||||
{ type: 'divider' },
|
||||
{ key: 'close-all', label: '关闭全部' },
|
||||
],
|
||||
onClick: ({ key }) => {
|
||||
if (key === 'close-others') closeOthers();
|
||||
else if (key === 'close-left') closeLeft();
|
||||
else if (key === 'close-right') closeRight();
|
||||
else if (key === 'close-all') closeAll();
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Button type="text" size="small" icon={<DownOutlined />} aria-label="更多页签操作">
|
||||
更多
|
||||
</Button>
|
||||
</Dropdown>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
</nav>
|
||||
);
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import React, { useRef } from 'react';
|
||||
import { useLocation, useOutlet } from 'react-router';
|
||||
import AppErrorBoundary from './AppErrorBoundary';
|
||||
import { ActivePageContext } from './routeKeeperContext';
|
||||
|
||||
const MAX_CACHED_PAGES = 30;
|
||||
|
||||
/**
|
||||
* 路由保活:切换页面时保留已访问页面的组件实例(输入、滚动、弹窗状态不丢失)。
|
||||
* 隐藏页面仍挂载在 DOM 中,仅通过 display:none 隐藏。
|
||||
*
|
||||
* - 每个缓存页外层包裹 AppErrorBoundary:单页渲染异常不影响其他缓存页。
|
||||
* - 通过 ActivePageContext 向页面暴露「当前激活页路径」,供 usePageVisible 使用。
|
||||
*/
|
||||
export const RouteKeeper: React.FC = () => {
|
||||
const location = useLocation();
|
||||
@@ -26,17 +31,17 @@ export const RouteKeeper: React.FC = () => {
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<ActivePageContext.Provider value={pageKey}>
|
||||
{Array.from(cacheRef.current.entries()).map(([key, node]) => (
|
||||
<div
|
||||
key={key}
|
||||
className="route-keeper-page"
|
||||
style={{ display: key === pageKey ? undefined : 'none' }}
|
||||
>
|
||||
{node}
|
||||
<AppErrorBoundary>{node}</AppErrorBoundary>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
</ActivePageContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
16
apps/admin/src/components/ScrollToTop.tsx
Normal file
16
apps/admin/src/components/ScrollToTop.tsx
Normal file
@@ -0,0 +1,16 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useLocation } from 'react-router';
|
||||
|
||||
/**
|
||||
* SPA 路由切换后把滚动位置复位到顶部。
|
||||
* 只在 pathname 变化时触发,避免干扰弹窗/抽屉等局部滚动。
|
||||
*/
|
||||
export const ScrollToTop: React.FC = () => {
|
||||
const { pathname } = useLocation();
|
||||
useEffect(() => {
|
||||
window.scrollTo(0, 0);
|
||||
}, [pathname]);
|
||||
return null;
|
||||
};
|
||||
|
||||
export default ScrollToTop;
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState } from 'react';
|
||||
import { App, Button, Popconfirm, Space, Table, Upload } from 'antd';
|
||||
import React, { useRef, useState } from 'react';
|
||||
import { App, Button, Modal, 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';
|
||||
@@ -10,6 +10,20 @@ import { getErrorMessage } from '../../utils/error';
|
||||
import { ATTACHMENT_CATEGORY_OPTIONS, formatFileSize } from './shared';
|
||||
import type { AttachmentRecord, TabProps } from './shared';
|
||||
|
||||
type AttachmentPreview = {
|
||||
url: string;
|
||||
name: string;
|
||||
kind: 'image' | 'pdf';
|
||||
};
|
||||
|
||||
/** 根据文件扩展名决定安全展示方式:图片/PDF 内联预览,其余一律下载 */
|
||||
function getAttachmentKind(fileName: string, mimeType?: string): 'image' | 'pdf' | 'download' {
|
||||
const ext = fileName.split('.').pop()?.toLowerCase() ?? '';
|
||||
if (['png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp', 'svg'].includes(ext)) return 'image';
|
||||
if (ext === 'pdf' || mimeType === 'application/pdf') return 'pdf';
|
||||
return 'download';
|
||||
}
|
||||
|
||||
export const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({
|
||||
data,
|
||||
studentId,
|
||||
@@ -18,6 +32,9 @@ export const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> =
|
||||
const { hasPermission } = usePermission();
|
||||
const canPurgeArchive = hasPermission('archive:purge');
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [preview, setPreview] = useState<AttachmentPreview | null>(null);
|
||||
// 预览请求序号:快速点不同行「查看」时,慢的旧响应回来直接丢弃,避免覆盖新预览
|
||||
const previewSeqRef = useRef(0);
|
||||
|
||||
const deleteAttachmentMutation = useApiMutation(
|
||||
async (attachmentId: number) => api.delete(`/archive/attachments/${attachmentId}`),
|
||||
@@ -33,6 +50,39 @@ export const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> =
|
||||
{ invalidate: [['archive', studentId]] },
|
||||
);
|
||||
|
||||
const closePreview = () => {
|
||||
previewSeqRef.current += 1; // 关闭后仍在途的旧响应也不再落地
|
||||
if (preview?.url) URL.revokeObjectURL(preview.url);
|
||||
setPreview(null);
|
||||
};
|
||||
|
||||
const openAttachment = async (record: AttachmentRecord) => {
|
||||
const seq = ++previewSeqRef.current;
|
||||
try {
|
||||
const blob = await api.get<Blob>(`/archive/${studentId}/attachments/${record.id}`, {
|
||||
responseType: 'blob',
|
||||
});
|
||||
if (seq !== previewSeqRef.current) return; // 已有更新的查看请求,丢弃本次慢响应
|
||||
const kind = getAttachmentKind(record.fileName, record.mimeType);
|
||||
const url = URL.createObjectURL(blob);
|
||||
if (kind === 'download') {
|
||||
// 非内联类型通过 download 属性触发下载,避免以页面同源打开可执行内容
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = record.fileName || 'attachment';
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
} else {
|
||||
if (preview?.url) URL.revokeObjectURL(preview.url);
|
||||
setPreview({ url, name: record.fileName || 'attachment', kind });
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
message.error(getErrorMessage(e, '查看失败'));
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (attachmentId: number) => {
|
||||
try {
|
||||
await deleteAttachmentMutation.mutateAsync(attachmentId);
|
||||
@@ -72,22 +122,7 @@ export const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> =
|
||||
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 size="small" icon={<EyeOutlined />} onClick={() => openAttachment(record)}>
|
||||
查看
|
||||
</Button>
|
||||
{hasPermission('student:edit') && record.status !== 'archived' ? (
|
||||
@@ -137,7 +172,7 @@ export const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> =
|
||||
</Button>
|
||||
</Upload>
|
||||
) : null}
|
||||
<Table<AttachmentRecord>
|
||||
<Table<AttachmentRecord> scroll={{ x: 'max-content' }}
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
rowKey="id"
|
||||
@@ -149,6 +184,25 @@ export const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> =
|
||||
}}
|
||||
style={{ marginTop: 16 }}
|
||||
/>
|
||||
<Modal
|
||||
title={preview?.name}
|
||||
open={!!preview}
|
||||
footer={null}
|
||||
onCancel={closePreview}
|
||||
width={preview?.kind === 'pdf' ? 900 : undefined}
|
||||
destroyOnHidden
|
||||
>
|
||||
{preview?.kind === 'image' ? (
|
||||
<img src={preview.url} alt={preview.name} style={{ width: '100%' }} />
|
||||
) : preview?.kind === 'pdf' ? (
|
||||
<iframe
|
||||
src={preview.url}
|
||||
title={preview.name}
|
||||
sandbox=""
|
||||
style={{ width: '100%', height: '70vh', border: 'none' }}
|
||||
/>
|
||||
) : null}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -205,7 +205,7 @@ export const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> =
|
||||
>
|
||||
添加报读记录
|
||||
</PermissionButton>
|
||||
<Table<EnrollmentRecord>
|
||||
<Table<EnrollmentRecord> scroll={{ x: 'max-content' }}
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
rowKey="id"
|
||||
|
||||
@@ -195,7 +195,7 @@ export const ExamScoresTab: React.FC<
|
||||
>
|
||||
添加考试成绩
|
||||
</PermissionButton>
|
||||
<Table<ExamScoreRecord>
|
||||
<Table<ExamScoreRecord> scroll={{ x: 'max-content' }}
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
rowKey="id"
|
||||
|
||||
@@ -162,7 +162,7 @@ export const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({
|
||||
>
|
||||
添加学情记录
|
||||
</PermissionButton>
|
||||
<Table<LearningRecord>
|
||||
<Table<LearningRecord> scroll={{ x: 'max-content' }}
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
rowKey="id"
|
||||
|
||||
@@ -28,10 +28,11 @@ import { message } from '../../ui/app-message';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||
import { validateResponse } from '../../utils/validate';
|
||||
import { queryKeys } from '../../api/queryKeys';
|
||||
import { organizationOptionsSchema, studentProfileAggregateSchema } from '../../api/schemas';
|
||||
import EditableCell from '../EditableCell';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
import { getErrorMessage } from '../../utils/error';
|
||||
import { QueryErrorState } from '../QueryState';
|
||||
|
||||
import { ADMISSION_STATUS_MAP, ATTENDANCE_STATUS_MAP, SESSION_LABELS, getOptionLabel } from './shared';
|
||||
import type { AttendanceRecordItem, ProfileData, ResultData, StudentInfo, StudentProfileAggregate, StudentProfileContentProps } from './shared';
|
||||
@@ -187,7 +188,7 @@ const InlineArchiveSummary: React.FC<{
|
||||
);
|
||||
|
||||
return (
|
||||
<Descriptions bordered column={3} size="small" style={{ marginBottom: 24 }}>
|
||||
<Descriptions bordered column={{ xs: 1, sm: 2, lg: 3 }} size="small" style={{ marginBottom: 24 }}>
|
||||
<Descriptions.Item label="手机号">
|
||||
<EditableCell
|
||||
value={student.phone}
|
||||
@@ -478,25 +479,21 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
|
||||
data: aggregateData,
|
||||
isLoading,
|
||||
isFetching,
|
||||
isError,
|
||||
refetch,
|
||||
} = useQuery<StudentProfileAggregate | null>({
|
||||
queryKey: ['archive', studentId],
|
||||
queryKey: queryKeys.archive.detail(studentId),
|
||||
queryFn: async () => {
|
||||
try {
|
||||
return validateResponse<StudentProfileAggregate>(
|
||||
studentProfileAggregateSchema,
|
||||
await api.get<StudentProfileAggregate>(`/archive/${studentId}`),
|
||||
);
|
||||
} catch (e: unknown) {
|
||||
message.error(getErrorMessage(e, '加载失败'));
|
||||
return null;
|
||||
}
|
||||
return validateResponse<StudentProfileAggregate>(
|
||||
studentProfileAggregateSchema,
|
||||
await api.get<StudentProfileAggregate>(`/archive/${studentId}`),
|
||||
);
|
||||
},
|
||||
});
|
||||
const { data: organizations = [] } = useQuery<
|
||||
Array<{ id: number; name: string; isHost?: boolean }>
|
||||
>({
|
||||
queryKey: ['organizations', 'options'],
|
||||
queryKey: queryKeys.organizations.options(),
|
||||
enabled: canLoadOrganizations,
|
||||
queryFn: async () => {
|
||||
try {
|
||||
@@ -582,6 +579,15 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (isError) {
|
||||
return (
|
||||
<QueryErrorState
|
||||
title="档案数据加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -76,6 +76,7 @@ export interface AttachmentRecord {
|
||||
category: string;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
mimeType?: string;
|
||||
}
|
||||
|
||||
export interface AttendanceRecordItem {
|
||||
|
||||
10
apps/admin/src/components/routeKeeperContext.ts
Normal file
10
apps/admin/src/components/routeKeeperContext.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { createContext, useContext } from 'react';
|
||||
|
||||
/**
|
||||
* 当前激活的页面路径(由 RouteKeeper 提供)。
|
||||
* RouteKeeper 用 display:none 保活已访问页面,页面组件本身不会重新挂载,
|
||||
* 因此需要该上下文让每个缓存页感知「自己是否处于激活状态」。
|
||||
*/
|
||||
export const ActivePageContext = createContext<string>('');
|
||||
|
||||
export const useActivePage = (): string => useContext(ActivePageContext);
|
||||
125
apps/admin/src/components/ux.integration.test.tsx
Normal file
125
apps/admin/src/components/ux.integration.test.tsx
Normal file
@@ -0,0 +1,125 @@
|
||||
import React, { act } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { MemoryRouter, Route, Routes, useNavigate } from 'react-router';
|
||||
import { RefreshButton } from './RefreshButton';
|
||||
import { BackTop } from './BackTop';
|
||||
import { ScrollToTop } from './ScrollToTop';
|
||||
import { useSubmitShortcut } from '../hooks/useSubmitShortcut';
|
||||
|
||||
let container: HTMLDivElement | null = null;
|
||||
let root: ReturnType<typeof createRoot> | null = null;
|
||||
|
||||
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
const mount = (node: React.ReactNode) => {
|
||||
const host = document.createElement('div');
|
||||
container = host;
|
||||
document.body.appendChild(host);
|
||||
root = createRoot(host);
|
||||
act(() => root?.render(node));
|
||||
};
|
||||
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await act(async () => root?.unmount());
|
||||
}
|
||||
container?.remove();
|
||||
root = null;
|
||||
container = null;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('UX 组件与交互', () => {
|
||||
it('RefreshButton 点击触发 onRefresh,loading 时展示加载态', async () => {
|
||||
const onRefresh = vi.fn();
|
||||
mount(<RefreshButton onRefresh={onRefresh} />);
|
||||
const button = container?.querySelector('button');
|
||||
if (!button) throw new Error('button not rendered');
|
||||
act(() => button.dispatchEvent(new MouseEvent('click', { bubbles: true })));
|
||||
await flush();
|
||||
expect(onRefresh).toHaveBeenCalledTimes(1);
|
||||
|
||||
mount(<RefreshButton onRefresh={onRefresh} loading />);
|
||||
expect(container?.querySelector('.ant-btn-loading')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('useSubmitShortcut 未激活时不响应 Cmd+Enter', async () => {
|
||||
const onSubmit = vi.fn();
|
||||
const Harness = () => {
|
||||
useSubmitShortcut(false, onSubmit);
|
||||
return <button type="button">ok</button>;
|
||||
};
|
||||
mount(<Harness />);
|
||||
window.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'Enter', metaKey: true, bubbles: true }),
|
||||
);
|
||||
await flush();
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('useSubmitShortcut 激活时响应 Cmd/Ctrl+Enter 且阻止默认行为', async () => {
|
||||
const onSubmit = vi.fn();
|
||||
const Harness = () => {
|
||||
useSubmitShortcut(true, onSubmit);
|
||||
return <button type="button">ok</button>;
|
||||
};
|
||||
mount(<Harness />);
|
||||
|
||||
const metaEvent = new KeyboardEvent('keydown', {
|
||||
key: 'Enter',
|
||||
metaKey: true,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
window.dispatchEvent(metaEvent);
|
||||
expect(metaEvent.defaultPrevented).toBe(true);
|
||||
|
||||
window.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'Enter', ctrlKey: true, bubbles: true }),
|
||||
);
|
||||
await flush();
|
||||
expect(onSubmit).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('BackTop 超过阈值后出现,点击回到顶部', async () => {
|
||||
const scrollSpy = vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
|
||||
mount(<BackTop threshold={-1} />);
|
||||
await flush();
|
||||
const button = container?.querySelector('button');
|
||||
expect(button).toBeTruthy();
|
||||
if (button) {
|
||||
act(() => button.dispatchEvent(new MouseEvent('click', { bubbles: true })));
|
||||
}
|
||||
await flush();
|
||||
expect(scrollSpy).toHaveBeenCalledWith(expect.objectContaining({ top: 0 }));
|
||||
});
|
||||
|
||||
it('ScrollToTop 在路由切换时把滚动位置复位到顶部', async () => {
|
||||
const scrollSpy = vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
|
||||
const Nav = () => {
|
||||
const navigate = useNavigate();
|
||||
return (
|
||||
<button type="button" onClick={() => navigate('/other')}>
|
||||
go
|
||||
</button>
|
||||
);
|
||||
};
|
||||
mount(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<ScrollToTop />
|
||||
<Routes>
|
||||
<Route path="/" element={<Nav />} />
|
||||
<Route path="/other" element={<div>other</div>} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
scrollSpy.mockClear();
|
||||
|
||||
const button = container?.querySelector('button');
|
||||
if (!button) throw new Error('button not rendered');
|
||||
act(() => button.dispatchEvent(new MouseEvent('click', { bubbles: true })));
|
||||
await flush();
|
||||
expect(scrollSpy).toHaveBeenCalledWith(0, 0);
|
||||
});
|
||||
});
|
||||
@@ -2,38 +2,62 @@ import { useMutation, useQueryClient, type QueryKey } from '@tanstack/react-quer
|
||||
import { message } from '../ui/app-message';
|
||||
import { getErrorMessage } from '../utils/error';
|
||||
|
||||
interface UseApiMutationOptions<TData, TVars> {
|
||||
interface UseApiMutationOptions<TData, TVars, TContext> {
|
||||
/** 成功后自动失效的查询 key(触发列表/详情刷新) */
|
||||
invalidate?: QueryKey[];
|
||||
/** 乐观更新:mutate 前同步改缓存,返回回滚上下文(失败时传给 onError) */
|
||||
onMutate?: (vars: TVars) => Promise<TContext | undefined> | TContext | undefined;
|
||||
/** 成功后回调(例如关闭弹窗) */
|
||||
onSuccess?: (data: TData, vars: TVars) => void;
|
||||
/** 失败回调;默认统一用 getErrorMessage 弹错误提示 */
|
||||
onError?: (error: unknown) => void;
|
||||
onSuccess?: (data: TData, vars: TVars, context?: TContext) => void;
|
||||
/** 失败回调;提供时由调用方负责(含乐观更新回滚),否则默认用 getErrorMessage 弹错误提示 */
|
||||
onError?: (error: unknown, vars: TVars, context?: TContext) => void;
|
||||
/** 结束后回调(无论成败) */
|
||||
onSettled?: (data: TData | undefined, error: unknown, vars: TVars, context?: TContext) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* useMutation 的轻量封装:统一错误提示 + 成功后 invalidateQueries,
|
||||
* 消除手写 `await api.xxx(); await fetchData();` 样板。
|
||||
*
|
||||
* 乐观更新示例:
|
||||
* ```ts
|
||||
* const mutation = useApiMutation(fn, {
|
||||
* onMutate: async (vars) => {
|
||||
* await queryClient.cancelQueries({ queryKey });
|
||||
* const previous = queryClient.getQueryData(queryKey);
|
||||
* queryClient.setQueryData(queryKey, updater);
|
||||
* return previous; // 回滚上下文
|
||||
* },
|
||||
* onError: (_e, _v, previous) => queryClient.setQueryData(queryKey, previous),
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function useApiMutation<TData = unknown, TVars = void>(
|
||||
export function useApiMutation<TData = unknown, TVars = void, TContext = unknown>(
|
||||
mutationFn: (vars: TVars) => Promise<TData>,
|
||||
options: UseApiMutationOptions<TData, TVars> = {},
|
||||
options: UseApiMutationOptions<TData, TVars, TContext> = {},
|
||||
) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<TData, Error, TVars>({
|
||||
return useMutation<TData, Error, TVars, TContext>({
|
||||
mutationFn,
|
||||
onSuccess: (data, vars) => {
|
||||
// 包装 onMutate:允许调用方返回 undefined(无回滚上下文),
|
||||
// React Query 的 onMutate 类型要求返回 TContext
|
||||
onMutate: async (vars) => {
|
||||
const context = await options.onMutate?.(vars);
|
||||
return context as TContext;
|
||||
},
|
||||
onSuccess: (data, vars, context) => {
|
||||
for (const key of options.invalidate ?? []) {
|
||||
void queryClient.invalidateQueries({ queryKey: key });
|
||||
}
|
||||
options.onSuccess?.(data, vars);
|
||||
options.onSuccess?.(data, vars, context);
|
||||
},
|
||||
onError: (error) => {
|
||||
onError: (error, vars, context) => {
|
||||
if (options.onError) {
|
||||
options.onError(error);
|
||||
options.onError(error, vars, context);
|
||||
} else {
|
||||
message.error(getErrorMessage(error));
|
||||
}
|
||||
},
|
||||
onSettled: options.onSettled,
|
||||
});
|
||||
}
|
||||
|
||||
31
apps/admin/src/hooks/useApiQuery.ts
Normal file
31
apps/admin/src/hooks/useApiQuery.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import type { QueryKey } from '@tanstack/react-query';
|
||||
import type { z } from 'zod';
|
||||
import { validateResponse } from '../utils/validate';
|
||||
|
||||
interface UseApiQueryOptions<T, TSelected = T> {
|
||||
queryKey: QueryKey;
|
||||
queryFn: () => Promise<unknown>;
|
||||
/** zod schema:响应校验失败会抛出带字段路径的错误,由统一错误处理展示 */
|
||||
schema: z.ZodType<unknown>;
|
||||
enabled?: boolean;
|
||||
staleTime?: number;
|
||||
/** 可选的数据转换(React Query select),例如列表原始行 → UI 模型 */
|
||||
select?: (data: T) => TSelected;
|
||||
}
|
||||
|
||||
/**
|
||||
* useQuery 的类型安全封装:queryFn 返回 unknown,
|
||||
* 由 zod schema 校验并收敛为 T,消除各页面重复的
|
||||
* `validateResponse(schema, await api.get(...))` 样板。
|
||||
*/
|
||||
export function useApiQuery<T, TSelected = T>(options: UseApiQueryOptions<T, TSelected>) {
|
||||
const { queryKey, queryFn, schema, enabled, staleTime, select } = options;
|
||||
return useQuery<T, Error, TSelected>({
|
||||
queryKey,
|
||||
enabled,
|
||||
staleTime,
|
||||
queryFn: async () => validateResponse<T>(schema, await queryFn()),
|
||||
select,
|
||||
});
|
||||
}
|
||||
53
apps/admin/src/hooks/useDirtyGuard.ts
Normal file
53
apps/admin/src/hooks/useDirtyGuard.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { useCallback, useMemo, useRef } from 'react';
|
||||
import { App } from 'antd';
|
||||
import type { FormInstance } from 'antd';
|
||||
import equal from 'fast-deep-equal';
|
||||
|
||||
/**
|
||||
* 弹窗「未保存内容」保护:关闭弹窗时若表单值已被修改,先确认再关闭,
|
||||
* 避免用户误关丢失已填内容。
|
||||
*
|
||||
* 用法:
|
||||
* const { confirmClose, snapshot } = useDirtyGuard(form);
|
||||
* // 打开弹窗(或编辑回填后)时调用一次 snapshot() 记录初始值
|
||||
* const openEdit = () => { form.setFieldsValue(record); snapshot(); setOpen(true); };
|
||||
* // Modal 的 onCancel 改用确认关闭
|
||||
* <Modal onCancel={() => confirmClose(() => setOpen(false))} ...>
|
||||
*/
|
||||
export function useDirtyGuard(form: FormInstance) {
|
||||
const { modal } = App.useApp();
|
||||
const pristineRef = useRef<unknown>(null);
|
||||
|
||||
/** 记录当前表单值为「未修改」基准;打开弹窗/回填后调用 */
|
||||
const snapshot = useCallback(() => {
|
||||
pristineRef.current = form.getFieldsValue();
|
||||
}, [form]);
|
||||
|
||||
/** 表单是否有未保存修改(与 snapshot 时对比) */
|
||||
const isDirty = useCallback(() => {
|
||||
return !equal(form.getFieldsValue(), pristineRef.current);
|
||||
}, [form]);
|
||||
|
||||
const confirmClose = useCallback(
|
||||
(close: () => void) => {
|
||||
if (!isDirty()) {
|
||||
close();
|
||||
return;
|
||||
}
|
||||
modal.confirm({
|
||||
title: '放弃未保存的修改?',
|
||||
content: '当前表单有未保存的内容,关闭后修改将丢失。',
|
||||
okText: '放弃修改',
|
||||
okButtonProps: { danger: true },
|
||||
cancelText: '继续编辑',
|
||||
onOk: close,
|
||||
});
|
||||
},
|
||||
[isDirty, modal],
|
||||
);
|
||||
|
||||
// 用 useMemo 稳定返回对象引用,避免消费方 useEffect 依赖每次渲染都变化
|
||||
return useMemo(() => ({ confirmClose, snapshot, isDirty }), [confirmClose, snapshot, isDirty]);
|
||||
}
|
||||
|
||||
export default useDirtyGuard;
|
||||
46
apps/admin/src/hooks/useDownload.ts
Normal file
46
apps/admin/src/hooks/useDownload.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
import { downloadBlob } from '../utils/download';
|
||||
import { message } from '../ui/app-message';
|
||||
|
||||
export interface DownloadOptions {
|
||||
/** 成功提示文案;默认「下载成功」 */
|
||||
successMsg?: string;
|
||||
/** 失败提示文案;默认使用接口返回的错误信息 */
|
||||
errorMsg?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一下载/导出状态:防重复点击 + 成功/失败反馈。
|
||||
*
|
||||
* 用法:
|
||||
* const { downloading, run } = useDownload();
|
||||
* <Button loading={downloading} onClick={() => run('/students/export', '名单.xlsx')}>
|
||||
*/
|
||||
export function useDownload() {
|
||||
const [downloading, setDownloading] = useState(false);
|
||||
const busyRef = useRef(false);
|
||||
|
||||
const run = useCallback(
|
||||
async (endpoint: string, filename: string, options?: DownloadOptions) => {
|
||||
if (busyRef.current) return;
|
||||
busyRef.current = true;
|
||||
setDownloading(true);
|
||||
try {
|
||||
await downloadBlob(endpoint, filename);
|
||||
message.success(options?.successMsg ?? '下载成功');
|
||||
} catch (error: unknown) {
|
||||
message.error(
|
||||
options?.errorMsg ?? (error instanceof Error ? error.message : '下载失败,请重试'),
|
||||
);
|
||||
} finally {
|
||||
busyRef.current = false;
|
||||
setDownloading(false);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return { downloading, run };
|
||||
}
|
||||
|
||||
export default useDownload;
|
||||
37
apps/admin/src/hooks/usePageVisible.ts
Normal file
37
apps/admin/src/hooks/usePageVisible.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useLocation } from 'react-router';
|
||||
import { useQueryClient, type QueryKey } from '@tanstack/react-query';
|
||||
import { useActivePage } from '../components/routeKeeperContext';
|
||||
|
||||
/**
|
||||
* 当前页面是否处于激活(可见)状态。
|
||||
* RouteKeeper 保活页面始终挂载,只有激活页可见;配合
|
||||
* `useVisibleRefetch` 可在切回页面时刷新数据。
|
||||
*/
|
||||
export function usePageVisible(): boolean {
|
||||
const activePage = useActivePage();
|
||||
const location = useLocation();
|
||||
return activePage === location.pathname;
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面重新变为可见时刷新指定 queryKey 的数据。
|
||||
* 解决 RouteKeeper 保活导致的「切回列表页看不到新增/删除数据」问题。
|
||||
*
|
||||
* 用法:`useVisibleRefetch(['students']);`
|
||||
*
|
||||
* 注意:queryKey 通过 ref 持有,effect 只依赖 visible,
|
||||
* 避免调用方每次渲染传入新数组字面量导致频繁重复请求。
|
||||
*/
|
||||
export function useVisibleRefetch(queryKey: QueryKey | undefined): void {
|
||||
const visible = usePageVisible();
|
||||
const queryClient = useQueryClient();
|
||||
const keyRef = useRef(queryKey);
|
||||
keyRef.current = queryKey;
|
||||
|
||||
useEffect(() => {
|
||||
if (visible && keyRef.current) {
|
||||
void queryClient.refetchQueries({ queryKey: keyRef.current });
|
||||
}
|
||||
}, [visible, queryClient]);
|
||||
}
|
||||
19
apps/admin/src/hooks/useSubmitShortcut.ts
Normal file
19
apps/admin/src/hooks/useSubmitShortcut.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
/**
|
||||
* 弹窗/表单内按 Cmd/Ctrl+Enter 触发表单提交。
|
||||
* 仅在 active(弹窗打开且非保存中)时监听,避免误触。
|
||||
*/
|
||||
export function useSubmitShortcut(active: boolean, onSubmit: () => void): void {
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
onSubmit();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [active, onSubmit]);
|
||||
}
|
||||
@@ -514,3 +514,68 @@ canvas {
|
||||
padding-inline: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* ─── 全局无障碍与质感增强 ─── */
|
||||
html {
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
::selection {
|
||||
background: rgba(0, 122, 255, 0.18);
|
||||
}
|
||||
|
||||
/* 键盘导航焦点可见(鼠标点击不显示,符合 WCAG 2.4.7) */
|
||||
:focus-visible {
|
||||
outline: 2px solid #007aff;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* 细滚动条(macOS/Chromium),降低大面积滚动条对视觉的干扰 */
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: rgba(0, 0, 0, 0.16);
|
||||
border: 2px solid transparent;
|
||||
border-radius: 8px;
|
||||
background-clip: content-box;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background-color: rgba(0, 0, 0, 0.28);
|
||||
}
|
||||
|
||||
/* 尊重系统「减少动态效果」偏好 */
|
||||
/* 窄屏下压缩路由标签尺寸,避免横向裁切 */
|
||||
@media (max-width: 575px) {
|
||||
.route-dock {
|
||||
padding: 6px 8px;
|
||||
}
|
||||
|
||||
.route-dock .ant-tabs-tab {
|
||||
min-width: 88px;
|
||||
max-width: 160px;
|
||||
padding: 0 8px 0 10px !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
html {
|
||||
scroll-behavior: auto;
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ import { AUTH_STORAGE_NAME, PERMISSION_STORAGE_NAME } from '../store/middleware/
|
||||
import NotificationBell from '../components/NotificationBell';
|
||||
import RouteDock from '../components/RouteDock';
|
||||
import RouteKeeper from '../components/RouteKeeper';
|
||||
import BackTop from '../components/BackTop';
|
||||
import { buildMenu, type AppMenuItem } from '../auth/menu-policy';
|
||||
|
||||
const AiChatDrawer = React.lazy(() => import('../components/AiChat/AiChatDrawer'));
|
||||
@@ -195,6 +196,7 @@ const MainLayout: React.FC = () => {
|
||||
const handleLogout = useCallback(() => {
|
||||
logoutUser();
|
||||
usePermissionStore.getState().clearPermissions();
|
||||
useAppStore.getState().setRouteDockTabs([]);
|
||||
navigate('/login');
|
||||
}, [logoutUser, navigate]);
|
||||
|
||||
@@ -431,6 +433,7 @@ const MainLayout: React.FC = () => {
|
||||
/>
|
||||
</React.Suspense>
|
||||
)}
|
||||
<BackTop />
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { QueryClientProvider } from '@tanstack/react-query';
|
||||
import { queryClient } from './api/queryClient';
|
||||
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
|
||||
import App from './App';
|
||||
import AppErrorBoundary from './components/AppErrorBoundary';
|
||||
import './index.css';
|
||||
import dayjs from 'dayjs';
|
||||
import 'dayjs/locale/zh-cn';
|
||||
@@ -28,23 +30,16 @@ dayjs.extend(updateLocale);
|
||||
// 必须在所有插件加载后设置 locale
|
||||
dayjs.locale('zh-cn');
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: 1,
|
||||
staleTime: 30_000,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const rootElement = document.getElementById('root');
|
||||
if (!rootElement) throw new Error('未找到 #root 挂载点');
|
||||
|
||||
ReactDOM.createRoot(rootElement).render(
|
||||
<React.StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
{import.meta.env.DEV && <ReactQueryDevtools initialIsOpen={false} />}
|
||||
</QueryClientProvider>
|
||||
<AppErrorBoundary>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
{import.meta.env.DEV && <ReactQueryDevtools initialIsOpen={false} />}
|
||||
</QueryClientProvider>
|
||||
</AppErrorBoundary>
|
||||
</React.StrictMode>,
|
||||
);
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useQuery } from '@tanstack/react-query';
|
||||
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||
import { validateResponse } from '../../utils/validate';
|
||||
import { aiConfigEnvelopeSchema } from '../../api/schemas';
|
||||
import { App, Alert, Button, Form, Space, Spin, Steps, Tag } from 'antd';
|
||||
import {App, Alert, Button, Form, Space, Steps, Tag, Skeleton} from 'antd';
|
||||
import api from '../../api';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
@@ -332,8 +332,8 @@ const AiConfigPage: React.FC = () => {
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className={styles.container} style={{ textAlign: 'center', paddingTop: 80 }}>
|
||||
<Spin size="large" />
|
||||
<div className={styles.container} style={{ paddingTop: 24 }}>
|
||||
<Skeleton active paragraph={{ rows: 10 }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -157,7 +157,7 @@ export const ADMIN_METRIC_META = [
|
||||
];
|
||||
|
||||
function pickPrimaryStatus(records: AttendanceRecordItem[]) {
|
||||
const priority = ['absent', 'leave', 'present'];
|
||||
const priority = ['absent', 'leave', 'late', 'present'];
|
||||
return (
|
||||
priority.find((item) =>
|
||||
records.some((record) => displayAttendanceStatus(record.status) === item),
|
||||
@@ -189,7 +189,10 @@ export function buildAdminStudentPanels(records: AttendanceRecordItem[]): AdminS
|
||||
}
|
||||
|
||||
return Array.from(map.values()).map((item) => {
|
||||
const checked = item.records.filter((record) => record.status === 'present').length;
|
||||
// late 与 present 一样视为已出勤(与 attendance-workspace 一致)
|
||||
const checked = item.records.filter(
|
||||
(record) => record.status === 'present' || record.status === 'late',
|
||||
).length;
|
||||
return {
|
||||
...item,
|
||||
primaryStatus: pickPrimaryStatus(item.records),
|
||||
|
||||
@@ -27,7 +27,8 @@ export const PeriodConfigModal: React.FC<{
|
||||
onOk: () => void;
|
||||
onCancel: () => void;
|
||||
onReset: () => void;
|
||||
}> = ({ open, form, onOk, onCancel, onReset }) => {
|
||||
confirmLoading?: boolean;
|
||||
}> = ({ open, form, onOk, onCancel, onReset, confirmLoading }) => {
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
@@ -37,6 +38,7 @@ export const PeriodConfigModal: React.FC<{
|
||||
className="attendance-period-modal"
|
||||
onOk={onOk}
|
||||
onCancel={onCancel}
|
||||
confirmLoading={confirmLoading}
|
||||
footer={(_, { OkBtn, CancelBtn }) => (
|
||||
<>
|
||||
<Button icon={<UndoOutlined />} onClick={onReset}>
|
||||
@@ -54,7 +56,7 @@ export const PeriodConfigModal: React.FC<{
|
||||
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 form={form} layout="vertical" scrollToFirstError>
|
||||
<Form.List name="periods">
|
||||
{(fields, { add, remove }) => (
|
||||
<div className="attendance-period-editor">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from 'react';
|
||||
import { Card, Empty, Input, Spin, Table } from 'antd';
|
||||
import { Button, Card, Empty, Input, Spin, Table } from 'antd';
|
||||
import { ExportOutlined } from '@ant-design/icons';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import {
|
||||
@@ -27,6 +27,11 @@ export const AttendanceAdminWorkspace: React.FC<{
|
||||
pageSize: number;
|
||||
total: number;
|
||||
onPageChange: (page: number, pageSize: number) => void;
|
||||
/** 明细表批量纠错 */
|
||||
selectedRecordKeys: number[];
|
||||
onSelectRecords: (keys: number[]) => void;
|
||||
onBatchCorrect: (status: string) => void;
|
||||
batchCorrecting: boolean;
|
||||
}> = ({
|
||||
metricFilter,
|
||||
studentSearch,
|
||||
@@ -44,6 +49,10 @@ export const AttendanceAdminWorkspace: React.FC<{
|
||||
pageSize,
|
||||
total,
|
||||
onPageChange,
|
||||
selectedRecordKeys,
|
||||
onSelectRecords,
|
||||
onBatchCorrect,
|
||||
batchCorrecting,
|
||||
}) => {
|
||||
return (
|
||||
<>
|
||||
@@ -135,12 +144,51 @@ export const AttendanceAdminWorkspace: React.FC<{
|
||||
</section>
|
||||
|
||||
<Card className="student-record-card" variant="borderless" title="原始考勤明细">
|
||||
{selectedRecordKeys.length > 0 ? (
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 8,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
flexWrap: 'wrap',
|
||||
}}
|
||||
>
|
||||
<span>已选 {selectedRecordKeys.length} 条</span>
|
||||
<Button
|
||||
size="small"
|
||||
type="primary"
|
||||
loading={batchCorrecting}
|
||||
onClick={() => onBatchCorrect('present')}
|
||||
>
|
||||
标记正常
|
||||
</Button>
|
||||
<Button size="small" loading={batchCorrecting} onClick={() => onBatchCorrect('leave')}>
|
||||
标记请假
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
danger
|
||||
loading={batchCorrecting}
|
||||
onClick={() => onBatchCorrect('absent')}
|
||||
>
|
||||
标记缺勤
|
||||
</Button>
|
||||
<Button size="small" type="text" onClick={() => onSelectRecords([])}>
|
||||
清空选择
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
<Table<AttendanceRecordItem>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={records}
|
||||
loading={loading}
|
||||
scroll={{ x: 'max-content' }}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedRecordKeys,
|
||||
onChange: (keys) => onSelectRecords(keys as number[]),
|
||||
}}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Alert, Avatar, Button, Drawer, Empty, Input, Progress, Select, Table, Tag } from 'antd';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Alert, App, Avatar, Button, Drawer, Empty, Input, Progress, Select, Table, Tag } from 'antd';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { QueryErrorState } from '../../components/QueryState';
|
||||
import {
|
||||
filterLessonAttendanceRecords,
|
||||
getPunchDisplayInfo,
|
||||
@@ -78,43 +79,108 @@ const LessonAttendanceDetail: React.FC<LessonAttendanceDetailProps> = ({
|
||||
className,
|
||||
onClose,
|
||||
}) => {
|
||||
const { modal } = App.useApp();
|
||||
const { hasAnyPermission } = usePermission();
|
||||
const canEditAttendance = hasAnyPermission('attendance:edit', 'attendance:self-edit');
|
||||
const [loadedSchedule, setLoadedSchedule] = useState<LessonAttendanceSchedule | null>(null);
|
||||
const [session, setSession] = useState<LessonAttendanceSession | null>(null);
|
||||
const [records, setRecords] = useState<LessonAttendanceRecord[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [filter, setFilter] = useState<LessonAttendanceFilter>('all');
|
||||
const [batchUpdating, setBatchUpdating] = useState<'present' | 'absent' | null>(null);
|
||||
// 组件以 key 重挂载(关闭/切换课节),卸载后 in-flight 请求不再更新状态或弹提示
|
||||
const cancelledRef = useRef(false);
|
||||
|
||||
/** 一键全部已打卡/全部未打卡(仅对状态不一致的记录) */
|
||||
const handleBatchMark = async (status: 'present' | 'absent') => {
|
||||
if (batchUpdating || records.length === 0) return;
|
||||
const targetIds = records
|
||||
.filter((record) =>
|
||||
status === 'present'
|
||||
? record.status !== 'present' && record.status !== 'late'
|
||||
: record.status !== 'absent',
|
||||
)
|
||||
.map((record) => record.id);
|
||||
if (targetIds.length === 0) {
|
||||
message.success(status === 'present' ? '所有学生都已打卡' : '所有学生都未打卡');
|
||||
return;
|
||||
}
|
||||
modal.confirm({
|
||||
title: status === 'present' ? `将 ${targetIds.length} 名学生标记为已打卡?` : `将 ${targetIds.length} 名学生标记为未打卡?`,
|
||||
content:
|
||||
'此操作会立即写入考勤记录;已结算(课程截止后)的记录无法修改。',
|
||||
okText: '确认',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
setBatchUpdating(status);
|
||||
try {
|
||||
const res = await api.put<{
|
||||
updated: number;
|
||||
failed: number;
|
||||
failedIds: number[];
|
||||
systemFailed: number;
|
||||
}>('/attendance-records/batch-status', { ids: targetIds, status });
|
||||
if (cancelledRef.current) return;
|
||||
const failedSet = new Set(res.failedIds);
|
||||
setRecords((items) =>
|
||||
items.map((record) =>
|
||||
targetIds.includes(record.id) && !failedSet.has(record.id)
|
||||
? { ...record, status }
|
||||
: record,
|
||||
),
|
||||
);
|
||||
message.success(`已更新 ${res.updated} 条记录`);
|
||||
if (res.failed > 0) {
|
||||
const bizFailed = res.failed - (res.systemFailed ?? 0);
|
||||
const parts: string[] = [];
|
||||
if (bizFailed > 0) parts.push(`${bizFailed} 条可能已结算`);
|
||||
if (res.systemFailed > 0) parts.push(`${res.systemFailed} 条系统错误`);
|
||||
message.warning(`有 ${res.failed} 条更新失败:${parts.join(',')}`);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (cancelledRef.current) return;
|
||||
message.error(getErrorMessage(error, '批量更新失败'));
|
||||
} finally {
|
||||
if (!cancelledRef.current) setBatchUpdating(null);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const loadLesson = useCallback(async () => {
|
||||
if (!schedule) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const date = dayjs().format('YYYY-MM-DD');
|
||||
try {
|
||||
const data = await api.post<LessonAttendanceResponse>(
|
||||
`/attendance-lessons/schedules/${schedule.id}/pull`,
|
||||
{ date },
|
||||
);
|
||||
if (cancelledRef.current) return;
|
||||
setLoadedSchedule(data.schedule);
|
||||
setSession(data.session);
|
||||
setRecords(data.records);
|
||||
message.success('钉钉打卡已更新;课程截止后系统将自动结算');
|
||||
} catch (error: unknown) {
|
||||
if (cancelledRef.current) return;
|
||||
setError(getErrorMessage(error, '加载本节课考勤失败'));
|
||||
} finally {
|
||||
if (!cancelledRef.current) setLoading(false);
|
||||
}
|
||||
}, [schedule]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!schedule) return;
|
||||
let cancelled = false;
|
||||
cancelledRef.current = false;
|
||||
setLoadedSchedule(schedule);
|
||||
setLoading(true);
|
||||
const date = dayjs().format('YYYY-MM-DD');
|
||||
void api
|
||||
.post<LessonAttendanceResponse>(`/attendance-lessons/schedules/${schedule.id}/pull`, {
|
||||
date,
|
||||
})
|
||||
.then((data) => {
|
||||
if (cancelled) return;
|
||||
setLoadedSchedule(data.schedule);
|
||||
setSession(data.session);
|
||||
setRecords(data.records);
|
||||
message.success('钉钉打卡已更新;课程截止后系统将自动结算');
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (cancelled) return;
|
||||
message.error(getErrorMessage(error, '加载本节课考勤失败'));
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
void loadLesson();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
cancelledRef.current = true;
|
||||
};
|
||||
}, [schedule]);
|
||||
}, [schedule, loadLesson]);
|
||||
|
||||
const updateRecord = useCallback(async (record: LessonAttendanceRecord, status: string) => {
|
||||
const previous = record.status;
|
||||
@@ -184,20 +250,47 @@ const LessonAttendanceDetail: React.FC<LessonAttendanceDetailProps> = ({
|
||||
<span className="lesson-record-filter-count">
|
||||
显示 {filteredRecords.length} / {records.length} 人
|
||||
</span>
|
||||
{canEditAttendance && records.length > 0 ? (
|
||||
<>
|
||||
<Button
|
||||
size="small"
|
||||
type="primary"
|
||||
loading={batchUpdating === 'present'}
|
||||
onClick={() => void handleBatchMark('present')}
|
||||
>
|
||||
全部已打卡
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
danger
|
||||
loading={batchUpdating === 'absent'}
|
||||
onClick={() => void handleBatchMark('absent')}
|
||||
>
|
||||
全部未打卡
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
<Table<LessonAttendanceRecord>
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
dataSource={filteredRecords}
|
||||
pagination={false}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<Empty
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
description={records.length === 0 ? '本节课尚未开始点名' : '没有符合条件的学生'}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
{error ? (
|
||||
<QueryErrorState
|
||||
title="本节课考勤加载失败"
|
||||
description={error}
|
||||
onRetry={() => void loadLesson()}
|
||||
/>
|
||||
) : (
|
||||
<Table<LessonAttendanceRecord> scroll={{ x: 'max-content' }}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
dataSource={filteredRecords}
|
||||
pagination={false}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<Empty
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
description={records.length === 0 ? '本节课尚未开始点名' : '没有符合条件的学生'}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
title: '学生',
|
||||
@@ -264,7 +357,8 @@ const LessonAttendanceDetail: React.FC<LessonAttendanceDetailProps> = ({
|
||||
render: (value: string | null) => value || <span className="muted-text">—</span>,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
/>
|
||||
)}
|
||||
</Drawer>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import React, { useCallback, useMemo, useState } from 'react';
|
||||
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 { getErrorMessage } from '../../utils/error';
|
||||
import {
|
||||
attendanceAlertsSchema,
|
||||
attendanceClassOptionsSchema,
|
||||
@@ -11,13 +12,14 @@ import {
|
||||
attendanceSummarySchema,
|
||||
dingTalkSyncStatusSchema,
|
||||
} from '../../api/schemas';
|
||||
import { Form, Grid } from 'antd';
|
||||
import { App, 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 { QueryErrorState } from '../../components/QueryState';
|
||||
import { useVisibleRefetch } from '../../hooks/usePageVisible';
|
||||
import { AttendanceAdminHeader } from './AttendanceAdminHeader';
|
||||
import { buildAttendanceAdminColumns } from './AttendanceAdminColumns';
|
||||
import { PeriodConfigModal, StudentDetailDrawer } from './AttendanceAdminModals';
|
||||
@@ -37,8 +39,10 @@ import {
|
||||
type DingTalkSyncStatus,
|
||||
type HistoryScheduleOption,
|
||||
} from './AttendanceAdmin.helpers';
|
||||
import { saveAs } from 'file-saver';
|
||||
|
||||
export const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) => {
|
||||
const { modal } = App.useApp();
|
||||
const screens = Grid.useBreakpoint();
|
||||
const isMobile = !screens.sm;
|
||||
const [periodModalOpen, setPeriodModalOpen] = useState(false);
|
||||
@@ -55,7 +59,11 @@ export const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit
|
||||
const [studentSearch, setStudentSearch] = useState('');
|
||||
const [selectedStudent, setSelectedStudent] = useState<AdminStudentPanel | null>(null);
|
||||
const [correctingRecordId, setCorrectingRecordId] = useState<number | null>(null);
|
||||
// 明细表批量纠错:选中的记录 ID + 执行中状态
|
||||
const [selectedRecordIds, setSelectedRecordIds] = useState<number[]>([]);
|
||||
const [batchCorrecting, setBatchCorrecting] = useState(false);
|
||||
const queryClient = useQueryClient();
|
||||
useVisibleRefetch(['attendance', 'records']);
|
||||
const recordQueryKey = [
|
||||
'attendance',
|
||||
'records',
|
||||
@@ -68,44 +76,34 @@ export const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit
|
||||
scheduleId,
|
||||
] as const;
|
||||
|
||||
// 筛选条件变化时清空批量选择,避免把上一批条件的记录带到新条件下提交
|
||||
useEffect(() => {
|
||||
setSelectedRecordIds([]);
|
||||
}, [classId, attendanceDate, status, session, scheduleId]);
|
||||
|
||||
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 [];
|
||||
}
|
||||
},
|
||||
queryFn: async () =>
|
||||
validateResponse<ClassOption[]>(
|
||||
attendanceClassOptionsSchema,
|
||||
await api.get<ClassOption[]>('/attendance-records/classes'),
|
||||
),
|
||||
});
|
||||
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 [];
|
||||
}
|
||||
},
|
||||
queryFn: async () =>
|
||||
validateResponse<AlertItem[]>(
|
||||
attendanceAlertsSchema,
|
||||
await api.get<AlertItem[]>('/attendance-records/alerts'),
|
||||
),
|
||||
});
|
||||
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;
|
||||
}
|
||||
},
|
||||
queryFn: async () =>
|
||||
validateResponse<AttendancePeriodConfigItem[]>(
|
||||
attendancePeriodsSchema,
|
||||
await api.get<AttendancePeriodConfigItem[]>('/attendance-period-configs'),
|
||||
),
|
||||
});
|
||||
const {
|
||||
data: scheduleOptions = [],
|
||||
@@ -114,18 +112,13 @@ export const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit
|
||||
queryKey: ['attendance', 'schedules', classId, attendanceDate],
|
||||
enabled: !!classId && !!attendanceDate,
|
||||
queryFn: async () => {
|
||||
try {
|
||||
if (!attendanceDate) return [];
|
||||
return validateResponse<HistoryScheduleOption[]>(
|
||||
attendanceScheduleOptionsSchema,
|
||||
await api.get<HistoryScheduleOption[]>('/attendance-records/schedules', {
|
||||
params: { classId, date: attendanceDate.format('YYYY-MM-DD') },
|
||||
}),
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
message.error(getErrorMessage(error, '加载班级科目失败'));
|
||||
return [];
|
||||
}
|
||||
if (!attendanceDate) return [];
|
||||
return validateResponse<HistoryScheduleOption[]>(
|
||||
attendanceScheduleOptionsSchema,
|
||||
await api.get<HistoryScheduleOption[]>('/attendance-records/schedules', {
|
||||
params: { classId, date: attendanceDate.format('YYYY-MM-DD') },
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
const scheduleOptionsLoading = scheduleOptionsFetching;
|
||||
@@ -187,13 +180,24 @@ export const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit
|
||||
}
|
||||
};
|
||||
|
||||
const resetPeriodConfig = async () => {
|
||||
try {
|
||||
await resetPeriodConfigMutation.mutateAsync();
|
||||
message.success('已恢复默认考勤时段');
|
||||
} catch {
|
||||
// 错误提示由 useApiMutation 统一处理
|
||||
}
|
||||
const resetPeriodConfig = () => {
|
||||
modal.confirm({
|
||||
title: '恢复默认考勤时段?',
|
||||
content: '当前自定义的考勤时段配置将被系统默认值覆盖,此操作不可撤销。',
|
||||
okText: '恢复默认',
|
||||
okButtonProps: { danger: true },
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
try {
|
||||
const data = await resetPeriodConfigMutation.mutateAsync();
|
||||
// 同步回填表单,避免界面仍显示旧配置、用户再点保存把旧值写回
|
||||
periodForm.setFieldsValue({ periods: data });
|
||||
message.success('已恢复默认考勤时段');
|
||||
} catch {
|
||||
// 错误提示由 useApiMutation 统一处理
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const buildParams = useCallback(
|
||||
@@ -216,22 +220,18 @@ export const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit
|
||||
|
||||
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;
|
||||
}
|
||||
},
|
||||
queryFn: async () =>
|
||||
validateResponse<DingTalkSyncStatus>(
|
||||
dingTalkSyncStatusSchema,
|
||||
await api.get<DingTalkSyncStatus>('/attendance-records/dingtalk-sync-status'),
|
||||
),
|
||||
});
|
||||
const loadSyncStatus = useCallback(() => refetchSyncStatus(), [refetchSyncStatus]);
|
||||
|
||||
const {
|
||||
data: recordQuery = { records: [], total: 0, summary: EMPTY_SUMMARY },
|
||||
isFetching: recordsFetching,
|
||||
isError: recordsError,
|
||||
refetch: refetchRecords,
|
||||
} = useQuery<{
|
||||
records: AttendanceRecordItem[];
|
||||
@@ -240,32 +240,27 @@ export const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit
|
||||
}>({
|
||||
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 [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 },
|
||||
};
|
||||
},
|
||||
});
|
||||
const records = recordQuery.records;
|
||||
@@ -355,14 +350,7 @@ export const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit
|
||||
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);
|
||||
})
|
||||
.then((blob) => saveAs(blob, `学生考勤-${dayjs().format('YYYYMMDD')}.xlsx`))
|
||||
.catch(() => message.error('导出失败'));
|
||||
}, [buildParams]);
|
||||
|
||||
@@ -415,6 +403,44 @@ export const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit
|
||||
}
|
||||
};
|
||||
|
||||
/** 批量纠错:对选中的明细记录统一标记状态 */
|
||||
const batchCorrectStatus = async (nextStatus: string) => {
|
||||
if (selectedRecordIds.length === 0) return;
|
||||
const statusLabel =
|
||||
nextStatus === 'present' ? '正常' : nextStatus === 'leave' ? '请假' : '缺勤';
|
||||
modal.confirm({
|
||||
title: `将选中的 ${selectedRecordIds.length} 条记录标记为「${statusLabel}」?`,
|
||||
content: '此操作会立即写入考勤记录;已结算的记录无法修改。',
|
||||
okText: '确认',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
setBatchCorrecting(true);
|
||||
try {
|
||||
const res = await api.put<{
|
||||
updated: number;
|
||||
failed: number;
|
||||
failedIds: number[];
|
||||
systemFailed: number;
|
||||
}>('/attendance-records/batch-status', { ids: selectedRecordIds, status: nextStatus });
|
||||
setSelectedRecordIds([]);
|
||||
message.success(`已更新 ${res.updated} 条记录`);
|
||||
if (res.failed > 0) {
|
||||
const bizFailed = res.failed - (res.systemFailed ?? 0);
|
||||
const parts: string[] = [];
|
||||
if (bizFailed > 0) parts.push(`${bizFailed} 条可能已结算`);
|
||||
if (res.systemFailed > 0) parts.push(`${res.systemFailed} 条系统错误`);
|
||||
message.warning(`有 ${res.failed} 条更新失败:${parts.join(',')}`);
|
||||
}
|
||||
void refetchRecords();
|
||||
} catch (e: unknown) {
|
||||
message.error(getErrorMessage(e, '批量更新失败'));
|
||||
} finally {
|
||||
setBatchCorrecting(false);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const saveAdminRecordCell = async (
|
||||
record: AttendanceRecordItem,
|
||||
field: 'status' | 'remark',
|
||||
@@ -532,27 +558,39 @@ export const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit
|
||||
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);
|
||||
}}
|
||||
/>
|
||||
{recordsError ? (
|
||||
<QueryErrorState
|
||||
title="学生考勤数据加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetchRecords()}
|
||||
/>
|
||||
) : (
|
||||
<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);
|
||||
}}
|
||||
selectedRecordKeys={selectedRecordIds}
|
||||
onSelectRecords={setSelectedRecordIds}
|
||||
onBatchCorrect={batchCorrectStatus}
|
||||
batchCorrecting={batchCorrecting}
|
||||
/>
|
||||
)}
|
||||
|
||||
<StudentDetailDrawer
|
||||
student={selectedStudent}
|
||||
@@ -571,6 +609,7 @@ export const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit
|
||||
onOk={savePeriodConfig}
|
||||
onCancel={() => setPeriodModalOpen(false)}
|
||||
onReset={() => void resetPeriodConfig()}
|
||||
confirmLoading={savePeriodConfigMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -59,13 +59,6 @@
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.attendance-eyebrow {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 1.7px;
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.teacher-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import React from 'react';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
import { useUserStore } from '../../store/user/userStore';
|
||||
import { getAttendanceExperience } from './attendance-workspace';
|
||||
@@ -6,14 +6,11 @@ import { TeacherAttendanceWorkspace } from './teacher';
|
||||
import { AdminAttendanceArchive } from './admin';
|
||||
import './attendance.css';
|
||||
|
||||
function readCurrentRoles(): string[] {
|
||||
const roles = useUserStore.getState().user?.roles;
|
||||
return Array.isArray(roles) ? roles : [];
|
||||
}
|
||||
|
||||
const AttendancePage: React.FC = () => {
|
||||
const { permissions, hasPermission } = usePermission();
|
||||
const roles = useMemo(readCurrentRoles, []);
|
||||
// 订阅 store:角色变化时重新计算体验(不再只在首渲染读一次)
|
||||
const rolesRef = useUserStore((s) => s.user?.roles);
|
||||
const roles = Array.isArray(rolesRef) ? rolesRef : [];
|
||||
const experience = getAttendanceExperience(permissions, roles);
|
||||
|
||||
if (experience === 'teacher') {
|
||||
|
||||
@@ -11,8 +11,7 @@ import {
|
||||
} from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { getErrorMessage } from '../../utils/error';
|
||||
import { QueryErrorState } from '../../components/QueryState';
|
||||
import {
|
||||
canPullAttendance,
|
||||
getSchedulePhase,
|
||||
@@ -41,21 +40,18 @@ export const TeacherAttendanceWorkspace: React.FC<{ canCreate: boolean }> = ({ c
|
||||
|
||||
const {
|
||||
data: workspace,
|
||||
isLoading,
|
||||
isFetching,
|
||||
isPending,
|
||||
isError,
|
||||
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;
|
||||
}
|
||||
return await api.get<TeacherWorkspaceData>('/rbac/teacher-workspace');
|
||||
},
|
||||
});
|
||||
const loading = isLoading || isFetching;
|
||||
// isPending 覆盖自动重试的退避窗口,避免「加载失败/重试中」短暂闪现为空态
|
||||
const loading = isPending || isFetching;
|
||||
const loadWorkspace = useCallback(() => refetch(), [refetch]);
|
||||
|
||||
const classNameById = useMemo(
|
||||
@@ -80,11 +76,10 @@ export const TeacherAttendanceWorkspace: React.FC<{ canCreate: boolean }> = ({ c
|
||||
<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>
|
||||
<p>
|
||||
{dayjs().format('MM月DD日 dddd')} · 课程开始后可查看最新打卡结果;课程截止时系统自动拉取并结算缺勤。
|
||||
</p>
|
||||
</div>
|
||||
<Button icon={<ReloadOutlined />} onClick={() => void loadWorkspace()}>
|
||||
刷新
|
||||
@@ -124,7 +119,15 @@ export const TeacherAttendanceWorkspace: React.FC<{ canCreate: boolean }> = ({ c
|
||||
</div>
|
||||
|
||||
<Spin spinning={loading}>
|
||||
{schedules.length === 0 ? (
|
||||
{isError ? (
|
||||
<Card className="attendance-empty-card">
|
||||
<QueryErrorState
|
||||
title="课程数据加载失败"
|
||||
description="请检查网络后点击重试;若持续失败请联系管理员。"
|
||||
onRetry={() => void loadWorkspace()}
|
||||
/>
|
||||
</Card>
|
||||
) : schedules.length === 0 ? (
|
||||
<Card className="attendance-empty-card">
|
||||
<Empty
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
|
||||
@@ -3,18 +3,22 @@ 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 { Form, Input, Modal, Popconfirm, Select, Space, Table, Tag } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { PlusOutlined } from '@ant-design/icons';
|
||||
import api from '../api';
|
||||
import PermissionButton from '../components/PermissionButton';
|
||||
import EditableCell from '../components/EditableCell';
|
||||
import { QueryErrorState, QueryEmpty } from '../components/QueryState';
|
||||
import { message } from '../ui/app-message';
|
||||
import { useDirtyGuard } from '../hooks/useDirtyGuard';
|
||||
import { usePermission } from '../hooks/usePermission';
|
||||
|
||||
interface ClassroomOption {
|
||||
id: number;
|
||||
name: string;
|
||||
building?: string | null;
|
||||
status?: string;
|
||||
}
|
||||
|
||||
interface AttendanceDeviceRow {
|
||||
@@ -34,35 +38,34 @@ const statusMeta = {
|
||||
} as const;
|
||||
|
||||
const AttendanceDevicesPage: React.FC = () => {
|
||||
const { hasPermission } = usePermission();
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<AttendanceDeviceRow | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [form] = Form.useForm();
|
||||
const formGuard = useDirtyGuard(form);
|
||||
|
||||
const {
|
||||
data: fetchResult = { devices: [], classrooms: [] },
|
||||
isLoading,
|
||||
isFetching,
|
||||
isError,
|
||||
refetch,
|
||||
} = useQuery<{ devices: AttendanceDeviceRow[]; classrooms: ClassroomOption[] }>({
|
||||
queryKey: ['attendance-devices'],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
const [devices, classroomList] = await Promise.all([
|
||||
api.get<AttendanceDeviceRow[]>('/attendance-devices'),
|
||||
api.get<ClassroomOption[]>('/classrooms'),
|
||||
]);
|
||||
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 [devices, classroomList] = await Promise.all([
|
||||
api.get<AttendanceDeviceRow[]>('/attendance-devices'),
|
||||
api.get<ClassroomOption[]>('/classrooms'),
|
||||
]);
|
||||
return {
|
||||
devices: validateResponse<AttendanceDeviceRow[]>(attendanceDevicesSchema, devices),
|
||||
classrooms: validateResponse<ClassroomOption[]>(
|
||||
classroomOptionsSchema,
|
||||
classroomList,
|
||||
).filter((item: ClassroomOption) => item.status !== 'archived'),
|
||||
};
|
||||
},
|
||||
});
|
||||
const data = fetchResult.devices;
|
||||
@@ -109,6 +112,7 @@ const AttendanceDevicesPage: React.FC = () => {
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
form.setFieldsValue({ status: 'active' });
|
||||
formGuard.snapshot();
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
@@ -122,6 +126,7 @@ const AttendanceDevicesPage: React.FC = () => {
|
||||
location: record.location,
|
||||
notes: record.notes,
|
||||
});
|
||||
formGuard.snapshot();
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
@@ -307,22 +312,43 @@ const AttendanceDevicesPage: React.FC = () => {
|
||||
添加考勤机
|
||||
</PermissionButton>
|
||||
</div>
|
||||
<Table<AttendanceDeviceRow>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={filteredData}
|
||||
loading={loading}
|
||||
locale={{ emptyText: <Empty description="暂无考勤机绑定" /> }}
|
||||
pagination={{ defaultPageSize: 20, showSizeChanger: true }}
|
||||
/>
|
||||
{isError ? (
|
||||
<QueryErrorState
|
||||
title="考勤机数据加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
) : (
|
||||
<Table<AttendanceDeviceRow> scroll={{ x: 'max-content' }}
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={filteredData}
|
||||
loading={loading}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<QueryEmpty
|
||||
description="暂无考勤机绑定"
|
||||
action={
|
||||
hasPermission('classroom:edit')
|
||||
? { label: '添加考勤机', icon: <PlusOutlined />, onClick: openCreate }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
pagination={{ defaultPageSize: 20, showSizeChanger: true }}
|
||||
/>
|
||||
)}
|
||||
<Modal
|
||||
title={editing ? '编辑考勤机绑定' : '添加考勤机绑定'}
|
||||
open={modalOpen}
|
||||
onOk={handleSave}
|
||||
onCancel={() => {
|
||||
setModalOpen(false);
|
||||
setEditing(null);
|
||||
}}
|
||||
onCancel={() =>
|
||||
formGuard.confirmClose(() => {
|
||||
setModalOpen(false);
|
||||
setEditing(null);
|
||||
})
|
||||
}
|
||||
confirmLoading={saving}
|
||||
okText="保存"
|
||||
>
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
Input,
|
||||
Select,
|
||||
Spin,
|
||||
Empty,
|
||||
} from 'antd';
|
||||
import {
|
||||
FileTextOutlined,
|
||||
@@ -24,8 +23,12 @@ import {
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { downloadBlob } from '../../utils/download';
|
||||
import { QueryErrorState, QueryEmpty } from '../../components/QueryState';
|
||||
import { NextStepHint } from '../../components/NextStepHint';
|
||||
import { useVisibleRefetch } from '../../hooks/usePageVisible';
|
||||
import { useDownload } from '../../hooks/useDownload';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { RefreshButton } from '../../components/RefreshButton';
|
||||
import { buildBillPrintHtml, type BillPrintData } from './bill-print';
|
||||
import { newOperationId } from '../../utils/operation-id';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
@@ -64,26 +67,27 @@ const BillsPage: React.FC = () => {
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
const [batchLoading, setBatchLoading] = useState(false);
|
||||
// 生成账单成功后的「下一步」引导提示
|
||||
const [billGeneratedHint, setBillGeneratedHint] = useState(false);
|
||||
|
||||
const {
|
||||
data: bills = [],
|
||||
isLoading,
|
||||
isFetching,
|
||||
isError,
|
||||
refetch,
|
||||
} = useQuery({
|
||||
queryKey: ['bills', filterStatus, filterExpenseType],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
const params: Record<string, string | undefined> = {};
|
||||
if (filterStatus) params.status = filterStatus;
|
||||
if (filterExpenseType) params.expenseType = filterExpenseType;
|
||||
return validateResponse<unknown[]>(billsSchema, await api.get('/bills', { params }));
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载失败,请稍后重试');
|
||||
return [];
|
||||
}
|
||||
const params: Record<string, string | undefined> = {};
|
||||
if (filterStatus) params.status = filterStatus;
|
||||
if (filterExpenseType) params.expenseType = filterExpenseType;
|
||||
return validateResponse<unknown[]>(billsSchema, await api.get('/bills', { params }));
|
||||
},
|
||||
});
|
||||
const loading = isLoading || isFetching;
|
||||
// RouteKeeper 保活页面切回时刷新账单列表
|
||||
useVisibleRefetch(['bills']);
|
||||
|
||||
const generateMutation = useApiMutation(
|
||||
async (payload: { operationId: string; billingMonth: string }) =>
|
||||
@@ -122,8 +126,8 @@ const BillsPage: React.FC = () => {
|
||||
}, [bills, searchText, filterStatus]);
|
||||
|
||||
const handleGenerate = async () => {
|
||||
setSaving(true);
|
||||
const values = await generateForm.validateFields();
|
||||
setSaving(true);
|
||||
try {
|
||||
const res: any = await generateMutation.mutateAsync({
|
||||
operationId: newOperationId(),
|
||||
@@ -132,6 +136,7 @@ const BillsPage: React.FC = () => {
|
||||
message.success(res.message || '生成成功');
|
||||
setGenerateModal(false);
|
||||
generateForm.resetFields();
|
||||
setBillGeneratedHint(true);
|
||||
} catch {
|
||||
// 错误提示由 useApiMutation 统一处理
|
||||
} finally {
|
||||
@@ -139,6 +144,11 @@ const BillsPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const openGenerateModal = () => {
|
||||
generateForm.resetFields();
|
||||
setGenerateModal(true);
|
||||
};
|
||||
|
||||
const showDetail = useCallback(async (id: number) => {
|
||||
setDetailLoading(true);
|
||||
try {
|
||||
@@ -228,11 +238,13 @@ const BillsPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const { downloading: exportExcelDownloading, run: runExportExcel } = useDownload();
|
||||
|
||||
const handleExportExcel = () => {
|
||||
downloadBlob('/bills/export/excel', `账单导出_${dayjs().format('YYYYMMDD_HHmmss')}.xlsx`).then(
|
||||
() => message.success('Excel 导出成功'),
|
||||
() => message.error('导出失败'),
|
||||
);
|
||||
void runExportExcel(`/bills/export/excel`, `账单导出_${dayjs().format('YYYYMMDD_HHmmss')}.xlsx`, {
|
||||
successMsg: 'Excel 导出成功',
|
||||
errorMsg: '导出失败',
|
||||
});
|
||||
};
|
||||
|
||||
const handleExportPdf = useCallback(async (billId: number) => {
|
||||
@@ -323,6 +335,7 @@ const BillsPage: React.FC = () => {
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
fixed: 'right' as const,
|
||||
width: 320,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
@@ -450,39 +463,72 @@ const BillsPage: React.FC = () => {
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<RefreshButton loading={isFetching} onRefresh={() => void refetch()} />
|
||||
<PermissionButton
|
||||
permission="bill:generate"
|
||||
type="primary"
|
||||
icon={<FileTextOutlined />}
|
||||
onClick={() => {
|
||||
generateForm.resetFields();
|
||||
setGenerateModal(true);
|
||||
}}
|
||||
onClick={openGenerateModal}
|
||||
>
|
||||
生成账单
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="bill:export-excel"
|
||||
icon={<DownloadOutlined />}
|
||||
loading={exportExcelDownloading}
|
||||
onClick={handleExportExcel}
|
||||
>
|
||||
导出Excel
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
</div>
|
||||
<Table
|
||||
scroll={{ x: 1400 }}
|
||||
columns={columns}
|
||||
dataSource={filteredBills}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
pagination={{ pageSize: 15, showTotal: (total) => `共 ${total} 条` }}
|
||||
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedRows,
|
||||
onChange: (keys) => setSelectedRows(keys as number[]),
|
||||
}}
|
||||
/>
|
||||
{billGeneratedHint && (
|
||||
<NextStepHint
|
||||
title="账单已生成"
|
||||
description="请核对账单明细,确认后标记已付,完成「住宿→计费」闭环。"
|
||||
action={{
|
||||
label: '筛选待确认账单',
|
||||
onClick: () => {
|
||||
// 账单生成后即为 unpaid(待支付)状态
|
||||
setFilterStatus('unpaid');
|
||||
setBillGeneratedHint(false);
|
||||
},
|
||||
}}
|
||||
onClose={() => setBillGeneratedHint(false)}
|
||||
/>
|
||||
)}
|
||||
{isError ? (
|
||||
<QueryErrorState
|
||||
title="账单数据加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
) : (
|
||||
<Table
|
||||
scroll={{ x: 1400 }}
|
||||
columns={columns}
|
||||
dataSource={filteredBills}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
pagination={{ pageSize: 15, showTotal: (total) => `共 ${total} 条` }}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<QueryEmpty
|
||||
description="暂无账单"
|
||||
action={
|
||||
hasPermission('bill:generate')
|
||||
? { label: '生成账单', onClick: openGenerateModal }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedRows,
|
||||
onChange: (keys) => setSelectedRows(keys as number[]),
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
title="生成账单"
|
||||
@@ -521,7 +567,7 @@ const BillsPage: React.FC = () => {
|
||||
>
|
||||
{detailModal && (
|
||||
<Spin spinning={detailLoading}>
|
||||
<Descriptions bordered size="small" column={2} style={{ marginBottom: 16 }}>
|
||||
<Descriptions bordered size="small" column={{ xs: 1, sm: 2 }} style={{ marginBottom: 16 }}>
|
||||
<Descriptions.Item label="学生">{detailModal.student?.name}</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">
|
||||
<Tag color={statusMap[detailModal.status]?.color}>
|
||||
@@ -546,7 +592,7 @@ const BillsPage: React.FC = () => {
|
||||
</strong>
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
<Descriptions bordered size="small" column={3} style={{ marginBottom: 16 }}>
|
||||
<Descriptions bordered size="small" column={{ xs: 1, sm: 2, lg: 3 }} style={{ marginBottom: 16 }}>
|
||||
<Descriptions.Item label="已扣余额">
|
||||
¥{Number(detailModal.paidAmount || 0).toFixed(2)}
|
||||
</Descriptions.Item>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
@@ -22,8 +22,11 @@ import { DownloadOutlined, PlusOutlined } from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import { useUserStore } from '../../store/user/userStore';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { QueryEmpty } from '../../components/QueryState';
|
||||
import { useSubmitShortcut } from '../../hooks/useSubmitShortcut';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { buildTeacherCandidateOptions, type TeacherCandidateUser } from './teacher-candidate';
|
||||
import { saveAs } from 'file-saver';
|
||||
|
||||
export interface ClassStudent {
|
||||
id: number;
|
||||
@@ -204,7 +207,7 @@ export const ClassInfoTab: React.FC<{
|
||||
</Form>
|
||||
) : (
|
||||
<div>
|
||||
<Descriptions column={3} bordered size="small">
|
||||
<Descriptions column={{ xs: 1, sm: 2, lg: 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') : '-'}
|
||||
@@ -246,6 +249,7 @@ export const ClassStudentsTab: React.FC<{
|
||||
onClose: () => void;
|
||||
onRemove: (studentId: number) => void;
|
||||
onSelect: (ids: number[]) => void;
|
||||
adding?: boolean;
|
||||
}> = ({
|
||||
id,
|
||||
detail,
|
||||
@@ -258,7 +262,9 @@ export const ClassStudentsTab: React.FC<{
|
||||
onClose,
|
||||
onRemove,
|
||||
onSelect,
|
||||
adding,
|
||||
}) => {
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const studentColumns: ColumnsType<ClassStudent> = [
|
||||
{ title: '姓名', dataIndex: 'studentName' },
|
||||
{ title: '学号', dataIndex: 'studentNo' },
|
||||
@@ -297,25 +303,24 @@ export const ClassStudentsTab: React.FC<{
|
||||
<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('花名册导出失败'));
|
||||
loading={exporting}
|
||||
onClick={async () => {
|
||||
setExporting(true);
|
||||
try {
|
||||
const token = useUserStore.getState().token;
|
||||
const res = await fetch(`/api/classes/${id}/roster/export`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (!res.ok) throw new Error('导出失败');
|
||||
const blob = await res.blob();
|
||||
saveAs(blob, `班级花名册-${detail?.name || id}.xlsx`);
|
||||
message.success('花名册导出成功');
|
||||
} catch (error) {
|
||||
console.error('花名册导出失败', error);
|
||||
message.error('花名册导出失败');
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
导出花名册
|
||||
@@ -324,13 +329,26 @@ export const ClassStudentsTab: React.FC<{
|
||||
columns={studentColumns}
|
||||
dataSource={students}
|
||||
rowKey="id"
|
||||
locale={{
|
||||
emptyText: (
|
||||
<QueryEmpty
|
||||
description="班级还没有学员"
|
||||
action={{
|
||||
label: '添加学员',
|
||||
type: 'primary',
|
||||
icon: <PlusOutlined />,
|
||||
onClick: onOpen,
|
||||
}}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
pagination={{
|
||||
defaultPageSize: 20,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [20, 50, 100],
|
||||
}}
|
||||
/>
|
||||
<Modal title="添加学员" open={modalOpen} onOk={onAdd} onCancel={onClose}>
|
||||
<Modal title="添加学员" open={modalOpen} onOk={onAdd} onCancel={onClose} confirmLoading={adding}>
|
||||
<Select
|
||||
mode="multiple"
|
||||
style={{ width: '100%' }}
|
||||
@@ -365,6 +383,7 @@ export const ClassTeachersTab: React.FC<{
|
||||
onSubjectChange: (subject: string) => void;
|
||||
onUserChange: (userId?: number) => void;
|
||||
getTeacherName: (teacher: ClassTeacher) => string;
|
||||
adding?: boolean;
|
||||
}> = ({
|
||||
teachers,
|
||||
allUsers,
|
||||
@@ -380,7 +399,9 @@ export const ClassTeachersTab: React.FC<{
|
||||
onSubjectChange,
|
||||
onUserChange,
|
||||
getTeacherName,
|
||||
adding,
|
||||
}) => {
|
||||
useSubmitShortcut(modalOpen, onAdd);
|
||||
const teacherColumns: ColumnsType<ClassTeacher> = [
|
||||
{ title: '姓名', render: (_: unknown, teacher) => getTeacherName(teacher) },
|
||||
{
|
||||
@@ -425,7 +446,7 @@ export const ClassTeachersTab: React.FC<{
|
||||
pageSizeOptions: [20, 50, 100],
|
||||
}}
|
||||
/>
|
||||
<Modal title="添加教师" open={modalOpen} onOk={onAdd} onCancel={onClose}>
|
||||
<Modal title="添加教师" open={modalOpen} onOk={onAdd} onCancel={onClose} confirmLoading={adding}>
|
||||
<Space orientation="vertical" style={{ width: '100%' }}>
|
||||
<Select
|
||||
style={{ width: '100%' }}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useState, useCallback } from 'react';
|
||||
import { useParams, useNavigate } from 'react-router';
|
||||
import { Button, Card, Form, Space, Tabs, Tag } from 'antd';
|
||||
import {Button, Card, Form, Space, Tabs, Tag, Skeleton} from 'antd';
|
||||
import { ArrowLeftOutlined } from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
@@ -8,6 +8,7 @@ import { message } from '../../ui/app-message';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import type { TeacherCandidateUser } from './teacher-candidate';
|
||||
import { getErrorMessage } from '../../utils/error';
|
||||
import { QueryErrorState } from '../../components/QueryState';
|
||||
import {
|
||||
ClassAttendanceTab,
|
||||
ClassInfoTab,
|
||||
@@ -32,6 +33,8 @@ const ClassDetailPage: React.FC = () => {
|
||||
const [studentModalOpen, setStudentModalOpen] = useState(false);
|
||||
const [allStudents, setAllStudents] = useState<StudentItem[]>([]);
|
||||
const [selectedStudentIds, setSelectedStudentIds] = useState<number[]>([]);
|
||||
const [addingStudents, setAddingStudents] = useState(false);
|
||||
const [addingTeacher, setAddingTeacher] = useState(false);
|
||||
|
||||
// Teacher modal state
|
||||
const [teacherModalOpen, setTeacherModalOpen] = useState(false);
|
||||
@@ -51,6 +54,7 @@ const ClassDetailPage: React.FC = () => {
|
||||
data: detailResult = { detail: null, students: [], teachers: [] },
|
||||
isLoading: detailLoading,
|
||||
isFetching: detailFetching,
|
||||
isError: detailError,
|
||||
refetch: refetchDetail,
|
||||
} = useQuery<{
|
||||
detail: ClassDetail | null;
|
||||
@@ -59,13 +63,8 @@ const ClassDetailPage: React.FC = () => {
|
||||
}>({
|
||||
queryKey: ['classes', 'detail', id],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
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 res = (await api.get(`/classes/${id}`)) as ClassDetail;
|
||||
return { detail: res, students: res.students || [], teachers: res.teachers || [] };
|
||||
},
|
||||
});
|
||||
const detail = detailResult.detail;
|
||||
@@ -74,52 +73,50 @@ const ClassDetailPage: React.FC = () => {
|
||||
const loading = detailLoading || detailFetching;
|
||||
const fetchDetail = useCallback(() => refetchDetail(), [refetchDetail]);
|
||||
|
||||
const { data: allUsers = [], refetch: refetchUsers } = useQuery<TeacherCandidateUser[]>({
|
||||
const {
|
||||
data: allUsers = [],
|
||||
isError: allUsersError,
|
||||
refetch: refetchUsers,
|
||||
} = useQuery<TeacherCandidateUser[]>({
|
||||
queryKey: ['rbac', 'users', 'all'],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
return (await api.get('/rbac/users')) as TeacherCandidateUser[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return (await api.get('/rbac/users')) as TeacherCandidateUser[];
|
||||
},
|
||||
});
|
||||
const fetchUsers = useCallback(() => refetchUsers(), [refetchUsers]);
|
||||
|
||||
const { data: schedules = [] } = useQuery<ClassScheduleItem[]>({
|
||||
const {
|
||||
data: schedules = [],
|
||||
isError: schedulesError,
|
||||
refetch: refetchSchedules,
|
||||
} = useQuery<ClassScheduleItem[]>({
|
||||
queryKey: ['classes', 'schedule', id, scheduleDateRange],
|
||||
queryFn: async () => {
|
||||
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 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 })) || [];
|
||||
},
|
||||
});
|
||||
|
||||
const { data: attendanceSummary = null } = useQuery<AttendanceSummary | null>({
|
||||
const {
|
||||
data: attendanceSummary = null,
|
||||
isError: attendanceSummaryError,
|
||||
refetch: refetchAttendanceSummary,
|
||||
} = useQuery<AttendanceSummary | null>({
|
||||
queryKey: ['classes', 'attendance-summary', id, attendanceDateRange],
|
||||
queryFn: async () => {
|
||||
if (!id) return null;
|
||||
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');
|
||||
return (
|
||||
(await api.get<AttendanceSummary>(`/classes/${id}/attendance-summary`, {
|
||||
params,
|
||||
})) || null
|
||||
);
|
||||
} catch (e: unknown) {
|
||||
message.error(getErrorMessage(e, '加载出勤汇总失败'));
|
||||
return null;
|
||||
}
|
||||
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');
|
||||
return (
|
||||
(await api.get<AttendanceSummary>(`/classes/${id}/attendance-summary`, {
|
||||
params,
|
||||
})) || null
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -156,6 +153,7 @@ const ClassDetailPage: React.FC = () => {
|
||||
|
||||
const handleAddStudents = async () => {
|
||||
if (!selectedStudentIds.length) return;
|
||||
setAddingStudents(true);
|
||||
try {
|
||||
await api.post(`/classes/${id}/students`, { studentIds: selectedStudentIds });
|
||||
setStudentModalOpen(false);
|
||||
@@ -164,11 +162,14 @@ const ClassDetailPage: React.FC = () => {
|
||||
message.success('已添加');
|
||||
} catch (e: unknown) {
|
||||
message.error(getErrorMessage(e, '添加失败'));
|
||||
} finally {
|
||||
setAddingStudents(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddTeacher = async () => {
|
||||
if (!teacherUserId) return;
|
||||
setAddingTeacher(true);
|
||||
try {
|
||||
await api.post(`/classes/${id}/teachers`, {
|
||||
userId: teacherUserId,
|
||||
@@ -180,6 +181,8 @@ const ClassDetailPage: React.FC = () => {
|
||||
message.success('已添加');
|
||||
} catch (e: unknown) {
|
||||
message.error(getErrorMessage(e, '添加失败'));
|
||||
} finally {
|
||||
setAddingTeacher(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -221,7 +224,25 @@ const ClassDetailPage: React.FC = () => {
|
||||
const getTeacherName = (teacher: ClassTeacher) =>
|
||||
allUsers.find((user) => user.id === teacher.userId)?.name?.trim() || '-';
|
||||
|
||||
if (!detail) return null;
|
||||
if (!detail) {
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<Skeleton active paragraph={{ rows: 8 }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (detailError) {
|
||||
return (
|
||||
<QueryErrorState
|
||||
title="班级详情加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetchDetail()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Card
|
||||
@@ -283,13 +304,20 @@ const ClassDetailPage: React.FC = () => {
|
||||
onClose={() => setStudentModalOpen(false)}
|
||||
onRemove={handleRemoveStudent}
|
||||
onSelect={setSelectedStudentIds}
|
||||
adding={addingStudents}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'teachers',
|
||||
label: `教师 (${teachers.length})`,
|
||||
children: (
|
||||
children: allUsersError ? (
|
||||
<QueryErrorState
|
||||
title="可添加教师加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void fetchUsers()}
|
||||
/>
|
||||
) : (
|
||||
<ClassTeachersTab
|
||||
teachers={teachers}
|
||||
allUsers={allUsers}
|
||||
@@ -305,13 +333,20 @@ const ClassDetailPage: React.FC = () => {
|
||||
onSubjectChange={setTeacherSubject}
|
||||
onUserChange={setTeacherUserId}
|
||||
getTeacherName={getTeacherName}
|
||||
adding={addingTeacher}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'schedule',
|
||||
label: '课表',
|
||||
children: (
|
||||
children: schedulesError ? (
|
||||
<QueryErrorState
|
||||
title="课表加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetchSchedules()}
|
||||
/>
|
||||
) : (
|
||||
<ClassScheduleTab
|
||||
schedules={schedules}
|
||||
scheduleDateRange={scheduleDateRange}
|
||||
@@ -322,7 +357,13 @@ const ClassDetailPage: React.FC = () => {
|
||||
{
|
||||
key: 'attendance-summary',
|
||||
label: '出勤汇总',
|
||||
children: (
|
||||
children: attendanceSummaryError ? (
|
||||
<QueryErrorState
|
||||
title="出勤汇总加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetchAttendanceSummary()}
|
||||
/>
|
||||
) : (
|
||||
<ClassAttendanceTab
|
||||
attendanceSummary={attendanceSummary}
|
||||
attendanceDateRange={attendanceDateRange}
|
||||
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
Popconfirm,
|
||||
Card,
|
||||
Switch,
|
||||
Empty,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { PlusOutlined, SearchOutlined, TeamOutlined, InboxOutlined } from '@ant-design/icons';
|
||||
@@ -30,6 +29,9 @@ import PermissionButton from '../../components/PermissionButton';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
import { QueryErrorState, QueryEmpty } from '../../components/QueryState';
|
||||
import { useVisibleRefetch } from '../../hooks/usePageVisible';
|
||||
import { useDirtyGuard } from '../../hooks/useDirtyGuard';
|
||||
|
||||
interface ClassItem {
|
||||
id: number;
|
||||
@@ -86,6 +88,7 @@ const ClassesPage: React.FC = () => {
|
||||
const [filterStatus, setFilterStatus] = useState<string>();
|
||||
const [filterType, setFilterType] = useState<string>();
|
||||
const [form] = Form.useForm<ClassFormValues>();
|
||||
const classFormGuard = useDirtyGuard(form);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
|
||||
@@ -93,25 +96,24 @@ const ClassesPage: React.FC = () => {
|
||||
data = [],
|
||||
isLoading,
|
||||
isFetching,
|
||||
isError,
|
||||
refetch,
|
||||
} = 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 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>),
|
||||
);
|
||||
},
|
||||
});
|
||||
const loading = isLoading || isFetching;
|
||||
// RouteKeeper 保活页面切回时刷新列表,避免看到陈旧数据
|
||||
useVisibleRefetch(['classes']);
|
||||
|
||||
const saveMutation = useApiMutation(
|
||||
async (payload: Record<string, unknown>) =>
|
||||
@@ -177,6 +179,7 @@ const ClassesPage: React.FC = () => {
|
||||
const handleCreate = () => {
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
classFormGuard.snapshot();
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
@@ -189,9 +192,10 @@ const ClassesPage: React.FC = () => {
|
||||
startDate: record.startDate ? dayjs(record.startDate) : undefined,
|
||||
endDate: record.endDate ? dayjs(record.endDate) : undefined,
|
||||
});
|
||||
classFormGuard.snapshot();
|
||||
setModalOpen(true);
|
||||
},
|
||||
[form],
|
||||
[form, classFormGuard],
|
||||
);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
@@ -430,25 +434,44 @@ const ClassesPage: React.FC = () => {
|
||||
/>
|
||||
</span>
|
||||
</Space>
|
||||
<Table<ClassItem>
|
||||
columns={columns}
|
||||
dataSource={filtered}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
||||
pagination={{
|
||||
defaultPageSize: 20,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [20, 50, 100],
|
||||
}}
|
||||
scroll={{ x: 1100 }}
|
||||
/>
|
||||
{isError ? (
|
||||
<QueryErrorState
|
||||
title="班级数据加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
) : (
|
||||
<Table<ClassItem>
|
||||
columns={columns}
|
||||
dataSource={filtered}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<QueryEmpty
|
||||
description="暂无班级数据"
|
||||
action={
|
||||
hasPermission('class:create')
|
||||
? { label: '创建班级', icon: <PlusOutlined />, onClick: handleCreate }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
pagination={{
|
||||
defaultPageSize: 20,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [20, 50, 100],
|
||||
}}
|
||||
scroll={{ x: 1100 }}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
title={editing ? '编辑班级' : '创建班级'}
|
||||
open={modalOpen}
|
||||
onOk={handleSubmit}
|
||||
onCancel={() => setModalOpen(false)}
|
||||
onCancel={() => classFormGuard.confirmClose(() => setModalOpen(false))}
|
||||
confirmLoading={saving}
|
||||
width={600}
|
||||
>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import React from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Empty,
|
||||
Popconfirm,
|
||||
Space,
|
||||
Table,
|
||||
@@ -19,6 +18,7 @@ import dayjs from 'dayjs';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { QueryEmpty } from '../../components/QueryState';
|
||||
|
||||
const RENTAL_FIELDS = {
|
||||
classroomId: 'classroomId',
|
||||
@@ -43,7 +43,11 @@ export interface RentalTableProps {
|
||||
onPurge: (id: number, name: string) => void;
|
||||
onDownloadContract: (id: number, filename?: string) => void;
|
||||
onDeleteContract: (id: number) => void;
|
||||
onUploadContract: (id: number, formData: FormData) => Promise<unknown>;
|
||||
onUploadContract: (
|
||||
id: number,
|
||||
formData: FormData,
|
||||
onProgress?: (percent: number) => void,
|
||||
) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export const RentalTable: React.FC<RentalTableProps> = ({
|
||||
@@ -62,6 +66,9 @@ export const RentalTable: React.FC<RentalTableProps> = ({
|
||||
onDeleteContract,
|
||||
onUploadContract,
|
||||
}) => {
|
||||
const [uploadingContractId, setUploadingContractId] = useState<number | null>(null);
|
||||
const [contractPercent, setContractPercent] = useState(0);
|
||||
|
||||
const EditableRentalCell = <R extends { id: number; effectiveStatus?: string }>({
|
||||
value,
|
||||
field,
|
||||
@@ -250,17 +257,28 @@ export const RentalTable: React.FC<RentalTableProps> = ({
|
||||
}
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
setUploadingContractId(r.id);
|
||||
setContractPercent(0);
|
||||
try {
|
||||
await onUploadContract(r.id, formData);
|
||||
await onUploadContract(r.id, formData, (percent) => setContractPercent(percent));
|
||||
message.success('合同已上传');
|
||||
onSuccess?.({});
|
||||
} catch (e) {
|
||||
onError?.(e as Error);
|
||||
} finally {
|
||||
setUploadingContractId(null);
|
||||
setContractPercent(0);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button size="small" icon={<UploadOutlined />}>
|
||||
上传PDF
|
||||
<Button
|
||||
size="small"
|
||||
icon={<UploadOutlined />}
|
||||
loading={uploadingContractId === r.id}
|
||||
>
|
||||
{uploadingContractId === r.id && contractPercent > 0 && contractPercent < 100
|
||||
? `上传中 ${contractPercent}%`
|
||||
: '上传PDF'}
|
||||
</Button>
|
||||
</Upload>
|
||||
) : (
|
||||
@@ -327,7 +345,7 @@ export const RentalTable: React.FC<RentalTableProps> = ({
|
||||
dataSource={data}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
||||
locale={{ emptyText: <QueryEmpty description="暂无租赁订单,点击右上角「新增租赁」创建第一笔订单" /> }}
|
||||
pagination={{
|
||||
defaultPageSize: 15,
|
||||
showSizeChanger: true,
|
||||
|
||||
@@ -15,8 +15,11 @@ import dayjs, { Dayjs } from 'dayjs';
|
||||
import api from '../../api';
|
||||
import { downloadBlob } from '../../utils/download';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { QueryErrorState } from '../../components/QueryState';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { useSubmitShortcut } from '../../hooks/useSubmitShortcut';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
import { useVisibleRefetch } from '../../hooks/usePageVisible';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||
import { getErrorMessage } from '../../utils/error';
|
||||
@@ -42,6 +45,7 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
const [filterStatus, setFilterStatus] = useState<string | undefined>();
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
useSubmitShortcut(modalOpen && !saving, () => handleSave());
|
||||
const [unavailableDates, setUnavailableDates] = useImmer<Set<string>>(new Set());
|
||||
const loadedUnavailableMonths = useRef<Set<string>>(new Set());
|
||||
const unavailableRequestVersion = useRef(0);
|
||||
@@ -52,21 +56,18 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
data = [],
|
||||
isLoading,
|
||||
isFetching,
|
||||
isError,
|
||||
refetch,
|
||||
} = 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 params: any = {};
|
||||
if (filterMonth) params.month = filterMonth.format('YYYY-MM');
|
||||
params.includeEnded = true;
|
||||
return validateResponse<any[]>(
|
||||
rentalsSchema,
|
||||
await api.get('/classroom-rentals', { params }),
|
||||
);
|
||||
},
|
||||
});
|
||||
const {
|
||||
@@ -93,6 +94,8 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
const classrooms = meta.classrooms;
|
||||
const organizations = meta.organizations;
|
||||
const loading = isLoading || isFetching;
|
||||
// RouteKeeper 保活页面切回时刷新列表,避免看到陈旧数据
|
||||
useVisibleRefetch(['classroom-rentals']);
|
||||
|
||||
const saveMutation = useApiMutation(
|
||||
async (payload: Record<string, unknown>) =>
|
||||
@@ -139,8 +142,21 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
{ invalidate: [['classroom-rentals']] },
|
||||
);
|
||||
const uploadContractMutation = useApiMutation(
|
||||
async ({ id, formData }: { id: number; formData: FormData }) =>
|
||||
api.post(`/classroom-rentals/${id}/contract`, formData),
|
||||
async ({
|
||||
id,
|
||||
formData,
|
||||
onProgress,
|
||||
}: {
|
||||
id: number;
|
||||
formData: FormData;
|
||||
onProgress?: (percent: number) => void;
|
||||
}) =>
|
||||
api.post(`/classroom-rentals/${id}/contract`, formData, {
|
||||
onUploadProgress: (event) => {
|
||||
if (!onProgress || !event.total) return;
|
||||
onProgress(Math.min(Math.round((event.loaded / event.total) * 100), 100));
|
||||
},
|
||||
}),
|
||||
{ invalidate: [['classroom-rentals']] },
|
||||
);
|
||||
|
||||
@@ -318,8 +334,12 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleUploadContract = async (id: number, formData: FormData) => {
|
||||
return uploadContractMutation.mutateAsync({ id, formData });
|
||||
const handleUploadContract = async (
|
||||
id: number,
|
||||
formData: FormData,
|
||||
onProgress?: (percent: number) => void,
|
||||
) => {
|
||||
return uploadContractMutation.mutateAsync({ id, formData, onProgress });
|
||||
};
|
||||
|
||||
const openEdit = (record: any) => {
|
||||
@@ -399,22 +419,30 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
新增租赁
|
||||
</PermissionButton>
|
||||
</div>
|
||||
<RentalTable
|
||||
data={filteredData}
|
||||
loading={loading}
|
||||
classrooms={classrooms}
|
||||
organizations={organizations}
|
||||
canPurgeRental={canPurgeRental}
|
||||
hasPermission={hasPermission}
|
||||
onSaveCell={saveCell}
|
||||
onEdit={openEdit}
|
||||
onAction={handleRentalAction}
|
||||
onArchive={handleDelete}
|
||||
onPurge={handlePurge}
|
||||
onDownloadContract={handleDownloadContract}
|
||||
onDeleteContract={handleDeleteContract}
|
||||
onUploadContract={handleUploadContract}
|
||||
/>
|
||||
{isError ? (
|
||||
<QueryErrorState
|
||||
title="租赁订单加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
) : (
|
||||
<RentalTable
|
||||
data={filteredData}
|
||||
loading={loading}
|
||||
classrooms={classrooms}
|
||||
organizations={organizations}
|
||||
canPurgeRental={canPurgeRental}
|
||||
hasPermission={hasPermission}
|
||||
onSaveCell={saveCell}
|
||||
onEdit={openEdit}
|
||||
onAction={handleRentalAction}
|
||||
onArchive={handleDelete}
|
||||
onPurge={handlePurge}
|
||||
onDownloadContract={handleDownloadContract}
|
||||
onDeleteContract={handleDeleteContract}
|
||||
onUploadContract={handleUploadContract}
|
||||
/>
|
||||
)}
|
||||
<Modal
|
||||
title={editing ? '编辑租赁' : '新增租赁'}
|
||||
open={modalOpen}
|
||||
@@ -428,7 +456,7 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
okText="保存"
|
||||
width={600}
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form form={form} layout="vertical" scrollToFirstError>
|
||||
<Form.Item name="classroomId" label="教室" rules={[{ required: true }]}>
|
||||
<Select
|
||||
showSearch
|
||||
@@ -479,6 +507,7 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
style={{ width: '100%' }}
|
||||
placeholder={['开始日期', '结束日期']}
|
||||
format="YYYY-MM-DD"
|
||||
allowEmpty={[true, true]}
|
||||
disabled={!selectedClassroomId}
|
||||
disabledDate={(date) => unavailableDatesLoading || isDateUnavailable(date)}
|
||||
onPanelChange={(dates) => dates.forEach((date) => date && handleCalendarChange(date))}
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
Button,
|
||||
Modal,
|
||||
Spin,
|
||||
Empty,
|
||||
Tooltip,
|
||||
} from 'antd';
|
||||
import { CalendarOutlined, FileTextOutlined, ReadOutlined } from '@ant-design/icons';
|
||||
@@ -22,6 +21,8 @@ import api from '../../api';
|
||||
import { downloadBlob } from '../../utils/download';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { getErrorMessage } from '../../utils/error';
|
||||
import { QueryErrorState, QueryEmpty } from '../../components/QueryState';
|
||||
import { useVisibleRefetch } from '../../hooks/usePageVisible';
|
||||
|
||||
interface ScheduleData {
|
||||
year: number;
|
||||
@@ -40,23 +41,19 @@ const ClassroomSchedulePage: React.FC = () => {
|
||||
const [month, setMonth] = useState<Dayjs>(dayjs());
|
||||
const [detailModal, setDetailModal] = useState<any>(null);
|
||||
|
||||
const { data, isLoading, isFetching } = useQuery<ScheduleData | null>({
|
||||
const { data, isLoading, isFetching, isError, refetch } = useQuery<ScheduleData | null>({
|
||||
queryKey: ['classroom-rentals', 'schedule', month.year(), month.month()],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
return validateResponse<ScheduleData | null>(
|
||||
classroomScheduleSchema,
|
||||
await api.get('/classroom-rentals/schedule', {
|
||||
params: { year: month.year(), month: month.month() + 1 },
|
||||
}),
|
||||
);
|
||||
} catch (e: unknown) {
|
||||
message.error(getErrorMessage(e, '加载失败,请稍后重试'));
|
||||
return null;
|
||||
}
|
||||
},
|
||||
queryFn: async () =>
|
||||
validateResponse<ScheduleData | null>(
|
||||
classroomScheduleSchema,
|
||||
await api.get('/classroom-rentals/schedule', {
|
||||
params: { year: month.year(), month: month.month() + 1 },
|
||||
}),
|
||||
),
|
||||
});
|
||||
const loading = isLoading || isFetching;
|
||||
// RouteKeeper 保活页面切回时刷新排期数据
|
||||
useVisibleRefetch(['classroom-rentals', 'schedule']);
|
||||
|
||||
// 按楼栋+楼层分组教室
|
||||
const groups = useMemo(() => {
|
||||
@@ -135,208 +132,218 @@ const ClassroomSchedulePage: React.FC = () => {
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
{/* 统计卡片 */}
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small">
|
||||
<Statistic title="教室总数" value={data?.classrooms.length || 0} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small">
|
||||
<Statistic title="本月天数" value={data?.days || 0} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small">
|
||||
<Statistic title="总占用天数" value={overall.rented} suffix={`/${overall.total}`} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small">
|
||||
<Statistic
|
||||
title="整体占用率"
|
||||
value={overall.rate}
|
||||
suffix="%"
|
||||
styles={{
|
||||
value: {
|
||||
color: overall.rate > 70 ? '#cf1322' : overall.rate > 40 ? '#fa8c16' : '#3f8600',
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
{isError ? (
|
||||
<QueryErrorState
|
||||
title="教室排期加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{/* 统计卡片 */}
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small">
|
||||
<Statistic title="教室总数" value={data?.classrooms.length || 0} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small">
|
||||
<Statistic title="本月天数" value={data?.days || 0} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small">
|
||||
<Statistic title="总占用天数" value={overall.rented} suffix={`/${overall.total}`} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small">
|
||||
<Statistic
|
||||
title="整体占用率"
|
||||
value={overall.rate}
|
||||
suffix="%"
|
||||
styles={{
|
||||
value: {
|
||||
color: overall.rate > 70 ? '#cf1322' : overall.rate > 40 ? '#fa8c16' : '#3f8600',
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* 图例 */}
|
||||
{data && (
|
||||
<Card size="small" style={{ marginBottom: 16 }} title="图例">
|
||||
<Space wrap>
|
||||
<Tag color="#52c41a">内部排课</Tag>
|
||||
{data.organizations.map((t) => (
|
||||
<Tag
|
||||
key={t.id}
|
||||
color={t.color}
|
||||
style={{ background: t.color, color: '#fff', borderColor: t.color }}
|
||||
>
|
||||
{t.name} (租赁)
|
||||
</Tag>
|
||||
))}
|
||||
<Tag color="#d9d9d9" style={{ color: '#999' }}>
|
||||
空闲
|
||||
</Tag>
|
||||
</Space>
|
||||
</Card>
|
||||
)}
|
||||
{/* 图例 */}
|
||||
{data && (
|
||||
<Card size="small" style={{ marginBottom: 16 }} title="图例">
|
||||
<Space wrap>
|
||||
<Tag color="#52c41a">内部排课</Tag>
|
||||
{data.organizations.map((t) => (
|
||||
<Tag
|
||||
key={t.id}
|
||||
color={t.color}
|
||||
style={{ background: t.color, color: '#fff', borderColor: t.color }}
|
||||
>
|
||||
{t.name} (租赁)
|
||||
</Tag>
|
||||
))}
|
||||
<Tag color="#d9d9d9" style={{ color: '#999' }}>
|
||||
空闲
|
||||
</Tag>
|
||||
</Space>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Spin spinning={loading}>
|
||||
{!data || data.classrooms.length === 0 ? (
|
||||
<Empty description="暂无教室数据" />
|
||||
) : (
|
||||
<div style={{ overflowX: 'auto' }}>
|
||||
{groups.map((group) => (
|
||||
<Card
|
||||
key={group.name}
|
||||
size="small"
|
||||
title={group.name}
|
||||
style={{ marginBottom: 12 }}
|
||||
styles={{ body: { padding: 0 } }}
|
||||
>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
|
||||
<thead>
|
||||
<tr style={{ background: '#fafafa' }}>
|
||||
<th
|
||||
style={{
|
||||
position: 'sticky',
|
||||
left: 0,
|
||||
background: '#fafafa',
|
||||
zIndex: 2,
|
||||
padding: '8px',
|
||||
border: '1px solid #f0f0f0',
|
||||
minWidth: 120,
|
||||
textAlign: 'left',
|
||||
}}
|
||||
>
|
||||
教室
|
||||
</th>
|
||||
<th style={{ padding: '8px 6px', border: '1px solid #f0f0f0', minWidth: 60 }}>
|
||||
类型
|
||||
</th>
|
||||
<th style={{ padding: '8px 6px', border: '1px solid #f0f0f0', minWidth: 70 }}>
|
||||
占用率
|
||||
</th>
|
||||
{Array.from({ length: data.days }, (_, i) => i + 1).map((d) => (
|
||||
<th
|
||||
key={d}
|
||||
style={{
|
||||
padding: '8px 4px',
|
||||
border: '1px solid #f0f0f0',
|
||||
minWidth: 26,
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
{d}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{group.classrooms.map((c) => {
|
||||
const sum = data.summary[c.id] || {
|
||||
rentedDays: 0,
|
||||
totalDays: data.days,
|
||||
occupancyRate: 0,
|
||||
};
|
||||
return (
|
||||
<tr key={c.id}>
|
||||
<td
|
||||
<Spin spinning={loading}>
|
||||
{!data || data.classrooms.length === 0 ? (
|
||||
<QueryEmpty description="暂无教室数据,可在「教室管理」中添加教室后查看排期" />
|
||||
) : (
|
||||
<div style={{ overflowX: 'auto' }}>
|
||||
{groups.map((group) => (
|
||||
<Card
|
||||
key={group.name}
|
||||
size="small"
|
||||
title={group.name}
|
||||
style={{ marginBottom: 12 }}
|
||||
styles={{ body: { padding: 0 } }}
|
||||
>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
|
||||
<thead>
|
||||
<tr style={{ background: '#fafafa' }}>
|
||||
<th
|
||||
style={{
|
||||
position: 'sticky',
|
||||
left: 0,
|
||||
background: '#fff',
|
||||
zIndex: 1,
|
||||
padding: '6px 8px',
|
||||
background: '#fafafa',
|
||||
zIndex: 2,
|
||||
padding: '8px',
|
||||
border: '1px solid #f0f0f0',
|
||||
fontWeight: 500,
|
||||
minWidth: 120,
|
||||
textAlign: 'left',
|
||||
}}
|
||||
>
|
||||
{c.name}
|
||||
</td>
|
||||
<td
|
||||
style={{
|
||||
padding: '6px',
|
||||
border: '1px solid #f0f0f0',
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
{c.roomType}
|
||||
</td>
|
||||
<td
|
||||
style={{
|
||||
padding: '6px',
|
||||
border: '1px solid #f0f0f0',
|
||||
textAlign: 'center',
|
||||
color:
|
||||
sum.occupancyRate > 0.7
|
||||
? '#cf1322'
|
||||
: sum.occupancyRate > 0.4
|
||||
? '#fa8c16'
|
||||
: '#3f8600',
|
||||
}}
|
||||
>
|
||||
{Math.round(sum.occupancyRate * 100)}%
|
||||
</td>
|
||||
{Array.from({ length: data.days }, (_, i) => i + 1).map((d) => {
|
||||
const cell = data.matrix[c.id]?.[d];
|
||||
const isInternal = cell?.scheduleType === 'INTERNAL';
|
||||
const isRental = cell?.scheduleType === 'RENTAL';
|
||||
return (
|
||||
教室
|
||||
</th>
|
||||
<th style={{ padding: '8px 6px', border: '1px solid #f0f0f0', minWidth: 60 }}>
|
||||
类型
|
||||
</th>
|
||||
<th style={{ padding: '8px 6px', border: '1px solid #f0f0f0', minWidth: 70 }}>
|
||||
占用率
|
||||
</th>
|
||||
{Array.from({ length: data.days }, (_, i) => i + 1).map((d) => (
|
||||
<th
|
||||
key={d}
|
||||
style={{
|
||||
padding: '8px 4px',
|
||||
border: '1px solid #f0f0f0',
|
||||
minWidth: 26,
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
{d}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{group.classrooms.map((c) => {
|
||||
const sum = data.summary[c.id] || {
|
||||
rentedDays: 0,
|
||||
totalDays: data.days,
|
||||
occupancyRate: 0,
|
||||
};
|
||||
return (
|
||||
<tr key={c.id}>
|
||||
<td
|
||||
key={d}
|
||||
onClick={() => {
|
||||
if (isRental) showDetail(cell.rentalId);
|
||||
}}
|
||||
style={{
|
||||
padding: 0,
|
||||
position: 'sticky',
|
||||
left: 0,
|
||||
background: '#fff',
|
||||
zIndex: 1,
|
||||
padding: '6px 8px',
|
||||
border: '1px solid #f0f0f0',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
{c.name}
|
||||
</td>
|
||||
<td
|
||||
style={{
|
||||
padding: '6px',
|
||||
border: '1px solid #f0f0f0',
|
||||
background: cell?.color || '#fff',
|
||||
height: 26,
|
||||
cursor: isRental ? 'pointer' : 'default',
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
{cell && (
|
||||
<Tooltip
|
||||
title={
|
||||
isInternal
|
||||
? `${cell.className} · ${cell.subject}\n${cell.teacherName} · ${cell.startTime}-${cell.endTime}`
|
||||
: `${cell.organizationName}${cell.hasContract ? ' · 有合同' : ''}`
|
||||
}
|
||||
>
|
||||
<span style={{ color: '#fff', fontSize: 10, fontWeight: 600 }}>
|
||||
{isInternal ? (
|
||||
<ReadOutlined style={{ fontSize: 12 }} />
|
||||
) : cell.hasContract ? (
|
||||
<FileTextOutlined style={{ fontSize: 12 }} />
|
||||
) : (
|
||||
''
|
||||
)}
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
{c.roomType}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Spin>
|
||||
<td
|
||||
style={{
|
||||
padding: '6px',
|
||||
border: '1px solid #f0f0f0',
|
||||
textAlign: 'center',
|
||||
color:
|
||||
sum.occupancyRate > 0.7
|
||||
? '#cf1322'
|
||||
: sum.occupancyRate > 0.4
|
||||
? '#fa8c16'
|
||||
: '#3f8600',
|
||||
}}
|
||||
>
|
||||
{Math.round(sum.occupancyRate * 100)}%
|
||||
</td>
|
||||
{Array.from({ length: data.days }, (_, i) => i + 1).map((d) => {
|
||||
const cell = data.matrix[c.id]?.[d];
|
||||
const isInternal = cell?.scheduleType === 'INTERNAL';
|
||||
const isRental = cell?.scheduleType === 'RENTAL';
|
||||
return (
|
||||
<td
|
||||
key={d}
|
||||
onClick={() => {
|
||||
if (isRental) showDetail(cell.rentalId);
|
||||
}}
|
||||
style={{
|
||||
padding: 0,
|
||||
border: '1px solid #f0f0f0',
|
||||
background: cell?.color || '#fff',
|
||||
height: 26,
|
||||
cursor: isRental ? 'pointer' : 'default',
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
{cell && (
|
||||
<Tooltip
|
||||
title={
|
||||
isInternal
|
||||
? `${cell.className} · ${cell.subject}\n${cell.teacherName} · ${cell.startTime}-${cell.endTime}`
|
||||
: `${cell.organizationName}${cell.hasContract ? ' · 有合同' : ''}`
|
||||
}
|
||||
>
|
||||
<span style={{ color: '#fff', fontSize: 10, fontWeight: 600 }}>
|
||||
{isInternal ? (
|
||||
<ReadOutlined style={{ fontSize: 12 }} />
|
||||
) : cell.hasContract ? (
|
||||
<FileTextOutlined style={{ fontSize: 12 }} />
|
||||
) : (
|
||||
''
|
||||
)}
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Spin>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
title="租赁详情"
|
||||
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
Popconfirm,
|
||||
Upload,
|
||||
Tooltip,
|
||||
Empty,
|
||||
} from 'antd';
|
||||
import {
|
||||
PlusOutlined,
|
||||
@@ -29,9 +28,15 @@ import {
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
import { QueryErrorState, QueryEmpty } from '../../components/QueryState';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { RefreshButton } from '../../components/RefreshButton';
|
||||
import { useSubmitShortcut } from '../../hooks/useSubmitShortcut';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
import { useUserStore } from '../../store/user/userStore';
|
||||
import { useVisibleRefetch } from '../../hooks/usePageVisible';
|
||||
import { useDirtyGuard } from '../../hooks/useDirtyGuard';
|
||||
import { saveAs } from 'file-saver';
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
available: { text: '可用', color: 'green' },
|
||||
@@ -61,30 +66,30 @@ const ClassroomsPage: React.FC = () => {
|
||||
const [editing, setEditing] = useState<any>(null);
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
const [form] = Form.useForm();
|
||||
const formGuard = useDirtyGuard(form);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
|
||||
|
||||
const [saving, setSaving] = useState(false);
|
||||
useSubmitShortcut(modalOpen && !saving, () => handleSave());
|
||||
|
||||
const {
|
||||
data = [],
|
||||
isLoading,
|
||||
isFetching,
|
||||
isError,
|
||||
refetch,
|
||||
} = 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 [];
|
||||
}
|
||||
},
|
||||
queryFn: async () =>
|
||||
validateResponse<any[]>(
|
||||
classroomsSchema,
|
||||
await api.get('/classrooms', { params: { includeArchived: showArchived } }),
|
||||
),
|
||||
});
|
||||
const loading = isLoading || isFetching;
|
||||
// RouteKeeper 保活页面切回时刷新列表,避免看到陈旧数据
|
||||
useVisibleRefetch(['classrooms']);
|
||||
|
||||
const saveMutation = useApiMutation(
|
||||
async (values: Record<string, unknown>) =>
|
||||
@@ -145,6 +150,13 @@ const ClassroomsPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const openCreateModal = () => {
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
formGuard.snapshot();
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const saveCell = useCallback(
|
||||
async (record: any, field: string, value: unknown) => {
|
||||
try {
|
||||
@@ -210,14 +222,7 @@ const ClassroomsPage: React.FC = () => {
|
||||
const token = useUserStore.getState().token;
|
||||
fetch(`${baseURL}/classrooms/template`, { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then((res) => res.blob())
|
||||
.then((blob) => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = '教室导入模板.xlsx';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.then((blob) => saveAs(blob, '教室导入模板.xlsx'))
|
||||
.catch(() => message.error('下载失败'));
|
||||
};
|
||||
|
||||
@@ -349,6 +354,7 @@ const ClassroomsPage: React.FC = () => {
|
||||
|
||||
{
|
||||
title: '操作',
|
||||
fixed: 'right' as const,
|
||||
width: 180,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
@@ -383,6 +389,7 @@ const ClassroomsPage: React.FC = () => {
|
||||
onClick={() => {
|
||||
setEditing(record);
|
||||
form.setFieldsValue(record);
|
||||
formGuard.snapshot();
|
||||
setModalOpen(true);
|
||||
}}
|
||||
>
|
||||
@@ -408,7 +415,7 @@ const ClassroomsPage: React.FC = () => {
|
||||
),
|
||||
},
|
||||
],
|
||||
[handlePurge, hasPermission, saveCell, handleArchive, handleRestore, form],
|
||||
[handlePurge, hasPermission, saveCell, handleArchive, handleRestore, form, formGuard],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -454,15 +461,12 @@ const ClassroomsPage: React.FC = () => {
|
||||
</Button>
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<RefreshButton loading={isFetching} onRefresh={() => void refetch()} />
|
||||
<PermissionButton
|
||||
permission="classroom:create"
|
||||
type="primary"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
setModalOpen(true);
|
||||
}}
|
||||
onClick={openCreateModal}
|
||||
>
|
||||
添加教室
|
||||
</PermissionButton>
|
||||
@@ -476,12 +480,8 @@ const ClassroomsPage: React.FC = () => {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
.then((r) => r.blob())
|
||||
.then((b) => {
|
||||
const a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(b);
|
||||
a.download = '教室使用报表.xlsx';
|
||||
a.click();
|
||||
});
|
||||
.then((b) => saveAs(b, '教室使用报表.xlsx'))
|
||||
.catch(() => message.error('导出失败'));
|
||||
}}
|
||||
>
|
||||
导出报表
|
||||
@@ -514,32 +514,53 @@ const ClassroomsPage: React.FC = () => {
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
</div>
|
||||
<Table
|
||||
scroll={{ x: 1100 }}
|
||||
columns={columns}
|
||||
dataSource={filteredData}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
||||
pagination={{
|
||||
defaultPageSize: 20,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [20, 50, 100],
|
||||
showTotal: (total) => `共 ${total} 条`,
|
||||
}}
|
||||
/>
|
||||
{isError ? (
|
||||
<QueryErrorState
|
||||
title="教室列表加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
) : (
|
||||
<Table
|
||||
scroll={{ x: 1100 }}
|
||||
columns={columns}
|
||||
dataSource={filteredData}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<QueryEmpty
|
||||
description="暂无数据"
|
||||
action={
|
||||
hasPermission('classroom:create')
|
||||
? { label: '添加教室', onClick: openCreateModal }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
pagination={{
|
||||
defaultPageSize: 20,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [20, 50, 100],
|
||||
showTotal: (total) => `共 ${total} 条`,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<Modal
|
||||
title={editing ? '编辑教室' : '添加教室'}
|
||||
open={modalOpen}
|
||||
onOk={handleSave}
|
||||
onCancel={() => {
|
||||
setModalOpen(false);
|
||||
setEditing(null);
|
||||
}}
|
||||
onCancel={() =>
|
||||
formGuard.confirmClose(() => {
|
||||
setModalOpen(false);
|
||||
setEditing(null);
|
||||
})
|
||||
}
|
||||
confirmLoading={saving}
|
||||
okText="保存"
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form form={form} layout="vertical" scrollToFirstError>
|
||||
<Form.Item name="name" label="教室名" rules={[{ required: true }]}>
|
||||
<Input placeholder="如:A201 / B301" />
|
||||
</Form.Item>
|
||||
|
||||
@@ -170,16 +170,6 @@ export function buildClassroomHeatmapOption(
|
||||
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',
|
||||
@@ -190,7 +180,7 @@ export function buildClassroomHeatmapOption(
|
||||
rentalCount: r.rentalCount,
|
||||
occupancy: r.occupancy,
|
||||
})),
|
||||
itemStyle: { borderRadius: [0, 4, 4, 0] },
|
||||
itemStyle: { color: '#1677ff', borderRadius: [0, 4, 4, 0] },
|
||||
label: {
|
||||
show: true,
|
||||
position: 'right',
|
||||
|
||||
@@ -49,13 +49,15 @@ export const ClassroomHeatmapCard: React.FC<{
|
||||
minHeight={isMobile ? 340 : 440}
|
||||
style={{ marginBottom: 24 }}
|
||||
>
|
||||
{data.length > 0 ? (
|
||||
{data.some((r) => Number(r.occupancy) > 0) ? (
|
||||
<ReactECharts
|
||||
option={buildClassroomHeatmapOption(data)}
|
||||
style={{ width: '100%', height: isMobile ? 300 : 400 }}
|
||||
/>
|
||||
) : (
|
||||
<div style={{ textAlign: 'center', padding: 40, color: '#999' }}>暂无教室数据</div>
|
||||
<div style={{ textAlign: 'center', padding: 40, color: '#999' }}>
|
||||
暂无教室占用数据
|
||||
</div>
|
||||
)}
|
||||
</LazySection>
|
||||
);
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
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, Skeleton, Alert} from 'antd';
|
||||
import {
|
||||
TeamOutlined,
|
||||
HomeOutlined,
|
||||
@@ -26,7 +26,6 @@ import {
|
||||
import ReactECharts from '../../components/ECharts';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import { message } from '../../ui/app-message';
|
||||
import {
|
||||
buildAttendanceLineOption,
|
||||
buildAttendanceRingOption,
|
||||
@@ -46,12 +45,14 @@ import {
|
||||
type GanttRoom,
|
||||
} from './Dashboard.types';
|
||||
import { DashboardTodoCards } from './DashboardTodoCards';
|
||||
import { QueryErrorState } from '../../components/QueryState';
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
const DashboardPage: React.FC = () => {
|
||||
const screens = Grid.useBreakpoint();
|
||||
const isMobile = !screens.sm;
|
||||
const [partialAlertClosed, setPartialAlertClosed] = useState(false);
|
||||
const [period, setPeriod] = useState<[string, string]>([
|
||||
dayjs().startOf('month').format('YYYY-MM-DD'),
|
||||
dayjs().endOf('month').format('YYYY-MM-DD'),
|
||||
@@ -65,9 +66,12 @@ const DashboardPage: React.FC = () => {
|
||||
ganttData: [],
|
||||
roomRanking: [],
|
||||
classroomUtil: null,
|
||||
partialFailures: 0,
|
||||
},
|
||||
isLoading,
|
||||
isFetching,
|
||||
isError,
|
||||
refetch,
|
||||
} = useQuery<{
|
||||
stats: DashboardStats | null;
|
||||
classRanking: { top: ClassAttendanceRank[]; bottom: ClassAttendanceRank[] };
|
||||
@@ -75,53 +79,81 @@ const DashboardPage: React.FC = () => {
|
||||
ganttData: GanttRoom[];
|
||||
roomRanking: Array<{ roomNumber: string; total: string }>;
|
||||
classroomUtil: ClassroomUtilStats | null;
|
||||
partialFailures: number;
|
||||
}>({
|
||||
queryKey: ['dashboard', period],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
const [s, rr, cr, g, co, cu] = await Promise.all([
|
||||
api.get<DashboardStats>('/dashboard/stats'),
|
||||
api.get<Array<{ roomNumber: string; total: string }>>('/dashboard/room-ranking', {
|
||||
params: { periodStart: period[0], periodEnd: period[1] },
|
||||
}),
|
||||
api.get<{ top: ClassAttendanceRank[]; bottom: ClassAttendanceRank[] }>(
|
||||
'/dashboard/class-attendance-ranking',
|
||||
),
|
||||
api.get<GanttRoom[]>('/dashboard/gantt', {
|
||||
params: { periodStart: period[0], periodEnd: period[1] },
|
||||
}),
|
||||
api.get<ClassroomOccupancy[]>('/dashboard/classroom-occupancy'),
|
||||
api.get<ClassroomUtilStats>('/dashboard/classroom-utilization'),
|
||||
]);
|
||||
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 settled = await Promise.allSettled([
|
||||
api.get<DashboardStats>('/dashboard/stats'),
|
||||
api.get<Array<{ roomNumber: string; total: string }>>('/dashboard/room-ranking', {
|
||||
params: { periodStart: period[0], periodEnd: period[1] },
|
||||
}),
|
||||
api.get<{ top: ClassAttendanceRank[]; bottom: ClassAttendanceRank[] }>(
|
||||
'/dashboard/class-attendance-ranking',
|
||||
),
|
||||
api.get<GanttRoom[]>('/dashboard/gantt', {
|
||||
params: { periodStart: period[0], periodEnd: period[1] },
|
||||
}),
|
||||
api.get<ClassroomOccupancy[]>('/dashboard/classroom-occupancy'),
|
||||
api.get<ClassroomUtilStats>('/dashboard/classroom-utilization'),
|
||||
]);
|
||||
const value = <T,>(r: PromiseSettledResult<T>): T | null =>
|
||||
r.status === 'fulfilled' ? r.value : null;
|
||||
const rejected = settled.filter((r) => r.status === 'rejected');
|
||||
if (rejected.length === settled.length) {
|
||||
// 全部失败:抛出让 react-query 自动重试
|
||||
console.error('看板数据加载失败', rejected);
|
||||
throw new Error('看板数据加载失败');
|
||||
}
|
||||
const partialFailures = rejected.length;
|
||||
if (partialFailures > 0) {
|
||||
console.error('部分看板数据加载失败', rejected);
|
||||
}
|
||||
// 校验失败的模块降级为对应空值,不影响其他模块
|
||||
type ValidateSchema = Parameters<typeof validateResponse>[0];
|
||||
const safeValidate = <T,>(schema: ValidateSchema, raw: unknown, fallback: T): T => {
|
||||
try {
|
||||
return validateResponse<T>(schema, raw);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
const stats = safeValidate<DashboardStats | null>(
|
||||
dashboardStatsSchema,
|
||||
value(settled[0]),
|
||||
null,
|
||||
);
|
||||
const roomRanking = safeValidate<Array<{ roomNumber: string; total: string }>>(
|
||||
roomRankingSchema,
|
||||
value(settled[1]),
|
||||
[],
|
||||
);
|
||||
const classRanking = safeValidate<{
|
||||
top: ClassAttendanceRank[];
|
||||
bottom: ClassAttendanceRank[];
|
||||
}>(classAttendanceRankingSchema, value(settled[2]), { top: [], bottom: [] });
|
||||
const ganttData = safeValidate<GanttRoom[]>(ganttRoomsSchema, value(settled[3]), []);
|
||||
const classroomOccupancy = safeValidate<ClassroomOccupancy[]>(
|
||||
classroomOccupanciesSchema,
|
||||
value(settled[4]),
|
||||
[],
|
||||
);
|
||||
const classroomUtil = safeValidate<ClassroomUtilStats | null>(
|
||||
classroomUtilStatsSchema,
|
||||
value(settled[5]),
|
||||
null,
|
||||
);
|
||||
return {
|
||||
stats,
|
||||
classRanking,
|
||||
classroomOccupancy,
|
||||
ganttData,
|
||||
roomRanking,
|
||||
classroomUtil,
|
||||
partialFailures,
|
||||
};
|
||||
},
|
||||
});
|
||||
const stats = fetchResult.stats;
|
||||
@@ -163,8 +195,35 @@ const DashboardPage: React.FC = () => {
|
||||
const draftTotal = draftBill ? Number(draftBill.total) : 0;
|
||||
const pendingDeposits = stats?.pendingDeposits ?? 0;
|
||||
|
||||
if (loading && !stats)
|
||||
return <Spin size="large" style={{ display: 'block', margin: '100px auto' }} />;
|
||||
if (loading && !stats) {
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<Skeleton active paragraph={{ rows: 3 }} />
|
||||
<Row gutter={[16, 16]} style={{ marginTop: 24 }}>
|
||||
{Array.from({ length: 6 }, (_, i) => (
|
||||
<Col key={i} xs={12} sm={8} md={4}>
|
||||
<Card>
|
||||
<Skeleton active title={false} paragraph={{ rows: 2 }} />
|
||||
</Card>
|
||||
</Col>
|
||||
))}
|
||||
</Row>
|
||||
<Card style={{ marginTop: 16 }}>
|
||||
<Skeleton active paragraph={{ rows: 8 }} />
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<QueryErrorState
|
||||
title="工作台加载失败"
|
||||
description="看板数据暂时无法获取,请检查网络后重试。"
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -186,13 +245,26 @@ const DashboardPage: React.FC = () => {
|
||||
aria-label="选择日期范围"
|
||||
value={[dayjs(period[0]), dayjs(period[1])]}
|
||||
onChange={(dates) => {
|
||||
if (dates?.[0] && dates?.[1])
|
||||
if (dates?.[0] && dates?.[1]) {
|
||||
setPeriod([dates[0].format('YYYY-MM-DD'), dates[1].format('YYYY-MM-DD')]);
|
||||
setPartialAlertClosed(false);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ═══════════ 待办与异常 ═══════════ */}
|
||||
{fetchResult.partialFailures > 0 && !partialAlertClosed ? (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
closable
|
||||
onClose={() => setPartialAlertClosed(true)}
|
||||
message={`有 ${fetchResult.partialFailures} 项数据加载失败,其余数据已正常显示`}
|
||||
style={{ marginBottom: 16 }}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{/* 待办与异常 */}
|
||||
<DashboardTodoCards
|
||||
absentCount={absentCount}
|
||||
draftCount={draftCount}
|
||||
@@ -200,7 +272,7 @@ const DashboardPage: React.FC = () => {
|
||||
pendingDeposits={pendingDeposits}
|
||||
/>
|
||||
|
||||
{/* ═══════════ 核心 KPI ═══════════ */}
|
||||
{/* 核心 KPI */}
|
||||
<Row gutter={[16, 16]} style={SECTION_ROW_STYLE}>
|
||||
<Col xs={12} sm={8} md={4}>
|
||||
<Card>
|
||||
@@ -257,7 +329,7 @@ const DashboardPage: React.FC = () => {
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* ═══════════ 更多指标(折叠) ═══════════ */}
|
||||
{/* 更多指标(折叠) */}
|
||||
<Collapse
|
||||
ghost
|
||||
items={[
|
||||
@@ -391,7 +463,7 @@ const DashboardPage: React.FC = () => {
|
||||
]}
|
||||
/>
|
||||
|
||||
{/* ═══════════ 图表:考勤趋势 + 出勤分布 ═══════════ */}
|
||||
{/* 图表:考勤趋势 + 出勤分布 */}
|
||||
<Row gutter={[16, 16]} style={SECTION_ROW_STYLE}>
|
||||
<Col xs={24} sm={12}>
|
||||
<Card title="考勤趋势(近30天)">
|
||||
@@ -419,7 +491,7 @@ const DashboardPage: React.FC = () => {
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* ═══════════ 图表:班级出勤排行 ═══════════ */}
|
||||
{/* 图表:班级出勤排行 */}
|
||||
<Row gutter={[16, 16]} style={SECTION_ROW_STYLE}>
|
||||
<Col xs={24} sm={12}>
|
||||
<Card title="班级出勤率 TOP 5">
|
||||
@@ -447,7 +519,7 @@ const DashboardPage: React.FC = () => {
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* ═══════════ 图表:费用分布 + 宿舍排行 ═══════════ */}
|
||||
{/* 图表:费用分布 + 宿舍排行 */}
|
||||
<Row gutter={[16, 16]} style={SECTION_ROW_STYLE}>
|
||||
<Col xs={24} sm={12}>
|
||||
<Card title="费用类型分布">
|
||||
@@ -475,7 +547,7 @@ const DashboardPage: React.FC = () => {
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* ═══════════ 图表:月度收入趋势 ═══════════ */}
|
||||
{/* 图表:月度收入趋势 */}
|
||||
<Row gutter={[16, 16]}>
|
||||
<Col xs={24}>
|
||||
<Card title="月度收入趋势">
|
||||
@@ -491,10 +563,10 @@ const DashboardPage: React.FC = () => {
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* ═══════════ 图表:教室占用热力图(懒加载) ═══════════ */}
|
||||
{/* 图表:教室占用热力图(懒加载) */}
|
||||
<ClassroomHeatmapCard data={classroomOccupancy} isMobile={isMobile} />
|
||||
|
||||
{/* ═══════════ 图表:入住时间线甘特图(懒加载) ═══════════ */}
|
||||
{/* 图表:入住时间线甘特图(懒加载) */}
|
||||
<GanttCard data={ganttData} isMobile={isMobile} periodEnd={period[1]} />
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -17,6 +17,7 @@ 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';
|
||||
import { useSubmitShortcut } from '../../hooks/useSubmitShortcut';
|
||||
|
||||
export interface DepositRecord {
|
||||
id: number;
|
||||
@@ -140,6 +141,10 @@ export const DepositModals: React.FC<DepositModalsProps> = ({
|
||||
onOpenInstallment,
|
||||
onSelectEligible,
|
||||
}) => {
|
||||
useSubmitShortcut(batchModal && !saving, onBatchCreate);
|
||||
useSubmitShortcut(createModal && !saving, onCreate);
|
||||
useSubmitShortcut(!!refundModal && !saving, onRefund);
|
||||
useSubmitShortcut(!!installmentModal && !saving, onAddInstallment);
|
||||
return (
|
||||
<>
|
||||
<Modal
|
||||
@@ -152,7 +157,7 @@ export const DepositModals: React.FC<DepositModalsProps> = ({
|
||||
okButtonProps={{ disabled: effectiveSelectedEligibleIds.length === 0 }}
|
||||
width={760}
|
||||
>
|
||||
<Form form={batchForm} layout="vertical">
|
||||
<Form form={batchForm} layout="vertical" scrollToFirstError>
|
||||
<Space style={{ width: '100%' }} align="start" wrap>
|
||||
<Form.Item
|
||||
name="roomType"
|
||||
@@ -193,7 +198,7 @@ export const DepositModals: React.FC<DepositModalsProps> = ({
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Table
|
||||
<Table scroll={{ x: 'max-content' }}
|
||||
size="small"
|
||||
columns={eligibleColumns as never}
|
||||
dataSource={eligibleStudents}
|
||||
@@ -216,7 +221,7 @@ export const DepositModals: React.FC<DepositModalsProps> = ({
|
||||
okText="确认"
|
||||
confirmLoading={saving}
|
||||
>
|
||||
<Form form={createForm} layout="vertical">
|
||||
<Form form={createForm} layout="vertical" scrollToFirstError>
|
||||
<Form.Item
|
||||
name="studentId"
|
||||
label="学生"
|
||||
@@ -249,7 +254,7 @@ export const DepositModals: React.FC<DepositModalsProps> = ({
|
||||
okText="确认退还"
|
||||
confirmLoading={saving}
|
||||
>
|
||||
<Form form={refundForm} layout="vertical">
|
||||
<Form form={refundForm} layout="vertical" scrollToFirstError>
|
||||
<div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 8 }}>
|
||||
当前可用押金: <strong>¥{Number(refundModal?.amount || 0).toFixed(2)}</strong>
|
||||
</div>
|
||||
@@ -311,7 +316,7 @@ export const DepositModals: React.FC<DepositModalsProps> = ({
|
||||
</PermissionButton>
|
||||
</div>
|
||||
{detailModal.installments && detailModal.installments.length > 0 ? (
|
||||
<Table
|
||||
<Table scroll={{ x: 'max-content' }}
|
||||
size="small"
|
||||
pagination={false}
|
||||
rowKey="id"
|
||||
@@ -408,8 +413,9 @@ export const DepositModals: React.FC<DepositModalsProps> = ({
|
||||
onOk={onAddInstallment}
|
||||
onCancel={onCloseInstallment}
|
||||
okText="确认"
|
||||
confirmLoading={saving}
|
||||
>
|
||||
<Form form={installmentForm} layout="vertical">
|
||||
<Form form={installmentForm} layout="vertical" scrollToFirstError>
|
||||
<Form.Item name="amount" label="分期金额(元)" rules={[{ required: true }]}>
|
||||
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import React from 'react';
|
||||
import { Button, Empty, Popconfirm, Space, Table, Tag } from 'antd';
|
||||
import { Button, Popconfirm, Space, Table, Tag } from 'antd';
|
||||
import { DeleteOutlined, InboxOutlined } from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { QueryEmpty } from '../../components/QueryState';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { statusMap } from './DepositModals';
|
||||
import type { DepositRecord } from './DepositModals';
|
||||
@@ -11,6 +12,8 @@ export interface DepositTableProps {
|
||||
data: any[];
|
||||
loading: boolean;
|
||||
canPurgeDeposit: boolean;
|
||||
canCreateDeposit?: boolean;
|
||||
onCreateDeposit?: () => void;
|
||||
refundForm: ReturnType<typeof import('antd').Form.useForm>[0];
|
||||
onDetail: (record: DepositRecord) => void;
|
||||
onRefund: (record: DepositRecord) => void;
|
||||
@@ -22,6 +25,8 @@ export const DepositTable: React.FC<DepositTableProps> = ({
|
||||
data,
|
||||
loading,
|
||||
canPurgeDeposit,
|
||||
canCreateDeposit,
|
||||
onCreateDeposit,
|
||||
refundForm,
|
||||
onDetail,
|
||||
onRefund,
|
||||
@@ -58,6 +63,7 @@ export const DepositTable: React.FC<DepositTableProps> = ({
|
||||
{ title: '备注', dataIndex: 'notes', width: 120, render: (v: unknown) => v || '-' },
|
||||
{
|
||||
title: '操作',
|
||||
fixed: 'right' as const,
|
||||
width: 240,
|
||||
render: (_: unknown, record: any) => {
|
||||
const hasDeposit = typeof record.id === 'number';
|
||||
@@ -142,7 +148,18 @@ export const DepositTable: React.FC<DepositTableProps> = ({
|
||||
pageSizeOptions: [15, 30, 50, 100],
|
||||
showTotal: (total) => `共 ${total} 条`,
|
||||
}}
|
||||
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<QueryEmpty
|
||||
description="暂无数据"
|
||||
action={
|
||||
canCreateDeposit && onCreateDeposit
|
||||
? { label: '收取押金', onClick: onCreateDeposit }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -11,6 +11,7 @@ import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { RefreshButton } from '../../components/RefreshButton';
|
||||
import { buildDepositStudentOptions, type DepositStudentLookup } from './deposit-student-option';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
import { useQuery, useQueryClient, type QueryKey } from '@tanstack/react-query';
|
||||
@@ -28,6 +29,8 @@ import {
|
||||
} from './DepositModals';
|
||||
import type { DepositRecord, EligibleStudent } from './DepositModals';
|
||||
import { DepositTable } from './DepositTable';
|
||||
import { QueryErrorState } from '../../components/QueryState';
|
||||
import { useVisibleRefetch } from '../../hooks/usePageVisible';
|
||||
|
||||
const DepositsPage: React.FC = () => {
|
||||
const { hasPermission } = usePermission();
|
||||
@@ -55,27 +58,26 @@ const DepositsPage: React.FC = () => {
|
||||
data: fetchResult = { data: [], students: [] },
|
||||
isLoading,
|
||||
isFetching,
|
||||
isError,
|
||||
refetch,
|
||||
} = useQuery<{ data: DepositRecord[]; students: DepositStudentLookup[] }>({
|
||||
queryKey: ['deposits'],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
const [d, s] = await Promise.all([
|
||||
api.get<DepositRecord[]>('/deposits'),
|
||||
api.get<DepositStudentLookup[]>('/deposits/student-lookups'),
|
||||
]);
|
||||
return {
|
||||
data: validateResponse<DepositRecord[]>(depositsSchema, d),
|
||||
students: validateResponse<DepositStudentLookup[]>(depositStudentLookupsSchema, s),
|
||||
};
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载失败');
|
||||
return { data: [], students: [] };
|
||||
}
|
||||
const [d, s] = await Promise.all([
|
||||
api.get<DepositRecord[]>('/deposits'),
|
||||
api.get<DepositStudentLookup[]>('/deposits/student-lookups'),
|
||||
]);
|
||||
return {
|
||||
data: validateResponse<DepositRecord[]>(depositsSchema, d),
|
||||
students: validateResponse<DepositStudentLookup[]>(depositStudentLookupsSchema, s),
|
||||
};
|
||||
},
|
||||
});
|
||||
const data = fetchResult.data;
|
||||
const students = fetchResult.students;
|
||||
const loading = isLoading || isFetching;
|
||||
// RouteKeeper 保活页面切回时刷新押金列表
|
||||
useVisibleRefetch(['deposits']);
|
||||
|
||||
const invalidateDeposits: QueryKey[] = [['deposits'], ['deposits', 'eligible']];
|
||||
const createMutation = useApiMutation(
|
||||
@@ -132,6 +134,8 @@ const DepositsPage: React.FC = () => {
|
||||
const {
|
||||
data: eligibleStudents = [],
|
||||
isFetching: eligibleFetching,
|
||||
isError: eligibleError,
|
||||
refetch: refetchEligible,
|
||||
} = useQuery<EligibleStudent[]>({
|
||||
queryKey: ['deposits', 'eligible', eligibleRoomType],
|
||||
queryFn: async () => {
|
||||
@@ -222,8 +226,17 @@ const DepositsPage: React.FC = () => {
|
||||
setBatchModal(true);
|
||||
};
|
||||
|
||||
const openCreateDeposit = () => {
|
||||
createForm.resetFields();
|
||||
createForm.setFieldsValue({ amount: 500, paidDate: dayjs() });
|
||||
setCreateModal(true);
|
||||
};
|
||||
|
||||
const handleBatchRoomTypeChange = (roomType: string) => {
|
||||
setBatchRoomType(roomType);
|
||||
// 切换房型后候选学生列表会变化,重置勾选状态,避免把上一房型的选择提交到新房型
|
||||
setSelectionTouched(false);
|
||||
setSelectedEligibleStudentIds([]);
|
||||
batchForm.setFieldsValue({
|
||||
amount: suggestedDepositByRoomType[roomType] ?? batchForm.getFieldValue('amount') ?? 100,
|
||||
});
|
||||
@@ -231,6 +244,7 @@ const DepositsPage: React.FC = () => {
|
||||
};
|
||||
|
||||
const handleCreate = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const values = await createForm.validateFields();
|
||||
await createMutation.mutateAsync({
|
||||
@@ -244,10 +258,13 @@ const DepositsPage: React.FC = () => {
|
||||
createForm.resetFields();
|
||||
} catch {
|
||||
// 错误提示由 useApiMutation 统一处理
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBatchCreate = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const values = await batchForm.validateFields();
|
||||
await batchCreateMutation.mutateAsync({
|
||||
@@ -263,6 +280,8 @@ const DepositsPage: React.FC = () => {
|
||||
setSelectionTouched(false);
|
||||
} catch {
|
||||
// 错误提示由 useApiMutation 统一处理
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -290,6 +309,7 @@ const DepositsPage: React.FC = () => {
|
||||
|
||||
const handleAddInstallment = async () => {
|
||||
if (installmentModal == null) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const values = await installmentForm.validateFields();
|
||||
await addInstallmentMutation.mutateAsync({
|
||||
@@ -304,6 +324,8 @@ const DepositsPage: React.FC = () => {
|
||||
installmentForm.resetFields();
|
||||
} catch {
|
||||
// 错误提示由 useApiMutation 统一处理
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -405,6 +427,7 @@ const DepositsPage: React.FC = () => {
|
||||
/>
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<RefreshButton loading={isFetching} onRefresh={() => void refetch()} />
|
||||
<PermissionButton
|
||||
permission="deposit:create"
|
||||
icon={<TeamOutlined />}
|
||||
@@ -416,26 +439,38 @@ const DepositsPage: React.FC = () => {
|
||||
permission="deposit:create"
|
||||
type="primary"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => {
|
||||
createForm.resetFields();
|
||||
createForm.setFieldsValue({ amount: 500, paidDate: dayjs() });
|
||||
setCreateModal(true);
|
||||
}}
|
||||
onClick={openCreateDeposit}
|
||||
>
|
||||
收取押金
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
</div>
|
||||
<DepositTable
|
||||
data={filteredData}
|
||||
loading={loading || (!!filterRoomType && eligibleLoading)}
|
||||
canPurgeDeposit={canPurgeDeposit}
|
||||
refundForm={refundForm}
|
||||
onDetail={(record) => setDetailModal(record)}
|
||||
onRefund={(record) => setRefundModal(record)}
|
||||
onArchive={(id) => archiveMutation.mutateAsync(id)}
|
||||
onPurge={(id) => purgeMutation.mutateAsync(id)}
|
||||
/>
|
||||
{isError ? (
|
||||
<QueryErrorState
|
||||
title="押金数据加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
) : filterRoomType && eligibleError ? (
|
||||
<QueryErrorState
|
||||
title="可收取押金的学生加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetchEligible()}
|
||||
/>
|
||||
) : (
|
||||
<DepositTable
|
||||
data={filteredData}
|
||||
loading={loading || (!!filterRoomType && eligibleLoading)}
|
||||
canPurgeDeposit={canPurgeDeposit}
|
||||
canCreateDeposit={hasPermission('deposit:create')}
|
||||
onCreateDeposit={openCreateDeposit}
|
||||
refundForm={refundForm}
|
||||
onDetail={(record) => setDetailModal(record)}
|
||||
onRefund={(record) => setRefundModal(record)}
|
||||
onArchive={(id) => archiveMutation.mutateAsync(id)}
|
||||
onPurge={(id) => purgeMutation.mutateAsync(id)}
|
||||
/>
|
||||
)}
|
||||
<DepositModals
|
||||
batchModal={batchModal}
|
||||
createModal={createModal}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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, Table, Tag, Tooltip, Skeleton} from 'antd';
|
||||
import { QueryErrorState } from '../../components/QueryState';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { ArrowLeftOutlined, EyeOutlined } from '@ant-design/icons';
|
||||
import { useNavigate, useParams } from 'react-router';
|
||||
@@ -15,7 +16,6 @@ import { examDetailSchema } from '../../api/schemas';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
import type { ExamItem } from './types';
|
||||
import './style.css';
|
||||
import { getErrorMessage } from '../../utils/error';
|
||||
|
||||
interface ScoreRow {
|
||||
id: number;
|
||||
@@ -56,19 +56,10 @@ const ExamDetailPage: React.FC = () => {
|
||||
const { id } = useParams();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { data: detail, isLoading, isFetching } = useQuery<ExamDetail | null>({
|
||||
const { data: detail, isLoading, isFetching, isError, refetch } = useQuery<ExamDetail | null>({
|
||||
queryKey: ['exams', 'detail', id],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
return validateResponse<ExamDetail>(
|
||||
examDetailSchema,
|
||||
await api.get<ExamDetail>(`/exams/${id}`),
|
||||
);
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error, '加载考试失败'));
|
||||
return null;
|
||||
}
|
||||
},
|
||||
queryFn: async () =>
|
||||
validateResponse<ExamDetail>(examDetailSchema, await api.get<ExamDetail>(`/exams/${id}`)),
|
||||
});
|
||||
const loading = isLoading || isFetching;
|
||||
|
||||
@@ -145,9 +136,18 @@ const ExamDetailPage: React.FC = () => {
|
||||
if (loading && !detail)
|
||||
return (
|
||||
<div className="exam-detail-loading">
|
||||
<Spin size="large" />
|
||||
<Skeleton active paragraph={{ rows: 10 }} />
|
||||
</div>
|
||||
);
|
||||
if (isError) {
|
||||
return (
|
||||
<QueryErrorState
|
||||
title="考试详情加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (!detail) return <Empty description="考试不存在或无权访问" />;
|
||||
|
||||
const average = detail.scores.find((row) => row.classAvg !== null)?.classAvg ?? null;
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
Card,
|
||||
Checkbox,
|
||||
Col,
|
||||
Empty,
|
||||
Form,
|
||||
Input,
|
||||
Popconfirm,
|
||||
@@ -39,6 +38,10 @@ import { useApiMutation } from '../../hooks/useApiMutation';
|
||||
import { validateResponse } from '../../utils/validate';
|
||||
import { classOptionsSchema, examsSchema } from '../../api/schemas';
|
||||
import { getErrorMessage } from '../../utils/error';
|
||||
import { QueryErrorState, QueryEmpty } from '../../components/QueryState';
|
||||
import { NextStepHint } from '../../components/NextStepHint';
|
||||
import { useVisibleRefetch } from '../../hooks/usePageVisible';
|
||||
import { useDirtyGuard } from '../../hooks/useDirtyGuard';
|
||||
|
||||
const ExamsPage: React.FC = () => {
|
||||
const { modal } = App.useApp();
|
||||
@@ -46,6 +49,7 @@ const ExamsPage: React.FC = () => {
|
||||
const { hasPermission } = usePermission();
|
||||
const canPurgeExam = hasPermission('exam:purge');
|
||||
const [form] = Form.useForm<ExamFormValues>();
|
||||
const examFormGuard = useDirtyGuard(form);
|
||||
const [batchLoading, setBatchLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
@@ -54,6 +58,8 @@ const ExamsPage: React.FC = () => {
|
||||
const [classId, setClassId] = useState<number>();
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
const [selectedExamIds, setSelectedExamIds] = useState<number[]>([]);
|
||||
// 考试创建成功后的「下一步:去详情录成绩」引导
|
||||
const [examCreatedId, setExamCreatedId] = useState<number | null>(null);
|
||||
const [debouncedFilters] = useDebounceValue(
|
||||
{ keyword, examType, classId, showArchived },
|
||||
200,
|
||||
@@ -76,7 +82,7 @@ const ExamsPage: React.FC = () => {
|
||||
},
|
||||
});
|
||||
|
||||
const { data = [], isFetching } = useQuery<ExamItem[]>({
|
||||
const { data = [], isFetching, isError, refetch } = useQuery<ExamItem[]>({
|
||||
queryKey: [
|
||||
'exams',
|
||||
debouncedFilters.keyword,
|
||||
@@ -85,26 +91,23 @@ const ExamsPage: React.FC = () => {
|
||||
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 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()}`),
|
||||
) ?? []
|
||||
);
|
||||
},
|
||||
});
|
||||
const loading = isFetching;
|
||||
// RouteKeeper 保活页面切回时刷新考试列表
|
||||
useVisibleRefetch(['exams']);
|
||||
|
||||
const saveMutation = useApiMutation(
|
||||
async (payload: Record<string, unknown>) => api.post('/exams', payload),
|
||||
@@ -153,6 +156,7 @@ const ExamsPage: React.FC = () => {
|
||||
const openCreate = () => {
|
||||
form.resetFields();
|
||||
form.setFieldValue('examDate', dayjs());
|
||||
examFormGuard.snapshot();
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
@@ -161,9 +165,10 @@ const ExamsPage: React.FC = () => {
|
||||
const values = await form.validateFields();
|
||||
setSaving(true);
|
||||
const payload = { ...values, examDate: values.examDate.format('YYYY-MM-DD') };
|
||||
await saveMutation.mutateAsync(payload);
|
||||
const created = (await saveMutation.mutateAsync(payload)) as { id?: number };
|
||||
message.success('考试已创建');
|
||||
setModalOpen(false);
|
||||
if (created?.id != null) setExamCreatedId(created.id);
|
||||
} catch {
|
||||
// 校验错误静默,接口错误由 useApiMutation 统一提示
|
||||
} finally {
|
||||
@@ -256,6 +261,20 @@ const ExamsPage: React.FC = () => {
|
||||
|
||||
return (
|
||||
<div className="exam-page">
|
||||
{examCreatedId !== null && (
|
||||
<NextStepHint
|
||||
title="考试已创建"
|
||||
description="接下来可以在考试详情中添加学生名单、录入成绩。"
|
||||
action={{
|
||||
label: '去考试详情',
|
||||
onClick: () => {
|
||||
navigate(`/exams/${examCreatedId}`);
|
||||
setExamCreatedId(null);
|
||||
},
|
||||
}}
|
||||
onClose={() => setExamCreatedId(null)}
|
||||
/>
|
||||
)}
|
||||
<div className="exam-toolbar">
|
||||
<Space wrap>
|
||||
<Input
|
||||
@@ -343,9 +362,22 @@ const ExamsPage: React.FC = () => {
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
{data.length === 0 && !loading ? (
|
||||
{isError ? (
|
||||
<QueryErrorState
|
||||
title="考试数据加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
) : data.length === 0 && !loading ? (
|
||||
<div className="exam-empty">
|
||||
<Empty description="暂无考试" />
|
||||
<QueryEmpty
|
||||
description="暂无考试"
|
||||
action={
|
||||
!showArchived
|
||||
? { label: '创建考试', icon: <PlusOutlined />, onClick: openCreate }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<Row gutter={[16, 16]}>
|
||||
@@ -456,7 +488,7 @@ const ExamsPage: React.FC = () => {
|
||||
saving={saving}
|
||||
form={form}
|
||||
classes={classes}
|
||||
onCancel={() => setModalOpen(false)}
|
||||
onCancel={() => examFormGuard.confirmClose(() => setModalOpen(false))}
|
||||
onSubmit={() => void submit()}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// aislop-ignore-file: duplicate-block -- 表格/表单声明结构相似且参数不同,渲染逻辑已共享组件化
|
||||
import React from 'react';
|
||||
import React, { useEffect } from 'react';
|
||||
import {
|
||||
DatePicker,
|
||||
Form,
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
Modal,
|
||||
Select,
|
||||
} from 'antd';
|
||||
import { useDirtyGuard } from '../../hooks/useDirtyGuard';
|
||||
import { useSubmitShortcut } from '../../hooks/useSubmitShortcut';
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
@@ -21,16 +23,23 @@ export const RoomExpenseModal: React.FC<{
|
||||
onOk: () => void;
|
||||
onCancel: () => void;
|
||||
}> = ({ open, editing, saving, form, rooms, typeOptions, onOk, onCancel }) => {
|
||||
useSubmitShortcut(open && !saving, () => onOk?.());
|
||||
const roomExpenseGuard = useDirtyGuard(form);
|
||||
// 父组件在打开弹窗前已完成表单回填,这里记录「未修改」基准
|
||||
useEffect(() => {
|
||||
if (open) roomExpenseGuard.snapshot();
|
||||
}, [open, roomExpenseGuard]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={editing ? '编辑宿舍费用' : '录入宿舍费用'}
|
||||
open={open}
|
||||
onOk={onOk}
|
||||
onCancel={onCancel}
|
||||
onCancel={() => roomExpenseGuard.confirmClose(onCancel)}
|
||||
okText={editing ? '保存' : '确认录入'}
|
||||
confirmLoading={saving}
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form form={form} layout="vertical" scrollToFirstError>
|
||||
<Form.Item name="roomId" label="宿舍" rules={[{ required: true }]}>
|
||||
<Select
|
||||
showSearch
|
||||
@@ -70,16 +79,23 @@ export const UtilityModal: React.FC<{
|
||||
onOk: () => void;
|
||||
onCancel: () => void;
|
||||
}> = ({ open, saving, form, students, onOk, onCancel }) => {
|
||||
useSubmitShortcut(open && !saving, () => onOk?.());
|
||||
const utilityGuard = useDirtyGuard(form);
|
||||
// 打开弹窗时记录当前表单值为「未修改」基准
|
||||
useEffect(() => {
|
||||
if (open) utilityGuard.snapshot();
|
||||
}, [open, utilityGuard]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title="添加学生水电费并立即出账"
|
||||
open={open}
|
||||
onOk={onOk}
|
||||
onCancel={onCancel}
|
||||
onCancel={() => utilityGuard.confirmClose(onCancel)}
|
||||
okText="生成账单并扣余额"
|
||||
confirmLoading={saving}
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form form={form} layout="vertical" scrollToFirstError>
|
||||
<Form.Item name="studentId" label="学生" rules={[{ required: true }]}>
|
||||
<Select
|
||||
showSearch
|
||||
@@ -123,16 +139,23 @@ export const PersonalExpenseModal: React.FC<{
|
||||
onOk: () => void;
|
||||
onCancel: () => void;
|
||||
}> = ({ open, editing, saving, form, students, rooms, personalTypeOptions, onOk, onCancel }) => {
|
||||
useSubmitShortcut(open && !saving, () => onOk?.());
|
||||
const personalExpenseGuard = useDirtyGuard(form);
|
||||
// 父组件在打开弹窗前已完成表单回填,这里记录「未修改」基准
|
||||
useEffect(() => {
|
||||
if (open) personalExpenseGuard.snapshot();
|
||||
}, [open, personalExpenseGuard]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={editing ? '编辑个人费用' : '录入个人附加费'}
|
||||
open={open}
|
||||
onOk={onOk}
|
||||
onCancel={onCancel}
|
||||
onCancel={() => personalExpenseGuard.confirmClose(onCancel)}
|
||||
okText={editing ? '保存' : '确认录入'}
|
||||
confirmLoading={saving}
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form form={form} layout="vertical" scrollToFirstError>
|
||||
<Form.Item name="studentId" label="学生" rules={[{ required: true }]}>
|
||||
<Select
|
||||
showSearch
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
Button,
|
||||
Empty,
|
||||
Input,
|
||||
Popconfirm,
|
||||
Select,
|
||||
@@ -24,6 +23,7 @@ import {
|
||||
import dayjs from 'dayjs';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
import { QueryEmpty } from '../../components/QueryState';
|
||||
import { message } from '../../ui/app-message';
|
||||
|
||||
export const EXPENSE_FIELDS = {
|
||||
@@ -65,6 +65,8 @@ export interface ExpenseTablePanelProps {
|
||||
onImport: (formData: FormData) => Promise<any>;
|
||||
onTemplateDownload: () => void;
|
||||
onExport?: () => void;
|
||||
templateLoading?: boolean;
|
||||
exportLoading?: boolean;
|
||||
onAddUtility?: () => void;
|
||||
}
|
||||
|
||||
@@ -98,6 +100,8 @@ export const ExpenseTablePanel: React.FC<ExpenseTablePanelProps> = ({
|
||||
onImport,
|
||||
onTemplateDownload,
|
||||
onExport,
|
||||
templateLoading,
|
||||
exportLoading,
|
||||
onAddUtility,
|
||||
}) => {
|
||||
const isRoom = kind === 'room';
|
||||
@@ -417,6 +421,7 @@ export const ExpenseTablePanel: React.FC<ExpenseTablePanelProps> = ({
|
||||
<PermissionButton
|
||||
permission="expense:view"
|
||||
icon={<DownloadOutlined />}
|
||||
loading={templateLoading}
|
||||
onClick={onTemplateDownload}
|
||||
>
|
||||
{isRoom ? '下载水电费模板' : '下载模板'}
|
||||
@@ -426,6 +431,7 @@ export const ExpenseTablePanel: React.FC<ExpenseTablePanelProps> = ({
|
||||
<PermissionButton
|
||||
permission="expense:view"
|
||||
icon={<ExportOutlined />}
|
||||
loading={exportLoading}
|
||||
onClick={onExport}
|
||||
>
|
||||
导出
|
||||
@@ -513,7 +519,18 @@ export const ExpenseTablePanel: React.FC<ExpenseTablePanelProps> = ({
|
||||
pageSizeOptions: [15, 30, 50, 100],
|
||||
showTotal: (total) => `共 ${total} 条`,
|
||||
}}
|
||||
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<QueryEmpty
|
||||
description="暂无数据"
|
||||
action={
|
||||
canImport && onAddUtility && !showArchived
|
||||
? { label: '添加学生水电费', onClick: onAddUtility }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedKeys,
|
||||
onChange: (keys) => onSelect(keys as number[]),
|
||||
|
||||
@@ -4,10 +4,10 @@ import { useQuery } from '@tanstack/react-query';
|
||||
import { App, Button, Form, Space, Tabs } from 'antd';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import { downloadBlob } from '../../utils/download';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
import { useApiMutation } from '../../hooks/useApiMutation';
|
||||
import { useDownload } from '../../hooks/useDownload';
|
||||
import { validateResponse } from '../../utils/validate';
|
||||
import {
|
||||
expenseLookupsSchema,
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
import { archiveViewPolicy, expenseStatusForView } from '../archive-view';
|
||||
import { ExpenseTablePanel } from './ExpenseTablePanel';
|
||||
import { PersonalExpenseModal, RoomExpenseModal, UtilityModal } from './ExpenseModals';
|
||||
import { QueryErrorState } from '../../components/QueryState';
|
||||
import { useVisibleRefetch } from '../../hooks/usePageVisible';
|
||||
|
||||
const ExpensesPage: React.FC = () => {
|
||||
const { modal } = App.useApp();
|
||||
@@ -42,6 +44,12 @@ const ExpensesPage: React.FC = () => {
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
const expenseViewPolicy = archiveViewPolicy(showArchived ? 'archived' : 'active');
|
||||
|
||||
const { downloading: utilityTemplateDownloading, run: runUtilityTemplateDownload } =
|
||||
useDownload();
|
||||
const { downloading: personalTemplateDownloading, run: runPersonalTemplateDownload } =
|
||||
useDownload();
|
||||
const { downloading: personalExportDownloading, run: runPersonalExportDownload } = useDownload();
|
||||
|
||||
const {
|
||||
data: typeLookups = { typeOptions: [], personalTypeOptions: [], typeMap: {} },
|
||||
} = useQuery<{
|
||||
@@ -64,6 +72,8 @@ const ExpensesPage: React.FC = () => {
|
||||
data: expenseResult = { rooms: [], personal: [], students: [], roomsList: [] },
|
||||
isLoading,
|
||||
isFetching,
|
||||
isError,
|
||||
refetch,
|
||||
} = useQuery<{
|
||||
rooms: any[];
|
||||
personal: any[];
|
||||
@@ -72,27 +82,22 @@ const ExpensesPage: React.FC = () => {
|
||||
}>({
|
||||
queryKey: ['expenses', showArchived ? 'archived' : 'active'],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
const [rooms, personal, students, roomsList] = await Promise.all([
|
||||
api.get('/expenses/room', {
|
||||
params: { status: expenseStatusForView(showArchived ? 'archived' : 'active') },
|
||||
}),
|
||||
api.get('/expenses/personal', {
|
||||
params: { status: expenseStatusForView(showArchived ? 'archived' : 'active') },
|
||||
}),
|
||||
api.get('/expenses/student-lookups'),
|
||||
api.get('/rooms'),
|
||||
]);
|
||||
return {
|
||||
rooms: validateResponse(expenseRecordsSchema, rooms),
|
||||
personal: validateResponse(expenseRecordsSchema, personal),
|
||||
students: validateResponse(expenseStudentLookupsSchema, students),
|
||||
roomsList: validateResponse(expenseRoomsListSchema, roomsList),
|
||||
};
|
||||
} catch {
|
||||
message.error('加载费用数据失败');
|
||||
return { rooms: [], personal: [], students: [], roomsList: [] };
|
||||
}
|
||||
const [rooms, personal, students, roomsList] = await Promise.all([
|
||||
api.get('/expenses/room', {
|
||||
params: { status: expenseStatusForView(showArchived ? 'archived' : 'active') },
|
||||
}),
|
||||
api.get('/expenses/personal', {
|
||||
params: { status: expenseStatusForView(showArchived ? 'archived' : 'active') },
|
||||
}),
|
||||
api.get('/expenses/student-lookups'),
|
||||
api.get('/rooms'),
|
||||
]);
|
||||
return {
|
||||
rooms: validateResponse(expenseRecordsSchema, rooms),
|
||||
personal: validateResponse(expenseRecordsSchema, personal),
|
||||
students: validateResponse(expenseStudentLookupsSchema, students),
|
||||
roomsList: validateResponse(expenseRoomsListSchema, roomsList),
|
||||
};
|
||||
},
|
||||
});
|
||||
const roomExpenses = expenseResult.rooms;
|
||||
@@ -100,6 +105,8 @@ const ExpensesPage: React.FC = () => {
|
||||
const students = expenseResult.students;
|
||||
const rooms = expenseResult.roomsList;
|
||||
const loading = isLoading || isFetching;
|
||||
// RouteKeeper 保活页面切回时刷新费用列表
|
||||
useVisibleRefetch(['expenses']);
|
||||
|
||||
const mutations = {
|
||||
saveRoom: useApiMutation(
|
||||
@@ -456,103 +463,117 @@ const ExpensesPage: React.FC = () => {
|
||||
已归档费用
|
||||
</Button>
|
||||
</Space>
|
||||
<Tabs
|
||||
items={[
|
||||
{
|
||||
key: 'room',
|
||||
label: '宿舍费用',
|
||||
children: (
|
||||
<ExpenseTablePanel
|
||||
kind="room"
|
||||
searchText={roomSearch}
|
||||
onSearchChange={setRoomSearch}
|
||||
typeFilter={roomTypeFilter}
|
||||
onTypeFilterChange={setRoomTypeFilter}
|
||||
typeOptions={typeOptions}
|
||||
typeMap={typeMap}
|
||||
data={filteredRoomExpenses}
|
||||
loading={loading}
|
||||
selectedKeys={selectedRoomKeys}
|
||||
onSelect={setSelectedRoomKeys}
|
||||
rooms={rooms}
|
||||
students={students}
|
||||
readonly={expenseViewPolicy.readonly}
|
||||
showArchived={showArchived}
|
||||
canPurgeExpense={canPurgeExpense}
|
||||
batchLoading={batchLoading}
|
||||
canImport={hasPermission('expense:create')}
|
||||
onBatchRestore={handleBatchRestoreRoom}
|
||||
onBatchPurge={handleBatchPurgeRoom}
|
||||
onBatchDelete={handleBatchDeleteRoom}
|
||||
onSaveCell={saveRoomCell}
|
||||
onPeriodSave={async (id, periodStart, periodEnd) => {
|
||||
try {
|
||||
await mutations.period.mutateAsync({ id, periodStart, periodEnd });
|
||||
message.success('已保存');
|
||||
} catch {
|
||||
// 错误提示由 useApiMutation 统一处理
|
||||
}
|
||||
}}
|
||||
onEdit={openEditRoom}
|
||||
onArchive={(id) => mutations.archiveRoom.mutateAsync(id)}
|
||||
onPurge={handlePurgeRoom}
|
||||
onImport={(formData) => mutations.importUtility.mutateAsync(formData)}
|
||||
onTemplateDownload={() => {
|
||||
void downloadBlob('/expenses/utility/template', '水电费导入模板.xlsx').catch(
|
||||
() => message.error('下载失败'),
|
||||
);
|
||||
}}
|
||||
onAddUtility={() => setUtilityModal(true)}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'personal',
|
||||
label: '个人附加费',
|
||||
children: (
|
||||
<ExpenseTablePanel
|
||||
kind="personal"
|
||||
searchText={personalSearch}
|
||||
onSearchChange={setPersonalSearch}
|
||||
typeFilter={personalTypeFilter}
|
||||
onTypeFilterChange={setPersonalTypeFilter}
|
||||
typeOptions={personalTypeOptions}
|
||||
typeMap={typeMap}
|
||||
data={filteredPersonalExpenses}
|
||||
loading={loading}
|
||||
selectedKeys={selectedPersonalKeys}
|
||||
onSelect={setSelectedPersonalKeys}
|
||||
rooms={rooms}
|
||||
students={students}
|
||||
readonly={expenseViewPolicy.readonly}
|
||||
showArchived={showArchived}
|
||||
canPurgeExpense={canPurgeExpense}
|
||||
batchLoading={batchLoading}
|
||||
canImport={hasPermission('expense:create')}
|
||||
onBatchRestore={handleBatchRestorePersonal}
|
||||
onBatchPurge={handleBatchPurgePersonal}
|
||||
onBatchDelete={handleBatchDeletePersonal}
|
||||
onSaveCell={savePersonalCell}
|
||||
onPeriodSave={async () => undefined}
|
||||
onEdit={openEditPersonal}
|
||||
onArchive={(id) => mutations.archivePersonal.mutateAsync(id)}
|
||||
onPurge={handlePurgePersonal}
|
||||
onImport={(formData) => mutations.importPersonal.mutateAsync(formData)}
|
||||
onTemplateDownload={() => {
|
||||
void downloadBlob('/expenses/personal/template', '个人附加费导入模板.xlsx').catch(
|
||||
() => message.error('下载失败'),
|
||||
);
|
||||
}}
|
||||
onExport={() => {
|
||||
downloadBlob('/expenses/personal/export', '个人附加费导出.xlsx').catch(() =>
|
||||
message.error('导出失败'),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
{isError ? (
|
||||
<QueryErrorState
|
||||
title="费用数据加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
) : (
|
||||
<Tabs
|
||||
items={[
|
||||
{
|
||||
key: 'room',
|
||||
label: '宿舍费用',
|
||||
children: (
|
||||
<ExpenseTablePanel
|
||||
kind="room"
|
||||
searchText={roomSearch}
|
||||
onSearchChange={setRoomSearch}
|
||||
typeFilter={roomTypeFilter}
|
||||
onTypeFilterChange={setRoomTypeFilter}
|
||||
typeOptions={typeOptions}
|
||||
typeMap={typeMap}
|
||||
data={filteredRoomExpenses}
|
||||
loading={loading}
|
||||
selectedKeys={selectedRoomKeys}
|
||||
onSelect={setSelectedRoomKeys}
|
||||
rooms={rooms}
|
||||
students={students}
|
||||
readonly={expenseViewPolicy.readonly}
|
||||
showArchived={showArchived}
|
||||
canPurgeExpense={canPurgeExpense}
|
||||
batchLoading={batchLoading}
|
||||
canImport={hasPermission('expense:create')}
|
||||
onBatchRestore={handleBatchRestoreRoom}
|
||||
onBatchPurge={handleBatchPurgeRoom}
|
||||
onBatchDelete={handleBatchDeleteRoom}
|
||||
onSaveCell={saveRoomCell}
|
||||
onPeriodSave={async (id, periodStart, periodEnd) => {
|
||||
try {
|
||||
await mutations.period.mutateAsync({ id, periodStart, periodEnd });
|
||||
message.success('已保存');
|
||||
} catch {
|
||||
// 错误提示由 useApiMutation 统一处理
|
||||
}
|
||||
}}
|
||||
onEdit={openEditRoom}
|
||||
onArchive={(id) => mutations.archiveRoom.mutateAsync(id)}
|
||||
onPurge={handlePurgeRoom}
|
||||
onImport={(formData) => mutations.importUtility.mutateAsync(formData)}
|
||||
onTemplateDownload={() => {
|
||||
void runUtilityTemplateDownload('/expenses/utility/template', '水电费导入模板.xlsx', {
|
||||
successMsg: '模板已下载',
|
||||
errorMsg: '下载失败',
|
||||
});
|
||||
}}
|
||||
templateLoading={utilityTemplateDownloading}
|
||||
onAddUtility={() => setUtilityModal(true)}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'personal',
|
||||
label: '个人附加费',
|
||||
children: (
|
||||
<ExpenseTablePanel
|
||||
kind="personal"
|
||||
searchText={personalSearch}
|
||||
onSearchChange={setPersonalSearch}
|
||||
typeFilter={personalTypeFilter}
|
||||
onTypeFilterChange={setPersonalTypeFilter}
|
||||
typeOptions={personalTypeOptions}
|
||||
typeMap={typeMap}
|
||||
data={filteredPersonalExpenses}
|
||||
loading={loading}
|
||||
selectedKeys={selectedPersonalKeys}
|
||||
onSelect={setSelectedPersonalKeys}
|
||||
rooms={rooms}
|
||||
students={students}
|
||||
readonly={expenseViewPolicy.readonly}
|
||||
showArchived={showArchived}
|
||||
canPurgeExpense={canPurgeExpense}
|
||||
batchLoading={batchLoading}
|
||||
canImport={hasPermission('expense:create')}
|
||||
onBatchRestore={handleBatchRestorePersonal}
|
||||
onBatchPurge={handleBatchPurgePersonal}
|
||||
onBatchDelete={handleBatchDeletePersonal}
|
||||
onSaveCell={savePersonalCell}
|
||||
onPeriodSave={async () => undefined}
|
||||
onEdit={openEditPersonal}
|
||||
onArchive={(id) => mutations.archivePersonal.mutateAsync(id)}
|
||||
onPurge={handlePurgePersonal}
|
||||
onImport={(formData) => mutations.importPersonal.mutateAsync(formData)}
|
||||
onTemplateDownload={() => {
|
||||
void runPersonalTemplateDownload('/expenses/personal/template', '个人附加费导入模板.xlsx', {
|
||||
successMsg: '模板已下载',
|
||||
errorMsg: '下载失败',
|
||||
});
|
||||
}}
|
||||
templateLoading={personalTemplateDownloading}
|
||||
onExport={() => {
|
||||
void runPersonalExportDownload('/expenses/personal/export', '个人附加费导出.xlsx', {
|
||||
successMsg: '导出成功',
|
||||
errorMsg: '导出失败',
|
||||
});
|
||||
}}
|
||||
exportLoading={personalExportDownloading}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
|
||||
<RoomExpenseModal
|
||||
open={roomModal}
|
||||
|
||||
@@ -30,12 +30,7 @@ import {
|
||||
isAppSecretRequired,
|
||||
type DingTalkConfigFormValues,
|
||||
} from './integration-config-form';
|
||||
import {
|
||||
cacheDingTalkDraft,
|
||||
cacheDingTalkServerSnapshot,
|
||||
commitDingTalkConfig,
|
||||
readDingTalkConfigCache,
|
||||
} from './integration-config-cache';
|
||||
import { useIntegrationConfigStore } from './integrationConfigStore';
|
||||
import { IntegrationOrgSyncPanel } from './IntegrationOrgSyncPanel';
|
||||
|
||||
interface DingTalkConfig {
|
||||
@@ -44,7 +39,10 @@ interface DingTalkConfig {
|
||||
}
|
||||
|
||||
const IntegrationConfigPage: React.FC = () => {
|
||||
const initialCache = useMemo(() => readDingTalkConfigCache(), []);
|
||||
const initialCache = useMemo(() => {
|
||||
const { loaded, config, verified, formValues, dirty } = useIntegrationConfigStore.getState();
|
||||
return { loaded, config, verified, formValues, dirty };
|
||||
}, []);
|
||||
const { hasPermission, hasAllPermissions } = usePermission();
|
||||
const canCreateClass = hasPermission('class:create');
|
||||
const [saving, setSaving] = useState(false);
|
||||
@@ -93,8 +91,8 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
|
||||
// 服务端配置同步进 localStorage 缓存,并回填表单
|
||||
useEffect(() => {
|
||||
cacheDingTalkServerSnapshot(config, verified);
|
||||
if (config) form.setFieldsValue(readDingTalkConfigCache().formValues);
|
||||
useIntegrationConfigStore.getState().cacheServerSnapshot(config, verified);
|
||||
if (config) form.setFieldsValue(useIntegrationConfigStore.getState().formValues);
|
||||
}, [config, verified, form]);
|
||||
|
||||
const handleSave = async () => {
|
||||
@@ -104,7 +102,7 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
try {
|
||||
await saveMutation.mutateAsync(payload);
|
||||
message.success('配置已保存');
|
||||
commitDingTalkConfig({ corpId: payload.corpId, agentId: payload.agentId });
|
||||
useIntegrationConfigStore.getState().commitConfig({ corpId: payload.corpId, agentId: payload.agentId });
|
||||
form.setFieldValue('appSecret', undefined);
|
||||
} catch {
|
||||
// 错误提示由 useApiMutation 统一处理
|
||||
@@ -162,7 +160,7 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
>
|
||||
<Spin spinning={loading}>
|
||||
{config && (
|
||||
<Descriptions size="small" column={2} style={{ marginBottom: 24 }}>
|
||||
<Descriptions size="small" column={{ xs: 1, sm: 2 }} style={{ marginBottom: 24 }}>
|
||||
<Descriptions.Item label="CorpId">{config.corpId || '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="AppKey">{config.agentId || '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="同步方式">手动触发</Descriptions.Item>
|
||||
@@ -180,7 +178,7 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
form={form}
|
||||
layout="vertical"
|
||||
initialValues={initialCache.formValues}
|
||||
onValuesChange={(_changed, values) => cacheDingTalkDraft(values)}
|
||||
onValuesChange={(_changed, values) => useIntegrationConfigStore.getState().cacheDraft(values)}
|
||||
style={{ maxWidth: 520 }}
|
||||
>
|
||||
<Form.Item
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
cacheDingTalkDraft,
|
||||
cacheDingTalkServerSnapshot,
|
||||
commitDingTalkConfig,
|
||||
readDingTalkConfigCache,
|
||||
resetDingTalkConfigCache,
|
||||
} from './integration-config-cache';
|
||||
|
||||
describe('DingTalk integration config page cache', () => {
|
||||
beforeEach(resetDingTalkConfigCache);
|
||||
|
||||
it('keeps an unsaved secret when a background refresh returns', () => {
|
||||
cacheDingTalkDraft({ corpId: 'draft-corp', agentId: 'draft-key', appSecret: 'draft-secret' });
|
||||
cacheDingTalkServerSnapshot({ corpId: 'saved-corp', agentId: 'saved-key' }, true);
|
||||
|
||||
expect(readDingTalkConfigCache()).toMatchObject({
|
||||
loaded: true,
|
||||
dirty: true,
|
||||
config: { corpId: 'saved-corp', agentId: 'saved-key' },
|
||||
formValues: {
|
||||
corpId: 'draft-corp',
|
||||
agentId: 'draft-key',
|
||||
appSecret: 'draft-secret',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('clears the secret after a successful save', () => {
|
||||
cacheDingTalkDraft({ corpId: 'corp', agentId: 'key', appSecret: 'secret' });
|
||||
commitDingTalkConfig({ corpId: 'corp', agentId: 'key' });
|
||||
|
||||
expect(readDingTalkConfigCache()).toMatchObject({
|
||||
loaded: true,
|
||||
dirty: false,
|
||||
formValues: { corpId: 'corp', agentId: 'key', appSecret: undefined },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,62 +0,0 @@
|
||||
import type { DingTalkConfigFormValues } from './integration-config-form';
|
||||
|
||||
export interface DingTalkSavedConfig {
|
||||
agentId: string;
|
||||
corpId: string;
|
||||
}
|
||||
|
||||
interface DingTalkConfigCache {
|
||||
loaded: boolean;
|
||||
config: DingTalkSavedConfig | null;
|
||||
verified: boolean | null;
|
||||
formValues: Partial<DingTalkConfigFormValues>;
|
||||
dirty: boolean;
|
||||
}
|
||||
|
||||
const cache: DingTalkConfigCache = {
|
||||
loaded: false,
|
||||
config: null,
|
||||
verified: null,
|
||||
formValues: {},
|
||||
dirty: false,
|
||||
};
|
||||
|
||||
export function readDingTalkConfigCache(): DingTalkConfigCache {
|
||||
return {
|
||||
...cache,
|
||||
config: cache.config ? { ...cache.config } : null,
|
||||
formValues: { ...cache.formValues },
|
||||
};
|
||||
}
|
||||
|
||||
export function cacheDingTalkDraft(values: Partial<DingTalkConfigFormValues>): void {
|
||||
cache.formValues = { ...values };
|
||||
cache.dirty = true;
|
||||
}
|
||||
|
||||
export function cacheDingTalkServerSnapshot(
|
||||
config: DingTalkSavedConfig | null,
|
||||
verified: boolean | null,
|
||||
): void {
|
||||
cache.loaded = true;
|
||||
cache.config = config ? { ...config } : null;
|
||||
cache.verified = verified;
|
||||
if (!cache.dirty) {
|
||||
cache.formValues = config ? { ...config, appSecret: undefined } : {};
|
||||
}
|
||||
}
|
||||
|
||||
export function commitDingTalkConfig(config: DingTalkSavedConfig): void {
|
||||
cache.loaded = true;
|
||||
cache.config = { ...config };
|
||||
cache.formValues = { ...config, appSecret: undefined };
|
||||
cache.dirty = false;
|
||||
}
|
||||
|
||||
export function resetDingTalkConfigCache(): void {
|
||||
cache.loaded = false;
|
||||
cache.config = null;
|
||||
cache.verified = null;
|
||||
cache.formValues = {};
|
||||
cache.dirty = false;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { useIntegrationConfigStore } from './integrationConfigStore';
|
||||
|
||||
const { getState } = useIntegrationConfigStore;
|
||||
|
||||
const readCache = () => {
|
||||
const { loaded, config, verified, formValues, dirty } = getState();
|
||||
return { loaded, config, verified, formValues, dirty };
|
||||
};
|
||||
|
||||
describe('DingTalk integration config page cache', () => {
|
||||
beforeEach(() => getState().reset());
|
||||
|
||||
it('keeps an unsaved secret when a background refresh returns', () => {
|
||||
getState().cacheDraft({ corpId: 'draft-corp', agentId: 'draft-key', appSecret: 'draft-secret' });
|
||||
getState().cacheServerSnapshot({ corpId: 'saved-corp', agentId: 'saved-key' }, true);
|
||||
|
||||
expect(readCache()).toMatchObject({
|
||||
loaded: true,
|
||||
dirty: true,
|
||||
config: { corpId: 'saved-corp', agentId: 'saved-key' },
|
||||
formValues: {
|
||||
corpId: 'draft-corp',
|
||||
agentId: 'draft-key',
|
||||
appSecret: 'draft-secret',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('clears the secret after a successful save', () => {
|
||||
getState().cacheDraft({ corpId: 'corp', agentId: 'key', appSecret: 'secret' });
|
||||
getState().commitConfig({ corpId: 'corp', agentId: 'key' });
|
||||
|
||||
expect(readCache()).toMatchObject({
|
||||
loaded: true,
|
||||
dirty: false,
|
||||
formValues: { corpId: 'corp', agentId: 'key', appSecret: undefined },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { create } from 'zustand';
|
||||
import { devtools } from 'zustand/middleware';
|
||||
import type { DingTalkConfigFormValues } from './integration-config-form';
|
||||
|
||||
export interface DingTalkSavedConfig {
|
||||
agentId: string;
|
||||
corpId: string;
|
||||
}
|
||||
|
||||
interface DingTalkConfigState {
|
||||
/** 服务端配置是否已加载过(区分「未加载」与「确实为空」) */
|
||||
loaded: boolean;
|
||||
config: DingTalkSavedConfig | null;
|
||||
verified: boolean | null;
|
||||
/** 表单草稿:保留未保存的 appSecret 等敏感字段 */
|
||||
formValues: Partial<DingTalkConfigFormValues>;
|
||||
/** 是否存在未保存的草稿 */
|
||||
dirty: boolean;
|
||||
}
|
||||
|
||||
interface DingTalkConfigActions {
|
||||
/** 表单变化时缓存草稿 */
|
||||
cacheDraft: (values: Partial<DingTalkConfigFormValues>) => void;
|
||||
/** 后台拉取服务端配置成功时缓存快照(不覆盖已有草稿) */
|
||||
cacheServerSnapshot: (config: DingTalkSavedConfig | null, verified: boolean | null) => void;
|
||||
/** 保存成功后提交配置并清空草稿 */
|
||||
commitConfig: (config: DingTalkSavedConfig) => void;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
export type DingTalkConfigStore = DingTalkConfigState & DingTalkConfigActions;
|
||||
|
||||
const initialDingTalkConfig: DingTalkConfigState = {
|
||||
loaded: false,
|
||||
config: null,
|
||||
verified: null,
|
||||
formValues: {},
|
||||
dirty: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* 钉钉集成页面的表单/配置会话缓存(页面级 store)。
|
||||
*
|
||||
* 原实现为模块级单例(integration-config-cache.ts):在 RouteKeeper 淘汰
|
||||
* 页面或重新进入页面时仍保留草稿。迁入 zustand 后语义一致、可重置可测试。
|
||||
*/
|
||||
export const useIntegrationConfigStore = create<DingTalkConfigStore>()(
|
||||
devtools(
|
||||
(set, get) => ({
|
||||
...initialDingTalkConfig,
|
||||
cacheDraft: (values) =>
|
||||
set(
|
||||
{ formValues: { ...values }, dirty: true },
|
||||
false,
|
||||
'integrationConfig/cacheDraft',
|
||||
),
|
||||
cacheServerSnapshot: (config, verified) => {
|
||||
const { dirty, formValues } = get();
|
||||
set(
|
||||
{
|
||||
loaded: true,
|
||||
config: config ? { ...config } : null,
|
||||
verified,
|
||||
formValues: dirty ? formValues : config ? { ...config, appSecret: undefined } : {},
|
||||
},
|
||||
false,
|
||||
'integrationConfig/cacheServerSnapshot',
|
||||
);
|
||||
},
|
||||
commitConfig: (config) =>
|
||||
set(
|
||||
{
|
||||
loaded: true,
|
||||
config: { ...config },
|
||||
formValues: { ...config, appSecret: undefined },
|
||||
dirty: false,
|
||||
},
|
||||
false,
|
||||
'integrationConfig/commitConfig',
|
||||
),
|
||||
reset: () =>
|
||||
set({ ...initialDingTalkConfig }, false, 'integrationConfig/reset'),
|
||||
}),
|
||||
{ name: 'integration-config-store', enabled: import.meta.env.DEV },
|
||||
),
|
||||
);
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useState } from 'react';
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { Form, Input, Button, Card, Typography } from 'antd';
|
||||
import { UserOutlined, LockOutlined } from '@ant-design/icons';
|
||||
@@ -18,6 +18,14 @@ const LoginPage: React.FC = () => {
|
||||
const clearPermissions = usePermissionStore((state) => state.clearPermissions);
|
||||
const writePermissions = usePermissionStore((state) => state.writePermissions);
|
||||
|
||||
// 会话过期被登出(如 AI 流式请求 401)后回到登录页时给出提示
|
||||
useEffect(() => {
|
||||
if (sessionStorage.getItem('login_expired_hint')) {
|
||||
sessionStorage.removeItem('login_expired_hint');
|
||||
message.warning('登录已过期,请重新登录');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const onFinish = useCallback(
|
||||
async (values: any) => {
|
||||
clearPermissions();
|
||||
@@ -75,7 +83,7 @@ const LoginPage: React.FC = () => {
|
||||
name="username"
|
||||
rules={[{ required: true, message: '请输入用户名' }]}
|
||||
>
|
||||
<Input prefix={<UserOutlined />} placeholder="用户名" autoComplete="username" />
|
||||
<Input prefix={<UserOutlined />} placeholder="用户名" autoComplete="username" autoFocus />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
label="密码"
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
import dayjs from 'dayjs';
|
||||
import { validateResponse } from '../../utils/validate';
|
||||
import { notificationsSchema } from '../../api/schemas';
|
||||
import { List, Typography, Menu, Layout, Button, Empty, Spin, Space, Grid, Select } from 'antd';
|
||||
import { List, Typography, Menu, Layout, Button, Spin, Space, Grid, Select } from 'antd';
|
||||
import {
|
||||
BellOutlined,
|
||||
DollarOutlined,
|
||||
@@ -14,10 +14,13 @@ import { useNavigate } from 'react-router';
|
||||
import api from '../../api';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { formatNotificationText } from '../../utils/notification-display';
|
||||
import { QueryErrorState, QueryEmpty } from '../../components/QueryState';
|
||||
|
||||
const { Sider, Content } = Layout;
|
||||
const { useBreakpoint } = Grid;
|
||||
|
||||
const PAGE_SIZE = 50;
|
||||
|
||||
interface NotificationItem {
|
||||
id: number;
|
||||
type: string;
|
||||
@@ -41,15 +44,11 @@ const typeMap: Record<string, { label: string; icon: React.ReactNode }> = {
|
||||
};
|
||||
|
||||
function timeAgo(dateStr: string): string {
|
||||
const diff = Date.now() - new Date(dateStr).getTime();
|
||||
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);
|
||||
if (days < 7) return `${days}天前`;
|
||||
return new Date(dateStr).toLocaleDateString('zh-CN');
|
||||
const diff = Date.now() - dayjs(dateStr).valueOf();
|
||||
if (diff < 60_000) return '刚刚';
|
||||
// 7 天内用相对时间(dayjs relativeTime 已全局配置),更早显示具体日期
|
||||
if (diff < 7 * 86_400_000) return dayjs(dateStr).fromNow();
|
||||
return dayjs(dateStr).format('YYYY/M/D');
|
||||
}
|
||||
|
||||
const FILTER_ITEMS: Array<{ key: string; icon: React.ReactNode; label: string }> = [
|
||||
@@ -65,31 +64,55 @@ const NotificationsPage: React.FC = () => {
|
||||
const isMobile = !screens.sm;
|
||||
const [filter, setFilter] = useState('all');
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data: notifications = [], isLoading, isFetching } = useQuery<NotificationItem[]>({
|
||||
queryKey: ['notifications'],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
return validateResponse<NotificationItem[]>(
|
||||
notificationsSchema,
|
||||
await api.get('/notifications?limit=50'),
|
||||
);
|
||||
} catch (e: any) {
|
||||
console.error('加载通知失败', e);
|
||||
message.error(e?.message || '加载通知失败');
|
||||
return [];
|
||||
}
|
||||
},
|
||||
});
|
||||
const loading = isLoading || isFetching;
|
||||
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
const [hasMore, setHasMore] = useState(true);
|
||||
|
||||
const loadPage = useCallback(async (after?: number) => {
|
||||
if (after === undefined) {
|
||||
setLoading(true);
|
||||
} else {
|
||||
setLoadingMore(true);
|
||||
}
|
||||
setError(false);
|
||||
try {
|
||||
const params =
|
||||
after !== undefined ? `?after=${after}&limit=${PAGE_SIZE}` : `?limit=${PAGE_SIZE}`;
|
||||
const res = validateResponse<NotificationItem[]>(
|
||||
notificationsSchema,
|
||||
await api.get(`/notifications${params}`),
|
||||
);
|
||||
setNotifications((prev) => (after === undefined ? res : [...prev, ...res]));
|
||||
setHasMore(res.length === PAGE_SIZE);
|
||||
} catch (e: any) {
|
||||
console.error('加载通知失败', e);
|
||||
setError(true);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setLoadingMore(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void loadPage();
|
||||
}, [loadPage]);
|
||||
|
||||
const loadMore = () => {
|
||||
const last = notifications[notifications.length - 1];
|
||||
if (!last || loadingMore || loading) return;
|
||||
// 列表按 createdAt DESC 排序,最后一条 id 最小,作为下一页游标
|
||||
void loadPage(last.id);
|
||||
};
|
||||
|
||||
const handleClick = async (item: NotificationItem) => {
|
||||
if (!item.isRead) {
|
||||
try {
|
||||
await api.put(`/notifications/${item.id}/read`);
|
||||
queryClient.setQueryData<NotificationItem[]>(['notifications'], (prev) =>
|
||||
(prev ?? []).map((n) => (n.id === item.id ? { ...n, isRead: true } : n)),
|
||||
setNotifications((prev) =>
|
||||
prev.map((n) => (n.id === item.id ? { ...n, isRead: true } : n)),
|
||||
);
|
||||
} catch (e: any) {
|
||||
console.error('标记已读失败', e);
|
||||
@@ -102,9 +125,7 @@ const NotificationsPage: React.FC = () => {
|
||||
const handleMarkAll = async () => {
|
||||
try {
|
||||
await api.put('/notifications/read-all');
|
||||
queryClient.setQueryData<NotificationItem[]>(['notifications'], (prev) =>
|
||||
(prev ?? []).map((n) => ({ ...n, isRead: true })),
|
||||
);
|
||||
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
|
||||
} catch (e: any) {
|
||||
console.error('全部已读失败', e);
|
||||
message.error(e?.message || '操作失败');
|
||||
@@ -141,76 +162,91 @@ const NotificationsPage: React.FC = () => {
|
||||
className="notifications-filter"
|
||||
/>
|
||||
)}
|
||||
<Spin spinning={loading}>
|
||||
{filtered.length === 0 ? (
|
||||
<Empty description="暂无通知" />
|
||||
) : (
|
||||
<List
|
||||
dataSource={filtered}
|
||||
renderItem={(item) => {
|
||||
const meta = typeMap[item.type] || { label: item.type, icon: <BellOutlined /> };
|
||||
return (
|
||||
<List.Item
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={`通知: ${item.title}`}
|
||||
onClick={() => handleClick(item)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
handleClick(item);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
cursor: 'pointer',
|
||||
padding: '16px 0',
|
||||
backgroundColor: item.isRead ? 'transparent' : '#f0f7ff',
|
||||
}}
|
||||
>
|
||||
<List.Item.Meta
|
||||
avatar={
|
||||
<div
|
||||
style={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: '50%',
|
||||
background: '#f0f0f0',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
{meta.icon}
|
||||
</div>
|
||||
}
|
||||
title={
|
||||
<Space wrap size={[8, 2]}>
|
||||
<Typography.Text strong={!item.isRead} style={{ fontSize: 15 }}>
|
||||
{formatNotificationText(item.title)}
|
||||
</Typography.Text>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{timeAgo(item.createdAt)}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
}
|
||||
description={
|
||||
item.content && (
|
||||
<Typography.Paragraph
|
||||
type="secondary"
|
||||
ellipsis={{ rows: 1 }}
|
||||
style={{ marginBottom: 0 }}
|
||||
{error && !loading ? (
|
||||
<QueryErrorState
|
||||
title="通知加载失败"
|
||||
description="请检查网络后重试。"
|
||||
onRetry={() => void loadPage()}
|
||||
/>
|
||||
) : (
|
||||
<Spin spinning={loading}>
|
||||
{filtered.length === 0 ? (
|
||||
<QueryEmpty description="暂无通知,有新消息时会在这里提醒你" />
|
||||
) : (
|
||||
<List
|
||||
dataSource={filtered}
|
||||
renderItem={(item) => {
|
||||
const meta = typeMap[item.type] || { label: item.type, icon: <BellOutlined /> };
|
||||
return (
|
||||
<List.Item
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={`通知: ${item.title}`}
|
||||
onClick={() => handleClick(item)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
handleClick(item);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
cursor: 'pointer',
|
||||
padding: '16px 0',
|
||||
backgroundColor: item.isRead ? 'transparent' : '#f0f7ff',
|
||||
}}
|
||||
>
|
||||
<List.Item.Meta
|
||||
avatar={
|
||||
<div
|
||||
style={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: '50%',
|
||||
background: '#f0f0f0',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
{formatNotificationText(item.content)}
|
||||
</Typography.Paragraph>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</List.Item>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Spin>
|
||||
{meta.icon}
|
||||
</div>
|
||||
}
|
||||
title={
|
||||
<Space wrap size={[8, 2]}>
|
||||
<Typography.Text strong={!item.isRead} style={{ fontSize: 15 }}>
|
||||
{formatNotificationText(item.title)}
|
||||
</Typography.Text>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{timeAgo(item.createdAt)}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
}
|
||||
description={
|
||||
item.content && (
|
||||
<Typography.Paragraph
|
||||
type="secondary"
|
||||
ellipsis={{ rows: 1 }}
|
||||
style={{ marginBottom: 0 }}
|
||||
>
|
||||
{formatNotificationText(item.content)}
|
||||
</Typography.Paragraph>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</List.Item>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{filtered.length > 0 && hasMore && (
|
||||
<div style={{ textAlign: 'center', padding: '16px 0' }}>
|
||||
<Button loading={loadingMore} onClick={loadMore}>
|
||||
加载更多
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Spin>
|
||||
)}
|
||||
</Content>
|
||||
</Layout>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import React from 'react';
|
||||
import { Alert, Button, Empty, Popconfirm, Table } from 'antd';
|
||||
import { Alert, Button, Popconfirm, Table } from 'antd';
|
||||
import { InboxOutlined, LogoutOutlined, UndoOutlined, DeleteOutlined } from '@ant-design/icons';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { QueryEmpty } from '../../components/QueryState';
|
||||
|
||||
export const OccupanciesTableArea: React.FC<{
|
||||
columns: any[];
|
||||
@@ -12,6 +13,8 @@ export const OccupanciesTableArea: React.FC<{
|
||||
batchAction: 'checkout' | 'archive' | 'restore';
|
||||
canDelete: boolean;
|
||||
canPurge: boolean;
|
||||
canCheckIn?: boolean;
|
||||
onCheckIn?: () => void;
|
||||
batchLoading: boolean;
|
||||
onBatchCheckOut: () => void;
|
||||
onBatchDelete: () => void;
|
||||
@@ -27,6 +30,8 @@ export const OccupanciesTableArea: React.FC<{
|
||||
batchAction,
|
||||
canDelete,
|
||||
canPurge,
|
||||
canCheckIn,
|
||||
onCheckIn,
|
||||
batchLoading,
|
||||
onBatchCheckOut,
|
||||
onBatchDelete,
|
||||
@@ -127,7 +132,18 @@ export const OccupanciesTableArea: React.FC<{
|
||||
dataSource={data}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<QueryEmpty
|
||||
description="暂无数据"
|
||||
action={
|
||||
canCheckIn && onCheckIn
|
||||
? { label: '入住登记', onClick: onCheckIn }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
scroll={{ x: 1300 }}
|
||||
pagination={{
|
||||
defaultPageSize: 15,
|
||||
|
||||
@@ -27,6 +27,8 @@ export const OccupanciesToolbar: React.FC<{
|
||||
onDepositAmountChange: (value: number) => void;
|
||||
onDownloadTemplate: () => void;
|
||||
onExport: () => void;
|
||||
templateLoading?: boolean;
|
||||
exportLoading?: boolean;
|
||||
}> = ({
|
||||
viewMode,
|
||||
onChangeViewMode,
|
||||
@@ -42,6 +44,8 @@ export const OccupanciesToolbar: React.FC<{
|
||||
onDepositAmountChange,
|
||||
onDownloadTemplate,
|
||||
onExport,
|
||||
templateLoading,
|
||||
exportLoading,
|
||||
}) => {
|
||||
return (
|
||||
<div className="responsive-toolbar">
|
||||
@@ -130,13 +134,19 @@ export const OccupanciesToolbar: React.FC<{
|
||||
<PermissionButton
|
||||
permission="occupancy:view"
|
||||
icon={<DownloadOutlined />}
|
||||
loading={templateLoading}
|
||||
onClick={onDownloadTemplate}
|
||||
>
|
||||
下载模板
|
||||
</PermissionButton>
|
||||
) : null}
|
||||
{viewMode !== 'archived' ? (
|
||||
<PermissionButton permission="occupancy:view" icon={<ExportOutlined />} onClick={onExport}>
|
||||
<PermissionButton
|
||||
permission="occupancy:view"
|
||||
icon={<ExportOutlined />}
|
||||
loading={exportLoading}
|
||||
onClick={onExport}
|
||||
>
|
||||
导出记录
|
||||
</PermissionButton>
|
||||
) : null}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user