forked from wangziqi/gongxue-base
Compare commits
72 Commits
codex/xyx
...
29c55ebff1
| Author | SHA1 | Date | |
|---|---|---|---|
| 29c55ebff1 | |||
| 5e1ba70e59 | |||
| d306de48e4 | |||
| b32dc33e8b | |||
| 151ef06ec2 | |||
| a87f26a915 | |||
| ad62b8595c | |||
| 2c0be0f033 | |||
| bbd700369c | |||
| 00e9c5e45a | |||
| 990c0c16e6 | |||
| 4c2192d85e | |||
| 2d7c30eb30 | |||
| 2ee8bd47e2 | |||
| a871bb3f96 | |||
| ed428c8aa3 | |||
| 62a5f817ae | |||
| c7ba2799b9 | |||
| 375c7ec60b | |||
| 92d303ed01 | |||
| 295debee33 | |||
| a8da6de235 | |||
| 98d335b889 | |||
| 5836b421d8 | |||
| 4af7acbeaa | |||
| c11f6bb614 | |||
| d25e451b61 | |||
| 7edb4ff853 | |||
| b3d0bafc22 | |||
| a5bda6f093 | |||
| f7328d670d | |||
| 3131d2e141 | |||
| 2beedc22af | |||
| fa086e4c1c | |||
| 4fbcde48b1 | |||
| c93ac986aa | |||
| ab7f7c725a | |||
| 200d2e423b | |||
| 559b8a56e9 | |||
| d037787346 | |||
| 8ba51f48c0 | |||
| 7a62d8962a | |||
| 1737563516 | |||
| 6a43f33f7a | |||
| d582d641c0 | |||
| fb9697bd05 | |||
| bc49d1016a | |||
| 8bd445df5a | |||
| fcde6caaaa | |||
| b1f35f9d1a | |||
| 17a5046ea0 | |||
| e45da7f998 | |||
| c75a08affe | |||
| b480070e69 | |||
| 598b4e8acd | |||
| eac336a54a | |||
| ce5fd1c6cb | |||
| 05a936bbc2 | |||
| 3adf4933d8 | |||
| d84f37e98f | |||
| 16b56ffcd5 | |||
| 718c58589f | |||
| aaf49d5580 | |||
| 5cf6aede1e | |||
| 811e7ce826 | |||
| 79fa472b78 | |||
| 029af37f3a | |||
| d572e984d2 | |||
| a93ba657a8 | |||
| 77714642a5 | |||
| e7aa202603 | |||
| 013b3f4afe |
@@ -1,21 +0,0 @@
|
||||
node_modules
|
||||
npm-debug.log
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
.git
|
||||
.gitignore
|
||||
README.md
|
||||
*.md
|
||||
dist
|
||||
build
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
coverage
|
||||
.nyc_output
|
||||
.DS_Store
|
||||
.vscode
|
||||
.idea
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
@@ -8,11 +8,15 @@ MYSQL_ROOT_PASSWORD=change-me-to-a-strong-password
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
DB_USERNAME=root
|
||||
DB_DATABASE=gongxue
|
||||
DB_DATABASE=dorm_billing_v2
|
||||
DB_SYNCHRONIZE=false
|
||||
JWT_SECRET=change-me-to-a-random-string-at-least-32-chars
|
||||
JWT_EXPIRES_IN=24h
|
||||
PORT=3000
|
||||
|
||||
# 初始管理员 admin 密码(仅首次创建 admin 用户时生效)
|
||||
ADMIN_PASSWORD=change-me-admin-password
|
||||
|
||||
PORT=3002
|
||||
|
||||
# ---- AI 模型配置 ----
|
||||
# AES-256-GCM 加密主密钥,用于加密存储 API Key
|
||||
|
||||
40
.gitea/workflows/ci.yml
Normal file
40
.gitea/workflows/ci.yml
Normal file
@@ -0,0 +1,40 @@
|
||||
# PR 自动检查:代码风格 + 类型检查 + 测试
|
||||
name: CI 检查
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
- run: npm ci
|
||||
- run: npm run lint
|
||||
|
||||
typecheck:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
- run: npm ci
|
||||
- run: npm run typecheck
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [lint, typecheck]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
- run: npm ci
|
||||
- run: npm run test
|
||||
80
.gitea/workflows/deploy.yml
Normal file
80
.gitea/workflows/deploy.yml
Normal file
@@ -0,0 +1,80 @@
|
||||
# PM2 手动部署工作流
|
||||
# 手动触发 → 构建 → rsync → 安装依赖 → 数据库迁移 → PM2 重载
|
||||
#
|
||||
# 前置准备:
|
||||
# 1. 服务器 MySQL 已在运行
|
||||
# 2. 服务器已安装 PM2: npm i -g pm2
|
||||
# 3. Gitea 仓库 Settings → Secrets 配置:
|
||||
# - SSH_PRIVATE_KEY : 部署用 SSH 私钥
|
||||
# - SSH_HOST : 服务器地址
|
||||
# - SSH_USER : SSH 用户名
|
||||
# - SSH_PORT : SSH 端口(默认 22,可选)
|
||||
# - REMOTE_DIR : 服务器项目目录,如 /opt/gongxue
|
||||
|
||||
name: PM2 部署
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 安装 Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
|
||||
- name: 安装依赖 & 构建
|
||||
run: |
|
||||
npm ci
|
||||
npm run build -w @gongxue/server
|
||||
npm run build -w @gongxue/admin
|
||||
|
||||
- name: 配置 SSH
|
||||
run: |
|
||||
mkdir -p ~/.ssh
|
||||
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/deploy_key
|
||||
chmod 600 ~/.ssh/deploy_key
|
||||
cat >> ~/.ssh/config <<'EOF'
|
||||
Host deploy-server
|
||||
HostName ${{ secrets.SSH_HOST }}
|
||||
User ${{ secrets.SSH_USER }}
|
||||
Port ${{ secrets.SSH_PORT || '22' }}
|
||||
IdentityFile ~/.ssh/deploy_key
|
||||
StrictHostKeyChecking accept-new
|
||||
EOF
|
||||
|
||||
- name: 同步代码到服务器
|
||||
run: |
|
||||
rsync -avz --delete \
|
||||
--exclude='node_modules' \
|
||||
--exclude='.git' \
|
||||
--exclude='*.db' \
|
||||
--exclude='.DS_Store' \
|
||||
--exclude='logs/' \
|
||||
--exclude='.turbo/' \
|
||||
--exclude='.claude/' \
|
||||
--exclude='.codegraph/' \
|
||||
./ deploy-server:${{ secrets.REMOTE_DIR }}/
|
||||
|
||||
- name: 安装依赖 → 迁移 → PM2 重载
|
||||
run: |
|
||||
ssh deploy-server "
|
||||
cd ${{ secrets.REMOTE_DIR }}
|
||||
mkdir -p logs
|
||||
if [ ! -d node_modules ]; then
|
||||
echo '首次部署,安装生产依赖...'
|
||||
npm ci --omit=dev
|
||||
fi
|
||||
echo '执行数据库迁移...'
|
||||
npm run migration:run -w @gongxue/server
|
||||
echo 'PM2 重载...'
|
||||
pm2 startOrReload ecosystem.config.cjs --update-env
|
||||
pm2 save
|
||||
echo '=== PM2 状态 ==='
|
||||
pm2 status
|
||||
"
|
||||
@@ -1,14 +0,0 @@
|
||||
FROM node:22-alpine AS builder
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
COPY apps/admin/package.json ./apps/admin/package.json
|
||||
COPY packages/typescript-config/package.json ./packages/typescript-config/package.json
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
RUN npm run build -w @gongxue/admin
|
||||
|
||||
FROM nginx:alpine
|
||||
COPY --from=builder /app/apps/admin/dist /usr/share/nginx/html
|
||||
COPY apps/admin/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
EXPOSE 80
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
@@ -14,6 +14,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^6.1.1",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"antd": "^6.3.6",
|
||||
"axios": "^1.15.1",
|
||||
"dayjs": "^1.11.20",
|
||||
|
||||
@@ -14,6 +14,7 @@ const RoomsPage = lazy(() => import('./pages/Rooms'));
|
||||
const OccupanciesPage = lazy(() => import('./pages/Occupancies'));
|
||||
const ExpensesPage = lazy(() => import('./pages/Expenses'));
|
||||
const BillsPage = lazy(() => import('./pages/Bills'));
|
||||
const WalletsPage = lazy(() => import('./pages/Wallets'));
|
||||
const RoomVisualPage = lazy(() => import('./pages/RoomVisual'));
|
||||
const OperationLogsPage = lazy(() => import('./pages/OperationLogs'));
|
||||
const UsersPage = lazy(() => import('./pages/Users'));
|
||||
@@ -23,13 +24,14 @@ const TeachersPage = lazy(() => import('./pages/Teachers'));
|
||||
const StudentProfilePage = lazy(() => import('./pages/StudentProfile'));
|
||||
const ClassesPage = lazy(() => import('./pages/Classes'));
|
||||
const ClassDetailPage = lazy(() => import('./pages/Classes/detail'));
|
||||
const OrganizationsPage = lazy(() => import('./pages/Organizations'))
|
||||
const OrganizationsPage = lazy(() => import('./pages/Organizations'));
|
||||
const ClassroomRentalsPage = lazy(() => import('./pages/ClassroomRentals'));
|
||||
const ClassroomSchedulePage = lazy(() => import('./pages/ClassroomSchedule'));
|
||||
const SchedulesPage = lazy(() => import('./pages/Schedules'));
|
||||
const RolesPage = lazy(() => import('./pages/Roles'));
|
||||
const PermissionsPage = lazy(() => import('./pages/Permissions'));
|
||||
const AttendancePage = lazy(() => import('./pages/Attendance'));
|
||||
const AttendanceDevicesPage = lazy(() => import('./pages/AttendanceDevices'));
|
||||
const TeacherWorkspacePage = lazy(() => import('./pages/TeacherWorkspace'));
|
||||
const NotificationsPage = lazy(() => import('./pages/Notifications'));
|
||||
const IntegrationConfigPage = lazy(() => import('./pages/IntegrationConfig'));
|
||||
@@ -57,236 +59,258 @@ const App: React.FC = () => {
|
||||
<AntdApp>
|
||||
<AppMessageBridge />
|
||||
<BrowserRouter>
|
||||
<Suspense fallback={<div style={{ minHeight: '40vh', display: 'grid', placeItems: 'center' }}><Spin size="large" /></div>}>
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<MainLayout />
|
||||
</PrivateRoute>
|
||||
}
|
||||
>
|
||||
<Route index element={<DefaultRoute />} />
|
||||
<Suspense
|
||||
fallback={
|
||||
<div style={{ minHeight: '40vh', display: 'grid', placeItems: 'center' }}>
|
||||
<Spin size="large" />
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route
|
||||
path="dashboard"
|
||||
path="/"
|
||||
element={
|
||||
<PermissionRoute permission="dashboard:view">
|
||||
<DashboardPage />
|
||||
</PermissionRoute>
|
||||
<PrivateRoute>
|
||||
<MainLayout />
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="room-visual"
|
||||
element={
|
||||
<PermissionRoute permission="room:view">
|
||||
<RoomVisualPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="students"
|
||||
element={
|
||||
<PermissionRoute permission="student:view">
|
||||
<StudentsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
>
|
||||
<Route index element={<DefaultRoute />} />
|
||||
<Route
|
||||
path="dashboard"
|
||||
element={
|
||||
<PermissionRoute permission="dashboard:view">
|
||||
<DashboardPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="room-visual"
|
||||
element={
|
||||
<PermissionRoute permission="room:view">
|
||||
<RoomVisualPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="students"
|
||||
element={
|
||||
<PermissionRoute permission="student:view">
|
||||
<StudentsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="students/:id/profile"
|
||||
element={
|
||||
<PermissionRoute permission="student:view">
|
||||
<StudentProfilePage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="rooms"
|
||||
element={
|
||||
<PermissionRoute permission="room:view">
|
||||
<RoomsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="occupancies"
|
||||
element={
|
||||
<PermissionRoute permission="occupancy:view">
|
||||
<OccupanciesPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="expenses"
|
||||
element={
|
||||
<PermissionRoute permission="expense:view">
|
||||
<ExpensesPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="deposits"
|
||||
element={
|
||||
<PermissionRoute permission="deposit:view">
|
||||
<DepositsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="bills"
|
||||
element={
|
||||
<PermissionRoute permission="bill:view">
|
||||
<BillsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="classes"
|
||||
element={
|
||||
<PermissionRoute permission="class:view">
|
||||
<ClassesPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="classes/:id"
|
||||
element={
|
||||
<PermissionRoute permission="class:view">
|
||||
<ClassDetailPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="operation-logs"
|
||||
element={
|
||||
<PermissionRoute permission="log:view">
|
||||
<OperationLogsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="roles"
|
||||
element={
|
||||
<PermissionRoute permission="role:view">
|
||||
<RolesPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="permissions"
|
||||
element={
|
||||
<PermissionRoute permission="role:view">
|
||||
<PermissionsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="users"
|
||||
element={
|
||||
<PermissionRoute permission="user:view">
|
||||
<UsersPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="teachers"
|
||||
element={
|
||||
<PermissionRoute permission="teacher:view">
|
||||
<TeachersPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="classrooms"
|
||||
element={
|
||||
<PermissionRoute permission="classroom:view">
|
||||
<ClassroomsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="organizations"
|
||||
element={
|
||||
<PermissionRoute permission="organization:view">
|
||||
<OrganizationsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="classroom-rentals"
|
||||
element={
|
||||
<PermissionRoute permission="rental:view">
|
||||
<ClassroomRentalsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="classroom-schedule"
|
||||
element={
|
||||
<PermissionRoute permission="rental:view">
|
||||
<ClassroomSchedulePage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="students/:id/profile"
|
||||
element={
|
||||
<PermissionRoute permission="student:view">
|
||||
<StudentProfilePage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="rooms"
|
||||
element={
|
||||
<PermissionRoute permission="room:view">
|
||||
<RoomsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="occupancies"
|
||||
element={
|
||||
<PermissionRoute permission="occupancy:view">
|
||||
<OccupanciesPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="expenses"
|
||||
element={
|
||||
<PermissionRoute permission="expense:view">
|
||||
<ExpensesPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="deposits"
|
||||
element={
|
||||
<PermissionRoute permission="deposit:view">
|
||||
<DepositsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="wallets"
|
||||
element={
|
||||
<PermissionRoute permission="wallet:view">
|
||||
<WalletsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="bills"
|
||||
element={
|
||||
<PermissionRoute permission="bill:view">
|
||||
<BillsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="classes"
|
||||
element={
|
||||
<PermissionRoute permission="class:view">
|
||||
<ClassesPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="classes/:id"
|
||||
element={
|
||||
<PermissionRoute permission="class:view">
|
||||
<ClassDetailPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="operation-logs"
|
||||
element={
|
||||
<PermissionRoute permission="log:view">
|
||||
<OperationLogsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="roles"
|
||||
element={
|
||||
<PermissionRoute permission="role:view">
|
||||
<RolesPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="permissions"
|
||||
element={
|
||||
<PermissionRoute permission="role:view">
|
||||
<PermissionsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="users"
|
||||
element={
|
||||
<PermissionRoute permission="user:view">
|
||||
<UsersPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="teachers"
|
||||
element={
|
||||
<PermissionRoute permission="teacher:view">
|
||||
<TeachersPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="classrooms"
|
||||
element={
|
||||
<PermissionRoute permission="classroom:view">
|
||||
<ClassroomsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="organizations"
|
||||
element={
|
||||
<PermissionRoute permission="organization:view">
|
||||
<OrganizationsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="classroom-rentals"
|
||||
element={
|
||||
<PermissionRoute permission="rental:view">
|
||||
<ClassroomRentalsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="classroom-schedule"
|
||||
element={
|
||||
<PermissionRoute permission="rental:view">
|
||||
<ClassroomSchedulePage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="attendance"
|
||||
element={
|
||||
<PermissionRoute permission="attendance:view">
|
||||
<AttendancePage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="attendance-devices"
|
||||
element={
|
||||
<PermissionRoute permission="classroom:view">
|
||||
<AttendanceDevicesPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="schedules"
|
||||
element={
|
||||
<PermissionRoute permission="schedule:view">
|
||||
<SchedulesPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="attendance"
|
||||
element={
|
||||
<PermissionRoute permission="attendance:view">
|
||||
<AttendancePage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="teacher-workspace"
|
||||
element={
|
||||
<PermissionRoute permission="teacher-workspace:view">
|
||||
<TeacherWorkspacePage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="schedules"
|
||||
element={
|
||||
<PermissionRoute permission="schedule:view">
|
||||
<SchedulesPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="notifications"
|
||||
element={
|
||||
<PermissionRoute permission="notification:view">
|
||||
<NotificationsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="teacher-workspace"
|
||||
element={
|
||||
<PermissionRoute permission="teacher-workspace:view">
|
||||
<TeacherWorkspacePage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="notifications"
|
||||
element={
|
||||
<PermissionRoute permission="notification:view">
|
||||
<NotificationsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="integration-config"
|
||||
element={
|
||||
<PermissionRoute permission="integration:read">
|
||||
<IntegrationConfigPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="integration-config"
|
||||
element={
|
||||
<PermissionRoute permission="integration:read">
|
||||
<IntegrationConfigPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="ai-config"
|
||||
element={
|
||||
<PermissionRoute permission="ai:config:read">
|
||||
<AiConfigPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
</Route>
|
||||
</Routes>
|
||||
<Route
|
||||
path="ai-config"
|
||||
element={
|
||||
<PermissionRoute permission="ai:config:read">
|
||||
<AiConfigPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
</Route>
|
||||
</Routes>
|
||||
</Suspense>
|
||||
</BrowserRouter>
|
||||
</AntdApp>
|
||||
|
||||
@@ -16,8 +16,7 @@ instance.interceptors.request.use((config) => {
|
||||
instance.interceptors.response.use(
|
||||
(res) => res.data,
|
||||
(err) => {
|
||||
const isLoginRequest =
|
||||
err.config?.url === '/auth/login' || err.config?.url === 'auth/login';
|
||||
const isLoginRequest = err.config?.url === '/auth/login' || err.config?.url === 'auth/login';
|
||||
|
||||
if (err.response?.status === 401 && !isLoginRequest) {
|
||||
localStorage.removeItem('token');
|
||||
|
||||
@@ -45,9 +45,7 @@ describe('role-aware menu policy', () => {
|
||||
'/attendance',
|
||||
'/notifications',
|
||||
]);
|
||||
expect(findRoleAwareLandingPath(['任课老师'], teacherPermissions)).toBe(
|
||||
'/teacher-workspace',
|
||||
);
|
||||
expect(findRoleAwareLandingPath(['任课老师'], teacherPermissions)).toBe('/teacher-workspace');
|
||||
});
|
||||
|
||||
it('places schedules and attendance only once in academic management', () => {
|
||||
|
||||
@@ -43,7 +43,12 @@ const SECTIONS: MenuSection[] = [
|
||||
icon: 'calendar',
|
||||
roles: ['teacher'],
|
||||
children: [
|
||||
{ key: '/teacher-workspace', label: '今日教学', icon: 'workspace', permission: 'teacher-workspace:view' },
|
||||
{
|
||||
key: '/teacher-workspace',
|
||||
label: '今日教学',
|
||||
icon: 'workspace',
|
||||
permission: 'teacher-workspace:view',
|
||||
},
|
||||
{ key: '/schedules', label: '我的排课', icon: 'calendar', permission: 'schedule:view' },
|
||||
{ key: '/attendance', label: '课程考勤', icon: 'attendance', permission: 'attendance:view' },
|
||||
],
|
||||
@@ -73,6 +78,7 @@ const SECTIONS: MenuSection[] = [
|
||||
{ key: '/occupancies', label: '入住管理', icon: 'occupancy', permission: 'occupancy:view' },
|
||||
{ key: '/expenses', label: '费用管理', icon: 'expense', permission: 'expense:view' },
|
||||
{ key: '/bills', label: '账单管理', icon: 'bill', permission: 'bill:view' },
|
||||
{ key: '/wallets', label: '学生余额', icon: 'wallet', permission: 'wallet:view' },
|
||||
{ key: '/deposits', label: '押金管理', icon: 'deposit', permission: 'deposit:view' },
|
||||
],
|
||||
},
|
||||
@@ -82,10 +88,26 @@ const SECTIONS: MenuSection[] = [
|
||||
icon: 'classroom',
|
||||
roles: ['classroom', 'super'],
|
||||
children: [
|
||||
{ key: '/classroom-schedule', label: '教室排期', icon: 'calendar', permission: 'rental:view' },
|
||||
{
|
||||
key: '/classroom-schedule',
|
||||
label: '教室排期',
|
||||
icon: 'calendar',
|
||||
permission: 'rental:view',
|
||||
},
|
||||
{ key: '/classrooms', label: '教室管理', icon: 'classroom', permission: 'classroom:view' },
|
||||
{
|
||||
key: '/attendance-devices',
|
||||
label: '考勤机绑定',
|
||||
icon: 'attendance',
|
||||
permission: 'classroom:view',
|
||||
},
|
||||
{ key: '/classroom-rentals', label: '租赁订单', icon: 'rental', permission: 'rental:view' },
|
||||
{ key: '/organizations', label: '机构管理', icon: 'organization', permission: 'organization:view' },
|
||||
{
|
||||
key: '/organizations',
|
||||
label: '机构管理',
|
||||
icon: 'organization',
|
||||
permission: 'organization:view',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -98,21 +120,30 @@ const SECTIONS: MenuSection[] = [
|
||||
{ key: '/roles', label: '角色管理', icon: 'role', permission: 'role:view' },
|
||||
{ key: '/permissions', label: '权限一览', icon: 'permission', permission: 'role:view' },
|
||||
{ key: '/operation-logs', label: '操作日志', icon: 'log', permission: 'log:view' },
|
||||
{ key: '/integration-config', label: '钉钉集成', icon: 'integration', permission: 'integration:read' },
|
||||
{
|
||||
key: '/integration-config',
|
||||
label: '钉钉集成',
|
||||
icon: 'integration',
|
||||
permission: 'integration:read',
|
||||
},
|
||||
{ key: '/ai-config', label: 'AI 配置', icon: 'ai', permission: 'ai:config:read' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export function getRoleDomains(roles: readonly string[], permissions: readonly string[]): Set<string> {
|
||||
export function getRoleDomains(
|
||||
roles: readonly string[],
|
||||
permissions: readonly string[],
|
||||
): Set<string> {
|
||||
const normalized = new Set(roles.map((role) => ROLE_ALIASES[role]).filter(Boolean));
|
||||
// 权限可以来自多个叠加角色,因此业务域按能力累加,而不是只选择一个。
|
||||
if (permissions.includes('student:view') || permissions.includes('class:view')) {
|
||||
normalized.add('academic');
|
||||
}
|
||||
if (
|
||||
permissions.includes('room:view') &&
|
||||
(permissions.includes('occupancy:view') || permissions.includes('expense:view'))
|
||||
(permissions.includes('room:view') &&
|
||||
(permissions.includes('occupancy:view') || permissions.includes('expense:view'))) ||
|
||||
permissions.includes('wallet:view')
|
||||
) {
|
||||
normalized.add('accommodation');
|
||||
}
|
||||
@@ -164,7 +195,8 @@ export function buildMenu(roles: readonly string[], permissions: readonly string
|
||||
const children = section.children
|
||||
.filter((child) => permissionSet.has(child.permission))
|
||||
.map(({ permission: _, ...child }) => child);
|
||||
if (children.length > 0) sections.push({ ...section, children, roles: undefined } as AppMenuItem);
|
||||
if (children.length > 0)
|
||||
sections.push({ ...section, children, roles: undefined } as AppMenuItem);
|
||||
}
|
||||
|
||||
if (permissionSet.has('notification:view')) {
|
||||
|
||||
@@ -13,11 +13,7 @@ describe('permission navigation', () => {
|
||||
|
||||
it('lands teachers on the teacher workspace without global student or class access', () => {
|
||||
expect(
|
||||
findFirstAccessiblePath([
|
||||
'teacher-workspace:view',
|
||||
'schedule:view',
|
||||
'attendance:view',
|
||||
]),
|
||||
findFirstAccessiblePath(['teacher-workspace:view', 'schedule:view', 'attendance:view']),
|
||||
).toBe('/teacher-workspace');
|
||||
expect(canAccessPath('/students', ['teacher-workspace:view'])).toBe(false);
|
||||
expect(canAccessPath('/classes', ['teacher-workspace:view'])).toBe(false);
|
||||
|
||||
@@ -14,12 +14,21 @@ export const PERMISSION_PAGES: readonly PermissionPage[] = [
|
||||
{ path: '/rooms', permission: 'room:view' },
|
||||
{ path: '/occupancies', permission: 'occupancy:view' },
|
||||
{ path: '/teacher-workspace', permission: 'teacher-workspace:view' },
|
||||
{ path: '/students', permission: 'student:view', matches: (p) => p === '/students' || /^\/students\/\d+\/profile$/.test(p) },
|
||||
{ path: '/classes', permission: 'class:view', matches: (p) => p === '/classes' || /^\/classes\/\d+$/.test(p) },
|
||||
{
|
||||
path: '/students',
|
||||
permission: 'student:view',
|
||||
matches: (p) => p === '/students' || /^\/students\/\d+\/profile$/.test(p),
|
||||
},
|
||||
{
|
||||
path: '/classes',
|
||||
permission: 'class:view',
|
||||
matches: (p) => p === '/classes' || /^\/classes\/\d+$/.test(p),
|
||||
},
|
||||
{ path: '/attendance', permission: 'attendance:view' },
|
||||
{ path: '/schedules', permission: 'schedule:view' },
|
||||
{ path: '/classroom-schedule', permission: 'rental:view' },
|
||||
{ path: '/classrooms', permission: 'classroom:view' },
|
||||
{ path: '/attendance-devices', permission: 'classroom:view' },
|
||||
{ path: '/classroom-rentals', permission: 'rental:view' },
|
||||
{ path: '/organizations', permission: 'organization:view' },
|
||||
{ path: '/expenses', permission: 'expense:view' },
|
||||
|
||||
@@ -3,7 +3,9 @@ export const PERMISSIONS_UPDATED_EVENT = 'permissions-updated';
|
||||
export function readPermissions(): string[] {
|
||||
try {
|
||||
const value = JSON.parse(localStorage.getItem('permissions') || '[]');
|
||||
return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
|
||||
return Array.isArray(value)
|
||||
? value.filter((item): item is string => typeof item === 'string')
|
||||
: [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -15,7 +15,9 @@ const DefaultRoute: React.FC = () => {
|
||||
})();
|
||||
const firstPath = findRoleAwareLandingPath(roles, permissions);
|
||||
if (firstPath) return <Navigate to={firstPath} replace />;
|
||||
return <Result status="403" title="暂无可访问功能" subTitle="请联系管理员为当前账号分配功能权限" />;
|
||||
return (
|
||||
<Result status="403" title="暂无可访问功能" subTitle="请联系管理员为当前账号分配功能权限" />
|
||||
);
|
||||
};
|
||||
|
||||
export default DefaultRoute;
|
||||
|
||||
@@ -34,16 +34,20 @@ const NotificationBell: React.FC = () => {
|
||||
|
||||
const fetchNotifications = async () => {
|
||||
try {
|
||||
const data = await api.get('/notifications?limit=20') as unknown as NotificationItem[];
|
||||
const data = (await api.get('/notifications?limit=20')) as unknown as NotificationItem[];
|
||||
setNotifications(data);
|
||||
} catch { /* ignore */ }
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
const fetchUnread = async () => {
|
||||
try {
|
||||
const data = await api.get('/notifications/unread-count') as unknown as { count: number };
|
||||
const data = (await api.get('/notifications/unread-count')) as unknown as { count: number };
|
||||
setUnreadCount(data.count);
|
||||
} catch { /* ignore */ }
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
const openRef = useRef(open);
|
||||
openRef.current = open;
|
||||
@@ -60,7 +64,9 @@ const NotificationBell: React.FC = () => {
|
||||
JSON.parse(event.data);
|
||||
setUnreadCount((c) => c + 1);
|
||||
if (openRef.current) fetchNotifications();
|
||||
} catch { /* ignore */ }
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
es.onerror = () => {
|
||||
es.close();
|
||||
@@ -84,7 +90,9 @@ const NotificationBell: React.FC = () => {
|
||||
try {
|
||||
await api.put(`/notifications/${item.id}/read`);
|
||||
setUnreadCount((c) => Math.max(0, c - 1));
|
||||
} catch { /* ignore */ }
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
setOpen(false);
|
||||
if (item.link) navigate(item.link);
|
||||
@@ -94,10 +102,10 @@ const NotificationBell: React.FC = () => {
|
||||
try {
|
||||
await api.put('/notifications/read-all');
|
||||
setUnreadCount(0);
|
||||
setNotifications((prev) =>
|
||||
prev.map((n) => ({ ...n, isRead: true })),
|
||||
);
|
||||
} catch { /* ignore */ }
|
||||
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
const content = (
|
||||
@@ -148,18 +156,13 @@ const NotificationBell: React.FC = () => {
|
||||
)
|
||||
}
|
||||
title={
|
||||
<Typography.Text
|
||||
strong={!item.isRead}
|
||||
style={{ fontSize: 14 }}
|
||||
>
|
||||
[{notificationTypeLabels[item.type] || item.type}] {formatNotificationText(item.title)}
|
||||
<Typography.Text strong={!item.isRead} style={{ fontSize: 14 }}>
|
||||
[{notificationTypeLabels[item.type] || item.type}]{' '}
|
||||
{formatNotificationText(item.title)}
|
||||
</Typography.Text>
|
||||
}
|
||||
description={
|
||||
<Typography.Text
|
||||
type="secondary"
|
||||
style={{ fontSize: 12 }}
|
||||
>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{timeAgo(item.createdAt)}
|
||||
</Typography.Text>
|
||||
}
|
||||
|
||||
@@ -25,7 +25,13 @@ const PermissionRoute: React.FC<PermissionRouteProps> = ({ permission, children
|
||||
status="403"
|
||||
title="无权访问"
|
||||
subTitle="您没有访问此页面的权限"
|
||||
extra={firstPath ? <Button type="primary" onClick={() => navigate(firstPath, { replace: true })}>前往可访问页面</Button> : undefined}
|
||||
extra={
|
||||
firstPath ? (
|
||||
<Button type="primary" onClick={() => navigate(firstPath, { replace: true })}>
|
||||
前往可访问页面
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
196
apps/admin/src/components/RouteDock/index.tsx
Normal file
196
apps/admin/src/components/RouteDock/index.tsx
Normal file
@@ -0,0 +1,196 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import type { DragEndEvent } from '@dnd-kit/core';
|
||||
import { closestCenter, DndContext, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
|
||||
import {
|
||||
arrayMove,
|
||||
horizontalListSortingStrategy,
|
||||
SortableContext,
|
||||
useSortable,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import { Tabs } from 'antd';
|
||||
import type { TabsProps } from 'antd';
|
||||
import type { Location } from 'react-router-dom';
|
||||
import type { AppMenuItem } from '../../auth/menu-policy';
|
||||
|
||||
const STORAGE_KEY = 'gongxue-route-dock';
|
||||
|
||||
interface DockTab {
|
||||
key: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface RouteDockProps {
|
||||
location: Location;
|
||||
menuItems: readonly AppMenuItem[];
|
||||
onNavigate: (path: string) => void;
|
||||
draggable: boolean;
|
||||
}
|
||||
|
||||
interface DraggableTabNodeProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
'data-node-key': string;
|
||||
}
|
||||
|
||||
function findMenuLabel(items: readonly AppMenuItem[], pathname: string): string | undefined {
|
||||
for (const item of items) {
|
||||
if (item.key === pathname) return item.label;
|
||||
if (item.children) {
|
||||
const label = findMenuLabel(item.children, pathname);
|
||||
if (label) return label;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getRouteLabel(items: readonly AppMenuItem[], pathname: string): string {
|
||||
const menuLabel = findMenuLabel(items, pathname);
|
||||
if (menuLabel) return menuLabel;
|
||||
if (/^\/students\/\d+\/profile$/.test(pathname)) return '学生档案';
|
||||
if (/^\/classes\/\d+$/.test(pathname)) return '班级详情';
|
||||
return pathname === '/' ? '首页' : '页面';
|
||||
}
|
||||
|
||||
function readStoredTabs(): DockTab[] {
|
||||
try {
|
||||
const parsed = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter(
|
||||
(tab): tab is DockTab =>
|
||||
typeof tab?.key === 'string' && tab.key.startsWith('/') && typeof tab?.label === 'string',
|
||||
);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const DraggableTabNode: React.FC<Readonly<DraggableTabNodeProps>> = ({ ...props }) => {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
|
||||
id: props['data-node-key'],
|
||||
});
|
||||
const child = props.children as React.ReactElement<{ style?: React.CSSProperties }>;
|
||||
|
||||
return React.cloneElement(child, {
|
||||
ref: setNodeRef,
|
||||
style: {
|
||||
...child.props.style,
|
||||
transform: CSS.Translate.toString(transform),
|
||||
transition,
|
||||
cursor: isDragging ? 'grabbing' : 'grab',
|
||||
zIndex: isDragging ? 1 : undefined,
|
||||
opacity: isDragging ? 0.92 : undefined,
|
||||
boxShadow: isDragging ? '0 8px 20px rgba(29, 29, 31, 0.14)' : undefined,
|
||||
},
|
||||
...attributes,
|
||||
...listeners,
|
||||
} as React.HTMLAttributes<HTMLElement>);
|
||||
};
|
||||
|
||||
const RouteDock: React.FC<RouteDockProps> = ({ location, menuItems, onNavigate, draggable }) => {
|
||||
const activeKey = `${location.pathname}${location.search}`;
|
||||
const [tabs, setTabs] = useState<DockTab[]>(() => {
|
||||
const storedTabs = readStoredTabs();
|
||||
if (location.pathname === '/') return storedTabs;
|
||||
if (storedTabs.some((tab) => tab.key === activeKey)) return storedTabs;
|
||||
return [...storedTabs, { key: activeKey, label: getRouteLabel(menuItems, location.pathname) }];
|
||||
});
|
||||
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }));
|
||||
|
||||
useEffect(() => {
|
||||
if (location.pathname === '/') return;
|
||||
setTabs((currentTabs) => {
|
||||
const label = getRouteLabel(menuItems, location.pathname);
|
||||
const existing = currentTabs.find((tab) => tab.key === activeKey);
|
||||
if (!existing) return [...currentTabs, { key: activeKey, label }];
|
||||
if (existing.label === label) return currentTabs;
|
||||
return currentTabs.map((tab) => (tab.key === activeKey ? { ...tab, label } : tab));
|
||||
});
|
||||
}, [activeKey, location.pathname, menuItems]);
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(tabs));
|
||||
}, [tabs]);
|
||||
|
||||
const tabItems = useMemo<NonNullable<TabsProps['items']>>(
|
||||
() =>
|
||||
tabs.map((tab) => ({
|
||||
key: tab.key,
|
||||
label: tab.label,
|
||||
closable: tabs.length > 1,
|
||||
})),
|
||||
[tabs],
|
||||
);
|
||||
|
||||
const closeTab = (targetKey: string) => {
|
||||
const targetIndex = tabs.findIndex((tab) => tab.key === targetKey);
|
||||
if (targetIndex < 0 || tabs.length === 1) return;
|
||||
const nextTabs = tabs.filter((tab) => tab.key !== targetKey);
|
||||
setTabs(nextTabs);
|
||||
if (targetKey === activeKey) {
|
||||
const nextActiveTab = nextTabs[Math.min(targetIndex, nextTabs.length - 1)];
|
||||
if (nextActiveTab) onNavigate(nextActiveTab.key);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDragEnd = ({ active, over }: DragEndEvent) => {
|
||||
if (!over || active.id === over.id) return;
|
||||
setTabs((currentTabs) => {
|
||||
const activeIndex = currentTabs.findIndex((tab) => tab.key === active.id);
|
||||
const overIndex = currentTabs.findIndex((tab) => tab.key === over.id);
|
||||
return activeIndex < 0 || overIndex < 0
|
||||
? currentTabs
|
||||
: arrayMove(currentTabs, activeIndex, overIndex);
|
||||
});
|
||||
};
|
||||
|
||||
const renderTabBar: TabsProps['renderTabBar'] = (tabBarProps, DefaultTabBar) => {
|
||||
const tabBar = (
|
||||
<DefaultTabBar {...tabBarProps}>
|
||||
{(node) => {
|
||||
if (!draggable) return node;
|
||||
return (
|
||||
<DraggableTabNode
|
||||
{...(node as React.ReactElement<DraggableTabNodeProps>).props}
|
||||
key={node.key}
|
||||
>
|
||||
{node}
|
||||
</DraggableTabNode>
|
||||
);
|
||||
}}
|
||||
</DefaultTabBar>
|
||||
);
|
||||
|
||||
if (!draggable) return tabBar;
|
||||
return (
|
||||
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
|
||||
<SortableContext
|
||||
items={tabs.map((tab) => tab.key)}
|
||||
strategy={horizontalListSortingStrategy}
|
||||
>
|
||||
{tabBar}
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
);
|
||||
};
|
||||
|
||||
if (location.pathname === '/' || tabs.length === 0) return null;
|
||||
|
||||
return (
|
||||
<nav className="route-dock" aria-label="已打开页面">
|
||||
<Tabs
|
||||
type="editable-card"
|
||||
size="small"
|
||||
hideAdd
|
||||
activeKey={activeKey}
|
||||
items={tabItems}
|
||||
animated={false}
|
||||
onChange={onNavigate}
|
||||
onEdit={(targetKey, action) => {
|
||||
if (action === 'remove') closeTab(String(targetKey));
|
||||
}}
|
||||
renderTabBar={renderTabBar}
|
||||
/>
|
||||
</nav>
|
||||
);
|
||||
};
|
||||
|
||||
export default RouteDock;
|
||||
@@ -25,7 +25,7 @@ import type { ColumnsType } from 'antd/es/table';
|
||||
import {
|
||||
PlusOutlined,
|
||||
UploadOutlined,
|
||||
DeleteOutlined,
|
||||
InboxOutlined,
|
||||
EyeOutlined,
|
||||
CloseOutlined,
|
||||
FileTextOutlined,
|
||||
@@ -105,6 +105,20 @@ interface AttachmentRecord {
|
||||
fileSize: number;
|
||||
}
|
||||
|
||||
interface AttendanceRecordItem {
|
||||
id: number;
|
||||
attendanceDate: string;
|
||||
session: string;
|
||||
status: string;
|
||||
source?: string;
|
||||
remark?: string | null;
|
||||
punchTime?: string | null;
|
||||
punchDeviceName?: string | null;
|
||||
punchDeviceId?: string | null;
|
||||
schedule?: { subject?: string } | null;
|
||||
class?: { name?: string } | null;
|
||||
}
|
||||
|
||||
interface StudentProfileAggregate {
|
||||
student: StudentInfo;
|
||||
profile: ProfileData | null;
|
||||
@@ -113,6 +127,7 @@ interface StudentProfileAggregate {
|
||||
learningRecords: LearningRecord[];
|
||||
result: ResultData | null;
|
||||
attachments: AttachmentRecord[];
|
||||
attendances: AttendanceRecordItem[];
|
||||
}
|
||||
|
||||
export interface StudentProfileContentProps {
|
||||
@@ -147,6 +162,19 @@ const RECORD_TYPE_OPTIONS = [
|
||||
{ value: 'other', label: '其他' },
|
||||
];
|
||||
|
||||
const STUDENT_STATUS_MAP: Record<string, { text: string; color: string }> = {
|
||||
active: { text: '在读', color: 'green' },
|
||||
graduated: { text: '已毕业', color: 'blue' },
|
||||
withdrawn: { text: '已退训', color: 'red' },
|
||||
archived: { text: '已归档', color: '#999' },
|
||||
};
|
||||
|
||||
const ENROLLMENT_STATUS_MAP: Record<string, { text: string; color: string }> = {
|
||||
active: { text: '报读中', color: 'green' },
|
||||
completed: { text: '已结课', color: 'blue' },
|
||||
withdrawn: { text: '已退训', color: 'red' },
|
||||
};
|
||||
|
||||
const COURSE_CATEGORY_OPTIONS = [
|
||||
{ value: 'culture', label: '文化课' },
|
||||
{ value: 'professional', label: '专业课' },
|
||||
@@ -161,6 +189,36 @@ const CLASS_TYPE_OPTIONS = [
|
||||
{ value: 'offline', label: '线下' },
|
||||
];
|
||||
|
||||
const getOptionLabel = (
|
||||
options: Array<{ value: string; label: string }>,
|
||||
value?: string | null,
|
||||
): string => {
|
||||
if (!value) return '-';
|
||||
return options.find((option) => option.value === value)?.label || value;
|
||||
};
|
||||
|
||||
const getCourseCategoryLabel = (value?: string | null): string =>
|
||||
getOptionLabel(COURSE_CATEGORY_OPTIONS, value);
|
||||
|
||||
const getClassTypeLabel = (value?: string | null): string =>
|
||||
getOptionLabel(CLASS_TYPE_OPTIONS, value);
|
||||
|
||||
const getEnrollmentStatus = (value?: string | null): { text: string; color: string } => {
|
||||
if (!value) return { text: '-', color: 'default' };
|
||||
return ENROLLMENT_STATUS_MAP[value] || { text: value, color: 'default' };
|
||||
};
|
||||
|
||||
const getStudentStatus = (value?: string | null): { text: string; color: string } => {
|
||||
if (!value) return { text: '-', color: 'default' };
|
||||
return STUDENT_STATUS_MAP[value] || { text: value, color: 'default' };
|
||||
};
|
||||
|
||||
const formatEnrollmentDisplayName = (enrollment: EnrollmentRecord): string =>
|
||||
enrollment.className ||
|
||||
(enrollment.courseCategory
|
||||
? getCourseCategoryLabel(enrollment.courseCategory)
|
||||
: String(enrollment.id));
|
||||
|
||||
const ATTACHMENT_CATEGORY_OPTIONS = [
|
||||
{ value: 'id_card', label: '身份证' },
|
||||
{ value: 'transcript', label: '成绩单' },
|
||||
@@ -178,16 +236,85 @@ const formatFileSize = (bytes: number): string => {
|
||||
|
||||
// ---- Tab Components ----
|
||||
|
||||
const ATTENDANCE_STATUS_MAP: Record<string, { text: string; color: string }> = {
|
||||
present: { text: '出勤', color: 'green' },
|
||||
late: { text: '迟到', color: 'orange' },
|
||||
absent: { text: '缺勤', color: 'red' },
|
||||
leave: { text: '请假', color: 'blue' },
|
||||
pending: { text: '待确认', color: 'default' },
|
||||
};
|
||||
|
||||
const SESSION_LABELS: Record<string, string> = {
|
||||
morning_reading: '早自习',
|
||||
morning: '上午',
|
||||
afternoon: '下午',
|
||||
evening_study: '晚自习',
|
||||
night_check: '晚寝',
|
||||
};
|
||||
|
||||
const AttendanceTab: React.FC<{ data: AttendanceRecordItem[] }> = ({ data }) => {
|
||||
const columns: ColumnsType<AttendanceRecordItem> = [
|
||||
{ title: '日期', dataIndex: 'attendanceDate', width: 120 },
|
||||
{
|
||||
title: '课程',
|
||||
render: (_: unknown, record) => record.schedule?.subject || record.class?.name || '课程考勤',
|
||||
},
|
||||
{
|
||||
title: '时段',
|
||||
dataIndex: 'session',
|
||||
width: 100,
|
||||
render: (value: string) => SESSION_LABELS[value] || value || '-',
|
||||
},
|
||||
{
|
||||
title: '结果',
|
||||
dataIndex: 'status',
|
||||
width: 90,
|
||||
render: (value: string) => {
|
||||
const meta = ATTENDANCE_STATUS_MAP[value] || { text: value || '-', color: 'default' };
|
||||
return <Tag color={meta.color}>{meta.text}</Tag>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '打卡时间',
|
||||
dataIndex: 'punchTime',
|
||||
width: 170,
|
||||
render: (value?: string | null) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '-'),
|
||||
},
|
||||
{
|
||||
title: '打卡设备',
|
||||
render: (_: unknown, record) => {
|
||||
const name = record.punchDeviceName?.trim();
|
||||
const id = record.punchDeviceId?.trim();
|
||||
if (name && id && name !== id) return `${name}(${id})`;
|
||||
return name || id || (record.source === 'manual' ? '老师手动标记' : '-');
|
||||
},
|
||||
},
|
||||
{ title: '备注', dataIndex: 'remark', render: (value?: string | null) => value || '-' },
|
||||
];
|
||||
|
||||
return data.length > 0 ? (
|
||||
<Table<AttendanceRecordItem>
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
rowKey="id"
|
||||
scroll={{ x: 900 }}
|
||||
pagination={{ defaultPageSize: 15, showSizeChanger: true, pageSizeOptions: [15, 30, 50] }}
|
||||
/>
|
||||
) : (
|
||||
<Empty description="暂无出勤记录" />
|
||||
);
|
||||
};
|
||||
|
||||
interface TabProps {
|
||||
studentId: number;
|
||||
onRefresh: () => void;
|
||||
}
|
||||
|
||||
const ProfileTab: React.FC<{ data: ProfileData | null; studentId: number; onRefresh: () => void }> = ({
|
||||
data,
|
||||
studentId,
|
||||
onRefresh,
|
||||
}) => {
|
||||
const ProfileTab: React.FC<{
|
||||
data: ProfileData | null;
|
||||
studentId: number;
|
||||
onRefresh: () => void;
|
||||
}> = ({ data, studentId, onRefresh }) => {
|
||||
const [form] = Form.useForm();
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
@@ -283,8 +410,8 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
|
||||
};
|
||||
|
||||
const columns: ColumnsType<EnrollmentRecord> = [
|
||||
{ title: '课程类别', dataIndex: 'courseCategory', render: (v: string) => v || '-' },
|
||||
{ title: '班型', dataIndex: 'classType', render: (v: string) => v || '-' },
|
||||
{ title: '课程类别', dataIndex: 'courseCategory', render: getCourseCategoryLabel },
|
||||
{ title: '班型', dataIndex: 'classType', render: getClassTypeLabel },
|
||||
{ title: '班级名称', dataIndex: 'className', render: (v: string) => v || '-' },
|
||||
{ title: '班主任', dataIndex: 'headTeacher', render: (v: string) => v || '-' },
|
||||
{ title: '任课教师', dataIndex: 'subjectTeacher', render: (v: string) => v || '-' },
|
||||
@@ -294,12 +421,8 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
render: (v: string) => {
|
||||
const colorMap: Record<string, string> = {
|
||||
active: 'green',
|
||||
completed: 'blue',
|
||||
withdrawn: 'red',
|
||||
};
|
||||
return <Tag color={colorMap[v] || 'default'}>{v || '-'}</Tag>;
|
||||
const status = getEnrollmentStatus(v);
|
||||
return <Tag color={status.color}>{status.text}</Tag>;
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -335,10 +458,18 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
|
||||
confirmLoading={saving}
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="courseCategory" label="课程类别" rules={[{ required: true, message: '请选择课程类别' }]}>
|
||||
<Form.Item
|
||||
name="courseCategory"
|
||||
label="课程类别"
|
||||
rules={[{ required: true, message: '请选择课程类别' }]}
|
||||
>
|
||||
<Select options={COURSE_CATEGORY_OPTIONS} placeholder="请选择" />
|
||||
</Form.Item>
|
||||
<Form.Item name="classType" label="班型" rules={[{ required: true, message: '请选择班型' }]}>
|
||||
<Form.Item
|
||||
name="classType"
|
||||
label="班型"
|
||||
rules={[{ required: true, message: '请选择班型' }]}
|
||||
>
|
||||
<Select options={CLASS_TYPE_OPTIONS} placeholder="请选择" />
|
||||
</Form.Item>
|
||||
<Form.Item name="className" label="班级名称">
|
||||
@@ -362,12 +493,9 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
|
||||
);
|
||||
};
|
||||
|
||||
const ExamScoresTab: React.FC<TabProps & { data: ExamScoreRecord[]; enrollments: EnrollmentRecord[] }> = ({
|
||||
data,
|
||||
studentId,
|
||||
enrollments,
|
||||
onRefresh,
|
||||
}) => {
|
||||
const ExamScoresTab: React.FC<
|
||||
TabProps & { data: ExamScoreRecord[]; enrollments: EnrollmentRecord[] }
|
||||
> = ({ data, studentId, enrollments, onRefresh }) => {
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [form] = Form.useForm();
|
||||
const [saving, setSaving] = useState(false);
|
||||
@@ -401,8 +529,16 @@ const ExamScoresTab: React.FC<TabProps & { data: ExamScoreRecord[]; enrollments:
|
||||
{ title: '考试名称', dataIndex: 'examName', render: (v: string) => v || '-' },
|
||||
{ title: '科目', dataIndex: 'subject' },
|
||||
{ title: '成绩', dataIndex: 'score' },
|
||||
{ title: '班级均分', dataIndex: 'classAvg', render: (v: number | undefined) => (v !== undefined ? v : '-') },
|
||||
{ title: '排名', dataIndex: 'rank', render: (v: number | undefined) => (v !== undefined ? v : '-') },
|
||||
{
|
||||
title: '班级均分',
|
||||
dataIndex: 'classAvg',
|
||||
render: (v: number | undefined) => (v !== undefined ? v : '-'),
|
||||
},
|
||||
{
|
||||
title: '排名',
|
||||
dataIndex: 'rank',
|
||||
render: (v: number | undefined) => (v !== undefined ? v : '-'),
|
||||
},
|
||||
{ title: '考试日期', dataIndex: 'examDate', render: (v: string) => v || '-' },
|
||||
{
|
||||
title: '关联报读',
|
||||
@@ -410,7 +546,7 @@ const ExamScoresTab: React.FC<TabProps & { data: ExamScoreRecord[]; enrollments:
|
||||
render: (v: number | undefined) => {
|
||||
if (v === undefined) return '-';
|
||||
const enr = enrollments.find((e) => e.id === v);
|
||||
return enr ? `${enr.className || enr.courseCategory || v}` : String(v);
|
||||
return enr ? formatEnrollmentDisplayName(enr) : String(v);
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -446,13 +582,21 @@ const ExamScoresTab: React.FC<TabProps & { data: ExamScoreRecord[]; enrollments:
|
||||
confirmLoading={saving}
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="examType" label="考试类型" rules={[{ required: true, message: '请选择考试类型' }]}>
|
||||
<Form.Item
|
||||
name="examType"
|
||||
label="考试类型"
|
||||
rules={[{ required: true, message: '请选择考试类型' }]}
|
||||
>
|
||||
<Select options={EXAM_TYPE_OPTIONS} placeholder="请选择" />
|
||||
</Form.Item>
|
||||
<Form.Item name="examName" label="考试名称">
|
||||
<Input placeholder="如:2024第一次月考" />
|
||||
</Form.Item>
|
||||
<Form.Item name="subject" label="科目" rules={[{ required: true, message: '请输入科目' }]}>
|
||||
<Form.Item
|
||||
name="subject"
|
||||
label="科目"
|
||||
rules={[{ required: true, message: '请输入科目' }]}
|
||||
>
|
||||
<Input placeholder="如:数学" />
|
||||
</Form.Item>
|
||||
<Form.Item name="score" label="成绩" rules={[{ required: true, message: '请输入成绩' }]}>
|
||||
@@ -473,7 +617,7 @@ const ExamScoresTab: React.FC<TabProps & { data: ExamScoreRecord[]; enrollments:
|
||||
placeholder="选择关联的报读记录"
|
||||
options={enrollments.map((e) => ({
|
||||
value: e.id,
|
||||
label: `${e.className || e.courseCategory || e.id} (${e.classType})`,
|
||||
label: `${formatEnrollmentDisplayName(e)}(${getClassTypeLabel(e.classType)})`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
@@ -483,7 +627,11 @@ const ExamScoresTab: React.FC<TabProps & { data: ExamScoreRecord[]; enrollments:
|
||||
);
|
||||
};
|
||||
|
||||
const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({ data, studentId, onRefresh }) => {
|
||||
const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({
|
||||
data,
|
||||
studentId,
|
||||
onRefresh,
|
||||
}) => {
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [form] = Form.useForm();
|
||||
const [saving, setSaving] = useState(false);
|
||||
@@ -551,13 +699,25 @@ const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({ data, st
|
||||
confirmLoading={saving}
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="recordDate" label="记录日期" rules={[{ required: true, message: '请选择日期' }]}>
|
||||
<Form.Item
|
||||
name="recordDate"
|
||||
label="记录日期"
|
||||
rules={[{ required: true, message: '请选择日期' }]}
|
||||
>
|
||||
<DatePicker style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="recordType" label="记录类型" rules={[{ required: true, message: '请选择记录类型' }]}>
|
||||
<Form.Item
|
||||
name="recordType"
|
||||
label="记录类型"
|
||||
rules={[{ required: true, message: '请选择记录类型' }]}
|
||||
>
|
||||
<Select options={RECORD_TYPE_OPTIONS} placeholder="请选择" />
|
||||
</Form.Item>
|
||||
<Form.Item name="content" label="内容" rules={[{ required: true, message: '请输入内容' }]}>
|
||||
<Form.Item
|
||||
name="content"
|
||||
label="内容"
|
||||
rules={[{ required: true, message: '请输入内容' }]}
|
||||
>
|
||||
<Input.TextArea rows={4} placeholder="请记录学情内容" />
|
||||
</Form.Item>
|
||||
<Form.Item name="followUpMethod" label="跟进方式">
|
||||
@@ -572,7 +732,11 @@ const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({ data, st
|
||||
);
|
||||
};
|
||||
|
||||
const ResultTab: React.FC<TabProps & { data: ResultData | null }> = ({ data, studentId, onRefresh }) => {
|
||||
const ResultTab: React.FC<TabProps & { data: ResultData | null }> = ({
|
||||
data,
|
||||
studentId,
|
||||
onRefresh,
|
||||
}) => {
|
||||
const [form] = Form.useForm();
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
@@ -637,17 +801,21 @@ const ResultTab: React.FC<TabProps & { data: ResultData | null }> = ({ data, stu
|
||||
);
|
||||
};
|
||||
|
||||
const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({ data, studentId, onRefresh }) => {
|
||||
const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({
|
||||
data,
|
||||
studentId,
|
||||
onRefresh,
|
||||
}) => {
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
const handleDelete = async (attachmentId: number) => {
|
||||
try {
|
||||
await api.delete(`/archive/attachments/${attachmentId}`);
|
||||
message.success('已删除');
|
||||
message.success('已归档');
|
||||
onRefresh();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
message.error(err?.message || '删除失败');
|
||||
message.error(err?.message || '归档失败');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -682,9 +850,9 @@ const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({ dat
|
||||
>
|
||||
查看
|
||||
</Button>
|
||||
<Popconfirm title="确定删除该附件?" onConfirm={() => handleDelete(record.id)}>
|
||||
<Button size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
<Popconfirm title="确定归档该附件?" onConfirm={() => handleDelete(record.id)}>
|
||||
<Button size="small" danger icon={<InboxOutlined />}>
|
||||
归档
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
@@ -698,7 +866,12 @@ const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({ dat
|
||||
showUploadList={false}
|
||||
customRequest={async (options) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', options.file instanceof File ? options.file : new File([options.file as Blob], 'attachment'));
|
||||
formData.append(
|
||||
'file',
|
||||
options.file instanceof File
|
||||
? options.file
|
||||
: new File([options.file as Blob], 'attachment'),
|
||||
);
|
||||
setUploading(true);
|
||||
try {
|
||||
await api.post(`/archive/${studentId}/attachments`, formData, {
|
||||
@@ -779,63 +952,60 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
|
||||
|
||||
const tabItems = useMemo(() => {
|
||||
if (!aggregateData) return [];
|
||||
const { profile, enrollments, examScores, learningRecords, result, attachments } = aggregateData;
|
||||
const { profile, enrollments, examScores, learningRecords, result, attachments, attendances } =
|
||||
aggregateData;
|
||||
return [
|
||||
{
|
||||
key: 'profile',
|
||||
label: '扩展档案',
|
||||
children: <ProfileTab data={profile} studentId={studentId} onRefresh={fetchData} />,
|
||||
},
|
||||
{
|
||||
key: 'enrollments',
|
||||
label: `报读班型 (${enrollments.length})`,
|
||||
children: (
|
||||
<EnrollmentsTab data={enrollments} studentId={studentId} onRefresh={fetchData} />
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'exams',
|
||||
label: `考试成绩 (${examScores.length})`,
|
||||
children: (
|
||||
<ExamScoresTab
|
||||
data={examScores}
|
||||
studentId={studentId}
|
||||
enrollments={enrollments}
|
||||
onRefresh={fetchData}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'attendance',
|
||||
label: '出勤记录',
|
||||
children: <Empty description="暂无出勤记录" />,
|
||||
},
|
||||
{
|
||||
key: 'learning',
|
||||
label: `课堂回访 (${learningRecords.length})`,
|
||||
children: (
|
||||
<LearningTab data={learningRecords} studentId={studentId} onRefresh={fetchData} />
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'result',
|
||||
label: '录取归档',
|
||||
children: <ResultTab data={result} studentId={studentId} onRefresh={fetchData} />,
|
||||
},
|
||||
{
|
||||
key: 'attachments',
|
||||
label: `附件 (${attachments.length})`,
|
||||
children: (
|
||||
<AttachmentsTab data={attachments} studentId={studentId} onRefresh={fetchData} />
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'reports',
|
||||
label: '报告版本',
|
||||
children: <Empty description="暂无报告版本" />,
|
||||
},
|
||||
];
|
||||
}, [aggregateData, studentId, fetchData]);
|
||||
{
|
||||
key: 'profile',
|
||||
label: '扩展档案',
|
||||
children: <ProfileTab data={profile} studentId={studentId} onRefresh={fetchData} />,
|
||||
},
|
||||
{
|
||||
key: 'enrollments',
|
||||
label: `报读班型 (${enrollments.length})`,
|
||||
children: <EnrollmentsTab data={enrollments} studentId={studentId} onRefresh={fetchData} />,
|
||||
},
|
||||
{
|
||||
key: 'exams',
|
||||
label: `考试成绩 (${examScores.length})`,
|
||||
children: (
|
||||
<ExamScoresTab
|
||||
data={examScores}
|
||||
studentId={studentId}
|
||||
enrollments={enrollments}
|
||||
onRefresh={fetchData}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'attendance',
|
||||
label: `出勤记录 (${attendances.length})`,
|
||||
children: <AttendanceTab data={attendances} />,
|
||||
},
|
||||
{
|
||||
key: 'learning',
|
||||
label: `课堂回访 (${learningRecords.length})`,
|
||||
children: (
|
||||
<LearningTab data={learningRecords} studentId={studentId} onRefresh={fetchData} />
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'result',
|
||||
label: '录取归档',
|
||||
children: <ResultTab data={result} studentId={studentId} onRefresh={fetchData} />,
|
||||
},
|
||||
{
|
||||
key: 'attachments',
|
||||
label: `附件 (${attachments.length})`,
|
||||
children: <AttachmentsTab data={attachments} studentId={studentId} onRefresh={fetchData} />,
|
||||
},
|
||||
{
|
||||
key: 'reports',
|
||||
label: '报告版本',
|
||||
children: <Empty description="暂无报告版本" />,
|
||||
},
|
||||
];
|
||||
}, [aggregateData, studentId, fetchData]);
|
||||
|
||||
if (!aggregateData) {
|
||||
if (loading) {
|
||||
@@ -896,7 +1066,9 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
|
||||
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
|
||||
</a>
|
||||
</span>
|
||||
) : '-'}
|
||||
) : (
|
||||
'-'
|
||||
)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="身份证号">
|
||||
{student.idNumber ? (
|
||||
@@ -906,10 +1078,15 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
|
||||
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
|
||||
</a>
|
||||
</span>
|
||||
) : '-'}
|
||||
) : (
|
||||
'-'
|
||||
)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">
|
||||
<Tag>{student.status || '-'}</Tag>
|
||||
{(() => {
|
||||
const status = getStudentStatus(student.status);
|
||||
return <Tag color={status.color}>{status.text}</Tag>;
|
||||
})()}
|
||||
</Descriptions.Item>
|
||||
{profile?.targetCollege && (
|
||||
<Descriptions.Item label="目标院校">{profile.targetCollege}</Descriptions.Item>
|
||||
@@ -917,18 +1094,13 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
|
||||
{profile?.targetMajor && (
|
||||
<Descriptions.Item label="目标专业">{profile.targetMajor}</Descriptions.Item>
|
||||
)}
|
||||
{profile?.grade && (
|
||||
<Descriptions.Item label="年级">{profile.grade}</Descriptions.Item>
|
||||
)}
|
||||
{profile?.grade && <Descriptions.Item label="年级">{profile.grade}</Descriptions.Item>}
|
||||
{profile?.subjectDirection && (
|
||||
<Descriptions.Item label="选科方向">{profile.subjectDirection}</Descriptions.Item>
|
||||
)}
|
||||
</Descriptions>
|
||||
|
||||
<Tabs
|
||||
defaultActiveKey="profile"
|
||||
items={tabItems}
|
||||
/>
|
||||
<Tabs defaultActiveKey="profile" items={tabItems} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -4,7 +4,15 @@
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html {
|
||||
min-width: 320px;
|
||||
background: #f5f5f7;
|
||||
}
|
||||
|
||||
body {
|
||||
min-width: 320px;
|
||||
overflow-x: hidden;
|
||||
background: #f5f5f7;
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
@@ -15,10 +23,159 @@ body {
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
/* === 通用:表格容器横向滚动(防双重滚动条) === */
|
||||
img,
|
||||
svg,
|
||||
canvas {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.app-shell,
|
||||
.app-main,
|
||||
.app-content {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.app-sidebar {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.app-content > * {
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.ant-card,
|
||||
.ant-card-body,
|
||||
.ant-tabs,
|
||||
.ant-tabs-content-holder,
|
||||
.ant-tabs-content,
|
||||
.ant-tabs-tabpane {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.app-header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.route-dock {
|
||||
position: sticky;
|
||||
top: 64px;
|
||||
z-index: 90;
|
||||
min-width: 0;
|
||||
height: 44px;
|
||||
padding: 6px 12px;
|
||||
overflow: hidden;
|
||||
background: #f5f5f7;
|
||||
border-bottom: 1px solid #e5e5e7;
|
||||
}
|
||||
|
||||
.route-dock .ant-tabs {
|
||||
height: 32px;
|
||||
}
|
||||
|
||||
.route-dock .ant-tabs-nav {
|
||||
height: 32px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.route-dock .ant-tabs-nav::before {
|
||||
border-bottom: 0;
|
||||
}
|
||||
|
||||
.route-dock .ant-tabs-tab {
|
||||
min-width: 112px;
|
||||
max-width: 220px;
|
||||
height: 32px;
|
||||
margin: 0 6px 0 0 !important;
|
||||
padding: 0 10px 0 12px !important;
|
||||
overflow: hidden;
|
||||
background: rgba(255, 255, 255, 0.58) !important;
|
||||
border: 1px solid transparent !important;
|
||||
border-radius: 7px !important;
|
||||
transition:
|
||||
background-color 160ms ease,
|
||||
border-color 160ms ease,
|
||||
box-shadow 160ms ease !important;
|
||||
}
|
||||
|
||||
.route-dock .ant-tabs-tab:hover {
|
||||
background: rgba(255, 255, 255, 0.9) !important;
|
||||
border-color: #dedee2 !important;
|
||||
}
|
||||
|
||||
.route-dock .ant-tabs-tab-active {
|
||||
background: #fff !important;
|
||||
border-color: #d8d8dc !important;
|
||||
box-shadow:
|
||||
inset 0 2px 0 #1677ff,
|
||||
0 2px 7px rgba(29, 29, 31, 0.08);
|
||||
}
|
||||
|
||||
.route-dock .ant-tabs-tab-btn {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
color: #4d4d4d;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.route-dock .ant-tabs-tab-remove {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 0 0 auto;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
margin-left: 8px;
|
||||
border-radius: 50%;
|
||||
transition: background-color 140ms ease;
|
||||
}
|
||||
|
||||
.route-dock .ant-tabs-tab-remove:hover {
|
||||
background: #ededf0;
|
||||
}
|
||||
|
||||
.route-dock .ant-tabs-content-holder {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Shared responsive toolbar: add these classes to page filter/action rows. */
|
||||
.responsive-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.responsive-toolbar__group {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.ant-drawer-content-wrapper {
|
||||
max-width: 100vw !important;
|
||||
}
|
||||
|
||||
.ant-pagination {
|
||||
row-gap: 8px;
|
||||
}
|
||||
|
||||
/* Data tables own their horizontal scroll instead of widening the page. */
|
||||
.ant-table-wrapper {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.ant-table-wrapper .ant-table-container {
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
overscroll-behavior-inline: contain;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
/* ── 表格单元格省略号截断(按需启用) ──
|
||||
@@ -54,6 +211,75 @@ body {
|
||||
|
||||
/* === 手机 (< 576px) === */
|
||||
@media (max-width: 575px) {
|
||||
.app-header {
|
||||
height: 56px;
|
||||
padding-inline: 8px !important;
|
||||
line-height: 56px;
|
||||
}
|
||||
|
||||
.route-dock {
|
||||
top: 56px;
|
||||
height: 42px;
|
||||
padding: 5px 8px;
|
||||
}
|
||||
|
||||
.route-dock .ant-tabs-tab {
|
||||
min-width: 104px;
|
||||
}
|
||||
|
||||
.app-header .ant-btn {
|
||||
width: 40px;
|
||||
min-height: 40px;
|
||||
padding-inline: 0;
|
||||
}
|
||||
|
||||
.app-content {
|
||||
min-height: calc(100dvh - 72px);
|
||||
margin: 8px !important;
|
||||
padding: 12px !important;
|
||||
border-radius: 10px !important;
|
||||
}
|
||||
|
||||
.app-navigation-drawer .ant-drawer-header {
|
||||
padding-inline: 16px;
|
||||
}
|
||||
|
||||
.responsive-toolbar {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.responsive-toolbar__group,
|
||||
.responsive-toolbar > .ant-space {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.responsive-toolbar__group > .ant-space-item,
|
||||
.responsive-toolbar > .ant-space > .ant-space-item {
|
||||
flex: 1 1 140px;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.responsive-toolbar .ant-input,
|
||||
.responsive-toolbar .ant-input-affix-wrapper,
|
||||
.responsive-toolbar .ant-input-search,
|
||||
.responsive-toolbar .ant-picker,
|
||||
.responsive-toolbar .ant-select,
|
||||
.responsive-toolbar .ant-upload,
|
||||
.responsive-toolbar .ant-upload-wrapper,
|
||||
.responsive-toolbar .ant-btn {
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
.ant-btn:not(.ant-btn-sm),
|
||||
.ant-input-affix-wrapper,
|
||||
.ant-input-search-button,
|
||||
.ant-picker,
|
||||
.ant-select-single .ant-select-selector {
|
||||
min-height: 40px;
|
||||
}
|
||||
|
||||
.ant-table {
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -65,12 +291,48 @@ body {
|
||||
font-size: 13px;
|
||||
}
|
||||
.ant-modal {
|
||||
max-width: calc(100vw - 24px) !important;
|
||||
margin: 12px auto !important;
|
||||
top: 12px;
|
||||
max-width: calc(100vw - 16px) !important;
|
||||
margin: 0 auto !important;
|
||||
padding-bottom: 12px;
|
||||
}
|
||||
.ant-modal .ant-modal-content {
|
||||
padding: 16px;
|
||||
}
|
||||
.ant-modal .ant-modal-body {
|
||||
max-height: 60vh;
|
||||
max-height: calc(100dvh - 180px);
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
.ant-modal .ant-modal-footer {
|
||||
display: flex;
|
||||
}
|
||||
.ant-modal .ant-modal-footer .ant-btn {
|
||||
flex: 1;
|
||||
min-height: 40px;
|
||||
}
|
||||
.ant-drawer .ant-drawer-header {
|
||||
padding: 14px 16px;
|
||||
}
|
||||
.ant-drawer .ant-drawer-body {
|
||||
padding: 16px;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
.ant-popover,
|
||||
.ant-picker-dropdown {
|
||||
max-width: calc(100vw - 16px);
|
||||
}
|
||||
.ant-pagination {
|
||||
justify-content: center;
|
||||
}
|
||||
.ant-pagination .ant-pagination-options {
|
||||
margin-inline-start: 0;
|
||||
}
|
||||
.ant-alert {
|
||||
padding: 10px 12px;
|
||||
}
|
||||
h1 {
|
||||
font-size: 22px !important;
|
||||
}
|
||||
h2 {
|
||||
font-size: 18px !important;
|
||||
@@ -78,9 +340,48 @@ body {
|
||||
.ant-card {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.ant-space-item .ant-btn {
|
||||
padding: 2px 6px;
|
||||
font-size: 12px;
|
||||
.ant-card .ant-card-body {
|
||||
padding: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 575px) {
|
||||
.ant-card-head {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding-block: 12px;
|
||||
}
|
||||
|
||||
.ant-card-head-wrapper {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.ant-card-extra {
|
||||
max-width: 100%;
|
||||
margin-inline-start: 0;
|
||||
}
|
||||
|
||||
.ant-card-extra > .ant-space {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.ant-form-item-control,
|
||||
.ant-form-item-control-input,
|
||||
.ant-form-item-control-input-content,
|
||||
.ant-picker-range {
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.ant-statistic-content {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
}
|
||||
@media (max-width: 991px) {
|
||||
.app-content {
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,3 +391,82 @@ body {
|
||||
max-width: calc(100vw - 48px) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.notifications-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.notifications-filter {
|
||||
width: 100%;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
@media (max-width: 575px) {
|
||||
.notifications-layout,
|
||||
.notifications-content {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.notifications-header {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.notifications-content .ant-list-item {
|
||||
align-items: flex-start;
|
||||
padding: 14px 6px !important;
|
||||
}
|
||||
|
||||
.notifications-content .ant-list-item-meta-avatar {
|
||||
margin-inline-end: 10px;
|
||||
}
|
||||
|
||||
.notifications-content .ant-list-item-meta-title {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 575px) {
|
||||
.ant-table-wrapper::before {
|
||||
content: '表格可左右滑动查看';
|
||||
display: block;
|
||||
margin-bottom: 6px;
|
||||
color: #8c8c8c;
|
||||
font-size: 11px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.ant-table-wrapper .ant-table-content {
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.ant-table-wrapper .ant-table-cell-fix-left,
|
||||
.ant-table-wrapper .ant-table-cell-fix-right {
|
||||
box-shadow: 2px 0 5px rgb(0 0 0 / 5%);
|
||||
}
|
||||
}
|
||||
|
||||
.responsive-toolbar--single {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
@media (max-width: 575px) {
|
||||
/* Input.Search is an internal compact group. Keep the text field flexible and
|
||||
the search icon button fixed instead of applying toolbar full-width rules
|
||||
to both children. */
|
||||
.responsive-toolbar .ant-input-search > .ant-input-affix-wrapper {
|
||||
flex: 1 1 auto;
|
||||
width: auto !important;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.responsive-toolbar .ant-input-search > .ant-input-search-btn {
|
||||
flex: 0 0 40px;
|
||||
width: 40px !important;
|
||||
min-width: 40px;
|
||||
padding-inline: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ import { usePermission } from '../hooks/usePermission';
|
||||
import api from '../api';
|
||||
import { writePermissions } from '../auth/permission-store';
|
||||
import NotificationBell from '../components/NotificationBell';
|
||||
import RouteDock from '../components/RouteDock';
|
||||
import { buildMenu, type AppMenuItem } from '../auth/menu-policy';
|
||||
|
||||
const { Header, Sider, Content } = Layout;
|
||||
@@ -51,6 +52,7 @@ const iconMap: Record<string, React.ReactNode> = {
|
||||
expense: <DollarOutlined />,
|
||||
bill: <FileTextOutlined />,
|
||||
deposit: <WalletOutlined />,
|
||||
wallet: <WalletOutlined />,
|
||||
classroom: <ReadOutlined />,
|
||||
rental: <FileProtectOutlined />,
|
||||
organization: <TagsOutlined />,
|
||||
@@ -78,7 +80,10 @@ const MainLayout: React.FC = () => {
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
api.get<{ id: number; username: string; permissions: string[]; roles?: string[] }>('/auth/profile')
|
||||
api
|
||||
.get<{ id: number; username: string; permissions: string[]; roles?: string[] }>(
|
||||
'/auth/profile',
|
||||
)
|
||||
.then((profile) => {
|
||||
if (cancelled) return;
|
||||
writePermissions(profile.permissions || []);
|
||||
@@ -90,13 +95,16 @@ const MainLayout: React.FC = () => {
|
||||
.catch(() => {
|
||||
// The API interceptor handles expired/invalid sessions.
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const screens = Grid.useBreakpoint();
|
||||
const isMobile = !screens.sm; // < 576px (仅 xs)
|
||||
const isMobile = !screens.sm; // < 576px (仅 xs)
|
||||
const isTablet = (screens.sm || screens.md) && !screens.lg; // 576-991px
|
||||
const isDesktop = !!screens.lg; // >= 992px
|
||||
const isDesktop = !!screens.lg; // >= 992px
|
||||
const usesDrawer = !isDesktop;
|
||||
|
||||
const menuItems = useMemo(
|
||||
() => buildMenu(user.roles ?? [], permissions),
|
||||
@@ -110,10 +118,13 @@ const MainLayout: React.FC = () => {
|
||||
navigate('/login');
|
||||
}, [navigate]);
|
||||
|
||||
const handleMenuClick = useCallback((key: string) => {
|
||||
navigate(key);
|
||||
if (isMobile) setDrawerOpen(false);
|
||||
}, [navigate, isMobile]);
|
||||
const handleMenuClick = useCallback(
|
||||
(key: string) => {
|
||||
navigate(key);
|
||||
if (usesDrawer) setDrawerOpen(false);
|
||||
},
|
||||
[navigate, usesDrawer],
|
||||
);
|
||||
|
||||
const findSelectedKeys = (items: AppMenuItem[], pathname: string): string[] => {
|
||||
for (const item of items) {
|
||||
@@ -129,7 +140,12 @@ const MainLayout: React.FC = () => {
|
||||
const findOpenKeys = (items: AppMenuItem[], pathname: string): string[] => {
|
||||
for (const item of items) {
|
||||
if (item.children) {
|
||||
if (item.children.some((c) => c.key === pathname || (c.children && c.children.some((gc) => gc.key === pathname)))) {
|
||||
if (
|
||||
item.children.some(
|
||||
(c) =>
|
||||
c.key === pathname || (c.children && c.children.some((gc) => gc.key === pathname)),
|
||||
)
|
||||
) {
|
||||
return [item.key];
|
||||
}
|
||||
}
|
||||
@@ -137,23 +153,23 @@ const MainLayout: React.FC = () => {
|
||||
return [];
|
||||
};
|
||||
|
||||
const selectedKeys = useMemo(() => findSelectedKeys(menuItems, location.pathname), [menuItems, location.pathname]);
|
||||
const selectedKeys = useMemo(
|
||||
() => findSelectedKeys(menuItems, location.pathname),
|
||||
[menuItems, location.pathname],
|
||||
);
|
||||
// 路径变化时同步展开的菜单(不干扰用户手动展开/收起)
|
||||
useEffect(() => {
|
||||
if (location.pathname !== prevPathname.current) {
|
||||
prevPathname.current = location.pathname;
|
||||
setOpenKeys(findOpenKeys(menuItems, location.pathname));
|
||||
const routeOpenKeys = findOpenKeys(menuItems, location.pathname);
|
||||
setOpenKeys((currentKeys) => [...new Set([...currentKeys, ...routeOpenKeys])]);
|
||||
}
|
||||
}, [location.pathname, menuItems]);
|
||||
|
||||
const handleOpenChange = useCallback((keys: string[]) => {
|
||||
// 只保留最新打开的一个子菜单
|
||||
const latestKey = keys[keys.length - 1];
|
||||
setOpenKeys(latestKey ? [latestKey] : []);
|
||||
setOpenKeys(keys);
|
||||
}, []);
|
||||
|
||||
|
||||
|
||||
const transformToMenuItems = (items: AppMenuItem[]): any[] => {
|
||||
return items.map((item) => ({
|
||||
key: item.key,
|
||||
@@ -162,27 +178,31 @@ const MainLayout: React.FC = () => {
|
||||
children: item.children ? transformToMenuItems(item.children) : undefined,
|
||||
}));
|
||||
};
|
||||
const menuContent = useMemo(() => (
|
||||
<Menu
|
||||
theme="light"
|
||||
mode="inline"
|
||||
selectedKeys={selectedKeys}
|
||||
openKeys={openKeys}
|
||||
onOpenChange={handleOpenChange}
|
||||
items={transformToMenuItems(menuItems)}
|
||||
onClick={({ key }) => handleMenuClick(key)}
|
||||
style={{ border: 'none' }}
|
||||
/>
|
||||
), [selectedKeys, openKeys, menuItems, handleMenuClick]);
|
||||
const menuContent = useMemo(
|
||||
() => (
|
||||
<Menu
|
||||
theme="light"
|
||||
mode="inline"
|
||||
selectedKeys={selectedKeys}
|
||||
openKeys={openKeys}
|
||||
onOpenChange={handleOpenChange}
|
||||
items={transformToMenuItems(menuItems)}
|
||||
onClick={({ key }) => handleMenuClick(key)}
|
||||
style={{ border: 'none' }}
|
||||
/>
|
||||
),
|
||||
[selectedKeys, openKeys, menuItems, handleMenuClick],
|
||||
);
|
||||
|
||||
return (
|
||||
<Layout style={{ minHeight: '100vh' }}>
|
||||
{!isMobile && (
|
||||
<Layout className="app-shell" style={{ minHeight: '100vh' }}>
|
||||
{isDesktop && (
|
||||
<Sider
|
||||
trigger={null}
|
||||
collapsible
|
||||
collapsed={isTablet ? true : collapsed}
|
||||
collapsed={collapsed}
|
||||
theme="light"
|
||||
className="app-sidebar"
|
||||
style={{ background: '#fff', borderRight: '1px solid #e5e5e7' }}
|
||||
>
|
||||
<div
|
||||
@@ -192,30 +212,32 @@ const MainLayout: React.FC = () => {
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
color: '#1d1d1f',
|
||||
fontSize: (isTablet || collapsed) ? 16 : 17,
|
||||
fontSize: collapsed ? 16 : 17,
|
||||
fontWeight: 600,
|
||||
borderBottom: '1px solid #e5e5e7',
|
||||
}}
|
||||
>
|
||||
{(isTablet || collapsed) ? '恭' : '恭学教育基地'}
|
||||
{collapsed ? '恭' : '恭学教育基地'}
|
||||
</div>
|
||||
{menuContent}
|
||||
</Sider>
|
||||
)}
|
||||
{isMobile && (
|
||||
{usesDrawer && (
|
||||
<Drawer
|
||||
placement="left"
|
||||
open={drawerOpen}
|
||||
onClose={() => setDrawerOpen(false)}
|
||||
size={240}
|
||||
styles={{ body: { padding: 0 } }}
|
||||
className="app-navigation-drawer"
|
||||
title="恭学教育基地"
|
||||
>
|
||||
{menuContent}
|
||||
</Drawer>
|
||||
)}
|
||||
<Layout style={{ background: '#f5f5f7' }}>
|
||||
<Layout className="app-main" style={{ background: '#f5f5f7' }}>
|
||||
<Header
|
||||
className="app-header"
|
||||
style={{
|
||||
padding: '0 16px',
|
||||
background: '#fff',
|
||||
@@ -228,9 +250,9 @@ const MainLayout: React.FC = () => {
|
||||
>
|
||||
<Button
|
||||
type="text"
|
||||
aria-label={isMobile || isTablet ? '打开菜单' : collapsed ? '展开侧边栏' : '收起侧边栏'}
|
||||
aria-label={usesDrawer ? '打开菜单' : collapsed ? '展开侧边栏' : '收起侧边栏'}
|
||||
icon={
|
||||
isMobile || isTablet ? (
|
||||
usesDrawer ? (
|
||||
<MenuUnfoldOutlined />
|
||||
) : collapsed ? (
|
||||
<MenuUnfoldOutlined />
|
||||
@@ -238,7 +260,7 @@ const MainLayout: React.FC = () => {
|
||||
<MenuFoldOutlined />
|
||||
)
|
||||
}
|
||||
onClick={() => (isMobile || isTablet ? setDrawerOpen(true) : setCollapsed(!collapsed))}
|
||||
onClick={() => (usesDrawer ? setDrawerOpen(true) : setCollapsed(!collapsed))}
|
||||
/>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
|
||||
{hasPermission('notification:view') && <NotificationBell />}
|
||||
@@ -266,9 +288,16 @@ const MainLayout: React.FC = () => {
|
||||
</Dropdown>
|
||||
</div>
|
||||
</Header>
|
||||
<RouteDock
|
||||
location={location}
|
||||
menuItems={menuItems}
|
||||
onNavigate={navigate}
|
||||
draggable={isDesktop}
|
||||
/>
|
||||
<Content
|
||||
className="app-content"
|
||||
style={{
|
||||
margin: isMobile ? 12 : isTablet ? 16 : 24,
|
||||
margin: isMobile ? 8 : isTablet ? 16 : 24,
|
||||
padding: isMobile ? 12 : isTablet ? 16 : 24,
|
||||
background: '#fff',
|
||||
borderRadius: 12,
|
||||
|
||||
@@ -17,11 +17,7 @@ describe('AiConfig helpers', () => {
|
||||
});
|
||||
|
||||
it('swaps when current baseUrl matches previous provider default', () => {
|
||||
const result = shouldAutoSwapBaseUrl(
|
||||
'DEEPSEEK',
|
||||
'https://api.openai.com/v1',
|
||||
'OPENAI',
|
||||
);
|
||||
const result = shouldAutoSwapBaseUrl('DEEPSEEK', 'https://api.openai.com/v1', 'OPENAI');
|
||||
expect(result.shouldSwap).toBe(true);
|
||||
expect(result.baseUrl).toBe(PROVIDER_DEFAULTS.DEEPSEEK);
|
||||
});
|
||||
@@ -32,11 +28,7 @@ describe('AiConfig helpers', () => {
|
||||
});
|
||||
|
||||
it('keeps custom baseUrl unchanged', () => {
|
||||
const result = shouldAutoSwapBaseUrl(
|
||||
'OPENAI',
|
||||
'https://custom.api.com/v1',
|
||||
'DEEPSEEK',
|
||||
);
|
||||
const result = shouldAutoSwapBaseUrl('OPENAI', 'https://custom.api.com/v1', 'DEEPSEEK');
|
||||
expect(result.shouldSwap).toBe(false);
|
||||
expect(result.baseUrl).toBe('https://custom.api.com/v1');
|
||||
});
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
CheckCircleOutlined,
|
||||
CloseCircleOutlined,
|
||||
KeyOutlined,
|
||||
DeleteOutlined,
|
||||
WarningOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import api from '../../api';
|
||||
@@ -418,7 +417,7 @@ const AiConfigPage: React.FC = () => {
|
||||
|
||||
{config?.hasDatabaseKey && canWrite && (
|
||||
<div style={{ marginBottom: 8 }}>
|
||||
<Button danger size="small" icon={<DeleteOutlined />} onClick={handleClearKey}>
|
||||
<Button danger size="small" onClick={handleClearKey}>
|
||||
清除服务器保存密钥
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
canPullAttendance,
|
||||
filterLessonAttendanceRecords,
|
||||
getAttendanceExperience,
|
||||
getPunchDisplayInfo,
|
||||
getSchedulePhase,
|
||||
summarizeAttendance,
|
||||
summarizeLessonCheckins,
|
||||
@@ -65,3 +67,60 @@ describe('lesson check-in summary', () => {
|
||||
).toEqual({ total: 4, checkedIn: 2, notCheckedIn: 2 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('lesson attendance filters', () => {
|
||||
const records = [
|
||||
{ id: 1, student: { name: '张三' }, status: 'present' },
|
||||
{ id: 2, student: { name: '李四' }, status: 'late' },
|
||||
{ id: 3, student: { name: '王五' }, status: 'pending' },
|
||||
{ id: 4, student: { name: '赵六' }, status: 'absent' },
|
||||
];
|
||||
|
||||
it('searches students by name and ignores surrounding whitespace', () => {
|
||||
expect(filterLessonAttendanceRecords(records, ' 张 ', 'all').map((item) => item.id)).toEqual([
|
||||
1,
|
||||
]);
|
||||
});
|
||||
|
||||
it('groups present and late as checked in', () => {
|
||||
expect(filterLessonAttendanceRecords(records, '', 'checked_in').map((item) => item.id)).toEqual(
|
||||
[1, 2],
|
||||
);
|
||||
});
|
||||
|
||||
it('groups pending and absent as not checked in and combines with search', () => {
|
||||
expect(
|
||||
filterLessonAttendanceRecords(records, '王', 'not_checked_in').map((item) => item.id),
|
||||
).toEqual([3]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('lesson punch device display', () => {
|
||||
it('labels attendance machine punches with the machine name and id', () => {
|
||||
expect(
|
||||
getPunchDisplayInfo({
|
||||
status: 'present',
|
||||
source: 'dingtalk',
|
||||
punchSource: 'ATM',
|
||||
punchDeviceName: '东门考勤机',
|
||||
punchDeviceId: 'ATM-01',
|
||||
punchTime: '2026-07-11T00:55:00.000Z',
|
||||
}),
|
||||
).toEqual({
|
||||
label: '考勤机打卡',
|
||||
machine: true,
|
||||
detail: '东门考勤机(ATM-01)',
|
||||
time: '2026-07-11T00:55:00.000Z',
|
||||
});
|
||||
});
|
||||
|
||||
it('distinguishes mobile punches and manual teacher markings', () => {
|
||||
expect(
|
||||
getPunchDisplayInfo({ status: 'present', source: 'dingtalk', punchSource: 'USER' }),
|
||||
).toEqual({ label: '手机打卡', machine: false, detail: undefined, time: undefined });
|
||||
expect(getPunchDisplayInfo({ status: 'present', source: 'manual' })).toEqual({
|
||||
label: '老师手动标记',
|
||||
machine: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,11 +8,7 @@ export function getAttendanceExperience(
|
||||
roles: readonly string[],
|
||||
): AttendanceExperience {
|
||||
const domains = getRoleDomains(roles, permissions);
|
||||
if (
|
||||
permissions.includes('attendance:manage') ||
|
||||
domains.has('academic') ||
|
||||
domains.has('super')
|
||||
) {
|
||||
if (permissions.includes('attendance:edit') || domains.has('academic') || domains.has('super')) {
|
||||
return 'admin';
|
||||
}
|
||||
return 'teacher';
|
||||
@@ -82,3 +78,79 @@ export function summarizeLessonCheckins(
|
||||
notCheckedIn: records.length - checkedIn,
|
||||
};
|
||||
}
|
||||
|
||||
export type LessonAttendanceFilter = 'all' | 'checked_in' | 'not_checked_in';
|
||||
|
||||
export interface LessonAttendanceFilterRecord {
|
||||
student: { name: string };
|
||||
status: string;
|
||||
}
|
||||
|
||||
export function filterLessonAttendanceRecords<T extends LessonAttendanceFilterRecord>(
|
||||
records: readonly T[],
|
||||
keyword: string,
|
||||
filter: LessonAttendanceFilter,
|
||||
): T[] {
|
||||
const normalizedKeyword = keyword.trim().toLocaleLowerCase('zh-CN');
|
||||
return records.filter((record) => {
|
||||
const matchesKeyword =
|
||||
!normalizedKeyword ||
|
||||
record.student.name.toLocaleLowerCase('zh-CN').includes(normalizedKeyword);
|
||||
if (!matchesKeyword || filter === 'all') return matchesKeyword;
|
||||
|
||||
const checkedIn = record.status === 'present' || record.status === 'late';
|
||||
return filter === 'checked_in' ? checkedIn : !checkedIn;
|
||||
});
|
||||
}
|
||||
|
||||
export interface PunchDisplayRecord {
|
||||
status: string;
|
||||
source?: string;
|
||||
punchTime?: string | null;
|
||||
punchSource?: string | null;
|
||||
punchDeviceName?: string | null;
|
||||
punchDeviceId?: string | null;
|
||||
}
|
||||
|
||||
export interface PunchDisplayInfo {
|
||||
label: string;
|
||||
machine: boolean;
|
||||
detail?: string;
|
||||
time?: string;
|
||||
}
|
||||
|
||||
export function getPunchDisplayInfo(record: PunchDisplayRecord): PunchDisplayInfo | null {
|
||||
if (record.status !== 'present' && record.status !== 'late') return null;
|
||||
if (record.source === 'manual') return { label: '老师手动标记', machine: false };
|
||||
|
||||
const source = (record.punchSource || '').trim().toUpperCase();
|
||||
const machine = ['ATM', 'ATTENDANCE_MACHINE', 'MACHINE', 'DEVICE'].some(
|
||||
(value) => source === value || source.includes(value),
|
||||
);
|
||||
const label = machine
|
||||
? '考勤机打卡'
|
||||
: source === 'USER'
|
||||
? '手机打卡'
|
||||
: source.includes('BEACON') || source.includes('BLE')
|
||||
? '蓝牙打卡'
|
||||
: source.includes('WIFI')
|
||||
? 'Wi-Fi 打卡'
|
||||
: source.includes('APPROVE')
|
||||
? '审批补卡'
|
||||
: source
|
||||
? `其他打卡(${record.punchSource})`
|
||||
: '打卡来源未知';
|
||||
const device = record.punchDeviceName?.trim();
|
||||
const deviceId = record.punchDeviceId?.trim();
|
||||
const detail = device
|
||||
? deviceId && deviceId !== device
|
||||
? `${device}(${deviceId})`
|
||||
: device
|
||||
: deviceId || undefined;
|
||||
return {
|
||||
label,
|
||||
machine,
|
||||
detail,
|
||||
time: record.punchTime || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
281
apps/admin/src/pages/AttendanceDevices.tsx
Normal file
281
apps/admin/src/pages/AttendanceDevices.tsx
Normal file
@@ -0,0 +1,281 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { Empty, Form, Input, Modal, Popconfirm, Select, Space, Table, Tag } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { PlusOutlined } from '@ant-design/icons';
|
||||
import api from '../api';
|
||||
import PermissionButton from '../components/PermissionButton';
|
||||
import { message } from '../ui/app-message';
|
||||
|
||||
interface ClassroomOption {
|
||||
id: number;
|
||||
name: string;
|
||||
building?: string | null;
|
||||
}
|
||||
|
||||
interface AttendanceDeviceRow {
|
||||
id: number;
|
||||
deviceSn: string;
|
||||
deviceName: string;
|
||||
classroomId: number;
|
||||
classroom?: ClassroomOption | null;
|
||||
status: 'active' | 'disabled';
|
||||
location?: string | null;
|
||||
notes?: string | null;
|
||||
}
|
||||
|
||||
const statusMeta = {
|
||||
active: { text: '启用', color: 'green' },
|
||||
disabled: { text: '停用', color: 'default' },
|
||||
} as const;
|
||||
|
||||
const AttendanceDevicesPage: React.FC = () => {
|
||||
const [data, setData] = useState<AttendanceDeviceRow[]>([]);
|
||||
const [classrooms, setClassrooms] = useState<ClassroomOption[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<AttendanceDeviceRow | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [form] = Form.useForm();
|
||||
|
||||
const loadData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [devices, classroomList] = await Promise.all([
|
||||
api.get<AttendanceDeviceRow[]>('/attendance-devices'),
|
||||
api.get<ClassroomOption[]>('/classrooms'),
|
||||
]);
|
||||
setData(devices);
|
||||
setClassrooms(classroomList.filter((item: any) => item.status !== 'archived'));
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '加载考勤机绑定失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
void loadData();
|
||||
}, []);
|
||||
|
||||
const classroomOptions = useMemo(
|
||||
() =>
|
||||
classrooms.map((item) => ({
|
||||
value: item.id,
|
||||
label: item.building ? `${item.name}(${item.building})` : item.name,
|
||||
})),
|
||||
[classrooms],
|
||||
);
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
const text = keyword.trim().toLocaleLowerCase('zh-CN');
|
||||
if (!text) return data;
|
||||
return data.filter((item) =>
|
||||
[item.deviceSn, item.deviceName, item.classroom?.name, item.location].some((value) =>
|
||||
(value || '').toLocaleLowerCase('zh-CN').includes(text),
|
||||
),
|
||||
);
|
||||
}, [data, keyword]);
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
form.setFieldsValue({ status: 'active' });
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const openEdit = (record: AttendanceDeviceRow) => {
|
||||
setEditing(record);
|
||||
form.setFieldsValue({
|
||||
deviceSn: record.deviceSn,
|
||||
deviceName: record.deviceName,
|
||||
classroomId: record.classroomId,
|
||||
status: record.status,
|
||||
location: record.location,
|
||||
notes: record.notes,
|
||||
});
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
const values = await form.validateFields();
|
||||
setSaving(true);
|
||||
try {
|
||||
if (editing) {
|
||||
await api.put(`/attendance-devices/${editing.id}`, values);
|
||||
message.success('考勤机绑定已更新');
|
||||
} else {
|
||||
await api.post('/attendance-devices', values);
|
||||
message.success('考勤机绑定已创建');
|
||||
}
|
||||
setModalOpen(false);
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
await loadData();
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '保存失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/attendance-devices/${id}`);
|
||||
message.success('已停用绑定');
|
||||
await loadData();
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '停用失败');
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ColumnsType<AttendanceDeviceRow> = [
|
||||
{ title: '设备名称', dataIndex: 'deviceName', width: 180 },
|
||||
{
|
||||
title: 'SN 码',
|
||||
dataIndex: 'deviceSn',
|
||||
width: 220,
|
||||
render: (value) => <span style={{ fontFamily: 'monospace' }}>{value}</span>,
|
||||
},
|
||||
{
|
||||
title: '绑定教室',
|
||||
dataIndex: ['classroom', 'name'],
|
||||
width: 160,
|
||||
render: (_value, record) => record.classroom?.name || `教室 ${record.classroomId}`,
|
||||
},
|
||||
{
|
||||
title: '位置',
|
||||
dataIndex: 'location',
|
||||
render: (value) => value || <span style={{ color: '#999' }}>—</span>,
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 90,
|
||||
render: (value: keyof typeof statusMeta) => (
|
||||
<Tag color={statusMeta[value]?.color}>{statusMeta[value]?.text || value}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '备注',
|
||||
dataIndex: 'notes',
|
||||
ellipsis: true,
|
||||
render: (value) => value || <span style={{ color: '#999' }}>—</span>,
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 150,
|
||||
render: (_, record) => (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="classroom:edit"
|
||||
size="small"
|
||||
type="link"
|
||||
onClick={() => openEdit(record)}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<Popconfirm title="确定停用此考勤机绑定?" onConfirm={() => handleDelete(record.id)}>
|
||||
<PermissionButton permission="classroom:edit" size="small" danger>
|
||||
停用
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<Input.Search
|
||||
allowClear
|
||||
placeholder="搜索设备/SN/教室"
|
||||
style={{ width: 260 }}
|
||||
value={keyword}
|
||||
onChange={(event) => setKeyword(event.target.value)}
|
||||
/>
|
||||
<PermissionButton
|
||||
permission="classroom:edit"
|
||||
type="primary"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={openCreate}
|
||||
>
|
||||
添加考勤机
|
||||
</PermissionButton>
|
||||
</div>
|
||||
<Table<AttendanceDeviceRow>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={filteredData}
|
||||
loading={loading}
|
||||
locale={{ emptyText: <Empty description="暂无考勤机绑定" /> }}
|
||||
pagination={{ defaultPageSize: 20, showSizeChanger: true }}
|
||||
/>
|
||||
<Modal
|
||||
title={editing ? '编辑考勤机绑定' : '添加考勤机绑定'}
|
||||
open={modalOpen}
|
||||
onOk={handleSave}
|
||||
onCancel={() => {
|
||||
setModalOpen(false);
|
||||
setEditing(null);
|
||||
}}
|
||||
confirmLoading={saving}
|
||||
okText="保存"
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item
|
||||
name="deviceName"
|
||||
label="设备名称"
|
||||
rules={[{ required: true, message: '请输入设备名称' }]}
|
||||
>
|
||||
<Input placeholder="如:彼岸游境_N1604" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="deviceSn"
|
||||
label="SN 码"
|
||||
rules={[{ required: true, message: '请输入钉钉返回的 deviceSN' }]}
|
||||
>
|
||||
<Input placeholder="如:300419260325WN1604" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="classroomId"
|
||||
label="绑定教室"
|
||||
rules={[{ required: true, message: '请选择绑定教室' }]}
|
||||
>
|
||||
<Select
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
options={classroomOptions}
|
||||
placeholder="选择教室"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="status" label="状态" initialValue="active">
|
||||
<Select
|
||||
options={[
|
||||
{ value: 'active', label: '启用' },
|
||||
{ value: 'disabled', label: '停用' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="location" label="位置">
|
||||
<Input placeholder="如:教学楼一楼东侧" />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AttendanceDevicesPage;
|
||||
110
apps/admin/src/pages/Bills/bill-print.ts
Normal file
110
apps/admin/src/pages/Bills/bill-print.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
interface BillPrintItem {
|
||||
expenseType?: string | null;
|
||||
description?: string | null;
|
||||
days?: number | null;
|
||||
totalRoomDays?: number | null;
|
||||
studentAmount?: number | string | null;
|
||||
}
|
||||
|
||||
export interface BillPrintData {
|
||||
id: number;
|
||||
student?: { name?: string | null } | null;
|
||||
periodStart?: string | null;
|
||||
periodEnd?: string | null;
|
||||
status?: string | null;
|
||||
sharedAmount?: number | string | null;
|
||||
personalAmount?: number | string | null;
|
||||
totalAmount?: number | string | null;
|
||||
paidAmount?: number | string | null;
|
||||
outstandingAmount?: number | string | null;
|
||||
items?: BillPrintItem[] | null;
|
||||
}
|
||||
|
||||
const statusLabels: Record<string, string> = {
|
||||
unpaid: '待支付',
|
||||
partially_paid: '部分支付',
|
||||
paid: '已结清',
|
||||
cancelled: '已取消',
|
||||
};
|
||||
|
||||
const escapeHtml = (value: unknown) =>
|
||||
String(value ?? '')
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
|
||||
const money = (value: unknown) => `¥${Number(value || 0).toFixed(2)}`;
|
||||
|
||||
export const buildBillPrintHtml = (bill: BillPrintData) => {
|
||||
const rows = (bill.items ?? [])
|
||||
.map(
|
||||
(item) => `
|
||||
<tr>
|
||||
<td>${escapeHtml(item.expenseType || '')}</td>
|
||||
<td>${escapeHtml(item.description || '')}</td>
|
||||
<td>${Number(item.days || 0)}</td>
|
||||
<td>${Number(item.totalRoomDays || 0)}</td>
|
||||
<td>${Number(item.studentAmount || 0).toFixed(2)}</td>
|
||||
</tr>`,
|
||||
)
|
||||
.join('');
|
||||
|
||||
return `<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>账单_${bill.id}</title>
|
||||
<style>
|
||||
@page { size: A4; margin: 50pt; }
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
color: #000;
|
||||
font-family: "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
h1 { margin: 0; font-size: 20px; font-weight: 600; text-align: center; }
|
||||
h2 { margin: 20px 0 6px; font-size: 14px; text-decoration: underline; }
|
||||
p { margin: 2px 0; }
|
||||
.generated { margin: 6px 0 18px; color: #666; font-size: 10px; text-align: center; }
|
||||
.total { color: #007aff; font-size: 14px; font-weight: 600; }
|
||||
.paid { color: #389e0d; font-size: 11px; }
|
||||
.outstanding { color: ${Number(bill.outstandingAmount || 0) > 0 ? '#ff3b30' : '#389e0d'}; font-size: 14px; font-weight: 600; }
|
||||
table { width: 100%; border-collapse: collapse; table-layout: fixed; font-size: 9px; }
|
||||
th, td { padding: 4px 0; text-align: left; vertical-align: top; word-break: break-word; }
|
||||
th { color: #333; font-size: 10px; font-weight: 400; border-bottom: 1px solid #ccc; }
|
||||
th:nth-child(1) { width: 24%; }
|
||||
th:nth-child(2) { width: 36%; }
|
||||
th:nth-child(3), th:nth-child(4) { width: 12%; }
|
||||
th:nth-child(5) { width: 16%; }
|
||||
.empty { padding: 12px 0; color: #999; text-align: center; }
|
||||
.footer { margin-top: 34px; color: #999; font-size: 8px; text-align: center; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>恭学教育基地水电费账单</h1>
|
||||
<div class="generated">生成时间: ${escapeHtml(new Date().toLocaleString('zh-CN'))}</div>
|
||||
<p>学生姓名: ${escapeHtml(bill.student?.name || '-')}</p>
|
||||
<p>计费周期: ${escapeHtml(bill.periodStart || '-')} ~ ${escapeHtml(bill.periodEnd || '-')}</p>
|
||||
<p>账单状态: ${escapeHtml(statusLabels[bill.status || ''] || bill.status || '-')}</p>
|
||||
|
||||
<h2>费用汇总</h2>
|
||||
<p>分摊费用: ${money(bill.sharedAmount)}</p>
|
||||
<p>个人费用: ${money(bill.personalAmount)}</p>
|
||||
<p class="total">应付总额: ${money(bill.totalAmount)}</p>
|
||||
<p class="paid">已扣余额: ${money(bill.paidAmount)}</p>
|
||||
<p class="outstanding">待补缴: ${money(bill.outstandingAmount)}</p>
|
||||
|
||||
<h2>费用明细</h2>
|
||||
<table>
|
||||
<thead><tr><th>费用类型</th><th>说明</th><th>天数</th><th>总人天</th><th>金额(元)</th></tr></thead>
|
||||
<tbody>${rows || '<tr><td class="empty" colspan="5">暂无费用明细</td></tr>'}</tbody>
|
||||
</table>
|
||||
<div class="footer">本账单由恭学教育基地管理系统自动生成</div>
|
||||
<script>window.addEventListener('load', function () { setTimeout(function () { window.print(); }, 100); });</script>
|
||||
</body>
|
||||
</html>`;
|
||||
};
|
||||
@@ -10,13 +10,12 @@ import {
|
||||
Popconfirm,
|
||||
Input,
|
||||
Select,
|
||||
Tooltip,
|
||||
Spin,
|
||||
Empty,
|
||||
} from 'antd';
|
||||
import {
|
||||
FileTextOutlined,
|
||||
DeleteOutlined,
|
||||
InboxOutlined,
|
||||
DownloadOutlined,
|
||||
FilePdfOutlined,
|
||||
} from '@ant-design/icons';
|
||||
@@ -25,13 +24,14 @@ import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { downloadBlob } from '../../utils/download';
|
||||
import { message } from '../../ui/app-message';
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
import { buildBillPrintHtml, type BillPrintData } from './bill-print';
|
||||
import { newOperationId } from '../../utils/operation-id';
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
draft: { text: '草稿', color: 'default' },
|
||||
confirmed: { text: '已确认', color: 'blue' },
|
||||
unpaid: { text: '待支付', color: 'orange' },
|
||||
partially_paid: { text: '部分支付', color: 'gold' },
|
||||
paid: { text: '已支付', color: 'green' },
|
||||
cancelled: { text: '已取消', color: 'default' },
|
||||
};
|
||||
|
||||
const typeMap: Record<string, string> = {
|
||||
@@ -63,7 +63,7 @@ const BillsPage: React.FC = () => {
|
||||
const params: Record<string, string | undefined> = {};
|
||||
if (filterStatus) params.status = filterStatus;
|
||||
if (filterExpenseType) params.expenseType = filterExpenseType;
|
||||
const res = await api.get('/bills', { params }) as unknown[];
|
||||
const res = (await api.get('/bills', { params })) as unknown[];
|
||||
setBills(res);
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载失败,请稍后重试');
|
||||
@@ -93,8 +93,8 @@ const BillsPage: React.FC = () => {
|
||||
const values = await generateForm.validateFields();
|
||||
try {
|
||||
const res: any = await api.post('/bills/generate', {
|
||||
periodStart: values.period[0].format('YYYY-MM-DD'),
|
||||
periodEnd: values.period[1].format('YYYY-MM-DD'),
|
||||
operationId: newOperationId(),
|
||||
billingMonth: values.billingMonth.format('YYYY-MM'),
|
||||
});
|
||||
message.success(res.message || '生成成功');
|
||||
setGenerateModal(false);
|
||||
@@ -119,52 +119,53 @@ const BillsPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const updateStatus = async (id: number, status: string) => {
|
||||
try {
|
||||
await api.put(`/bills/${id}/status`, { status });
|
||||
message.success('状态更新成功');
|
||||
fetchData();
|
||||
if (detailModal?.id === id) {
|
||||
setDetailModal({ ...detailModal, status });
|
||||
}
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '操作失败');
|
||||
}
|
||||
const handleCancel = async (id: number) => {
|
||||
let reason = '';
|
||||
Modal.confirm({
|
||||
title: '取消账单并退回已扣余额',
|
||||
content: (
|
||||
<Input.TextArea
|
||||
placeholder="请输入取消原因"
|
||||
maxLength={300}
|
||||
onChange={(event) => {
|
||||
reason = event.target.value;
|
||||
}}
|
||||
/>
|
||||
),
|
||||
okText: '确认取消',
|
||||
cancelText: '返回',
|
||||
onOk: async () => {
|
||||
if (!reason.trim()) {
|
||||
message.error('请输入取消原因');
|
||||
throw new Error('reason required');
|
||||
}
|
||||
await api.post(`/bills/${id}/cancel`, {
|
||||
operationId: newOperationId(),
|
||||
reason: reason.trim(),
|
||||
});
|
||||
message.success('账单已取消,已扣余额已冲正退回');
|
||||
fetchData();
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const batchUpdateStatus = async (status: string) => {
|
||||
if (selectedRows.length === 0) return message.warning('请先选择账单');
|
||||
if (batchLoading) return;
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
await api.put('/bills/batch/status', { ids: selectedRows, status });
|
||||
message.success(`已批量更新 ${selectedRows.length} 条账单`);
|
||||
setSelectedRows([]);
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '操作失败');
|
||||
} finally {
|
||||
setBatchLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
const handleArchive = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/bills/${id}`);
|
||||
message.success('账单已删除');
|
||||
message.success('账单已归档');
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '删除失败');
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '归档失败');
|
||||
}
|
||||
};
|
||||
|
||||
const batchDelete = async () => {
|
||||
const batchArchive = async () => {
|
||||
if (selectedRows.length === 0) return message.warning('请先选择账单');
|
||||
if (batchLoading) return;
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
await api.post('/bills/batch/delete', { ids: selectedRows });
|
||||
message.success(`已删除 ${selectedRows.length} 条账单`);
|
||||
message.success(`已归档 ${selectedRows.length} 条账单`);
|
||||
setSelectedRows([]);
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
@@ -181,142 +182,151 @@ const BillsPage: React.FC = () => {
|
||||
);
|
||||
};
|
||||
|
||||
const handleExportPdf = (billId: number) => {
|
||||
downloadBlob(`/bills/export/pdf/${billId}`, `账单_${billId}.pdf`).catch(() =>
|
||||
message.error('导出失败'),
|
||||
const handleExportPdf = async (billId: number) => {
|
||||
const printWindow = window.open('', '_blank');
|
||||
if (!printWindow) {
|
||||
message.error('浏览器阻止了打印窗口,请允许弹出窗口后重试');
|
||||
return;
|
||||
}
|
||||
|
||||
printWindow.document.write(
|
||||
'<p style="font-family:sans-serif;padding:24px">正在加载账单...</p>',
|
||||
);
|
||||
try {
|
||||
const bill = await api.get<BillPrintData>(`/bills/${billId}`);
|
||||
printWindow.document.open();
|
||||
printWindow.document.write(buildBillPrintHtml(bill));
|
||||
printWindow.document.close();
|
||||
} catch (error: any) {
|
||||
printWindow.close();
|
||||
message.error(error?.message || '账单加载失败');
|
||||
}
|
||||
};
|
||||
|
||||
const columns = useMemo(() => [
|
||||
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
|
||||
{ title: '账单周期', width: 200, render: (_: any, r: any) => `${r.periodStart} ~ ${r.periodEnd}` },
|
||||
{
|
||||
title: '分摊费用',
|
||||
dataIndex: 'sharedAmount',
|
||||
width: 120,
|
||||
align: 'right' as const,
|
||||
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '个人费用',
|
||||
dataIndex: 'personalAmount',
|
||||
width: 120,
|
||||
align: 'right' as const,
|
||||
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '总计',
|
||||
dataIndex: 'totalAmount',
|
||||
width: 100,
|
||||
align: 'right' as const,
|
||||
render: (v: number) => <strong>¥{Number(v).toFixed(2)}</strong>,
|
||||
},
|
||||
{
|
||||
title: '可用押金',
|
||||
dataIndex: 'availableDeposit',
|
||||
width: 120,
|
||||
render: (v: number) =>
|
||||
v > 0 ? (
|
||||
<span style={{ color: '#52c41a' }}>¥{Number(v).toFixed(2)}</span>
|
||||
) : (
|
||||
<span style={{ color: '#999' }}>-</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '抵扣后应付',
|
||||
dataIndex: 'amountAfterDeposit',
|
||||
width: 130,
|
||||
render: (v: number, r: any) => {
|
||||
const has = Number(r.availableDeposit || 0) > 0;
|
||||
if (!has) return <span style={{ color: '#999' }}>-</span>;
|
||||
const after = Number(v ?? r.totalAmount).toFixed(2);
|
||||
const applied = Number(r.depositApplied || 0).toFixed(2);
|
||||
return (
|
||||
<Tooltip title={`已抵扣押金 ¥${applied}`}>
|
||||
<strong style={{ color: '#fa541c' }}>¥{after}</strong>
|
||||
</Tooltip>
|
||||
);
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
|
||||
{
|
||||
title: '账单周期',
|
||||
width: 200,
|
||||
render: (_: any, r: any) => `${r.periodStart} ~ ${r.periodEnd}`,
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 90,
|
||||
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '生成时间',
|
||||
dataIndex: 'generatedAt',
|
||||
width: 160,
|
||||
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 320,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="bill:view"
|
||||
size="small"
|
||||
type="link"
|
||||
onClick={() => showDetail(record.id)}
|
||||
>
|
||||
详情
|
||||
</PermissionButton>
|
||||
{record.status === 'draft' && (
|
||||
{
|
||||
title: '分摊费用',
|
||||
dataIndex: 'sharedAmount',
|
||||
width: 120,
|
||||
align: 'right' as const,
|
||||
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '个人费用',
|
||||
dataIndex: 'personalAmount',
|
||||
width: 120,
|
||||
align: 'right' as const,
|
||||
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '总计',
|
||||
dataIndex: 'totalAmount',
|
||||
width: 100,
|
||||
align: 'right' as const,
|
||||
render: (v: number) => <strong>¥{Number(v).toFixed(2)}</strong>,
|
||||
},
|
||||
{
|
||||
title: '已扣余额',
|
||||
dataIndex: 'paidAmount',
|
||||
width: 110,
|
||||
render: (value: number) => (
|
||||
<span style={{ color: '#389e0d' }}>¥{Number(value || 0).toFixed(2)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '待补缴',
|
||||
dataIndex: 'outstandingAmount',
|
||||
width: 110,
|
||||
render: (value: number) => (
|
||||
<strong style={{ color: Number(value) > 0 ? '#cf1322' : '#389e0d' }}>
|
||||
¥{Number(value || 0).toFixed(2)}
|
||||
</strong>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '钱包余额',
|
||||
dataIndex: 'walletBalance',
|
||||
width: 110,
|
||||
render: (value: number) => `¥${Number(value || 0).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 90,
|
||||
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '生成时间',
|
||||
dataIndex: 'generatedAt',
|
||||
width: 160,
|
||||
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 320,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="bill:confirm"
|
||||
permission="bill:view"
|
||||
size="small"
|
||||
onClick={() => updateStatus(record.id, 'confirmed')}
|
||||
type="link"
|
||||
onClick={() => showDetail(record.id)}
|
||||
>
|
||||
确认
|
||||
详情
|
||||
</PermissionButton>
|
||||
)}
|
||||
{record.status === 'confirmed' && (
|
||||
<PermissionButton
|
||||
permission="bill:confirm"
|
||||
permission="bill:export-pdf"
|
||||
size="small"
|
||||
type="primary"
|
||||
onClick={() => updateStatus(record.id, 'paid')}
|
||||
icon={<FilePdfOutlined />}
|
||||
onClick={() => handleExportPdf(record.id)}
|
||||
>
|
||||
标记已付
|
||||
PDF
|
||||
</PermissionButton>
|
||||
)}
|
||||
<PermissionButton
|
||||
permission="bill:export-pdf"
|
||||
size="small"
|
||||
icon={<FilePdfOutlined />}
|
||||
onClick={() => handleExportPdf(record.id)}
|
||||
>
|
||||
PDF
|
||||
</PermissionButton>
|
||||
<Popconfirm
|
||||
title="确定删除此账单?"
|
||||
onConfirm={() => handleDelete(record.id)}
|
||||
okText="删除"
|
||||
cancelText="取消"
|
||||
>
|
||||
<PermissionButton permission="bill:delete" size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
], [showDetail, updateStatus, handleDelete, handleExportPdf]);
|
||||
{record.status !== 'cancelled' && (
|
||||
<PermissionButton
|
||||
permission="bill:delete"
|
||||
size="small"
|
||||
danger
|
||||
onClick={() => handleCancel(record.id)}
|
||||
>
|
||||
取消并冲正
|
||||
</PermissionButton>
|
||||
)}
|
||||
{Number(record.paidAmount || 0) === 0 && record.status !== 'cancelled' && (
|
||||
<Popconfirm
|
||||
title="确定归档此未支付账单?"
|
||||
onConfirm={() => handleArchive(record.id)}
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
>
|
||||
<PermissionButton
|
||||
permission="bill:delete"
|
||||
size="small"
|
||||
danger
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
],
|
||||
[showDetail, handleArchive, handleCancel, handleExportPdf],
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<Space wrap>
|
||||
<div className="responsive-toolbar">
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<Input.Search
|
||||
placeholder="搜索学生姓名或账单周期"
|
||||
allowClear
|
||||
@@ -333,32 +343,30 @@ const BillsPage: React.FC = () => {
|
||||
value={filterStatus}
|
||||
onChange={(v) => setFilterStatus(v)}
|
||||
options={[
|
||||
{ value: 'draft', label: '草稿' },
|
||||
{ value: 'confirmed', label: '已确认' },
|
||||
{ value: 'unpaid', label: '待支付' },
|
||||
{ value: 'partially_paid', label: '部分支付' },
|
||||
{ value: 'paid', label: '已支付' },
|
||||
{ value: 'cancelled', label: '已取消' },
|
||||
]}
|
||||
/>
|
||||
<Select
|
||||
placeholder="费用类型"
|
||||
allowClear
|
||||
style={{ width: 120 }}
|
||||
value={filterExpenseType}
|
||||
onChange={setFilterExpenseType}
|
||||
options={[
|
||||
{ value: 'water', label: '水费' },
|
||||
{ value: 'electricity', label: '电费' },
|
||||
{ value: 'cleaning', label: '保洁费' },
|
||||
{ value: 'rent', label: '租金' },
|
||||
{ value: 'other', label: '其他' },
|
||||
]}
|
||||
/>
|
||||
<Select placeholder="费用类型" allowClear style={{ width: 120 }} value={filterExpenseType} onChange={setFilterExpenseType}
|
||||
options={[{value:'water',label:'水费'},{value:'electricity',label:'电费'},{value:'cleaning',label:'保洁费'},{value:'rent',label:'租金'},{value:'other',label:'其他'}]} />
|
||||
<PermissionButton
|
||||
permission="bill:confirm"
|
||||
onClick={() => batchUpdateStatus('confirmed')}
|
||||
disabled={selectedRows.length === 0}
|
||||
>
|
||||
批量确认
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="bill:confirm"
|
||||
type="primary"
|
||||
onClick={() => batchUpdateStatus('paid')}
|
||||
disabled={selectedRows.length === 0}
|
||||
>
|
||||
批量标记已付
|
||||
</PermissionButton>
|
||||
<Popconfirm
|
||||
title={`确定删除选中的 ${selectedRows.length} 条账单?`}
|
||||
onConfirm={batchDelete}
|
||||
okText="删除"
|
||||
title={`确定归档选中的 ${selectedRows.length} 条账单?`}
|
||||
onConfirm={batchArchive}
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
disabled={selectedRows.length === 0}
|
||||
>
|
||||
@@ -366,13 +374,13 @@ const BillsPage: React.FC = () => {
|
||||
permission="bill:delete"
|
||||
danger
|
||||
disabled={selectedRows.length === 0}
|
||||
icon={<DeleteOutlined />}
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
批量删除
|
||||
批量归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
<Space>
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<PermissionButton
|
||||
permission="bill:generate"
|
||||
type="primary"
|
||||
@@ -399,12 +407,7 @@ const BillsPage: React.FC = () => {
|
||||
dataSource={filteredBills}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
pagination={{
|
||||
defaultPageSize: 15,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [15, 30, 50, 100],
|
||||
showTotal: (total) => `共 ${total} 条`,
|
||||
}}
|
||||
pagination={{ pageSize: 15, showTotal: (total) => `共 ${total} 条` }}
|
||||
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedRows,
|
||||
@@ -422,15 +425,19 @@ const BillsPage: React.FC = () => {
|
||||
>
|
||||
<Form form={generateForm} layout="vertical">
|
||||
<Form.Item
|
||||
name="period"
|
||||
label="账单周期"
|
||||
rules={[{ required: true, message: '请选择账单周期' }]}
|
||||
extra="选择费用对应的时间段,系统将自动计算每个学生的分摊费用"
|
||||
name="billingMonth"
|
||||
label="账单月份"
|
||||
rules={[{ required: true, message: '请选择账单月份' }]}
|
||||
extra="只能选择已结束月份,每个月只能生成一次账单"
|
||||
>
|
||||
<RangePicker
|
||||
<DatePicker
|
||||
style={{ width: '100%' }}
|
||||
placeholder={['开始日期', '结束日期']}
|
||||
format="YYYY-MM-DD"
|
||||
picker="month"
|
||||
placeholder="选择月份"
|
||||
format="YYYY-MM"
|
||||
disabledDate={(current) =>
|
||||
!!current && !current.endOf('month').isBefore(dayjs(), 'day')
|
||||
}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
@@ -470,42 +477,17 @@ const BillsPage: React.FC = () => {
|
||||
</strong>
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
{Number(detailModal.availableDeposit || 0) > 0 && (
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
padding: 12,
|
||||
background: '#f6ffed',
|
||||
border: '1px solid #b7eb8f',
|
||||
borderRadius: 8,
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: 13, color: '#666', marginBottom: 6 }}>
|
||||
押金联动(不影响实际押金状态,仅作收款参考)
|
||||
</div>
|
||||
<Space size={24} wrap>
|
||||
<span>
|
||||
当前可用押金:
|
||||
<strong style={{ color: '#52c41a' }}>
|
||||
¥{Number(detailModal.availableDeposit).toFixed(2)}
|
||||
</strong>
|
||||
</span>
|
||||
<span>
|
||||
本账单可抵扣:
|
||||
<strong style={{ color: '#fa8c16' }}>
|
||||
-¥{Number(detailModal.depositApplied || 0).toFixed(2)}
|
||||
</strong>
|
||||
</span>
|
||||
<span>
|
||||
抵扣后实付:
|
||||
<strong style={{ color: '#fa541c', fontSize: 16 }}>
|
||||
¥
|
||||
{Number(detailModal.amountAfterDeposit ?? detailModal.totalAmount).toFixed(2)}
|
||||
</strong>
|
||||
</span>
|
||||
</Space>
|
||||
</div>
|
||||
)}
|
||||
<Descriptions bordered size="small" column={3} style={{ marginBottom: 16 }}>
|
||||
<Descriptions.Item label="已扣余额">
|
||||
¥{Number(detailModal.paidAmount || 0).toFixed(2)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="待补缴">
|
||||
¥{Number(detailModal.outstandingAmount || 0).toFixed(2)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="当前钱包余额">
|
||||
¥{Number(detailModal.walletBalance || 0).toFixed(2)}
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
<h4>费用明细</h4>
|
||||
<Table
|
||||
scroll={{ x: 700 }}
|
||||
|
||||
@@ -1,8 +1,23 @@
|
||||
import React, { useEffect, useState, useCallback } from 'react';
|
||||
import { useParams, useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
Card, Tabs, Descriptions, Table, Button, Space, Select, Modal, Tag,
|
||||
Popconfirm, Form, Input, DatePicker, InputNumber, Row, Col, Statistic,
|
||||
Card,
|
||||
Tabs,
|
||||
Descriptions,
|
||||
Table,
|
||||
Button,
|
||||
Space,
|
||||
Select,
|
||||
Modal,
|
||||
Tag,
|
||||
Popconfirm,
|
||||
Form,
|
||||
Input,
|
||||
DatePicker,
|
||||
InputNumber,
|
||||
Row,
|
||||
Col,
|
||||
Statistic,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { ArrowLeftOutlined, PlusOutlined, DownloadOutlined } from '@ant-design/icons';
|
||||
@@ -10,6 +25,7 @@ import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { buildTeacherCandidateOptions, type TeacherCandidateUser } from './teacher-candidate';
|
||||
|
||||
// ---- Types ----
|
||||
|
||||
@@ -39,6 +55,7 @@ interface ClassScheduleItem {
|
||||
weekDay: number;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
attendanceAdvanceMinutes: number;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
subject: string;
|
||||
@@ -83,10 +100,7 @@ interface StudentItem {
|
||||
studentNo?: string;
|
||||
}
|
||||
|
||||
interface UserItem {
|
||||
id: number;
|
||||
username: string;
|
||||
}
|
||||
type UserItem = TeacherCandidateUser;
|
||||
|
||||
// ---- Constants ----
|
||||
|
||||
@@ -112,7 +126,13 @@ const ROLE_MAP: Record<string, string> = {
|
||||
};
|
||||
|
||||
const WEEK_DAY_MAP: Record<number, string> = {
|
||||
1: '周一', 2: '周二', 3: '周三', 4: '周四', 5: '周五', 6: '周六', 7: '周日',
|
||||
1: '周一',
|
||||
2: '周二',
|
||||
3: '周三',
|
||||
4: '周四',
|
||||
5: '周五',
|
||||
6: '周六',
|
||||
7: '周日',
|
||||
};
|
||||
|
||||
const SCHEDULE_TYPE_MAP: Record<string, string> = {
|
||||
@@ -146,14 +166,18 @@ const ClassDetailPage: React.FC = () => {
|
||||
|
||||
// Schedule & attendance state
|
||||
const [schedules, setSchedules] = useState<ClassScheduleItem[]>([]);
|
||||
const [scheduleDateRange, setScheduleDateRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null]>([null, null]);
|
||||
const [scheduleDateRange, setScheduleDateRange] = useState<
|
||||
[dayjs.Dayjs | null, dayjs.Dayjs | null]
|
||||
>([null, null]);
|
||||
const [attendanceSummary, setAttendanceSummary] = useState<AttendanceSummary | null>(null);
|
||||
const [attendanceDateRange, setAttendanceDateRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null]>([null, null]);
|
||||
const [attendanceDateRange, setAttendanceDateRange] = useState<
|
||||
[dayjs.Dayjs | null, dayjs.Dayjs | null]
|
||||
>([null, null]);
|
||||
|
||||
const fetchDetail = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await api.get(`/classes/${id}`) as ClassDetail;
|
||||
const res = (await api.get(`/classes/${id}`)) as ClassDetail;
|
||||
setDetail(res);
|
||||
setStudents(res.students || []);
|
||||
setTeachers(res.teachers || []);
|
||||
@@ -165,7 +189,9 @@ const ClassDetailPage: React.FC = () => {
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => { fetchDetail(); }, [fetchDetail]);
|
||||
useEffect(() => {
|
||||
fetchDetail();
|
||||
}, [fetchDetail]);
|
||||
|
||||
const fetchSchedules = useCallback(async () => {
|
||||
if (!id) return;
|
||||
@@ -181,7 +207,9 @@ const ClassDetailPage: React.FC = () => {
|
||||
}
|
||||
}, [id, scheduleDateRange]);
|
||||
|
||||
useEffect(() => { fetchSchedules(); }, [fetchSchedules]);
|
||||
useEffect(() => {
|
||||
fetchSchedules();
|
||||
}, [fetchSchedules]);
|
||||
|
||||
const fetchAttendanceSummary = useCallback(async () => {
|
||||
if (!id) return;
|
||||
@@ -197,7 +225,9 @@ const ClassDetailPage: React.FC = () => {
|
||||
}
|
||||
}, [id, attendanceDateRange]);
|
||||
|
||||
useEffect(() => { fetchAttendanceSummary(); }, [fetchAttendanceSummary]);
|
||||
useEffect(() => {
|
||||
fetchAttendanceSummary();
|
||||
}, [fetchAttendanceSummary]);
|
||||
|
||||
const handleSaveInfo = async () => {
|
||||
try {
|
||||
@@ -276,7 +306,9 @@ const ClassDetailPage: React.FC = () => {
|
||||
|
||||
const openStudentModal = async () => {
|
||||
try {
|
||||
const res = await api.get('/students', { params: { includeArchived: 'false' } }) as StudentItem[];
|
||||
const res = (await api.get('/students', {
|
||||
params: { includeArchived: 'false' },
|
||||
})) as StudentItem[];
|
||||
setAllStudents(res || []);
|
||||
setSelectedStudentIds([]);
|
||||
setStudentModalOpen(true);
|
||||
@@ -288,7 +320,7 @@ const ClassDetailPage: React.FC = () => {
|
||||
|
||||
const openTeacherModal = async () => {
|
||||
try {
|
||||
const res = await api.get('/rbac/users') as UserItem[];
|
||||
const res = (await api.get('/rbac/users')) as UserItem[];
|
||||
setAllUsers(res || []);
|
||||
setTeacherUserId(undefined);
|
||||
setTeacherRole('subject_teacher');
|
||||
@@ -311,9 +343,7 @@ const ClassDetailPage: React.FC = () => {
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
render: (v: string) => (
|
||||
<Tag color={v === 'active' ? 'green' : 'default'}>
|
||||
{v === 'active' ? '在读' : '已离班'}
|
||||
</Tag>
|
||||
<Tag color={v === 'active' ? 'green' : 'default'}>{v === 'active' ? '在读' : '已离班'}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -321,7 +351,9 @@ const ClassDetailPage: React.FC = () => {
|
||||
render: (_: unknown, r: ClassStudent) =>
|
||||
r.status === 'active' ? (
|
||||
<Popconfirm title="确认移除?" onConfirm={() => handleRemoveStudent(r.studentId)}>
|
||||
<PermissionButton permission="class:edit" size="small" danger>移除</PermissionButton>
|
||||
<PermissionButton permission="class:edit" size="small" danger>
|
||||
移除
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
) : null,
|
||||
},
|
||||
@@ -343,7 +375,9 @@ const ClassDetailPage: React.FC = () => {
|
||||
title: '操作',
|
||||
render: (_: unknown, r: ClassTeacher) => (
|
||||
<Popconfirm title="确认移除?" onConfirm={() => handleRemoveTeacher(r.userId)}>
|
||||
<PermissionButton permission="class:edit" size="small" danger>移除</PermissionButton>
|
||||
<PermissionButton permission="class:edit" size="small" danger>
|
||||
移除
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
),
|
||||
},
|
||||
@@ -352,14 +386,27 @@ const ClassDetailPage: React.FC = () => {
|
||||
const scheduleColumns: ColumnsType<ClassScheduleItem> = [
|
||||
{ title: '教室', dataIndex: 'classroomName', render: (v: string | null) => v || '-' },
|
||||
{ title: '星期', dataIndex: 'weekDay', render: (v: number) => WEEK_DAY_MAP[v] || v },
|
||||
{ title: '时间', render: (_: unknown, r: ClassScheduleItem) => `${r.startTime} - ${r.endTime}` },
|
||||
{ title: '日期范围', render: (_: unknown, r: ClassScheduleItem) => `${r.startDate} ~ ${r.endDate}` },
|
||||
{
|
||||
title: '时间',
|
||||
render: (_: unknown, r: ClassScheduleItem) => `${r.startTime} - ${r.endTime}`,
|
||||
},
|
||||
{
|
||||
title: '签到窗口',
|
||||
render: (_: unknown, r: ClassScheduleItem) =>
|
||||
`课前 ${r.attendanceAdvanceMinutes ?? 30} 分钟至下课`,
|
||||
},
|
||||
{
|
||||
title: '日期范围',
|
||||
render: (_: unknown, r: ClassScheduleItem) => `${r.startDate} ~ ${r.endDate}`,
|
||||
},
|
||||
{ title: '科目', dataIndex: 'subject' },
|
||||
{ title: '类型', dataIndex: 'scheduleType', render: (v: string) => SCHEDULE_TYPE_MAP[v] || v },
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
render: (v: string) => <Tag color={v === 'active' ? 'green' : 'default'}>{v === 'active' ? '启用' : v}</Tag>,
|
||||
render: (v: string) => (
|
||||
<Tag color={v === 'active' ? 'green' : 'default'}>{v === 'active' ? '启用' : v}</Tag>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -368,7 +415,9 @@ const ClassDetailPage: React.FC = () => {
|
||||
title={
|
||||
<Space>
|
||||
<Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/classes')} />
|
||||
<span>{detail.name} ({detail.code})</span>
|
||||
<span>
|
||||
{detail.name} ({detail.code})
|
||||
</span>
|
||||
<Tag color={STATUS_MAP[detail.status]?.color}>{STATUS_MAP[detail.status]?.text}</Tag>
|
||||
</Space>
|
||||
}
|
||||
@@ -434,7 +483,11 @@ const ClassDetailPage: React.FC = () => {
|
||||
<Input.TextArea rows={3} />
|
||||
</Form.Item>
|
||||
<Space>
|
||||
<PermissionButton permission="class:edit" type="primary" onClick={handleSaveInfo}>
|
||||
<PermissionButton
|
||||
permission="class:edit"
|
||||
type="primary"
|
||||
onClick={handleSaveInfo}
|
||||
>
|
||||
保存
|
||||
</PermissionButton>
|
||||
<Button onClick={() => setEditingInfo(false)}>取消</Button>
|
||||
@@ -458,9 +511,7 @@ const ClassDetailPage: React.FC = () => {
|
||||
<Descriptions.Item label="班主任">
|
||||
{teachers.find((t) => t.roleType === 'head_teacher')?.username || '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="备注">
|
||||
{detail.notes || '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="备注">{detail.notes || '-'}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
<PermissionButton
|
||||
permission="class:edit"
|
||||
@@ -593,16 +644,13 @@ const ClassDetailPage: React.FC = () => {
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
<Select
|
||||
style={{ width: '100%' }}
|
||||
placeholder="选择教师"
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
placeholder="搜索姓名、用户名、角色或学科"
|
||||
value={teacherUserId}
|
||||
onChange={setTeacherUserId}
|
||||
options={allUsers.map((u) => ({
|
||||
value: u.id,
|
||||
label: u.username,
|
||||
}))}
|
||||
filterOption={(input, option) =>
|
||||
(option?.label as string)?.toLowerCase().includes(input.toLowerCase())
|
||||
}
|
||||
options={buildTeacherCandidateOptions(allUsers)}
|
||||
notFoundContent="没有可分配的工作人员账号"
|
||||
/>
|
||||
<Select
|
||||
style={{ width: '100%' }}
|
||||
@@ -630,10 +678,12 @@ const ClassDetailPage: React.FC = () => {
|
||||
label: '课表',
|
||||
children: (
|
||||
<div>
|
||||
<Space style={{ marginBottom: 16 }}>
|
||||
<Space style={{ marginBottom: 16, maxWidth: '100%' }} wrap>
|
||||
<DatePicker.RangePicker
|
||||
value={scheduleDateRange}
|
||||
onChange={(dates) => setScheduleDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])}
|
||||
onChange={(dates) =>
|
||||
setScheduleDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])
|
||||
}
|
||||
placeholder={['开始日期', '结束日期']}
|
||||
/>
|
||||
</Space>
|
||||
@@ -641,6 +691,7 @@ const ClassDetailPage: React.FC = () => {
|
||||
columns={scheduleColumns}
|
||||
dataSource={schedules}
|
||||
rowKey="id"
|
||||
scroll={{ x: 'max-content' }}
|
||||
pagination={{
|
||||
defaultPageSize: 20,
|
||||
showSizeChanger: true,
|
||||
@@ -655,31 +706,37 @@ const ClassDetailPage: React.FC = () => {
|
||||
label: '出勤汇总',
|
||||
children: (
|
||||
<div>
|
||||
<Space style={{ marginBottom: 16 }}>
|
||||
<Space style={{ marginBottom: 16, maxWidth: '100%' }} wrap>
|
||||
<DatePicker.RangePicker
|
||||
value={attendanceDateRange}
|
||||
onChange={(dates) => setAttendanceDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])}
|
||||
onChange={(dates) =>
|
||||
setAttendanceDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])
|
||||
}
|
||||
placeholder={['开始日期', '结束日期']}
|
||||
/>
|
||||
</Space>
|
||||
{attendanceSummary && (
|
||||
<Row gutter={16}>
|
||||
<Col span={6}>
|
||||
<Row gutter={[16, 16]}>
|
||||
<Col xs={12} md={6}>
|
||||
<Card bordered={false}>
|
||||
<Statistic title="总记录" value={attendanceSummary.total} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Col xs={12} md={6}>
|
||||
<Card bordered={false}>
|
||||
<Statistic title="出勤率" value={attendanceSummary.presentRate} suffix="%" />
|
||||
<Statistic
|
||||
title="出勤率"
|
||||
value={attendanceSummary.presentRate}
|
||||
suffix="%"
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Col xs={12} md={6}>
|
||||
<Card bordered={false}>
|
||||
<Statistic title="缺勤率" value={attendanceSummary.absentRate} suffix="%" />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Col xs={12} md={6}>
|
||||
<Card bordered={false}>
|
||||
<Statistic title="迟到率" value={attendanceSummary.lateRate} suffix="%" />
|
||||
</Card>
|
||||
|
||||
@@ -1,7 +1,19 @@
|
||||
import React, { useEffect, useState, useMemo, useCallback } from 'react';
|
||||
import {
|
||||
Table, Button, Input, Select, Space, Tag, Modal, Form, InputNumber,
|
||||
DatePicker, Popconfirm, Card, Switch, Empty,
|
||||
Table,
|
||||
Button,
|
||||
Input,
|
||||
Select,
|
||||
Space,
|
||||
Tag,
|
||||
Modal,
|
||||
Form,
|
||||
InputNumber,
|
||||
DatePicker,
|
||||
Popconfirm,
|
||||
Card,
|
||||
Switch,
|
||||
Empty,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { PlusOutlined, SearchOutlined, TeamOutlined, InboxOutlined } from '@ant-design/icons';
|
||||
@@ -96,13 +108,14 @@ const ClassesPage: React.FC = () => {
|
||||
setData(res);
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载失败,请稍后重试');
|
||||
}
|
||||
finally {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [filterStatus, filterType, showArchived]);
|
||||
|
||||
useEffect(() => { fetchData(); }, [fetchData]);
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
if (!searchText) return data;
|
||||
@@ -154,73 +167,86 @@ const ClassesPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/classes/${id}`);
|
||||
message.success('已删除');
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '删除失败');
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ColumnsType<ClassItem> = useMemo(() => [
|
||||
{
|
||||
title: '班级名称', dataIndex: 'name', width: 120,
|
||||
sorter: (a, b) => a.name.localeCompare(b.name),
|
||||
},
|
||||
{ title: '编码', dataIndex: 'code', width: 140 },
|
||||
{
|
||||
title: '班型', dataIndex: 'classType', width: 100,
|
||||
render: (v: string) => <Tag>{TYPE_MAP[v] || v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '开班日期', dataIndex: 'startDate', width: 110,
|
||||
render: (v: string | null) => v || '-',
|
||||
},
|
||||
{
|
||||
title: '学员', width: 100,
|
||||
render: (_: unknown, r: ClassItem) => `${r.studentCount || 0}/${r.maxStudents || '-'}`,
|
||||
},
|
||||
{
|
||||
title: '状态', dataIndex: 'status', width: 100,
|
||||
render: (v: string) => {
|
||||
const cfg = STATUS_MAP[v] || { color: 'default', text: v };
|
||||
return <Tag color={cfg.color}>{cfg.text}</Tag>;
|
||||
const columns: ColumnsType<ClassItem> = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: '班级名称',
|
||||
dataIndex: 'name',
|
||||
width: 120,
|
||||
sorter: (a, b) => a.name.localeCompare(b.name),
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '操作', width: 280,
|
||||
render: (_: unknown, r: ClassItem) => (
|
||||
<Space>
|
||||
<Button size="small" icon={<TeamOutlined />} onClick={() => navigate(`/classes/${r.id}`)}>
|
||||
详情
|
||||
</Button>
|
||||
<PermissionButton permission="class:edit" size="small" onClick={() => handleEdit(r)}>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
{r.isArchived ? (
|
||||
<Popconfirm title="确认恢复?" onConfirm={() => handleArchive(r.id, false)}>
|
||||
<PermissionButton permission="class:edit" size="small">恢复</PermissionButton>
|
||||
</Popconfirm>
|
||||
) : (
|
||||
<Popconfirm title="归档后可恢复,确认归档?" onConfirm={() => handleArchive(r.id, true)}>
|
||||
<PermissionButton permission="class:edit" size="small">归档</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
<Popconfirm title="确认删除?" onConfirm={() => handleDelete(r.id)}>
|
||||
<PermissionButton permission="class:delete" size="small" danger>
|
||||
删除
|
||||
{ title: '编码', dataIndex: 'code', width: 140 },
|
||||
{
|
||||
title: '班型',
|
||||
dataIndex: 'classType',
|
||||
width: 100,
|
||||
render: (v: string) => <Tag>{TYPE_MAP[v] || v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '开班日期',
|
||||
dataIndex: 'startDate',
|
||||
width: 110,
|
||||
render: (v: string | null) => v || '-',
|
||||
},
|
||||
{
|
||||
title: '学员',
|
||||
width: 100,
|
||||
render: (_: unknown, r: ClassItem) => `${r.studentCount || 0}/${r.maxStudents || '-'}`,
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 100,
|
||||
render: (v: string) => {
|
||||
const cfg = STATUS_MAP[v] || { color: 'default', text: v };
|
||||
return <Tag color={cfg.color}>{cfg.text}</Tag>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 280,
|
||||
render: (_: unknown, r: ClassItem) => (
|
||||
<Space>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<TeamOutlined />}
|
||||
onClick={() => navigate(`/classes/${r.id}`)}
|
||||
>
|
||||
详情
|
||||
</Button>
|
||||
<PermissionButton permission="class:edit" size="small" onClick={() => handleEdit(r)}>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
], []);
|
||||
{r.isArchived ? (
|
||||
<Popconfirm title="确认恢复?" onConfirm={() => handleArchive(r.id, false)}>
|
||||
<PermissionButton permission="class:edit" size="small">
|
||||
恢复
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
) : (
|
||||
<Popconfirm
|
||||
title="归档后可恢复,确认归档?"
|
||||
onConfirm={() => handleArchive(r.id, true)}
|
||||
>
|
||||
<PermissionButton permission="class:edit" size="small">
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<Space style={{ marginBottom: 16 }} wrap>
|
||||
<Space
|
||||
style={{ marginBottom: 16 }}
|
||||
wrap
|
||||
className="responsive-toolbar responsive-toolbar--single"
|
||||
>
|
||||
<Input
|
||||
placeholder="搜索名称/编码"
|
||||
prefix={<SearchOutlined />}
|
||||
@@ -244,7 +270,12 @@ const ClassesPage: React.FC = () => {
|
||||
onChange={setFilterStatus}
|
||||
options={Object.entries(STATUS_MAP).map(([k, v]) => ({ value: k, label: v.text }))}
|
||||
/>
|
||||
<PermissionButton permission="class:create" type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
|
||||
<PermissionButton
|
||||
permission="class:create"
|
||||
type="primary"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={handleCreate}
|
||||
>
|
||||
创建班级
|
||||
</PermissionButton>
|
||||
<span style={{ marginLeft: 8 }}>
|
||||
@@ -302,7 +333,9 @@ const ClassesPage: React.FC = () => {
|
||||
</Form.Item>
|
||||
</Space>
|
||||
<Form.Item name="status" label="状态" initialValue="enrolling">
|
||||
<Select options={Object.entries(STATUS_MAP).map(([k, v]) => ({ value: k, label: v.text }))} />
|
||||
<Select
|
||||
options={Object.entries(STATUS_MAP).map(([k, v]) => ({ value: k, label: v.text }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={3} />
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
buildTeacherCandidateLabel,
|
||||
buildTeacherCandidateOptions,
|
||||
isTeacherCandidate,
|
||||
type TeacherCandidateUser,
|
||||
} from './teacher-candidate';
|
||||
|
||||
const baseUser = (overrides: Partial<TeacherCandidateUser> = {}): TeacherCandidateUser => ({
|
||||
id: 1,
|
||||
username: 'teacher',
|
||||
name: '测试老师',
|
||||
isActive: true,
|
||||
isArchived: false,
|
||||
studentStatus: null,
|
||||
roles: [{ code: 'teacher', name: '任课老师' }],
|
||||
profile: { subjects: ['数学', '物理'] },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('class teacher candidates', () => {
|
||||
it('keeps non-teacher staff roles because class duty is selected separately', () => {
|
||||
expect(
|
||||
isTeacherCandidate(baseUser({ roles: [{ code: 'academic', name: '教务管理员' }] })),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps staff-linked accounts so they can serve as head or life teachers', () => {
|
||||
expect(isTeacherCandidate(baseUser({ studentStatus: 'staff' }))).toBe(true);
|
||||
});
|
||||
|
||||
it('excludes active students, disabled, archived, and super-admin accounts', () => {
|
||||
const users = [
|
||||
baseUser({ id: 1, studentStatus: 'active' }),
|
||||
baseUser({ id: 2, isActive: false }),
|
||||
baseUser({ id: 3, isArchived: true }),
|
||||
baseUser({
|
||||
id: 4,
|
||||
roles: [{ code: 'super_admin', name: '超级管理员' }],
|
||||
}),
|
||||
];
|
||||
|
||||
expect(buildTeacherCandidateOptions(users)).toEqual([]);
|
||||
});
|
||||
|
||||
it('shows real name, username, system role, and teaching subjects', () => {
|
||||
expect(buildTeacherCandidateLabel(baseUser())).toBe(
|
||||
'测试老师(teacher) · 任课老师 · 数学/物理',
|
||||
);
|
||||
});
|
||||
});
|
||||
44
apps/admin/src/pages/Classes/teacher-candidate.ts
Normal file
44
apps/admin/src/pages/Classes/teacher-candidate.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
export interface TeacherCandidateRole {
|
||||
code?: string | null;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface TeacherCandidateUser {
|
||||
id: number;
|
||||
username: string;
|
||||
name?: string | null;
|
||||
isActive: boolean;
|
||||
isArchived: boolean;
|
||||
studentStatus?: string | null;
|
||||
roles?: TeacherCandidateRole[];
|
||||
profile?: { subjects?: string[] } | null;
|
||||
}
|
||||
|
||||
const isSuperAdminRole = (role: TeacherCandidateRole) =>
|
||||
role.code === 'super_admin' || role.name === '超级管理员' || role.name === '超管';
|
||||
|
||||
export const isTeacherCandidate = (user: TeacherCandidateUser) => {
|
||||
if (!user.isActive || user.isArchived) return false;
|
||||
if (user.studentStatus && user.studentStatus !== 'staff') return false;
|
||||
return !(user.roles || []).some(isSuperAdminRole);
|
||||
};
|
||||
|
||||
export const buildTeacherCandidateLabel = (user: TeacherCandidateUser) => {
|
||||
const displayName = user.name?.trim();
|
||||
const identity =
|
||||
displayName && displayName !== user.username
|
||||
? `${displayName}(${user.username})`
|
||||
: user.username;
|
||||
const roleNames = [...new Set((user.roles || []).map((role) => role.name).filter(Boolean))];
|
||||
const subjects = [
|
||||
...new Set((user.profile?.subjects || []).map((subject) => subject.trim()).filter(Boolean)),
|
||||
];
|
||||
|
||||
return [identity, roleNames.join('/'), subjects.join('/')].filter(Boolean).join(' · ');
|
||||
};
|
||||
|
||||
export const buildTeacherCandidateOptions = (users: TeacherCandidateUser[]) =>
|
||||
users.filter(isTeacherCandidate).map((user) => ({
|
||||
value: user.id,
|
||||
label: buildTeacherCandidateLabel(user),
|
||||
}));
|
||||
@@ -15,7 +15,13 @@ import {
|
||||
Tooltip,
|
||||
Empty,
|
||||
} from 'antd';
|
||||
import { PlusOutlined, UploadOutlined, DeleteOutlined, FileTextOutlined, StopOutlined, CheckOutlined } from '@ant-design/icons';
|
||||
import {
|
||||
PlusOutlined,
|
||||
UploadOutlined,
|
||||
FileTextOutlined,
|
||||
StopOutlined,
|
||||
CheckOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import dayjs, { Dayjs } from 'dayjs';
|
||||
import api from '../../api';
|
||||
import { downloadBlob } from '../../utils/download';
|
||||
@@ -211,10 +217,10 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/classroom-rentals/${id}`);
|
||||
message.success('已删除');
|
||||
message.success('已归档');
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '删除失败');
|
||||
message.error(e?.message || '归档失败');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -239,10 +245,10 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
const handleDeleteContract = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/classroom-rentals/${id}/contract`);
|
||||
message.success('合同已删除');
|
||||
message.success('合同已移除');
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '删除失败');
|
||||
message.error(e?.message || '移除失败');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -350,8 +356,8 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
下载
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Popconfirm title="删除合同文件?" onConfirm={() => handleDeleteContract(r.id)}>
|
||||
<Button size="small" danger icon={<DeleteOutlined />} aria-label="删除合同文件" />
|
||||
<Popconfirm title="移除合同文件?" onConfirm={() => handleDeleteContract(r.id)}>
|
||||
<Button size="small" danger icon={<StopOutlined />} aria-label="移除合同文件" />
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
) : (
|
||||
@@ -392,17 +398,36 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
<Space>
|
||||
{record.effectiveStatus === 'active' && (
|
||||
<>
|
||||
<PermissionButton permission="rental:edit" size="small" onClick={() => openEdit(record)}>
|
||||
<PermissionButton
|
||||
permission="rental:edit"
|
||||
size="small"
|
||||
onClick={() => openEdit(record)}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<Popconfirm title="确定取消该租赁?" onConfirm={() => handleRentalAction(record.id, 'cancel')}>
|
||||
<PermissionButton permission="rental:edit" size="small" danger icon={<StopOutlined />}>
|
||||
<Popconfirm
|
||||
title="确定取消该租赁?"
|
||||
onConfirm={() => handleRentalAction(record.id, 'cancel')}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="rental:edit"
|
||||
size="small"
|
||||
danger
|
||||
icon={<StopOutlined />}
|
||||
>
|
||||
取消
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
{!dayjs(record.startDate).isAfter(dayjs(), 'day') && (
|
||||
<Popconfirm title="确定今天结束该租赁?" onConfirm={() => handleRentalAction(record.id, 'end')}>
|
||||
<PermissionButton permission="rental:edit" size="small" icon={<CheckOutlined />}>
|
||||
<Popconfirm
|
||||
title="确定今天结束该租赁?"
|
||||
onConfirm={() => handleRentalAction(record.id, 'end')}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="rental:edit"
|
||||
size="small"
|
||||
icon={<CheckOutlined />}
|
||||
>
|
||||
结束
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
@@ -410,8 +435,13 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
</>
|
||||
)}
|
||||
{record.effectiveStatus !== 'active' && (
|
||||
<Popconfirm title="确定删除该租赁订单?合同文件将一并删除。" onConfirm={() => handleDelete(record.id)}>
|
||||
<PermissionButton permission="rental:delete" size="small" danger>删除</PermissionButton>
|
||||
<Popconfirm
|
||||
title="确定归档该租赁订单?合同文件会保留。"
|
||||
onConfirm={() => handleDelete(record.id)}
|
||||
>
|
||||
<PermissionButton permission="rental:delete" size="small" danger>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
@@ -511,10 +541,12 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
optionFilterProp="label"
|
||||
placeholder="选择教室"
|
||||
onChange={handleClassroomChange}
|
||||
options={classrooms.filter((c) => c.status === 'available').map((c) => ({
|
||||
value: c.id,
|
||||
label: `${c.building ? c.building + ' · ' : ''}${c.name}(${c.roomType})`,
|
||||
}))}
|
||||
options={classrooms
|
||||
.filter((c) => c.status === 'available')
|
||||
.map((c) => ({
|
||||
value: c.id,
|
||||
label: `${c.building ? c.building + ' · ' : ''}${c.name}(${c.roomType})`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="lessorOrganizationId" label="出租机构" tooltip="默认由本机构出租">
|
||||
@@ -559,10 +591,10 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="dailyRate" label="日租金(可选)">
|
||||
<InputNumber min={0} precision={2} style={{ width: '100%' }} prefix="¥" />
|
||||
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} prefix="¥" />
|
||||
</Form.Item>
|
||||
<Form.Item name="totalAmount" label="合同总额(可选)">
|
||||
<InputNumber min={0} precision={2} style={{ width: '100%' }} prefix="¥" />
|
||||
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} prefix="¥" />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} />
|
||||
|
||||
@@ -60,8 +60,16 @@ const ClassroomsPage: React.FC = () => {
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
let result = data;
|
||||
if (searchText) { const s = searchText.toLowerCase(); result = result.filter((d: Record<string, unknown>) => (typeof d.name === 'string' && d.name.toLowerCase().includes(s)) || (typeof d.building === 'string' && d.building.toLowerCase().includes(s))); }
|
||||
if (filterStatus) result = result.filter((d: Record<string, unknown>) => d.effectiveStatus === filterStatus);
|
||||
if (searchText) {
|
||||
const s = searchText.toLowerCase();
|
||||
result = result.filter(
|
||||
(d: Record<string, unknown>) =>
|
||||
(typeof d.name === 'string' && d.name.toLowerCase().includes(s)) ||
|
||||
(typeof d.building === 'string' && d.building.toLowerCase().includes(s)),
|
||||
);
|
||||
}
|
||||
if (filterStatus)
|
||||
result = result.filter((d: Record<string, unknown>) => d.effectiveStatus === filterStatus);
|
||||
return result;
|
||||
}, [data, searchText, filterStatus]);
|
||||
|
||||
@@ -140,72 +148,98 @@ const ClassroomsPage: React.FC = () => {
|
||||
.catch(() => message.error('下载失败'));
|
||||
};
|
||||
|
||||
const columns = useMemo(() => [
|
||||
{
|
||||
title: '教室名', width: 120,
|
||||
dataIndex: 'name',
|
||||
sorter: (a: any, b: any) => a.name.localeCompare(b.name),
|
||||
},
|
||||
{ title: '楼栋', dataIndex: 'building', width: 80 },
|
||||
{ title: '楼层', dataIndex: 'floor', width: 80 },
|
||||
{
|
||||
title: '类型', width: 90,
|
||||
dataIndex: 'roomType',
|
||||
render: (v: string) => <Tag color={typeColor[v] || 'default'}>{v || '-'}</Tag>,
|
||||
},
|
||||
{ title: '容量', dataIndex: 'capacity', width: 80 },
|
||||
{
|
||||
title: '状态', width: 100,
|
||||
dataIndex: 'status',
|
||||
render: (_s: string, record: { effectiveStatus?: string; status: string; currentUsage?: CurrentUsage | null }) => {
|
||||
const effectiveStatus = record.effectiveStatus || record.status;
|
||||
return (
|
||||
<Tooltip title={record.currentUsage ? `${record.currentUsage.title} (${record.currentUsage.startTime}-${record.currentUsage.endTime})` : undefined}>
|
||||
<Tag color={statusMap[effectiveStatus]?.color}>{statusMap[effectiveStatus]?.text || effectiveStatus}</Tag>
|
||||
</Tooltip>
|
||||
);
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: '教室名',
|
||||
width: 120,
|
||||
dataIndex: 'name',
|
||||
sorter: (a: any, b: any) => a.name.localeCompare(b.name),
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 180,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
{record.status === 'archived' ? (
|
||||
<Popconfirm title="确定恢复此教室?" onConfirm={() => handleRestore(record.id)}>
|
||||
<PermissionButton permission="classroom:edit" size="small" icon={<UndoOutlined />} type="link">
|
||||
恢复
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
) : (
|
||||
<>
|
||||
<PermissionButton
|
||||
permission="classroom:edit"
|
||||
size="small"
|
||||
onClick={() => {
|
||||
setEditing(record);
|
||||
form.setFieldsValue(record);
|
||||
setModalOpen(true);
|
||||
}}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<Popconfirm
|
||||
title="归档后数据保留,可随时恢复。存在进行中的租赁将无法归档。"
|
||||
onConfirm={() => handleArchive(record.id)}
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
>
|
||||
<PermissionButton permission="classroom:delete" size="small" icon={<InboxOutlined />}>
|
||||
归档
|
||||
{ title: '楼栋', dataIndex: 'building', width: 80 },
|
||||
{ title: '楼层', dataIndex: 'floor', width: 80 },
|
||||
{
|
||||
title: '类型',
|
||||
width: 90,
|
||||
dataIndex: 'roomType',
|
||||
render: (v: string) => <Tag color={typeColor[v] || 'default'}>{v || '-'}</Tag>,
|
||||
},
|
||||
{ title: '容量', dataIndex: 'capacity', width: 80 },
|
||||
{
|
||||
title: '状态',
|
||||
width: 100,
|
||||
dataIndex: 'status',
|
||||
render: (
|
||||
_s: string,
|
||||
record: { effectiveStatus?: string; status: string; currentUsage?: CurrentUsage | null },
|
||||
) => {
|
||||
const effectiveStatus = record.effectiveStatus || record.status;
|
||||
return (
|
||||
<Tooltip
|
||||
title={
|
||||
record.currentUsage
|
||||
? `${record.currentUsage.title} (${record.currentUsage.startTime}-${record.currentUsage.endTime})`
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<Tag color={statusMap[effectiveStatus]?.color}>
|
||||
{statusMap[effectiveStatus]?.text || effectiveStatus}
|
||||
</Tag>
|
||||
</Tooltip>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 180,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
{record.status === 'archived' ? (
|
||||
<Popconfirm title="确定恢复此教室?" onConfirm={() => handleRestore(record.id)}>
|
||||
<PermissionButton
|
||||
permission="classroom:edit"
|
||||
size="small"
|
||||
icon={<UndoOutlined />}
|
||||
type="link"
|
||||
>
|
||||
恢复
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
], []);
|
||||
) : (
|
||||
<>
|
||||
<PermissionButton
|
||||
permission="classroom:edit"
|
||||
size="small"
|
||||
onClick={() => {
|
||||
setEditing(record);
|
||||
form.setFieldsValue(record);
|
||||
setModalOpen(true);
|
||||
}}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<Popconfirm
|
||||
title="归档后数据保留,可随时恢复。存在进行中的租赁将无法归档。"
|
||||
onConfirm={() => handleArchive(record.id)}
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
>
|
||||
<PermissionButton
|
||||
permission="classroom:delete"
|
||||
size="small"
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -228,7 +262,20 @@ const ClassroomsPage: React.FC = () => {
|
||||
if (!e.target.value) setSearchText('');
|
||||
}}
|
||||
/>
|
||||
<Select placeholder="状态" allowClear style={{ width: 110 }} value={filterStatus} onChange={setFilterStatus} options={[{value:'available',label:'可用'},{value:'in_use',label:'使用中'},{value:'reserved',label:'已预留'},{value:'maintenance',label:'维护中'},{value:'archived',label:'已归档'}]} />
|
||||
<Select
|
||||
placeholder="状态"
|
||||
allowClear
|
||||
style={{ width: 110 }}
|
||||
value={filterStatus}
|
||||
onChange={setFilterStatus}
|
||||
options={[
|
||||
{ value: 'available', label: '可用' },
|
||||
{ value: 'in_use', label: '使用中' },
|
||||
{ value: 'reserved', label: '已预留' },
|
||||
{ value: 'maintenance', label: '维护中' },
|
||||
{ value: 'archived', label: '已归档' },
|
||||
]}
|
||||
/>
|
||||
<Button
|
||||
type={showArchived ? 'primary' : 'default'}
|
||||
onClick={() => setShowArchived(!showArchived)}
|
||||
@@ -249,7 +296,26 @@ const ClassroomsPage: React.FC = () => {
|
||||
>
|
||||
添加教室
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="classroom:view" icon={<DownloadOutlined />} onClick={() => { const baseURL = '/api'; const token = localStorage.getItem('token'); fetch(`${baseURL}/classrooms/export`, { headers: { Authorization: `Bearer ${token}` } }).then(r => r.blob()).then(b => { const a = document.createElement('a'); a.href = URL.createObjectURL(b); a.download = '教室使用报表.xlsx'; a.click(); }); }}>导出报表</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="classroom:view"
|
||||
icon={<DownloadOutlined />}
|
||||
onClick={() => {
|
||||
const baseURL = '/api';
|
||||
const token = localStorage.getItem('token');
|
||||
fetch(`${baseURL}/classrooms/export`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
.then((r) => r.blob())
|
||||
.then((b) => {
|
||||
const a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(b);
|
||||
a.download = '教室使用报表.xlsx';
|
||||
a.click();
|
||||
});
|
||||
}}
|
||||
>
|
||||
导出报表
|
||||
</PermissionButton>
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildDepositStudentOption } from './deposit-student-option';
|
||||
import { buildDepositStudentOption, buildDepositStudentOptions } from './deposit-student-option';
|
||||
|
||||
describe('deposit student option', () => {
|
||||
it('uses the student number as the non-sensitive identifier', () => {
|
||||
expect(
|
||||
buildDepositStudentOption({ id: 23, name: '张三', studentNo: 'S2026001' }),
|
||||
).toEqual({
|
||||
expect(buildDepositStudentOption({ id: 23, name: '张三', studentNo: 'S2026001' })).toEqual({
|
||||
value: 23,
|
||||
label: '张三 (S2026001)',
|
||||
});
|
||||
@@ -17,4 +15,27 @@ describe('deposit student option', () => {
|
||||
label: '张三 (#23)',
|
||||
});
|
||||
});
|
||||
|
||||
it('uses lookup rows without requiring a status field', () => {
|
||||
expect(buildDepositStudentOptions([{ id: 23, name: '张三', studentNo: 'S2026001' }])).toEqual([
|
||||
{
|
||||
value: 23,
|
||||
label: '张三 (S2026001)',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('includes room type when available', () => {
|
||||
expect(
|
||||
buildDepositStudentOption({
|
||||
id: 23,
|
||||
name: '张三',
|
||||
studentNo: 'S2026001',
|
||||
roomType: '四人间',
|
||||
}),
|
||||
).toEqual({
|
||||
value: 23,
|
||||
label: '张三 (S2026001) - 四人间',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,9 +2,13 @@ export interface DepositStudentLookup {
|
||||
id: number;
|
||||
name: string;
|
||||
studentNo?: string | null;
|
||||
roomType?: string | null;
|
||||
}
|
||||
|
||||
export const buildDepositStudentOption = (student: DepositStudentLookup) => ({
|
||||
value: student.id,
|
||||
label: `${student.name} (${student.studentNo || `#${student.id}`})`,
|
||||
label: `${student.name} (${student.studentNo || `#${student.id}`})${student.roomType ? ` - ${student.roomType}` : ''}`,
|
||||
});
|
||||
|
||||
export const buildDepositStudentOptions = (students: DepositStudentLookup[]) =>
|
||||
students.map(buildDepositStudentOption);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Table,
|
||||
Modal,
|
||||
@@ -14,18 +14,17 @@ import {
|
||||
Card,
|
||||
Empty,
|
||||
} from 'antd';
|
||||
import { PlusOutlined, DeleteOutlined, DollarOutlined } from '@ant-design/icons';
|
||||
import { PlusOutlined, InboxOutlined, DollarOutlined, TeamOutlined } from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { buildDepositStudentOption } from './deposit-student-option';
|
||||
import { buildDepositStudentOptions, type DepositStudentLookup } from './deposit-student-option';
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
paid: { text: '已缴', color: 'green' },
|
||||
paid: { text: '有余额', color: 'green' },
|
||||
refunded: { text: '已全退', color: 'blue' },
|
||||
partial_refund: { text: '部分退还', color: 'orange' },
|
||||
deducted: { text: '已全扣', color: 'red' },
|
||||
depleted: { text: '已扣完', color: 'red' },
|
||||
};
|
||||
|
||||
const installmentStatusMap: Record<string, { text: string; color: string }> = {
|
||||
@@ -33,49 +32,152 @@ const installmentStatusMap: Record<string, { text: string; color: string }> = {
|
||||
paid: { text: '已缴', color: 'green' },
|
||||
};
|
||||
|
||||
const roomTypeOptions = [
|
||||
{ value: '单人间', label: '单人间' },
|
||||
{ value: '四人间', label: '四人间' },
|
||||
];
|
||||
|
||||
const suggestedDepositByRoomType: Record<string, number> = {
|
||||
单人间: 200,
|
||||
四人间: 100,
|
||||
};
|
||||
|
||||
interface DepositRecord {
|
||||
id: number;
|
||||
studentId: number;
|
||||
amount: number;
|
||||
status: string;
|
||||
paidDate: string;
|
||||
refundDate?: string | null;
|
||||
notes?: string | null;
|
||||
installments?: Array<{
|
||||
id: number;
|
||||
amount: number;
|
||||
dueDate: string;
|
||||
paidDate?: string | null;
|
||||
status: string;
|
||||
}>;
|
||||
student?: DepositStudentLookup;
|
||||
}
|
||||
|
||||
interface EligibleStudent {
|
||||
studentId: number;
|
||||
studentName: string;
|
||||
studentNo?: string | null;
|
||||
roomId: number;
|
||||
roomNumber: string;
|
||||
building?: string | null;
|
||||
roomType?: string | null;
|
||||
capacity: number;
|
||||
depositAmount: number;
|
||||
}
|
||||
|
||||
const isFormValidationError = (error: unknown) =>
|
||||
typeof error === 'object'
|
||||
&& error !== null
|
||||
&& Array.isArray((error as { errorFields?: unknown }).errorFields);
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
Array.isArray((error as { errorFields?: unknown }).errorFields);
|
||||
|
||||
const DepositsPage: React.FC = () => {
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [students, setStudents] = useState<any[]>([]);
|
||||
const [data, setData] = useState<DepositRecord[]>([]);
|
||||
const [students, setStudents] = useState<DepositStudentLookup[]>([]);
|
||||
const [eligibleStudents, setEligibleStudents] = useState<EligibleStudent[]>([]);
|
||||
const [selectedEligibleStudentIds, setSelectedEligibleStudentIds] = useState<number[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [eligibleLoading, setEligibleLoading] = useState(false);
|
||||
const [createModal, setCreateModal] = useState(false);
|
||||
const [refundModal, setRefundModal] = useState<any>(null);
|
||||
const [detailModal, setDetailModal] = useState<any>(null);
|
||||
const [batchModal, setBatchModal] = useState(false);
|
||||
const [refundModal, setRefundModal] = useState<DepositRecord | null>(null);
|
||||
const [detailModal, setDetailModal] = useState<DepositRecord | null>(null);
|
||||
const [installmentModal, setInstallmentModal] = useState<number | null>(null);
|
||||
const [createForm] = Form.useForm();
|
||||
const [batchForm] = Form.useForm();
|
||||
const [refundForm] = Form.useForm();
|
||||
const [installmentForm] = Form.useForm();
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
|
||||
const [filterRoomType, setFilterRoomType] = useState<string | undefined>(undefined);
|
||||
const [batchRoomType, setBatchRoomType] = useState<string>('四人间');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const fetchData = async () => {
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [d, s]: any[] = await Promise.all([
|
||||
api.get('/deposits'),
|
||||
api.get('/deposits/student-lookups'),
|
||||
const [d, s] = await Promise.all([
|
||||
api.get<DepositRecord[]>('/deposits'),
|
||||
api.get<DepositStudentLookup[]>('/deposits/student-lookups'),
|
||||
]);
|
||||
setData(d);
|
||||
setStudents(s);
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载失败,请稍后重试');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
}, []);
|
||||
|
||||
const fetchEligibleStudents = useCallback(async (roomType?: string) => {
|
||||
setEligibleLoading(true);
|
||||
try {
|
||||
const params = roomType ? `?roomType=${encodeURIComponent(roomType)}` : '';
|
||||
const rows = await api.get<EligibleStudent[]>(`/deposits/eligible-students${params}`);
|
||||
setEligibleStudents(rows);
|
||||
setSelectedEligibleStudentIds(rows.map((item) => item.studentId));
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载在住人员失败');
|
||||
} finally {
|
||||
setEligibleLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, []);
|
||||
}, [fetchData]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchEligibleStudents(filterRoomType);
|
||||
}, [fetchEligibleStudents, filterRoomType]);
|
||||
|
||||
const depositByStudentId = useMemo(() => {
|
||||
const map = new Map<number, DepositRecord>();
|
||||
data.forEach((item) => map.set(item.studentId, item));
|
||||
return map;
|
||||
}, [data]);
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
return data.filter((d: any) => {
|
||||
if (filterRoomType) {
|
||||
const s = searchText.trim().toLowerCase();
|
||||
return eligibleStudents
|
||||
.filter(
|
||||
(item) =>
|
||||
!s ||
|
||||
item.studentName.toLowerCase().includes(s) ||
|
||||
item.studentNo?.toLowerCase().includes(s),
|
||||
)
|
||||
.map((item) => {
|
||||
const deposit = depositByStudentId.get(item.studentId);
|
||||
return {
|
||||
id: deposit?.id ?? `eligible-${item.studentId}`,
|
||||
studentId: item.studentId,
|
||||
amount: deposit?.amount ?? item.depositAmount ?? 0,
|
||||
status: deposit?.status ?? 'unpaid',
|
||||
paidDate: deposit?.paidDate ?? '',
|
||||
refundDate: deposit?.refundDate,
|
||||
notes: deposit?.notes,
|
||||
installments: deposit?.installments ?? [],
|
||||
student: {
|
||||
id: item.studentId,
|
||||
name: item.studentName,
|
||||
studentNo: item.studentNo,
|
||||
roomType: item.roomType,
|
||||
},
|
||||
roomNumber: item.roomNumber,
|
||||
building: item.building,
|
||||
roomType: item.roomType,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
return data.filter((d) => {
|
||||
if (searchText) {
|
||||
const s = searchText.toLowerCase();
|
||||
if (!d.student?.name?.toLowerCase().includes(s)) return false;
|
||||
@@ -83,15 +185,26 @@ const DepositsPage: React.FC = () => {
|
||||
if (filterStatus && d.status !== filterStatus) return false;
|
||||
return true;
|
||||
});
|
||||
}, [data, searchText, filterStatus]);
|
||||
}, [data, depositByStudentId, eligibleStudents, filterRoomType, filterStatus, searchText]);
|
||||
|
||||
const studentOptions = useMemo(
|
||||
() =>
|
||||
students
|
||||
.filter((s: any) => s.status === 'active')
|
||||
.map(buildDepositStudentOption),
|
||||
[students],
|
||||
);
|
||||
const studentOptions = useMemo(() => buildDepositStudentOptions(students), [students]);
|
||||
|
||||
const openBatchModal = (roomType = filterRoomType || '四人间') => {
|
||||
const amount = suggestedDepositByRoomType[roomType] ?? 100;
|
||||
setBatchRoomType(roomType);
|
||||
batchForm.resetFields();
|
||||
batchForm.setFieldsValue({ roomType, amount, paidDate: dayjs() });
|
||||
setBatchModal(true);
|
||||
fetchEligibleStudents(roomType);
|
||||
};
|
||||
|
||||
const handleBatchRoomTypeChange = (roomType: string) => {
|
||||
setBatchRoomType(roomType);
|
||||
batchForm.setFieldsValue({
|
||||
amount: suggestedDepositByRoomType[roomType] ?? batchForm.getFieldValue('amount') ?? 100,
|
||||
});
|
||||
fetchEligibleStudents(roomType);
|
||||
};
|
||||
|
||||
const handleCreate = async () => {
|
||||
setSaving(true);
|
||||
@@ -103,10 +216,40 @@ const DepositsPage: React.FC = () => {
|
||||
paidDate: values.paidDate.format('YYYY-MM-DD'),
|
||||
notes: values.notes,
|
||||
});
|
||||
message.success('押金记录已创建');
|
||||
message.success('押金金额已增加');
|
||||
setCreateModal(false);
|
||||
createForm.resetFields();
|
||||
fetchData();
|
||||
fetchEligibleStudents(filterRoomType);
|
||||
} catch (e: any) {
|
||||
if (!isFormValidationError(e)) {
|
||||
message.error(e?.message || '操作失败');
|
||||
}
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBatchCreate = async () => {
|
||||
if (selectedEligibleStudentIds.length === 0) {
|
||||
message.warning('请选择至少一名学生');
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const values = await batchForm.validateFields();
|
||||
await api.post('/deposits/batch', {
|
||||
studentIds: selectedEligibleStudentIds,
|
||||
amount: values.amount,
|
||||
paidDate: values.paidDate.format('YYYY-MM-DD'),
|
||||
notes: values.notes,
|
||||
roomType: values.roomType,
|
||||
});
|
||||
message.success(`已为 ${selectedEligibleStudentIds.length} 人批量收取押金`);
|
||||
setBatchModal(false);
|
||||
batchForm.resetFields();
|
||||
await fetchData();
|
||||
fetchEligibleStudents(filterRoomType);
|
||||
} catch (e: any) {
|
||||
if (!isFormValidationError(e)) {
|
||||
message.error(e?.message || '操作失败');
|
||||
@@ -117,19 +260,19 @@ const DepositsPage: React.FC = () => {
|
||||
};
|
||||
|
||||
const handleRefund = async () => {
|
||||
if (!refundModal) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const values = await refundForm.validateFields();
|
||||
await api.put(`/deposits/${refundModal.id}/refund`, {
|
||||
refundDate: values.refundDate.format('YYYY-MM-DD'),
|
||||
deductionAmount: values.deductionAmount || 0,
|
||||
deductionReason: values.deductionReason,
|
||||
notes: values.notes,
|
||||
});
|
||||
message.success('退还操作完成');
|
||||
setRefundModal(null);
|
||||
refundForm.resetFields();
|
||||
fetchData();
|
||||
fetchEligibleStudents(filterRoomType);
|
||||
} catch (e: any) {
|
||||
if (!isFormValidationError(e)) {
|
||||
message.error(e?.message || '操作失败');
|
||||
@@ -174,154 +317,269 @@ const DepositsPage: React.FC = () => {
|
||||
const handleDeleteInstallment = async (installmentId: number) => {
|
||||
try {
|
||||
await api.delete(`/deposits/installments/${installmentId}`);
|
||||
message.success('分期已删除');
|
||||
message.success('分期已归档');
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '操作失败');
|
||||
}
|
||||
};
|
||||
|
||||
const columns = useMemo(() => [
|
||||
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
|
||||
{ title: '押金金额', dataIndex: 'amount', width: 110, render: (v: number) => `¥${Number(v).toFixed(2)}` },
|
||||
{ title: '缴纳日期', dataIndex: 'paidDate', width: 110 },
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '退还金额',
|
||||
dataIndex: 'refundAmount',
|
||||
render: (v: any) => (v != null ? `¥${Number(v).toFixed(2)}` : '-'),
|
||||
},
|
||||
{
|
||||
title: '扣除金额',
|
||||
dataIndex: 'deductionAmount',
|
||||
render: (v: any) => (v > 0 ? `¥${Number(v).toFixed(2)}` : '-'),
|
||||
},
|
||||
{ title: '扣除原因', dataIndex: 'deductionReason', width: 120, render: (v: any) => v || '-' },
|
||||
{ title: '退还日期', dataIndex: 'refundDate', width: 110, render: (v: any) => v || '-' },
|
||||
{ title: '备注', dataIndex: 'notes', width: 120, render: (v: any) => v || '-' },
|
||||
{
|
||||
title: '操作',
|
||||
width: 240,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="deposit:view"
|
||||
size="small"
|
||||
onClick={() => {
|
||||
setDetailModal(record);
|
||||
}}
|
||||
>
|
||||
详情
|
||||
</PermissionButton>
|
||||
{record.status === 'paid' && (
|
||||
<>
|
||||
<PermissionButton
|
||||
permission="deposit:refund"
|
||||
size="small"
|
||||
type="primary"
|
||||
onClick={() => {
|
||||
setRefundModal(record);
|
||||
refundForm.setFieldsValue({ refundDate: dayjs(), deductionAmount: 0 });
|
||||
}}
|
||||
>
|
||||
退还
|
||||
</PermissionButton>
|
||||
</>
|
||||
)}
|
||||
<Popconfirm
|
||||
title="确定删除?"
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await api.delete(`/deposits/${record.id}`);
|
||||
message.success('删除成功');
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '删除失败');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="deposit:delete"
|
||||
size="small"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
>
|
||||
删除
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
], [fetchData]);
|
||||
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{ title: '学生', width: 120, render: (_: unknown, r: any) => r.student?.name || '-' },
|
||||
{
|
||||
title: '当前可用押金',
|
||||
dataIndex: 'amount',
|
||||
width: 130,
|
||||
render: (v: number) => `¥${Number(v || 0).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '房间',
|
||||
width: 120,
|
||||
render: (_: unknown, r: any) =>
|
||||
r.roomNumber ? `${r.building ? `${r.building}-` : ''}${r.roomNumber}` : '-',
|
||||
},
|
||||
{ title: '房型', dataIndex: 'roomType', width: 100, render: (v: string) => v || '-' },
|
||||
{ title: '最近收取日期', dataIndex: 'paidDate', width: 120, render: (v: string) => v || '-' },
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
render: (s: string) =>
|
||||
s === 'unpaid' ? (
|
||||
<Tag color="default">未缴</Tag>
|
||||
) : (
|
||||
<Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>
|
||||
),
|
||||
},
|
||||
{ title: '退还日期', dataIndex: 'refundDate', width: 110, render: (v: unknown) => v || '-' },
|
||||
{ title: '备注', dataIndex: 'notes', width: 120, render: (v: unknown) => v || '-' },
|
||||
{
|
||||
title: '操作',
|
||||
width: 240,
|
||||
render: (_: unknown, record: any) => {
|
||||
const hasDeposit = typeof record.id === 'number';
|
||||
return (
|
||||
<Space>
|
||||
{hasDeposit && (
|
||||
<PermissionButton
|
||||
permission="deposit:view"
|
||||
size="small"
|
||||
onClick={() => {
|
||||
setDetailModal(record);
|
||||
}}
|
||||
>
|
||||
详情
|
||||
</PermissionButton>
|
||||
)}
|
||||
{record.status === 'paid' && hasDeposit && (
|
||||
<PermissionButton
|
||||
permission="deposit:refund"
|
||||
size="small"
|
||||
type="primary"
|
||||
onClick={() => {
|
||||
setRefundModal(record);
|
||||
refundForm.setFieldsValue({ refundDate: dayjs() });
|
||||
}}
|
||||
>
|
||||
退还
|
||||
</PermissionButton>
|
||||
)}
|
||||
{hasDeposit && (
|
||||
<Popconfirm
|
||||
title="确定归档?"
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await api.delete(`/deposits/${record.id}`);
|
||||
message.success('归档成功');
|
||||
fetchData();
|
||||
fetchEligibleStudents(filterRoomType);
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '归档失败');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="deposit:delete"
|
||||
size="small"
|
||||
danger
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
[fetchData, fetchEligibleStudents, filterRoomType, refundForm],
|
||||
);
|
||||
|
||||
const eligibleColumns = [
|
||||
{
|
||||
title: '学生',
|
||||
render: (_: unknown, r: EligibleStudent) =>
|
||||
`${r.studentName} (${r.studentNo || `#${r.studentId}`})`,
|
||||
},
|
||||
{
|
||||
title: '房间',
|
||||
render: (_: unknown, r: EligibleStudent) =>
|
||||
`${r.building ? `${r.building}-` : ''}${r.roomNumber}`,
|
||||
},
|
||||
{ title: '房型', dataIndex: 'roomType' },
|
||||
{
|
||||
title: '当前押金',
|
||||
dataIndex: 'depositAmount',
|
||||
render: (v: number) => `¥${Number(v || 0).toFixed(2)}`,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<Space wrap>
|
||||
<Input.Search
|
||||
placeholder="搜索学生姓名"
|
||||
allowClear
|
||||
style={{ width: 180 }}
|
||||
onSearch={(v) => setSearchText(v)}
|
||||
onChange={(e) => {
|
||||
if (!e.target.value) setSearchText('');
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<Space wrap>
|
||||
<Input.Search
|
||||
placeholder="搜索学生姓名/学号"
|
||||
allowClear
|
||||
style={{ width: 180 }}
|
||||
onSearch={(v) => setSearchText(v)}
|
||||
onChange={(e) => {
|
||||
setSearchText(e.target.value);
|
||||
}}
|
||||
/>
|
||||
<Select
|
||||
placeholder="房型筛选"
|
||||
allowClear
|
||||
style={{ width: 130 }}
|
||||
value={filterRoomType}
|
||||
onChange={(v) => setFilterRoomType(v)}
|
||||
options={roomTypeOptions}
|
||||
/>
|
||||
<Select
|
||||
placeholder="状态筛选"
|
||||
allowClear
|
||||
style={{ width: 120 }}
|
||||
value={filterStatus}
|
||||
disabled={!!filterRoomType}
|
||||
onChange={(v) => setFilterStatus(v)}
|
||||
options={[
|
||||
{ value: 'paid', label: '有余额' },
|
||||
{ value: 'refunded', label: '已全退' },
|
||||
{ value: 'depleted', label: '已扣完' },
|
||||
]}
|
||||
/>
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<PermissionButton
|
||||
permission="deposit:create"
|
||||
icon={<TeamOutlined />}
|
||||
onClick={() => openBatchModal()}
|
||||
>
|
||||
按房型批量收取
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="deposit:create"
|
||||
type="primary"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => {
|
||||
createForm.resetFields();
|
||||
createForm.setFieldsValue({ amount: 500, paidDate: dayjs() });
|
||||
setCreateModal(true);
|
||||
}}
|
||||
>
|
||||
收取押金
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
</div>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={filteredData}
|
||||
rowKey="id"
|
||||
loading={loading || (!!filterRoomType && eligibleLoading)}
|
||||
scroll={{ x: 1200 }}
|
||||
pagination={{
|
||||
defaultPageSize: 15,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [15, 30, 50, 100],
|
||||
showTotal: (total) => `共 ${total} 条`,
|
||||
}}
|
||||
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
||||
/>
|
||||
<Select
|
||||
placeholder="状态筛选"
|
||||
allowClear
|
||||
style={{ width: 120 }}
|
||||
value={filterStatus}
|
||||
onChange={(v) => setFilterStatus(v)}
|
||||
options={[
|
||||
{ value: 'paid', label: '已缴' },
|
||||
{ value: 'refunded', label: '已全退' },
|
||||
{ value: 'partial_refund', label: '部分退还' },
|
||||
{ value: 'deducted', label: '已全扣' },
|
||||
]}
|
||||
/>
|
||||
</Space>
|
||||
<PermissionButton
|
||||
permission="deposit:create"
|
||||
type="primary"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => {
|
||||
createForm.resetFields();
|
||||
createForm.setFieldsValue({ amount: 500, paidDate: dayjs() });
|
||||
setCreateModal(true);
|
||||
}}
|
||||
>
|
||||
收取押金
|
||||
</PermissionButton>
|
||||
</div>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={filteredData}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
scroll={{ x: 1200 }}
|
||||
pagination={{
|
||||
defaultPageSize: 15,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [15, 30, 50, 100],
|
||||
showTotal: (total) => `共 ${total} 条`,
|
||||
}}
|
||||
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
||||
/>
|
||||
|
||||
{/* Batch Create Modal */}
|
||||
<Modal
|
||||
title="按房型批量收取押金"
|
||||
open={batchModal}
|
||||
onOk={handleBatchCreate}
|
||||
onCancel={() => setBatchModal(false)}
|
||||
okText="确认批量收取"
|
||||
confirmLoading={saving}
|
||||
okButtonProps={{ disabled: selectedEligibleStudentIds.length === 0 }}
|
||||
width={760}
|
||||
>
|
||||
<Form form={batchForm} layout="vertical">
|
||||
<Space style={{ width: '100%' }} align="start" wrap>
|
||||
<Form.Item
|
||||
name="roomType"
|
||||
label="房型"
|
||||
rules={[{ required: true, message: '请选择房型' }]}
|
||||
>
|
||||
<Select
|
||||
style={{ width: 140 }}
|
||||
options={roomTypeOptions}
|
||||
onChange={handleBatchRoomTypeChange}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="amount"
|
||||
label="每人收取金额(元)"
|
||||
rules={[{ required: true, message: '请输入金额' }]}
|
||||
>
|
||||
<InputNumber min={0.01} precision={2} style={{ width: 180 }} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="paidDate"
|
||||
label="收取日期"
|
||||
rules={[{ required: true, message: '请选择日期' }]}
|
||||
>
|
||||
<DatePicker style={{ width: 180 }} placeholder="选择收取日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
</Space>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} placeholder={`${batchRoomType}押金`} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
<div style={{ marginBottom: 8 }}>
|
||||
已选择 <strong>{selectedEligibleStudentIds.length}</strong> / {eligibleStudents.length} 人
|
||||
{suggestedDepositByRoomType[batchRoomType] && (
|
||||
<span style={{ color: '#999', marginLeft: 8 }}>
|
||||
建议金额:¥{suggestedDepositByRoomType[batchRoomType]}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Table
|
||||
size="small"
|
||||
columns={eligibleColumns}
|
||||
dataSource={eligibleStudents}
|
||||
rowKey="studentId"
|
||||
loading={eligibleLoading}
|
||||
locale={{ emptyText: <Empty description="暂无符合条件的在住人员" /> }}
|
||||
pagination={{ pageSize: 6, showSizeChanger: false }}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedEligibleStudentIds,
|
||||
onChange: (keys) => setSelectedEligibleStudentIds(keys as number[]),
|
||||
}}
|
||||
/>
|
||||
</Modal>
|
||||
|
||||
{/* Create Modal */}
|
||||
<Modal
|
||||
@@ -345,11 +603,11 @@ const DepositsPage: React.FC = () => {
|
||||
options={studentOptions}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="amount" label="押金金额(元)" rules={[{ required: true }]}>
|
||||
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
|
||||
<Form.Item name="amount" label="本次收取金额(元)" rules={[{ required: true }]}>
|
||||
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="paidDate" label="缴纳日期" rules={[{ required: true }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择缴纳日期" format="YYYY-MM-DD" />
|
||||
<Form.Item name="paidDate" label="收取日期" rules={[{ required: true }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择收取日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} />
|
||||
@@ -368,22 +626,11 @@ const DepositsPage: React.FC = () => {
|
||||
>
|
||||
<Form form={refundForm} layout="vertical">
|
||||
<div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 8 }}>
|
||||
押金金额: <strong>¥{Number(refundModal?.amount || 0).toFixed(2)}</strong>
|
||||
当前可用押金: <strong>¥{Number(refundModal?.amount || 0).toFixed(2)}</strong>
|
||||
</div>
|
||||
<Form.Item name="refundDate" label="退还日期" rules={[{ required: true }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择退还日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="deductionAmount" label="扣除金额(元)" extra="如无扣除填0">
|
||||
<InputNumber
|
||||
min={0}
|
||||
max={Number(refundModal?.amount || 500)}
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="deductionReason" label="扣除原因">
|
||||
<Input placeholder="如:房间损坏赔偿" />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
@@ -401,19 +648,34 @@ const DepositsPage: React.FC = () => {
|
||||
{detailModal && (
|
||||
<div>
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<p><strong>押金金额:</strong> ¥{Number(detailModal.amount).toFixed(2)}</p>
|
||||
<p><strong>缴纳日期:</strong> {detailModal.paidDate}</p>
|
||||
<p>
|
||||
<strong>当前可用押金:</strong> ¥{Number(detailModal.amount).toFixed(2)}
|
||||
</p>
|
||||
<p>
|
||||
<strong>最近收取日期:</strong> {detailModal.paidDate}
|
||||
</p>
|
||||
<p>
|
||||
<strong>状态:</strong>{' '}
|
||||
<Tag color={statusMap[detailModal.status]?.color}>
|
||||
{statusMap[detailModal.status]?.text || detailModal.status}
|
||||
</Tag>
|
||||
</p>
|
||||
{detailModal.notes && <p><strong>备注:</strong> {detailModal.notes}</p>}
|
||||
{detailModal.notes && (
|
||||
<p>
|
||||
<strong>备注:</strong> {detailModal.notes}
|
||||
</p>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Installments Section */}
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginBottom: 8,
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: 0 }}>分期记录</h4>
|
||||
<PermissionButton
|
||||
permission="deposit:edit"
|
||||
@@ -428,10 +690,10 @@ const DepositsPage: React.FC = () => {
|
||||
添加分期
|
||||
</PermissionButton>
|
||||
</div>
|
||||
{detailModal.installments?.length > 0 ? (
|
||||
{detailModal.installments && detailModal.installments.length > 0 ? (
|
||||
<List
|
||||
dataSource={detailModal.installments}
|
||||
renderItem={(item: any) => (
|
||||
renderItem={(item) => (
|
||||
<List.Item
|
||||
actions={[
|
||||
item.status === 'pending' && (
|
||||
@@ -447,13 +709,20 @@ const DepositsPage: React.FC = () => {
|
||||
</PermissionButton>
|
||||
),
|
||||
<Popconfirm
|
||||
title="确定删除?"
|
||||
key="archive"
|
||||
title="确定归档?"
|
||||
onConfirm={() => handleDeleteInstallment(item.id)}
|
||||
>
|
||||
<PermissionButton key="del" permission="deposit:delete" size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
<PermissionButton
|
||||
key="del"
|
||||
permission="deposit:delete"
|
||||
size="small"
|
||||
danger
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>,
|
||||
].filter(Boolean)}
|
||||
>
|
||||
<List.Item.Meta
|
||||
@@ -483,15 +752,13 @@ const DepositsPage: React.FC = () => {
|
||||
>
|
||||
<Form form={installmentForm} layout="vertical">
|
||||
<Form.Item name="amount" label="分期金额(元)" rules={[{ required: true }]}>
|
||||
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
|
||||
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="dueDate" label="到期日期" rules={[{ required: true }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择到期日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
} from 'antd';
|
||||
import {
|
||||
PlusOutlined,
|
||||
DeleteOutlined,
|
||||
InboxOutlined,
|
||||
EditOutlined,
|
||||
UploadOutlined,
|
||||
DownloadOutlined,
|
||||
@@ -32,11 +32,9 @@ import { message } from '../../ui/app-message';
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
const isFormValidationError = (error: unknown) =>
|
||||
typeof error === 'object'
|
||||
&& error !== null
|
||||
&& Array.isArray((error as { errorFields?: unknown }).errorFields);
|
||||
|
||||
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
Array.isArray((error as { errorFields?: unknown }).errorFields);
|
||||
|
||||
const ExpensesPage: React.FC = () => {
|
||||
const [roomExpenses, setRoomExpenses] = useState<any[]>([]);
|
||||
@@ -46,10 +44,12 @@ const ExpensesPage: React.FC = () => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [roomModal, setRoomModal] = useState(false);
|
||||
const [personalModal, setPersonalModal] = useState(false);
|
||||
const [utilityModal, setUtilityModal] = useState(false);
|
||||
const [editingRoom, setEditingRoom] = useState<any>(null);
|
||||
const [editingPersonal, setEditingPersonal] = useState<any>(null);
|
||||
const [roomForm] = Form.useForm();
|
||||
const [personalForm] = Form.useForm();
|
||||
const [utilityForm] = Form.useForm();
|
||||
const [roomSearch, setRoomSearch] = useState('');
|
||||
const [roomTypeFilter, setRoomTypeFilter] = useState<string | undefined>(undefined);
|
||||
const [personalSearch, setPersonalSearch] = useState('');
|
||||
@@ -61,27 +61,32 @@ const ExpensesPage: React.FC = () => {
|
||||
|
||||
// Dynamic expense type options from API
|
||||
const [typeOptions, setTypeOptions] = useState<{ value: string; label: string }[]>([]);
|
||||
const [personalTypeOptions, setPersonalTypeOptions] = useState<{ value: string; label: string }[]>([]);
|
||||
const [personalTypeOptions, setPersonalTypeOptions] = useState<
|
||||
{ value: string; label: string }[]
|
||||
>([]);
|
||||
const [typeMap, setTypeMap] = useState<Record<string, string>>({});
|
||||
|
||||
useEffect(() => {
|
||||
api.get<Array<{ code: string; name: string; category: string }>>('/expense-types').then((types) => {
|
||||
const roomTypes: { value: string; label: string }[] = [];
|
||||
const personalTypes: { value: string; label: string }[] = [];
|
||||
const map: Record<string, string> = {};
|
||||
for (const t of types) {
|
||||
map[t.code] = t.name;
|
||||
if (t.category === 'room' || t.category === 'both') {
|
||||
roomTypes.push({ value: t.code, label: t.name });
|
||||
api
|
||||
.get<Array<{ code: string; name: string; category: string }>>('/expense-types')
|
||||
.then((types) => {
|
||||
const roomTypes: { value: string; label: string }[] = [];
|
||||
const personalTypes: { value: string; label: string }[] = [];
|
||||
const map: Record<string, string> = {};
|
||||
for (const t of types) {
|
||||
map[t.code] = t.name;
|
||||
if (t.category === 'room' || t.category === 'both') {
|
||||
roomTypes.push({ value: t.code, label: t.name });
|
||||
}
|
||||
if (t.category === 'personal' || t.category === 'both') {
|
||||
personalTypes.push({ value: t.code, label: t.name });
|
||||
}
|
||||
}
|
||||
if (t.category === 'personal' || t.category === 'both') {
|
||||
personalTypes.push({ value: t.code, label: t.name });
|
||||
}
|
||||
}
|
||||
setTypeOptions(roomTypes);
|
||||
setPersonalTypeOptions(personalTypes);
|
||||
setTypeMap(map);
|
||||
}).catch(() => {});
|
||||
setTypeOptions(roomTypes);
|
||||
setPersonalTypeOptions(personalTypes);
|
||||
setTypeMap(map);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const handleBatchDeleteRoom = async () => {
|
||||
@@ -89,11 +94,11 @@ const ExpensesPage: React.FC = () => {
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
const res: any = await api.post('/expenses/room/batch-delete', { ids: selectedRoomKeys });
|
||||
message.success(res?.message || `已删除 ${selectedRoomKeys.length} 条`);
|
||||
message.success(res?.message || `已归档 ${selectedRoomKeys.length} 条`);
|
||||
setSelectedRoomKeys([]);
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '批量删除失败');
|
||||
message.error(e?.message || '批量归档失败');
|
||||
} finally {
|
||||
setBatchLoading(false);
|
||||
}
|
||||
@@ -106,11 +111,11 @@ const ExpensesPage: React.FC = () => {
|
||||
const res: any = await api.post('/expenses/personal/batch-delete', {
|
||||
ids: selectedPersonalKeys,
|
||||
});
|
||||
message.success(res?.message || `已删除 ${selectedPersonalKeys.length} 条`);
|
||||
message.success(res?.message || `已归档 ${selectedPersonalKeys.length} 条`);
|
||||
setSelectedPersonalKeys([]);
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '批量删除失败');
|
||||
message.error(e?.message || '批量归档失败');
|
||||
} finally {
|
||||
setBatchLoading(false);
|
||||
}
|
||||
@@ -192,6 +197,32 @@ const ExpensesPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleStudentUtility = async () => {
|
||||
const values = await utilityForm.validateFields();
|
||||
setSaving(true);
|
||||
try {
|
||||
const result: any = await api.post('/expenses/student-utility', {
|
||||
studentId: values.studentId,
|
||||
expenseType: values.expenseType,
|
||||
amount: values.amount,
|
||||
periodStart: values.period[0].format('YYYY-MM-DD'),
|
||||
periodEnd: values.period[1].format('YYYY-MM-DD'),
|
||||
description: values.description,
|
||||
});
|
||||
const bill = result.bill;
|
||||
message.success(
|
||||
`账单已生成,已从余额扣除 ¥${Number(bill.paidAmount || 0).toFixed(2)},待补缴 ¥${Number(bill.outstandingAmount || 0).toFixed(2)}`,
|
||||
);
|
||||
setUtilityModal(false);
|
||||
utilityForm.resetFields();
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '水电费出账失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePersonalExpense = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
@@ -224,121 +255,139 @@ const ExpensesPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const roomColumns = useMemo(() => [
|
||||
{ title: '宿舍', width: 120, render: (_: any, r: any) => r.room?.roomNumber || '-' },
|
||||
{
|
||||
title: '费用类型', width: 100,
|
||||
dataIndex: 'expenseType',
|
||||
render: (v: string) => <Tag>{typeMap[v] || v}</Tag>,
|
||||
},
|
||||
{ title: '金额', dataIndex: 'amount', width: 100, render: (v: number) => `¥${Number(v).toFixed(2)}` },
|
||||
{ title: '账单周期', width: 200, render: (_: any, r: any) => `${r.periodStart} ~ ${r.periodEnd}` },
|
||||
{ title: '说明', dataIndex: 'description', width: 150 },
|
||||
{
|
||||
title: '录入时间', width: 160,
|
||||
dataIndex: 'createdAt',
|
||||
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 120,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="expense:edit"
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => {
|
||||
setEditingRoom(record);
|
||||
roomForm.setFieldsValue({
|
||||
roomId: record.roomId,
|
||||
expenseType: record.expenseType,
|
||||
amount: Number(record.amount),
|
||||
period: [dayjs(record.periodStart), dayjs(record.periodEnd)],
|
||||
description: record.description,
|
||||
});
|
||||
setRoomModal(true);
|
||||
}}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<Popconfirm
|
||||
title="确定删除?"
|
||||
onConfirm={async () => {
|
||||
await api.delete(`/expenses/room/${record.id}`);
|
||||
message.success('删除成功');
|
||||
fetchData();
|
||||
}}
|
||||
>
|
||||
const roomColumns = useMemo(
|
||||
() => [
|
||||
{ title: '宿舍', width: 120, render: (_: any, r: any) => r.room?.roomNumber || '-' },
|
||||
{
|
||||
title: '费用类型',
|
||||
width: 100,
|
||||
dataIndex: 'expenseType',
|
||||
render: (v: string) => <Tag>{typeMap[v] || v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '金额',
|
||||
dataIndex: 'amount',
|
||||
width: 100,
|
||||
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '账单周期',
|
||||
width: 200,
|
||||
render: (_: any, r: any) => `${r.periodStart} ~ ${r.periodEnd}`,
|
||||
},
|
||||
{ title: '说明', dataIndex: 'description', width: 150 },
|
||||
{
|
||||
title: '录入时间',
|
||||
width: 160,
|
||||
dataIndex: 'createdAt',
|
||||
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 120,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="expense:delete"
|
||||
permission="expense:edit"
|
||||
size="small"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => {
|
||||
setEditingRoom(record);
|
||||
roomForm.setFieldsValue({
|
||||
roomId: record.roomId,
|
||||
expenseType: record.expenseType,
|
||||
amount: Number(record.amount),
|
||||
period: [dayjs(record.periodStart), dayjs(record.periodEnd)],
|
||||
description: record.description,
|
||||
});
|
||||
setRoomModal(true);
|
||||
}}
|
||||
>
|
||||
删除
|
||||
编辑
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
], [setEditingRoom, roomForm, setRoomModal, fetchData, typeMap]);
|
||||
<Popconfirm
|
||||
title="确定归档?"
|
||||
onConfirm={async () => {
|
||||
await api.delete(`/expenses/room/${record.id}`);
|
||||
message.success('归档成功');
|
||||
fetchData();
|
||||
}}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="expense:delete"
|
||||
size="small"
|
||||
danger
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
],
|
||||
[setEditingRoom, roomForm, setRoomModal, fetchData, typeMap],
|
||||
);
|
||||
|
||||
const personalColumns = useMemo(() => [
|
||||
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
|
||||
{
|
||||
title: '费用类型', width: 100,
|
||||
dataIndex: 'expenseType',
|
||||
render: (v: string) => <Tag color="orange">{typeMap[v] || v}</Tag>,
|
||||
},
|
||||
{ title: '金额', dataIndex: 'amount', render: (v: number) => `¥${Number(v).toFixed(2)}` },
|
||||
{ title: '日期', dataIndex: 'expenseDate', width: 110 },
|
||||
{ title: '说明', dataIndex: 'description', width: 150 },
|
||||
{
|
||||
title: '操作',
|
||||
width: 120,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="expense:edit"
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => {
|
||||
setEditingPersonal(record);
|
||||
personalForm.setFieldsValue({
|
||||
studentId: record.studentId,
|
||||
roomId: record.roomId,
|
||||
expenseType: record.expenseType,
|
||||
amount: Number(record.amount),
|
||||
expenseDate: dayjs(record.expenseDate),
|
||||
description: record.description,
|
||||
});
|
||||
setPersonalModal(true);
|
||||
}}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<Popconfirm
|
||||
title="确定删除?"
|
||||
onConfirm={async () => {
|
||||
await api.delete(`/expenses/personal/${record.id}`);
|
||||
message.success('删除成功');
|
||||
fetchData();
|
||||
}}
|
||||
>
|
||||
const personalColumns = useMemo(
|
||||
() => [
|
||||
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
|
||||
{
|
||||
title: '费用类型',
|
||||
width: 100,
|
||||
dataIndex: 'expenseType',
|
||||
render: (v: string) => <Tag color="orange">{typeMap[v] || v}</Tag>,
|
||||
},
|
||||
{ title: '金额', dataIndex: 'amount', render: (v: number) => `¥${Number(v).toFixed(2)}` },
|
||||
{ title: '日期', dataIndex: 'expenseDate', width: 110 },
|
||||
{ title: '说明', dataIndex: 'description', width: 150 },
|
||||
{
|
||||
title: '操作',
|
||||
width: 120,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="expense:delete"
|
||||
permission="expense:edit"
|
||||
size="small"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => {
|
||||
setEditingPersonal(record);
|
||||
personalForm.setFieldsValue({
|
||||
studentId: record.studentId,
|
||||
roomId: record.roomId,
|
||||
expenseType: record.expenseType,
|
||||
amount: Number(record.amount),
|
||||
expenseDate: dayjs(record.expenseDate),
|
||||
description: record.description,
|
||||
});
|
||||
setPersonalModal(true);
|
||||
}}
|
||||
>
|
||||
删除
|
||||
编辑
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
], [setEditingPersonal, personalForm, setPersonalModal, fetchData, typeMap]);
|
||||
<Popconfirm
|
||||
title="确定归档?"
|
||||
onConfirm={async () => {
|
||||
await api.delete(`/expenses/personal/${record.id}`);
|
||||
message.success('归档成功');
|
||||
fetchData();
|
||||
}}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="expense:delete"
|
||||
size="small"
|
||||
danger
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
],
|
||||
[setEditingPersonal, personalForm, setPersonalModal, fetchData, typeMap],
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -407,8 +456,8 @@ const ExpensesPage: React.FC = () => {
|
||||
permission="expense:view"
|
||||
icon={<DownloadOutlined />}
|
||||
onClick={() => {
|
||||
downloadBlob('/expenses/utility/template', '水电费导入模板.xlsx').catch(() =>
|
||||
message.error('下载失败'),
|
||||
downloadBlob('/expenses/utility/template', '水电费导入模板.xlsx').catch(
|
||||
() => message.error('下载失败'),
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -417,19 +466,19 @@ const ExpensesPage: React.FC = () => {
|
||||
</Space>
|
||||
<Space>
|
||||
<Popconfirm
|
||||
title={`确定删除选中的 ${selectedRoomKeys.length} 条费用?`}
|
||||
title={`确定归档选中的 ${selectedRoomKeys.length} 条费用?`}
|
||||
onConfirm={handleBatchDeleteRoom}
|
||||
okText="删除"
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
disabled={selectedRoomKeys.length === 0}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="expense:delete"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
icon={<InboxOutlined />}
|
||||
disabled={selectedRoomKeys.length === 0}
|
||||
>
|
||||
批量删除
|
||||
批量归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
<PermissionButton
|
||||
@@ -524,9 +573,10 @@ const ExpensesPage: React.FC = () => {
|
||||
permission="expense:view"
|
||||
icon={<DownloadOutlined />}
|
||||
onClick={() => {
|
||||
downloadBlob('/expenses/personal/template', '个人附加费导入模板.xlsx').catch(
|
||||
() => message.error('下载失败'),
|
||||
);
|
||||
downloadBlob(
|
||||
'/expenses/personal/template',
|
||||
'个人附加费导入模板.xlsx',
|
||||
).catch(() => message.error('下载失败'));
|
||||
}}
|
||||
>
|
||||
下载模板
|
||||
@@ -545,21 +595,31 @@ const ExpensesPage: React.FC = () => {
|
||||
</Space>
|
||||
<Space>
|
||||
<Popconfirm
|
||||
title={`确定删除选中的 ${selectedPersonalKeys.length} 条个人费用?`}
|
||||
title={`确定归档选中的 ${selectedPersonalKeys.length} 条个人费用?`}
|
||||
onConfirm={handleBatchDeletePersonal}
|
||||
okText="删除"
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
disabled={selectedPersonalKeys.length === 0}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="expense:delete"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
icon={<InboxOutlined />}
|
||||
disabled={selectedPersonalKeys.length === 0}
|
||||
>
|
||||
批量删除
|
||||
批量归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
<PermissionButton
|
||||
permission="expense:create"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => {
|
||||
utilityForm.resetFields();
|
||||
setUtilityModal(true);
|
||||
}}
|
||||
>
|
||||
添加学生水电费
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="expense:create"
|
||||
type="primary"
|
||||
@@ -624,7 +684,7 @@ const ExpensesPage: React.FC = () => {
|
||||
<Select options={typeOptions} />
|
||||
</Form.Item>
|
||||
<Form.Item name="amount" label="金额(元)" rules={[{ required: true }]}>
|
||||
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
|
||||
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="period" label="账单周期" rules={[{ required: true }]}>
|
||||
<RangePicker
|
||||
@@ -639,6 +699,45 @@ const ExpensesPage: React.FC = () => {
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="添加学生水电费并立即出账"
|
||||
open={utilityModal}
|
||||
onOk={handleStudentUtility}
|
||||
onCancel={() => setUtilityModal(false)}
|
||||
okText="生成账单并扣余额"
|
||||
confirmLoading={saving}
|
||||
>
|
||||
<Form form={utilityForm} layout="vertical">
|
||||
<Form.Item name="studentId" label="学生" rules={[{ required: true }]}>
|
||||
<Select
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
options={students.map((student: any) => ({
|
||||
value: student.id,
|
||||
label: `${student.name} (${student.studentNo || `#${student.id}`})`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="expenseType" label="费用类型" rules={[{ required: true }]}>
|
||||
<Select
|
||||
options={[
|
||||
{ value: 'water', label: '水费' },
|
||||
{ value: 'electricity', label: '电费' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="amount" label="金额(元)" rules={[{ required: true }]}>
|
||||
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="period" label="账单周期" rules={[{ required: true }]}>
|
||||
<RangePicker style={{ width: '100%' }} format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="description" label="说明">
|
||||
<Input.TextArea rows={2} maxLength={300} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title={editingPersonal ? '编辑个人费用' : '录入个人附加费'}
|
||||
open={personalModal}
|
||||
@@ -670,7 +769,7 @@ const ExpensesPage: React.FC = () => {
|
||||
<Select options={personalTypeOptions} />
|
||||
</Form.Item>
|
||||
<Form.Item name="amount" label="金额(元)" rules={[{ required: true }]}>
|
||||
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
|
||||
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="expenseDate" label="费用日期" rules={[{ required: true }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择日期" format="YYYY-MM-DD" />
|
||||
|
||||
@@ -1,13 +1,34 @@
|
||||
import React, { useEffect, useState, useMemo, useCallback } from 'react';
|
||||
import {
|
||||
Card, Form, Input, Button, Space, Spin, Alert, Descriptions, Tag, Divider,
|
||||
Drawer, Tree, Select, TreeSelect, Modal, DatePicker, InputNumber,
|
||||
Row, Col, List,
|
||||
Card,
|
||||
Form,
|
||||
Input,
|
||||
Button,
|
||||
Space,
|
||||
Spin,
|
||||
Alert,
|
||||
Descriptions,
|
||||
Tag,
|
||||
Divider,
|
||||
Drawer,
|
||||
Tree,
|
||||
Select,
|
||||
TreeSelect,
|
||||
Modal,
|
||||
DatePicker,
|
||||
Row,
|
||||
Col,
|
||||
List,
|
||||
} from 'antd';
|
||||
import {
|
||||
SaveOutlined, ApiOutlined, CheckCircleOutlined, CloseCircleOutlined,
|
||||
SyncOutlined, BankOutlined, UserOutlined,
|
||||
DeleteOutlined,
|
||||
SaveOutlined,
|
||||
ApiOutlined,
|
||||
CheckCircleOutlined,
|
||||
CloseCircleOutlined,
|
||||
SyncOutlined,
|
||||
BankOutlined,
|
||||
UserOutlined,
|
||||
StopOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import type { DataNode } from 'antd/es/tree';
|
||||
import type { TreeSelectProps } from 'antd/es/tree-select';
|
||||
@@ -59,13 +80,13 @@ interface ClassItem {
|
||||
classType?: string;
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
maxStudents?: number;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
interface ImportResult {
|
||||
imported: number;
|
||||
skipped: number;
|
||||
conflicts: number;
|
||||
}
|
||||
|
||||
interface DingTalkAttendanceGroup {
|
||||
@@ -89,7 +110,6 @@ interface DeleteAttendanceGroupsResponse {
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
const IntegrationConfigPage: React.FC = () => {
|
||||
const { hasAllPermissions } = usePermission();
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -116,11 +136,13 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
const [loadingGroups, setLoadingGroups] = useState(false);
|
||||
const [deletingGroups, setDeletingGroups] = useState(false);
|
||||
|
||||
|
||||
const fetchConfig = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await api.get<{ success: boolean; data: Array<{ type: string; verify: boolean; config: DingTalkConfig }> }>('/integration/config');
|
||||
const res = await api.get<{
|
||||
success: boolean;
|
||||
data: Array<{ type: string; verify: boolean; config: DingTalkConfig }>;
|
||||
}>('/integration/config');
|
||||
const dt = res.data?.find((c) => c.type === 'DINGTALK');
|
||||
if (dt) {
|
||||
setConfig(dt.config);
|
||||
@@ -159,10 +181,13 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
const payload = buildDingTalkConfigPayload(values);
|
||||
setTesting(true);
|
||||
try {
|
||||
const res = await api.post<{ success: boolean; message: string }>('/integration/config/test', {
|
||||
type: 'DINGTALK',
|
||||
config: payload,
|
||||
});
|
||||
const res = await api.post<{ success: boolean; message: string }>(
|
||||
'/integration/config/test',
|
||||
{
|
||||
type: 'DINGTALK',
|
||||
config: payload,
|
||||
},
|
||||
);
|
||||
setVerified(res.success);
|
||||
message.success(res.message);
|
||||
} catch (e: unknown) {
|
||||
@@ -174,7 +199,6 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const loadDeptTree = async () => {
|
||||
try {
|
||||
const res = await api.get<OrgTreeResponse>('/sync/dingtalk/org-tree');
|
||||
@@ -200,7 +224,9 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
} else {
|
||||
setClasses(res.data ?? []);
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
const handleFetchOrgTree = async () => {
|
||||
@@ -208,7 +234,9 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
try {
|
||||
const params: Record<string, string> = {};
|
||||
if (syncRootDeptId) params.rootDeptId = String(syncRootDeptId);
|
||||
const res = await api.get<OrgTreeWithUsersResponse>('/sync/dingtalk/org-tree-with-users', { params });
|
||||
const res = await api.get<OrgTreeWithUsersResponse>('/sync/dingtalk/org-tree-with-users', {
|
||||
params,
|
||||
});
|
||||
if (res.success && res.data) {
|
||||
setOrgTree(res.data);
|
||||
setCheckedKeys([]);
|
||||
@@ -226,7 +254,6 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const buildTreeData = useCallback((nodes: DingOrgTreeNodeExt[]): DataNode[] => {
|
||||
return nodes.map((node) => {
|
||||
const users = node.users ?? [];
|
||||
@@ -262,7 +289,11 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
|
||||
const treeData = useMemo(() => buildTreeData(orgTree), [orgTree, buildTreeData]);
|
||||
|
||||
const extractCheckedUsers = useCallback((): Array<{ dingUserId: string; name: string; mobile?: string }> => {
|
||||
const extractCheckedUsers = useCallback((): Array<{
|
||||
dingUserId: string;
|
||||
name: string;
|
||||
mobile?: string;
|
||||
}> => {
|
||||
const result: Array<{ dingUserId: string; name: string; mobile?: string }> = [];
|
||||
const walk = (nodes: DingOrgTreeNodeExt[]) => {
|
||||
for (const node of nodes) {
|
||||
@@ -285,8 +316,16 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
|
||||
setImporting(true);
|
||||
try {
|
||||
const res = await api.post<ImportResult>(`/classes/${selectedClassId}/students/import`, { users });
|
||||
message.success(`导入 ${res.imported} 人,跳过 ${res.skipped} 人`);
|
||||
const res = await api.post<ImportResult>(`/classes/${selectedClassId}/students/import`, {
|
||||
users,
|
||||
});
|
||||
if (res.conflicts > 0) {
|
||||
message.warning(
|
||||
`导入 ${res.imported} 人,跳过 ${res.skipped} 人,${res.conflicts} 人需人工绑定`,
|
||||
);
|
||||
} else {
|
||||
message.success(`导入 ${res.imported} 人,跳过 ${res.skipped} 人`);
|
||||
}
|
||||
setCheckedKeys([]);
|
||||
setSelectedClassId(null);
|
||||
} catch (e: unknown) {
|
||||
@@ -338,190 +377,218 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
setAttendanceGroups([]);
|
||||
if (response.data.failed.length > 0) {
|
||||
message.warning(
|
||||
`已删除 ${response.data.deleted.length} 个,失败 ${response.data.failed.length} 个`,
|
||||
`已清空 ${response.data.deleted.length} 个,失败 ${response.data.failed.length} 个`,
|
||||
);
|
||||
} else {
|
||||
message.success(`已删除钉钉全部 ${response.data.deleted.length} 个考勤组`);
|
||||
message.success(`已清空钉钉全部 ${response.data.deleted.length} 个考勤组`);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
message.error(error instanceof Error ? error.message : '删除钉钉考勤组失败');
|
||||
message.error(error instanceof Error ? error.message : '清空钉钉考勤组失败');
|
||||
} finally {
|
||||
setDeletingGroups(false);
|
||||
}
|
||||
};
|
||||
|
||||
const syncPanel = config && hasAllPermissions('sync:read', 'class:view', 'class:edit')
|
||||
? (
|
||||
<div>
|
||||
<Alert
|
||||
type="info"
|
||||
message="从钉钉获取组织架构,勾选用户后批量导入到班级。"
|
||||
style={{ marginBottom: 16 }}
|
||||
showIcon
|
||||
/>
|
||||
const syncPanel =
|
||||
config && hasAllPermissions('sync:read', 'class:view', 'class:edit') ? (
|
||||
<div>
|
||||
<Alert
|
||||
type="info"
|
||||
message="从钉钉获取组织架构,勾选用户后批量导入到班级。"
|
||||
style={{ marginBottom: 16 }}
|
||||
showIcon
|
||||
/>
|
||||
<Space>
|
||||
<TreeSelect
|
||||
treeData={deptPickerTree}
|
||||
value={syncRootDeptId}
|
||||
onChange={(v) => setSyncRootDeptId(v)}
|
||||
placeholder="选择起始部门(不选=全部)"
|
||||
allowClear
|
||||
treeDefaultExpandAll
|
||||
style={{ minWidth: 240 }}
|
||||
onDropdownVisibleChange={(open) => {
|
||||
if (open) loadDeptTree();
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<SyncOutlined />}
|
||||
loading={fetchingTree}
|
||||
onClick={handleFetchOrgTree}
|
||||
>
|
||||
获取组织架构
|
||||
</Button>
|
||||
<PermissionButton
|
||||
permission="sync:trigger"
|
||||
danger
|
||||
icon={<StopOutlined />}
|
||||
loading={loadingGroups}
|
||||
onClick={openDeleteAllGroups}
|
||||
>
|
||||
清空钉钉全部考勤组
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
|
||||
{drawerOpen && (
|
||||
<Drawer
|
||||
title="钉钉组织架构 — 批量导入"
|
||||
open={drawerOpen}
|
||||
onClose={() => {
|
||||
setDrawerOpen(false);
|
||||
}}
|
||||
width="min(900px, 100vw)"
|
||||
footer={
|
||||
<Space>
|
||||
<TreeSelect
|
||||
treeData={deptPickerTree}
|
||||
value={syncRootDeptId}
|
||||
onChange={(v) => setSyncRootDeptId(v)}
|
||||
placeholder="选择起始部门(不选=全部)"
|
||||
allowClear
|
||||
treeDefaultExpandAll
|
||||
style={{ minWidth: 240 }}
|
||||
onDropdownVisibleChange={(open) => { if (open) loadDeptTree(); }}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setDrawerOpen(false);
|
||||
}}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<SyncOutlined />}
|
||||
loading={fetchingTree}
|
||||
onClick={handleFetchOrgTree}
|
||||
loading={importing}
|
||||
disabled={
|
||||
checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0 ||
|
||||
selectedClassId === null
|
||||
}
|
||||
onClick={handleJoinClass}
|
||||
>
|
||||
获取组织架构
|
||||
加入选中的班级
|
||||
</Button>
|
||||
<PermissionButton
|
||||
permission="sync:trigger"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
loading={loadingGroups}
|
||||
onClick={openDeleteAllGroups}
|
||||
<Button
|
||||
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0}
|
||||
onClick={() => setClassModalOpen(true)}
|
||||
>
|
||||
删除钉钉全部考勤组
|
||||
</PermissionButton>
|
||||
创建班级
|
||||
</Button>
|
||||
</Space>
|
||||
|
||||
{drawerOpen && (
|
||||
<Drawer
|
||||
title="钉钉组织架构 — 批量导入"
|
||||
open={drawerOpen}
|
||||
onClose={() => { setDrawerOpen(false); }}
|
||||
width={900}
|
||||
footer={
|
||||
<Space>
|
||||
<Button onClick={() => { setDrawerOpen(false); }}>取消</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
loading={importing}
|
||||
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0 || selectedClassId === null}
|
||||
onClick={handleJoinClass}
|
||||
>加入选中的班级</Button>
|
||||
<Button
|
||||
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0}
|
||||
onClick={() => setClassModalOpen(true)}
|
||||
>创建班级</Button>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Row gutter={[16, 16]}>
|
||||
<Col xs={24} md={14}>
|
||||
<div style={{ maxHeight: '60vh', overflow: 'auto' }}>
|
||||
<Tree
|
||||
checkable
|
||||
treeData={treeData}
|
||||
defaultExpandAll
|
||||
showLine={{ showLeafIcon: false }}
|
||||
checkedKeys={checkedKeys}
|
||||
onCheck={(checked) => setCheckedKeys(checked as React.Key[])}
|
||||
/>
|
||||
</div>
|
||||
</Col>
|
||||
<Col xs={24} md={10}>
|
||||
<Card
|
||||
title="班级列表"
|
||||
size="small"
|
||||
extra={
|
||||
<Button size="small" onClick={() => setClassModalOpen(true)}>
|
||||
+ 创建班级
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<Row gutter={16}>
|
||||
<Col span={14}>
|
||||
<div style={{ maxHeight: '60vh', overflow: 'auto' }}>
|
||||
<Tree
|
||||
checkable
|
||||
treeData={treeData}
|
||||
defaultExpandAll
|
||||
showLine={{ showLeafIcon: false }}
|
||||
checkedKeys={checkedKeys}
|
||||
onCheck={(checked) => setCheckedKeys(checked as React.Key[])}
|
||||
<List
|
||||
dataSource={classes}
|
||||
renderItem={(cls: ClassItem) => (
|
||||
<List.Item
|
||||
onClick={() => setSelectedClassId(cls.id)}
|
||||
style={{
|
||||
cursor: 'pointer',
|
||||
background: selectedClassId === cls.id ? '#e6f4ff' : undefined,
|
||||
borderRadius: 4,
|
||||
padding: '8px 12px',
|
||||
}}
|
||||
>
|
||||
<List.Item.Meta
|
||||
title={cls.name}
|
||||
description={`${cls.code} ${cls.classType || ''}`}
|
||||
/>
|
||||
</div>
|
||||
</Col>
|
||||
<Col span={10}>
|
||||
<Card title="班级列表" size="small"
|
||||
extra={<Button size="small" onClick={() => setClassModalOpen(true)}>+ 创建班级</Button>}>
|
||||
<List
|
||||
dataSource={classes}
|
||||
renderItem={(cls: ClassItem) => (
|
||||
<List.Item
|
||||
onClick={() => setSelectedClassId(cls.id)}
|
||||
style={{
|
||||
cursor: 'pointer',
|
||||
background: selectedClassId === cls.id ? '#e6f4ff' : undefined,
|
||||
borderRadius: 4,
|
||||
padding: '8px 12px',
|
||||
}}
|
||||
>
|
||||
<List.Item.Meta title={cls.name} description={`${cls.code} ${cls.classType || ''}`} />
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{ /* Create class Modal */ }
|
||||
<Modal
|
||||
title="创建班级"
|
||||
open={classModalOpen}
|
||||
onOk={handleCreateClass}
|
||||
onCancel={() => { setClassModalOpen(false); classForm.resetFields(); }}
|
||||
confirmLoading={importing}
|
||||
destroyOnClose
|
||||
>
|
||||
<Form form={classForm} layout="vertical">
|
||||
<Form.Item name="name" label="班级名称" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="code" label="班级编码" rules={[{ required: true }]}>
|
||||
<Input placeholder="如 CS2024-01" />
|
||||
</Form.Item>
|
||||
<Form.Item name="classType" label="班型" rules={[{ required: true }]}>
|
||||
<Select options={[
|
||||
{ value: 'culture', label: '文化课' },
|
||||
{ value: 'professional', label: '专业课' },
|
||||
{ value: 'bootcamp', label: '集训营' },
|
||||
{ value: 'sprint', label: '冲刺班' },
|
||||
]} />
|
||||
</Form.Item>
|
||||
<Form.Item name="startDate" label="开班日期">
|
||||
<DatePicker style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="endDate" label="结束日期">
|
||||
<DatePicker style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="maxStudents" label="最大人数">
|
||||
<InputNumber min={0} style={{ width: '100%' }} placeholder="0=不限制" />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</Drawer>
|
||||
)}
|
||||
<Modal
|
||||
title="确认删除钉钉全部考勤组"
|
||||
open={deleteGroupsOpen}
|
||||
okText="确认全部删除"
|
||||
okButtonProps={{ danger: true, disabled: attendanceGroups.length === 0 }}
|
||||
cancelText="取消"
|
||||
confirmLoading={deletingGroups}
|
||||
onOk={deleteAllGroups}
|
||||
onCancel={() => setDeleteGroupsOpen(false)}
|
||||
>
|
||||
<Alert
|
||||
type="error"
|
||||
showIcon
|
||||
message={`将永久删除钉钉上的 ${attendanceGroups.length} 个考勤组`}
|
||||
description="本地班级和排课不会删除。删除后需在排课管理中重新同步,才能重建考勤组。"
|
||||
style={{ marginBottom: 12 }}
|
||||
{/* Create class Modal */}
|
||||
<Modal
|
||||
title="创建班级"
|
||||
open={classModalOpen}
|
||||
onOk={handleCreateClass}
|
||||
onCancel={() => {
|
||||
setClassModalOpen(false);
|
||||
classForm.resetFields();
|
||||
}}
|
||||
confirmLoading={importing}
|
||||
destroyOnClose
|
||||
>
|
||||
<Form form={classForm} layout="vertical">
|
||||
<Form.Item name="name" label="班级名称" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="code" label="班级编码" rules={[{ required: true }]}>
|
||||
<Input placeholder="如 CS2024-01" />
|
||||
</Form.Item>
|
||||
<Form.Item name="classType" label="班型" rules={[{ required: true }]}>
|
||||
<Select
|
||||
options={[
|
||||
{ value: 'culture', label: '文化课' },
|
||||
{ value: 'professional', label: '专业课' },
|
||||
{ value: 'bootcamp', label: '集训营' },
|
||||
{ value: 'sprint', label: '冲刺班' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="startDate" label="开班日期">
|
||||
<DatePicker style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="endDate" label="结束日期">
|
||||
<DatePicker style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</Drawer>
|
||||
)}
|
||||
<Modal
|
||||
title="确认清空钉钉全部考勤组"
|
||||
open={deleteGroupsOpen}
|
||||
okText="确认全部清空"
|
||||
okButtonProps={{ danger: true, disabled: attendanceGroups.length === 0 }}
|
||||
cancelText="取消"
|
||||
confirmLoading={deletingGroups}
|
||||
onOk={deleteAllGroups}
|
||||
onCancel={() => setDeleteGroupsOpen(false)}
|
||||
>
|
||||
<Alert
|
||||
type="error"
|
||||
showIcon
|
||||
message={`将永久清空钉钉上的 ${attendanceGroups.length} 个考勤组`}
|
||||
description="本地班级和排课不会清空。清空后需在排课管理中重新同步,才能重建考勤组。"
|
||||
style={{ marginBottom: 12 }}
|
||||
/>
|
||||
<List
|
||||
size="small"
|
||||
bordered
|
||||
dataSource={attendanceGroups}
|
||||
style={{ maxHeight: 280, overflow: 'auto' }}
|
||||
renderItem={(group) => (
|
||||
<List.Item>
|
||||
<List.Item.Meta
|
||||
title={group.group_name}
|
||||
description={`ID ${group.group_id} · ${group.member_count} 人`}
|
||||
/>
|
||||
<List
|
||||
size="small"
|
||||
bordered
|
||||
dataSource={attendanceGroups}
|
||||
style={{ maxHeight: 280, overflow: 'auto' }}
|
||||
renderItem={(group) => (
|
||||
<List.Item>
|
||||
<List.Item.Meta
|
||||
title={group.group_name}
|
||||
description={`ID ${group.group_id} · ${group.member_count} 人`}
|
||||
/>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
</Modal>
|
||||
</div>
|
||||
)
|
||||
: null;
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
</Modal>
|
||||
</div>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<Card
|
||||
@@ -587,9 +654,7 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
: '首次配置需要填写完整 AppSecret'
|
||||
}
|
||||
>
|
||||
<Input.Password
|
||||
placeholder={config ? '留空保持已保存的密钥' : '从钉钉开放平台获取'}
|
||||
/>
|
||||
<Input.Password placeholder={config ? '留空保持已保存的密钥' : '从钉钉开放平台获取'} />
|
||||
</Form.Item>
|
||||
<Space>
|
||||
<PermissionButton
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
buildDingTalkConfigPayload,
|
||||
isAppSecretRequired,
|
||||
} from './integration-config-form';
|
||||
import { buildDingTalkConfigPayload, isAppSecretRequired } from './integration-config-form';
|
||||
|
||||
describe('DingTalk integration config form', () => {
|
||||
it('requires AppSecret only for the first configuration', () => {
|
||||
|
||||
@@ -13,22 +13,27 @@ const LoginPage: React.FC = () => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const onFinish = useCallback(async (values: any) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res: any = await api.post('/auth/login', values);
|
||||
localStorage.setItem('token', res.access_token);
|
||||
localStorage.setItem('user', JSON.stringify(res.user));
|
||||
const permissions = res.user.permissions || [];
|
||||
writePermissions(permissions);
|
||||
message.success('登录成功');
|
||||
navigate(findRoleAwareLandingPath(res.user.roles || [], permissions) || '/', { replace: true });
|
||||
} catch (err: any) {
|
||||
message.error(err?.message || '登录失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [navigate]);
|
||||
const onFinish = useCallback(
|
||||
async (values: any) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res: any = await api.post('/auth/login', values);
|
||||
localStorage.setItem('token', res.access_token);
|
||||
localStorage.setItem('user', JSON.stringify(res.user));
|
||||
const permissions = res.user.permissions || [];
|
||||
writePermissions(permissions);
|
||||
message.success('登录成功');
|
||||
navigate(findRoleAwareLandingPath(res.user.roles || [], permissions) || '/', {
|
||||
replace: true,
|
||||
});
|
||||
} catch (err: any) {
|
||||
message.error(err?.message || '登录失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[navigate],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -56,10 +61,18 @@ const LoginPage: React.FC = () => {
|
||||
<p style={{ color: '#86868b', marginTop: 8 }}>水电费精准计费平台</p>
|
||||
</div>
|
||||
<Form name="login" onFinish={onFinish} size="large">
|
||||
<Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名' }]}>
|
||||
<Form.Item
|
||||
label="用户名"
|
||||
name="username"
|
||||
rules={[{ required: true, message: '请输入用户名' }]}
|
||||
>
|
||||
<Input prefix={<UserOutlined />} placeholder="用户名" />
|
||||
</Form.Item>
|
||||
<Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码' }]}>
|
||||
<Form.Item
|
||||
label="密码"
|
||||
name="password"
|
||||
rules={[{ required: true, message: '请输入密码' }]}
|
||||
>
|
||||
<Input.Password prefix={<LockOutlined />} placeholder="密码" />
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { List, Typography, Menu, Layout, Button, Empty, Spin, Space } from 'antd';
|
||||
import { List, Typography, Menu, Layout, Button, Empty, Spin, Space, Grid, Select } from 'antd';
|
||||
import {
|
||||
BellOutlined,
|
||||
DollarOutlined,
|
||||
@@ -13,6 +13,7 @@ import { message } from '../../ui/app-message';
|
||||
import { formatNotificationText } from '../../utils/notification-display';
|
||||
|
||||
const { Sider, Content } = Layout;
|
||||
const { useBreakpoint } = Grid;
|
||||
|
||||
interface NotificationItem {
|
||||
id: number;
|
||||
@@ -49,6 +50,8 @@ function timeAgo(dateStr: string): string {
|
||||
}
|
||||
|
||||
const NotificationsPage: React.FC = () => {
|
||||
const screens = useBreakpoint();
|
||||
const isMobile = !screens.sm;
|
||||
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
|
||||
const [filter, setFilter] = useState('all');
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -57,7 +60,7 @@ const NotificationsPage: React.FC = () => {
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await api.get('/notifications?limit=50') as unknown as NotificationItem[];
|
||||
const data = (await api.get('/notifications?limit=50')) as unknown as NotificationItem[];
|
||||
setNotifications(data);
|
||||
} catch (e: any) {
|
||||
console.error('加载通知失败', e);
|
||||
@@ -88,40 +91,51 @@ const NotificationsPage: React.FC = () => {
|
||||
const handleMarkAll = async () => {
|
||||
try {
|
||||
await api.put('/notifications/read-all');
|
||||
setNotifications((prev) =>
|
||||
prev.map((n) => ({ ...n, isRead: true })),
|
||||
);
|
||||
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
|
||||
} catch (e: any) {
|
||||
console.error('全部已读失败', e);
|
||||
message.error(e?.message || '操作失败');
|
||||
}
|
||||
};
|
||||
|
||||
const filtered = filter === 'all'
|
||||
? notifications
|
||||
: notifications.filter((n) => n.type === filter);
|
||||
const filtered =
|
||||
filter === 'all' ? notifications : notifications.filter((n) => n.type === filter);
|
||||
|
||||
const filterItems = [
|
||||
{ key: 'all', icon: <BellOutlined />, label: '全部' },
|
||||
{ key: 'bill_generated', icon: <DollarOutlined />, label: '账单' },
|
||||
{ key: 'check_in', icon: <HomeOutlined />, label: '入住' },
|
||||
{ key: 'class_change', icon: <TeamOutlined />, label: '班级' },
|
||||
{ key: 'announcement', icon: <SettingOutlined />, label: '公告' },
|
||||
];
|
||||
|
||||
return (
|
||||
<Layout style={{ minHeight: '100%', background: '#fff' }}>
|
||||
<Sider width={180} style={{ background: '#fff', borderRight: '1px solid #f0f0f0' }}>
|
||||
<Menu
|
||||
mode="inline"
|
||||
selectedKeys={[filter]}
|
||||
onClick={({ key }) => setFilter(key)}
|
||||
items={[
|
||||
{ key: 'all', icon: <BellOutlined />, label: '全部' },
|
||||
{ key: 'bill_generated', icon: <DollarOutlined />, label: '账单' },
|
||||
{ key: 'check_in', icon: <HomeOutlined />, label: '入住' },
|
||||
{ key: 'class_change', icon: <TeamOutlined />, label: '班级' },
|
||||
{ key: 'announcement', icon: <SettingOutlined />, label: '公告' },
|
||||
]}
|
||||
/>
|
||||
</Sider>
|
||||
<Content style={{ padding: 24 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
|
||||
<Typography.Title level={4} style={{ margin: 0 }}>通知中心</Typography.Title>
|
||||
<Layout className="notifications-layout" style={{ minHeight: '100%', background: '#fff' }}>
|
||||
{!isMobile && (
|
||||
<Sider width={180} style={{ background: '#fff', borderRight: '1px solid #f0f0f0' }}>
|
||||
<Menu
|
||||
mode="inline"
|
||||
selectedKeys={[filter]}
|
||||
onClick={({ key }) => setFilter(key)}
|
||||
items={filterItems}
|
||||
/>
|
||||
</Sider>
|
||||
)}
|
||||
<Content className="notifications-content" style={{ padding: isMobile ? 0 : 24 }}>
|
||||
<div className="notifications-header">
|
||||
<Typography.Title level={4} style={{ margin: 0 }}>
|
||||
通知中心
|
||||
</Typography.Title>
|
||||
<Button onClick={handleMarkAll}>全部已读</Button>
|
||||
</div>
|
||||
{isMobile && (
|
||||
<Select
|
||||
value={filter}
|
||||
onChange={setFilter}
|
||||
options={filterItems.map((item) => ({ value: item.key, label: item.label }))}
|
||||
className="notifications-filter"
|
||||
/>
|
||||
)}
|
||||
<Spin spinning={loading}>
|
||||
{filtered.length === 0 ? (
|
||||
<Empty description="暂无通知" />
|
||||
@@ -165,11 +179,8 @@ const NotificationsPage: React.FC = () => {
|
||||
</div>
|
||||
}
|
||||
title={
|
||||
<Space>
|
||||
<Typography.Text
|
||||
strong={!item.isRead}
|
||||
style={{ fontSize: 15 }}
|
||||
>
|
||||
<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 }}>
|
||||
|
||||
@@ -21,18 +21,18 @@ import {
|
||||
PlusOutlined,
|
||||
SwapOutlined,
|
||||
LogoutOutlined,
|
||||
DeleteOutlined,
|
||||
InboxOutlined,
|
||||
UploadOutlined,
|
||||
DownloadOutlined,
|
||||
ExportOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import dayjs, { type Dayjs } from 'dayjs';
|
||||
import api from '../../api';
|
||||
import { downloadBlob } from '../../utils/download';
|
||||
import { maskPhone, maskIdNumber } from '../../utils/sensitive';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { buildTransferPayload } from './occupancy-form';
|
||||
import { buildCheckInPayload, buildTransferPayload } from './occupancy-form';
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
@@ -40,7 +40,6 @@ const OccupanciesPage: React.FC = () => {
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [students, setStudents] = useState<any[]>([]);
|
||||
const [rooms, setRooms] = useState<any[]>([]);
|
||||
const [organizations, setOrganizations] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [checkInModal, setCheckInModal] = useState(false);
|
||||
const [checkOutModal, setCheckOutModal] = useState<any>(null);
|
||||
@@ -60,20 +59,78 @@ const OccupanciesPage: React.FC = () => {
|
||||
const [batchCheckOutForm] = Form.useForm();
|
||||
const [availableBeds, setAvailableBeds] = useState<any[]>([]);
|
||||
const [availableLockers, setAvailableLockers] = useState<any[]>([]);
|
||||
const [availableResourcesLoading, setAvailableResourcesLoading] = useState(false);
|
||||
const [transferAvailableBeds, setTransferAvailableBeds] = useState<any[]>([]);
|
||||
const [transferAvailableLockers, setTransferAvailableLockers] = useState<any[]>([]);
|
||||
const [transferResourcesLoading, setTransferResourcesLoading] = useState(false);
|
||||
const selectedCheckInRoomId = Form.useWatch('roomId', checkInForm);
|
||||
const selectedTransferRoomId = Form.useWatch('newRoomId', transferForm);
|
||||
|
||||
const activeOccupancyByStudentId = useMemo(() => {
|
||||
const map = new Map<number, any>();
|
||||
data.forEach((item) => {
|
||||
if (!item.checkOutDate && item.status !== 'archived') map.set(item.studentId, item);
|
||||
});
|
||||
return map;
|
||||
}, [data]);
|
||||
|
||||
const isRoomSelectable = useCallback((room: any) => {
|
||||
const currentCount = Number(room.currentCount || 0);
|
||||
const capacity = Number(room.capacity || 0);
|
||||
return room.status !== 'archived' && room.status !== 'maintenance' && currentCount < capacity;
|
||||
}, []);
|
||||
|
||||
const roomOptionLabel = useCallback((room: any) => {
|
||||
const base = `${room.roomNumber} (${room.building || ''}) [${room.currentCount}/${room.capacity}]`;
|
||||
if (room.status === 'maintenance') return `${base} · 维修中`;
|
||||
if (room.status === 'archived') return `${base} · 已归档`;
|
||||
if (Number(room.currentCount || 0) >= Number(room.capacity || 0)) return `${base} · 已满`;
|
||||
return base;
|
||||
}, []);
|
||||
|
||||
const selectedBatchRecords = useMemo(
|
||||
() => data.filter((item) => selectedRowKeys.includes(item.id) && !item.checkOutDate),
|
||||
[data, selectedRowKeys],
|
||||
);
|
||||
const latestSelectedCheckInDate = useMemo(
|
||||
() => selectedBatchRecords.map((item) => item.checkInDate).filter(Boolean).sort().at(-1),
|
||||
[selectedBatchRecords],
|
||||
);
|
||||
const latestSelectedBillingStartDate = useMemo(
|
||||
() =>
|
||||
selectedBatchRecords
|
||||
.map((item) => item.billingStartDate || item.checkInDate)
|
||||
.filter(Boolean)
|
||||
.sort()
|
||||
.at(-1),
|
||||
[selectedBatchRecords],
|
||||
);
|
||||
|
||||
const dateNotBefore = (start: string | Dayjs | null | undefined, messageText: string) =>
|
||||
(_: unknown, value?: Dayjs | null) => {
|
||||
if (!value || !start) return Promise.resolve();
|
||||
const startDate = dayjs.isDayjs(start) ? start : dayjs(start);
|
||||
return value.isBefore(startDate, 'day')
|
||||
? Promise.reject(new Error(messageText))
|
||||
: Promise.resolve();
|
||||
};
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [occRes, stuRes, rmRes, tnRes] = (await Promise.allSettled([
|
||||
api.get('/occupancies', { params: { active: showActive ? 'true' : undefined, dateFrom: dateRange?.[0]?.format('YYYY-MM-DD'), dateTo: dateRange?.[1]?.format('YYYY-MM-DD') } }),
|
||||
const [occRes, stuRes, rmRes] = (await Promise.allSettled([
|
||||
api.get('/occupancies', {
|
||||
params: {
|
||||
active: showActive ? 'true' : undefined,
|
||||
dateFrom: dateRange?.[0]?.format('YYYY-MM-DD'),
|
||||
dateTo: dateRange?.[1]?.format('YYYY-MM-DD'),
|
||||
},
|
||||
}),
|
||||
api.get('/students/basic-lookups'),
|
||||
api.get('/rooms/overview'),
|
||||
api.get('/organizations'),
|
||||
])) as PromiseSettledResult<any>[];
|
||||
const labels = ['入住数据', '学生列表', '房间列表', '机构列表'];
|
||||
[occRes, stuRes, rmRes, tnRes].forEach((res, i) => {
|
||||
const labels = ['入住数据', '学生列表', '房间列表'];
|
||||
[occRes, stuRes, rmRes].forEach((res, i) => {
|
||||
if (res.status === 'rejected') {
|
||||
message.warning(`${labels[i]}加载失败`);
|
||||
}
|
||||
@@ -81,7 +138,6 @@ const OccupanciesPage: React.FC = () => {
|
||||
setData(occRes.status === 'fulfilled' ? occRes.value : []);
|
||||
setStudents(stuRes.status === 'fulfilled' ? stuRes.value : []);
|
||||
setRooms(rmRes.status === 'fulfilled' ? rmRes.value : []);
|
||||
setOrganizations(tnRes.status === 'fulfilled' ? tnRes.value : []);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
message.error('数据加载异常');
|
||||
@@ -97,11 +153,11 @@ const OccupanciesPage: React.FC = () => {
|
||||
const handleRoomChange = async (roomId: number) => {
|
||||
checkInForm.setFieldValue('bedId', undefined);
|
||||
checkInForm.setFieldValue('lockerId', undefined);
|
||||
if (!roomId) {
|
||||
setAvailableBeds([]);
|
||||
setAvailableLockers([]);
|
||||
return;
|
||||
}
|
||||
setAvailableBeds([]);
|
||||
setAvailableLockers([]);
|
||||
if (!roomId) return;
|
||||
|
||||
setAvailableResourcesLoading(true);
|
||||
try {
|
||||
const [beds, lockers] = await Promise.all([
|
||||
api.get<any[]>(`/rooms/${roomId}/beds/available`),
|
||||
@@ -110,17 +166,25 @@ const OccupanciesPage: React.FC = () => {
|
||||
setAvailableBeds(beds);
|
||||
setAvailableLockers(lockers);
|
||||
if (beds.length === 1) checkInForm.setFieldValue('bedId', beds[0].id);
|
||||
} catch (e) { console.error(e); }
|
||||
if (beds.length === 0) message.warning('该宿舍暂无可用床位,请先在宿舍详情添加或释放床位');
|
||||
} catch (e: any) {
|
||||
console.error(e);
|
||||
setAvailableBeds([]);
|
||||
setAvailableLockers([]);
|
||||
message.error(e?.message || '宿舍床位和柜子加载失败');
|
||||
} finally {
|
||||
setAvailableResourcesLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleTransferRoomChange = async (roomId: number) => {
|
||||
transferForm.setFieldValue('newBedId', undefined);
|
||||
transferForm.setFieldValue('newLockerId', undefined);
|
||||
if (!roomId) {
|
||||
setTransferAvailableBeds([]);
|
||||
setTransferAvailableLockers([]);
|
||||
return;
|
||||
}
|
||||
setTransferAvailableBeds([]);
|
||||
setTransferAvailableLockers([]);
|
||||
if (!roomId) return;
|
||||
|
||||
setTransferResourcesLoading(true);
|
||||
try {
|
||||
const [beds, lockers] = await Promise.all([
|
||||
api.get<any[]>(`/rooms/${roomId}/beds/available`),
|
||||
@@ -129,11 +193,14 @@ const OccupanciesPage: React.FC = () => {
|
||||
setTransferAvailableBeds(beds);
|
||||
setTransferAvailableLockers(lockers);
|
||||
if (beds.length === 1) transferForm.setFieldValue('newBedId', beds[0].id);
|
||||
} catch (e) {
|
||||
if (beds.length === 0) message.warning('目标宿舍暂无可用床位,请先在宿舍详情添加或释放床位');
|
||||
} catch (e: any) {
|
||||
console.error(e);
|
||||
setTransferAvailableBeds([]);
|
||||
setTransferAvailableLockers([]);
|
||||
message.error('目标宿舍床位和柜子加载失败');
|
||||
message.error(e?.message || '目标宿舍床位和柜子加载失败');
|
||||
} finally {
|
||||
setTransferResourcesLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -151,17 +218,7 @@ const OccupanciesPage: React.FC = () => {
|
||||
const values = await checkInForm.validateFields();
|
||||
setSaving(true);
|
||||
try {
|
||||
await api.post('/occupancies/check-in', {
|
||||
studentId: values.studentId,
|
||||
roomId: values.roomId,
|
||||
checkInDate: values.checkInDate.format('YYYY-MM-DD'),
|
||||
billingStartDate: values.billingStartDate?.format('YYYY-MM-DD'),
|
||||
stayType: values.stayType,
|
||||
responsibleOrganizationId: values.responsibleOrganizationId,
|
||||
notes: values.notes,
|
||||
bedId: values.bedId,
|
||||
lockerId: values.lockerId || undefined,
|
||||
});
|
||||
await api.post('/occupancies/check-in', buildCheckInPayload(values));
|
||||
message.success('入住登记成功');
|
||||
setCheckInModal(false);
|
||||
checkInForm.resetFields();
|
||||
@@ -197,10 +254,7 @@ const OccupanciesPage: React.FC = () => {
|
||||
const values = await transferForm.validateFields();
|
||||
setSaving(true);
|
||||
try {
|
||||
await api.put(
|
||||
`/occupancies/${transferModal.id}/transfer`,
|
||||
buildTransferPayload(values),
|
||||
);
|
||||
await api.put(`/occupancies/${transferModal.id}/transfer`, buildTransferPayload(values));
|
||||
message.success('换房成功');
|
||||
setTransferModal(null);
|
||||
transferForm.resetFields();
|
||||
@@ -238,114 +292,127 @@ const OccupanciesPage: React.FC = () => {
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
const res: any = await api.post('/occupancies/batch-delete', { ids: selectedRowKeys });
|
||||
message.success(res?.message || `已删除 ${selectedRowKeys.length} 条`);
|
||||
message.success(res?.message || `已归档 ${selectedRowKeys.length} 条`);
|
||||
setSelectedRowKeys([]);
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '批量删除失败');
|
||||
message.error(e?.message || '批量归档失败');
|
||||
} finally {
|
||||
setBatchLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const columns = useMemo(() => [
|
||||
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
|
||||
{ title: '宿舍', width: 120, render: (_: any, r: any) => r.room?.roomNumber || '-' },
|
||||
{ title: '床位', width: 80, render: (_: unknown, r: Record<string, unknown>) => (r.bed as Record<string, string> | undefined)?.bedNumber || '-' },
|
||||
{ title: '柜子', width: 80, render: (_: unknown, r: Record<string, unknown>) => (r.locker as Record<string, string> | undefined)?.lockerNumber || '-' },
|
||||
{ title: '入住日期', dataIndex: 'checkInDate', width: 110 },
|
||||
{ title: '计费起始', dataIndex: 'billingStartDate', width: 110 },
|
||||
{
|
||||
title: '退宿日期',
|
||||
dataIndex: 'checkOutDate',
|
||||
width: 110,
|
||||
render: (v: any) => v || <Tag color="green">在住</Tag>,
|
||||
},
|
||||
{ title: '计费截止', dataIndex: 'billingEndDate', render: (v: any) => v || '-' },
|
||||
{ title: '退宿原因', dataIndex: 'checkOutReason', render: (v: any) => v || '-' },
|
||||
{
|
||||
title: '操作',
|
||||
width: 220,
|
||||
render: (_: any, record: any) =>
|
||||
!record.checkOutDate ? (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="occupancy:checkout"
|
||||
size="small"
|
||||
icon={<LogoutOutlined />}
|
||||
onClick={() => {
|
||||
setCheckOutModal(record);
|
||||
checkOutForm.setFieldsValue({ checkOutDate: dayjs() });
|
||||
}}
|
||||
>
|
||||
退宿
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="occupancy:transfer"
|
||||
size="small"
|
||||
icon={<SwapOutlined />}
|
||||
onClick={() => {
|
||||
setTransferAvailableBeds([]);
|
||||
setTransferAvailableLockers([]);
|
||||
transferForm.resetFields();
|
||||
setTransferModal(record);
|
||||
transferForm.setFieldsValue({ transferDate: dayjs() });
|
||||
}}
|
||||
>
|
||||
换房
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
) : (
|
||||
<Space>
|
||||
<Tag>已退宿</Tag>
|
||||
<Popconfirm
|
||||
title="确定删除此记录?"
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await api.delete(`/occupancies/${record.id}`);
|
||||
message.success('删除成功');
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '删除失败');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<PermissionButton permission="occupancy:delete" size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
|
||||
{ title: '宿舍', width: 120, render: (_: any, r: any) => r.room?.roomNumber || '-' },
|
||||
{
|
||||
title: '床位',
|
||||
width: 80,
|
||||
render: (_: unknown, r: Record<string, unknown>) =>
|
||||
(r.bed as Record<string, string> | undefined)?.bedNumber || '-',
|
||||
},
|
||||
{
|
||||
title: '柜子',
|
||||
width: 80,
|
||||
render: (_: unknown, r: Record<string, unknown>) =>
|
||||
(r.locker as Record<string, string> | undefined)?.lockerNumber || '-',
|
||||
},
|
||||
{ title: '入住日期', dataIndex: 'checkInDate', width: 110 },
|
||||
{ title: '计费起始', dataIndex: 'billingStartDate', width: 110 },
|
||||
{
|
||||
title: '退宿日期',
|
||||
dataIndex: 'checkOutDate',
|
||||
width: 110,
|
||||
render: (v: any) => v || <Tag color="green">在住</Tag>,
|
||||
},
|
||||
{ title: '计费截止', dataIndex: 'billingEndDate', render: (v: any) => v || '-' },
|
||||
{ title: '退宿原因', dataIndex: 'checkOutReason', render: (v: any) => v || '-' },
|
||||
{
|
||||
title: '操作',
|
||||
width: 220,
|
||||
render: (_: any, record: any) =>
|
||||
!record.checkOutDate ? (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="occupancy:checkout"
|
||||
size="small"
|
||||
icon={<LogoutOutlined />}
|
||||
onClick={() => {
|
||||
setCheckOutModal(record);
|
||||
checkOutForm.setFieldsValue({ checkOutDate: dayjs() });
|
||||
}}
|
||||
>
|
||||
退宿
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
], [fetchData, setCheckOutModal, checkOutForm, setTransferModal, transferForm]);
|
||||
<PermissionButton
|
||||
permission="occupancy:transfer"
|
||||
size="small"
|
||||
icon={<SwapOutlined />}
|
||||
onClick={() => {
|
||||
setTransferAvailableBeds([]);
|
||||
setTransferAvailableLockers([]);
|
||||
transferForm.resetFields();
|
||||
setTransferModal(record);
|
||||
transferForm.setFieldsValue({ transferDate: dayjs() });
|
||||
}}
|
||||
>
|
||||
换房
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
) : (
|
||||
<Space>
|
||||
<Tag>已退宿</Tag>
|
||||
<Popconfirm
|
||||
title="确定归档此记录?"
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await api.delete(`/occupancies/${record.id}`);
|
||||
message.success('归档成功');
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '归档失败');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="occupancy:delete"
|
||||
size="small"
|
||||
danger
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
],
|
||||
[fetchData, setCheckOutModal, checkOutForm, setTransferModal, transferForm],
|
||||
);
|
||||
|
||||
const rowSelection = useMemo(() => ({
|
||||
selectedRowKeys,
|
||||
onChange: (keys: any[]) => setSelectedRowKeys(keys),
|
||||
// 「在住记录」Tab:禁用已退宿(防止误选用于批量退宿);「全部记录」Tab:均可选用于批量删除
|
||||
getCheckboxProps: (record: any) => (showActive ? { disabled: !!record.checkOutDate } : {}),
|
||||
}), [selectedRowKeys, showActive]);
|
||||
const rowSelection = useMemo(
|
||||
() => ({
|
||||
selectedRowKeys,
|
||||
onChange: (keys: any[]) => setSelectedRowKeys(keys),
|
||||
// 「在住记录」Tab:禁用已退宿(防止误选用于批量退宿);「全部记录」Tab:均可选用于批量归档
|
||||
getCheckboxProps: (record: any) => (showActive ? { disabled: !!record.checkOutDate } : {}),
|
||||
}),
|
||||
[selectedRowKeys, showActive],
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Alert
|
||||
title="一站式导入"
|
||||
description="导入入住名单时会自动创建学生和宿舍,无需单独在「学生管理」或「宿舍管理」中手动添加。后续仅需在此页面处理换房/退宿等日常操作即可。"
|
||||
description="导入入住名单时会优先按手机号关联已有学生,所属机构自动取学生档案;未找到学生或宿舍时会自动创建。后续仅需在此页面处理换房/退宿等日常操作即可。"
|
||||
type="info"
|
||||
showIcon
|
||||
closable
|
||||
style={{ marginBottom: 16 }}
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<Space wrap>
|
||||
<div className="responsive-toolbar">
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<Button type={showActive ? 'primary' : 'default'} onClick={() => setShowActive(true)}>
|
||||
在住记录
|
||||
</Button>
|
||||
@@ -358,16 +425,33 @@ const OccupanciesPage: React.FC = () => {
|
||||
allowClear
|
||||
style={{ width: 200 }}
|
||||
/>
|
||||
<RangePicker value={dateRange} onChange={(dates) => { setDateRange(dates ? [dates[0], dates[1]] : null); }} placeholder={['入住开始', '入住结束']} style={{ width: 240 }} />
|
||||
<RangePicker
|
||||
value={dateRange}
|
||||
onChange={(dates) => {
|
||||
setDateRange(dates ? [dates[0], dates[1]] : null);
|
||||
}}
|
||||
placeholder={['入住开始', '入住结束']}
|
||||
style={{ width: 240 }}
|
||||
/>
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<PermissionButton
|
||||
permission="occupancy:checkin"
|
||||
type="primary"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => {
|
||||
checkInForm.resetFields();
|
||||
checkInForm.setFieldsValue({ checkInDate: dayjs() });
|
||||
setAvailableBeds([]);
|
||||
setAvailableLockers([]);
|
||||
setAvailableResourcesLoading(false);
|
||||
const today = dayjs();
|
||||
checkInForm.setFieldsValue({
|
||||
checkInDate: today,
|
||||
billingStartDate: today,
|
||||
stayType: 'short',
|
||||
collectDeposit: true,
|
||||
depositAmount: 500,
|
||||
});
|
||||
setCheckInModal(true);
|
||||
}}
|
||||
>
|
||||
@@ -407,7 +491,7 @@ const OccupanciesPage: React.FC = () => {
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Tooltip title="导入时自动创建学生、宿舍和入住记录">
|
||||
<Tooltip title="按手机号关联学生,并自动创建缺失的学生、宿舍和入住记录">
|
||||
<Button type="primary" ghost icon={<UploadOutlined />}>
|
||||
导入入住名单
|
||||
</Button>
|
||||
@@ -442,26 +526,26 @@ const OccupanciesPage: React.FC = () => {
|
||||
导入时自动收押金
|
||||
{autoDeposit && (
|
||||
<Space.Compact>
|
||||
<InputNumber
|
||||
size="small"
|
||||
min={0}
|
||||
value={depositAmount}
|
||||
onChange={(v) => setDepositAmount(v || 500)}
|
||||
style={{ width: 60 }}
|
||||
/>
|
||||
<span
|
||||
style={{
|
||||
padding: '0 8px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
border: '1px solid #d9d9d9',
|
||||
backgroundColor: '#fafafa',
|
||||
fontSize: 12,
|
||||
}}
|
||||
>
|
||||
元
|
||||
</span>
|
||||
</Space.Compact>
|
||||
<InputNumber
|
||||
size="small"
|
||||
min={0}
|
||||
value={depositAmount}
|
||||
onChange={(v) => setDepositAmount(v || 500)}
|
||||
style={{ width: 60 }}
|
||||
/>
|
||||
<span
|
||||
style={{
|
||||
padding: '0 8px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
border: '1px solid #d9d9d9',
|
||||
backgroundColor: '#fafafa',
|
||||
fontSize: 12,
|
||||
}}
|
||||
>
|
||||
元
|
||||
</span>
|
||||
</Space.Compact>
|
||||
)}
|
||||
</span>
|
||||
</Space>
|
||||
@@ -489,20 +573,20 @@ const OccupanciesPage: React.FC = () => {
|
||||
</PermissionButton>
|
||||
) : (
|
||||
<Popconfirm
|
||||
title={`确定删除选中的 ${selectedRowKeys.length} 条入住记录?在住记录会自动跳过`}
|
||||
title={`确定归档选中的 ${selectedRowKeys.length} 条入住记录?在住记录会自动跳过`}
|
||||
onConfirm={handleBatchDelete}
|
||||
okText="删除"
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
>
|
||||
<PermissionButton
|
||||
permission="occupancy:delete"
|
||||
danger
|
||||
size="small"
|
||||
icon={<DeleteOutlined />}
|
||||
icon={<InboxOutlined />}
|
||||
style={{ marginLeft: 12 }}
|
||||
loading={batchLoading}
|
||||
>
|
||||
批量删除
|
||||
批量归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
@@ -534,7 +618,12 @@ const OccupanciesPage: React.FC = () => {
|
||||
title="入住登记"
|
||||
open={checkInModal}
|
||||
onOk={handleCheckIn}
|
||||
onCancel={() => setCheckInModal(false)}
|
||||
onCancel={() => {
|
||||
setCheckInModal(false);
|
||||
setAvailableBeds([]);
|
||||
setAvailableLockers([]);
|
||||
setAvailableResourcesLoading(false);
|
||||
}}
|
||||
okText="确认入住"
|
||||
confirmLoading={saving}
|
||||
width={500}
|
||||
@@ -551,10 +640,15 @@ const OccupanciesPage: React.FC = () => {
|
||||
placeholder="搜索并选择学生"
|
||||
options={students
|
||||
.filter((s: any) => s.status === 'active')
|
||||
.map((s: any) => ({
|
||||
value: s.id,
|
||||
label: `${s.name} (${s.idNumber ? maskIdNumber(s.idNumber) : (s.phone ? maskPhone(s.phone) : '')})`,
|
||||
}))}
|
||||
.map((s: any) => {
|
||||
const activeOccupancy = activeOccupancyByStudentId.get(s.id);
|
||||
const identifier = s.idNumber ? maskIdNumber(s.idNumber) : s.phone ? maskPhone(s.phone) : '';
|
||||
return {
|
||||
value: s.id,
|
||||
label: `${s.name} (${identifier})${activeOccupancy ? ` · 已入住${activeOccupancy.room?.roomNumber ? ` ${activeOccupancy.room.roomNumber}` : ''}` : ''}`,
|
||||
disabled: !!activeOccupancy,
|
||||
};
|
||||
})}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
@@ -569,18 +663,25 @@ const OccupanciesPage: React.FC = () => {
|
||||
onChange={handleRoomChange}
|
||||
options={rooms.map((r) => ({
|
||||
value: r.id,
|
||||
label: `${r.roomNumber} (${r.building || ''}) [${r.currentCount}/${r.capacity}]`,
|
||||
disabled: r.currentCount >= r.capacity,
|
||||
label: roomOptionLabel(r),
|
||||
disabled: !isRoomSelectable(r),
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="checkInDate" label="入住日期" rules={[{ required: true }]}>
|
||||
<Form.Item name="checkInDate" label="入住日期" rules={[{ required: true, message: '请选择入住日期' }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择入住日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="billingStartDate"
|
||||
label="计费起始日"
|
||||
dependencies={["checkInDate"]}
|
||||
extra="默认与入住日期相同,可调整(如学生要求从次日开始计费)"
|
||||
rules={[
|
||||
{ required: true, message: '请选择计费起始日' },
|
||||
({ getFieldValue }) => ({
|
||||
validator: dateNotBefore(getFieldValue('checkInDate'), '计费起始日不能早于入住日期'),
|
||||
}),
|
||||
]}
|
||||
>
|
||||
<DatePicker
|
||||
style={{ width: '100%' }}
|
||||
@@ -588,9 +689,8 @@ const OccupanciesPage: React.FC = () => {
|
||||
format="YYYY-MM-DD"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="stayType" label="入住类型">
|
||||
<Form.Item name="stayType" label="入住类型" rules={[{ required: true, message: '请选择入住类型' }]}>
|
||||
<Select
|
||||
allowClear
|
||||
options={[
|
||||
{ value: 'short', label: '短租' },
|
||||
{ value: 'long', label: '长租' },
|
||||
@@ -598,31 +698,28 @@ const OccupanciesPage: React.FC = () => {
|
||||
placeholder="默认为短租"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="responsibleOrganizationId" label="负责机构">
|
||||
<Select
|
||||
showSearch
|
||||
allowClear
|
||||
optionFilterProp="label"
|
||||
placeholder="默认取学生所属机构"
|
||||
options={organizations.map((t: { id: number; name: string }) => ({
|
||||
value: t.id,
|
||||
label: t.name,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="bedId"
|
||||
label="床位"
|
||||
rules={[{ required: true, message: '请选择床位' }]}
|
||||
rules={[
|
||||
{ required: true, message: '请选择床位' },
|
||||
{
|
||||
validator: (_: unknown, value?: number) =>
|
||||
!value || availableBeds.some((bed) => bed.id === value)
|
||||
? Promise.resolve()
|
||||
: Promise.reject(new Error('请选择当前宿舍下的可用床位')),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Select
|
||||
placeholder="请先选择房间"
|
||||
disabled={availableBeds.length === 0}
|
||||
placeholder={selectedCheckInRoomId ? '请选择床位' : '请先选择房间'}
|
||||
loading={availableResourcesLoading}
|
||||
disabled={!selectedCheckInRoomId || availableResourcesLoading || availableBeds.length === 0}
|
||||
options={availableBeds.map((b) => ({
|
||||
value: b.id,
|
||||
label: b.bedNumber,
|
||||
}))}
|
||||
notFoundContent="该房间暂无可用床位"
|
||||
notFoundContent={selectedCheckInRoomId ? '该房间暂无可用床位' : '请先选择房间'}
|
||||
/>
|
||||
</Form.Item>
|
||||
{availableBeds.length > 0 && (
|
||||
@@ -634,13 +731,38 @@ const OccupanciesPage: React.FC = () => {
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="可选分配柜子"
|
||||
disabled={availableLockers.length === 0}
|
||||
loading={availableResourcesLoading}
|
||||
disabled={!selectedCheckInRoomId || availableResourcesLoading || availableLockers.length === 0}
|
||||
options={availableLockers.map((l) => ({
|
||||
value: l.id,
|
||||
label: l.lockerNumber,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="collectDeposit"
|
||||
label="押金缴纳"
|
||||
valuePropName="checked"
|
||||
extra="开启后,确认入住时同步生成已缴押金记录;已有已缴押金时不会重复创建"
|
||||
>
|
||||
<Switch checkedChildren="已缴" unCheckedChildren="不缴" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
noStyle
|
||||
shouldUpdate={(prev, current) => prev.collectDeposit !== current.collectDeposit}
|
||||
>
|
||||
{({ getFieldValue }) =>
|
||||
getFieldValue('collectDeposit') ? (
|
||||
<Form.Item
|
||||
name="depositAmount"
|
||||
label="押金金额"
|
||||
rules={[{ required: true, message: '请输入押金金额' }]}
|
||||
>
|
||||
<InputNumber min={0.01} precision={2} addonAfter="元" style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
) : null
|
||||
}
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
@@ -657,10 +779,30 @@ const OccupanciesPage: React.FC = () => {
|
||||
confirmLoading={saving}
|
||||
>
|
||||
<Form form={checkOutForm} layout="vertical">
|
||||
<Form.Item name="checkOutDate" label="退宿日期" rules={[{ required: true }]}>
|
||||
<Form.Item
|
||||
name="checkOutDate"
|
||||
label="退宿日期"
|
||||
rules={[
|
||||
{ required: true, message: '请选择退宿日期' },
|
||||
{ validator: dateNotBefore(checkOutModal?.checkInDate, '退宿日期不能早于入住日期') },
|
||||
]}
|
||||
>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择退宿日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="billingEndDate" label="计费截止日" extra="默认与退宿日期相同">
|
||||
<Form.Item
|
||||
name="billingEndDate"
|
||||
label="计费截止日"
|
||||
dependencies={["checkOutDate"]}
|
||||
extra="默认与退宿日期相同"
|
||||
rules={[
|
||||
({ getFieldValue }) => ({
|
||||
validator: dateNotBefore(
|
||||
checkOutModal?.billingStartDate || checkOutModal?.checkInDate || getFieldValue('checkOutDate'),
|
||||
'计费截止日不能早于计费起始日',
|
||||
),
|
||||
}),
|
||||
]}
|
||||
>
|
||||
<DatePicker
|
||||
style={{ width: '100%' }}
|
||||
placeholder="选择计费截止日"
|
||||
@@ -692,10 +834,34 @@ const OccupanciesPage: React.FC = () => {
|
||||
width={500}
|
||||
>
|
||||
<Form form={batchCheckOutForm} layout="vertical">
|
||||
<Form.Item name="checkOutDate" label="退宿日期" rules={[{ required: true }]}>
|
||||
<Form.Item
|
||||
name="checkOutDate"
|
||||
label="退宿日期"
|
||||
rules={[
|
||||
{ required: true, message: '请选择退宿日期' },
|
||||
{
|
||||
validator: dateNotBefore(
|
||||
latestSelectedCheckInDate,
|
||||
'退宿日期不能早于所选记录中最晚的入住日期',
|
||||
),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择退宿日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="billingEndDate" label="计费截止日" extra="默认与退宿日期相同">
|
||||
<Form.Item
|
||||
name="billingEndDate"
|
||||
label="计费截止日"
|
||||
extra="默认与退宿日期相同"
|
||||
rules={[
|
||||
{
|
||||
validator: dateNotBefore(
|
||||
latestSelectedBillingStartDate,
|
||||
'计费截止日不能早于所选记录中最晚的计费起始日',
|
||||
),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<DatePicker
|
||||
style={{ width: '100%' }}
|
||||
placeholder="选择计费截止日"
|
||||
@@ -761,24 +927,33 @@ const OccupanciesPage: React.FC = () => {
|
||||
.filter((r: any) => r.id !== transferModal?.roomId)
|
||||
.map((r: any) => ({
|
||||
value: r.id,
|
||||
label: `${r.roomNumber} (${r.building || ''}) [${r.currentCount}/${r.capacity}]`,
|
||||
disabled: r.currentCount >= r.capacity,
|
||||
label: roomOptionLabel(r),
|
||||
disabled: !isRoomSelectable(r),
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="newBedId"
|
||||
label="目标床位"
|
||||
rules={[{ required: true, message: '请选择目标床位' }]}
|
||||
rules={[
|
||||
{ required: true, message: '请选择目标床位' },
|
||||
{
|
||||
validator: (_: unknown, value?: number) =>
|
||||
!value || transferAvailableBeds.some((bed) => bed.id === value)
|
||||
? Promise.resolve()
|
||||
: Promise.reject(new Error('请选择目标宿舍下的可用床位')),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Select
|
||||
placeholder="请先选择目标宿舍"
|
||||
disabled={transferAvailableBeds.length === 0}
|
||||
placeholder={selectedTransferRoomId ? '请选择目标床位' : '请先选择目标宿舍'}
|
||||
loading={transferResourcesLoading}
|
||||
disabled={!selectedTransferRoomId || transferResourcesLoading || transferAvailableBeds.length === 0}
|
||||
options={transferAvailableBeds.map((bed) => ({
|
||||
value: bed.id,
|
||||
label: bed.bedNumber,
|
||||
}))}
|
||||
notFoundContent="目标宿舍暂无可用床位"
|
||||
notFoundContent={selectedTransferRoomId ? '目标宿舍暂无可用床位' : '请先选择目标宿舍'}
|
||||
/>
|
||||
</Form.Item>
|
||||
{transferAvailableBeds.length > 0 && (
|
||||
@@ -790,7 +965,8 @@ const OccupanciesPage: React.FC = () => {
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="可选分配目标宿舍柜子"
|
||||
disabled={transferAvailableLockers.length === 0}
|
||||
loading={transferResourcesLoading}
|
||||
disabled={!selectedTransferRoomId || transferResourcesLoading || transferAvailableLockers.length === 0}
|
||||
options={transferAvailableLockers.map((locker) => ({
|
||||
value: locker.id,
|
||||
label: locker.lockerNumber,
|
||||
@@ -798,17 +974,47 @@ const OccupanciesPage: React.FC = () => {
|
||||
notFoundContent="目标宿舍暂无可用柜子"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="transferDate" label="换房日期" rules={[{ required: true }]}>
|
||||
<Form.Item
|
||||
name="transferDate"
|
||||
label="换房日期"
|
||||
rules={[
|
||||
{ required: true, message: '请选择换房日期' },
|
||||
{ validator: dateNotBefore(transferModal?.checkInDate, '换房日期不能早于原入住日期') },
|
||||
]}
|
||||
>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择换房日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="oldBillingEndDate" label="旧房计费截止日" extra="默认为换房当天">
|
||||
<Form.Item
|
||||
name="oldBillingEndDate"
|
||||
label="旧房计费截止日"
|
||||
dependencies={["transferDate"]}
|
||||
extra="默认为换房当天"
|
||||
rules={[
|
||||
({ getFieldValue }) => ({
|
||||
validator: dateNotBefore(
|
||||
transferModal?.billingStartDate || transferModal?.checkInDate || getFieldValue('transferDate'),
|
||||
'旧房计费截止日不能早于计费起始日',
|
||||
),
|
||||
}),
|
||||
]}
|
||||
>
|
||||
<DatePicker
|
||||
style={{ width: '100%' }}
|
||||
placeholder="选择旧房计费截止日"
|
||||
format="YYYY-MM-DD"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="newBillingStartDate" label="新房计费起始日" extra="默认为换房次日">
|
||||
<Form.Item
|
||||
name="newBillingStartDate"
|
||||
label="新房计费起始日"
|
||||
dependencies={["transferDate"]}
|
||||
extra="默认为换房次日"
|
||||
rules={[
|
||||
({ getFieldValue }) => ({
|
||||
validator: dateNotBefore(getFieldValue('transferDate'), '新房计费起始日不能早于换房日期'),
|
||||
}),
|
||||
]}
|
||||
>
|
||||
<DatePicker
|
||||
style={{ width: '100%' }}
|
||||
placeholder="选择新房计费起始日"
|
||||
|
||||
@@ -1,6 +1,54 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import dayjs from 'dayjs';
|
||||
import { buildTransferPayload } from './occupancy-form';
|
||||
import { buildCheckInPayload, buildTransferPayload } from './occupancy-form';
|
||||
|
||||
describe('occupancy check-in form', () => {
|
||||
it('submits all required manual check-in fields with defaults', () => {
|
||||
expect(
|
||||
buildCheckInPayload({
|
||||
studentId: 1,
|
||||
roomId: 2,
|
||||
checkInDate: dayjs('2026-07-18'),
|
||||
billingStartDate: dayjs('2026-07-18'),
|
||||
stayType: 'short',
|
||||
collectDeposit: true,
|
||||
depositAmount: 500,
|
||||
bedId: 3,
|
||||
notes: ' 备注 ',
|
||||
}),
|
||||
).toEqual({
|
||||
studentId: 1,
|
||||
roomId: 2,
|
||||
checkInDate: '2026-07-18',
|
||||
billingStartDate: '2026-07-18',
|
||||
stayType: 'short',
|
||||
collectDeposit: true,
|
||||
depositAmount: 500,
|
||||
notes: '备注',
|
||||
bedId: 3,
|
||||
lockerId: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to check-in date and short stay type', () => {
|
||||
expect(
|
||||
buildCheckInPayload({
|
||||
studentId: 1,
|
||||
roomId: 2,
|
||||
checkInDate: dayjs('2026-07-18'),
|
||||
collectDeposit: false,
|
||||
bedId: 3,
|
||||
}),
|
||||
).toEqual(
|
||||
expect.objectContaining({
|
||||
billingStartDate: '2026-07-18',
|
||||
stayType: 'short',
|
||||
collectDeposit: false,
|
||||
depositAmount: undefined,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('occupancy transfer form', () => {
|
||||
it('submits the target room resources with the transfer dates', () => {
|
||||
|
||||
@@ -1,5 +1,34 @@
|
||||
import type { Dayjs } from 'dayjs';
|
||||
|
||||
export interface CheckInFormValues {
|
||||
studentId: number;
|
||||
roomId: number;
|
||||
checkInDate: Dayjs;
|
||||
billingStartDate?: Dayjs;
|
||||
stayType?: string;
|
||||
collectDeposit?: boolean;
|
||||
depositAmount?: number;
|
||||
notes?: string;
|
||||
bedId: number;
|
||||
lockerId?: number;
|
||||
}
|
||||
|
||||
export const buildCheckInPayload = (values: CheckInFormValues) => {
|
||||
const collectDeposit = values.collectDeposit ?? false;
|
||||
return {
|
||||
studentId: values.studentId,
|
||||
roomId: values.roomId,
|
||||
checkInDate: values.checkInDate.format('YYYY-MM-DD'),
|
||||
billingStartDate: (values.billingStartDate || values.checkInDate).format('YYYY-MM-DD'),
|
||||
stayType: values.stayType || 'short',
|
||||
collectDeposit,
|
||||
depositAmount: collectDeposit ? values.depositAmount ?? 500 : undefined,
|
||||
notes: values.notes?.trim() || undefined,
|
||||
bedId: values.bedId,
|
||||
lockerId: values.lockerId || undefined,
|
||||
};
|
||||
};
|
||||
|
||||
export interface TransferFormValues {
|
||||
newRoomId: number;
|
||||
newBedId: number;
|
||||
|
||||
@@ -53,63 +53,67 @@ const OperationLogsPage: React.FC = () => {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
const columns = useMemo(() => [
|
||||
{
|
||||
title: '时间',
|
||||
dataIndex: 'createdAt',
|
||||
width: 170,
|
||||
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm:ss'),
|
||||
},
|
||||
{ title: '操作人', dataIndex: 'username', width: 100 },
|
||||
{
|
||||
title: '模块',
|
||||
dataIndex: 'module',
|
||||
width: 100,
|
||||
render: (v: string) => <Tag color={moduleColorMap[v] || 'default'}>{v}</Tag>,
|
||||
},
|
||||
{ title: '操作', dataIndex: 'action', width: 150 },
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 80,
|
||||
render: (v: string) => {
|
||||
const s = statusMap[v] || statusMap['success'];
|
||||
return <Tag color={s.color}>{s.text}</Tag>;
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: '时间',
|
||||
dataIndex: 'createdAt',
|
||||
width: 170,
|
||||
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm:ss'),
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '详情', width: 200,
|
||||
dataIndex: 'detail',
|
||||
ellipsis: true,
|
||||
render: (v: string) =>
|
||||
v ? (
|
||||
<Tooltip title={v}>
|
||||
<span>{v}</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
'-'
|
||||
),
|
||||
},
|
||||
{ title: 'IP地址', dataIndex: 'ipAddress', width: 130, render: (v: string) => v || '-' },
|
||||
{
|
||||
title: '终端',
|
||||
dataIndex: 'userAgent',
|
||||
width: 120,
|
||||
ellipsis: true,
|
||||
render: (v: string) => {
|
||||
if (!v) return '-';
|
||||
if (v.includes('Mobile')) return <Tag color="blue">手机</Tag>;
|
||||
if (v.includes('Windows')) return <Tag>Windows</Tag>;
|
||||
if (v.includes('Mac')) return <Tag>Mac</Tag>;
|
||||
if (v.includes('Linux')) return <Tag>Linux</Tag>;
|
||||
return (
|
||||
<Tooltip title={v}>
|
||||
<Tag>其他</Tag>
|
||||
</Tooltip>
|
||||
);
|
||||
{ title: '操作人', dataIndex: 'username', width: 100 },
|
||||
{
|
||||
title: '模块',
|
||||
dataIndex: 'module',
|
||||
width: 100,
|
||||
render: (v: string) => <Tag color={moduleColorMap[v] || 'default'}>{v}</Tag>,
|
||||
},
|
||||
},
|
||||
], []);
|
||||
{ title: '操作', dataIndex: 'action', width: 150 },
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 80,
|
||||
render: (v: string) => {
|
||||
const s = statusMap[v] || statusMap['success'];
|
||||
return <Tag color={s.color}>{s.text}</Tag>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '详情',
|
||||
width: 200,
|
||||
dataIndex: 'detail',
|
||||
ellipsis: true,
|
||||
render: (v: string) =>
|
||||
v ? (
|
||||
<Tooltip title={v}>
|
||||
<span>{v}</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
'-'
|
||||
),
|
||||
},
|
||||
{ title: 'IP地址', dataIndex: 'ipAddress', width: 130, render: (v: string) => v || '-' },
|
||||
{
|
||||
title: '终端',
|
||||
dataIndex: 'userAgent',
|
||||
width: 120,
|
||||
ellipsis: true,
|
||||
render: (v: string) => {
|
||||
if (!v) return '-';
|
||||
if (v.includes('Mobile')) return <Tag color="blue">手机</Tag>;
|
||||
if (v.includes('Windows')) return <Tag>Windows</Tag>;
|
||||
if (v.includes('Mac')) return <Tag>Mac</Tag>;
|
||||
if (v.includes('Linux')) return <Tag>Linux</Tag>;
|
||||
return (
|
||||
<Tooltip title={v}>
|
||||
<Tag>其他</Tag>
|
||||
</Tooltip>
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { Alert, Empty, Form, Input, Modal, Popconfirm, Select, Space, Table, Tag } from 'antd';
|
||||
import { BankOutlined, InboxOutlined, PlusOutlined } from '@ant-design/icons';
|
||||
import { BankOutlined, InboxOutlined, PlusOutlined, UndoOutlined } from '@ant-design/icons';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { message } from '../../ui/app-message';
|
||||
@@ -148,35 +148,61 @@ const OrganizationsPage: React.FC = () => {
|
||||
width: 160,
|
||||
render: (_: unknown, record: OrganizationItem) => (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="organization:edit"
|
||||
size="small"
|
||||
onClick={() => openEditor(record)}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
{!record.isHost && record.status === 'active' ? (
|
||||
{record.status === 'archived' ? (
|
||||
<Popconfirm
|
||||
title="归档后仍保留历史学生、入住和租赁记录"
|
||||
title="确定恢复此机构?"
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await api.delete(`/organizations/${record.id}`);
|
||||
message.success('机构已归档');
|
||||
await api.put(`/organizations/${record.id}`, { status: 'active' });
|
||||
message.success('机构已恢复');
|
||||
await fetchData();
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '归档失败');
|
||||
message.error(error?.message || '恢复失败');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="organization:delete"
|
||||
permission="organization:edit"
|
||||
size="small"
|
||||
icon={<InboxOutlined />}
|
||||
type="link"
|
||||
icon={<UndoOutlined />}
|
||||
>
|
||||
归档
|
||||
恢复
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
) : null}
|
||||
) : (
|
||||
<>
|
||||
<PermissionButton
|
||||
permission="organization:edit"
|
||||
size="small"
|
||||
onClick={() => openEditor(record)}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
{!record.isHost ? (
|
||||
<Popconfirm
|
||||
title="归档后仍保留历史学生、入住和租赁记录"
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await api.delete(`/organizations/${record.id}`);
|
||||
message.success('机构已归档');
|
||||
await fetchData();
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '归档失败');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="organization:delete"
|
||||
size="small"
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
|
||||
@@ -37,13 +37,9 @@ const PermissionsPage: React.FC = () => {
|
||||
class: '班级管理',
|
||||
schedule: '排课管理',
|
||||
attendance: '考勤管理',
|
||||
learning: '学习记录',
|
||||
exam: '考试管理',
|
||||
sync: '数据同步',
|
||||
integration: '集成配置',
|
||||
department: '部门管理',
|
||||
notification: '通知中心',
|
||||
profile: '个人资料',
|
||||
ai: 'AI 模型配置',
|
||||
};
|
||||
|
||||
|
||||
@@ -1,17 +1,6 @@
|
||||
import React, { useEffect, useState, useMemo, useCallback } from 'react';
|
||||
import {
|
||||
Table,
|
||||
Modal,
|
||||
Form,
|
||||
Input,
|
||||
Space,
|
||||
Tag,
|
||||
Popconfirm,
|
||||
Card,
|
||||
Checkbox,
|
||||
Empty,
|
||||
} from 'antd';
|
||||
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
|
||||
import { Table, Modal, Form, Input, Space, Tag, Popconfirm, Card, Checkbox, Empty } from 'antd';
|
||||
import { PlusOutlined, EditOutlined, StopOutlined } from '@ant-design/icons';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { message } from '../../ui/app-message';
|
||||
@@ -106,79 +95,99 @@ const RolesPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
const handleDisable = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/rbac/roles/${id}`);
|
||||
message.success('角色已删除');
|
||||
message.success('角色已停用');
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e.message || '删除失败');
|
||||
message.error(e.message || '停用失败');
|
||||
}
|
||||
};
|
||||
|
||||
const groupNames: Record<string, string> = {
|
||||
dashboard: '数据面板',
|
||||
notification: '通知中心',
|
||||
student: '学生管理',
|
||||
'student-scope': '学生范围权限',
|
||||
teacher: '教师管理',
|
||||
'teacher-workspace': '教师工作台',
|
||||
room: '宿舍管理',
|
||||
occupancy: '入住管理',
|
||||
expense: '费用管理',
|
||||
bill: '账单管理',
|
||||
deposit: '押金管理',
|
||||
wallet: '学生余额',
|
||||
classroom: '教室管理',
|
||||
organization: '机构管理',
|
||||
rental: '租赁订单',
|
||||
class: '班级管理',
|
||||
schedule: '排课管理',
|
||||
attendance: '考勤管理',
|
||||
'attendance-scope': '考勤范围权限',
|
||||
log: '操作日志',
|
||||
user: '用户管理',
|
||||
role: '角色管理',
|
||||
sync: '数据同步',
|
||||
integration: '集成配置',
|
||||
ai: 'AI 配置',
|
||||
};
|
||||
|
||||
const columns = useMemo(() => [
|
||||
{ title: 'ID', dataIndex: 'id', width: 80 },
|
||||
{ title: '名称', dataIndex: 'name', width: 120 },
|
||||
{ title: '描述', dataIndex: 'description', width: 200 },
|
||||
{
|
||||
title: '权限标签',
|
||||
dataIndex: 'permissions',
|
||||
width: 150,
|
||||
render: (perms: PermissionItem[]) =>
|
||||
perms?.length > 0 ? (
|
||||
<Tag color="blue">{perms.length} 个权限</Tag>
|
||||
) : (
|
||||
<Tag color="default">无权限</Tag>
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{ title: 'ID', dataIndex: 'id', width: 80 },
|
||||
{ title: '名称', dataIndex: 'name', width: 120 },
|
||||
{ title: '描述', dataIndex: 'description', width: 200 },
|
||||
{
|
||||
title: '权限标签',
|
||||
dataIndex: 'permissions',
|
||||
width: 150,
|
||||
render: (perms: PermissionItem[]) =>
|
||||
perms?.length > 0 ? (
|
||||
<Tag color="blue">{perms.length} 个权限</Tag>
|
||||
) : (
|
||||
<Tag color="default">无权限</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '系统',
|
||||
dataIndex: 'isSystem',
|
||||
width: 80,
|
||||
render: (v: boolean) => (v ? <Tag color="orange">系统</Tag> : null),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 180,
|
||||
fixed: 'right' as const,
|
||||
render: (_: any, record: RoleItem) => (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="role:edit"
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => handleEdit(record)}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
{!record.isSystem && (
|
||||
<Popconfirm title="确认停用该角色?" onConfirm={() => handleDisable(record.id)}>
|
||||
<PermissionButton
|
||||
permission="role:delete"
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<StopOutlined />}
|
||||
>
|
||||
停用
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '系统',
|
||||
dataIndex: 'isSystem',
|
||||
width: 80,
|
||||
render: (v: boolean) => (v ? <Tag color="orange">系统</Tag> : null),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 180,
|
||||
fixed: 'right' as const,
|
||||
render: (_: any, record: RoleItem) => (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="role:edit"
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => handleEdit(record)}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
{!record.isSystem && (
|
||||
<Popconfirm title="确认删除该角色?" onConfirm={() => handleDelete(record.id)}>
|
||||
<PermissionButton permission="role:delete" type="link" size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
], []);
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
const handleGroupCheckAll = (group: string, checked: boolean) => {
|
||||
const groupPermIds =
|
||||
|
||||
@@ -1,6 +1,27 @@
|
||||
import React, { useEffect, useState, useCallback } from 'react';
|
||||
import { Row, Col, Card, Tag, Select, Statistic, Modal, Spin, Badge, Tooltip, DatePicker, Alert, Button } from 'antd';
|
||||
import { HomeOutlined, UserOutlined, CalendarOutlined, BankOutlined, HistoryOutlined, ShopOutlined } from '@ant-design/icons';
|
||||
import {
|
||||
Row,
|
||||
Col,
|
||||
Card,
|
||||
Tag,
|
||||
Select,
|
||||
Statistic,
|
||||
Modal,
|
||||
Spin,
|
||||
Badge,
|
||||
Tooltip,
|
||||
DatePicker,
|
||||
Alert,
|
||||
Button,
|
||||
} from 'antd';
|
||||
import {
|
||||
HomeOutlined,
|
||||
UserOutlined,
|
||||
CalendarOutlined,
|
||||
BankOutlined,
|
||||
HistoryOutlined,
|
||||
ShopOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import dayjs, { Dayjs } from 'dayjs';
|
||||
import api from '../../api';
|
||||
import { message } from '../../ui/app-message';
|
||||
@@ -9,10 +30,14 @@ function getCardStyle(room: any): React.CSSProperties {
|
||||
let base: React.CSSProperties;
|
||||
if (room.status === 'maintenance') base = { background: '#f5f5f5', borderColor: '#d9d9d9' };
|
||||
else if (room.currentCount === 0) base = { background: '#f6ffed', borderColor: '#b7eb8f' };
|
||||
else if (room.currentCount >= room.capacity) base = { background: '#fff2f0', borderColor: '#ffccc7' };
|
||||
else if (room.currentCount >= room.capacity)
|
||||
base = { background: '#fff2f0', borderColor: '#ffccc7' };
|
||||
else base = { background: '#e6f4ff', borderColor: '#91caff' };
|
||||
if (room.organizationColor) {
|
||||
return { ...base, background: `color-mix(in srgb, ${room.organizationColor} 15%, ${base.background || '#fff'} 85%)` };
|
||||
return {
|
||||
...base,
|
||||
background: `color-mix(in srgb, ${room.organizationColor} 15%, ${base.background || '#fff'} 85%)`,
|
||||
};
|
||||
}
|
||||
return base;
|
||||
}
|
||||
@@ -29,7 +54,10 @@ function getOrganizationTags(occupants: any[]) {
|
||||
...new Map(
|
||||
occupants
|
||||
.filter((o: any) => o.organizationName)
|
||||
.map((o: any) => [o.organizationId, { name: o.organizationName, color: o.organizationColor }]),
|
||||
.map((o: any) => [
|
||||
o.organizationId,
|
||||
{ name: o.organizationName, color: o.organizationColor },
|
||||
]),
|
||||
).values(),
|
||||
] as { name: string; color: string | null }[];
|
||||
if (organizationList.length === 0) return null;
|
||||
@@ -80,7 +108,8 @@ const RoomVisualPage: React.FC = () => {
|
||||
|
||||
const rooms = data.rooms.filter((r: any) => {
|
||||
if (selectedBuilding !== 'all' && r.building !== selectedBuilding) return false;
|
||||
if (selectedOrganization !== 'all' && !(r.organizationIds || []).includes(selectedOrganization)) return false;
|
||||
if (selectedOrganization !== 'all' && !(r.organizationIds || []).includes(selectedOrganization))
|
||||
return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
@@ -138,7 +167,15 @@ const RoomVisualPage: React.FC = () => {
|
||||
label: (
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
|
||||
{t.color && (
|
||||
<span style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: t.color, display: 'inline-block' }} />
|
||||
<span
|
||||
style={{
|
||||
width: 8,
|
||||
height: 8,
|
||||
borderRadius: '50%',
|
||||
backgroundColor: t.color,
|
||||
display: 'inline-block',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{t.name}
|
||||
</span>
|
||||
@@ -175,17 +212,29 @@ const RoomVisualPage: React.FC = () => {
|
||||
</Col>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small">
|
||||
<Statistic title="空闲房间" value={emptyRooms} styles={{ value: { color: '#34C759' } }} />
|
||||
<Statistic
|
||||
title="空闲房间"
|
||||
value={emptyRooms}
|
||||
styles={{ value: { color: '#34C759' } }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small">
|
||||
<Statistic title="可安排床位" value={availableBedsCount} styles={{ value: { color: '#007AFF' } }} />
|
||||
<Statistic
|
||||
title="可安排床位"
|
||||
value={availableBedsCount}
|
||||
styles={{ value: { color: '#007AFF' } }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small">
|
||||
<Statistic title="满员房间" value={fullRooms} styles={{ value: { color: '#FF3B30' } }} />
|
||||
<Statistic
|
||||
title="满员房间"
|
||||
value={fullRooms}
|
||||
styles={{ value: { color: '#FF3B30' } }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
@@ -214,13 +263,27 @@ const RoomVisualPage: React.FC = () => {
|
||||
marginBottom: 8,
|
||||
}}
|
||||
>
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 16, fontWeight: 600, color: '#1d1d1f' }}>
|
||||
<span
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 6,
|
||||
fontSize: 16,
|
||||
fontWeight: 600,
|
||||
color: '#1d1d1f',
|
||||
}}
|
||||
>
|
||||
{room.organizationColor && (
|
||||
<span style={{
|
||||
width: 10, height: 10, borderRadius: '50%',
|
||||
backgroundColor: room.organizationColor, display: 'inline-block',
|
||||
flexShrink: 0,
|
||||
}} />
|
||||
<span
|
||||
style={{
|
||||
width: 10,
|
||||
height: 10,
|
||||
borderRadius: '50%',
|
||||
backgroundColor: room.organizationColor,
|
||||
display: 'inline-block',
|
||||
flexShrink: 0,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{room.roomNumber}
|
||||
</span>
|
||||
@@ -231,7 +294,13 @@ const RoomVisualPage: React.FC = () => {
|
||||
{room.floor && <span>{room.floor}F</span>}
|
||||
</div>
|
||||
{room.totalBeds > 0 && (
|
||||
<div style={{ fontSize: 12, color: room.occupiedBeds >= room.totalBeds ? '#FF3B30' : '#34C759', marginBottom: 6 }}>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 12,
|
||||
color: room.occupiedBeds >= room.totalBeds ? '#FF3B30' : '#34C759',
|
||||
marginBottom: 6,
|
||||
}}
|
||||
>
|
||||
床位: {room.occupiedBeds}/{room.totalBeds}
|
||||
</div>
|
||||
)}
|
||||
@@ -259,10 +328,16 @@ const RoomVisualPage: React.FC = () => {
|
||||
)}
|
||||
{getOrganizationTags(room.occupants)}
|
||||
{room.occupants.length > 0 && (
|
||||
<div className="room-card-tag-wrapper" style={{ borderTop: '1px solid rgba(0,0,0,0.06)', paddingTop: 6 }}>
|
||||
<div
|
||||
className="room-card-tag-wrapper"
|
||||
style={{ borderTop: '1px solid rgba(0,0,0,0.06)', paddingTop: 6 }}
|
||||
>
|
||||
{room.occupants.slice(0, 4).map((o: any) => (
|
||||
<Tooltip key={o.studentId} title={`入住 ${o.days} 天 (${o.checkInDate} 起)`}>
|
||||
<Tag style={{ margin: '0 4px 4px 0', fontSize: 12, maxWidth: '100%' }} icon={<UserOutlined />}>
|
||||
<Tag
|
||||
style={{ margin: '0 4px 4px 0', fontSize: 12, maxWidth: '100%' }}
|
||||
icon={<UserOutlined />}
|
||||
>
|
||||
{o.studentName}
|
||||
</Tag>
|
||||
</Tooltip>
|
||||
|
||||
@@ -25,7 +25,6 @@ import {
|
||||
InboxOutlined,
|
||||
SearchOutlined,
|
||||
ExportOutlined,
|
||||
DeleteOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import api from '../../api';
|
||||
import { downloadBlob } from '../../utils/download';
|
||||
@@ -71,8 +70,13 @@ function parseRoomNumber(input: string) {
|
||||
const floor = parseInt(roomPart.charAt(0), 10) || undefined;
|
||||
let roomType = '四人间';
|
||||
let capacity = 4;
|
||||
if (bldgNum === '2') { roomType = '单人间'; capacity = 1; }
|
||||
else if (bldgNum === '8') { roomType = '爆改房'; capacity = 2; }
|
||||
if (bldgNum === '2') {
|
||||
roomType = '单人间';
|
||||
capacity = 1;
|
||||
} else if (bldgNum === '8') {
|
||||
roomType = '爆改房';
|
||||
capacity = 2;
|
||||
}
|
||||
return { building: `${bldgNum}号楼`, floor, roomType, capacity };
|
||||
}
|
||||
return null;
|
||||
@@ -88,6 +92,7 @@ const RoomsPage: React.FC = () => {
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [filterBuilding, setFilterBuilding] = useState<string | undefined>(undefined);
|
||||
const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
|
||||
const [filterRentalCategory, setFilterRentalCategory] = useState<string | undefined>(undefined);
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [form] = Form.useForm();
|
||||
@@ -150,12 +155,22 @@ const RoomsPage: React.FC = () => {
|
||||
let result = data;
|
||||
if (searchText) {
|
||||
const keyword = searchText.toLowerCase();
|
||||
result = result.filter((r: Record<string, unknown>) => typeof r.roomNumber === 'string' && r.roomNumber.toLowerCase().includes(keyword));
|
||||
result = result.filter(
|
||||
(r: Record<string, unknown>) =>
|
||||
typeof r.roomNumber === 'string' && r.roomNumber.toLowerCase().includes(keyword),
|
||||
);
|
||||
}
|
||||
if (filterBuilding)
|
||||
result = result.filter((r: Record<string, unknown>) => r.building === filterBuilding);
|
||||
if (filterStatus)
|
||||
result = result.filter((r: Record<string, unknown>) => r.status === filterStatus);
|
||||
if (filterRentalCategory) {
|
||||
result = result.filter(
|
||||
(r: Record<string, unknown>) => r.rentalCategory === filterRentalCategory,
|
||||
);
|
||||
}
|
||||
if (filterBuilding) result = result.filter((r: Record<string, unknown>) => r.building === filterBuilding);
|
||||
if (filterStatus) result = result.filter((r: Record<string, unknown>) => r.status === filterStatus);
|
||||
return result;
|
||||
}, [data, searchText, filterBuilding, filterStatus]);
|
||||
}, [data, searchText, filterBuilding, filterStatus, filterRentalCategory]);
|
||||
const remainingBedSlots = useMemo(() => {
|
||||
const capacity = Number(drawerRoom?.capacity) || 0;
|
||||
return Math.max(capacity - beds.length, 0);
|
||||
@@ -218,16 +233,21 @@ const RoomsPage: React.FC = () => {
|
||||
bedForm.resetFields();
|
||||
setBedEditing(null);
|
||||
fetchBeds(drawerRoom.id);
|
||||
} catch (e: any) { message.error(e?.message || '操作失败'); }
|
||||
finally { setSavingBed(false); }
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '操作失败');
|
||||
} finally {
|
||||
setSavingBed(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteBed = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/rooms/${drawerRoom.id}/beds/${id}`);
|
||||
message.success('已删除');
|
||||
message.success('已归档');
|
||||
fetchBeds(drawerRoom.id);
|
||||
} catch (e: any) { message.error(e?.message || '删除失败'); }
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '归档失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handleBatchBeds = async (count: number) => {
|
||||
@@ -235,7 +255,9 @@ const RoomsPage: React.FC = () => {
|
||||
await api.post(`/rooms/${drawerRoom.id}/beds/batch`, { count });
|
||||
message.success(`已生成 ${count} 张床位`);
|
||||
fetchBeds(drawerRoom.id);
|
||||
} catch (e: any) { message.error(e?.message || '批量生成失败'); }
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '批量生成失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveLocker = async () => {
|
||||
@@ -252,16 +274,21 @@ const RoomsPage: React.FC = () => {
|
||||
lockerForm.resetFields();
|
||||
setLockerEditing(null);
|
||||
fetchLockers(drawerRoom.id);
|
||||
} catch (e: any) { message.error(e?.message || '操作失败'); }
|
||||
finally { setSavingLocker(false); }
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '操作失败');
|
||||
} finally {
|
||||
setSavingLocker(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteLocker = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/rooms/${drawerRoom.id}/lockers/${id}`);
|
||||
message.success('已删除');
|
||||
message.success('已归档');
|
||||
fetchLockers(drawerRoom.id);
|
||||
} catch (e: any) { message.error(e?.message || '删除失败'); }
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '归档失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handleBatchLockers = async (count: number) => {
|
||||
@@ -269,7 +296,9 @@ const RoomsPage: React.FC = () => {
|
||||
await api.post(`/rooms/${drawerRoom.id}/lockers/batch`, { count });
|
||||
message.success(`已生成 ${count} 个柜子`);
|
||||
fetchLockers(drawerRoom.id);
|
||||
} catch (e: any) { message.error(e?.message || '批量生成失败'); }
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '批量生成失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handleArchive = async (id: number) => {
|
||||
@@ -301,122 +330,131 @@ const RoomsPage: React.FC = () => {
|
||||
downloadBlob('/rooms/export' + params, '房间列表.xlsx').catch(() => message.error('导出失败'));
|
||||
};
|
||||
|
||||
const columns = useMemo(() => [
|
||||
{
|
||||
title: '房间号',
|
||||
dataIndex: 'roomNumber',
|
||||
width: 100,
|
||||
sorter: (a: any, b: any) => a.roomNumber.localeCompare(b.roomNumber),
|
||||
},
|
||||
{ title: '楼栋', dataIndex: 'building', width: 80 },
|
||||
{ title: '楼层', dataIndex: 'floor', width: 80 },
|
||||
{ title: '类型', dataIndex: 'roomType', width: 90, render: (v: any) => v || '-' },
|
||||
{
|
||||
title: '租赁类型',
|
||||
dataIndex: 'rentalCategory',
|
||||
width: 100,
|
||||
render: (v: string) => {
|
||||
if (v === 'long') return <Tag color="blue">长租</Tag>;
|
||||
if (v === 'short') return <Tag color="green">短租</Tag>;
|
||||
return '-';
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: '房间号',
|
||||
dataIndex: 'roomNumber',
|
||||
width: 100,
|
||||
sorter: (a: any, b: any) => a.roomNumber.localeCompare(b.roomNumber),
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '月租金',
|
||||
dataIndex: 'monthlyRate',
|
||||
width: 100,
|
||||
render: (v: number) => (v ? `¥${v}` : '-'),
|
||||
},
|
||||
{ title: '额定人数', dataIndex: 'capacity', width: 80 },
|
||||
{
|
||||
title: '当前入住',
|
||||
width: 80,
|
||||
render: (_: any, r: any) =>
|
||||
r.status === 'archived' ? (
|
||||
<Tag color="#999">-</Tag>
|
||||
) : (
|
||||
<Badge
|
||||
count={r.currentCount}
|
||||
showZero
|
||||
overflowCount={99}
|
||||
style={{ backgroundColor: r.currentCount >= r.capacity ? '#ff4d4f' : '#52c41a' }}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 80,
|
||||
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 220,
|
||||
render: (_: unknown, record: unknown) => {
|
||||
const r = record as { status?: string; id: number };
|
||||
return (
|
||||
<Space>
|
||||
{r.status === 'archived' ? (
|
||||
<Popconfirm
|
||||
title="确定恢复此宿舍?"
|
||||
onConfirm={() => handleRestore(r.id)}
|
||||
>
|
||||
<PermissionButton permission="room:edit" size="small" icon={<UndoOutlined />} type="link">
|
||||
恢复
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
) : (
|
||||
<>
|
||||
<PermissionButton
|
||||
permission="room:view"
|
||||
size="small"
|
||||
type="link"
|
||||
onClick={async () => {
|
||||
const rec = record as { id: number };
|
||||
setDrawerRoom(record);
|
||||
setDrawerOpen(true);
|
||||
await Promise.all([fetchBeds(rec.id), fetchLockers(rec.id)]);
|
||||
}}
|
||||
>
|
||||
查看
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="room:edit"
|
||||
size="small"
|
||||
onClick={() => {
|
||||
const rec = record as { id: number };
|
||||
setEditing(rec);
|
||||
form.setFieldsValue(rec);
|
||||
setModalOpen(true);
|
||||
}}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<Popconfirm title="确定归档?" onConfirm={() => handleArchive(r.id)}>
|
||||
<PermissionButton permission="room:delete" size="small" icon={<InboxOutlined />}>
|
||||
归档
|
||||
{ title: '楼栋', dataIndex: 'building', width: 80 },
|
||||
{ title: '楼层', dataIndex: 'floor', width: 80 },
|
||||
{ title: '类型', dataIndex: 'roomType', width: 90, render: (v: any) => v || '-' },
|
||||
{
|
||||
title: '租赁类型',
|
||||
dataIndex: 'rentalCategory',
|
||||
width: 100,
|
||||
render: (v: string) => {
|
||||
if (v === 'long') return <Tag color="blue">长租</Tag>;
|
||||
if (v === 'short') return <Tag color="green">短租</Tag>;
|
||||
return '-';
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '月租金',
|
||||
dataIndex: 'monthlyRate',
|
||||
width: 100,
|
||||
render: (v: number) => (v ? `¥${v}` : '-'),
|
||||
},
|
||||
{ title: '额定人数', dataIndex: 'capacity', width: 80 },
|
||||
{
|
||||
title: '当前入住',
|
||||
width: 80,
|
||||
render: (_: any, r: any) =>
|
||||
r.status === 'archived' ? (
|
||||
<Tag color="#999">-</Tag>
|
||||
) : (
|
||||
<Badge
|
||||
count={r.currentCount}
|
||||
showZero
|
||||
overflowCount={99}
|
||||
style={{ backgroundColor: r.currentCount >= r.capacity ? '#ff4d4f' : '#52c41a' }}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 80,
|
||||
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 220,
|
||||
render: (_: unknown, record: unknown) => {
|
||||
const r = record as { status?: string; id: number };
|
||||
return (
|
||||
<Space>
|
||||
{r.status === 'archived' ? (
|
||||
<Popconfirm title="确定恢复此宿舍?" onConfirm={() => handleRestore(r.id)}>
|
||||
<PermissionButton
|
||||
permission="room:edit"
|
||||
size="small"
|
||||
icon={<UndoOutlined />}
|
||||
type="link"
|
||||
>
|
||||
恢复
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
);
|
||||
) : (
|
||||
<>
|
||||
<PermissionButton
|
||||
permission="room:view"
|
||||
size="small"
|
||||
type="link"
|
||||
onClick={async () => {
|
||||
const rec = record as { id: number };
|
||||
setDrawerRoom(record);
|
||||
setDrawerOpen(true);
|
||||
await Promise.all([fetchBeds(rec.id), fetchLockers(rec.id)]);
|
||||
}}
|
||||
>
|
||||
查看
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="room:edit"
|
||||
size="small"
|
||||
onClick={() => {
|
||||
const rec = record as { id: number };
|
||||
setEditing(rec);
|
||||
form.setFieldsValue(rec);
|
||||
setModalOpen(true);
|
||||
}}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<Popconfirm title="确定归档?" onConfirm={() => handleArchive(r.id)}>
|
||||
<PermissionButton
|
||||
permission="room:delete"
|
||||
size="small"
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
);
|
||||
},
|
||||
},
|
||||
},
|
||||
], [showArchived, buildings, handleBatchDelete, handleRestore, handleArchive, fetchBeds, fetchLockers]);
|
||||
],
|
||||
[
|
||||
showArchived,
|
||||
buildings,
|
||||
handleBatchDelete,
|
||||
handleRestore,
|
||||
handleArchive,
|
||||
fetchBeds,
|
||||
fetchLockers,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<Space wrap>
|
||||
<div className="responsive-toolbar">
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<h3 style={{ margin: 0 }}>宿舍管理</h3>
|
||||
<Input.Search
|
||||
placeholder="搜索房间号"
|
||||
@@ -432,8 +470,29 @@ const RoomsPage: React.FC = () => {
|
||||
onChange={(v) => setFilterBuilding(v)}
|
||||
options={buildings.map((b) => ({ value: b, label: b }))}
|
||||
/>
|
||||
<Select placeholder="状态" allowClear style={{ width: 110 }} value={filterStatus} onChange={setFilterStatus}
|
||||
options={[{value:'available',label:'可入住'},{value:'full',label:'已满'},{value:'maintenance',label:'维护中'}]} />
|
||||
<Select
|
||||
placeholder="状态"
|
||||
allowClear
|
||||
style={{ width: 110 }}
|
||||
value={filterStatus}
|
||||
onChange={setFilterStatus}
|
||||
options={[
|
||||
{ value: 'available', label: '可入住' },
|
||||
{ value: 'full', label: '已满' },
|
||||
{ value: 'maintenance', label: '维护中' },
|
||||
]}
|
||||
/>
|
||||
<Select
|
||||
placeholder="租赁类型"
|
||||
allowClear
|
||||
style={{ width: 120 }}
|
||||
value={filterRentalCategory}
|
||||
onChange={setFilterRentalCategory}
|
||||
options={[
|
||||
{ value: 'long', label: '长租' },
|
||||
{ value: 'short', label: '短租' },
|
||||
]}
|
||||
/>
|
||||
<Button
|
||||
type={showArchived ? 'primary' : 'default'}
|
||||
onClick={() => setShowArchived(!showArchived)}
|
||||
@@ -443,7 +502,7 @@ const RoomsPage: React.FC = () => {
|
||||
: `显示已归档${archivedCount > 0 ? ` (${archivedCount})` : ''}`}
|
||||
</Button>
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<Popconfirm
|
||||
title={`确定批量归档选中的 ${selectedRowKeys.length} 间宿舍?(有在住人员的会跳过)`}
|
||||
onConfirm={handleBatchDelete}
|
||||
@@ -454,7 +513,7 @@ const RoomsPage: React.FC = () => {
|
||||
<PermissionButton
|
||||
permission="room:delete"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
icon={<InboxOutlined />}
|
||||
disabled={selectedRowKeys.length === 0}
|
||||
loading={batchLoading}
|
||||
>
|
||||
@@ -606,7 +665,10 @@ const RoomsPage: React.FC = () => {
|
||||
<Drawer
|
||||
title={`${drawerRoom?.roomNumber} 房间详情`}
|
||||
open={drawerOpen}
|
||||
onClose={() => { setDrawerOpen(false); setDrawerRoom(null); }}
|
||||
onClose={() => {
|
||||
setDrawerOpen(false);
|
||||
setDrawerRoom(null);
|
||||
}}
|
||||
width={640}
|
||||
destroyOnClose
|
||||
>
|
||||
@@ -618,14 +680,40 @@ const RoomsPage: React.FC = () => {
|
||||
label: '基本信息',
|
||||
children: drawerRoom && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<div><strong>房间号:</strong>{drawerRoom.roomNumber}</div>
|
||||
<div><strong>楼栋:</strong>{drawerRoom.building || '-'}</div>
|
||||
<div><strong>楼层:</strong>{drawerRoom.floor ?? '-'}</div>
|
||||
<div><strong>类型:</strong>{drawerRoom.roomType || '-'}</div>
|
||||
<div><strong>额定人数:</strong>{drawerRoom.capacity}</div>
|
||||
<div><strong>租赁类别:</strong>{drawerRoom.rentalCategory === 'long' ? '长租' : '短租'}</div>
|
||||
<div><strong>月租金:</strong>{drawerRoom.monthlyRate ? `¥${drawerRoom.monthlyRate}` : '-'}</div>
|
||||
<div><strong>状态:</strong><Tag color={statusMap[drawerRoom.status]?.color}>{statusMap[drawerRoom.status]?.text}</Tag></div>
|
||||
<div>
|
||||
<strong>房间号:</strong>
|
||||
{drawerRoom.roomNumber}
|
||||
</div>
|
||||
<div>
|
||||
<strong>楼栋:</strong>
|
||||
{drawerRoom.building || '-'}
|
||||
</div>
|
||||
<div>
|
||||
<strong>楼层:</strong>
|
||||
{drawerRoom.floor ?? '-'}
|
||||
</div>
|
||||
<div>
|
||||
<strong>类型:</strong>
|
||||
{drawerRoom.roomType || '-'}
|
||||
</div>
|
||||
<div>
|
||||
<strong>额定人数:</strong>
|
||||
{drawerRoom.capacity}
|
||||
</div>
|
||||
<div>
|
||||
<strong>租赁类别:</strong>
|
||||
{drawerRoom.rentalCategory === 'long' ? '长租' : '短租'}
|
||||
</div>
|
||||
<div>
|
||||
<strong>月租金:</strong>
|
||||
{drawerRoom.monthlyRate ? `¥${drawerRoom.monthlyRate}` : '-'}
|
||||
</div>
|
||||
<div>
|
||||
<strong>状态:</strong>
|
||||
<Tag color={statusMap[drawerRoom.status]?.color}>
|
||||
{statusMap[drawerRoom.status]?.text}
|
||||
</Tag>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
@@ -640,25 +728,48 @@ const RoomsPage: React.FC = () => {
|
||||
size="small"
|
||||
icon={<PlusOutlined />}
|
||||
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
|
||||
onClick={() => { setBedEditing(null); bedForm.resetFields(); setBedModalOpen(true); }}
|
||||
onClick={() => {
|
||||
setBedEditing(null);
|
||||
bedForm.resetFields();
|
||||
setBedModalOpen(true);
|
||||
}}
|
||||
>
|
||||
添加床位
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title={remainingBedSlots > 0 ? '批量生成床位' : '床位已达到额定人数'}
|
||||
description={
|
||||
remainingBedSlots > 0
|
||||
? <InputNumber min={1} max={remainingBedSlots} defaultValue={defaultBatchBedCount} id="batch-bed-count" style={{ width: 80 }} />
|
||||
: '如需增加床位,请先调整宿舍额定人数'
|
||||
remainingBedSlots > 0 ? (
|
||||
<InputNumber
|
||||
min={1}
|
||||
max={remainingBedSlots}
|
||||
defaultValue={defaultBatchBedCount}
|
||||
id="batch-bed-count"
|
||||
style={{ width: 80 }}
|
||||
/>
|
||||
) : (
|
||||
'如需增加床位,请先调整宿舍额定人数'
|
||||
)
|
||||
}
|
||||
onConfirm={() => {
|
||||
const input = document.getElementById('batch-bed-count') as HTMLInputElement;
|
||||
handleBatchBeds(input ? parseInt(input.value) || defaultBatchBedCount : defaultBatchBedCount);
|
||||
const input = document.getElementById(
|
||||
'batch-bed-count',
|
||||
) as HTMLInputElement;
|
||||
handleBatchBeds(
|
||||
input
|
||||
? parseInt(input.value) || defaultBatchBedCount
|
||||
: defaultBatchBedCount,
|
||||
);
|
||||
}}
|
||||
okText="生成"
|
||||
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
|
||||
>
|
||||
<Button size="small" disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}>批量生成</Button>
|
||||
<Button
|
||||
size="small"
|
||||
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
|
||||
>
|
||||
批量生成
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</div>
|
||||
<Table
|
||||
@@ -669,7 +780,9 @@ const RoomsPage: React.FC = () => {
|
||||
columns={[
|
||||
{ title: '编号', dataIndex: 'bedNumber', width: 80 },
|
||||
{
|
||||
title: '状态', dataIndex: 'status', width: 80,
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 80,
|
||||
render: (s: string) => {
|
||||
const map: Record<string, { text: string; color: string }> = {
|
||||
available: { text: '空闲', color: 'green' },
|
||||
@@ -681,7 +794,8 @@ const RoomsPage: React.FC = () => {
|
||||
},
|
||||
{ title: '备注', dataIndex: 'notes', render: (v: string) => v || '-' },
|
||||
{
|
||||
title: '操作', width: 120,
|
||||
title: '操作',
|
||||
width: 120,
|
||||
render: (_: any, r: any) => (
|
||||
<Space size="small">
|
||||
<PermissionButton
|
||||
@@ -689,12 +803,19 @@ const RoomsPage: React.FC = () => {
|
||||
size="small"
|
||||
type="link"
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
onClick={() => { setBedEditing(r); bedForm.setFieldsValue(r); setBedModalOpen(true); }}
|
||||
onClick={() => {
|
||||
setBedEditing(r);
|
||||
bedForm.setFieldsValue(r);
|
||||
setBedModalOpen(true);
|
||||
}}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
{r.status !== 'occupied' && (
|
||||
<Popconfirm title="确定删除?" onConfirm={() => handleDeleteBed(r.id)}>
|
||||
<Popconfirm
|
||||
title="确定归档?"
|
||||
onConfirm={() => handleDeleteBed(r.id)}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="room:edit"
|
||||
size="small"
|
||||
@@ -702,7 +823,7 @@ const RoomsPage: React.FC = () => {
|
||||
danger
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
>
|
||||
删除
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
@@ -725,23 +846,37 @@ const RoomsPage: React.FC = () => {
|
||||
size="small"
|
||||
icon={<PlusOutlined />}
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
onClick={() => { setLockerEditing(null); lockerForm.resetFields(); setLockerModalOpen(true); }}
|
||||
onClick={() => {
|
||||
setLockerEditing(null);
|
||||
lockerForm.resetFields();
|
||||
setLockerModalOpen(true);
|
||||
}}
|
||||
>
|
||||
添加柜子
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="批量生成柜子"
|
||||
description={
|
||||
<InputNumber min={1} max={20} defaultValue={4} id="batch-locker-count" style={{ width: 80 }} />
|
||||
<InputNumber
|
||||
min={1}
|
||||
max={20}
|
||||
defaultValue={4}
|
||||
id="batch-locker-count"
|
||||
style={{ width: 80 }}
|
||||
/>
|
||||
}
|
||||
onConfirm={() => {
|
||||
const input = document.getElementById('batch-locker-count') as HTMLInputElement;
|
||||
const input = document.getElementById(
|
||||
'batch-locker-count',
|
||||
) as HTMLInputElement;
|
||||
handleBatchLockers(input ? parseInt(input.value) || 4 : 4);
|
||||
}}
|
||||
okText="生成"
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
>
|
||||
<Button size="small" disabled={drawerRoom?.status === 'archived'}>批量生成</Button>
|
||||
<Button size="small" disabled={drawerRoom?.status === 'archived'}>
|
||||
批量生成
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</div>
|
||||
<Table
|
||||
@@ -752,7 +887,9 @@ const RoomsPage: React.FC = () => {
|
||||
columns={[
|
||||
{ title: '编号', dataIndex: 'lockerNumber', width: 80 },
|
||||
{
|
||||
title: '状态', dataIndex: 'status', width: 80,
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 80,
|
||||
render: (s: string) => {
|
||||
const map: Record<string, { text: string; color: string }> = {
|
||||
available: { text: '空闲', color: 'green' },
|
||||
@@ -764,7 +901,8 @@ const RoomsPage: React.FC = () => {
|
||||
},
|
||||
{ title: '备注', dataIndex: 'notes', render: (v: string) => v || '-' },
|
||||
{
|
||||
title: '操作', width: 120,
|
||||
title: '操作',
|
||||
width: 120,
|
||||
render: (_: any, r: any) => (
|
||||
<Space size="small">
|
||||
<PermissionButton
|
||||
@@ -772,12 +910,19 @@ const RoomsPage: React.FC = () => {
|
||||
size="small"
|
||||
type="link"
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
onClick={() => { setLockerEditing(r); lockerForm.setFieldsValue(r); setLockerModalOpen(true); }}
|
||||
onClick={() => {
|
||||
setLockerEditing(r);
|
||||
lockerForm.setFieldsValue(r);
|
||||
setLockerModalOpen(true);
|
||||
}}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
{r.status !== 'occupied' && (
|
||||
<Popconfirm title="确定删除?" onConfirm={() => handleDeleteLocker(r.id)}>
|
||||
<Popconfirm
|
||||
title="确定归档?"
|
||||
onConfirm={() => handleDeleteLocker(r.id)}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="room:edit"
|
||||
size="small"
|
||||
@@ -785,7 +930,7 @@ const RoomsPage: React.FC = () => {
|
||||
danger
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
>
|
||||
删除
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
@@ -805,7 +950,10 @@ const RoomsPage: React.FC = () => {
|
||||
title={bedEditing ? '编辑床位' : '添加床位'}
|
||||
open={bedModalOpen}
|
||||
onOk={handleSaveBed}
|
||||
onCancel={() => { setBedModalOpen(false); setBedEditing(null); }}
|
||||
onCancel={() => {
|
||||
setBedModalOpen(false);
|
||||
setBedEditing(null);
|
||||
}}
|
||||
confirmLoading={savingBed}
|
||||
okText="保存"
|
||||
>
|
||||
@@ -832,7 +980,10 @@ const RoomsPage: React.FC = () => {
|
||||
title={lockerEditing ? '编辑柜子' : '添加柜子'}
|
||||
open={lockerModalOpen}
|
||||
onOk={handleSaveLocker}
|
||||
onCancel={() => { setLockerModalOpen(false); setLockerEditing(null); }}
|
||||
onCancel={() => {
|
||||
setLockerModalOpen(false);
|
||||
setLockerEditing(null);
|
||||
}}
|
||||
confirmLoading={savingLocker}
|
||||
okText="保存"
|
||||
>
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
Modal,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
DatePicker,
|
||||
TimePicker,
|
||||
Popconfirm,
|
||||
@@ -26,10 +27,10 @@ import {
|
||||
CalendarOutlined,
|
||||
LeftOutlined,
|
||||
RightOutlined,
|
||||
DeleteOutlined,
|
||||
CloudSyncOutlined,
|
||||
PlusOutlined,
|
||||
EditOutlined,
|
||||
StopOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import dayjs, { Dayjs } from 'dayjs';
|
||||
import api from '../../api';
|
||||
@@ -53,6 +54,7 @@ interface ClassScheduleItem {
|
||||
weekDay: number;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
attendanceAdvanceMinutes: number;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
subject: string;
|
||||
@@ -351,7 +353,7 @@ const SchedulesPage: React.FC = () => {
|
||||
setEditingSchedule(null);
|
||||
setModalMode('create');
|
||||
form.resetFields();
|
||||
form.setFieldsValue({ classroomId, weekDay });
|
||||
form.setFieldsValue({ classroomId, weekDay, attendanceAdvanceMinutes: 30 });
|
||||
setModalOpen(true);
|
||||
}
|
||||
};
|
||||
@@ -453,23 +455,26 @@ const SchedulesPage: React.FC = () => {
|
||||
void loadClassTeachers(editableSchedule.classId);
|
||||
};
|
||||
|
||||
// ---- Delete schedule ----
|
||||
const removeScheduleFromSelection = (id: number) => {
|
||||
const remaining = selectedSchedules.filter((s) => s.id !== id);
|
||||
setSelectedSchedules(remaining);
|
||||
if (remaining.length === 0) {
|
||||
setModalOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number | null) => {
|
||||
// ---- Disable / delete schedule ----
|
||||
|
||||
const handleDisable = async (id: number | null) => {
|
||||
if (id === null) return;
|
||||
try {
|
||||
await api.delete(`/class-schedules/${id}`);
|
||||
message.success('排课已删除');
|
||||
// Refresh the displayed schedules
|
||||
const remaining = selectedSchedules.filter((s) => s.id !== id);
|
||||
setSelectedSchedules(remaining);
|
||||
if (remaining.length === 0) {
|
||||
setModalOpen(false);
|
||||
}
|
||||
await api.put(`/class-schedules/${id}`, { status: 'inactive' });
|
||||
message.success('排课已停用,历史考勤记录已保留,教室占用已释放');
|
||||
removeScheduleFromSelection(id);
|
||||
fetchData();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
message.error(err?.message || '删除失败');
|
||||
message.error(err?.message || '停用失败');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -960,9 +965,28 @@ const SchedulesPage: React.FC = () => {
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="attendanceAdvanceMinutes"
|
||||
label="课前签到时间"
|
||||
tooltip="从上课前指定分钟开始,到下课时间结束;期间任意上班或下班打卡都计为出勤"
|
||||
initialValue={30}
|
||||
rules={[{ required: true, message: '请设置课前签到时间' }]}
|
||||
>
|
||||
<InputNumber
|
||||
min={0}
|
||||
max={1440}
|
||||
step={5}
|
||||
addonAfter="分钟"
|
||||
style={{ width: '100%' }}
|
||||
placeholder="例如 30"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="timeRange"
|
||||
label="上课时段"
|
||||
tooltip="同一教室的前后两节排课必须至少间隔10分钟"
|
||||
extra="系统按10分钟选择时间,并为相邻排课强制预留至少10分钟。"
|
||||
rules={[{ required: true, message: '请选择时段' }]}
|
||||
>
|
||||
<TimePicker.RangePicker
|
||||
@@ -1008,6 +1032,7 @@ const SchedulesPage: React.FC = () => {
|
||||
weekDay:
|
||||
selectedCell?.weekDay ?? (selectedDate ? selectedDate.day() || 7 : undefined),
|
||||
dateRange: selectedDate ? [selectedDate, selectedDate] : undefined,
|
||||
attendanceAdvanceMinutes: 30,
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -1054,6 +1079,12 @@ const SchedulesPage: React.FC = () => {
|
||||
<strong>时段:</strong>
|
||||
{s.startTime} ~ {s.endTime}
|
||||
</div>
|
||||
{!isMaskedSchedule(s) && (
|
||||
<div>
|
||||
<strong>签到窗口:</strong>
|
||||
课前 {s.attendanceAdvanceMinutes ?? 30} 分钟至下课
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<strong>日期:</strong>
|
||||
{s.startDate} ~ {s.endDate}
|
||||
@@ -1085,21 +1116,23 @@ const SchedulesPage: React.FC = () => {
|
||||
编辑
|
||||
</PermissionButton>
|
||||
)}
|
||||
<Popconfirm
|
||||
title="确认删除该排课?"
|
||||
onConfirm={() => handleDelete(s.id)}
|
||||
okText="删除"
|
||||
cancelText="取消"
|
||||
>
|
||||
<PermissionButton
|
||||
permission="schedule:delete"
|
||||
size="small"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
{s.scheduleType !== 'RENTAL' && s.status === 'active' && (
|
||||
<Popconfirm
|
||||
title="确认停用该排课?"
|
||||
description="停用后历史考勤记录会保留,但该排课不会再显示或占用教室。"
|
||||
onConfirm={() => handleDisable(s.id)}
|
||||
okText="停用"
|
||||
cancelText="取消"
|
||||
>
|
||||
删除
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
<PermissionButton
|
||||
permission="schedule:edit"
|
||||
size="small"
|
||||
icon={<StopOutlined />}
|
||||
>
|
||||
停用
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
)}
|
||||
</div>
|
||||
@@ -1158,17 +1191,17 @@ const SchedulesPage: React.FC = () => {
|
||||
{syncResult ? (
|
||||
/* ── 同步结果 ── */
|
||||
<div>
|
||||
<Row gutter={16} style={{ marginBottom: 16 }}>
|
||||
<Col span={6}>
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
|
||||
<Col xs={12} sm={6}>
|
||||
<Statistic title="排课" value={syncResult.scheduleCount} suffix="条" />
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Col xs={12} sm={6}>
|
||||
<Statistic title="班次" value={syncResult.shiftCount} suffix="个" />
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Col xs={12} sm={6}>
|
||||
<Statistic title="考勤组" value={syncResult.groupCount} suffix="个" />
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Col xs={12} sm={6}>
|
||||
<Statistic
|
||||
title="排班数"
|
||||
value={syncResult.syncedItems}
|
||||
@@ -1223,11 +1256,11 @@ const SchedulesPage: React.FC = () => {
|
||||
) : syncStatus ? (
|
||||
/* ── 同步确认信息 ── */
|
||||
<div>
|
||||
<Row gutter={16} style={{ marginBottom: 16 }}>
|
||||
<Col span={8}>
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
|
||||
<Col xs={24} sm={8}>
|
||||
<Statistic title="活跃排课" value={syncStatus.activeSchedules} suffix="条" />
|
||||
</Col>
|
||||
<Col span={8}>
|
||||
<Col xs={24} sm={8}>
|
||||
<Statistic
|
||||
title="已就绪班级"
|
||||
value={syncStatus.mappedClasses}
|
||||
@@ -1238,7 +1271,7 @@ const SchedulesPage: React.FC = () => {
|
||||
}}
|
||||
/>
|
||||
</Col>
|
||||
<Col span={8}>
|
||||
<Col xs={24} sm={8}>
|
||||
<Statistic
|
||||
title="无绑定学生班级"
|
||||
value={syncStatus.totalClasses - syncStatus.mappedClasses}
|
||||
|
||||
@@ -16,11 +16,13 @@ describe('schedule edit form mapping', () => {
|
||||
startDate: '2026-07-01',
|
||||
endDate: '2026-07-31',
|
||||
notes: '需要投影设备',
|
||||
attendanceAdvanceMinutes: 45,
|
||||
});
|
||||
|
||||
expect(values.classroomId).toBe(1);
|
||||
expect(values.weekDay).toBe(5);
|
||||
expect(values.notes).toBe('需要投影设备');
|
||||
expect(values.attendanceAdvanceMinutes).toBe(45);
|
||||
expect(values.timeRange.map((item) => item.format('HH:mm'))).toEqual(['14:00', '18:00']);
|
||||
expect(values.dateRange.map((item) => item.format('YYYY-MM-DD'))).toEqual([
|
||||
'2026-07-01',
|
||||
@@ -39,6 +41,7 @@ describe('schedule edit form mapping', () => {
|
||||
timeRange: [dayjs('2026-01-01 13:30'), dayjs('2026-01-01 17:20')],
|
||||
dateRange: [dayjs('2026-08-01'), dayjs('2026-08-31')],
|
||||
notes: ' 临时调整教室 ',
|
||||
attendanceAdvanceMinutes: 20,
|
||||
}),
|
||||
).toEqual({
|
||||
classId: 1,
|
||||
@@ -51,11 +54,11 @@ describe('schedule edit form mapping', () => {
|
||||
startDate: '2026-08-01',
|
||||
endDate: '2026-08-31',
|
||||
notes: '临时调整教室',
|
||||
attendanceAdvanceMinutes: 20,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('schedule notes normalization', () => {
|
||||
it('omits whitespace-only notes from the payload', () => {
|
||||
expect(
|
||||
@@ -67,6 +70,7 @@ describe('schedule notes normalization', () => {
|
||||
timeRange: [dayjs('2026-01-01 13:30'), dayjs('2026-01-01 17:20')],
|
||||
dateRange: [dayjs('2026-08-01'), dayjs('2026-08-31')],
|
||||
notes: ' ',
|
||||
attendanceAdvanceMinutes: 30,
|
||||
}).notes,
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@ export interface ScheduleFormValues {
|
||||
subject: string;
|
||||
teacherId?: number;
|
||||
notes?: string;
|
||||
attendanceAdvanceMinutes: number;
|
||||
timeRange: [Dayjs, Dayjs];
|
||||
dateRange: [Dayjs, Dayjs];
|
||||
}
|
||||
@@ -19,6 +20,7 @@ export interface EditableSchedule {
|
||||
subject: string;
|
||||
teacherId: number | null;
|
||||
notes?: string | null;
|
||||
attendanceAdvanceMinutes?: number | null;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
startDate: string;
|
||||
@@ -32,6 +34,7 @@ export const scheduleToFormValues = (schedule: EditableSchedule): ScheduleFormVa
|
||||
subject: schedule.subject,
|
||||
teacherId: schedule.teacherId ?? undefined,
|
||||
notes: schedule.notes ?? undefined,
|
||||
attendanceAdvanceMinutes: schedule.attendanceAdvanceMinutes ?? 30,
|
||||
timeRange: [dayjs(`2000-01-01 ${schedule.startTime}`), dayjs(`2000-01-01 ${schedule.endTime}`)],
|
||||
dateRange: [dayjs(schedule.startDate), dayjs(schedule.endDate)],
|
||||
});
|
||||
@@ -43,6 +46,7 @@ export const buildSchedulePayload = (values: ScheduleFormValues) => ({
|
||||
subject: values.subject,
|
||||
teacherId: values.teacherId,
|
||||
notes: values.notes?.trim() || undefined,
|
||||
attendanceAdvanceMinutes: values.attendanceAdvanceMinutes,
|
||||
startTime: values.timeRange[0].format('HH:mm'),
|
||||
endTime: values.timeRange[1].format('HH:mm'),
|
||||
startDate: values.dateRange[0].format('YYYY-MM-DD'),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
App,
|
||||
Button,
|
||||
Card,
|
||||
@@ -20,7 +21,6 @@ import {
|
||||
} from 'antd';
|
||||
import type { UploadProps } from 'antd';
|
||||
import {
|
||||
DeleteOutlined,
|
||||
DownloadOutlined,
|
||||
ExportOutlined,
|
||||
EyeOutlined,
|
||||
@@ -62,6 +62,23 @@ interface EnrollmentInfo {
|
||||
};
|
||||
}
|
||||
|
||||
interface StudentCreateImportResult {
|
||||
message?: string;
|
||||
imported?: number;
|
||||
skipped?: number;
|
||||
}
|
||||
|
||||
interface StudentUpdateImportResult {
|
||||
message?: string;
|
||||
matched?: number;
|
||||
skipped?: number;
|
||||
}
|
||||
|
||||
interface StudentFilterLookups {
|
||||
classes: Array<{ id: number; name: string; code?: string }>;
|
||||
teachers: Array<{ id: number; name: string; username: string }>;
|
||||
}
|
||||
|
||||
const StudentsPage: React.FC = () => {
|
||||
const { modal } = App.useApp();
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
@@ -72,6 +89,10 @@ const StudentsPage: React.FC = () => {
|
||||
const [searchName, setSearchName] = useState('');
|
||||
const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
|
||||
const [filterOrganizationId, setFilterOrganizationId] = useState<number | undefined>(undefined);
|
||||
const [filterClassId, setFilterClassId] = useState<number | undefined>(undefined);
|
||||
const [filterTeacherId, setFilterTeacherId] = useState<number | undefined>(undefined);
|
||||
const [classOptions, setClassOptions] = useState<StudentFilterLookups['classes']>([]);
|
||||
const [teacherOptions, setTeacherOptions] = useState<StudentFilterLookups['teachers']>([]);
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
const [archivedCount, setArchivedCount] = useState(0);
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
|
||||
@@ -137,6 +158,8 @@ const StudentsPage: React.FC = () => {
|
||||
};
|
||||
if (filterStatus) params.status = filterStatus;
|
||||
if (filterOrganizationId) params.organizationId = filterOrganizationId;
|
||||
if (filterClassId) params.classId = filterClassId;
|
||||
if (filterTeacherId) params.teacherId = filterTeacherId;
|
||||
const res = (await api.get('/students', { params })) as Array<Record<string, unknown>>;
|
||||
const list = res as Array<Record<string, unknown>>;
|
||||
const archived = list.filter((r) => r.status === 'archived');
|
||||
@@ -147,7 +170,7 @@ const StudentsPage: React.FC = () => {
|
||||
message.error(err?.message || '加载失败,请稍后重试');
|
||||
}
|
||||
setLoading(false);
|
||||
}, [searchName, showArchived, filterStatus, filterOrganizationId]);
|
||||
}, [searchName, showArchived, filterStatus, filterOrganizationId, filterClassId, filterTeacherId]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
@@ -160,6 +183,13 @@ const StudentsPage: React.FC = () => {
|
||||
setOrganizations(res as Array<{ id: number; name: string }>);
|
||||
})
|
||||
.catch(() => {});
|
||||
api
|
||||
.get<StudentFilterLookups>('/students/filter-lookups')
|
||||
.then((res) => {
|
||||
setClassOptions(res.classes || []);
|
||||
setTeacherOptions(res.teachers || []);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
const handleSave = async () => {
|
||||
const values = await form.validateFields();
|
||||
@@ -221,20 +251,94 @@ const StudentsPage: React.FC = () => {
|
||||
.catch(() => message.error('下载失败'));
|
||||
};
|
||||
|
||||
const handleMatchImport: UploadProps['customRequest'] = async ({ file, onSuccess, onError }) => {
|
||||
const showCreateImportResult = (result: StudentCreateImportResult) => {
|
||||
const imported = result.imported ?? 0;
|
||||
const skipped = result.skipped ?? 0;
|
||||
|
||||
modal.success({
|
||||
title: '导入完成',
|
||||
okText: '知道了',
|
||||
content: (
|
||||
<div>
|
||||
<Descriptions column={1} size="small">
|
||||
<Descriptions.Item label="成功新增">{imported} 人</Descriptions.Item>
|
||||
<Descriptions.Item label="跳过">{skipped} 人</Descriptions.Item>
|
||||
</Descriptions>
|
||||
<div style={{ marginTop: 12, fontWeight: 600 }}>跳过原因:</div>
|
||||
<ul style={{ marginBottom: 0, paddingLeft: 20 }}>
|
||||
<li>姓名为空</li>
|
||||
<li>已存在同名学生</li>
|
||||
</ul>
|
||||
<div style={{ marginTop: 8, color: '#8c8c8c', fontSize: 12 }}>
|
||||
当前后端只返回统计汇总,暂时无法列出具体哪几行被跳过。
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const showUpdateImportResult = (result: StudentUpdateImportResult) => {
|
||||
const matched = result.matched ?? 0;
|
||||
const skipped = result.skipped ?? 0;
|
||||
|
||||
modal.success({
|
||||
title: '更新完成',
|
||||
okText: '知道了',
|
||||
content: (
|
||||
<div>
|
||||
<Descriptions column={1} size="small">
|
||||
<Descriptions.Item label="成功更新">{matched} 人</Descriptions.Item>
|
||||
<Descriptions.Item label="未匹配">{skipped} 人</Descriptions.Item>
|
||||
</Descriptions>
|
||||
<div style={{ marginTop: 12, fontWeight: 600 }}>匹配规则:</div>
|
||||
<div>手机号优先,身份证号其次</div>
|
||||
<div style={{ marginTop: 8, color: '#8c8c8c', fontSize: 12 }}>
|
||||
当前后端只返回统计汇总,暂时无法列出具体哪几行未匹配。
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const handleCreateStudentsImport: UploadProps['customRequest'] = async ({
|
||||
file,
|
||||
onSuccess,
|
||||
onError,
|
||||
}) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file as File);
|
||||
try {
|
||||
const res = (await api.post('/students/import', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})) as StudentCreateImportResult;
|
||||
showCreateImportResult(res);
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
message.error(err?.message || '导入失败');
|
||||
onError?.(e instanceof Error ? e : new Error(err?.message || '导入失败'));
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdateExistingStudentsImport: UploadProps['customRequest'] = async ({
|
||||
file,
|
||||
onSuccess,
|
||||
onError,
|
||||
}) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file as File);
|
||||
try {
|
||||
const res = (await api.post('/students/import-match', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})) as { message: string };
|
||||
message.success(res.message);
|
||||
})) as StudentUpdateImportResult;
|
||||
showUpdateImportResult(res);
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
message.error(err?.message || '匹配导入失败');
|
||||
onError?.(e instanceof Error ? e : new Error(err?.message || '匹配导入失败'));
|
||||
message.error(err?.message || '更新已有学生资料失败');
|
||||
onError?.(e instanceof Error ? e : new Error(err?.message || '更新已有学生资料失败'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -243,8 +347,15 @@ const StudentsPage: React.FC = () => {
|
||||
? '/api'
|
||||
: `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
|
||||
const token = localStorage.getItem('token');
|
||||
const params = showArchived ? '?includeArchived=true' : '';
|
||||
fetch(`${baseURL}/students/export${params}`, { headers: { Authorization: `Bearer ${token}` } })
|
||||
const params = new URLSearchParams();
|
||||
if (searchName) params.set('name', searchName);
|
||||
if (filterStatus) params.set('status', filterStatus);
|
||||
if (filterOrganizationId) params.set('organizationId', String(filterOrganizationId));
|
||||
if (showArchived) params.set('includeArchived', 'true');
|
||||
if (filterClassId) params.set('classId', String(filterClassId));
|
||||
if (filterTeacherId) params.set('teacherId', String(filterTeacherId));
|
||||
const query = params.toString() ? `?${params.toString()}` : '';
|
||||
fetch(`${baseURL}/students/export${query}`, { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then((res) => res.blob())
|
||||
.then((blob) => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
@@ -277,12 +388,12 @@ const StudentsPage: React.FC = () => {
|
||||
render: (v: string, record: any) => {
|
||||
if (!v) return '-';
|
||||
return (
|
||||
<span>
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
|
||||
<span style={{ marginRight: 4 }}>{maskPhone(v)}</span>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ padding: '8px 4px' }}
|
||||
style={{ padding: '8px 4px', flex: 'none' }}
|
||||
onClick={() => handleViewSensitive(record.id, '电话', v)}
|
||||
title="点击查看完整号码"
|
||||
>
|
||||
@@ -305,12 +416,12 @@ const StudentsPage: React.FC = () => {
|
||||
render: (v: string, record: any) => {
|
||||
if (!v) return '-';
|
||||
return (
|
||||
<span>
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
|
||||
<span style={{ marginRight: 4 }}>{maskIdNumber(v)}</span>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ padding: '8px 4px' }}
|
||||
style={{ padding: '8px 4px', flex: 'none' }}
|
||||
onClick={() => handleViewSensitive(record.id, '身份证号', v)}
|
||||
title="点击查看完整号码"
|
||||
>
|
||||
@@ -329,12 +440,12 @@ const StudentsPage: React.FC = () => {
|
||||
render: (v: string, record: any) => {
|
||||
if (!v) return '-';
|
||||
return (
|
||||
<span>
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
|
||||
<span style={{ marginRight: 4 }}>{maskPhone(v)}</span>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ padding: '8px 4px' }}
|
||||
style={{ padding: '8px 4px', flex: 'none' }}
|
||||
onClick={() => handleViewSensitive(record.id, '紧急联系人电话', v)}
|
||||
title="点击查看完整号码"
|
||||
>
|
||||
@@ -441,16 +552,8 @@ const StudentsPage: React.FC = () => {
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<Space wrap>
|
||||
<div className="responsive-toolbar">
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<Input.Search
|
||||
placeholder="搜索学生姓名"
|
||||
onSearch={setSearchName}
|
||||
@@ -489,6 +592,36 @@ const StudentsPage: React.FC = () => {
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
<Select
|
||||
placeholder="所属班级"
|
||||
allowClear
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
style={{ width: 160 }}
|
||||
value={filterClassId}
|
||||
onChange={(v) => {
|
||||
setFilterClassId(v);
|
||||
}}
|
||||
options={classOptions.map((item) => ({
|
||||
value: item.id,
|
||||
label: item.code ? `${item.name}(${item.code})` : item.name,
|
||||
}))}
|
||||
/>
|
||||
<Select
|
||||
placeholder="所属老师"
|
||||
allowClear
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
style={{ width: 160 }}
|
||||
value={filterTeacherId}
|
||||
onChange={(v) => {
|
||||
setFilterTeacherId(v);
|
||||
}}
|
||||
options={teacherOptions.map((item) => ({
|
||||
value: item.id,
|
||||
label: item.name === item.username ? item.name : `${item.name}(${item.username})`,
|
||||
}))}
|
||||
/>
|
||||
<Button
|
||||
type={showArchived ? 'primary' : 'default'}
|
||||
onClick={() => setShowArchived(!showArchived)}
|
||||
@@ -498,7 +631,7 @@ const StudentsPage: React.FC = () => {
|
||||
: `显示已归档${archivedCount > 0 ? ` (${archivedCount})` : ''}`}
|
||||
</Button>
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<Popconfirm
|
||||
title={`确定批量归档选中的 ${selectedRowKeys.length} 名学生?(数据保留,可恢复)`}
|
||||
onConfirm={handleBatchDelete}
|
||||
@@ -509,7 +642,7 @@ const StudentsPage: React.FC = () => {
|
||||
<PermissionButton
|
||||
permission="student:delete"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
icon={<InboxOutlined />}
|
||||
disabled={selectedRowKeys.length === 0}
|
||||
loading={batchLoading}
|
||||
>
|
||||
@@ -533,26 +666,16 @@ const StudentsPage: React.FC = () => {
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
try {
|
||||
const res: any = await api.post('/students/import', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
});
|
||||
message.success(res.message);
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '导入失败');
|
||||
onError?.(e instanceof Error ? e : new Error(e?.message || '导入失败'));
|
||||
}
|
||||
}}
|
||||
customRequest={handleCreateStudentsImport}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入Excel</Button>
|
||||
</Upload>
|
||||
<Upload accept=".xlsx,.xls" showUploadList={false} customRequest={handleMatchImport}>
|
||||
<Button icon={<SwapOutlined />}>匹配导入</Button>
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={handleUpdateExistingStudentsImport}
|
||||
>
|
||||
<Button icon={<SwapOutlined />}>更新已有学生资料</Button>
|
||||
</Upload>
|
||||
<PermissionButton
|
||||
permission="student:view"
|
||||
@@ -570,6 +693,17 @@ const StudentsPage: React.FC = () => {
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
</div>
|
||||
<Alert
|
||||
showIcon
|
||||
type="warning"
|
||||
style={{ marginBottom: 12 }}
|
||||
message={
|
||||
<span>
|
||||
<strong>更新已有学生资料:</strong>先按手机号、再按身份证号匹配;Excel
|
||||
中填写的非空字段会覆盖原资料,未匹配的学生不会新增。请确认姓名、手机号、身份证号、所属机构和联系人等内容无误。
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
@@ -603,9 +737,9 @@ const StudentsPage: React.FC = () => {
|
||||
}
|
||||
return (
|
||||
<Card title="多班型对比" size="small" style={{ margin: '8px 0' }}>
|
||||
<Row gutter={16}>
|
||||
<Row gutter={[16, 16]}>
|
||||
{enrollments.map((enr, idx) => (
|
||||
<Col span={12} key={enr.classId}>
|
||||
<Col xs={24} md={12} key={enr.classId}>
|
||||
<Card
|
||||
size="small"
|
||||
title={enr.classType || `班型 ${idx + 1}`}
|
||||
|
||||
@@ -74,56 +74,65 @@ const TeacherWorkspacePage: React.FC = () => {
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
const classColumns: ColumnsType<AssignedClass> = useMemo(() => [
|
||||
{
|
||||
title: '班级名称',
|
||||
dataIndex: 'className',
|
||||
render: (v: string, r: AssignedClass) => `${v} (${r.classCode})`,
|
||||
},
|
||||
{
|
||||
title: '角色',
|
||||
dataIndex: 'roleType',
|
||||
render: (v: string) => <Tag>{ROLE_LABELS[v] || v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '科目',
|
||||
dataIndex: 'subject',
|
||||
render: (v: string | null) => v || '-',
|
||||
},
|
||||
], []);
|
||||
const classColumns: ColumnsType<AssignedClass> = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: '班级名称',
|
||||
dataIndex: 'className',
|
||||
render: (v: string, r: AssignedClass) => `${v} (${r.classCode})`,
|
||||
},
|
||||
{
|
||||
title: '角色',
|
||||
dataIndex: 'roleType',
|
||||
render: (v: string) => <Tag>{ROLE_LABELS[v] || v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '科目',
|
||||
dataIndex: 'subject',
|
||||
render: (v: string | null) => v || '-',
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
const scheduleColumns: ColumnsType<ScheduleItem> = useMemo(() => [
|
||||
{
|
||||
title: '时间',
|
||||
key: 'time',
|
||||
render: (_: unknown, r: ScheduleItem) => `${r.startTime} - ${r.endTime}`,
|
||||
},
|
||||
{
|
||||
title: '星期',
|
||||
dataIndex: 'weekDay',
|
||||
render: (v: number) => <Tag>{WEEKDAY_LABELS[String(v)] || v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '科目',
|
||||
dataIndex: 'subject',
|
||||
},
|
||||
{
|
||||
title: '类型',
|
||||
dataIndex: 'scheduleType',
|
||||
render: (v: string) => (
|
||||
<Tag color={v === 'INTERNAL' ? 'blue' : 'orange'}>
|
||||
{v === 'INTERNAL' ? '内部课程' : '租赁'}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
], []);
|
||||
const scheduleColumns: ColumnsType<ScheduleItem> = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: '时间',
|
||||
key: 'time',
|
||||
render: (_: unknown, r: ScheduleItem) => `${r.startTime} - ${r.endTime}`,
|
||||
},
|
||||
{
|
||||
title: '星期',
|
||||
dataIndex: 'weekDay',
|
||||
render: (v: number) => <Tag>{WEEKDAY_LABELS[String(v)] || v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '科目',
|
||||
dataIndex: 'subject',
|
||||
},
|
||||
{
|
||||
title: '类型',
|
||||
dataIndex: 'scheduleType',
|
||||
render: (v: string) => (
|
||||
<Tag color={v === 'INTERNAL' ? 'blue' : 'orange'}>
|
||||
{v === 'INTERNAL' ? '内部课程' : '租赁'}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
const studentColumns: ColumnsType<StudentItem> = useMemo(() => [
|
||||
{ title: '姓名', dataIndex: 'studentName' },
|
||||
{ title: '学号', dataIndex: 'studentNo', render: (v: string) => v || '-' },
|
||||
{ title: '班级', dataIndex: 'className' },
|
||||
{ title: '加入日期', dataIndex: 'joinDate', render: (v: string) => v || '-' },
|
||||
], []);
|
||||
const studentColumns: ColumnsType<StudentItem> = useMemo(
|
||||
() => [
|
||||
{ title: '姓名', dataIndex: 'studentName' },
|
||||
{ title: '学号', dataIndex: 'studentNo', render: (v: string) => v || '-' },
|
||||
{ title: '班级', dataIndex: 'className' },
|
||||
{ title: '加入日期', dataIndex: 'joinDate', render: (v: string) => v || '-' },
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
|
||||
@@ -101,87 +101,94 @@ const TeachersPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const columns = useMemo(() => [
|
||||
{ title: '姓名', dataIndex: 'name', key: 'name', width: 120 },
|
||||
{ title: '用户名', dataIndex: 'username', key: 'username', width: 130 },
|
||||
{
|
||||
title: '角色',
|
||||
dataIndex: 'roles',
|
||||
key: 'roles',
|
||||
width: 220,
|
||||
render: (roles: TeacherRow['roles']) =>
|
||||
roles.map((r) => <Tag key={r.code}>{ROLE_LABELS[r.code] || r.name}</Tag>),
|
||||
},
|
||||
{
|
||||
title: '任课班级',
|
||||
dataIndex: 'classAssignments',
|
||||
key: 'classes',
|
||||
width: 200,
|
||||
render: (ca: TeacherRow['classAssignments']) =>
|
||||
ca?.length
|
||||
? ca.map((a, i) => (
|
||||
<Tag key={i}>
|
||||
{a.className || '-'}
|
||||
{a.subject ? ` (${a.subject})` : ''}
|
||||
</Tag>
|
||||
))
|
||||
: '-',
|
||||
},
|
||||
{
|
||||
title: '科目',
|
||||
dataIndex: 'profile',
|
||||
key: 'subjects',
|
||||
width: 130,
|
||||
render: (p: TeacherRow['profile']) => p?.subjects?.join('、') || '-',
|
||||
},
|
||||
{
|
||||
title: '入职日期',
|
||||
dataIndex: 'profile',
|
||||
key: 'joinedAt',
|
||||
width: 110,
|
||||
render: (p: TeacherRow['profile']) => p?.joinedAt || '-',
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'isActive',
|
||||
key: 'status',
|
||||
width: 90,
|
||||
render: (v: boolean) => <Tag color={v ? 'green' : 'red'}>{v ? '在职' : '停用'}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '最后登录',
|
||||
dataIndex: 'lastLoginAt',
|
||||
key: 'login',
|
||||
width: 160,
|
||||
render: (v: string) => (v ? dayjs(v).format('YYYY-MM-DD HH:mm') : '-'),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'actions',
|
||||
width: 100,
|
||||
render: (_: unknown, r: TeacherRow) => (
|
||||
<Button
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => {
|
||||
setProfileModal(r);
|
||||
form.setFieldsValue({
|
||||
subjects: r.profile?.subjects || [],
|
||||
joinedAt: r.profile?.joinedAt ? dayjs(r.profile.joinedAt) : null,
|
||||
qualifications: r.profile?.qualifications || '',
|
||||
});
|
||||
}}
|
||||
>
|
||||
档案
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
], []);
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{ title: '姓名', dataIndex: 'name', key: 'name', width: 120 },
|
||||
{ title: '用户名', dataIndex: 'username', key: 'username', width: 130 },
|
||||
{
|
||||
title: '角色',
|
||||
dataIndex: 'roles',
|
||||
key: 'roles',
|
||||
width: 220,
|
||||
render: (roles: TeacherRow['roles']) =>
|
||||
roles.map((r) => <Tag key={r.code}>{ROLE_LABELS[r.code] || r.name}</Tag>),
|
||||
},
|
||||
{
|
||||
title: '任课班级',
|
||||
dataIndex: 'classAssignments',
|
||||
key: 'classes',
|
||||
width: 200,
|
||||
render: (ca: TeacherRow['classAssignments']) =>
|
||||
ca?.length
|
||||
? ca.map((a, i) => (
|
||||
<Tag key={i}>
|
||||
{a.className || '-'}
|
||||
{a.subject ? ` (${a.subject})` : ''}
|
||||
</Tag>
|
||||
))
|
||||
: '-',
|
||||
},
|
||||
{
|
||||
title: '科目',
|
||||
dataIndex: 'profile',
|
||||
key: 'subjects',
|
||||
width: 130,
|
||||
render: (p: TeacherRow['profile']) => p?.subjects?.join('、') || '-',
|
||||
},
|
||||
{
|
||||
title: '入职日期',
|
||||
dataIndex: 'profile',
|
||||
key: 'joinedAt',
|
||||
width: 110,
|
||||
render: (p: TeacherRow['profile']) => p?.joinedAt || '-',
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'isActive',
|
||||
key: 'status',
|
||||
width: 90,
|
||||
render: (v: boolean) => <Tag color={v ? 'green' : 'red'}>{v ? '在职' : '停用'}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '最后登录',
|
||||
dataIndex: 'lastLoginAt',
|
||||
key: 'login',
|
||||
width: 160,
|
||||
render: (v: string) => (v ? dayjs(v).format('YYYY-MM-DD HH:mm') : '-'),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'actions',
|
||||
width: 100,
|
||||
render: (_: unknown, r: TeacherRow) => (
|
||||
<Button
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => {
|
||||
setProfileModal(r);
|
||||
form.setFieldsValue({
|
||||
subjects: r.profile?.subjects || [],
|
||||
joinedAt: r.profile?.joinedAt ? dayjs(r.profile.joinedAt) : null,
|
||||
qualifications: r.profile?.qualifications || '',
|
||||
});
|
||||
}}
|
||||
>
|
||||
档案
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h2 style={{ marginBottom: 16 }}>教师管理</h2>
|
||||
<Space style={{ marginBottom: 16 }}>
|
||||
<Space
|
||||
style={{ marginBottom: 16 }}
|
||||
wrap
|
||||
className="responsive-toolbar responsive-toolbar--single"
|
||||
>
|
||||
<Input.Search
|
||||
placeholder="搜索姓名/用户名"
|
||||
allowClear
|
||||
|
||||
@@ -1,24 +1,17 @@
|
||||
import React, { useEffect, useState, useMemo, useCallback } from 'react';
|
||||
import { Table, Modal, Form, Input, Select, Switch, Space, Tag, Popconfirm } from 'antd';
|
||||
import {
|
||||
Table,
|
||||
Modal,
|
||||
Form,
|
||||
Input,
|
||||
Select,
|
||||
Switch,
|
||||
Space,
|
||||
Tag,
|
||||
Popconfirm,
|
||||
} from 'antd';
|
||||
import { PlusOutlined, EditOutlined, DeleteOutlined, KeyOutlined, IdcardOutlined, InboxOutlined } from '@ant-design/icons';
|
||||
PlusOutlined,
|
||||
EditOutlined,
|
||||
KeyOutlined,
|
||||
IdcardOutlined,
|
||||
InboxOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { message } from '../../ui/app-message';
|
||||
import {
|
||||
userProfileResponseToFormValues,
|
||||
type UserProfileResponse,
|
||||
} from './user-profile-form';
|
||||
import { userProfileResponseToFormValues, type UserProfileResponse } from './user-profile-form';
|
||||
|
||||
const UsersPage: React.FC = () => {
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
@@ -36,7 +29,6 @@ const UsersPage: React.FC = () => {
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
|
||||
|
||||
const handleOpenProfile = async (record: any) => {
|
||||
setProfileUser(record);
|
||||
try {
|
||||
@@ -79,7 +71,6 @@ const UsersPage: React.FC = () => {
|
||||
setLoading(false);
|
||||
}, [showArchived]);
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
@@ -141,18 +132,6 @@ const UsersPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/rbac/users/${id}`);
|
||||
message.success('已删除');
|
||||
fetchData();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
message.error(err?.message || '删除失败');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const handleResetPwd = (record: any) => {
|
||||
setResetTarget(record);
|
||||
pwdForm.resetFields();
|
||||
@@ -174,96 +153,99 @@ const UsersPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const columns = useMemo(() => [
|
||||
{ title: 'ID', dataIndex: 'id', width: 60 },
|
||||
{ title: '用户名', dataIndex: 'username', width: 120 },
|
||||
{ title: '姓名', dataIndex: 'name', width: 120 },
|
||||
{
|
||||
title: '角色',
|
||||
dataIndex: 'roles',
|
||||
width: 200,
|
||||
render: (v: any[]) =>
|
||||
v && v.length > 0 ? (
|
||||
v.map((r: any) => (
|
||||
<Tag key={r.id} color="blue">
|
||||
{r.name}
|
||||
</Tag>
|
||||
))
|
||||
) : (
|
||||
<Tag color="default">无角色</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'isActive',
|
||||
width: 80,
|
||||
render: (v: boolean) => <Tag color={v ? 'green' : 'default'}>{v ? '启用' : '禁用'}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '最后登录',
|
||||
dataIndex: 'lastLoginAt',
|
||||
width: 170,
|
||||
render: (v: string) => (v ? dayjs(v).format('YYYY-MM-DD HH:mm:ss') : '-'),
|
||||
},
|
||||
{
|
||||
title: '创建时间',
|
||||
dataIndex: 'createdAt',
|
||||
width: 170,
|
||||
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm:ss'),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 240,
|
||||
fixed: 'right' as const,
|
||||
render: (_: unknown, record: any) => (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="user:edit"
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<IdcardOutlined />}
|
||||
onClick={() => handleOpenProfile(record)}
|
||||
>
|
||||
档案
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="user:edit"
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => handleEdit(record)}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="user:reset-password"
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<KeyOutlined />}
|
||||
onClick={() => handleResetPwd(record)}
|
||||
>
|
||||
重置密码
|
||||
</PermissionButton>
|
||||
{record.isArchived ? (
|
||||
<Popconfirm title="确认恢复?" onConfirm={() => handleArchive(record.id, false)}>
|
||||
<PermissionButton permission="user:edit" type="link" size="small">恢复</PermissionButton>
|
||||
</Popconfirm>
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{ title: 'ID', dataIndex: 'id', width: 60 },
|
||||
{ title: '用户名', dataIndex: 'username', width: 120 },
|
||||
{ title: '姓名', dataIndex: 'name', width: 120 },
|
||||
{
|
||||
title: '角色',
|
||||
dataIndex: 'roles',
|
||||
width: 200,
|
||||
render: (v: any[]) =>
|
||||
v && v.length > 0 ? (
|
||||
v.map((r: any) => (
|
||||
<Tag key={r.id} color="blue">
|
||||
{r.name}
|
||||
</Tag>
|
||||
))
|
||||
) : (
|
||||
<Popconfirm title="归档后可恢复,确认归档?" onConfirm={() => handleArchive(record.id, true)}>
|
||||
<PermissionButton permission="user:edit" type="link" size="small">归档</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
{record.username !== 'admin' && (
|
||||
<Popconfirm title="确认删除?需先归档" onConfirm={() => handleDelete(record.id)}>
|
||||
<PermissionButton permission="user:delete" type="link" size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
], []);
|
||||
<Tag color="default">无角色</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'isActive',
|
||||
width: 80,
|
||||
render: (v: boolean) => <Tag color={v ? 'green' : 'default'}>{v ? '启用' : '禁用'}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '最后登录',
|
||||
dataIndex: 'lastLoginAt',
|
||||
width: 170,
|
||||
render: (v: string) => (v ? dayjs(v).format('YYYY-MM-DD HH:mm:ss') : '-'),
|
||||
},
|
||||
{
|
||||
title: '创建时间',
|
||||
dataIndex: 'createdAt',
|
||||
width: 170,
|
||||
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm:ss'),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 240,
|
||||
fixed: 'right' as const,
|
||||
render: (_: unknown, record: any) => (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="user:edit"
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<IdcardOutlined />}
|
||||
onClick={() => handleOpenProfile(record)}
|
||||
>
|
||||
档案
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="user:edit"
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => handleEdit(record)}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="user:reset-password"
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<KeyOutlined />}
|
||||
onClick={() => handleResetPwd(record)}
|
||||
>
|
||||
重置密码
|
||||
</PermissionButton>
|
||||
{record.isArchived ? (
|
||||
<Popconfirm title="确认恢复?" onConfirm={() => handleArchive(record.id, false)}>
|
||||
<PermissionButton permission="user:edit" type="link" size="small">
|
||||
恢复
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
) : (
|
||||
<Popconfirm
|
||||
title="归档后可恢复,确认归档?"
|
||||
onConfirm={() => handleArchive(record.id, true)}
|
||||
>
|
||||
<PermissionButton permission="user:edit" type="link" size="small">
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -275,7 +257,8 @@ const UsersPage: React.FC = () => {
|
||||
alignItems: 'center',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}>
|
||||
}}
|
||||
>
|
||||
<h2 style={{ margin: 0 }}>账号管理</h2>
|
||||
<Space wrap>
|
||||
<PermissionButton
|
||||
@@ -393,10 +376,7 @@ const UsersPage: React.FC = () => {
|
||||
<Form.Item name="qualifications" label="资质">
|
||||
<Input.TextArea placeholder="教师资格证号、学历等" rows={2} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="subjects"
|
||||
label="任教学科"
|
||||
>
|
||||
<Form.Item name="subjects" label="任教学科">
|
||||
<Select
|
||||
mode="tags"
|
||||
placeholder="输入学科后回车添加"
|
||||
@@ -415,7 +395,7 @@ const UsersPage: React.FC = () => {
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
393
apps/admin/src/pages/Wallets/index.tsx
Normal file
393
apps/admin/src/pages/Wallets/index.tsx
Normal file
@@ -0,0 +1,393 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Drawer,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Radio,
|
||||
Select,
|
||||
Space,
|
||||
Switch,
|
||||
Table,
|
||||
Tag,
|
||||
} from 'antd';
|
||||
import { HistoryOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { newOperationId } from '../../utils/operation-id';
|
||||
|
||||
interface WalletRow {
|
||||
studentId: number;
|
||||
studentName: string;
|
||||
studentNo?: string;
|
||||
balance: number;
|
||||
outstandingAmount: number;
|
||||
roomType?: string;
|
||||
roomNumber?: string;
|
||||
}
|
||||
|
||||
const transactionNames: Record<string, string> = {
|
||||
recharge: '充值',
|
||||
adjustment: '调账',
|
||||
bill_payment: '账单扣款',
|
||||
bill_refund: '账单冲正',
|
||||
};
|
||||
|
||||
const WalletsPage: React.FC = () => {
|
||||
const [rows, setRows] = useState<WalletRow[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [debtOnly, setDebtOnly] = useState(false);
|
||||
const [roomType, setRoomType] = useState<string | undefined>();
|
||||
const [roomTypes, setRoomTypes] = useState<string[]>([]);
|
||||
const [selected, setSelected] = useState<WalletRow | null>(null);
|
||||
const [transactions, setTransactions] = useState<any[]>([]);
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const [form] = Form.useForm();
|
||||
const [batchForm] = Form.useForm();
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
|
||||
const [batchModalOpen, setBatchModalOpen] = useState(false);
|
||||
|
||||
const fetchRows = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await api.get('/wallets', {
|
||||
params: { keyword: keyword || undefined, debtOnly, roomType },
|
||||
});
|
||||
setRows(data as WalletRow[]);
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '加载学生余额失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [keyword, debtOnly, roomType]);
|
||||
|
||||
useEffect(() => {
|
||||
void fetchRows();
|
||||
}, [fetchRows]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchRoomTypes = async () => {
|
||||
try {
|
||||
setRoomTypes((await api.get('/wallets/room-types')) as string[]);
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '加载房型失败');
|
||||
}
|
||||
};
|
||||
void fetchRoomTypes();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedRowKeys([]);
|
||||
}, [keyword, debtOnly, roomType]);
|
||||
|
||||
const openChange = (row: WalletRow) => {
|
||||
setSelected(row);
|
||||
form.setFieldsValue({ type: 'recharge', amount: undefined, description: '' });
|
||||
};
|
||||
|
||||
const openBatchChange = () => {
|
||||
batchForm.setFieldsValue({ type: 'recharge', amount: undefined, description: '' });
|
||||
setBatchModalOpen(true);
|
||||
};
|
||||
|
||||
const submitChange = async () => {
|
||||
if (!selected) return;
|
||||
const values = await form.validateFields();
|
||||
setSaving(true);
|
||||
try {
|
||||
const result: any = await api.post('/wallets/change-balance', {
|
||||
operationId: newOperationId(),
|
||||
studentId: selected.studentId,
|
||||
...values,
|
||||
});
|
||||
const paid = (result.payments || []).reduce(
|
||||
(sum: number, bill: any) => sum + Number(bill.paidAmount || 0),
|
||||
0,
|
||||
);
|
||||
message.success(paid > 0 ? `余额已更新,并自动补扣历史账单` : '余额已更新');
|
||||
setSelected(null);
|
||||
await fetchRows();
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '余额操作失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const submitBatchChange = async () => {
|
||||
const values = await batchForm.validateFields();
|
||||
setSaving(true);
|
||||
try {
|
||||
const result: any = await api.post('/wallets/batch-change-balance', {
|
||||
operationId: newOperationId(),
|
||||
studentIds: selectedRowKeys,
|
||||
...values,
|
||||
});
|
||||
const paid = (result.results || []).reduce((sum: number, item: any) => {
|
||||
return (
|
||||
sum +
|
||||
(item.payments || []).reduce(
|
||||
(paymentSum: number, bill: any) => paymentSum + Number(bill.paidAmount || 0),
|
||||
0,
|
||||
)
|
||||
);
|
||||
}, 0);
|
||||
message.success(
|
||||
paid > 0
|
||||
? `已批量更新 ${selectedRowKeys.length} 名学生余额,并自动补扣历史账单`
|
||||
: `已批量更新 ${selectedRowKeys.length} 名学生余额`,
|
||||
);
|
||||
setBatchModalOpen(false);
|
||||
setSelectedRowKeys([]);
|
||||
batchForm.resetFields();
|
||||
await fetchRows();
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '批量余额操作失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const showTransactions = async (row: WalletRow) => {
|
||||
setSelected(row);
|
||||
setDrawerOpen(true);
|
||||
try {
|
||||
setTransactions(
|
||||
(await api.get('/wallets/transactions', { params: { studentId: row.studentId } })) as any[],
|
||||
);
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '加载流水失败');
|
||||
}
|
||||
};
|
||||
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: '学生',
|
||||
render: (_: unknown, row: WalletRow) => (
|
||||
<>
|
||||
<strong>{row.studentName}</strong>
|
||||
<div style={{ color: '#999' }}>{row.studentNo || `#${row.studentId}`}</div>
|
||||
<div style={{ color: '#999' }}>
|
||||
{row.roomType ? `${row.roomType}${row.roomNumber ? ` · ${row.roomNumber}` : ''}` : '未入住'}
|
||||
</div>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '可用余额',
|
||||
dataIndex: 'balance',
|
||||
render: (value: number) => (
|
||||
<strong style={{ color: Number(value) > 0 ? '#1677ff' : undefined }}>
|
||||
¥{Number(value).toFixed(2)}
|
||||
</strong>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '未付账单',
|
||||
dataIndex: 'outstandingAmount',
|
||||
render: (value: number) =>
|
||||
Number(value) > 0 ? (
|
||||
<Tag color="red">¥{Number(value).toFixed(2)}</Tag>
|
||||
) : (
|
||||
<Tag color="green">无欠费</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
render: (_: unknown, row: WalletRow) => (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="wallet:edit"
|
||||
type="primary"
|
||||
size="small"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => openChange(row)}
|
||||
>
|
||||
充值/调账
|
||||
</PermissionButton>
|
||||
<Button size="small" icon={<HistoryOutlined />} onClick={() => showTransactions(row)}>
|
||||
流水
|
||||
</Button>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
gap: 12,
|
||||
marginBottom: 16,
|
||||
flexWrap: 'wrap',
|
||||
}}
|
||||
>
|
||||
<Space wrap>
|
||||
<Input.Search
|
||||
allowClear
|
||||
placeholder="搜索姓名或学号"
|
||||
style={{ width: 240 }}
|
||||
onSearch={setKeyword}
|
||||
onChange={(event) => !event.target.value && setKeyword('')}
|
||||
/>
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="按房型筛选"
|
||||
style={{ width: 180 }}
|
||||
value={roomType}
|
||||
onChange={setRoomType}
|
||||
options={roomTypes.map((type) => ({ label: type, value: type }))}
|
||||
/>
|
||||
<span>仅看欠费</span>
|
||||
<Switch checked={debtOnly} onChange={setDebtOnly} />
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<PermissionButton
|
||||
permission="wallet:edit"
|
||||
type="primary"
|
||||
icon={<PlusOutlined />}
|
||||
disabled={selectedRowKeys.length === 0}
|
||||
onClick={openBatchChange}
|
||||
>
|
||||
批量充值/调账
|
||||
</PermissionButton>
|
||||
<Button icon={<ReloadOutlined />} onClick={fetchRows}>
|
||||
刷新
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
<Table
|
||||
rowKey="studentId"
|
||||
loading={loading}
|
||||
dataSource={rows}
|
||||
columns={columns}
|
||||
rowSelection={{ selectedRowKeys, onChange: setSelectedRowKeys }}
|
||||
pagination={{ pageSize: 15, showTotal: (total) => `共 ${total} 人` }}
|
||||
/>
|
||||
<Modal
|
||||
title={`${selected?.studentName || ''} - 余额操作`}
|
||||
open={!!selected && !drawerOpen}
|
||||
onCancel={() => setSelected(null)}
|
||||
onOk={submitChange}
|
||||
confirmLoading={saving}
|
||||
okText="确认"
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="type" label="操作类型" rules={[{ required: true }]}>
|
||||
<Radio.Group
|
||||
options={[
|
||||
{ label: '充值', value: 'recharge' },
|
||||
{ label: '调账', value: 'adjustment' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="amount"
|
||||
label="变动金额"
|
||||
extra="充值填正数;调减余额时填写负数。充值后会按最早账单优先自动补扣。"
|
||||
rules={[{ required: true, message: '请输入金额' }]}
|
||||
>
|
||||
<InputNumber precision={2} style={{ width: '100%' }} addonBefore="¥" />
|
||||
</Form.Item>
|
||||
<Form.Item name="description" label="备注">
|
||||
<Input.TextArea maxLength={300} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
<Modal
|
||||
title={`批量余额操作(${selectedRowKeys.length} 人)`}
|
||||
open={batchModalOpen}
|
||||
onCancel={() => setBatchModalOpen(false)}
|
||||
onOk={submitBatchChange}
|
||||
confirmLoading={saving}
|
||||
okText="确认批量修改"
|
||||
>
|
||||
<Form form={batchForm} layout="vertical">
|
||||
<div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 8 }}>
|
||||
已选择 <strong>{selectedRowKeys.length}</strong>{' '}
|
||||
名学生,将按相同金额批量修改水电费余额。可先按房型筛选并勾选对应学生后批量缴费。
|
||||
</div>
|
||||
<Form.Item name="type" label="操作类型" rules={[{ required: true }]}>
|
||||
<Radio.Group
|
||||
options={[
|
||||
{ label: '充值', value: 'recharge' },
|
||||
{ label: '调账', value: 'adjustment' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="amount"
|
||||
label="变动金额(元/人)"
|
||||
extra="充值填正数;调减余额时填写负数。充值后会按最早账单优先自动补扣。"
|
||||
rules={[{ required: true, message: '请输入金额' }]}
|
||||
>
|
||||
<InputNumber precision={2} style={{ width: '100%' }} addonBefore="¥" />
|
||||
</Form.Item>
|
||||
<Form.Item name="description" label="备注">
|
||||
<Input.TextArea maxLength={300} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
<Drawer
|
||||
title={`${selected?.studentName || ''} - 余额流水`}
|
||||
width={680}
|
||||
open={drawerOpen}
|
||||
onClose={() => {
|
||||
setDrawerOpen(false);
|
||||
setSelected(null);
|
||||
}}
|
||||
>
|
||||
<Table
|
||||
rowKey="id"
|
||||
dataSource={transactions}
|
||||
pagination={{ pageSize: 10 }}
|
||||
columns={[
|
||||
{
|
||||
title: '时间',
|
||||
dataIndex: 'createdAt',
|
||||
render: (value: string) => dayjs(value).format('YYYY-MM-DD HH:mm'),
|
||||
},
|
||||
{
|
||||
title: '类型',
|
||||
dataIndex: 'type',
|
||||
render: (value: string) => transactionNames[value] || value,
|
||||
},
|
||||
{
|
||||
title: '金额',
|
||||
dataIndex: 'amount',
|
||||
render: (value: number) => (
|
||||
<span style={{ color: Number(value) >= 0 ? '#389e0d' : '#cf1322' }}>
|
||||
{Number(value) >= 0 ? '+' : ''}¥{Number(value).toFixed(2)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '变动后余额',
|
||||
dataIndex: 'balanceAfter',
|
||||
render: (value: number) => `¥${Number(value).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '关联账单',
|
||||
dataIndex: 'billId',
|
||||
render: (value: number) => (value ? `#${value}` : '-'),
|
||||
},
|
||||
{ title: '说明', dataIndex: 'description' },
|
||||
]}
|
||||
/>
|
||||
</Drawer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default WalletsPage;
|
||||
@@ -202,24 +202,67 @@ export const LOG_ACTIONS = {
|
||||
// ── Permission nodes (PRD §17) ──────────────────────────────────────
|
||||
|
||||
export const PERMISSION_NODES = [
|
||||
'student:view', 'student:add', 'student:update', 'student:delete',
|
||||
'student:import', 'student:export',
|
||||
'room:view', 'room:add', 'room:update', 'room:delete',
|
||||
'occupancy:view', 'occupancy:add', 'occupancy:update',
|
||||
'bill:view', 'bill:generate', 'bill:confirm', 'bill:markPaid', 'bill:export',
|
||||
'expense:view', 'expense:add', 'expense:update', 'expense:delete',
|
||||
'deposit:view', 'deposit:collect', 'deposit:refund',
|
||||
'class:view', 'class:add', 'class:update', 'class:delete',
|
||||
'schedule:view', 'schedule:add', 'schedule:update', 'schedule:delete',
|
||||
'attendance:view', 'attendance:add', 'attendance:update', 'attendance:delete',
|
||||
'student:view',
|
||||
'student:add',
|
||||
'student:update',
|
||||
'student:delete',
|
||||
'student:import',
|
||||
'student:export',
|
||||
'room:view',
|
||||
'room:add',
|
||||
'room:update',
|
||||
'room:delete',
|
||||
'occupancy:view',
|
||||
'occupancy:add',
|
||||
'occupancy:update',
|
||||
'bill:view',
|
||||
'bill:generate',
|
||||
'bill:confirm',
|
||||
'bill:markPaid',
|
||||
'bill:export',
|
||||
'expense:view',
|
||||
'expense:add',
|
||||
'expense:update',
|
||||
'expense:delete',
|
||||
'deposit:view',
|
||||
'deposit:collect',
|
||||
'deposit:refund',
|
||||
'class:view',
|
||||
'class:add',
|
||||
'class:update',
|
||||
'class:delete',
|
||||
'schedule:view',
|
||||
'schedule:add',
|
||||
'schedule:update',
|
||||
'schedule:delete',
|
||||
'attendance:view',
|
||||
'attendance:add',
|
||||
'attendance:update',
|
||||
'attendance:delete',
|
||||
'attendance:batch',
|
||||
'classroom:view', 'classroom:add', 'classroom:update', 'classroom:delete',
|
||||
'organization:view', 'organization:create', 'organization:edit', 'organization:delete',
|
||||
'rental:view', 'rental:add', 'rental:update', 'rental:delete',
|
||||
'archive:view', 'archive:import', 'archive:export',
|
||||
'classroom:view',
|
||||
'classroom:add',
|
||||
'classroom:update',
|
||||
'classroom:delete',
|
||||
'organization:view',
|
||||
'organization:create',
|
||||
'organization:edit',
|
||||
'organization:delete',
|
||||
'rental:view',
|
||||
'rental:add',
|
||||
'rental:update',
|
||||
'rental:delete',
|
||||
'archive:view',
|
||||
'archive:import',
|
||||
'archive:export',
|
||||
'report:generate',
|
||||
'log:view',
|
||||
'role:view', 'role:add', 'role:update', 'role:delete',
|
||||
'user:view', 'user:add', 'user:update', 'user:delete',
|
||||
'role:view',
|
||||
'role:add',
|
||||
'role:update',
|
||||
'role:delete',
|
||||
'user:view',
|
||||
'user:add',
|
||||
'user:update',
|
||||
'dashboard:view',
|
||||
] as const;
|
||||
|
||||
@@ -25,7 +25,9 @@ type Role = keyof typeof CREDENTIALS;
|
||||
* Login as a specific role and store the token in localStorage.
|
||||
* Returns the parsed response data.
|
||||
*/
|
||||
export async function loginAs(role: Role): Promise<{ token: string; user: Record<string, unknown> }> {
|
||||
export async function loginAs(
|
||||
role: Role,
|
||||
): Promise<{ token: string; user: Record<string, unknown> }> {
|
||||
const creds = CREDENTIALS[role];
|
||||
const res = await fetch(`${BASE}/api/auth/login`, {
|
||||
method: 'POST',
|
||||
|
||||
1
apps/admin/src/utils/operation-id.ts
Normal file
1
apps/admin/src/utils/operation-id.ts
Normal file
@@ -0,0 +1 @@
|
||||
export const newOperationId = () => crypto.randomUUID();
|
||||
@@ -22,7 +22,7 @@ JWT_EXPIRES_IN=24h
|
||||
ADMIN_PASSWORD=请替换为强密码
|
||||
|
||||
# ---- 服务端口 ----
|
||||
PORT=3000
|
||||
PORT=3002
|
||||
|
||||
# ---- 文件上传 ----
|
||||
# 合同 PDF 存储根目录(相对或绝对)
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
FROM node:22-alpine AS builder
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
COPY apps/server/package.json ./apps/server/package.json
|
||||
COPY packages/typescript-config/package.json ./packages/typescript-config/package.json
|
||||
RUN npm ci --no-optional
|
||||
COPY . .
|
||||
RUN npm run build -w @gongxue/server
|
||||
|
||||
FROM node:22-alpine
|
||||
WORKDIR /app
|
||||
COPY --from=builder /app/apps/server/dist ./dist
|
||||
COPY --from=builder /app/apps/server/package.json ./
|
||||
COPY --from=builder /app/node_modules ./node_modules
|
||||
EXPOSE 3000
|
||||
CMD ["node", "dist/main.js"]
|
||||
21
apps/server/datasource.ts
Normal file
21
apps/server/datasource.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { DataSource } from 'typeorm';
|
||||
import { config } from 'dotenv';
|
||||
import { join } from 'path';
|
||||
|
||||
// TypeORM CLI runs from apps/server/
|
||||
const root = process.cwd();
|
||||
config({ path: join(root, '.env') });
|
||||
|
||||
const dbType = process.env.DB_TYPE || 'sqlite';
|
||||
|
||||
export default new DataSource({
|
||||
type: dbType === 'mysql' ? 'mysql' : 'better-sqlite3',
|
||||
host: dbType === 'mysql' ? (process.env.DB_HOST || 'localhost') : undefined,
|
||||
port: dbType === 'mysql' ? (Number(process.env.DB_PORT) || 3306) : undefined,
|
||||
username: dbType === 'mysql' ? (process.env.DB_USERNAME || 'root') : undefined,
|
||||
password: dbType === 'mysql' ? (process.env.DB_PASSWORD || '') : undefined,
|
||||
database: process.env.DB_DATABASE || (dbType === 'mysql' ? 'dorm_billing' : 'dorm_billing.db'),
|
||||
charset: dbType === 'mysql' ? 'utf8mb4' : undefined,
|
||||
entities: [join(root, 'src/**/*.entity.ts')],
|
||||
migrations: [join(root, 'src/migrations/*.ts')],
|
||||
});
|
||||
@@ -19,7 +19,12 @@
|
||||
"test:watch": "jest --watch",
|
||||
"test:cov": "jest --coverage",
|
||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json",
|
||||
"migration:generate": "ts-node -r tsconfig-paths/register -P tsconfig.json ../../node_modules/typeorm/cli.js -d datasource.ts migration:generate",
|
||||
"migration:create": "ts-node -r tsconfig-paths/register -P tsconfig.json ../../node_modules/typeorm/cli.js -d datasource.ts migration:create",
|
||||
"migration:run": "ts-node -r tsconfig-paths/register -P tsconfig.json ../../node_modules/typeorm/cli.js -d datasource.ts migration:run",
|
||||
"migration:revert": "ts-node -r tsconfig-paths/register -P tsconfig.json ../../node_modules/typeorm/cli.js -d datasource.ts migration:revert",
|
||||
"migration:show": "ts-node -r tsconfig-paths/register -P tsconfig.json ../../node_modules/typeorm/cli.js -d datasource.ts migration:show"
|
||||
},
|
||||
"dependencies": {
|
||||
"@casl/ability": "^7.0.1",
|
||||
|
||||
@@ -30,6 +30,8 @@ import {
|
||||
ClassSchedule,
|
||||
AttendanceRecord,
|
||||
AttendanceSession,
|
||||
AttendanceDevice,
|
||||
AttendancePeriodConfig,
|
||||
DingAttendanceRaw,
|
||||
SyncLog,
|
||||
SyncState,
|
||||
@@ -43,8 +45,13 @@ import {
|
||||
ArchiveAttachment,
|
||||
StudentDingMapping,
|
||||
AiConfig,
|
||||
StudentWallet,
|
||||
WalletTransaction,
|
||||
FinancialOperation,
|
||||
} from './entities';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { InitialSchema1784520727860 } from './migrations/1784520727860-InitialSchema';
|
||||
const allMigrations = [InitialSchema1784520727860];
|
||||
import { AuthorizationModule } from './authorization';
|
||||
import { RbacModule } from './rbac/rbac.module';
|
||||
import { StudentsModule } from './students/students.module';
|
||||
@@ -62,6 +69,7 @@ import { ClassroomsModule } from './classrooms/classrooms.module';
|
||||
import { ClassesModule } from './classes/classes.module';
|
||||
import { OrganizationsModule } from './organizations/organizations.module';
|
||||
import { AttendanceModule } from './attendance/attendance.module';
|
||||
import { AttendanceDevicesModule } from './attendance-devices/attendance-devices.module';
|
||||
import { SchedulesModule } from './schedules/schedules.module';
|
||||
import { ClassroomRentalsModule } from './classroom-rentals/classroom-rentals.module';
|
||||
import { SyncModule } from './sync/sync.module';
|
||||
@@ -71,6 +79,8 @@ import { ExpenseTypesModule } from './expense-types/expense-types.module';
|
||||
import { DatabaseMigrationsModule } from './database/database-migrations.module';
|
||||
import { AgentToolsModule } from './agent-tools';
|
||||
import { AiConfigModule } from './ai-config/ai-config.module';
|
||||
import { WalletsModule } from './wallets/wallets.module';
|
||||
import { FinancialOperationsModule } from './financial-operations/financial-operations.module';
|
||||
|
||||
import {
|
||||
IntegrationConfig,
|
||||
@@ -120,6 +130,8 @@ import { IntegrationConfigModule } from './integration/config/config.module';
|
||||
ClassSchedule,
|
||||
AttendanceRecord,
|
||||
AttendanceSession,
|
||||
AttendanceDevice,
|
||||
AttendancePeriodConfig,
|
||||
DingAttendanceRaw,
|
||||
Notification,
|
||||
StudentProfile,
|
||||
@@ -135,6 +147,9 @@ import { IntegrationConfigModule } from './integration/config/config.module';
|
||||
IntegrationConfig,
|
||||
IntegrationConfigDetail,
|
||||
AiConfig,
|
||||
StudentWallet,
|
||||
WalletTransaction,
|
||||
FinancialOperation,
|
||||
];
|
||||
if (dbType === 'mysql') {
|
||||
return {
|
||||
@@ -145,6 +160,7 @@ import { IntegrationConfigModule } from './integration/config/config.module';
|
||||
password: config.get<string>('DB_PASSWORD', ''),
|
||||
database: config.get<string>('DB_DATABASE', 'dorm_billing'),
|
||||
entities: allEntities,
|
||||
migrations: allMigrations,
|
||||
synchronize: config.get('DB_SYNCHRONIZE', 'true') !== 'false',
|
||||
charset: 'utf8mb4',
|
||||
};
|
||||
@@ -152,6 +168,7 @@ import { IntegrationConfigModule } from './integration/config/config.module';
|
||||
return {
|
||||
type: 'better-sqlite3' as const,
|
||||
database: config.get<string>('DB_DATABASE', 'dorm_billing.db'),
|
||||
migrations: allMigrations,
|
||||
entities: allEntities,
|
||||
synchronize: config.get('DB_SYNCHRONIZE', 'true') !== 'false',
|
||||
};
|
||||
@@ -168,8 +185,11 @@ import { IntegrationConfigModule } from './integration/config/config.module';
|
||||
DashboardModule,
|
||||
OperationLogsModule,
|
||||
DepositsModule,
|
||||
WalletsModule,
|
||||
FinancialOperationsModule,
|
||||
ClassroomsModule,
|
||||
AttendanceModule,
|
||||
AttendanceDevicesModule,
|
||||
ClassesModule,
|
||||
OrganizationsModule,
|
||||
SchedulesModule,
|
||||
|
||||
@@ -208,11 +208,11 @@ export class ArchiveReportService {
|
||||
}
|
||||
|
||||
private pageHeader(title: string): string {
|
||||
return `<div class="header"><span class="logo">G</span><span class="brand">工学云 · 学生档案</span><span class="page-kicker">${this.esc(title)}</span></div>`;
|
||||
return `<div class="header"><span class="logo">G</span><span class="brand">恭学教育 · 学生档案</span><span class="page-kicker">${this.esc(title)}</span></div>`;
|
||||
}
|
||||
|
||||
private pageFooter(): string {
|
||||
return `<div class="footer"><span>工学云 · 学生档案报告</span><span>机密 · 仅限内部使用</span></div>`;
|
||||
return `<div class="footer"><span>恭学教育 · 学生档案报告</span><span>机密 · 仅限内部使用</span></div>`;
|
||||
}
|
||||
|
||||
private buildHtml(data: ReportData): string {
|
||||
@@ -281,7 +281,7 @@ ${this.buildLearningAndResult(learnings, result, now)}
|
||||
<div class="toc-row"><span class="toc-index">04</span><span class="toc-name">文化课考试成绩</span><span class="toc-page">第 5 页</span></div>
|
||||
<div class="toc-row"><span class="toc-index">05</span><span class="toc-name">学情记录与录取归档</span><span class="toc-page">第 6 页</span></div>
|
||||
</div>
|
||||
<div class="watermark">工学云</div>
|
||||
<div class="watermark">恭学教育</div>
|
||||
${this.pageFooter()}
|
||||
`);
|
||||
}
|
||||
|
||||
102
apps/server/src/archive/archive.boundaries.spec.ts
Normal file
102
apps/server/src/archive/archive.boundaries.spec.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { ArchiveService } from './archive.service';
|
||||
|
||||
function createService(repos: Partial<Record<string, Record<string, jest.Mock>>> = {}) {
|
||||
return new ArchiveService(
|
||||
(repos.student ?? {}) as never,
|
||||
(repos.profile ?? {}) as never,
|
||||
(repos.enrollment ?? {}) as never,
|
||||
(repos.exam ?? {}) as never,
|
||||
(repos.learning ?? {}) as never,
|
||||
(repos.result ?? {}) as never,
|
||||
(repos.attachment ?? {}) as never,
|
||||
(repos.attendance ?? {}) as never,
|
||||
{} as never,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ArchiveService — resource and relationship boundaries', () => {
|
||||
it('rejects adding archive records for a missing student', async () => {
|
||||
const student = { findOne: jest.fn().mockResolvedValue(null) };
|
||||
const service = createService({ student });
|
||||
|
||||
await expect(
|
||||
service.addEnrollment(404, { courseCategory: '文化', classType: '冲刺' }),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(
|
||||
service.addLearningRecord(404, {
|
||||
recordDate: '2026-07-14',
|
||||
recordType: '沟通',
|
||||
content: '内容',
|
||||
}),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
|
||||
it('rejects linking an exam score to another student enrollment', async () => {
|
||||
const exam = { create: jest.fn(), save: jest.fn() };
|
||||
const service = createService({
|
||||
student: { findOne: jest.fn().mockResolvedValue({ id: 7 }) },
|
||||
enrollment: { findOne: jest.fn().mockResolvedValue(null) },
|
||||
exam,
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.addExamScore(7, {
|
||||
examType: '月考',
|
||||
subject: '语文',
|
||||
score: 90,
|
||||
enrollmentId: 99,
|
||||
}),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(exam.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects moving an existing exam score to another student enrollment', async () => {
|
||||
const exam = {
|
||||
findOne: jest.fn().mockResolvedValue({ id: 3, studentId: 7, enrollmentId: 1 }),
|
||||
save: jest.fn(),
|
||||
};
|
||||
const service = createService({
|
||||
enrollment: { findOne: jest.fn().mockResolvedValue(null) },
|
||||
exam,
|
||||
});
|
||||
|
||||
await expect(service.updateExamScore(3, { enrollmentId: 99 })).rejects.toBeInstanceOf(
|
||||
BadRequestException,
|
||||
);
|
||||
expect(exam.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a missing attachment upload before writing to disk', async () => {
|
||||
const service = createService({ student: { findOne: jest.fn() } });
|
||||
await expect(service.addAttachment(7, undefined as never, 'other')).rejects.toBeInstanceOf(
|
||||
BadRequestException,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects attachment path traversal', async () => {
|
||||
const service = createService({
|
||||
attachment: {
|
||||
findOne: jest.fn().mockResolvedValue({
|
||||
id: 1,
|
||||
studentId: 7,
|
||||
filePath: '../../etc/passwd',
|
||||
}),
|
||||
},
|
||||
});
|
||||
await expect(service.getAttachmentFile(7, 1)).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('returns not found for update/delete of absent child records', async () => {
|
||||
const service = createService({
|
||||
enrollment: { findOne: jest.fn().mockResolvedValue(null) },
|
||||
exam: { findOne: jest.fn().mockResolvedValue(null) },
|
||||
learning: { findOne: jest.fn().mockResolvedValue(null) },
|
||||
attachment: { findOne: jest.fn().mockResolvedValue(null) },
|
||||
});
|
||||
await expect(service.updateEnrollment(1, {})).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(service.deleteExamScore(1)).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(service.deleteLearningRecord(1)).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(service.deleteAttachment(1)).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
UseInterceptors,
|
||||
UploadedFile,
|
||||
Res,
|
||||
ParseIntPipe,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import type { Request as ExpressRequest, Response } from 'express';
|
||||
@@ -47,15 +48,15 @@ export class ArchiveController {
|
||||
|
||||
@Get(':studentId')
|
||||
@RequirePermission('student:view')
|
||||
async getProfile(@Param('studentId') studentId: string, @Request() req: AuthenticatedRequest) {
|
||||
async getProfile(@Param('studentId', ParseIntPipe) studentId: number, @Request() req: AuthenticatedRequest) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.getProfile(+studentId);
|
||||
const result = await this.archiveService.getProfile(studentId);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '查看档案',
|
||||
targetId: +studentId,
|
||||
targetId: studentId,
|
||||
targetType: 'archive',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -66,18 +67,18 @@ export class ArchiveController {
|
||||
@Put(':studentId/profile')
|
||||
@RequirePermission('student:edit')
|
||||
async upsertProfile(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@Body() dto: UpsertProfileDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.upsertProfile(+studentId, dto);
|
||||
const result = await this.archiveService.upsertProfile(studentId, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '更新档案信息',
|
||||
targetId: +studentId,
|
||||
targetId: studentId,
|
||||
targetType: 'student_profile',
|
||||
detail: JSON.stringify(dto),
|
||||
ipAddress,
|
||||
@@ -89,12 +90,12 @@ export class ArchiveController {
|
||||
@Post(':studentId/enrollments')
|
||||
@RequirePermission('student:edit')
|
||||
async addEnrollment(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@Body() dto: CreateEnrollmentDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.addEnrollment(+studentId, dto);
|
||||
const result = await this.archiveService.addEnrollment(studentId, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
@@ -112,18 +113,18 @@ export class ArchiveController {
|
||||
@Put('enrollments/:id')
|
||||
@RequirePermission('student:edit')
|
||||
async updateEnrollment(
|
||||
@Param('id') id: string,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: UpdateEnrollmentDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.updateEnrollment(+id, dto);
|
||||
const result = await this.archiveService.updateEnrollment(id, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '编辑报名记录',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'student_enrollment',
|
||||
detail: JSON.stringify(dto),
|
||||
ipAddress,
|
||||
@@ -134,15 +135,15 @@ export class ArchiveController {
|
||||
|
||||
@Delete('enrollments/:id')
|
||||
@RequirePermission('student:edit')
|
||||
async deleteEnrollment(@Param('id') id: string, @Request() req: AuthenticatedRequest) {
|
||||
async deleteEnrollment(@Param('id', ParseIntPipe) id: number, @Request() req: AuthenticatedRequest) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.deleteEnrollment(+id);
|
||||
const result = await this.archiveService.deleteEnrollment(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '删除报名记录',
|
||||
targetId: +id,
|
||||
action: '归档报名记录',
|
||||
targetId: id,
|
||||
targetType: 'student_enrollment',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -153,12 +154,12 @@ export class ArchiveController {
|
||||
@Post(':studentId/exam-scores')
|
||||
@RequirePermission('student:edit')
|
||||
async addExamScore(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@Body() dto: CreateExamScoreDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.addExamScore(+studentId, dto);
|
||||
const result = await this.archiveService.addExamScore(studentId, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
@@ -176,18 +177,18 @@ export class ArchiveController {
|
||||
@Put('exam-scores/:id')
|
||||
@RequirePermission('student:edit')
|
||||
async updateExamScore(
|
||||
@Param('id') id: string,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: UpdateExamScoreDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.updateExamScore(+id, dto);
|
||||
const result = await this.archiveService.updateExamScore(id, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '编辑考试成绩',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'exam_score',
|
||||
detail: JSON.stringify(dto),
|
||||
ipAddress,
|
||||
@@ -198,15 +199,15 @@ export class ArchiveController {
|
||||
|
||||
@Delete('exam-scores/:id')
|
||||
@RequirePermission('student:edit')
|
||||
async deleteExamScore(@Param('id') id: string, @Request() req: AuthenticatedRequest) {
|
||||
async deleteExamScore(@Param('id', ParseIntPipe) id: number, @Request() req: AuthenticatedRequest) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.deleteExamScore(+id);
|
||||
const result = await this.archiveService.deleteExamScore(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '删除考试成绩',
|
||||
targetId: +id,
|
||||
action: '归档考试成绩',
|
||||
targetId: id,
|
||||
targetType: 'exam_score',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -217,12 +218,12 @@ export class ArchiveController {
|
||||
@Post(':studentId/learning-records')
|
||||
@RequirePermission('student:edit')
|
||||
async addLearningRecord(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@Body() dto: CreateLearningRecordDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.addLearningRecord(+studentId, dto);
|
||||
const result = await this.archiveService.addLearningRecord(studentId, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
@@ -240,18 +241,18 @@ export class ArchiveController {
|
||||
@Put('learning-records/:id')
|
||||
@RequirePermission('student:edit')
|
||||
async updateLearningRecord(
|
||||
@Param('id') id: string,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: UpdateLearningRecordDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.updateLearningRecord(+id, dto);
|
||||
const result = await this.archiveService.updateLearningRecord(id, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '编辑学习记录',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'learning_record',
|
||||
detail: JSON.stringify(dto),
|
||||
ipAddress,
|
||||
@@ -262,15 +263,15 @@ export class ArchiveController {
|
||||
|
||||
@Delete('learning-records/:id')
|
||||
@RequirePermission('student:edit')
|
||||
async deleteLearningRecord(@Param('id') id: string, @Request() req: AuthenticatedRequest) {
|
||||
async deleteLearningRecord(@Param('id', ParseIntPipe) id: number, @Request() req: AuthenticatedRequest) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.deleteLearningRecord(+id);
|
||||
const result = await this.archiveService.deleteLearningRecord(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '删除学习记录',
|
||||
targetId: +id,
|
||||
action: '归档学习记录',
|
||||
targetId: id,
|
||||
targetType: 'learning_record',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -281,18 +282,18 @@ export class ArchiveController {
|
||||
@Put(':studentId/result')
|
||||
@RequirePermission('student:edit')
|
||||
async upsertResult(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@Body() dto: UpsertResultDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.upsertResult(+studentId, dto);
|
||||
const result = await this.archiveService.upsertResult(studentId, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '更新录取结果',
|
||||
targetId: +studentId,
|
||||
targetId: studentId,
|
||||
targetType: 'result_archive',
|
||||
detail: JSON.stringify(dto),
|
||||
ipAddress,
|
||||
@@ -305,13 +306,13 @@ export class ArchiveController {
|
||||
@RequirePermission('student:edit')
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
async uploadAttachment(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@UploadedFile() file: Express.Multer.File,
|
||||
@Body('category') category: string,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.addAttachment(+studentId, file, category || 'other');
|
||||
const result = await this.archiveService.addAttachment(studentId, file, category || 'other');
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
@@ -329,13 +330,13 @@ export class ArchiveController {
|
||||
@Get(':studentId/attachments/:id')
|
||||
@RequirePermission('student:view')
|
||||
async downloadAttachment(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('id') id: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Res() res: Response,
|
||||
) {
|
||||
const { fullPath, fileName, mimeType } = await this.archiveService.getAttachmentFile(
|
||||
+studentId,
|
||||
+id,
|
||||
studentId,
|
||||
id,
|
||||
);
|
||||
res.setHeader('Content-Type', mimeType);
|
||||
res.setHeader('Content-Disposition', `inline; filename="${encodeURIComponent(fileName)}"`);
|
||||
@@ -345,15 +346,15 @@ export class ArchiveController {
|
||||
|
||||
@Delete('attachments/:id')
|
||||
@RequirePermission('student:edit')
|
||||
async deleteAttachment(@Param('id') id: string, @Request() req: AuthenticatedRequest) {
|
||||
async deleteAttachment(@Param('id', ParseIntPipe) id: number, @Request() req: AuthenticatedRequest) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.deleteAttachment(+id);
|
||||
const result = await this.archiveService.deleteAttachment(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '删除附件',
|
||||
targetId: +id,
|
||||
action: '归档附件',
|
||||
targetId: id,
|
||||
targetType: 'archive_attachment',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -364,7 +365,7 @@ export class ArchiveController {
|
||||
@Get(':studentId/report-html')
|
||||
@RequirePermission('student:view')
|
||||
async generateReportHtml(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
@@ -373,12 +374,12 @@ export class ArchiveController {
|
||||
username: req.user?.username,
|
||||
module: 'archive',
|
||||
action: 'generate_report_html',
|
||||
targetId: +studentId,
|
||||
targetId: studentId,
|
||||
targetType: 'student',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
const html = await this.reportService.generateReportHtml(+studentId);
|
||||
const html = await this.reportService.generateReportHtml(studentId);
|
||||
return { html };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ describe('ArchiveService.getProfile', () => {
|
||||
const learningRecordRepo = { find: jest.fn().mockResolvedValue([]) };
|
||||
const resultRepo = { findOne: jest.fn().mockResolvedValue(result) };
|
||||
const attachmentRepo = { find: jest.fn().mockResolvedValue([]) };
|
||||
const attendanceRepo = { find: jest.fn().mockResolvedValue([]) };
|
||||
|
||||
const service = new ArchiveService(
|
||||
studentRepo as never,
|
||||
@@ -26,12 +27,13 @@ describe('ArchiveService.getProfile', () => {
|
||||
learningRecordRepo as never,
|
||||
resultRepo as never,
|
||||
attachmentRepo as never,
|
||||
attendanceRepo as never,
|
||||
{} as never,
|
||||
);
|
||||
|
||||
const response = await service.getProfile(7);
|
||||
|
||||
expect(response).toMatchObject({ student, result });
|
||||
expect(response).toMatchObject({ student, result, attendances: [] });
|
||||
expect(response).not.toHaveProperty('resultArchive');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@ import { ExamScore } from '../entities/exam-score.entity';
|
||||
import { LearningRecord } from '../entities/learning-record.entity';
|
||||
import { ResultArchive } from '../entities/result-archive.entity';
|
||||
import { ArchiveAttachment } from '../entities/archive-attachment.entity';
|
||||
import { AttendanceRecord } from '../entities/attendance-record.entity';
|
||||
import {
|
||||
UpsertProfileDto,
|
||||
CreateEnrollmentDto,
|
||||
@@ -33,6 +34,7 @@ export class ArchiveService {
|
||||
@InjectRepository(LearningRecord) private learningRecordRepo: Repository<LearningRecord>,
|
||||
@InjectRepository(ResultArchive) private resultRepo: Repository<ResultArchive>,
|
||||
@InjectRepository(ArchiveAttachment) private attachmentRepo: Repository<ArchiveAttachment>,
|
||||
@InjectRepository(AttendanceRecord) private attendanceRepo: Repository<AttendanceRecord>,
|
||||
private readonly notificationsService: NotificationsService,
|
||||
) {}
|
||||
|
||||
@@ -59,15 +61,27 @@ export class ArchiveService {
|
||||
const student = await this.studentRepo.findOne({ where: { id: studentId } });
|
||||
if (!student) throw new NotFoundException('学生不存在');
|
||||
|
||||
const [profileRaw, enrollments, examScores, learningRecords, resultArchive, attachments] =
|
||||
await Promise.all([
|
||||
this.profileRepo.findOne({ where: { studentId } }),
|
||||
this.enrollmentRepo.find({ where: { studentId }, order: { createdAt: 'DESC' } }),
|
||||
this.examScoreRepo.find({ where: { studentId }, order: { examDate: 'DESC' } }),
|
||||
this.learningRecordRepo.find({ where: { studentId }, order: { recordDate: 'DESC' } }),
|
||||
this.resultRepo.findOne({ where: { studentId } }),
|
||||
this.attachmentRepo.find({ where: { studentId }, order: { createdAt: 'DESC' } }),
|
||||
]);
|
||||
const [
|
||||
profileRaw,
|
||||
enrollments,
|
||||
examScores,
|
||||
learningRecords,
|
||||
resultArchive,
|
||||
attachments,
|
||||
attendances,
|
||||
] = await Promise.all([
|
||||
this.profileRepo.findOne({ where: { studentId } }),
|
||||
this.enrollmentRepo.find({ where: { studentId, status: 'active' }, order: { createdAt: 'DESC' } }),
|
||||
this.examScoreRepo.find({ where: { studentId, status: 'active' }, order: { examDate: 'DESC' } }),
|
||||
this.learningRecordRepo.find({ where: { studentId, status: 'active' }, order: { recordDate: 'DESC' } }),
|
||||
this.resultRepo.findOne({ where: { studentId } }),
|
||||
this.attachmentRepo.find({ where: { studentId, status: 'active' }, order: { createdAt: 'DESC' } }),
|
||||
this.attendanceRepo.find({
|
||||
where: { studentId },
|
||||
relations: ['schedule', 'class'],
|
||||
order: { attendanceDate: 'DESC', punchTime: 'DESC' },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
student,
|
||||
@@ -77,6 +91,7 @@ export class ArchiveService {
|
||||
learningRecords,
|
||||
result: resultArchive,
|
||||
attachments,
|
||||
attendances,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -111,13 +126,23 @@ export class ArchiveService {
|
||||
async deleteEnrollment(id: number) {
|
||||
const entity = await this.enrollmentRepo.findOne({ where: { id } });
|
||||
if (!entity) throw new NotFoundException('报名记录不存在');
|
||||
await this.enrollmentRepo.remove(entity);
|
||||
return { message: '已删除' };
|
||||
if (entity.status === 'archived') throw new BadRequestException('报名记录已归档');
|
||||
await this.enrollmentRepo.update(id, { status: 'archived' });
|
||||
return { message: '已归档' };
|
||||
}
|
||||
|
||||
private async assertEnrollmentBelongsToStudent(studentId: number, enrollmentId?: number) {
|
||||
if (enrollmentId === undefined) return;
|
||||
const enrollment = await this.enrollmentRepo.findOne({
|
||||
where: { id: enrollmentId, studentId },
|
||||
});
|
||||
if (!enrollment) throw new BadRequestException('报名记录不属于该学生');
|
||||
}
|
||||
|
||||
async addExamScore(studentId: number, dto: CreateExamScoreDto) {
|
||||
const student = await this.studentRepo.findOne({ where: { id: studentId } });
|
||||
if (!student) throw new NotFoundException('学生不存在');
|
||||
await this.assertEnrollmentBelongsToStudent(studentId, dto.enrollmentId);
|
||||
|
||||
const entity = this.examScoreRepo.create({ ...dto, studentId });
|
||||
return this.examScoreRepo.save(entity);
|
||||
@@ -126,6 +151,7 @@ export class ArchiveService {
|
||||
async updateExamScore(id: number, dto: UpdateExamScoreDto) {
|
||||
const entity = await this.examScoreRepo.findOne({ where: { id } });
|
||||
if (!entity) throw new NotFoundException('考试成绩不存在');
|
||||
await this.assertEnrollmentBelongsToStudent(entity.studentId, dto.enrollmentId);
|
||||
Object.assign(entity, dto);
|
||||
return this.examScoreRepo.save(entity);
|
||||
}
|
||||
@@ -133,8 +159,9 @@ export class ArchiveService {
|
||||
async deleteExamScore(id: number) {
|
||||
const entity = await this.examScoreRepo.findOne({ where: { id } });
|
||||
if (!entity) throw new NotFoundException('考试成绩不存在');
|
||||
await this.examScoreRepo.remove(entity);
|
||||
return { message: '已删除' };
|
||||
if (entity.status === 'archived') throw new BadRequestException('考试成绩已归档');
|
||||
await this.examScoreRepo.update(id, { status: 'archived' });
|
||||
return { message: '已归档' };
|
||||
}
|
||||
|
||||
async addLearningRecord(studentId: number, dto: CreateLearningRecordDto) {
|
||||
@@ -155,8 +182,9 @@ export class ArchiveService {
|
||||
async deleteLearningRecord(id: number) {
|
||||
const entity = await this.learningRecordRepo.findOne({ where: { id } });
|
||||
if (!entity) throw new NotFoundException('学习记录不存在');
|
||||
await this.learningRecordRepo.remove(entity);
|
||||
return { message: '已删除' };
|
||||
if (entity.status === 'archived') throw new BadRequestException('学习记录已归档');
|
||||
await this.learningRecordRepo.update(id, { status: 'archived' });
|
||||
return { message: '已归档' };
|
||||
}
|
||||
|
||||
async upsertResult(studentId: number, dto: UpsertResultDto) {
|
||||
@@ -173,6 +201,8 @@ export class ArchiveService {
|
||||
}
|
||||
|
||||
async addAttachment(studentId: number, file: Express.Multer.File, category: string) {
|
||||
if (!file?.buffer || !file.originalname) throw new BadRequestException('请选择附件文件');
|
||||
|
||||
const student = await this.studentRepo.findOne({ where: { id: studentId } });
|
||||
if (!student) throw new NotFoundException('学生不存在');
|
||||
|
||||
@@ -214,13 +244,8 @@ export class ArchiveService {
|
||||
async deleteAttachment(id: number) {
|
||||
const entity = await this.attachmentRepo.findOne({ where: { id } });
|
||||
if (!entity) throw new NotFoundException('附件不存在');
|
||||
|
||||
const absPath = this.resolveAttachmentPath(entity.filePath);
|
||||
if (fs.existsSync(absPath)) {
|
||||
fs.unlinkSync(absPath);
|
||||
}
|
||||
|
||||
await this.attachmentRepo.remove(entity);
|
||||
return { message: '已删除' };
|
||||
if (entity.status === 'archived') throw new BadRequestException('附件已归档');
|
||||
await this.attachmentRepo.update(id, { status: 'archived' });
|
||||
return { message: '已归档' };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { IsOptional, IsString, IsNumber, IsDateString } from 'class-validator';
|
||||
import { IsOptional, IsString, IsNumber, IsDateString, IsNotEmpty, Min } from 'class-validator';
|
||||
|
||||
export class UpsertProfileDto {
|
||||
@IsOptional() @IsString() targetCollege?: string;
|
||||
@@ -11,8 +11,8 @@ export class UpsertProfileDto {
|
||||
}
|
||||
|
||||
export class CreateEnrollmentDto {
|
||||
@IsString() courseCategory: string;
|
||||
@IsString() classType: string;
|
||||
@IsString() @IsNotEmpty() courseCategory: string;
|
||||
@IsString() @IsNotEmpty() classType: string;
|
||||
@IsOptional() @IsString() className?: string;
|
||||
@IsOptional() @IsString() headTeacher?: string;
|
||||
@IsOptional() @IsString() subjectTeacher?: string;
|
||||
@@ -24,12 +24,12 @@ export class CreateEnrollmentDto {
|
||||
export class UpdateEnrollmentDto extends PartialType(CreateEnrollmentDto) {}
|
||||
|
||||
export class CreateExamScoreDto {
|
||||
@IsString() examType: string;
|
||||
@IsString() @IsNotEmpty() examType: string;
|
||||
@IsOptional() @IsString() examName?: string;
|
||||
@IsString() subject: string;
|
||||
@IsNumber() score: number;
|
||||
@IsOptional() @IsNumber() classAvg?: number;
|
||||
@IsOptional() @IsNumber() rank?: number;
|
||||
@IsString() @IsNotEmpty() subject: string;
|
||||
@IsNumber() @Min(0) score: number;
|
||||
@IsOptional() @IsNumber() @Min(0) classAvg?: number;
|
||||
@IsOptional() @IsNumber() @Min(1) rank?: number;
|
||||
@IsOptional() @IsDateString() examDate?: string;
|
||||
@IsOptional() @IsNumber() enrollmentId?: number;
|
||||
}
|
||||
@@ -38,8 +38,8 @@ export class UpdateExamScoreDto extends PartialType(CreateExamScoreDto) {}
|
||||
|
||||
export class CreateLearningRecordDto {
|
||||
@IsDateString() recordDate: string;
|
||||
@IsString() recordType: string;
|
||||
@IsString() content: string;
|
||||
@IsString() @IsNotEmpty() recordType: string;
|
||||
@IsString() @IsNotEmpty() content: string;
|
||||
@IsOptional() @IsString() followUpMethod?: string;
|
||||
@IsOptional() @IsString() nextStep?: string;
|
||||
}
|
||||
@@ -47,8 +47,8 @@ export class CreateLearningRecordDto {
|
||||
export class UpdateLearningRecordDto extends PartialType(CreateLearningRecordDto) {}
|
||||
|
||||
export class UpsertResultDto {
|
||||
@IsOptional() @IsNumber() cultureFinalScore?: number;
|
||||
@IsOptional() @IsNumber() professionalFinalScore?: number;
|
||||
@IsOptional() @IsNumber() @Min(0) cultureFinalScore?: number;
|
||||
@IsOptional() @IsNumber() @Min(0) professionalFinalScore?: number;
|
||||
@IsOptional() @IsString() admissionStatus?: string;
|
||||
@IsOptional() @IsString() admittedCollege?: string;
|
||||
@IsOptional() @IsString() admittedMajor?: string;
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put, Query, Request, UseGuards } from '@nestjs/common';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RequirePermission } from '../auth/decorators/permission.decorator';
|
||||
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
||||
import { extractRequestInfo } from '../common/request-utils';
|
||||
import { AttendanceDevicesService } from './attendance-devices.service';
|
||||
import { CreateAttendanceDeviceDto, UpdateAttendanceDeviceDto } from './dto/attendance-device.dto';
|
||||
import { AttendanceDeviceStatus } from '../entities';
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('attendance-devices')
|
||||
export class AttendanceDevicesController {
|
||||
constructor(
|
||||
private readonly service: AttendanceDevicesService,
|
||||
private readonly logService: OperationLogsService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@RequirePermission('classroom:view')
|
||||
findAll(
|
||||
@Query('classroomId') classroomId?: string,
|
||||
@Query('status') status?: AttendanceDeviceStatus | 'active' | 'disabled',
|
||||
) {
|
||||
return this.service.findAll({
|
||||
classroomId: classroomId ? Number(classroomId) : undefined,
|
||||
status,
|
||||
});
|
||||
}
|
||||
|
||||
@Post()
|
||||
@RequirePermission('classroom:edit')
|
||||
async create(@Body() dto: CreateAttendanceDeviceDto, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.create(dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '考勤机',
|
||||
action: '新增考勤机绑定',
|
||||
targetId: result.id,
|
||||
targetType: 'attendanceDevice',
|
||||
detail: `${result.deviceSn} -> ${result.classroom?.name || result.classroomId}`,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
@RequirePermission('classroom:edit')
|
||||
async update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateAttendanceDeviceDto, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.update(id, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '考勤机',
|
||||
action: '编辑考勤机绑定',
|
||||
targetId: id,
|
||||
targetType: 'attendanceDevice',
|
||||
detail: JSON.stringify(dto),
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@RequirePermission('classroom:edit')
|
||||
async remove(@Param('id', ParseIntPipe) id: number, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.remove(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '考勤机',
|
||||
action: '停用考勤机绑定',
|
||||
targetId: id,
|
||||
targetType: 'attendanceDevice',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AttendanceDevice, Classroom } from '../entities';
|
||||
import { OperationLogsModule } from '../operation-logs/operation-logs.module';
|
||||
import { AttendanceDevicesController } from './attendance-devices.controller';
|
||||
import { AttendanceDevicesService } from './attendance-devices.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([AttendanceDevice, Classroom]), OperationLogsModule],
|
||||
controllers: [AttendanceDevicesController],
|
||||
providers: [AttendanceDevicesService],
|
||||
exports: [AttendanceDevicesService],
|
||||
})
|
||||
export class AttendanceDevicesModule {}
|
||||
108
apps/server/src/attendance-devices/attendance-devices.service.ts
Normal file
108
apps/server/src/attendance-devices/attendance-devices.service.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { In, Repository } from 'typeorm';
|
||||
import { AttendanceDevice, AttendanceDeviceStatus, Classroom } from '../entities';
|
||||
import { CreateAttendanceDeviceDto, UpdateAttendanceDeviceDto } from './dto/attendance-device.dto';
|
||||
|
||||
@Injectable()
|
||||
export class AttendanceDevicesService {
|
||||
constructor(
|
||||
@InjectRepository(AttendanceDevice)
|
||||
private readonly repo: Repository<AttendanceDevice>,
|
||||
@InjectRepository(Classroom)
|
||||
private readonly classroomRepo: Repository<Classroom>,
|
||||
) {}
|
||||
|
||||
private normalizeSn(sn: string): string {
|
||||
return sn.trim();
|
||||
}
|
||||
|
||||
private async assertClassroomExists(classroomId: number): Promise<void> {
|
||||
const exists = await this.classroomRepo.exist({ where: { id: classroomId } });
|
||||
if (!exists) throw new BadRequestException('绑定教室不存在');
|
||||
}
|
||||
|
||||
async findAll(query?: { classroomId?: number; status?: AttendanceDeviceStatus | 'active' | 'disabled' }) {
|
||||
const where: Record<string, unknown> = {};
|
||||
if (query?.classroomId) where.classroomId = query.classroomId;
|
||||
if (query?.status) where.status = query.status;
|
||||
return this.repo.find({
|
||||
where,
|
||||
relations: ['classroom'],
|
||||
order: { classroomId: 'ASC', deviceName: 'ASC' },
|
||||
});
|
||||
}
|
||||
|
||||
async findOne(id: number) {
|
||||
const device = await this.repo.findOne({ where: { id }, relations: ['classroom'] });
|
||||
if (!device) throw new NotFoundException('考勤机不存在');
|
||||
return device;
|
||||
}
|
||||
|
||||
async create(dto: CreateAttendanceDeviceDto) {
|
||||
const deviceSn = this.normalizeSn(dto.deviceSn);
|
||||
await this.assertClassroomExists(dto.classroomId);
|
||||
const exists = await this.repo.findOne({ where: { deviceSn } });
|
||||
if (exists) throw new BadRequestException(`SN ${deviceSn} 已绑定教室`);
|
||||
const saved = await this.repo.save(
|
||||
this.repo.create({
|
||||
...dto,
|
||||
deviceSn,
|
||||
deviceName: dto.deviceName.trim(),
|
||||
status: dto.status ?? AttendanceDeviceStatus.ACTIVE,
|
||||
}),
|
||||
);
|
||||
return this.findOne(saved.id);
|
||||
}
|
||||
|
||||
async update(id: number, dto: UpdateAttendanceDeviceDto) {
|
||||
const device = await this.repo.findOne({ where: { id } });
|
||||
if (!device) throw new NotFoundException('考勤机不存在');
|
||||
const patch: Partial<AttendanceDevice> = { ...dto };
|
||||
if (dto.classroomId != null) await this.assertClassroomExists(dto.classroomId);
|
||||
if (dto.deviceSn != null) {
|
||||
const deviceSn = this.normalizeSn(dto.deviceSn);
|
||||
const exists = await this.repo.findOne({ where: { deviceSn } });
|
||||
if (exists && exists.id !== id) throw new BadRequestException(`SN ${deviceSn} 已绑定教室`);
|
||||
patch.deviceSn = deviceSn;
|
||||
}
|
||||
if (dto.deviceName != null) patch.deviceName = dto.deviceName.trim();
|
||||
await this.repo.update(id, patch);
|
||||
return this.findOne(id);
|
||||
}
|
||||
|
||||
async remove(id: number) {
|
||||
const device = await this.repo.findOne({ where: { id } });
|
||||
if (!device) throw new NotFoundException('考勤机不存在');
|
||||
if (device.status === AttendanceDeviceStatus.DISABLED) {
|
||||
throw new BadRequestException('考勤机已停用');
|
||||
}
|
||||
await this.repo.update(id, { status: AttendanceDeviceStatus.DISABLED });
|
||||
return { message: '已停用(绑定数据已保留)' };
|
||||
}
|
||||
|
||||
async findActiveBySn(deviceSns: string[]) {
|
||||
const sns = [...new Set(deviceSns.map((sn) => this.normalizeSn(sn)).filter(Boolean))];
|
||||
if (sns.length === 0) return new Map<string, AttendanceDevice>();
|
||||
const devices = await this.repo.find({
|
||||
where: { deviceSn: In(sns), status: AttendanceDeviceStatus.ACTIVE },
|
||||
relations: ['classroom'],
|
||||
});
|
||||
return new Map(devices.map((device) => [device.deviceSn, device]));
|
||||
}
|
||||
|
||||
async findActiveByClassroomIds(classroomIds: number[]) {
|
||||
const ids = [...new Set(classroomIds.filter((id) => Number.isFinite(id)))];
|
||||
if (ids.length === 0) return new Map<number, AttendanceDevice>();
|
||||
const devices = await this.repo.find({
|
||||
where: { classroomId: In(ids), status: AttendanceDeviceStatus.ACTIVE },
|
||||
relations: ['classroom'],
|
||||
order: { id: 'ASC' },
|
||||
});
|
||||
const result = new Map<number, AttendanceDevice>();
|
||||
for (const device of devices) {
|
||||
if (!result.has(device.classroomId)) result.set(device.classroomId, device);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { IsEnum, IsInt, IsNotEmpty, IsOptional, IsString, MaxLength } from 'class-validator';
|
||||
import { AttendanceDeviceStatus } from '../../entities/attendance-device.entity';
|
||||
|
||||
export class CreateAttendanceDeviceDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(100)
|
||||
deviceSn: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(100)
|
||||
deviceName: string;
|
||||
|
||||
@IsInt()
|
||||
classroomId: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(AttendanceDeviceStatus)
|
||||
status?: AttendanceDeviceStatus;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
location?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export class UpdateAttendanceDeviceDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(100)
|
||||
deviceSn?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(100)
|
||||
deviceName?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
classroomId?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(AttendanceDeviceStatus)
|
||||
status?: AttendanceDeviceStatus;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
location?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
}
|
||||
@@ -93,6 +93,31 @@ describe('AttendanceImportService', () => {
|
||||
expect(entity.userName).toBe('张三');
|
||||
});
|
||||
|
||||
it('stores DingTalk punch source and attendance machine metadata', async () => {
|
||||
const entity = await (service as any).mapToEntity({
|
||||
userId: 'ding-1',
|
||||
userName: '张三',
|
||||
workDate: '2026-07-01',
|
||||
timeResult: 'Normal',
|
||||
locationResult: '',
|
||||
planCheckTime: '',
|
||||
actualCheckTime: '2026-07-01T08:00:00.000Z',
|
||||
checkId: 'check-1',
|
||||
checkType: 'OnDuty',
|
||||
sourceType: 'ATM',
|
||||
deviceName: '东门考勤机',
|
||||
deviceId: 'ATM-01',
|
||||
});
|
||||
|
||||
expect(entity).toEqual(
|
||||
expect.objectContaining({
|
||||
punchSource: 'ATM',
|
||||
punchDeviceName: '东门考勤机',
|
||||
punchDeviceId: 'ATM-01',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('fills the student name from the DingTalk mapping when saving an imported record', async () => {
|
||||
dingTalkService.fetchAttendanceResults.mockResolvedValue([
|
||||
{
|
||||
@@ -138,9 +163,19 @@ describe('AttendanceImportService', () => {
|
||||
actualCheckTime: '2026-07-01T08:00:00.000Z',
|
||||
checkId: 'check-1',
|
||||
checkType: 'OnDuty',
|
||||
sourceType: 'ATM',
|
||||
deviceName: '东门考勤机',
|
||||
deviceId: 'ATM-01',
|
||||
},
|
||||
]);
|
||||
dingRawRepo.find.mockResolvedValue([{ dingId: 'check-1' }]);
|
||||
dingRawRepo.find.mockResolvedValue([{
|
||||
dingId: 'check-1',
|
||||
punchSource: null,
|
||||
punchDeviceName: null,
|
||||
punchDeviceId: null,
|
||||
rawData: '',
|
||||
}]);
|
||||
dingRawRepo.save.mockImplementation(async (entities) => entities);
|
||||
attendanceService.autoMatchDingRecords.mockResolvedValue({ matched: 1, total: 1 });
|
||||
|
||||
const result = await service.importFromDingTalk({
|
||||
@@ -150,10 +185,57 @@ describe('AttendanceImportService', () => {
|
||||
autoMatch: true,
|
||||
});
|
||||
|
||||
expect(dingRawRepo.save).toHaveBeenCalledWith(
|
||||
[expect.objectContaining({
|
||||
dingId: 'check-1',
|
||||
punchSource: 'ATM',
|
||||
punchDeviceName: '东门考勤机',
|
||||
punchDeviceId: 'ATM-01',
|
||||
})],
|
||||
{ chunk: 50 },
|
||||
);
|
||||
expect(attendanceService.autoMatchDingRecords).toHaveBeenCalled();
|
||||
expect(result.matched).toBe(1);
|
||||
});
|
||||
|
||||
it('preserves existing device metadata when a duplicate response omits it', async () => {
|
||||
const existing = {
|
||||
dingId: 'check-keep-device',
|
||||
punchSource: 'ATM',
|
||||
punchDeviceName: '东门考勤机',
|
||||
punchDeviceId: 'ATM-01',
|
||||
rawData: '{}',
|
||||
};
|
||||
dingTalkService.fetchAttendanceResults.mockResolvedValue([{
|
||||
userId: 'ding-1',
|
||||
userName: '张三',
|
||||
workDate: '2026-07-01',
|
||||
timeResult: 'Normal',
|
||||
locationResult: '',
|
||||
planCheckTime: '',
|
||||
actualCheckTime: '2026-07-01T08:00:00.000Z',
|
||||
checkId: 'check-keep-device',
|
||||
checkType: 'OnDuty',
|
||||
sourceType: '',
|
||||
}]);
|
||||
dingRawRepo.find.mockResolvedValue([existing]);
|
||||
attendanceService.autoMatchDingRecords.mockResolvedValue({ matched: 0, total: 1 });
|
||||
|
||||
await service.importFromDingTalk({
|
||||
startDate: '2026-07-01',
|
||||
endDate: '2026-07-01',
|
||||
userIds: ['ding-1'],
|
||||
autoMatch: true,
|
||||
});
|
||||
|
||||
expect(existing).toEqual(expect.objectContaining({
|
||||
punchSource: 'ATM',
|
||||
punchDeviceName: '东门考勤机',
|
||||
punchDeviceId: 'ATM-01',
|
||||
}));
|
||||
expect(dingRawRepo.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('scopes SSE progress events to the importing user', async () => {
|
||||
dingTalkService.fetchAttendanceResults.mockResolvedValue([
|
||||
{
|
||||
|
||||
@@ -104,8 +104,10 @@ export class AttendanceImportService {
|
||||
|
||||
// Stage 2: Parse & deduplicate
|
||||
this.emit('parsing', 0, total, `Parsing ${total} records...`);
|
||||
const existingDingIds = await this.getExistingDingIds(rawResults);
|
||||
const newRecords = rawResults.filter((r) => !existingDingIds.has(r.checkId));
|
||||
const existingByDingId = await this.getExistingRecordsByDingId(rawResults);
|
||||
const newRecords = rawResults.filter((r) => !existingByDingId.has(r.checkId));
|
||||
const duplicateRecords = rawResults.filter((r) => existingByDingId.has(r.checkId));
|
||||
await this.refreshDuplicatePunchMetadata(duplicateRecords, existingByDingId);
|
||||
skipped = rawResults.length - newRecords.length;
|
||||
this.emit('parsing', newRecords.length, total, `${newRecords.length} new records, ${skipped} duplicates skipped`);
|
||||
|
||||
@@ -246,17 +248,45 @@ export class AttendanceImportService {
|
||||
/**
|
||||
* Query which dingIds already exist to skip duplicates.
|
||||
*/
|
||||
private async getExistingDingIds(
|
||||
private async getExistingRecordsByDingId(
|
||||
results: DingTalkAttendanceResult[],
|
||||
): Promise<Set<string>> {
|
||||
): Promise<Map<string, DingAttendanceRaw>> {
|
||||
const dingIds = results.map((r) => r.checkId).filter(Boolean);
|
||||
if (dingIds.length === 0) return new Set();
|
||||
if (dingIds.length === 0) return new Map();
|
||||
|
||||
const existing = await this.dingRawRepo.find({
|
||||
where: { dingId: In(dingIds) },
|
||||
select: ['dingId'],
|
||||
});
|
||||
return new Set(existing.map((e) => e.dingId));
|
||||
return new Map(existing.map((entity) => [entity.dingId, entity]));
|
||||
}
|
||||
|
||||
private async refreshDuplicatePunchMetadata(
|
||||
results: DingTalkAttendanceResult[],
|
||||
existingByDingId: Map<string, DingAttendanceRaw>,
|
||||
): Promise<void> {
|
||||
const changed: DingAttendanceRaw[] = [];
|
||||
for (const result of results) {
|
||||
const entity = existingByDingId.get(result.checkId);
|
||||
if (!entity) continue;
|
||||
const punchSource = result.sourceType || entity.punchSource || null;
|
||||
const punchDeviceName = result.deviceName || entity.punchDeviceName || null;
|
||||
const punchDeviceId = result.deviceId || entity.punchDeviceId || null;
|
||||
if (
|
||||
entity.punchSource === punchSource &&
|
||||
entity.punchDeviceName === punchDeviceName &&
|
||||
entity.punchDeviceId === punchDeviceId
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
entity.punchSource = punchSource;
|
||||
entity.punchDeviceName = punchDeviceName;
|
||||
entity.punchDeviceId = punchDeviceId;
|
||||
entity.rawData = JSON.stringify(result);
|
||||
changed.push(entity);
|
||||
}
|
||||
if (changed.length > 0) {
|
||||
await this.dingRawRepo.save(changed, { chunk: 50 });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -271,6 +301,9 @@ export class AttendanceImportService {
|
||||
entity.attendanceType = r.checkType || 'OnDuty';
|
||||
entity.timeResult = r.timeResult;
|
||||
entity.locationResult = r.locationResult || '';
|
||||
entity.punchSource = r.sourceType || null;
|
||||
entity.punchDeviceName = r.deviceName || null;
|
||||
entity.punchDeviceId = r.deviceId || null;
|
||||
|
||||
// Parse check-in/out times
|
||||
if (r.actualCheckTime) {
|
||||
|
||||
@@ -20,6 +20,14 @@ const createService = () => {
|
||||
update: jest.fn().mockResolvedValue({ affected: 1 }),
|
||||
};
|
||||
const attendanceService = {
|
||||
getLessonAttendanceImportDateRange: jest.fn().mockImplementation((targetSchedule, lessonDate: string) => {
|
||||
if (targetSchedule.endTime > targetSchedule.startTime) {
|
||||
return { startDate: lessonDate, endDate: lessonDate };
|
||||
}
|
||||
const next = new Date(`${lessonDate}T00:00:00.000Z`);
|
||||
next.setUTCDate(next.getUTCDate() + 1);
|
||||
return { startDate: lessonDate, endDate: next.toISOString().slice(0, 10) };
|
||||
}),
|
||||
getTeacherClassDingUserIds: jest.fn().mockResolvedValue(['ding-1']),
|
||||
createLessonAttendanceFromDingTalk: jest.fn().mockImplementation(
|
||||
async (_scheduleId: number, lessonDate: string, userId: number, finalize: boolean) => ({
|
||||
@@ -72,6 +80,49 @@ describe('AttendanceSettlementService', () => {
|
||||
expect(attendanceService.createLessonAttendanceFromDingTalk).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not settle an in-progress lesson before its end time', async () => {
|
||||
const { service, scheduleRepo, sessionRepo, attendanceService, importService } = createService();
|
||||
scheduleRepo.find.mockResolvedValue([schedule]);
|
||||
sessionRepo.find.mockResolvedValue([
|
||||
{
|
||||
id: 90,
|
||||
scheduleId: 2,
|
||||
lessonDate: '2026-07-13',
|
||||
status: 'in_progress',
|
||||
schedule,
|
||||
},
|
||||
]);
|
||||
|
||||
await service.settleEndedLessons(new Date('2026-07-13T09:30:00+08:00'));
|
||||
|
||||
expect(importService.importFromDingTalk).not.toHaveBeenCalled();
|
||||
expect(attendanceService.createLessonAttendanceFromDingTalk).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('settles an in-progress lesson when its end time is reached', async () => {
|
||||
const { service, scheduleRepo, sessionRepo, attendanceService } = createService();
|
||||
scheduleRepo.find.mockResolvedValue([schedule]);
|
||||
sessionRepo.find.mockResolvedValue([
|
||||
{
|
||||
id: 90,
|
||||
scheduleId: 2,
|
||||
lessonDate: '2026-07-13',
|
||||
status: 'in_progress',
|
||||
schedule,
|
||||
},
|
||||
]);
|
||||
|
||||
await service.settleEndedLessons(new Date('2026-07-13T10:00:00+08:00'));
|
||||
|
||||
expect(attendanceService.createLessonAttendanceFromDingTalk).toHaveBeenCalledTimes(1);
|
||||
expect(attendanceService.createLessonAttendanceFromDingTalk).toHaveBeenCalledWith(
|
||||
2,
|
||||
'2026-07-13',
|
||||
21,
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('continues with the next lesson when one settlement fails', async () => {
|
||||
const { service, scheduleRepo, sessionRepo, attendanceService, importService } = createService();
|
||||
scheduleRepo.find.mockResolvedValue([schedule, { ...schedule, id: 3 }]);
|
||||
@@ -155,6 +206,32 @@ describe('AttendanceSettlementService', () => {
|
||||
expect(attendanceService.createLessonAttendanceFromDingTalk).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not settle an in-progress overnight lesson before its next-day end time', async () => {
|
||||
const { service, scheduleRepo, sessionRepo, attendanceService, importService } = createService();
|
||||
const overnightSchedule = {
|
||||
...schedule,
|
||||
id: 4,
|
||||
weekDay: 7,
|
||||
startTime: '22:00',
|
||||
endTime: '01:00',
|
||||
};
|
||||
scheduleRepo.find.mockResolvedValue([]);
|
||||
sessionRepo.find.mockResolvedValue([
|
||||
{
|
||||
id: 91,
|
||||
scheduleId: 4,
|
||||
lessonDate: '2026-07-12',
|
||||
status: 'in_progress',
|
||||
schedule: overnightSchedule,
|
||||
},
|
||||
]);
|
||||
|
||||
await service.settleEndedLessons(new Date('2026-07-13T00:30:00+08:00'));
|
||||
|
||||
expect(importService.importFromDingTalk).not.toHaveBeenCalled();
|
||||
expect(attendanceService.createLessonAttendanceFromDingTalk).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('settles an overnight lesson after its next-day end time', async () => {
|
||||
const { service, scheduleRepo, sessionRepo, attendanceService } = createService();
|
||||
scheduleRepo.find.mockResolvedValue([
|
||||
|
||||
@@ -61,7 +61,11 @@ export class AttendanceSettlementService {
|
||||
}
|
||||
}
|
||||
for (const session of sessions) {
|
||||
if (session.status === 'in_progress' && session.schedule) {
|
||||
if (
|
||||
session.status === 'in_progress' &&
|
||||
session.schedule &&
|
||||
this.hasOccurrenceEnded(session.schedule, session.lessonDate, clock)
|
||||
) {
|
||||
candidates.set(`${session.scheduleId}|${session.lessonDate}`, {
|
||||
schedule: session.schedule,
|
||||
lessonDate: session.lessonDate,
|
||||
@@ -109,10 +113,15 @@ export class AttendanceSettlementService {
|
||||
const userIds = await this.attendanceService.getTeacherClassDingUserIds(
|
||||
schedule.teacherId,
|
||||
schedule.classId,
|
||||
false,
|
||||
lessonDate,
|
||||
);
|
||||
const importRange = this.attendanceService.getLessonAttendanceImportDateRange(
|
||||
schedule,
|
||||
lessonDate,
|
||||
);
|
||||
const imported = await this.importService.importFromDingTalk({
|
||||
startDate: lessonDate,
|
||||
endDate: this.isOvernight(schedule) ? this.shiftDate(lessonDate, 1) : lessonDate,
|
||||
...importRange,
|
||||
userIds,
|
||||
autoMatch: true,
|
||||
userId: schedule.teacherId,
|
||||
@@ -160,6 +169,18 @@ export class AttendanceSettlementService {
|
||||
return null;
|
||||
}
|
||||
|
||||
private hasOccurrenceEnded(
|
||||
schedule: ClassSchedule,
|
||||
lessonDate: string,
|
||||
clock: { date: string; minutes: number },
|
||||
): boolean {
|
||||
const occurrenceEndDate = this.isOvernight(schedule)
|
||||
? this.shiftDate(lessonDate, 1)
|
||||
: lessonDate;
|
||||
if (clock.date !== occurrenceEndDate) return clock.date > occurrenceEndDate;
|
||||
return clock.minutes >= this.toMinutes(schedule.endTime);
|
||||
}
|
||||
|
||||
private isOvernight(schedule: ClassSchedule): boolean {
|
||||
return this.toMinutes(schedule.endTime) <= this.toMinutes(schedule.startTime);
|
||||
}
|
||||
|
||||
361
apps/server/src/attendance/attendance.boundaries.spec.ts
Normal file
361
apps/server/src/attendance/attendance.boundaries.spec.ts
Normal file
@@ -0,0 +1,361 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { AttendanceService } from './attendance.service';
|
||||
import { AttendancePeriodConfig } from '../entities/attendance-period-config.entity';
|
||||
import { ClassSchedule } from '../entities/class-schedule.entity';
|
||||
|
||||
// ── saveAttendancePeriodConfigs ──
|
||||
|
||||
describe('AttendanceService — saveAttendancePeriodConfigs boundaries', () => {
|
||||
function createService(periodConfigRepoOverrides?: {
|
||||
clear?: jest.Mock;
|
||||
save?: jest.Mock;
|
||||
create?: jest.Mock;
|
||||
find?: jest.Mock;
|
||||
count?: jest.Mock;
|
||||
}) {
|
||||
const periodConfigRepo = {
|
||||
clear: jest.fn().mockResolvedValue(undefined),
|
||||
save: jest.fn().mockImplementation((entities: unknown) => Promise.resolve(entities)),
|
||||
create: jest.fn().mockImplementation((data: Partial<AttendancePeriodConfig>) => ({
|
||||
id: 1,
|
||||
...data,
|
||||
} as AttendancePeriodConfig)),
|
||||
find: jest.fn().mockResolvedValue([]),
|
||||
count: jest.fn().mockResolvedValue(0),
|
||||
...periodConfigRepoOverrides,
|
||||
};
|
||||
|
||||
return new AttendanceService(
|
||||
{} as never, // attendanceRepo
|
||||
{} as never, // dingRawRepo
|
||||
{} as never, // classRepo
|
||||
{} as never, // studentRepo
|
||||
{} as never, // scheduleRepo
|
||||
{} as never, // classStudentRepo
|
||||
{} as never, // studentDingMappingRepo
|
||||
{} as never, // classTeacherRepo
|
||||
{} as never, // attendanceSessionRepo
|
||||
{} as never, // attendanceDeviceRepo
|
||||
periodConfigRepo as never,
|
||||
{} as never, // dataSource
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('detects overlap when sorted by startTime even if sortOrder is inconsistent', async () => {
|
||||
// A: sortOrder=1 but startTime="14:00" (later in the day)
|
||||
// B: sortOrder=2 but startTime="09:00" (earlier in the day)
|
||||
// When sorted by sortOrder, A comes first, then B.
|
||||
// The overlap check sorts by startTime, so B (09:00–15:00) comes first,
|
||||
// and A (14:00–17:00) is detected as overlapping B.
|
||||
const savedPeriods: AttendancePeriodConfig[] = [];
|
||||
const service = createService({
|
||||
save: jest.fn().mockImplementation((entities: AttendancePeriodConfig[]) => {
|
||||
savedPeriods.push(...entities);
|
||||
return Promise.resolve(entities);
|
||||
}),
|
||||
find: jest.fn().mockResolvedValue([]),
|
||||
});
|
||||
|
||||
const dto = {
|
||||
periods: [
|
||||
{ periodKey: 'afternoon', label: '晚课', startTime: '14:00', endTime: '17:00', sortOrder: 1, enabled: true },
|
||||
{ periodKey: 'morning', label: '早课', startTime: '09:00', endTime: '15:00', sortOrder: 2, enabled: true },
|
||||
],
|
||||
};
|
||||
|
||||
await expect(service.saveAttendancePeriodConfigs(dto as any)).rejects.toThrow(BadRequestException);
|
||||
await expect(service.saveAttendancePeriodConfigs(dto as any)).rejects.toThrow('时间段不能重叠');
|
||||
});
|
||||
|
||||
it('accepts valid non-overlapping periods sorted by sortOrder', async () => {
|
||||
const savedPeriods: AttendancePeriodConfig[] = [];
|
||||
const expectedPeriods: AttendancePeriodConfig[] = [
|
||||
{ id: 1, periodKey: 'morning_reading', label: '早自习', startTime: '07:30', endTime: '08:30', sortOrder: 1, enabled: true, createdAt: expect.any(Date) as any, updatedAt: expect.any(Date) as any },
|
||||
{ id: 1, periodKey: 'morning', label: '早课', startTime: '09:00', endTime: '12:00', sortOrder: 2, enabled: true, createdAt: expect.any(Date) as any, updatedAt: expect.any(Date) as any },
|
||||
{ id: 1, periodKey: 'afternoon', label: '晚课', startTime: '14:00', endTime: '17:00', sortOrder: 3, enabled: true, createdAt: expect.any(Date) as any, updatedAt: expect.any(Date) as any },
|
||||
{ id: 1, periodKey: 'evening_study', label: '晚自习', startTime: '18:30', endTime: '21:00', sortOrder: 4, enabled: true, createdAt: expect.any(Date) as any, updatedAt: expect.any(Date) as any },
|
||||
];
|
||||
|
||||
// count returns > 0 so ensureAttendancePeriodConfigs does not re-seed defaults
|
||||
const service = createService({
|
||||
count: jest.fn().mockResolvedValue(4),
|
||||
save: jest.fn().mockImplementation((entities: AttendancePeriodConfig[]) => {
|
||||
savedPeriods.push(...entities);
|
||||
return Promise.resolve(entities);
|
||||
}),
|
||||
find: jest.fn().mockResolvedValue(expectedPeriods),
|
||||
});
|
||||
|
||||
const dto = {
|
||||
periods: [
|
||||
{ periodKey: 'morning_reading', label: '早自习', startTime: '07:30', endTime: '08:30', sortOrder: 1, enabled: true },
|
||||
{ periodKey: 'morning', label: '早课', startTime: '09:00', endTime: '12:00', sortOrder: 2, enabled: true },
|
||||
{ periodKey: 'afternoon', label: '晚课', startTime: '14:00', endTime: '17:00', sortOrder: 3, enabled: true },
|
||||
{ periodKey: 'evening_study', label: '晚自习', startTime: '18:30', endTime: '21:00', sortOrder: 4, enabled: true },
|
||||
],
|
||||
};
|
||||
|
||||
const result = await service.saveAttendancePeriodConfigs(dto as any);
|
||||
|
||||
expect(result).toEqual(expectedPeriods);
|
||||
expect(savedPeriods).toHaveLength(4);
|
||||
// Verify they were saved in sortOrder order (ascending)
|
||||
expect(savedPeriods[0].periodKey).toBe('morning_reading');
|
||||
expect(savedPeriods[1].periodKey).toBe('morning');
|
||||
expect(savedPeriods[2].periodKey).toBe('afternoon');
|
||||
expect(savedPeriods[3].periodKey).toBe('evening_study');
|
||||
});
|
||||
|
||||
it('rejects periods where endTime is not after startTime', async () => {
|
||||
const service = createService();
|
||||
|
||||
const dto = {
|
||||
periods: [
|
||||
{ periodKey: 'bad', label: 'Bad Period', startTime: '10:00', endTime: '09:00', sortOrder: 1, enabled: true },
|
||||
],
|
||||
};
|
||||
|
||||
await expect(service.saveAttendancePeriodConfigs(dto as any)).rejects.toThrow(BadRequestException);
|
||||
await expect(service.saveAttendancePeriodConfigs(dto as any)).rejects.toThrow('结束时间必须晚于开始时间');
|
||||
});
|
||||
|
||||
it('rejects duplicate periodKey', async () => {
|
||||
const service = createService();
|
||||
|
||||
const dto = {
|
||||
periods: [
|
||||
{ periodKey: 'morning', label: '早课', startTime: '09:00', endTime: '12:00', sortOrder: 1, enabled: true },
|
||||
{ periodKey: 'morning', label: '早课2', startTime: '14:00', endTime: '17:00', sortOrder: 2, enabled: true },
|
||||
],
|
||||
};
|
||||
|
||||
await expect(service.saveAttendancePeriodConfigs(dto as any)).rejects.toThrow(BadRequestException);
|
||||
await expect(service.saveAttendancePeriodConfigs(dto as any)).rejects.toThrow('重复');
|
||||
});
|
||||
|
||||
it('rejects empty period key or label', async () => {
|
||||
const service = createService();
|
||||
|
||||
const dto = {
|
||||
periods: [
|
||||
{ periodKey: ' ', label: 'Valid Label', startTime: '09:00', endTime: '12:00', sortOrder: 1, enabled: true },
|
||||
],
|
||||
};
|
||||
|
||||
await expect(service.saveAttendancePeriodConfigs(dto as any)).rejects.toThrow(BadRequestException);
|
||||
await expect(service.saveAttendancePeriodConfigs(dto as any)).rejects.toThrow('时段标识和名称不能为空');
|
||||
});
|
||||
|
||||
it('disabled periods are ignored during overlap check', async () => {
|
||||
const savedPeriods: AttendancePeriodConfig[] = [];
|
||||
const service = createService({
|
||||
count: jest.fn().mockResolvedValue(2),
|
||||
save: jest.fn().mockImplementation((entities: AttendancePeriodConfig[]) => {
|
||||
savedPeriods.push(...entities);
|
||||
return Promise.resolve(entities);
|
||||
}),
|
||||
find: jest.fn().mockResolvedValue([]),
|
||||
});
|
||||
|
||||
// A (enabled, startTime=09:00, endTime=17:00) and B (disabled, startTime=10:00, endTime=12:00, which would overlap A)
|
||||
// The disabled period should be skipped in overlap check
|
||||
const dto = {
|
||||
periods: [
|
||||
{ periodKey: 'day', label: '全天', startTime: '09:00', endTime: '17:00', sortOrder: 1, enabled: true },
|
||||
{ periodKey: 'break', label: '休息', startTime: '10:00', endTime: '12:00', sortOrder: 2, enabled: false },
|
||||
],
|
||||
};
|
||||
|
||||
// Should not throw — the disabled period is ignored
|
||||
const result = await service.saveAttendancePeriodConfigs(dto as any);
|
||||
expect(result).toBeDefined();
|
||||
expect(savedPeriods).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
// ── getScheduleOptionsForAttendance ──
|
||||
|
||||
describe('AttendanceService — getScheduleOptionsForAttendance boundaries', () => {
|
||||
it('returns null teacher when schedule has no matching raw entry (teacher not found)', async () => {
|
||||
const entity = {
|
||||
id: 42,
|
||||
classId: 8,
|
||||
subject: '数学',
|
||||
startTime: '09:00',
|
||||
endTime: '12:00',
|
||||
weekDay: 1,
|
||||
startDate: '2026-01-01',
|
||||
endDate: '2026-12-31',
|
||||
} as ClassSchedule;
|
||||
|
||||
// Simulate the case where getRawAndEntities returns the entity
|
||||
// but `raw` is empty (no teacher row). This happens when the
|
||||
// schedule has no teacher assignment.
|
||||
const qb = {
|
||||
leftJoin: jest.fn().mockReturnThis(),
|
||||
addSelect: jest.fn().mockReturnThis(),
|
||||
where: jest.fn().mockReturnThis(),
|
||||
andWhere: jest.fn().mockReturnThis(),
|
||||
orderBy: jest.fn().mockReturnThis(),
|
||||
addOrderBy: jest.fn().mockReturnThis(),
|
||||
getRawAndEntities: jest.fn().mockResolvedValue({
|
||||
entities: [entity],
|
||||
raw: [], // empty raw → no teacher info
|
||||
}),
|
||||
};
|
||||
|
||||
const scheduleRepo = {
|
||||
createQueryBuilder: jest.fn().mockReturnValue(qb),
|
||||
};
|
||||
|
||||
const service = new AttendanceService(
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
scheduleRepo as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
|
||||
const result = await service.getScheduleOptionsForAttendance(8, '2026-07-20');
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toMatchObject({
|
||||
id: 42,
|
||||
teacherName: null,
|
||||
teacherUsername: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns teacher info when raw contains a matching schedule entry', async () => {
|
||||
const entity = {
|
||||
id: 42,
|
||||
classId: 8,
|
||||
subject: '数学',
|
||||
startTime: '09:00',
|
||||
endTime: '12:00',
|
||||
weekDay: 1,
|
||||
startDate: '2026-01-01',
|
||||
endDate: '2026-12-31',
|
||||
} as ClassSchedule;
|
||||
|
||||
const qb = {
|
||||
leftJoin: jest.fn().mockReturnThis(),
|
||||
addSelect: jest.fn().mockReturnThis(),
|
||||
where: jest.fn().mockReturnThis(),
|
||||
andWhere: jest.fn().mockReturnThis(),
|
||||
orderBy: jest.fn().mockReturnThis(),
|
||||
addOrderBy: jest.fn().mockReturnThis(),
|
||||
getRawAndEntities: jest.fn().mockResolvedValue({
|
||||
entities: [entity],
|
||||
raw: [
|
||||
{
|
||||
scheduleIdForTeacherMap: 42,
|
||||
teacherName: '张老师',
|
||||
teacherUsername: 'zhang',
|
||||
},
|
||||
],
|
||||
}),
|
||||
};
|
||||
|
||||
const scheduleRepo = {
|
||||
createQueryBuilder: jest.fn().mockReturnValue(qb),
|
||||
};
|
||||
|
||||
const service = new AttendanceService(
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
scheduleRepo as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
|
||||
const result = await service.getScheduleOptionsForAttendance(8, '2026-07-20');
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toMatchObject({
|
||||
id: 42,
|
||||
teacherName: '张老师',
|
||||
teacherUsername: 'zhang',
|
||||
});
|
||||
});
|
||||
|
||||
it('returns null teacher when raw has a different schedule id than the entity', async () => {
|
||||
const entity = {
|
||||
id: 42,
|
||||
classId: 8,
|
||||
subject: '数学',
|
||||
startTime: '09:00',
|
||||
endTime: '12:00',
|
||||
weekDay: 1,
|
||||
startDate: '2026-01-01',
|
||||
endDate: '2026-12-31',
|
||||
} as ClassSchedule;
|
||||
|
||||
// raw contains teacher info but for a DIFFERENT schedule id (99 ≠ 42)
|
||||
// The fallback `??` should kick in for schedule 42
|
||||
const qb = {
|
||||
leftJoin: jest.fn().mockReturnThis(),
|
||||
addSelect: jest.fn().mockReturnThis(),
|
||||
where: jest.fn().mockReturnThis(),
|
||||
andWhere: jest.fn().mockReturnThis(),
|
||||
orderBy: jest.fn().mockReturnThis(),
|
||||
addOrderBy: jest.fn().mockReturnThis(),
|
||||
getRawAndEntities: jest.fn().mockResolvedValue({
|
||||
entities: [entity],
|
||||
raw: [
|
||||
{
|
||||
scheduleIdForTeacherMap: 99,
|
||||
teacherName: '张老师',
|
||||
teacherUsername: 'zhang',
|
||||
},
|
||||
],
|
||||
}),
|
||||
};
|
||||
|
||||
const scheduleRepo = {
|
||||
createQueryBuilder: jest.fn().mockReturnValue(qb),
|
||||
};
|
||||
|
||||
const service = new AttendanceService(
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
scheduleRepo as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
|
||||
const result = await service.getScheduleOptionsForAttendance(8, '2026-07-20');
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toMatchObject({
|
||||
id: 42,
|
||||
teacherName: null,
|
||||
teacherUsername: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -162,6 +162,9 @@ describe('AttendanceController — write data scope', () => {
|
||||
assertClassAccess: jest.fn(),
|
||||
getAccessibleClassIds: jest.fn(),
|
||||
getTeacherClassDingUserIds: jest.fn(),
|
||||
getLessonAttendanceImportDateRange: jest.fn().mockImplementation(
|
||||
(_schedule, lessonDate: string) => ({ startDate: lessonDate, endDate: lessonDate }),
|
||||
),
|
||||
batchCreate: jest.fn(),
|
||||
generateFromSchedules: jest.fn(),
|
||||
findAttendanceRecord: jest.fn(),
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
Res,
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
ParseIntPipe,
|
||||
} from '@nestjs/common';
|
||||
import { Observable, filter } from 'rxjs';
|
||||
import type { Request as ExpressRequest, Response } from 'express';
|
||||
@@ -24,13 +25,17 @@ import {
|
||||
AttendanceSummaryQueryDto,
|
||||
AttendanceCalendarQueryDto,
|
||||
QueryAttendanceRecordsDto,
|
||||
AttendanceScheduleOptionsQueryDto,
|
||||
QueryDingRawDto,
|
||||
MatchDingRecordDto,
|
||||
AttendanceReportQueryDto,
|
||||
AttendanceAlertsQueryDto,
|
||||
UpdateAttendanceRecordDto,
|
||||
GenerateFromSchedulesDto,
|
||||
LessonAttendanceQueryDto,
|
||||
StartLessonAttendanceDto,
|
||||
SaveAttendancePeriodConfigsDto,
|
||||
RefreshDingTalkAttendanceDto,
|
||||
} from './dto/attendance.dto';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
||||
@@ -90,14 +95,53 @@ export class AttendanceController {
|
||||
return this.service.assertClassAccess(req.user.id, classId, this.canManageAllAttendance(req));
|
||||
}
|
||||
|
||||
|
||||
@Get('attendance-period-configs')
|
||||
@RequirePermission('attendance:view')
|
||||
getAttendancePeriodConfigs() {
|
||||
return this.service.getAttendancePeriodConfigs();
|
||||
}
|
||||
|
||||
@Put('attendance-period-configs')
|
||||
@RequirePermission('attendance:edit')
|
||||
async saveAttendancePeriodConfigs(
|
||||
@Body() dto: SaveAttendancePeriodConfigsDto,
|
||||
@Request() req: { user: RequestUser },
|
||||
) {
|
||||
const result = await this.service.saveAttendancePeriodConfigs(dto);
|
||||
await this.logService.log({
|
||||
userId: req.user.id,
|
||||
username: req.user.username,
|
||||
module: '考勤管理',
|
||||
action: '保存考勤时段配置',
|
||||
targetType: 'attendancePeriodConfig',
|
||||
detail: dto.periods.map((item) => `${item.label}:${item.startTime}-${item.endTime}`).join(';'),
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post('attendance-period-configs/reset')
|
||||
@RequirePermission('attendance:edit')
|
||||
async resetAttendancePeriodConfigs(@Request() req: { user: RequestUser }) {
|
||||
const result = await this.service.resetAttendancePeriodConfigs();
|
||||
await this.logService.log({
|
||||
userId: req.user.id,
|
||||
username: req.user.username,
|
||||
module: '考勤管理',
|
||||
action: '重置考勤时段配置',
|
||||
targetType: 'attendancePeriodConfig',
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@Get('attendance-lessons/schedules/:scheduleId')
|
||||
@RequirePermission('attendance:view')
|
||||
async getLessonAttendance(
|
||||
@Param('scheduleId') scheduleId: string,
|
||||
@Param('scheduleId', ParseIntPipe) scheduleId: number,
|
||||
@Query() query: LessonAttendanceQueryDto,
|
||||
@Request() req: { user: RequestUser },
|
||||
) {
|
||||
const result = await this.service.getLessonAttendance(+scheduleId, query.date);
|
||||
const result = await this.service.getLessonAttendance(scheduleId, query.date);
|
||||
await this.assertClassAccess(req, result.schedule.classId!);
|
||||
return result;
|
||||
}
|
||||
@@ -105,26 +149,33 @@ export class AttendanceController {
|
||||
@Post('attendance-lessons/schedules/:scheduleId/pull')
|
||||
@RequirePermission('attendance:create')
|
||||
async pullLessonAttendance(
|
||||
@Param('scheduleId') scheduleId: string,
|
||||
@Param('scheduleId', ParseIntPipe) scheduleId: number,
|
||||
@Body() dto: StartLessonAttendanceDto,
|
||||
@Request() req: { user: RequestUser },
|
||||
) {
|
||||
const schedule = await this.service.getLessonAttendance(+scheduleId, dto.date);
|
||||
const schedule = await this.service.getLessonAttendance(scheduleId, dto.date);
|
||||
await this.assertClassAccess(req, schedule.schedule.classId!);
|
||||
const importClassIds = await this.service.getTeacherClassDingUserIds(
|
||||
req.user.id,
|
||||
schedule.schedule.classId!,
|
||||
this.canManageAllAttendance(req),
|
||||
dto.date,
|
||||
);
|
||||
const importRange = this.service.getLessonAttendanceImportDateRange(
|
||||
schedule.schedule,
|
||||
dto.date,
|
||||
);
|
||||
const importResult = await this.importService.importFromDingTalk({
|
||||
startDate: dto.date,
|
||||
endDate: dto.date,
|
||||
...importRange,
|
||||
userIds: importClassIds,
|
||||
autoMatch: true,
|
||||
userId: req.user.id,
|
||||
});
|
||||
if (!importResult.success || importResult.errors.length > 0) {
|
||||
throw new BadRequestException(importResult.errors.join('; ') || '钉钉考勤拉取失败');
|
||||
}
|
||||
const result = await this.service.createLessonAttendanceFromDingTalk(
|
||||
+scheduleId,
|
||||
scheduleId,
|
||||
dto.date,
|
||||
req.user.id,
|
||||
);
|
||||
@@ -143,24 +194,102 @@ export class AttendanceController {
|
||||
@Post('attendance-lessons/:sessionId/complete')
|
||||
@RequirePermission('attendance:create')
|
||||
async completeLessonAttendance(
|
||||
@Param('sessionId') sessionId: string,
|
||||
@Param('sessionId', ParseIntPipe) sessionId: number,
|
||||
@Request() req: { user: RequestUser },
|
||||
) {
|
||||
const session = await this.service.findAttendanceSession(+sessionId);
|
||||
const session = await this.service.findAttendanceSession(sessionId);
|
||||
await this.assertClassAccess(req, session.classId);
|
||||
const result = await this.service.completeLessonAttendance(+sessionId, req.user.id);
|
||||
const result = await this.service.completeLessonAttendance(sessionId, req.user.id);
|
||||
await this.logService.log({
|
||||
userId: req.user.id,
|
||||
username: req.user.username,
|
||||
module: '考勤管理',
|
||||
action: '完成课程点名',
|
||||
targetId: +sessionId,
|
||||
targetId: sessionId,
|
||||
targetType: 'attendanceSession',
|
||||
detail: `班级${session.classId} 日期${session.lessonDate}`,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@Get('attendance-records/dingtalk-sync-status')
|
||||
@RequirePermission('attendance:view')
|
||||
async getDingTalkSyncStatus() {
|
||||
const latest = await this.logService.findLatestDingTalkAttendancePull();
|
||||
return {
|
||||
lastPulledAt: latest?.createdAt ?? null,
|
||||
action: latest?.action ?? null,
|
||||
username: latest?.username ?? null,
|
||||
detail: latest?.detail ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@Post('attendance-records/refresh-dingtalk')
|
||||
@RequirePermission('attendance:create')
|
||||
async refreshDingTalkAttendance(
|
||||
@Body() dto: RefreshDingTalkAttendanceDto,
|
||||
@Request() req: { user: RequestUser },
|
||||
) {
|
||||
if (dto.date > this.getTodayDateOnly()) {
|
||||
throw new BadRequestException('不能查看或刷新未来日期的考勤');
|
||||
}
|
||||
if (dto.classId) await this.assertClassAccess(req, dto.classId);
|
||||
const schedules = await this.service.getRefreshableSchedules(
|
||||
dto.date,
|
||||
dto.classId,
|
||||
dto.session,
|
||||
await this.getAccessibleClassIds(req),
|
||||
);
|
||||
let refreshed = 0;
|
||||
let imported = 0;
|
||||
let matched = 0;
|
||||
const errors: string[] = [];
|
||||
|
||||
for (const schedule of schedules) {
|
||||
try {
|
||||
const importClassIds = await this.service.getTeacherClassDingUserIds(
|
||||
req.user.id,
|
||||
schedule.classId!,
|
||||
this.canManageAllAttendance(req),
|
||||
dto.date,
|
||||
);
|
||||
const importRange = this.service.getLessonAttendanceImportDateRange(schedule, dto.date);
|
||||
const importResult = await this.importService.importFromDingTalk({
|
||||
...importRange,
|
||||
userIds: importClassIds,
|
||||
autoMatch: true,
|
||||
userId: req.user.id,
|
||||
});
|
||||
if (!importResult.success || importResult.errors.length > 0) {
|
||||
errors.push(...importResult.errors);
|
||||
continue;
|
||||
}
|
||||
await this.service.createLessonAttendanceFromDingTalk(schedule.id, dto.date, req.user.id);
|
||||
refreshed += 1;
|
||||
imported += importResult.imported;
|
||||
matched += importResult.matched;
|
||||
} catch (error: unknown) {
|
||||
errors.push((error as { message?: string })?.message || `排课 ${schedule.id} 刷新失败`);
|
||||
}
|
||||
}
|
||||
|
||||
await this.logService.log({
|
||||
userId: req.user.id,
|
||||
username: req.user.username,
|
||||
module: '考勤管理',
|
||||
action: '刷新钉钉考勤',
|
||||
targetType: 'attendanceRecord',
|
||||
detail: `日期${dto.date},排课${schedules.length}节,刷新${refreshed}节,钉钉新增${imported}条,匹配${matched}条${errors.length ? `,错误${errors.length}条` : ''}`,
|
||||
status: errors.length > 0 && refreshed === 0 ? 'failure' : 'success',
|
||||
});
|
||||
|
||||
if (schedules.length === 0) {
|
||||
return { refreshed, imported, matched, errors: ['当前条件下没有可刷新的课程'] };
|
||||
}
|
||||
return { refreshed, imported, matched, errors };
|
||||
}
|
||||
|
||||
// ── Batch create attendance records ──
|
||||
@Post('attendance-records/batch')
|
||||
@RequirePermission('attendance:create')
|
||||
@@ -231,8 +360,10 @@ export class AttendanceController {
|
||||
{ header: '时段', key: 'session', width: 15 },
|
||||
{ header: '状态', key: 'status', width: 10 },
|
||||
{ header: '来源', key: 'source', width: 10 },
|
||||
{ header: '打卡设备', key: 'punchDevice', width: 30 },
|
||||
{ header: '打卡时间', key: 'punchTime', width: 20 },
|
||||
{ header: '备注', key: 'remark', width: 30 },
|
||||
{ header: '打卡时间', key: 'createdAt', width: 20 },
|
||||
{ header: '归档时间', key: 'createdAt', width: 20 },
|
||||
];
|
||||
ws.getRow(1).font = { bold: true };
|
||||
ws.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
|
||||
@@ -245,6 +376,10 @@ export class AttendanceController {
|
||||
session: record.session || '',
|
||||
status: record.status || '',
|
||||
source: record.source || '',
|
||||
punchDevice: record.punchDeviceName || record.punchDeviceId || '',
|
||||
punchTime: record.punchTime
|
||||
? record.punchTime.toISOString().replace('T', ' ').substring(0, 19)
|
||||
: '',
|
||||
remark: record.remark || '',
|
||||
createdAt: record.createdAt
|
||||
? record.createdAt.toISOString().replace('T', ' ').substring(0, 19)
|
||||
@@ -266,6 +401,16 @@ export class AttendanceController {
|
||||
res.end();
|
||||
}
|
||||
|
||||
@Get('attendance-records/schedules')
|
||||
@RequirePermission('attendance:view')
|
||||
async getAttendanceScheduleOptions(
|
||||
@Query() query: AttendanceScheduleOptionsQueryDto,
|
||||
@Request() req: { user: RequestUser },
|
||||
) {
|
||||
await this.assertClassAccess(req, query.classId);
|
||||
return this.service.getScheduleOptionsForAttendance(query.classId, query.date);
|
||||
}
|
||||
|
||||
// ── List attendance records with filters ──
|
||||
@Get('attendance-records')
|
||||
@RequirePermission('attendance:view')
|
||||
@@ -278,23 +423,23 @@ export class AttendanceController {
|
||||
@Put('attendance-records/:id')
|
||||
@RequirePermission('attendance:edit', 'attendance:self-edit')
|
||||
async update(
|
||||
@Param('id') id: string,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: UpdateAttendanceRecordDto,
|
||||
@Request() req: any,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const existing = await this.service.findAttendanceRecord(+id);
|
||||
const existing = await this.service.findAttendanceRecord(id);
|
||||
if (existing.classId == null && !this.canManageAllAttendance(req)) {
|
||||
throw new ForbiddenException('无权修改未关联班级的考勤记录');
|
||||
}
|
||||
if (existing.classId != null) await this.assertClassAccess(req, existing.classId);
|
||||
const result = await this.service.update(+id, dto);
|
||||
const result = await this.service.update(id, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '考勤管理',
|
||||
action: '编辑考勤记录',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'attendanceRecord',
|
||||
detail: `状态=${result.status}, 备注=${result.remark || ''}`,
|
||||
ipAddress,
|
||||
@@ -306,22 +451,22 @@ export class AttendanceController {
|
||||
// ── Delete a single attendance record ──
|
||||
@Delete('attendance-records/:id')
|
||||
@RequirePermission('attendance:edit', 'attendance:self-edit')
|
||||
async remove(@Param('id') id: string, @Request() req: any) {
|
||||
async remove(@Param('id', ParseIntPipe) id: number, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const existing = await this.service.findAttendanceRecord(+id);
|
||||
const existing = await this.service.findAttendanceRecord(id);
|
||||
if (existing.classId == null && !this.canManageAllAttendance(req)) {
|
||||
throw new ForbiddenException('无权删除未关联班级的考勤记录');
|
||||
}
|
||||
if (existing.classId != null) await this.assertClassAccess(req, existing.classId);
|
||||
const result = await this.service.remove(+id);
|
||||
const result = await this.service.remove(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '考勤管理',
|
||||
action: '删除考勤记录',
|
||||
targetId: +id,
|
||||
action: '归档考勤记录',
|
||||
targetId: id,
|
||||
targetType: 'attendanceRecord',
|
||||
detail: `删除考勤记录 ${id}`,
|
||||
detail: `归档考勤记录 ${id}`,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
@@ -369,18 +514,18 @@ export class AttendanceController {
|
||||
@Post('ding-attendance-raw/:id/match')
|
||||
@RequirePermission('attendance:edit')
|
||||
async matchDingRecord(
|
||||
@Param('id') id: string,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: MatchDingRecordDto,
|
||||
@Request() req: any,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.matchDingRecord(+id, dto);
|
||||
const result = await this.service.matchDingRecord(id, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '考勤管理',
|
||||
action: '匹配考勤记录',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'dingAttendanceRaw',
|
||||
detail: `匹配到学生 ${dto.studentId}`,
|
||||
ipAddress,
|
||||
@@ -458,12 +603,11 @@ export class AttendanceController {
|
||||
@RequirePermission('attendance:view')
|
||||
async getAlerts(
|
||||
@Request() req: { user: RequestUser },
|
||||
@Query('days') days?: string,
|
||||
@Query('threshold') threshold?: string,
|
||||
@Query() query: AttendanceAlertsQueryDto,
|
||||
) {
|
||||
return this.service.getAlerts(
|
||||
days ? +days : 14,
|
||||
threshold ? +threshold : 3,
|
||||
query.days ?? 14,
|
||||
query.threshold ?? 3,
|
||||
await this.getAccessibleClassIds(req),
|
||||
);
|
||||
}
|
||||
@@ -512,6 +656,7 @@ export class AttendanceController {
|
||||
req.user.id,
|
||||
dto.classId,
|
||||
canManageAll,
|
||||
dto.start,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ const createService = () => {
|
||||
create: jest.fn((value: Record<string, unknown>) => ({ id: 90, ...value })),
|
||||
save: jest.fn(async (value: unknown) => value),
|
||||
};
|
||||
const attendanceDeviceRepo = { find: jest.fn().mockResolvedValue([]) };
|
||||
const dataSource = {
|
||||
transaction: jest.fn(
|
||||
async (cb: (manager: { getRepository: jest.Mock }) => Promise<unknown>) => {
|
||||
@@ -43,9 +44,11 @@ const createService = () => {
|
||||
{} as never,
|
||||
{} as never,
|
||||
sessionRepo as never,
|
||||
attendanceDeviceRepo as never,
|
||||
{} as never,
|
||||
dataSource as unknown as DataSource,
|
||||
);
|
||||
return { service, attendanceRepo, dingRawRepo, scheduleRepo, classStudentRepo, sessionRepo, dataSource };
|
||||
return { service, attendanceRepo, dingRawRepo, scheduleRepo, classStudentRepo, sessionRepo, attendanceDeviceRepo, dataSource };
|
||||
};
|
||||
|
||||
const endedSchedule = {
|
||||
@@ -59,6 +62,7 @@ const endedSchedule = {
|
||||
subject: '\u6570\u5B66',
|
||||
status: 'active',
|
||||
scheduleType: 'INTERNAL',
|
||||
attendanceAdvanceMinutes: 30,
|
||||
};
|
||||
|
||||
describe('AttendanceService \u2014 DingTalk course attendance', () => {
|
||||
@@ -79,6 +83,9 @@ describe('AttendanceService \u2014 DingTalk course attendance', () => {
|
||||
attendanceType: 'OnDuty',
|
||||
timeResult: 'Normal',
|
||||
checkInTime: new Date('2026-07-11T08:55:00+08:00'),
|
||||
punchSource: 'ATM',
|
||||
punchDeviceName: '东门考勤机',
|
||||
punchDeviceId: 'ATM-01',
|
||||
},
|
||||
{
|
||||
matchedStudentId: 2,
|
||||
@@ -100,7 +107,15 @@ describe('AttendanceService \u2014 DingTalk course attendance', () => {
|
||||
}),
|
||||
);
|
||||
expect(attendanceRepo.save).toHaveBeenCalledWith([
|
||||
expect.objectContaining({ studentId: 1, status: 'present', source: 'dingtalk' }),
|
||||
expect.objectContaining({
|
||||
studentId: 1,
|
||||
status: 'present',
|
||||
source: 'dingtalk',
|
||||
punchSource: 'ATM',
|
||||
punchDeviceName: '东门考勤机',
|
||||
punchDeviceId: 'ATM-01',
|
||||
punchTime: new Date('2026-07-11T08:55:00+08:00'),
|
||||
}),
|
||||
expect.objectContaining({ studentId: 2, status: 'present', source: 'dingtalk' }),
|
||||
expect.objectContaining({ studentId: 3, status: 'pending', source: 'dingtalk' }),
|
||||
expect.objectContaining({ studentId: 4, status: 'pending', source: 'dingtalk' }),
|
||||
@@ -175,6 +190,40 @@ describe('AttendanceService \u2014 DingTalk course attendance', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('counts both OnDuty and OffDuty punches only inside the configured window', async () => {
|
||||
const { service, attendanceRepo, dingRawRepo, scheduleRepo, classStudentRepo, sessionRepo } =
|
||||
createService();
|
||||
scheduleRepo.findOne.mockResolvedValue({ ...endedSchedule, attendanceAdvanceMinutes: 20 });
|
||||
sessionRepo.findOne.mockResolvedValue(null);
|
||||
classStudentRepo.find.mockResolvedValue([
|
||||
{ studentId: 1, student: { id: 1, name: '张三' } },
|
||||
{ studentId: 2, student: { id: 2, name: '李四' } },
|
||||
{ studentId: 3, student: { id: 3, name: '王五' } },
|
||||
]);
|
||||
dingRawRepo.find.mockResolvedValue([
|
||||
{ matchedStudentId: 1, attendanceType: 'OffDuty', checkOutTime: new Date('2026-07-11T08:40:00+08:00') },
|
||||
{ matchedStudentId: 2, attendanceType: 'OffDuty', checkOutTime: new Date('2026-07-11T10:00:00+08:00') },
|
||||
{ matchedStudentId: 3, attendanceType: 'OnDuty', checkInTime: new Date('2026-07-11T08:39:59+08:00') },
|
||||
{ matchedStudentId: 3, attendanceType: 'OffDuty', checkOutTime: new Date('2026-07-11T10:00:01+08:00') },
|
||||
]);
|
||||
|
||||
await service.createLessonAttendanceFromDingTalk(4, '2026-07-11', 21, true);
|
||||
|
||||
expect(attendanceRepo.save).toHaveBeenCalledWith([
|
||||
expect.objectContaining({ studentId: 1, status: 'present' }),
|
||||
expect.objectContaining({ studentId: 2, status: 'present' }),
|
||||
expect.objectContaining({ studentId: 3, status: 'absent' }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('expands import dates when the pre-class window crosses midnight', () => {
|
||||
const { service } = createService();
|
||||
expect(service.getLessonAttendanceImportDateRange(
|
||||
{ startTime: '00:15', endTime: '01:00', attendanceAdvanceMinutes: 30 },
|
||||
'2026-07-11',
|
||||
)).toEqual({ startDate: '2026-07-10', endDate: '2026-07-11' });
|
||||
});
|
||||
|
||||
it('creates local attendance after the lesson starts', async () => {
|
||||
const { service, attendanceRepo, dingRawRepo, scheduleRepo, classStudentRepo, sessionRepo } =
|
||||
createService();
|
||||
@@ -547,3 +596,38 @@ describe('AttendanceService \u2014 DingTalk course attendance', () => {
|
||||
expect(result.source).toBe('manual');
|
||||
});
|
||||
});
|
||||
|
||||
describe('AttendanceService — attendance window boundaries', () => {
|
||||
it('crosses calendar boundaries only when the window requires it', () => {
|
||||
const { service } = createService();
|
||||
expect(service.getLessonAttendanceImportDateRange(
|
||||
{ startTime: '00:30', endTime: '01:30', attendanceAdvanceMinutes: 30 }, '2026-07-13',
|
||||
)).toEqual({ startDate: '2026-07-13', endDate: '2026-07-13' });
|
||||
expect(service.getLessonAttendanceImportDateRange(
|
||||
{ startTime: '00:30', endTime: '01:30', attendanceAdvanceMinutes: 31 }, '2026-07-13',
|
||||
)).toEqual({ startDate: '2026-07-12', endDate: '2026-07-13' });
|
||||
expect(service.getLessonAttendanceImportDateRange(
|
||||
{ startTime: '22:00', endTime: '01:00', attendanceAdvanceMinutes: 30 }, '2026-07-13',
|
||||
)).toEqual({ startDate: '2026-07-13', endDate: '2026-07-14' });
|
||||
});
|
||||
|
||||
it('uses Asia/Shanghai time when deciding whether todays lesson has started', async () => {
|
||||
const originalTz = process.env.TZ;
|
||||
process.env.TZ = 'UTC';
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-07-13T01:00:00.000Z'));
|
||||
try {
|
||||
const { service, scheduleRepo, sessionRepo, attendanceRepo } = createService();
|
||||
scheduleRepo.findOne.mockResolvedValue({
|
||||
...endedSchedule, weekDay: 1, startTime: '08:30', endTime: '10:00',
|
||||
startDate: '2026-07-13', endDate: '2026-07-13',
|
||||
});
|
||||
sessionRepo.findOne.mockResolvedValue({ id: 90, status: 'completed' });
|
||||
attendanceRepo.find.mockResolvedValue([]);
|
||||
await expect(service.createLessonAttendanceFromDingTalk(4, '2026-07-13', 21))
|
||||
.resolves.toMatchObject({ records: [] });
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
process.env.TZ = originalTz;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AttendanceRecord, AttendanceSession, DingAttendanceRaw, Student, Class, ClassSchedule, ClassStudent, ClassTeacher, StudentDingMapping } from '../entities';
|
||||
import { AttendanceRecord, AttendanceSession, AttendanceDevice, AttendancePeriodConfig, DingAttendanceRaw, Student, Class, ClassSchedule, ClassStudent, ClassTeacher, StudentDingMapping } from '../entities';
|
||||
import { AttendanceService } from './attendance.service';
|
||||
import { AttendanceImportService } from './attendance-import.service';
|
||||
import { AttendanceSettlementService } from './attendance-settlement.service';
|
||||
@@ -10,7 +10,7 @@ import { IntegrationModule } from '../integration/integration.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([AttendanceRecord, AttendanceSession, DingAttendanceRaw, Student, Class, ClassSchedule, ClassStudent, ClassTeacher, StudentDingMapping]),
|
||||
TypeOrmModule.forFeature([AttendanceRecord, AttendanceSession, AttendanceDevice, AttendancePeriodConfig, DingAttendanceRaw, Student, Class, ClassSchedule, ClassStudent, ClassTeacher, StudentDingMapping]),
|
||||
OperationLogsModule,
|
||||
IntegrationModule,
|
||||
],
|
||||
|
||||
@@ -6,6 +6,8 @@ import { Repository } from 'typeorm';
|
||||
import { AttendanceService } from './attendance.service';
|
||||
import { AttendanceRecord } from '../entities/attendance-record.entity';
|
||||
import { AttendanceSession } from '../entities/attendance-session.entity';
|
||||
import { AttendanceDevice } from '../entities/attendance-device.entity';
|
||||
import { AttendancePeriodConfig } from '../entities/attendance-period-config.entity';
|
||||
import { DingAttendanceRaw } from '../entities/ding-attendance-raw.entity';
|
||||
import { Class } from '../entities/class.entity';
|
||||
import { Student } from '../entities/student.entity';
|
||||
@@ -43,6 +45,7 @@ describe('AttendanceService — batchCreate', () => {
|
||||
const mockScheduleRepo = { find: jest.fn().mockResolvedValue([]) };
|
||||
const mockClassStudentRepo = { find: jest.fn().mockResolvedValue([]) };
|
||||
const mockStudentDingMappingRepo = { find: jest.fn().mockResolvedValue([]) };
|
||||
const mockAttendanceDeviceRepo = { find: jest.fn().mockResolvedValue([]) };
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
@@ -56,6 +59,8 @@ describe('AttendanceService — batchCreate', () => {
|
||||
{ provide: getRepositoryToken(ClassStudent), useValue: mockClassStudentRepo },
|
||||
{ provide: getRepositoryToken(ClassTeacher), useValue: { findOne: jest.fn() } },
|
||||
{ provide: getRepositoryToken(AttendanceSession), useValue: {} },
|
||||
{ provide: getRepositoryToken(AttendanceDevice), useValue: mockAttendanceDeviceRepo },
|
||||
{ provide: getRepositoryToken(AttendancePeriodConfig), useValue: {} },
|
||||
{ provide: getDataSourceToken(), useValue: { transaction: jest.fn() } },
|
||||
],
|
||||
}).compile();
|
||||
@@ -136,6 +141,8 @@ describe('AttendanceService — teacher DingTalk class scope', () => {
|
||||
classTeacherRepo as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -211,6 +218,8 @@ describe('AttendanceService — DingTalk raw query', () => {
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
|
||||
await expect(
|
||||
@@ -229,6 +238,107 @@ describe('AttendanceService — DingTalk raw query', () => {
|
||||
});
|
||||
|
||||
|
||||
describe('AttendanceService — attendance device display mappings', () => {
|
||||
function createHistoryQueryBuilder(records: AttendanceRecord[]) {
|
||||
return {
|
||||
leftJoinAndSelect: jest.fn().mockReturnThis(),
|
||||
andWhere: jest.fn().mockReturnThis(),
|
||||
orderBy: jest.fn().mockReturnThis(),
|
||||
addOrderBy: jest.fn().mockReturnThis(),
|
||||
skip: jest.fn().mockReturnThis(),
|
||||
take: jest.fn().mockReturnThis(),
|
||||
getManyAndCount: jest.fn().mockResolvedValue([records, records.length]),
|
||||
getMany: jest.fn().mockResolvedValue(records),
|
||||
};
|
||||
}
|
||||
|
||||
function createServiceWithRecords(records: AttendanceRecord[]) {
|
||||
const qb = createHistoryQueryBuilder(records);
|
||||
const attendanceRepo = { createQueryBuilder: jest.fn().mockReturnValue(qb) };
|
||||
const attendanceDeviceRepo = {
|
||||
find: jest.fn().mockImplementation(async (options: { where?: Record<string, unknown> }) => {
|
||||
if (options.where && 'deviceSn' in options.where) {
|
||||
return [
|
||||
{
|
||||
id: 1,
|
||||
deviceSn: 'ATM-01',
|
||||
deviceName: '东门考勤机',
|
||||
classroomId: 8,
|
||||
classroom: { id: 8, name: '一号教室' },
|
||||
status: 'disabled',
|
||||
},
|
||||
];
|
||||
}
|
||||
return [];
|
||||
}),
|
||||
};
|
||||
const service = new AttendanceService(
|
||||
attendanceRepo as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
attendanceDeviceRepo as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
return { service, qb, attendanceDeviceRepo };
|
||||
}
|
||||
|
||||
it('maps history list punch device ids to configured attendance device names', async () => {
|
||||
const record = {
|
||||
id: 1,
|
||||
classId: 8,
|
||||
status: 'present',
|
||||
source: 'dingtalk',
|
||||
punchSource: 'ATM',
|
||||
punchDeviceId: 'ATM-01',
|
||||
punchDeviceName: '钉钉原始设备名',
|
||||
} as AttendanceRecord;
|
||||
const { service, attendanceDeviceRepo } = createServiceWithRecords([record]);
|
||||
|
||||
await expect(service.findAll({}, [8])).resolves.toMatchObject({
|
||||
list: [
|
||||
{
|
||||
punchDeviceId: 'ATM-01',
|
||||
punchDeviceName: '东门考勤机 · 一号教室',
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
expect(attendanceDeviceRepo.find).toHaveBeenCalledWith({
|
||||
where: { deviceSn: expect.any(Object) },
|
||||
relations: ['classroom'],
|
||||
});
|
||||
});
|
||||
|
||||
it('maps exported punch device ids to configured attendance device names', async () => {
|
||||
const record = {
|
||||
id: 2,
|
||||
classId: 8,
|
||||
status: 'present',
|
||||
source: 'dingtalk',
|
||||
punchSource: 'ATM',
|
||||
punchDeviceId: 'ATM-01',
|
||||
punchDeviceName: '钉钉原始设备名',
|
||||
} as AttendanceRecord;
|
||||
const { service } = createServiceWithRecords([record]);
|
||||
|
||||
await expect(service.findAllForExport({}, [8])).resolves.toEqual([
|
||||
expect.objectContaining({
|
||||
punchDeviceId: 'ATM-01',
|
||||
punchDeviceName: '东门考勤机 · 一号教室',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
// ── Session serialization tests ──
|
||||
function deferred<T>(): {
|
||||
promise: Promise<T>;
|
||||
@@ -283,6 +393,8 @@ describe('AttendanceService — session serialization', () => {
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{ find: jest.fn().mockResolvedValue([]) } as never,
|
||||
{} as never,
|
||||
dataSourceMock as never,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,12 +4,15 @@ import { Repository, In, Between, LessThanOrEqual, MoreThanOrEqual, DataSource }
|
||||
import {
|
||||
AttendanceRecord,
|
||||
AttendanceSession,
|
||||
AttendanceDevice,
|
||||
AttendancePeriodConfig,
|
||||
DingAttendanceRaw,
|
||||
Class,
|
||||
Student,
|
||||
ClassSchedule,
|
||||
ClassStudent,
|
||||
ClassTeacher,
|
||||
TeacherRoleType,
|
||||
ScheduleType,
|
||||
StudentDingMapping,
|
||||
} from '../entities';
|
||||
@@ -23,6 +26,7 @@ import {
|
||||
UpdateAttendanceRecordDto,
|
||||
GenerateAttendanceFromSchedulesDto,
|
||||
GenerateFromSchedulesDto,
|
||||
SaveAttendancePeriodConfigsDto,
|
||||
} from './dto/attendance.dto';
|
||||
|
||||
/** Keyed mutex serializing operations on the same attendance session. */
|
||||
@@ -66,11 +70,80 @@ export class AttendanceService {
|
||||
private classTeacherRepo: Repository<ClassTeacher>,
|
||||
@InjectRepository(AttendanceSession)
|
||||
private attendanceSessionRepo: Repository<AttendanceSession>,
|
||||
@InjectRepository(AttendanceDevice)
|
||||
private attendanceDeviceRepo: Repository<AttendanceDevice>,
|
||||
@InjectRepository(AttendancePeriodConfig)
|
||||
private attendancePeriodConfigRepo: Repository<AttendancePeriodConfig>,
|
||||
private dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
private sessionMutex = new SessionMutex();
|
||||
|
||||
private readonly defaultAttendancePeriods = [
|
||||
{ periodKey: 'morning_reading', label: '早自习', startTime: '07:30', endTime: '08:30', sortOrder: 1 },
|
||||
{ periodKey: 'morning', label: '早课', startTime: '09:00', endTime: '12:00', sortOrder: 2 },
|
||||
{ periodKey: 'afternoon', label: '晚课', startTime: '14:00', endTime: '17:00', sortOrder: 3 },
|
||||
{ periodKey: 'evening_study', label: '晚自习', startTime: '18:30', endTime: '21:00', sortOrder: 4 },
|
||||
] as const;
|
||||
|
||||
private formatDeviceDetail(device: AttendanceDevice): string {
|
||||
const classroomName = device.classroom?.name;
|
||||
return classroomName ? `${device.deviceName} · ${classroomName}` : device.deviceName;
|
||||
}
|
||||
|
||||
private async attachAttendanceDeviceMappings<T extends AttendanceRecord>(
|
||||
records: T[],
|
||||
classroomId?: number | null,
|
||||
): Promise<T[]> {
|
||||
if (records.length === 0) return records;
|
||||
const sns = [...new Set(records.map((record) => record.punchDeviceId?.trim()).filter(Boolean) as string[])];
|
||||
const devicesBySn = new Map<string, AttendanceDevice>();
|
||||
if (sns.length > 0) {
|
||||
const devices = await this.attendanceDeviceRepo.find({
|
||||
where: { deviceSn: In(sns) },
|
||||
relations: ['classroom'],
|
||||
});
|
||||
for (const device of devices) devicesBySn.set(device.deviceSn, device);
|
||||
}
|
||||
|
||||
const classroomIds = [...new Set([
|
||||
...records.map((record) => record.classId).filter((id): id is number => id != null),
|
||||
...(classroomId != null ? [classroomId] : []),
|
||||
])];
|
||||
const devicesByClassroom = new Map<number, AttendanceDevice>();
|
||||
if (classroomIds.length > 0) {
|
||||
const devices = await this.attendanceDeviceRepo.find({
|
||||
where: { classroomId: In(classroomIds), status: 'active' },
|
||||
relations: ['classroom'],
|
||||
order: { id: 'ASC' },
|
||||
});
|
||||
for (const device of devices) {
|
||||
if (!devicesByClassroom.has(device.classroomId)) devicesByClassroom.set(device.classroomId, device);
|
||||
}
|
||||
}
|
||||
|
||||
for (const record of records) {
|
||||
const sn = record.punchDeviceId?.trim();
|
||||
const mappedBySn = sn ? devicesBySn.get(sn) : undefined;
|
||||
if (mappedBySn) {
|
||||
record.punchDeviceName = this.formatDeviceDetail(mappedBySn);
|
||||
record.punchDeviceId = mappedBySn.deviceSn;
|
||||
continue;
|
||||
}
|
||||
const source = (record.punchSource || '').trim().toUpperCase();
|
||||
const isMachine = ['ATM', 'ATTENDANCE_MACHINE', 'MACHINE', 'DEVICE'].some(
|
||||
(value) => source === value || source.includes(value),
|
||||
);
|
||||
const fallbackClassroomId = record.classId ?? classroomId ?? undefined;
|
||||
const mappedByClassroom = fallbackClassroomId ? devicesByClassroom.get(fallbackClassroomId) : undefined;
|
||||
if (isMachine && mappedByClassroom && !record.punchDeviceName) {
|
||||
record.punchDeviceName = this.formatDeviceDetail(mappedByClassroom);
|
||||
record.punchDeviceId = record.punchDeviceId || mappedByClassroom.deviceSn;
|
||||
}
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
async getAccessibleClassIds(userId: number, canManageAll = false): Promise<number[] | undefined> {
|
||||
if (canManageAll) return undefined;
|
||||
const assignments = await this.classTeacherRepo.find({ where: { userId } });
|
||||
@@ -83,6 +156,28 @@ export class AttendanceService {
|
||||
if (!assignment) throw new BadRequestException('只能访问自己任教班级的考勤');
|
||||
}
|
||||
|
||||
private isClassStudentActiveOnDate(classStudent: Pick<ClassStudent, 'joinDate' | 'leaveDate' | 'status'>, lessonDate: string): boolean {
|
||||
const status = classStudent.status ?? 'active';
|
||||
if (!['active', 'left'].includes(status)) return false;
|
||||
if (classStudent.joinDate && classStudent.joinDate > lessonDate) return false;
|
||||
if (classStudent.leaveDate && classStudent.leaveDate < lessonDate) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private async getClassStudentsForLesson(
|
||||
classId: number,
|
||||
lessonDate: string,
|
||||
relations: string[] = [],
|
||||
): Promise<ClassStudent[]> {
|
||||
const classStudents = await this.classStudentRepo.find({
|
||||
where: { classId, status: In(['active', 'left']) },
|
||||
relations,
|
||||
});
|
||||
return classStudents.filter((classStudent) =>
|
||||
this.isClassStudentActiveOnDate(classStudent, lessonDate),
|
||||
);
|
||||
}
|
||||
|
||||
/** List classes the current user may select for DingTalk attendance import. */
|
||||
async getImportableClasses(userId: number, isSuperAdmin = false) {
|
||||
if (isSuperAdmin) {
|
||||
@@ -113,6 +208,7 @@ export class AttendanceService {
|
||||
userId: number,
|
||||
classId: number,
|
||||
isSuperAdmin = false,
|
||||
lessonDate?: string,
|
||||
): Promise<string[]> {
|
||||
if (!isSuperAdmin) {
|
||||
const assignment = await this.classTeacherRepo.findOne({
|
||||
@@ -126,9 +222,11 @@ export class AttendanceService {
|
||||
if (!cls) throw new NotFoundException(`Class ${classId} not found`);
|
||||
}
|
||||
|
||||
const classStudents = await this.classStudentRepo.find({
|
||||
where: { classId, status: 'active' },
|
||||
});
|
||||
const classStudents = lessonDate
|
||||
? await this.getClassStudentsForLesson(classId, lessonDate)
|
||||
: await this.classStudentRepo.find({
|
||||
where: { classId, status: 'active' },
|
||||
});
|
||||
const studentIds = [...new Set(classStudents.map((item) => item.studentId))];
|
||||
if (studentIds.length === 0) {
|
||||
throw new BadRequestException('该班级暂无在读学生');
|
||||
@@ -172,27 +270,48 @@ export class AttendanceService {
|
||||
order: { studentId: 'ASC' },
|
||||
})
|
||||
: [];
|
||||
return { schedule, session, records };
|
||||
return { schedule, session, records: await this.attachAttendanceDeviceMappings(records, schedule.classId) };
|
||||
}
|
||||
|
||||
private getLessonAttendanceWindow(
|
||||
schedule: Pick<ClassSchedule, 'startTime' | 'endTime' | 'attendanceAdvanceMinutes'>,
|
||||
lessonDate: string,
|
||||
): { start: number; end: number; dateFrom: string; dateTo: string } {
|
||||
const startMinuteOfDay = this.toMinutes(schedule.startTime);
|
||||
const endMinuteOfDay = this.toMinutes(schedule.endTime);
|
||||
const advanceMinutes = Math.max(0, schedule.attendanceAdvanceMinutes ?? 30);
|
||||
const lessonStart = new Date(`${lessonDate}T${schedule.startTime}:00+08:00`).getTime();
|
||||
let lessonEnd = new Date(`${lessonDate}T${schedule.endTime}:00+08:00`).getTime();
|
||||
const overnight = endMinuteOfDay <= startMinuteOfDay;
|
||||
if (overnight) lessonEnd += 24 * 60 * 60 * 1000;
|
||||
|
||||
return {
|
||||
start: lessonStart - advanceMinutes * 60 * 1000,
|
||||
end: lessonEnd,
|
||||
dateFrom: advanceMinutes > startMinuteOfDay ? this.shiftDate(lessonDate, -1) : lessonDate,
|
||||
dateTo: overnight ? this.shiftDate(lessonDate, 1) : lessonDate,
|
||||
};
|
||||
}
|
||||
|
||||
getLessonAttendanceImportDateRange(
|
||||
schedule: Pick<ClassSchedule, 'startTime' | 'endTime' | 'attendanceAdvanceMinutes'>,
|
||||
lessonDate: string,
|
||||
): { startDate: string; endDate: string } {
|
||||
const window = this.getLessonAttendanceWindow(schedule, lessonDate);
|
||||
return { startDate: window.dateFrom, endDate: window.dateTo };
|
||||
}
|
||||
|
||||
private selectDingTalkRecordsForLesson(
|
||||
records: DingAttendanceRaw[],
|
||||
schedule: Pick<ClassSchedule, 'startTime' | 'endTime' | 'attendanceAdvanceMinutes'>,
|
||||
lessonDate: string,
|
||||
startTime: string,
|
||||
endTime: string,
|
||||
): DingAttendanceRaw[] {
|
||||
const [startHour, startMinute] = startTime.split(':').map(Number);
|
||||
const [endHour, endMinute] = endTime.split(':').map(Number);
|
||||
const start = new Date(`${lessonDate}T${startTime}:00+08:00`).getTime();
|
||||
let end = new Date(`${lessonDate}T${endTime}:00+08:00`).getTime();
|
||||
if (endHour * 60 + endMinute <= startHour * 60 + startMinute) end += 24 * 60 * 60 * 1000;
|
||||
const windowStart = start - 3 * 60 * 60 * 1000;
|
||||
const windowEnd = end + 3 * 60 * 60 * 1000;
|
||||
const timed = records.filter((record) => {
|
||||
const window = this.getLessonAttendanceWindow(schedule, lessonDate);
|
||||
return records.filter((record) => {
|
||||
// 上班、下班打卡都有效,按原始记录中实际存在的时间判断。
|
||||
const time = record.checkInTime ?? record.checkOutTime;
|
||||
return time && time.getTime() >= windowStart && time.getTime() <= windowEnd;
|
||||
return time && time.getTime() >= window.start && time.getTime() <= window.end;
|
||||
});
|
||||
return timed.length > 0 ? timed : records.filter((record) => !record.checkInTime && !record.checkOutTime);
|
||||
}
|
||||
|
||||
private mapDingTalkStatus(records: DingAttendanceRaw[], finalize = false): string {
|
||||
@@ -200,6 +319,53 @@ export class AttendanceService {
|
||||
if (hasPunch) return 'present';
|
||||
return finalize ? 'absent' : 'pending';
|
||||
}
|
||||
|
||||
private getLessonPunchMetadata(
|
||||
records: DingAttendanceRaw[],
|
||||
lessonDate: string,
|
||||
startTime: string,
|
||||
): Pick<AttendanceRecord, 'punchTime' | 'punchSource' | 'punchDeviceName' | 'punchDeviceId'> {
|
||||
const punches = records
|
||||
.map((record) => ({ record, time: record.checkInTime ?? record.checkOutTime }))
|
||||
.filter((item): item is { record: DingAttendanceRaw; time: Date } => !!item.time);
|
||||
if (punches.length === 0) {
|
||||
return {
|
||||
punchTime: null,
|
||||
punchSource: null,
|
||||
punchDeviceName: null,
|
||||
punchDeviceId: null,
|
||||
};
|
||||
}
|
||||
|
||||
const lessonStart = new Date(`${lessonDate}T${startTime}:00+08:00`).getTime();
|
||||
punches.sort(
|
||||
(left, right) =>
|
||||
Math.abs(left.time.getTime() - lessonStart) - Math.abs(right.time.getTime() - lessonStart),
|
||||
);
|
||||
const primary = punches[0];
|
||||
const metadataRecord = [...punches]
|
||||
.filter(({ record }) =>
|
||||
!!(record.punchSource || record.punchDeviceName || record.punchDeviceId) ||
|
||||
!['OnDuty', 'OffDuty'].includes(record.attendanceType),
|
||||
)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
Math.abs(left.time.getTime() - primary.time.getTime()) -
|
||||
Math.abs(right.time.getTime() - primary.time.getTime()),
|
||||
)[0]?.record;
|
||||
const source =
|
||||
metadataRecord?.punchSource ||
|
||||
(metadataRecord && !['OnDuty', 'OffDuty'].includes(metadataRecord.attendanceType)
|
||||
? metadataRecord.attendanceType
|
||||
: primary.record.punchSource);
|
||||
|
||||
return {
|
||||
punchTime: primary.time,
|
||||
punchSource: source || null,
|
||||
punchDeviceName: metadataRecord?.punchDeviceName || primary.record.punchDeviceName || null,
|
||||
punchDeviceId: metadataRecord?.punchDeviceId || primary.record.punchDeviceId || null,
|
||||
};
|
||||
}
|
||||
async createLessonAttendanceFromDingTalk(
|
||||
scheduleId: number,
|
||||
lessonDate: string,
|
||||
@@ -208,16 +374,13 @@ export class AttendanceService {
|
||||
) {
|
||||
const schedule = await this.getScheduleOccurrence(scheduleId, lessonDate);
|
||||
const now = new Date();
|
||||
const today = [
|
||||
now.getFullYear(),
|
||||
String(now.getMonth() + 1).padStart(2, '0'),
|
||||
String(now.getDate()).padStart(2, '0'),
|
||||
].join('-');
|
||||
const courseClock = this.getCourseClock(now);
|
||||
const today = courseClock.date;
|
||||
if (lessonDate > today) throw new BadRequestException('课程尚未开始,不能拉取考勤');
|
||||
if (lessonDate === today) {
|
||||
const [hour, minute] = schedule.startTime.split(':').map(Number);
|
||||
const startMinute = hour * 60 + minute;
|
||||
const currentMinute = now.getHours() * 60 + now.getMinutes();
|
||||
const currentMinute = courseClock.minutes;
|
||||
if (currentMinute < startMinute) {
|
||||
throw new BadRequestException('课程尚未开始,不能拉取考勤');
|
||||
}
|
||||
@@ -234,7 +397,7 @@ export class AttendanceService {
|
||||
relations: ['student'],
|
||||
order: { studentId: 'ASC' },
|
||||
});
|
||||
return { schedule, session: existing, records };
|
||||
return { schedule, session: existing, records: await this.attachAttendanceDeviceMappings(records, schedule.classId) };
|
||||
}
|
||||
if (existing.status !== 'in_progress' && !(finalize && existing.status === 'settling')) {
|
||||
throw new BadRequestException('课程考勤正在结算');
|
||||
@@ -244,20 +407,22 @@ export class AttendanceService {
|
||||
return this.dataSource.transaction(async (manager) => {
|
||||
const sessionRepo = manager.getRepository(AttendanceSession);
|
||||
const recordRepo = manager.getRepository(AttendanceRecord);
|
||||
const rawByStudent = await this.fetchDingTalkRawByStudent(schedule.classId!, lessonDate);
|
||||
const rawByStudent = await this.fetchDingTalkRawByStudent(schedule.classId!, schedule, lessonDate);
|
||||
const existingRecords = await recordRepo.find({
|
||||
where: { attendanceSessionId: existing.id },
|
||||
order: { studentId: 'ASC' },
|
||||
});
|
||||
const classStudents = await this.classStudentRepo.find({
|
||||
where: { classId: schedule.classId!, status: 'active' },
|
||||
relations: ['student'],
|
||||
});
|
||||
const classStudents = await this.getClassStudentsForLesson(
|
||||
schedule.classId!,
|
||||
lessonDate,
|
||||
['student'],
|
||||
);
|
||||
const studentsById = new Map(
|
||||
classStudents.map((classStudent) => [classStudent.studentId, classStudent.student]),
|
||||
);
|
||||
const existingStudentIds = new Set(existingRecords.map((record) => record.studentId));
|
||||
|
||||
const lessonSessionKey = this.mapLessonScheduleTimeToSession(schedule.startTime);
|
||||
const updatedRecords = existingRecords.map((record) => {
|
||||
record.student = studentsById.get(record.studentId)!;
|
||||
// Preserve manual corrections only while the lesson is still in progress.
|
||||
@@ -265,11 +430,15 @@ export class AttendanceService {
|
||||
|
||||
const raw = this.selectDingTalkRecordsForLesson(
|
||||
rawByStudent.get(record.studentId) ?? [],
|
||||
schedule,
|
||||
lessonDate,
|
||||
schedule.startTime,
|
||||
schedule.endTime,
|
||||
);
|
||||
record.status = this.mapDingTalkStatus(raw, finalize);
|
||||
Object.assign(record, this.getLessonPunchMetadata(
|
||||
raw,
|
||||
lessonDate,
|
||||
schedule.startTime,
|
||||
));
|
||||
record.remark = raw.some((item) => item.checkInTime || item.checkOutTime)
|
||||
? null
|
||||
: finalize
|
||||
@@ -281,9 +450,8 @@ export class AttendanceService {
|
||||
if (existingStudentIds.has(classStudent.studentId)) continue;
|
||||
const raw = this.selectDingTalkRecordsForLesson(
|
||||
rawByStudent.get(classStudent.studentId) ?? [],
|
||||
schedule,
|
||||
lessonDate,
|
||||
schedule.startTime,
|
||||
schedule.endTime,
|
||||
);
|
||||
updatedRecords.push(
|
||||
recordRepo.create({
|
||||
@@ -293,9 +461,14 @@ export class AttendanceService {
|
||||
scheduleId,
|
||||
attendanceSessionId: existing.id,
|
||||
attendanceDate: lessonDate,
|
||||
session: this.mapScheduleTimeToSession(schedule.startTime),
|
||||
session: lessonSessionKey,
|
||||
status: this.mapDingTalkStatus(raw, finalize),
|
||||
source: 'dingtalk',
|
||||
...this.getLessonPunchMetadata(
|
||||
raw,
|
||||
lessonDate,
|
||||
schedule.startTime,
|
||||
),
|
||||
remark: raw.some((item) => item.checkInTime || item.checkOutTime)
|
||||
? undefined
|
||||
: finalize
|
||||
@@ -312,7 +485,7 @@ export class AttendanceService {
|
||||
existing.completedAt = new Date();
|
||||
await sessionRepo.save(existing);
|
||||
}
|
||||
return { schedule, session: existing, records: saved };
|
||||
return { schedule, session: existing, records: await this.attachAttendanceDeviceMappings(saved, schedule.classId) };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -320,12 +493,13 @@ export class AttendanceService {
|
||||
return this.dataSource.transaction(async (manager) => {
|
||||
const sessionRepo = manager.getRepository(AttendanceSession);
|
||||
const recordRepo = manager.getRepository(AttendanceRecord);
|
||||
const rawByStudent = await this.fetchDingTalkRawByStudent(schedule.classId!, lessonDate);
|
||||
const rawByStudent = await this.fetchDingTalkRawByStudent(schedule.classId!, schedule, lessonDate);
|
||||
|
||||
const classStudents = await this.classStudentRepo.find({
|
||||
where: { classId: schedule.classId!, status: 'active' },
|
||||
relations: ['student'],
|
||||
});
|
||||
const classStudents = await this.getClassStudentsForLesson(
|
||||
schedule.classId!,
|
||||
lessonDate,
|
||||
['student'],
|
||||
);
|
||||
if (classStudents.length === 0) throw new BadRequestException('该班级暂无在读学生');
|
||||
|
||||
let session: AttendanceSession;
|
||||
@@ -355,18 +529,18 @@ export class AttendanceService {
|
||||
relations: ['student'],
|
||||
order: { studentId: 'ASC' },
|
||||
});
|
||||
return { schedule, session, records: existingRecords };
|
||||
return { schedule, session, records: await this.attachAttendanceDeviceMappings(existingRecords, schedule.classId) };
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const lessonSessionKey = this.mapLessonScheduleTimeToSession(schedule.startTime);
|
||||
const records = classStudents.map((classStudent) => {
|
||||
const raw = this.selectDingTalkRecordsForLesson(
|
||||
rawByStudent.get(classStudent.studentId) ?? [],
|
||||
schedule,
|
||||
lessonDate,
|
||||
schedule.startTime,
|
||||
schedule.endTime,
|
||||
);
|
||||
return recordRepo.create({
|
||||
studentId: classStudent.studentId,
|
||||
@@ -375,9 +549,14 @@ export class AttendanceService {
|
||||
scheduleId,
|
||||
attendanceSessionId: session.id,
|
||||
attendanceDate: lessonDate,
|
||||
session: this.mapScheduleTimeToSession(schedule.startTime),
|
||||
session: lessonSessionKey,
|
||||
status: this.mapDingTalkStatus(raw, finalize),
|
||||
source: 'dingtalk',
|
||||
...this.getLessonPunchMetadata(
|
||||
raw,
|
||||
lessonDate,
|
||||
schedule.startTime,
|
||||
),
|
||||
remark: raw.some((item) => item.checkInTime || item.checkOutTime)
|
||||
? undefined
|
||||
: finalize
|
||||
@@ -392,22 +571,22 @@ export class AttendanceService {
|
||||
session.completedAt = new Date();
|
||||
session = await sessionRepo.save(session);
|
||||
}
|
||||
return { schedule, session, records: saved };
|
||||
return { schedule, session, records: await this.attachAttendanceDeviceMappings(saved, schedule.classId) };
|
||||
});
|
||||
}
|
||||
|
||||
private async fetchDingTalkRawByStudent(
|
||||
classId: number,
|
||||
schedule: Pick<ClassSchedule, 'startTime' | 'endTime' | 'attendanceAdvanceMinutes'>,
|
||||
lessonDate: string,
|
||||
): Promise<Map<number, DingAttendanceRaw[]>> {
|
||||
const classStudents = await this.classStudentRepo.find({
|
||||
where: { classId, status: 'active' },
|
||||
});
|
||||
const classStudents = await this.getClassStudentsForLesson(classId, lessonDate);
|
||||
if (classStudents.length === 0) return new Map();
|
||||
const studentIds = classStudents.map((cs) => cs.studentId);
|
||||
const window = this.getLessonAttendanceWindow(schedule, lessonDate);
|
||||
const rawRecords = await this.dingRawRepo.find({
|
||||
where: {
|
||||
attendanceDate: lessonDate,
|
||||
attendanceDate: Between(window.dateFrom, window.dateTo),
|
||||
matchedStudentId: In(studentIds),
|
||||
},
|
||||
});
|
||||
@@ -437,7 +616,7 @@ export class AttendanceService {
|
||||
relations: ['student'],
|
||||
order: { studentId: 'ASC' },
|
||||
});
|
||||
return { session, records };
|
||||
return { session, records: await this.attachAttendanceDeviceMappings(records, session.classId) };
|
||||
}
|
||||
|
||||
const pendingRecords = await recordRepo.count({
|
||||
@@ -456,7 +635,7 @@ export class AttendanceService {
|
||||
relations: ['student'],
|
||||
order: { studentId: 'ASC' },
|
||||
});
|
||||
return { session: savedSession, records };
|
||||
return { session: savedSession, records: await this.attachAttendanceDeviceMappings(records, session.classId) };
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -514,7 +693,7 @@ export class AttendanceService {
|
||||
});
|
||||
|
||||
const classStudents = await this.classStudentRepo.find({
|
||||
where: { classId, status: 'active' },
|
||||
where: { classId, status: In(['active', 'left']) },
|
||||
relations: ['student'],
|
||||
});
|
||||
|
||||
@@ -539,8 +718,11 @@ export class AttendanceService {
|
||||
if (sched.weekDay !== weekDay) continue;
|
||||
if (dateStr < sched.startDate || dateStr > sched.endDate) continue;
|
||||
|
||||
const session = this.mapScheduleTimeToSession(sched.startTime);
|
||||
for (const cs of classStudents) {
|
||||
const session = await this.mapScheduleTimeToSession(sched.startTime);
|
||||
const classStudentsForDate = classStudents.filter((cs) =>
|
||||
this.isClassStudentActiveOnDate(cs, dateStr),
|
||||
);
|
||||
for (const cs of classStudentsForDate) {
|
||||
const key = `${cs.studentId}|${dateStr}|${session}`;
|
||||
if (existingKeys.has(key)) continue;
|
||||
|
||||
@@ -589,7 +771,126 @@ export class AttendanceService {
|
||||
});
|
||||
}
|
||||
|
||||
private mapScheduleTimeToSession(startTime: string): string {
|
||||
private toMinutes(time: string): number {
|
||||
const [hour, minute] = time.split(':').map(Number);
|
||||
return hour * 60 + minute;
|
||||
}
|
||||
|
||||
private getCourseClock(date: Date): { date: string; minutes: number } {
|
||||
const parts = Object.fromEntries(
|
||||
new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric', month: '2-digit', day: '2-digit',
|
||||
hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
|
||||
}).formatToParts(date).filter((part) => part.type !== 'literal').map((part) => [part.type, part.value]),
|
||||
);
|
||||
return {
|
||||
date: `${parts.year}-${parts.month}-${parts.day}`,
|
||||
minutes: Number(parts.hour) * 60 + Number(parts.minute),
|
||||
};
|
||||
}
|
||||
|
||||
private shiftDate(date: string, days: number): string {
|
||||
const shifted = new Date(`${date}T00:00:00.000Z`);
|
||||
shifted.setUTCDate(shifted.getUTCDate() + days);
|
||||
return shifted.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
private async ensureAttendancePeriodConfigs() {
|
||||
const count = await this.attendancePeriodConfigRepo.count();
|
||||
if (count === 0) {
|
||||
await this.attendancePeriodConfigRepo.save(
|
||||
this.defaultAttendancePeriods.map((period) => this.attendancePeriodConfigRepo.create({
|
||||
...period,
|
||||
enabled: true,
|
||||
})),
|
||||
);
|
||||
}
|
||||
return this.attendancePeriodConfigRepo.find({ order: { sortOrder: 'ASC', id: 'ASC' } });
|
||||
}
|
||||
|
||||
async getAttendancePeriodConfigs() {
|
||||
return this.ensureAttendancePeriodConfigs();
|
||||
}
|
||||
|
||||
async getRefreshableSchedules(date: string, classId?: number, session?: string, accessibleClassIds?: number[]) {
|
||||
const parsedDate = new Date(`${date}T00:00:00`);
|
||||
if (Number.isNaN(parsedDate.getTime())) throw new BadRequestException('无效日期');
|
||||
const weekDay = parsedDate.getDay() === 0 ? 7 : parsedDate.getDay();
|
||||
const qb = this.scheduleRepo
|
||||
.createQueryBuilder('schedule')
|
||||
.where('schedule.scheduleType = :scheduleType', { scheduleType: ScheduleType.INTERNAL })
|
||||
.andWhere('schedule.status = :status', { status: 'active' })
|
||||
.andWhere('schedule.classId IS NOT NULL')
|
||||
.andWhere('schedule.weekDay = :weekDay', { weekDay })
|
||||
.andWhere('schedule.startDate <= :date', { date })
|
||||
.andWhere('schedule.endDate >= :date', { date });
|
||||
|
||||
if (classId) {
|
||||
qb.andWhere('schedule.classId = :classId', { classId });
|
||||
} else if (accessibleClassIds) {
|
||||
if (accessibleClassIds.length === 0) return [];
|
||||
qb.andWhere('schedule.classId IN (:...accessibleClassIds)', { accessibleClassIds });
|
||||
}
|
||||
|
||||
const schedules = await qb.orderBy('schedule.startTime', 'ASC').getMany();
|
||||
if (!session) return schedules;
|
||||
|
||||
const matchedSchedules: ClassSchedule[] = [];
|
||||
for (const schedule of schedules) {
|
||||
if ((await this.mapScheduleTimeToSession(schedule.startTime)) === session) {
|
||||
matchedSchedules.push(schedule);
|
||||
}
|
||||
}
|
||||
return matchedSchedules;
|
||||
}
|
||||
|
||||
async saveAttendancePeriodConfigs(dto: SaveAttendancePeriodConfigsDto) {
|
||||
const seen = new Set<string>();
|
||||
const normalized = dto.periods.map((period, index) => {
|
||||
const periodKey = period.periodKey.trim();
|
||||
const label = period.label.trim();
|
||||
if (!periodKey || !label) throw new BadRequestException('时段标识和名称不能为空');
|
||||
if (seen.has(periodKey)) throw new BadRequestException(`时段标识 ${periodKey} 重复`);
|
||||
seen.add(periodKey);
|
||||
if (this.toMinutes(period.endTime) <= this.toMinutes(period.startTime)) {
|
||||
throw new BadRequestException(`${label} 的结束时间必须晚于开始时间`);
|
||||
}
|
||||
return {
|
||||
periodKey,
|
||||
label,
|
||||
startTime: period.startTime,
|
||||
endTime: period.endTime,
|
||||
sortOrder: period.sortOrder ?? index + 1,
|
||||
enabled: period.enabled ?? true,
|
||||
};
|
||||
}).sort((left, right) => left.sortOrder - right.sortOrder);
|
||||
|
||||
// 按开始时间排序后再检查重叠,避免 sortOrder 与时间顺序不一致时漏检
|
||||
const sortedByTime = [...normalized].sort(
|
||||
(left, right) => this.toMinutes(left.startTime) - this.toMinutes(right.startTime),
|
||||
);
|
||||
for (let index = 1; index < sortedByTime.length; index += 1) {
|
||||
const previous = sortedByTime[index - 1];
|
||||
const current = sortedByTime[index];
|
||||
if (previous.enabled && current.enabled && this.toMinutes(current.startTime) < this.toMinutes(previous.endTime)) {
|
||||
throw new BadRequestException(`${previous.label} 和 ${current.label} 时间段不能重叠`);
|
||||
}
|
||||
}
|
||||
|
||||
await this.attendancePeriodConfigRepo.clear();
|
||||
await this.attendancePeriodConfigRepo.save(
|
||||
normalized.map((period) => this.attendancePeriodConfigRepo.create(period)),
|
||||
);
|
||||
return this.getAttendancePeriodConfigs();
|
||||
}
|
||||
|
||||
async resetAttendancePeriodConfigs() {
|
||||
await this.attendancePeriodConfigRepo.clear();
|
||||
return this.ensureAttendancePeriodConfigs();
|
||||
}
|
||||
|
||||
private mapLessonScheduleTimeToSession(startTime: string): string {
|
||||
const hour = parseInt(startTime.slice(0, 2), 10);
|
||||
if (hour < 8) return 'morning_reading';
|
||||
if (hour < 12) return 'morning';
|
||||
@@ -598,15 +899,31 @@ export class AttendanceService {
|
||||
return 'night_check';
|
||||
}
|
||||
|
||||
private async mapScheduleTimeToSession(startTime: string): Promise<string> {
|
||||
const startMinutes = this.toMinutes(startTime);
|
||||
const periods = (await this.ensureAttendancePeriodConfigs()).filter((period) => period.enabled);
|
||||
const matched = periods.find((period) => {
|
||||
const periodStart = this.toMinutes(period.startTime);
|
||||
const periodEnd = this.toMinutes(period.endTime);
|
||||
return startMinutes >= periodStart && startMinutes < periodEnd;
|
||||
});
|
||||
if (matched) return matched.periodKey;
|
||||
throw new BadRequestException(`课程开始时间 ${startTime} 未匹配到考勤时段,请先配置考勤时段`);
|
||||
}
|
||||
|
||||
|
||||
// ── Attendance summary ──
|
||||
async getSummary(query: AttendanceSummaryQueryDto, accessibleClassIds?: number[]) {
|
||||
const qb = this.attendanceRepo.createQueryBuilder('ar');
|
||||
if (query.classId) {
|
||||
qb.andWhere('ar.classId = :classId', { classId: query.classId });
|
||||
} else if (accessibleClassIds) {
|
||||
}
|
||||
if (query.scheduleId) {
|
||||
qb.andWhere('ar.scheduleId = :scheduleId', { scheduleId: query.scheduleId });
|
||||
}
|
||||
if (!query.classId && accessibleClassIds) {
|
||||
if (accessibleClassIds.length === 0)
|
||||
return { total: 0, present: 0, late: 0, absent: 0, leave: 0, presentRate: 0 };
|
||||
return { total: 0, present: 0, late: 0, absent: 0, leave: 0, pending: 0, presentRate: 0 };
|
||||
qb.andWhere('ar.classId IN (:...accessibleClassIds)', { accessibleClassIds });
|
||||
}
|
||||
if (query.dateFrom) {
|
||||
@@ -615,6 +932,9 @@ export class AttendanceService {
|
||||
if (query.dateTo) {
|
||||
qb.andWhere('ar.attendanceDate <= :dateTo', { dateTo: query.dateTo });
|
||||
}
|
||||
if (query.session) {
|
||||
qb.andWhere('ar.session = :session', { session: query.session });
|
||||
}
|
||||
|
||||
const rows = await qb.getMany();
|
||||
|
||||
@@ -623,9 +943,10 @@ export class AttendanceService {
|
||||
const late = rows.filter((r) => r.status === 'late').length;
|
||||
const absent = rows.filter((r) => r.status === 'absent').length;
|
||||
const leave = rows.filter((r) => r.status === 'leave').length;
|
||||
const pending = rows.filter((r) => r.status === 'pending').length;
|
||||
const presentRate = total > 0 ? Number(((present / total) * 100).toFixed(1)) : 0;
|
||||
|
||||
return { total, present, late, absent, leave, presentRate };
|
||||
return { total, present, late, absent, leave, pending, presentRate };
|
||||
}
|
||||
|
||||
// ── Attendance calendar ──
|
||||
@@ -647,6 +968,47 @@ export class AttendanceService {
|
||||
return this.buildCalendar(classId, weekStart);
|
||||
}
|
||||
|
||||
private getWeekDayForDate(date: string): number {
|
||||
const day = new Date(`${date}T00:00:00+08:00`).getUTCDay();
|
||||
return day === 0 ? 7 : day;
|
||||
}
|
||||
|
||||
async getScheduleOptionsForAttendance(classId: number, date: string) {
|
||||
const weekDay = this.getWeekDayForDate(date);
|
||||
const { entities, raw } = await this.scheduleRepo
|
||||
.createQueryBuilder('cs')
|
||||
.leftJoin('cs.teacher', 'teacher')
|
||||
.addSelect('cs.id', 'scheduleIdForTeacherMap')
|
||||
.addSelect('teacher.username', 'teacherUsername')
|
||||
.addSelect('teacher.name', 'teacherName')
|
||||
.where('cs.classId = :classId', { classId })
|
||||
.andWhere('cs.weekDay = :weekDay', { weekDay })
|
||||
.andWhere('cs.startDate <= :date', { date })
|
||||
.andWhere('cs.endDate >= :date', { date })
|
||||
.andWhere('cs.status = :status', { status: 'active' })
|
||||
.orderBy('cs.startTime', 'ASC')
|
||||
.addOrderBy('cs.subject', 'ASC')
|
||||
.getRawAndEntities();
|
||||
|
||||
const teacherByScheduleId = new Map(
|
||||
raw.map((row) => [
|
||||
Number(row.scheduleIdForTeacherMap),
|
||||
{
|
||||
teacherName: row.teacherName || null,
|
||||
teacherUsername: row.teacherUsername || null,
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
return entities.map((schedule) => {
|
||||
const teacher = teacherByScheduleId.get(schedule.id) ?? {
|
||||
teacherName: null,
|
||||
teacherUsername: null,
|
||||
};
|
||||
return { ...schedule, ...teacher };
|
||||
});
|
||||
}
|
||||
|
||||
private async buildCalendar(classId: number, weekStart: string) {
|
||||
// Compute weekEnd (Sunday = weekStart + 6 days)
|
||||
const start = new Date(weekStart);
|
||||
@@ -742,7 +1104,7 @@ export class AttendanceService {
|
||||
qb.skip((page - 1) * pageSize).take(pageSize);
|
||||
|
||||
const [list, total] = await qb.getManyAndCount();
|
||||
return { list, total, page, pageSize };
|
||||
return { list: await this.attachAttendanceDeviceMappings(list), total, page, pageSize };
|
||||
}
|
||||
|
||||
// ── Get distinct classes with attendance records ──
|
||||
@@ -760,9 +1122,51 @@ export class AttendanceService {
|
||||
if (classIds.length === 0) return [];
|
||||
|
||||
const where = { id: In(classIds) };
|
||||
const classes = await this.classRepo.find({ where });
|
||||
const [classes, teachers] = await Promise.all([
|
||||
this.classRepo.find({ where }),
|
||||
this.classTeacherRepo.find({
|
||||
where: {
|
||||
classId: In(classIds),
|
||||
roleType: In([
|
||||
TeacherRoleType.HEAD_TEACHER,
|
||||
TeacherRoleType.LIFE_TEACHER,
|
||||
TeacherRoleType.SUBJECT_TEACHER,
|
||||
]),
|
||||
},
|
||||
relations: ['user'],
|
||||
order: { roleType: 'ASC', id: 'ASC' },
|
||||
}),
|
||||
]);
|
||||
const nameMap = new Map(classes.map((c) => [c.id, c.name]));
|
||||
return classIds.map((id) => ({ classId: id, className: nameMap.get(id) || `班级${id}` }));
|
||||
const teacherMap = new Map<
|
||||
number,
|
||||
Array<{
|
||||
userId: number;
|
||||
username: string | null;
|
||||
name: string | null;
|
||||
roleType: string;
|
||||
subject: string | null;
|
||||
}>
|
||||
>();
|
||||
|
||||
for (const teacher of teachers) {
|
||||
const user = teacher.user as { username?: string | null; name?: string | null } | undefined;
|
||||
const items = teacherMap.get(teacher.classId) ?? [];
|
||||
items.push({
|
||||
userId: teacher.userId,
|
||||
username: user?.username || null,
|
||||
name: user?.name || null,
|
||||
roleType: teacher.roleType,
|
||||
subject: teacher.subject || null,
|
||||
});
|
||||
teacherMap.set(teacher.classId, items);
|
||||
}
|
||||
|
||||
return classIds.map((id) => ({
|
||||
classId: id,
|
||||
className: nameMap.get(id) || `班级${id}`,
|
||||
teachers: teacherMap.get(id) ?? [],
|
||||
}));
|
||||
}
|
||||
|
||||
// ── DingAttendance raw records ──
|
||||
@@ -853,6 +1257,7 @@ export class AttendanceService {
|
||||
async findAllForExport(
|
||||
query: {
|
||||
classId?: number;
|
||||
scheduleId?: number;
|
||||
dateFrom?: string;
|
||||
dateTo?: string;
|
||||
session?: string;
|
||||
@@ -864,6 +1269,9 @@ export class AttendanceService {
|
||||
const qb = this.attendanceRepo.createQueryBuilder('ar');
|
||||
|
||||
qb.leftJoinAndSelect('ar.student', 'student').leftJoinAndSelect('ar.class', 'class');
|
||||
if (query.scheduleId) {
|
||||
qb.andWhere('ar.scheduleId = :scheduleId', { scheduleId: query.scheduleId });
|
||||
}
|
||||
if (query.classId) {
|
||||
qb.andWhere('ar.classId = :classId', { classId: query.classId });
|
||||
} else if (accessibleClassIds) {
|
||||
@@ -888,7 +1296,8 @@ export class AttendanceService {
|
||||
|
||||
qb.orderBy('ar.attendanceDate', 'DESC').addOrderBy('ar.createdAt', 'DESC');
|
||||
|
||||
return qb.getMany();
|
||||
const records = await qb.getMany();
|
||||
return this.attachAttendanceDeviceMappings(records);
|
||||
}
|
||||
|
||||
async findAttendanceRecord(id: number) {
|
||||
@@ -908,6 +1317,10 @@ export class AttendanceService {
|
||||
if (dto.status !== undefined) {
|
||||
record.status = dto.status;
|
||||
record.source = 'manual';
|
||||
record.punchTime = null;
|
||||
record.punchSource = null;
|
||||
record.punchDeviceName = null;
|
||||
record.punchDeviceId = null;
|
||||
}
|
||||
if (dto.remark !== undefined) {
|
||||
record.remark = dto.remark;
|
||||
@@ -933,6 +1346,10 @@ export class AttendanceService {
|
||||
if (dto.status !== undefined) {
|
||||
freshRecord.status = dto.status;
|
||||
freshRecord.source = 'manual';
|
||||
freshRecord.punchTime = null;
|
||||
freshRecord.punchSource = null;
|
||||
freshRecord.punchDeviceName = null;
|
||||
freshRecord.punchDeviceId = null;
|
||||
}
|
||||
if (dto.remark !== undefined) {
|
||||
freshRecord.remark = dto.remark;
|
||||
|
||||
@@ -68,8 +68,10 @@ describe('DingTalkService — attendance records', () => {
|
||||
userId: 'ding-1',
|
||||
workDate: Date.parse('2026-07-12T00:00:00+08:00'),
|
||||
userCheckTime: Date.parse('2026-07-12T21:05:00+08:00'),
|
||||
sourceType: 'USER',
|
||||
sourceType: 'ATM',
|
||||
checkType: 'OnDuty',
|
||||
deviceName: '东门考勤机',
|
||||
deviceId: 'ATM-01',
|
||||
timeResult: 'Normal',
|
||||
},
|
||||
],
|
||||
@@ -83,6 +85,13 @@ describe('DingTalkService — attendance records', () => {
|
||||
});
|
||||
|
||||
expect(record.workDate).toBe('2026-07-12');
|
||||
expect(record).toEqual(
|
||||
expect.objectContaining({
|
||||
checkType: 'OnDuty',
|
||||
sourceType: 'ATM',
|
||||
deviceName: '东门考勤机',
|
||||
deviceId: 'ATM-01',
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -3,13 +3,53 @@ import {
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsInt,
|
||||
IsBoolean,
|
||||
IsDateString,
|
||||
IsIn,
|
||||
ValidateNested,
|
||||
IsNotEmpty,
|
||||
ArrayNotEmpty,
|
||||
Matches,
|
||||
Max,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
|
||||
export class AttendancePeriodConfigItemDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
periodKey: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
label: string;
|
||||
|
||||
@IsString()
|
||||
@Matches(/^([01]\d|2[0-3]):[0-5]\d$/)
|
||||
startTime: string;
|
||||
|
||||
@IsString()
|
||||
@Matches(/^([01]\d|2[0-3]):[0-5]\d$/)
|
||||
endTime: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
sortOrder?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export class SaveAttendancePeriodConfigsDto {
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => AttendancePeriodConfigItemDto)
|
||||
periods: AttendancePeriodConfigItemDto[];
|
||||
}
|
||||
|
||||
export class AttendanceRecordItem {
|
||||
@IsInt()
|
||||
@IsNotEmpty()
|
||||
@@ -24,7 +64,7 @@ export class AttendanceRecordItem {
|
||||
attendanceDate: string;
|
||||
|
||||
@IsString()
|
||||
@IsIn(['morning_reading', 'morning', 'afternoon', 'evening_study', 'night_check'])
|
||||
@IsIn(['morning_reading', 'morning', 'afternoon', 'evening_study', 'night_check'])
|
||||
@IsNotEmpty()
|
||||
session: string;
|
||||
|
||||
@@ -44,6 +84,7 @@ export class AttendanceRecordItem {
|
||||
|
||||
export class BatchCreateAttendanceDto {
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => AttendanceRecordItem)
|
||||
records: AttendanceRecordItem[];
|
||||
@@ -55,6 +96,11 @@ export class AttendanceSummaryQueryDto {
|
||||
@Type(() => Number)
|
||||
classId?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Type(() => Number)
|
||||
scheduleId?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
dateFrom?: string;
|
||||
@@ -62,6 +108,26 @@ export class AttendanceSummaryQueryDto {
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
dateTo?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
session?: string;
|
||||
}
|
||||
|
||||
|
||||
export class RefreshDingTalkAttendanceDto {
|
||||
@IsDateString()
|
||||
@IsNotEmpty()
|
||||
date: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Type(() => Number)
|
||||
classId?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
session?: string;
|
||||
}
|
||||
|
||||
export class AttendanceCalendarQueryDto {
|
||||
@@ -96,15 +162,29 @@ export class QueryDingRawDto {
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Type(() => Number)
|
||||
page?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(200)
|
||||
@Type(() => Number)
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export class AttendanceScheduleOptionsQueryDto {
|
||||
@IsInt()
|
||||
@Type(() => Number)
|
||||
@IsNotEmpty()
|
||||
classId: number;
|
||||
|
||||
@IsDateString()
|
||||
@IsNotEmpty()
|
||||
date: string;
|
||||
}
|
||||
|
||||
export class QueryAttendanceRecordsDto {
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@@ -130,7 +210,7 @@ export class QueryAttendanceRecordsDto {
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsIn(['present', 'late', 'absent', 'leave'])
|
||||
@IsIn(['present', 'late', 'absent', 'leave', 'pending'])
|
||||
status?: string;
|
||||
|
||||
@IsOptional()
|
||||
@@ -139,11 +219,14 @@ export class QueryAttendanceRecordsDto {
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Type(() => Number)
|
||||
page?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(200)
|
||||
@Type(() => Number)
|
||||
pageSize?: number;
|
||||
}
|
||||
@@ -165,6 +248,22 @@ export class UpdateAttendanceRecordDto {
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
|
||||
export class AttendanceAlertsQueryDto {
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(365)
|
||||
days?: number;
|
||||
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
threshold?: number;
|
||||
}
|
||||
|
||||
export class AttendanceReportQueryDto {
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthService — super admin identity', () => {
|
||||
describe('AuthService — authentication boundaries', () => {
|
||||
it('marks the preset 超管 role as super admin in the JWT payload', async () => {
|
||||
const userRepo = {
|
||||
findOne: jest.fn().mockResolvedValue({
|
||||
@@ -22,8 +22,29 @@ describe('AuthService — super admin identity', () => {
|
||||
|
||||
await service.login({ username: 'admin', password: 'secret' }, '127.0.0.1');
|
||||
|
||||
expect(jwtService.sign).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ isSuperAdmin: true }),
|
||||
expect(jwtService.sign).toHaveBeenCalledWith(expect.objectContaining({ isSuperAdmin: true }));
|
||||
});
|
||||
it('rejects an archived user even when the password is valid', async () => {
|
||||
const userRepo = {
|
||||
findOne: jest.fn().mockResolvedValue({
|
||||
id: 2,
|
||||
username: 'archived',
|
||||
passwordHash: await bcrypt.hash('secret', 4),
|
||||
isActive: true,
|
||||
isArchived: true,
|
||||
roles: [],
|
||||
}),
|
||||
save: jest.fn(),
|
||||
};
|
||||
const service = new AuthService(
|
||||
userRepo as never,
|
||||
{ sign: jest.fn() } as never,
|
||||
{ getUserPermissions: jest.fn() } as never,
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.login({ username: 'archived', password: 'secret' }, '192.0.2.10'),
|
||||
).rejects.toThrow('账号已失效');
|
||||
expect(userRepo.save).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -38,7 +38,9 @@ export class AuthService {
|
||||
this.recordFailedAttempt(attemptKey);
|
||||
throw new UnauthorizedException('用户名或密码错误');
|
||||
}
|
||||
if (!user.isActive) throw new UnauthorizedException('账号已被禁用,请联系管理员');
|
||||
if (!user.isActive || user.isArchived) {
|
||||
throw new UnauthorizedException('账号已失效,请联系管理员');
|
||||
}
|
||||
const valid = await bcrypt.compare(dto.password, user.passwordHash);
|
||||
if (!valid) {
|
||||
this.recordFailedAttempt(attemptKey);
|
||||
|
||||
@@ -33,6 +33,23 @@ describe('JwtStrategy', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('recognizes the canonical super_admin role code even when the display name changes', async () => {
|
||||
const userRepo = {
|
||||
findOne: jest.fn().mockResolvedValue({
|
||||
id: 1,
|
||||
username: 'admin',
|
||||
isActive: true,
|
||||
isArchived: false,
|
||||
roles: [{ name: '系统管理员', code: 'super_admin', status: 1, permissions: [] }],
|
||||
}),
|
||||
};
|
||||
const strategy = new JwtStrategy(config as never, userRepo as never);
|
||||
|
||||
await expect(strategy.validate({ sub: 1 })).resolves.toEqual(
|
||||
expect.objectContaining({ isSuperAdmin: true }),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ id: 7, isActive: false, isArchived: false, roles: [] }],
|
||||
[{ id: 7, isActive: true, isArchived: true, roles: [] }],
|
||||
|
||||
@@ -47,7 +47,9 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
for (const role of user.roles ?? []) {
|
||||
if (role.status !== 1) continue;
|
||||
roles.push(role.name);
|
||||
if (role.name === '超管' || role.name === 'super_admin') isSuperAdmin = true;
|
||||
if (role.name === '超管' || role.name === 'super_admin' || role.code === 'super_admin') {
|
||||
isSuperAdmin = true;
|
||||
}
|
||||
for (const permission of role.permissions ?? []) permissions.add(permission.code);
|
||||
}
|
||||
|
||||
|
||||
@@ -34,20 +34,6 @@ export class BillsExportService {
|
||||
if (query.status) qb.andWhere('b.status = :status', { status: query.status });
|
||||
const bills = await qb.getMany();
|
||||
|
||||
// 查询涉及学生的"已缴未退"押金,用于导出押金抵扣字段
|
||||
const studentIds = Array.from(new Set(bills.map((b) => b.studentId)));
|
||||
const depMap = new Map<number, number>();
|
||||
if (studentIds.length > 0) {
|
||||
const deposits = await this.depositRepo
|
||||
.createQueryBuilder('d')
|
||||
.where('d.studentId IN (:...ids)', { ids: studentIds })
|
||||
.andWhere('d.status = :status', { status: 'paid' })
|
||||
.getMany();
|
||||
for (const d of deposits) {
|
||||
depMap.set(d.studentId, (depMap.get(d.studentId) || 0) + Number(d.amount || 0));
|
||||
}
|
||||
}
|
||||
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
workbook.creator = '恭学教育基地管理系统';
|
||||
|
||||
@@ -60,9 +46,8 @@ export class BillsExportService {
|
||||
{ header: '分摊费用', key: 'shared', width: 12 },
|
||||
{ header: '个人费用', key: 'personal', width: 12 },
|
||||
{ header: '总金额', key: 'total', width: 12 },
|
||||
{ header: '可用押金', key: 'deposit', width: 12 },
|
||||
{ header: '押金抵扣', key: 'depositApplied', width: 12 },
|
||||
{ header: '抵扣后应付', key: 'afterDeposit', width: 14 },
|
||||
{ header: '已扣余额', key: 'paidAmount', width: 12 },
|
||||
{ header: '待补缴', key: 'outstandingAmount', width: 12 },
|
||||
{ header: '状态', key: 'status', width: 10 },
|
||||
{ header: '生成时间', key: 'generatedAt', width: 20 },
|
||||
];
|
||||
@@ -71,15 +56,13 @@ export class BillsExportService {
|
||||
ws.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
|
||||
|
||||
const statusMap: Record<string, string> = {
|
||||
draft: '草稿',
|
||||
confirmed: '已确认',
|
||||
unpaid: '待支付',
|
||||
partially_paid: '部分支付',
|
||||
paid: '已结清',
|
||||
cancelled: '已取消',
|
||||
};
|
||||
for (const bill of bills) {
|
||||
const total = Number(bill.totalAmount || 0);
|
||||
const dep = Number((depMap.get(bill.studentId) || 0).toFixed(2));
|
||||
const applied = Number(Math.min(dep, total).toFixed(2));
|
||||
const after = Number(Math.max(0, total - applied).toFixed(2));
|
||||
ws.addRow({
|
||||
id: bill.id,
|
||||
studentName: (bill as any).student?.name || '-',
|
||||
@@ -87,9 +70,8 @@ export class BillsExportService {
|
||||
shared: Number(bill.sharedAmount),
|
||||
personal: Number(bill.personalAmount),
|
||||
total,
|
||||
deposit: dep,
|
||||
depositApplied: applied,
|
||||
afterDeposit: after,
|
||||
paidAmount: Number(bill.paidAmount || 0),
|
||||
outstandingAmount: Number(bill.outstandingAmount || 0),
|
||||
status: statusMap[bill.status] || bill.status,
|
||||
generatedAt: bill.generatedAt ? new Date(bill.generatedAt).toLocaleString('zh-CN') : '',
|
||||
});
|
||||
@@ -147,16 +129,9 @@ export class BillsExportService {
|
||||
return;
|
||||
}
|
||||
|
||||
// 查询该学生的可用押金(已缴未退)
|
||||
const deposits = await this.depositRepo
|
||||
.createQueryBuilder('d')
|
||||
.where('d.studentId = :sid', { sid: bill.studentId })
|
||||
.andWhere('d.status = :status', { status: 'paid' })
|
||||
.getMany();
|
||||
const availableDeposit = deposits.reduce((s, d) => s + Number(d.amount || 0), 0);
|
||||
const totalAmount = Number(bill.totalAmount || 0);
|
||||
const depositApplied = Math.min(availableDeposit, totalAmount);
|
||||
const amountAfterDeposit = Math.max(0, totalAmount - depositApplied);
|
||||
const paidAmount = Number(bill.paidAmount || 0);
|
||||
const outstandingAmount = Number(bill.outstandingAmount || 0);
|
||||
|
||||
const doc = new PDFDocument({ size: 'A4', margin: 50 });
|
||||
res.setHeader('Content-Type', 'application/pdf');
|
||||
@@ -191,9 +166,10 @@ export class BillsExportService {
|
||||
}
|
||||
|
||||
const statusMap: Record<string, string> = {
|
||||
draft: '草稿',
|
||||
confirmed: '已确认',
|
||||
unpaid: '待支付',
|
||||
partially_paid: '部分支付',
|
||||
paid: '已结清',
|
||||
cancelled: '已取消',
|
||||
};
|
||||
|
||||
// 标题
|
||||
@@ -223,20 +199,8 @@ export class BillsExportService {
|
||||
.fillColor('#007AFF')
|
||||
.text(`应付总额: ¥${totalAmount.toFixed(2)}`);
|
||||
doc.moveDown(0.3);
|
||||
if (availableDeposit > 0) {
|
||||
doc
|
||||
.fontSize(11)
|
||||
.fillColor('#52C41A')
|
||||
.text(`可用押金: ¥${availableDeposit.toFixed(2)}`);
|
||||
doc
|
||||
.fontSize(11)
|
||||
.fillColor('#FA8C16')
|
||||
.text(`押金抵扣: -¥${depositApplied.toFixed(2)}`);
|
||||
doc
|
||||
.fontSize(14)
|
||||
.fillColor('#FF3B30')
|
||||
.text(`抵扣后应付: ¥${amountAfterDeposit.toFixed(2)}`);
|
||||
}
|
||||
doc.fontSize(11).fillColor('#389E0D').text(`已扣余额: ¥${paidAmount.toFixed(2)}`);
|
||||
doc.fontSize(14).fillColor(outstandingAmount > 0 ? '#FF3B30' : '#389E0D').text(`待补缴: ¥${outstandingAmount.toFixed(2)}`);
|
||||
doc.moveDown(1);
|
||||
|
||||
// 明细表格
|
||||
|
||||
81
apps/server/src/bills/bills.boundaries.spec.ts
Normal file
81
apps/server/src/bills/bills.boundaries.spec.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { BillsService } from './bills.service';
|
||||
import { Bill } from '../entities/bill.entity';
|
||||
|
||||
function queryBuilder() {
|
||||
return {
|
||||
update: jest.fn().mockReturnThis(),
|
||||
set: jest.fn().mockReturnThis(),
|
||||
where: jest.fn().mockReturnThis(),
|
||||
execute: jest.fn().mockResolvedValue({ affected: 1 }),
|
||||
};
|
||||
}
|
||||
|
||||
function createService(bills: Partial<Bill>[] = []) {
|
||||
const billRepo = {
|
||||
find: jest.fn().mockResolvedValue(bills),
|
||||
findOne: jest.fn().mockResolvedValue(bills[0] ?? null),
|
||||
save: jest.fn(async (value) => value),
|
||||
update: jest.fn(),
|
||||
createQueryBuilder: jest.fn(() => queryBuilder()),
|
||||
};
|
||||
const manager = {
|
||||
delete: jest.fn(),
|
||||
update: jest.fn(),
|
||||
};
|
||||
const dataSource = { transaction: jest.fn(async (callback) => callback(manager)) };
|
||||
const service = new BillsService(
|
||||
billRepo as any,
|
||||
{ delete: jest.fn() } as any,
|
||||
{} as any,
|
||||
{ update: jest.fn() } as any,
|
||||
{} as any,
|
||||
{} as any,
|
||||
dataSource as any,
|
||||
{} as any,
|
||||
);
|
||||
return { service, billRepo, dataSource, manager };
|
||||
}
|
||||
|
||||
describe('BillsService state and batch boundaries', () => {
|
||||
it('rejects an empty batch status update', async () => {
|
||||
const { service, billRepo } = createService();
|
||||
await expect(service.batchUpdateStatus([], 'paid')).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(billRepo.find).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a batch status update when some ids do not exist', async () => {
|
||||
const { service, billRepo } = createService([{ id: 1, paidAmount: 0, outstandingAmount: 10 }]);
|
||||
await expect(service.batchUpdateStatus([1, 2], 'unpaid')).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(billRepo.createQueryBuilder).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects marking a partially paid bill unpaid', async () => {
|
||||
const { service, billRepo } = createService([{ id: 1, paidAmount: 10, outstandingAmount: 90, status: 'partially_paid' }]);
|
||||
await expect(service.updateStatus(1, { status: 'unpaid' })).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(billRepo.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects an empty batch archive', async () => {
|
||||
const { service, dataSource } = createService();
|
||||
await expect(service.batchRemove([])).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(dataSource.transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a batch archive when some ids do not exist', async () => {
|
||||
const { service, dataSource } = createService([{ id: 1, paidAmount: 0, status: 'unpaid' }]);
|
||||
await expect(service.batchRemove([1, 2])).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(dataSource.transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('archives an unpaid bill without deleting rows', async () => {
|
||||
const { service, billRepo, dataSource, manager } = createService([{ id: 1, paidAmount: 0, status: 'unpaid' }]);
|
||||
await expect(service.remove(1)).resolves.toEqual({ message: '账单已归档' });
|
||||
expect(billRepo.save).not.toHaveBeenCalled();
|
||||
expect(billRepo.createQueryBuilder).not.toHaveBeenCalled();
|
||||
expect(billRepo.findOne).toHaveBeenCalledWith({ where: { id: 1 } });
|
||||
expect((billRepo as any).update).toHaveBeenCalledWith(1, expect.objectContaining({ status: 'cancelled' }));
|
||||
expect(dataSource.transaction).not.toHaveBeenCalled();
|
||||
expect(manager.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
Request,
|
||||
Res,
|
||||
Req,
|
||||
ParseIntPipe,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, In } from 'typeorm';
|
||||
@@ -20,7 +21,7 @@ import { NotificationType } from '../entities/notification.entity';
|
||||
import { Student } from '../entities/student.entity';
|
||||
import { Bill } from '../entities/bill.entity';
|
||||
import { BillsExportService } from './bills-export.service';
|
||||
import { GenerateBillsDto, UpdateBillStatusDto } from './dto/bill.dto';
|
||||
import { CancelBillDto, GenerateBillsDto, UpdateBillStatusDto } from './dto/bill.dto';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
||||
import { extractRequestInfo } from '../common/request-utils';
|
||||
@@ -49,7 +50,7 @@ export class BillsController {
|
||||
username: req.user?.username,
|
||||
module: '账单管理',
|
||||
action: '生成账单',
|
||||
detail: `周期 ${dto.periodStart}~${dto.periodEnd}, 生成 ${result.count} 条`,
|
||||
detail: `周期 ${result.periodStart}~${result.periodEnd}, 生成 ${result.count} 条`,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
@@ -62,7 +63,7 @@ export class BillsController {
|
||||
recipientIds: [student.userId],
|
||||
type: NotificationType.BILL_GENERATED,
|
||||
title: '新账单',
|
||||
content: `您有一笔新账单,金额: ¥${bill.totalAmount}, 周期: ${dto.periodStart}~${dto.periodEnd}`,
|
||||
content: `您有一笔新账单,金额: ¥${bill.totalAmount}, 周期: ${result.periodStart}~${result.periodEnd}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -75,38 +76,38 @@ export class BillsController {
|
||||
findAll(
|
||||
@Query('periodStart') periodStart?: string,
|
||||
@Query('periodEnd') periodEnd?: string,
|
||||
@Query('studentId') studentId?: string,
|
||||
@Query('studentId', new ParseIntPipe({ optional: true })) studentId?: number,
|
||||
@Query('status') status?: string,
|
||||
@Query('expenseType') expenseType?: string,
|
||||
) {
|
||||
return this.service.findAll({
|
||||
periodStart, periodEnd,
|
||||
studentId: studentId ? +studentId : undefined,
|
||||
studentId,
|
||||
status, expenseType,
|
||||
});
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@RequirePermission('bill:view')
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.service.findOne(+id);
|
||||
findOne(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.service.findOne(id);
|
||||
}
|
||||
|
||||
@Put(':id/status')
|
||||
@RequirePermission('bill:confirm')
|
||||
async updateStatus(
|
||||
@Param('id') id: string,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: UpdateBillStatusDto,
|
||||
@Request() req: any,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.updateStatus(+id, dto);
|
||||
const result = await this.service.updateStatus(id, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '账单管理',
|
||||
action: '确认账单',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'bill',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -158,17 +159,36 @@ export class BillsController {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@Post(':id/cancel')
|
||||
@RequirePermission('bill:delete')
|
||||
async remove(@Param('id') id: string, @Request() req: any) {
|
||||
async cancel(@Param('id', ParseIntPipe) id: number, @Body() dto: CancelBillDto, @Request() req: any) {
|
||||
const result = await this.service.cancel(id, dto, req.user?.id);
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.remove(+id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '账单管理',
|
||||
action: '删除账单',
|
||||
targetId: +id,
|
||||
action: '取消账单并冲正',
|
||||
targetId: id,
|
||||
targetType: 'bill',
|
||||
detail: dto.reason,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@RequirePermission('bill:delete')
|
||||
async remove(@Param('id', ParseIntPipe) id: number, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.remove(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '账单管理',
|
||||
action: '归档账单',
|
||||
targetId: id,
|
||||
targetType: 'bill',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -185,7 +205,7 @@ export class BillsController {
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '账单管理',
|
||||
action: '批量删除账单',
|
||||
action: '批量归档账单',
|
||||
detail: `IDs: ${body.ids.join(',')}`,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -198,7 +218,7 @@ export class BillsController {
|
||||
async exportExcel(
|
||||
@Query('periodStart') periodStart?: string,
|
||||
@Query('periodEnd') periodEnd?: string,
|
||||
@Query('studentId') studentId?: string,
|
||||
@Query('studentId', new ParseIntPipe({ optional: true })) studentId?: number,
|
||||
@Query('status') status?: string,
|
||||
@Res() res?: Response,
|
||||
@Req() req?: any,
|
||||
@@ -217,7 +237,7 @@ export class BillsController {
|
||||
{
|
||||
periodStart,
|
||||
periodEnd,
|
||||
studentId: studentId ? +studentId : undefined,
|
||||
studentId,
|
||||
status,
|
||||
},
|
||||
res!,
|
||||
@@ -226,18 +246,18 @@ export class BillsController {
|
||||
|
||||
@Get('export/pdf/:id')
|
||||
@RequirePermission('bill:export-pdf')
|
||||
async exportPdf(@Param('id') id: string, @Res() res: Response, @Req() req: any) {
|
||||
async exportPdf(@Param('id', ParseIntPipe) id: number, @Res() res: Response, @Req() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
await this.logService.log({
|
||||
userId: req?.user?.id,
|
||||
username: req?.user?.username,
|
||||
module: '账单管理',
|
||||
action: '导出账单',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'bill',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
return this.exportService.exportStudentPdf(+id, res);
|
||||
return this.exportService.exportStudentPdf(id, res);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { NotificationsModule } from '../notifications/notifications.module';
|
||||
import { WalletsModule } from '../wallets/wallets.module';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Bill } from '../entities/bill.entity';
|
||||
import { BillItem } from '../entities/bill-item.entity';
|
||||
@@ -7,8 +8,8 @@ import { RoomExpense } from '../entities/room-expense.entity';
|
||||
import { PersonalExpense } from '../entities/personal-expense.entity';
|
||||
import { Occupancy } from '../entities/occupancy.entity';
|
||||
import { Room } from '../entities/room.entity';
|
||||
import { Deposit } from '../entities/deposit.entity';
|
||||
import { Student } from '../entities/student.entity';
|
||||
import { Deposit } from '../entities/deposit.entity';
|
||||
import { BillsService } from './bills.service';
|
||||
import { BillsExportService } from './bills-export.service';
|
||||
import { BillsController } from './bills.controller';
|
||||
@@ -22,10 +23,11 @@ import { BillsController } from './bills.controller';
|
||||
PersonalExpense,
|
||||
Occupancy,
|
||||
Room,
|
||||
Deposit,
|
||||
Student,
|
||||
Deposit,
|
||||
]),
|
||||
NotificationsModule,
|
||||
WalletsModule,
|
||||
],
|
||||
controllers: [BillsController],
|
||||
providers: [BillsService, BillsExportService],
|
||||
|
||||
@@ -9,6 +9,7 @@ import { PersonalExpense } from '../entities/personal-expense.entity';
|
||||
import { Occupancy } from '../entities/occupancy.entity';
|
||||
import { Room } from '../entities/room.entity';
|
||||
import { Deposit } from '../entities/deposit.entity';
|
||||
import { WalletsService } from '../wallets/wallets.service';
|
||||
|
||||
type MockRepository<T> = Partial<Record<keyof Repository<T>, jest.Mock>>;
|
||||
|
||||
@@ -56,7 +57,23 @@ describe('BillsService — generateBills', () => {
|
||||
occRepo = mockRepo<Occupancy>();
|
||||
roomRepo = mockRepo<Room>();
|
||||
depositRepo = mockRepo<Deposit>();
|
||||
dataSource = { transaction: jest.fn(), query: jest.fn().mockResolvedValue([]) };
|
||||
let nextBillId = 0;
|
||||
dataSource = {
|
||||
transaction: jest.fn(async (callback) => callback({
|
||||
create: (_entity: unknown, value: unknown) => value,
|
||||
save: jest.fn(async (value: any) => {
|
||||
if ('totalAmount' in value && 'studentId' in value) {
|
||||
const saved = { id: ++nextBillId, ...value };
|
||||
await (billRepo.save as jest.Mock)(saved);
|
||||
return saved;
|
||||
}
|
||||
await (itemRepo.save as jest.Mock)(value);
|
||||
return { id: value.id || 1, ...value };
|
||||
}),
|
||||
createQueryBuilder: jest.fn(() => ({ update: jest.fn().mockReturnThis(), set: jest.fn().mockReturnThis(), where: jest.fn().mockReturnThis(), execute: jest.fn().mockResolvedValue({ affected: 1 }) })),
|
||||
})),
|
||||
query: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
@@ -69,6 +86,7 @@ describe('BillsService — generateBills', () => {
|
||||
{ provide: getRepositoryToken(Room), useValue: roomRepo },
|
||||
{ provide: getRepositoryToken(Deposit), useValue: depositRepo },
|
||||
{ provide: DataSource, useValue: dataSource },
|
||||
{ provide: WalletsService, useValue: { debitBill: jest.fn(async (_manager, bill) => bill), refundBill: jest.fn() } },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
@@ -166,6 +184,43 @@ describe('BillsService — generateBills', () => {
|
||||
).toBeCloseTo(300, 0);
|
||||
});
|
||||
|
||||
it('includes room expenses whose periods are inside the generated bill period', async () => {
|
||||
const qb = mockQueryBuilder<RoomExpense>([
|
||||
{
|
||||
id: 1, roomId: 1, expenseType: 'water',
|
||||
amount: '300' as unknown as number, periodStart: '2026-07-01', periodEnd: '2026-07-31',
|
||||
} as RoomExpense,
|
||||
]);
|
||||
(roomExpRepo.createQueryBuilder as jest.Mock).mockReturnValue(qb);
|
||||
|
||||
(occRepo.createQueryBuilder as jest.Mock).mockReturnValue(
|
||||
mockQueryBuilder<Occupancy>([
|
||||
{
|
||||
id: 1, studentId: 10, roomId: 1,
|
||||
billingStartDate: '2026-07-01', billingEndDate: null as unknown as string,
|
||||
stayType: 'short', room: undefined,
|
||||
} as Occupancy,
|
||||
]),
|
||||
);
|
||||
|
||||
(personalExpRepo.createQueryBuilder as jest.Mock).mockReturnValue(
|
||||
mockQueryBuilder<PersonalExpense>([]),
|
||||
);
|
||||
|
||||
const result = await service.generateBills({
|
||||
periodStart: '2026-06-29',
|
||||
periodEnd: '2026-07-31',
|
||||
});
|
||||
|
||||
expect(result.count).toBe(1);
|
||||
expect(qb.where).toHaveBeenCalledWith(
|
||||
'e.periodStart >= :periodStart AND e.periodEnd <= :periodEnd',
|
||||
{ periodStart: '2026-06-29', periodEnd: '2026-07-31' },
|
||||
);
|
||||
const savedCalls = (billRepo.save as jest.Mock).mock.calls as Array<[Record<string, unknown>]>;
|
||||
expect(Number(savedCalls[0][0].sharedAmount)).toBeCloseTo(300, 0);
|
||||
});
|
||||
|
||||
it('mixed → long-term get individual bills, short-term share expenses', async () => {
|
||||
// Room 1: two expenses
|
||||
(roomExpRepo.createQueryBuilder as jest.Mock).mockReturnValue(
|
||||
@@ -229,7 +284,7 @@ describe('BillsService — generateBills', () => {
|
||||
// Bug-exposing tests
|
||||
// ============================================================
|
||||
|
||||
it.skip('BUG: long-term multi-month period → monthlyRate not multiplied by months', async () => {
|
||||
it('long-term multi-month period multiplies and prorates monthly rent', async () => {
|
||||
// 3-month period: Jan–Mar 2026
|
||||
const THREE_MONTHS = { periodStart: '2026-01-01', periodEnd: '2026-03-31' };
|
||||
|
||||
@@ -273,7 +328,7 @@ describe('BillsService — generateBills', () => {
|
||||
expect(actual).toBeCloseTo(expected, 0);
|
||||
});
|
||||
|
||||
it.skip('BUG: long-term partial month → full monthlyRate charged instead of prorated', async () => {
|
||||
it('long-term partial month prorates by calendar days', async () => {
|
||||
// Student occupies only Jun 15–30 (16 days out of 30), monthlyRate 600
|
||||
(roomExpRepo.createQueryBuilder as jest.Mock).mockReturnValue(
|
||||
mockQueryBuilder<RoomExpense>([
|
||||
@@ -489,3 +544,52 @@ describe('BillsService — generateBills', () => {
|
||||
expect(result.count).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BillsService — allocation rounding boundary', () => {
|
||||
it('keeps allocated cents equal to the original expense total', async () => {
|
||||
const billRepo = mockRepo<Bill>();
|
||||
const itemRepo = mockRepo<BillItem>();
|
||||
const roomExpRepo = mockRepo<RoomExpense>();
|
||||
const personalExpRepo = mockRepo<PersonalExpense>();
|
||||
const occRepo = mockRepo<Occupancy>();
|
||||
const roomRepo = mockRepo<Room>();
|
||||
let nextBillId = 0;
|
||||
const dataSource = {
|
||||
query: jest.fn().mockResolvedValue([]),
|
||||
transaction: jest.fn(async (callback) => callback({
|
||||
create: (_entity: unknown, value: any) => value,
|
||||
save: jest.fn(async (value: any) => ({ id: value.id || ++nextBillId, ...value })),
|
||||
createQueryBuilder: jest.fn(() => ({
|
||||
update: jest.fn().mockReturnThis(),
|
||||
set: jest.fn().mockReturnThis(),
|
||||
where: jest.fn().mockReturnThis(),
|
||||
execute: jest.fn().mockResolvedValue({ affected: 1 }),
|
||||
})),
|
||||
})),
|
||||
};
|
||||
const service = new BillsService(
|
||||
billRepo as any,
|
||||
itemRepo as any,
|
||||
roomExpRepo as any,
|
||||
personalExpRepo as any,
|
||||
occRepo as any,
|
||||
roomRepo as any,
|
||||
dataSource as any,
|
||||
{ debitBill: jest.fn(async (_manager, bill) => bill) } as any,
|
||||
);
|
||||
(roomExpRepo.createQueryBuilder as jest.Mock).mockReturnValue(mockQueryBuilder<RoomExpense>([
|
||||
{ id: 1, roomId: 1, expenseType: 'water', amount: 100, periodStart: '2026-06-01', periodEnd: '2026-06-30' } as RoomExpense,
|
||||
]));
|
||||
(occRepo.createQueryBuilder as jest.Mock).mockReturnValue(mockQueryBuilder<Occupancy>([
|
||||
{ id: 1, roomId: 1, studentId: 1, stayType: 'short', billingStartDate: '2026-06-01', billingEndDate: '2026-06-01' } as Occupancy,
|
||||
{ id: 2, roomId: 1, studentId: 2, stayType: 'short', billingStartDate: '2026-06-01', billingEndDate: '2026-06-01' } as Occupancy,
|
||||
{ id: 3, roomId: 1, studentId: 3, stayType: 'short', billingStartDate: '2026-06-01', billingEndDate: '2026-06-01' } as Occupancy,
|
||||
]));
|
||||
(personalExpRepo.createQueryBuilder as jest.Mock).mockReturnValue(mockQueryBuilder<PersonalExpense>([]));
|
||||
|
||||
const result = await service.generateBills({ periodStart: '2026-06-01', periodEnd: '2026-06-30' } as any);
|
||||
|
||||
expect(result.bills.map((bill) => Number(bill.totalAmount))).toEqual([33.33, 33.33, 33.34]);
|
||||
expect(result.bills.reduce((sum, bill) => sum + Number(bill.totalAmount), 0)).toBe(100);
|
||||
});
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user