forked from wangziqi/gongxue-base
Compare commits
114 Commits
codex/xyx
...
302dbe0621
| Author | SHA1 | Date | |
|---|---|---|---|
| 302dbe0621 | |||
| 5bd63846d1 | |||
| 301064dbf6 | |||
| fa7ed8e128 | |||
| a267238e7c | |||
| d93f6cb0b9 | |||
| 0ce8f58adb | |||
| 43ca5a6e36 | |||
| 90cc321221 | |||
| d33c37b4b0 | |||
| bf867eedaa | |||
| 6286864df0 | |||
| 5b10e80d3a | |||
| a9009f86fb | |||
| 7ffc573d2e | |||
| cd1996f281 | |||
| e1bc3a6b2c | |||
| 6052b03fc6 | |||
| 67fdf093e5 | |||
| 393ee62168 | |||
| 1dc13274de | |||
| 576dab0d41 | |||
| 22a4431ba3 | |||
| da023759a1 | |||
| f2cae27575 | |||
| 257c39db90 | |||
| 54e283b687 | |||
| e27d8b512e | |||
| c888dce065 | |||
| d4fb55a20c | |||
| 8f1ff5970d | |||
| 25760a4ec7 | |||
| 4fdf190d69 | |||
| 04082820b0 | |||
| cbc04fea4f | |||
| 37ef6f9dd7 | |||
| 2626d5f460 | |||
| 90cc0c10b2 | |||
| 6a35e406d5 | |||
| a585fd42d5 | |||
| fe0b71a0a9 | |||
| a9961d1a99 | |||
| 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
|
||||
|
||||
43
.gitea/workflows/ci.yml
Normal file
43
.gitea/workflows/ci.yml
Normal file
@@ -0,0 +1,43 @@
|
||||
name: CI
|
||||
|
||||
env:
|
||||
NPM_CONFIG_REGISTRY: https://registry.npmmirror.com
|
||||
NPM_CONFIG_AUDIT: "false"
|
||||
NPM_CONFIG_FUND: "false"
|
||||
NPM_CONFIG_REPLACE_REGISTRY_HOST: always
|
||||
CI: "true"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
container: node:22.22.0-bookworm
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: https://gitee.com/mirrors_actions/checkout@v4
|
||||
with:
|
||||
github-server-url: https://git.gongxue100.com
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Lint
|
||||
run: |
|
||||
npm run lint -w @gongxue/admin
|
||||
npm run lint -w @gongxue/server -- --quiet
|
||||
|
||||
- name: Type check
|
||||
run: npm run typecheck
|
||||
|
||||
- name: Build frontend
|
||||
run: npm run build -w @gongxue/admin
|
||||
|
||||
- name: Run backend tests
|
||||
run: npm run test -w @gongxue/server -- --runInBand --forceExit
|
||||
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;"]
|
||||
@@ -4,7 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>恭学教育基地管理系统</title>
|
||||
<title>学生管理系统</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -1,182 +0,0 @@
|
||||
.counter {
|
||||
font-size: 16px;
|
||||
padding: 5px 10px;
|
||||
border-radius: 5px;
|
||||
color: var(--accent);
|
||||
background: var(--accent-bg);
|
||||
border: 2px solid transparent;
|
||||
transition: border-color 0.3s;
|
||||
margin-bottom: 24px;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--accent-border);
|
||||
}
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.hero {
|
||||
position: relative;
|
||||
|
||||
.base,
|
||||
.framework,
|
||||
.vite {
|
||||
inset-inline: 0;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.base {
|
||||
width: 170px;
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.framework,
|
||||
.vite {
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.framework {
|
||||
z-index: 1;
|
||||
top: 34px;
|
||||
height: 28px;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg) scale(1.4);
|
||||
}
|
||||
|
||||
.vite {
|
||||
z-index: 0;
|
||||
top: 107px;
|
||||
height: 26px;
|
||||
width: auto;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg) scale(0.8);
|
||||
}
|
||||
}
|
||||
|
||||
#center {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 25px;
|
||||
place-content: center;
|
||||
place-items: center;
|
||||
flex-grow: 1;
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
padding: 32px 20px 24px;
|
||||
gap: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps {
|
||||
display: flex;
|
||||
border-top: 1px solid var(--border);
|
||||
text-align: left;
|
||||
|
||||
& > div {
|
||||
flex: 1 1 0;
|
||||
padding: 32px;
|
||||
@media (max-width: 1024px) {
|
||||
padding: 24px 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.icon {
|
||||
margin-bottom: 16px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
flex-direction: column;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
#docs {
|
||||
border-right: 1px solid var(--border);
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
border-right: none;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin: 32px 0 0;
|
||||
|
||||
.logo {
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--text-h);
|
||||
font-size: 16px;
|
||||
border-radius: 6px;
|
||||
background: var(--social-bg);
|
||||
display: flex;
|
||||
padding: 6px 12px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
text-decoration: none;
|
||||
transition: box-shadow 0.3s;
|
||||
|
||||
&:hover {
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.button-icon {
|
||||
height: 18px;
|
||||
width: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
margin-top: 20px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
|
||||
li {
|
||||
flex: 1 1 calc(50% - 8px);
|
||||
}
|
||||
|
||||
a {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#spacer {
|
||||
height: 88px;
|
||||
border-top: 1px solid var(--border);
|
||||
@media (max-width: 1024px) {
|
||||
height: 48px;
|
||||
}
|
||||
}
|
||||
|
||||
.ticks {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -4.5px;
|
||||
border: 5px solid transparent;
|
||||
}
|
||||
|
||||
&::before {
|
||||
left: 0;
|
||||
border-left-color: var(--border);
|
||||
}
|
||||
&::after {
|
||||
right: 0;
|
||||
border-right-color: var(--border);
|
||||
}
|
||||
}
|
||||
@@ -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,16 @@ 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 ExamsPage = lazy(() => import('./pages/Exams'));
|
||||
const ExamDetailPage = lazy(() => import('./pages/Exams/detail'));
|
||||
const OrganizationsPage = lazy(() => import('./pages/Organizations'));
|
||||
const ClassroomRentalsPage = lazy(() => import('./pages/ClassroomRentals'));
|
||||
const ClassroomSchedulePage = lazy(() => import('./pages/ClassroomSchedule'));
|
||||
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 +61,274 @@ 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="exams"
|
||||
element={
|
||||
<PermissionRoute permission="exam:view">
|
||||
<ExamsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="exams/:id"
|
||||
element={
|
||||
<PermissionRoute permission="exam:view">
|
||||
<ExamDetailPage />
|
||||
</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');
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 13 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 4.0 KiB |
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 8.5 KiB |
@@ -11,6 +11,7 @@ const academicPermissions = [
|
||||
'dashboard:view',
|
||||
'student:view',
|
||||
'class:view',
|
||||
'exam:view',
|
||||
'teacher:view',
|
||||
'schedule:view',
|
||||
'attendance:view',
|
||||
@@ -45,9 +46,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', () => {
|
||||
@@ -56,6 +55,7 @@ describe('role-aware menu policy', () => {
|
||||
expect(menu.map((item) => item.label)).toEqual(['数据面板', '教务管理', '通知中心']);
|
||||
expect(paths.filter((path) => path === '/schedules')).toHaveLength(1);
|
||||
expect(paths.filter((path) => path === '/attendance')).toHaveLength(1);
|
||||
expect(paths).toContain('/exams');
|
||||
expect(paths).not.toContain('/teacher-workspace');
|
||||
});
|
||||
|
||||
|
||||
@@ -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' },
|
||||
],
|
||||
@@ -56,6 +61,7 @@ const SECTIONS: MenuSection[] = [
|
||||
children: [
|
||||
{ key: '/students', label: '学生管理', icon: 'students', permission: 'student:view' },
|
||||
{ key: '/classes', label: '班级管理', icon: 'classes', permission: 'class:view' },
|
||||
{ key: '/exams', label: '考试管理', icon: 'exam', permission: 'exam:view' },
|
||||
{ key: '/teachers', label: '教师管理', icon: 'teachers', permission: 'teacher:view' },
|
||||
{ key: '/schedules', label: '排课管理', icon: 'calendar', permission: 'schedule:view' },
|
||||
{ key: '/attendance', label: '历史考勤', icon: 'attendance', permission: 'attendance:view' },
|
||||
@@ -73,6 +79,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 +89,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 +121,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 +196,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);
|
||||
@@ -34,6 +30,7 @@ describe('permission navigation', () => {
|
||||
it('keeps route permission lookup aligned for nested detail routes', () => {
|
||||
expect(getRequiredPermission('/classes/12')).toBe('class:view');
|
||||
expect(getRequiredPermission('/students/8/profile')).toBe('student:view');
|
||||
expect(getRequiredPermission('/exams/8')).toBe('exam:view');
|
||||
expect(canAccessPath('/ai-config', ['ai:config:read'])).toBe(true);
|
||||
expect(canAccessPath('/ai-config', ['integration:read'])).toBe(false);
|
||||
});
|
||||
|
||||
@@ -14,12 +14,26 @@ 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: '/exams',
|
||||
permission: 'exam:view',
|
||||
matches: (p) => p === '/exams' || /^\/exams\/\d+$/.test(p),
|
||||
},
|
||||
{ path: '/attendance', permission: 'attendance:view' },
|
||||
{ path: '/schedules', permission: 'schedule:view' },
|
||||
{ path: '/classroom-schedule', permission: 'rental:view' },
|
||||
{ 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;
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import React, { act } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import dayjs from 'dayjs';
|
||||
import EditableCell, {
|
||||
editableValuesEqual,
|
||||
normalizeEditableValue,
|
||||
serializeEditableValue,
|
||||
} from './index';
|
||||
|
||||
let container: HTMLDivElement | null = null;
|
||||
let root: ReturnType<typeof createRoot> | null = null;
|
||||
|
||||
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
const dispatchPointer = (
|
||||
target: Element,
|
||||
type: 'pointerdown' | 'pointerup',
|
||||
init: { pointerType: 'touch' | 'mouse'; pointerId?: number; clientX?: number; clientY?: number },
|
||||
) => {
|
||||
const event = new Event(type, { bubbles: true });
|
||||
Object.defineProperties(event, {
|
||||
pointerType: { value: init.pointerType },
|
||||
pointerId: { value: init.pointerId ?? 1 },
|
||||
clientX: { value: init.clientX ?? 0 },
|
||||
clientY: { value: init.clientY ?? 0 },
|
||||
});
|
||||
target.dispatchEvent(event);
|
||||
};
|
||||
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await act(async () => root?.unmount());
|
||||
}
|
||||
container?.remove();
|
||||
root = null;
|
||||
container = null;
|
||||
});
|
||||
|
||||
describe('editable cell value mapping', () => {
|
||||
it('normalizes and serializes date values', () => {
|
||||
const value = normalizeEditableValue('2026-07-21', 'date');
|
||||
expect(dayjs.isDayjs(value)).toBe(true);
|
||||
expect(serializeEditableValue(value, 'date')).toBe('2026-07-21');
|
||||
});
|
||||
|
||||
it('normalizes and serializes date ranges', () => {
|
||||
const value = normalizeEditableValue(['2026-07-01', '2026-07-31'], 'date-range');
|
||||
expect(serializeEditableValue(value, 'date-range')).toEqual(['2026-07-01', '2026-07-31']);
|
||||
});
|
||||
|
||||
it('converts numeric input and preserves zero', () => {
|
||||
expect(serializeEditableValue(normalizeEditableValue('12.50', 'money'), 'money')).toBe(12.5);
|
||||
expect(serializeEditableValue(0, 'number')).toBe(0);
|
||||
});
|
||||
|
||||
it('normalizes empty and multi-select values', () => {
|
||||
expect(serializeEditableValue('', 'number')).toBeUndefined();
|
||||
expect(normalizeEditableValue(undefined, 'multi-select')).toEqual([]);
|
||||
});
|
||||
|
||||
it('compares structured values without reference equality', () => {
|
||||
expect(editableValuesEqual([1, 2], [1, 2])).toBe(true);
|
||||
expect(editableValuesEqual(' a ', 'a')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('editable cell interactions', () => {
|
||||
const renderTextCell = async () => {
|
||||
const onSave = vi.fn(async () => undefined);
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root?.render(
|
||||
React.createElement(EditableCell, { value: '张三', onSave }, '张三'),
|
||||
);
|
||||
});
|
||||
return container.querySelector('.editable-cell') as HTMLElement;
|
||||
};
|
||||
|
||||
it('keeps a single touch tap read-only', async () => {
|
||||
const cell = await renderTextCell();
|
||||
|
||||
await act(async () => {
|
||||
dispatchPointer(cell, 'pointerdown', { pointerType: 'touch', clientX: 10, clientY: 10 });
|
||||
dispatchPointer(cell, 'pointerup', { pointerType: 'touch', clientX: 12, clientY: 11 });
|
||||
await flush();
|
||||
});
|
||||
|
||||
expect(container?.querySelector('.editable-cell--editing')).toBeNull();
|
||||
});
|
||||
|
||||
it('enters edit mode after two nearby touch taps', async () => {
|
||||
const cell = await renderTextCell();
|
||||
|
||||
await act(async () => {
|
||||
dispatchPointer(cell, 'pointerdown', { pointerType: 'touch', clientX: 10, clientY: 10 });
|
||||
dispatchPointer(cell, 'pointerup', { pointerType: 'touch', clientX: 11, clientY: 10 });
|
||||
dispatchPointer(cell, 'pointerdown', { pointerType: 'touch', clientX: 12, clientY: 11 });
|
||||
dispatchPointer(cell, 'pointerup', { pointerType: 'touch', clientX: 12, clientY: 11 });
|
||||
await flush();
|
||||
});
|
||||
|
||||
expect(container?.querySelector('.editable-cell--editing')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('keeps mouse single-click behavior read-only', async () => {
|
||||
const cell = await renderTextCell();
|
||||
|
||||
await act(async () => {
|
||||
dispatchPointer(cell, 'pointerdown', { pointerType: 'mouse' });
|
||||
dispatchPointer(cell, 'pointerup', { pointerType: 'mouse' });
|
||||
await flush();
|
||||
});
|
||||
|
||||
expect(container?.querySelector('.editable-cell--editing')).toBeNull();
|
||||
});
|
||||
|
||||
it('does not edit when a touch gesture scrolls the table', async () => {
|
||||
const cell = await renderTextCell();
|
||||
|
||||
await act(async () => {
|
||||
dispatchPointer(cell, 'pointerdown', { pointerType: 'touch', clientX: 10, clientY: 10 });
|
||||
dispatchPointer(cell, 'pointerup', { pointerType: 'touch', clientX: 30, clientY: 10 });
|
||||
await flush();
|
||||
});
|
||||
|
||||
expect(container?.querySelector('.editable-cell--editing')).toBeNull();
|
||||
});
|
||||
|
||||
it('saves a single-select value immediately when an option is clicked', async () => {
|
||||
const onSave = vi.fn(async () => undefined);
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root?.render(
|
||||
React.createElement(
|
||||
EditableCell,
|
||||
{
|
||||
value: 'active',
|
||||
editor: 'select',
|
||||
options: [
|
||||
{ value: 'active', label: '启用' },
|
||||
{ value: 'disabled', label: '停用' },
|
||||
],
|
||||
onSave,
|
||||
},
|
||||
'启用',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
container?.querySelector('.editable-cell')?.dispatchEvent(
|
||||
new MouseEvent('dblclick', { bubbles: true }),
|
||||
);
|
||||
await flush();
|
||||
});
|
||||
|
||||
const options = Array.from(document.querySelectorAll<HTMLElement>('.ant-select-item-option'));
|
||||
const disabledOption = options.find((option) => option.textContent?.includes('停用'));
|
||||
expect(disabledOption).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
disabledOption?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
await flush();
|
||||
});
|
||||
|
||||
expect(onSave).toHaveBeenCalledOnce();
|
||||
expect(onSave).toHaveBeenCalledWith('disabled');
|
||||
expect(container.querySelector('.editable-cell--editing')).toBeNull();
|
||||
});
|
||||
});
|
||||
318
apps/admin/src/components/EditableCell/index.tsx
Normal file
318
apps/admin/src/components/EditableCell/index.tsx
Normal file
@@ -0,0 +1,318 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { DatePicker, Input, InputNumber, Select, Spin, Tooltip } from 'antd';
|
||||
import type { Dayjs } from 'dayjs';
|
||||
import dayjs from 'dayjs';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
import { message } from '../../ui/app-message';
|
||||
import './style.css';
|
||||
|
||||
export type EditableCellEditor =
|
||||
| 'text'
|
||||
| 'textarea'
|
||||
| 'number'
|
||||
| 'money'
|
||||
| 'date'
|
||||
| 'date-range'
|
||||
| 'select'
|
||||
| 'multi-select'
|
||||
| 'tags';
|
||||
|
||||
export interface EditableCellOption {
|
||||
label: React.ReactNode;
|
||||
value: string | number | boolean;
|
||||
}
|
||||
|
||||
export interface EditableCellProps<Value = unknown> {
|
||||
value: Value;
|
||||
children?: React.ReactNode;
|
||||
editor?: EditableCellEditor;
|
||||
options?: EditableCellOption[];
|
||||
permission?: string;
|
||||
disabled?: boolean;
|
||||
required?: boolean;
|
||||
min?: number;
|
||||
max?: number;
|
||||
placeholder?: string;
|
||||
formatValue?: (value: Value) => unknown;
|
||||
parseValue?: (value: unknown) => Value;
|
||||
onSave: (value: Value) => Promise<void>;
|
||||
}
|
||||
|
||||
let activeCell: { id: string; save: () => Promise<boolean> } | null = null;
|
||||
let replayingOutsideAction = false;
|
||||
|
||||
export function normalizeEditableValue(value: unknown, editor: EditableCellEditor) {
|
||||
if (editor === 'date') return value ? dayjs(value as string) : null;
|
||||
if (editor === 'date-range')
|
||||
return Array.isArray(value) ? value.map((item) => dayjs(item as string)) : null;
|
||||
if (editor === 'number' || editor === 'money') {
|
||||
return value === null || value === undefined || value === '' ? null : Number(value);
|
||||
}
|
||||
if (editor === 'multi-select' || editor === 'tags') return Array.isArray(value) ? value : [];
|
||||
return value ?? '';
|
||||
}
|
||||
|
||||
export function serializeEditableValue(value: unknown, editor: EditableCellEditor) {
|
||||
if (editor === 'date') return value ? (value as Dayjs).format('YYYY-MM-DD') : undefined;
|
||||
if (editor === 'date-range')
|
||||
return Array.isArray(value)
|
||||
? value.map((item) => (item as Dayjs).format('YYYY-MM-DD'))
|
||||
: undefined;
|
||||
if (editor === 'number' || editor === 'money') {
|
||||
return value === null || value === undefined || value === '' ? undefined : Number(value);
|
||||
}
|
||||
if (typeof value === 'string') return value.trim();
|
||||
return value;
|
||||
}
|
||||
|
||||
export function editableValuesEqual(left: unknown, right: unknown) {
|
||||
return JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
|
||||
}
|
||||
|
||||
function isEditorOverlay(target: EventTarget | null) {
|
||||
return (
|
||||
target instanceof Element &&
|
||||
!!target.closest('.ant-select-dropdown, .ant-picker-dropdown, .ant-tooltip, .ant-message')
|
||||
);
|
||||
}
|
||||
|
||||
const EditableCell = <Value,>({
|
||||
value,
|
||||
children,
|
||||
editor = 'text',
|
||||
options,
|
||||
permission,
|
||||
disabled,
|
||||
required,
|
||||
min,
|
||||
max,
|
||||
placeholder,
|
||||
formatValue,
|
||||
parseValue,
|
||||
onSave,
|
||||
}: EditableCellProps<Value>) => {
|
||||
const { hasPermission } = usePermission();
|
||||
const idRef = useRef(crypto.randomUUID());
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const touchStartRef = useRef<{ pointerId: number; x: number; y: number } | null>(null);
|
||||
const lastTouchTapRef = useRef<{ time: number; x: number; y: number } | null>(null);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [draft, setDraft] = useState<unknown>(() =>
|
||||
normalizeEditableValue(formatValue ? formatValue(value) : value, editor),
|
||||
);
|
||||
const enabled = !disabled && (!permission || hasPermission(permission));
|
||||
|
||||
const original = useMemo(
|
||||
() =>
|
||||
serializeEditableValue(
|
||||
normalizeEditableValue(formatValue ? formatValue(value) : value, editor),
|
||||
editor,
|
||||
),
|
||||
[editor, formatValue, value],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!editing) {
|
||||
setDraft(normalizeEditableValue(formatValue ? formatValue(value) : value, editor));
|
||||
}
|
||||
}, [editing, editor, formatValue, value]);
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
setDraft(normalizeEditableValue(formatValue ? formatValue(value) : value, editor));
|
||||
if (activeCell?.id === idRef.current) activeCell = null;
|
||||
setEditing(false);
|
||||
}, [editor, formatValue, value]);
|
||||
|
||||
const saveValue = useCallback(async (nextDraft: unknown) => {
|
||||
if (saving) return false;
|
||||
const serialized = serializeEditableValue(nextDraft, editor);
|
||||
if (required && (serialized === '' || serialized === undefined || serialized === null)) {
|
||||
message.error('该字段不能为空');
|
||||
return false;
|
||||
}
|
||||
if (editableValuesEqual(serialized, original)) {
|
||||
if (activeCell?.id === idRef.current) activeCell = null;
|
||||
setEditing(false);
|
||||
return true;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
await onSave(parseValue ? parseValue(serialized) : (serialized as Value));
|
||||
if (activeCell?.id === idRef.current) activeCell = null;
|
||||
setEditing(false);
|
||||
return true;
|
||||
} catch (error) {
|
||||
message.error((error as { message?: string })?.message || '保存失败');
|
||||
return false;
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, [editor, onSave, original, parseValue, required, saving]);
|
||||
|
||||
const save = useCallback(() => saveValue(draft), [draft, saveValue]);
|
||||
|
||||
useEffect(() => {
|
||||
const cellId = idRef.current;
|
||||
if (editing && activeCell?.id === cellId) activeCell.save = save;
|
||||
return () => {
|
||||
if (activeCell?.id === cellId) activeCell = null;
|
||||
};
|
||||
}, [editing, save]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!editing) return;
|
||||
const onPointerDown = (event: PointerEvent) => {
|
||||
if (replayingOutsideAction) return;
|
||||
if (rootRef.current?.contains(event.target as Node) || isEditorOverlay(event.target)) return;
|
||||
const actionTarget =
|
||||
event.target instanceof Element
|
||||
? (event.target.closest(
|
||||
'button, a, input, label, [role="button"], .ant-pagination-item, .ant-pagination-prev, .ant-pagination-next',
|
||||
) as HTMLElement | null)
|
||||
: null;
|
||||
if (!actionTarget) {
|
||||
void save();
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void save().then((saved) => {
|
||||
if (!saved) return;
|
||||
replayingOutsideAction = true;
|
||||
actionTarget.click();
|
||||
queueMicrotask(() => {
|
||||
replayingOutsideAction = false;
|
||||
});
|
||||
});
|
||||
};
|
||||
document.addEventListener('pointerdown', onPointerDown, true);
|
||||
return () => {
|
||||
document.removeEventListener('pointerdown', onPointerDown, true);
|
||||
};
|
||||
}, [editing, save]);
|
||||
|
||||
const beginEdit = async () => {
|
||||
if (!enabled || saving) return;
|
||||
if (activeCell && activeCell.id !== idRef.current) {
|
||||
const saved = await activeCell.save();
|
||||
if (!saved) return;
|
||||
}
|
||||
activeCell = { id: idRef.current, save };
|
||||
setEditing(true);
|
||||
};
|
||||
|
||||
const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (event.pointerType !== 'touch' || editing) return;
|
||||
touchStartRef.current = {
|
||||
pointerId: event.pointerId,
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
};
|
||||
};
|
||||
|
||||
const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
|
||||
const touchStart = touchStartRef.current;
|
||||
touchStartRef.current = null;
|
||||
if (!touchStart || event.pointerType !== 'touch' || event.pointerId !== touchStart.pointerId) {
|
||||
return;
|
||||
}
|
||||
const moved = Math.hypot(event.clientX - touchStart.x, event.clientY - touchStart.y);
|
||||
if (moved > 8) {
|
||||
lastTouchTapRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const lastTap = lastTouchTapRef.current;
|
||||
const isDoubleTap =
|
||||
!!lastTap &&
|
||||
now - lastTap.time <= 450 &&
|
||||
Math.hypot(event.clientX - lastTap.x, event.clientY - lastTap.y) <= 24;
|
||||
lastTouchTapRef.current = isDoubleTap
|
||||
? null
|
||||
: { time: now, x: event.clientX, y: event.clientY };
|
||||
if (isDoubleTap) void beginEdit();
|
||||
};
|
||||
|
||||
const onKeyDown = async (event: React.KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
cancel();
|
||||
return;
|
||||
}
|
||||
if (event.key === 'Enter' && editor !== 'textarea') {
|
||||
event.preventDefault();
|
||||
await save();
|
||||
return;
|
||||
}
|
||||
if (event.key === 'Tab') await save();
|
||||
};
|
||||
|
||||
const commonProps = {
|
||||
autoFocus: true,
|
||||
value: draft as never,
|
||||
placeholder,
|
||||
disabled: saving,
|
||||
onChange: (next: unknown) =>
|
||||
setDraft(
|
||||
next && typeof next === 'object' && 'target' in next
|
||||
? (next as React.ChangeEvent<HTMLInputElement>).target.value
|
||||
: next,
|
||||
),
|
||||
onKeyDown,
|
||||
};
|
||||
|
||||
let control: React.ReactNode;
|
||||
if (editor === 'select' || editor === 'multi-select' || editor === 'tags') {
|
||||
control = (
|
||||
<Select
|
||||
{...commonProps}
|
||||
onChange={(next) => {
|
||||
setDraft(next);
|
||||
if (editor === 'select') void saveValue(next);
|
||||
}}
|
||||
mode={editor === 'multi-select' ? 'multiple' : editor === 'tags' ? 'tags' : undefined}
|
||||
options={options}
|
||||
open
|
||||
popupMatchSelectWidth={false}
|
||||
popupClassName="editable-cell-dropdown"
|
||||
/>
|
||||
);
|
||||
} else if (editor === 'date') {
|
||||
control = <DatePicker {...commonProps} format="YYYY-MM-DD" open />;
|
||||
} else if (editor === 'date-range') {
|
||||
const { placeholder: _placeholder, ...rangeProps } = commonProps;
|
||||
control = <DatePicker.RangePicker {...rangeProps} format="YYYY-MM-DD" open />;
|
||||
} else if (editor === 'number' || editor === 'money') {
|
||||
control = (
|
||||
<InputNumber {...commonProps} min={min} max={max} precision={editor === 'money' ? 2 : 0} />
|
||||
);
|
||||
} else if (editor === 'textarea') {
|
||||
control = <Input.TextArea {...commonProps} autoSize={{ minRows: 1, maxRows: 4 }} />;
|
||||
} else {
|
||||
control = <Input {...commonProps} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={rootRef}
|
||||
className={`editable-cell${enabled ? ' editable-cell--enabled' : ''}${editing ? ' editable-cell--editing' : ''}`}
|
||||
onDoubleClick={() => void beginEdit()}
|
||||
onPointerDown={onPointerDown}
|
||||
onPointerUp={onPointerUp}
|
||||
onPointerCancel={() => {
|
||||
touchStartRef.current = null;
|
||||
lastTouchTapRef.current = null;
|
||||
}}
|
||||
>
|
||||
{editing ? (
|
||||
<Spin spinning={saving}>{control}</Spin>
|
||||
) : (
|
||||
<Tooltip title={enabled ? '双击编辑,触屏双击编辑' : undefined}>{children}</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditableCell;
|
||||
47
apps/admin/src/components/EditableCell/style.css
Normal file
47
apps/admin/src/components/EditableCell/style.css
Normal file
@@ -0,0 +1,47 @@
|
||||
.editable-cell {
|
||||
min-height: 30px;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.editable-cell--enabled {
|
||||
cursor: cell;
|
||||
touch-action: manipulation;
|
||||
padding: 4px 6px;
|
||||
margin: -4px -6px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.editable-cell--enabled:not(.editable-cell--editing):hover {
|
||||
border-color: #91caff;
|
||||
background: #e6f4ff;
|
||||
}
|
||||
|
||||
.editable-cell--editing {
|
||||
cursor: text;
|
||||
padding: 0;
|
||||
margin: -4px -6px;
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
min-width: 88px;
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.editable-cell--editing .ant-spin-nested-loading,
|
||||
.editable-cell--editing .ant-spin-container,
|
||||
.editable-cell--editing .ant-input-number,
|
||||
.editable-cell--editing .ant-picker,
|
||||
.editable-cell--editing .ant-select {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.editable-cell-dropdown {
|
||||
min-width: 140px !important;
|
||||
}
|
||||
|
||||
.editable-cell-dropdown .ant-select-item-option-content {
|
||||
white-space: nowrap;
|
||||
}
|
||||
565
apps/admin/src/components/JinshujuMatchModal.tsx
Normal file
565
apps/admin/src/components/JinshujuMatchModal.tsx
Normal file
@@ -0,0 +1,565 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { Button, Form, Input, Modal, Popconfirm, Select, Spin, Steps, Tag, Typography } from 'antd';
|
||||
import {
|
||||
CloudUploadOutlined,
|
||||
DeleteOutlined,
|
||||
EditOutlined,
|
||||
LinkOutlined,
|
||||
PlusOutlined,
|
||||
SaveOutlined,
|
||||
SearchOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import api from '../api';
|
||||
import { message } from '../ui/app-message';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
// ── Types ──
|
||||
|
||||
interface JinshujuEntryRow {
|
||||
serialNumber: number;
|
||||
name: string;
|
||||
phone: string | null;
|
||||
suggestedStudent: {
|
||||
id: number;
|
||||
name: string;
|
||||
phone: string | null;
|
||||
studentNo: string | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface StudentOption {
|
||||
id: number;
|
||||
name: string;
|
||||
phone: string | null;
|
||||
studentNo: string | null;
|
||||
}
|
||||
|
||||
interface PreviewResponse {
|
||||
success: boolean;
|
||||
entries: JinshujuEntryRow[];
|
||||
students: StudentOption[];
|
||||
}
|
||||
|
||||
interface MatchRule {
|
||||
id: number;
|
||||
name: string;
|
||||
formToken: string;
|
||||
mappings: Record<string, string>;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface JinshujuFormField {
|
||||
key: string;
|
||||
label: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
type MatchDecision =
|
||||
| { action: 'match'; matchStudentId: number }
|
||||
| { action: 'create'; createName: string; createPhone: string }
|
||||
| { action: 'skip' };
|
||||
|
||||
// ── Constants ──
|
||||
|
||||
const ROW_HEIGHT = 72;
|
||||
const LEFT_WIDTH = 260;
|
||||
const GAP = 80;
|
||||
|
||||
const STUDENT_FIELDS = [
|
||||
{ key: 'name', label: '姓名' },
|
||||
{ key: 'phone', label: '手机号' },
|
||||
{ key: 'idNumber', label: '身份证号' },
|
||||
{ key: 'gender', label: '性别' },
|
||||
{ key: 'ethnicity', label: '民族' },
|
||||
{ key: 'emergencyContact', label: '紧急联系人' },
|
||||
{ key: 'emergencyPhone', label: '紧急联系电话' },
|
||||
{ key: 'studentNo', label: '学号' },
|
||||
];
|
||||
|
||||
// ── MatchSelector sub-component ──
|
||||
|
||||
interface MatchSelectorProps {
|
||||
entry: JinshujuEntryRow;
|
||||
decision: MatchDecision | undefined;
|
||||
studentOptions: StudentOption[];
|
||||
onChange: (d: MatchDecision) => void;
|
||||
}
|
||||
|
||||
const MatchSelector: React.FC<MatchSelectorProps> = ({ entry, decision, studentOptions, onChange }) => {
|
||||
const action = decision?.action ?? 'skip';
|
||||
|
||||
if (action === 'match') {
|
||||
const matchD = decision as { action: 'match'; matchStudentId: number };
|
||||
const matchedStudent = studentOptions.find((s) => s.id === matchD.matchStudentId);
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
|
||||
<Tag color="blue" icon={<LinkOutlined />}>已匹配</Tag>
|
||||
<Text style={{ flex: 1 }}>
|
||||
{matchedStudent?.name ?? '未知'}
|
||||
{matchedStudent?.studentNo && (
|
||||
<Text type="secondary" style={{ fontSize: 12, marginLeft: 4 }}>
|
||||
({matchedStudent.studentNo})
|
||||
</Text>
|
||||
)}
|
||||
</Text>
|
||||
<Button size="small" type="link" danger onClick={() => onChange({ action: 'skip' })}>取消</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (action === 'create') {
|
||||
const createD = decision as { action: 'create'; createName: string; createPhone: string };
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
|
||||
<Tag color="green" icon={<PlusOutlined />}>将新建</Tag>
|
||||
<Input size="small" value={createD.createName} placeholder="姓名" style={{ width: 100 }}
|
||||
onChange={(e) => onChange({ action: 'create', createName: e.target.value, createPhone: createD.createPhone })} />
|
||||
<Input size="small" value={createD.createPhone} placeholder="手机号" style={{ width: 120 }}
|
||||
onChange={(e) => onChange({ action: 'create', createName: createD.createName, createPhone: e.target.value })} />
|
||||
<Button size="small" type="link" danger onClick={() => onChange({ action: 'skip' })}>取消</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
|
||||
<Select showSearch size="small" placeholder="搜索学生…" style={{ flex: 1 }} value={undefined}
|
||||
filterOption={(input, option) => ((option?.label as string) || '').toLowerCase().includes(input.toLowerCase())}
|
||||
options={studentOptions.map((s) => ({
|
||||
value: s.id,
|
||||
label: `${s.name}${s.phone ? ` (${s.phone})` : ''}${s.studentNo ? ` [${s.studentNo}]` : ''}`,
|
||||
}))}
|
||||
onChange={(studentId: number) => onChange({ action: 'match', matchStudentId: studentId })} />
|
||||
<Button size="small" type="dashed" icon={<PlusOutlined />}
|
||||
onClick={() => onChange({ action: 'create', createName: entry.name || '', createPhone: entry.phone || '' })}>
|
||||
新建
|
||||
</Button>
|
||||
<Button size="small" type="link" onClick={() => onChange({ action: 'skip' })}>跳过</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// ── Rule Editor sub-component ──
|
||||
|
||||
interface RuleEditorProps {
|
||||
rule: MatchRule | null;
|
||||
formToken: string;
|
||||
fields: JinshujuFormField[];
|
||||
onSave: () => void;
|
||||
onDelete: (id: number) => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
const RuleEditor: React.FC<RuleEditorProps> = ({ rule, formToken, fields, onSave, onDelete, onCancel }) => {
|
||||
const [name, setName] = useState(rule?.name ?? '');
|
||||
const [mappings, setMappings] = useState<Record<string, string>>(rule?.mappings ?? { name: 'field_1', phone: 'field_2' });
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!name.trim()) { message.warning('请输入规则名称'); return; }
|
||||
setSaving(true);
|
||||
try {
|
||||
if (rule) {
|
||||
await api.put(`/sync/jinshuju/rules/${rule.id}`, { name, mappings });
|
||||
} else {
|
||||
await api.post('/sync/jinshuju/rules', { name, formToken, mappings });
|
||||
}
|
||||
message.success('规则已保存');
|
||||
onSave();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
if (err?.message) message.error(err.message);
|
||||
} finally { setSaving(false); }
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: '12px 0' }}>
|
||||
<Input placeholder="规则名称" value={name} onChange={(e) => setName(e.target.value)}
|
||||
style={{ marginBottom: 12 }} />
|
||||
<Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>选择金数据字段映射到学生资料</Text>
|
||||
{STUDENT_FIELDS.map((sf) => (
|
||||
<div key={sf.key} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
|
||||
<Text style={{ width: 100, textAlign: 'right', fontSize: 13 }}>{sf.label}</Text>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>←</Text>
|
||||
<Select
|
||||
allowClear
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
placeholder="选择金数据字段"
|
||||
value={mappings[sf.key]}
|
||||
style={{ flex: 1 }}
|
||||
options={fields.map((field) => ({
|
||||
value: field.key,
|
||||
label: `${field.label}(${field.key})`,
|
||||
}))}
|
||||
onChange={(value) => setMappings((prev) => {
|
||||
const next = { ...prev };
|
||||
if (value) next[sf.key] = value;
|
||||
else delete next[sf.key];
|
||||
return next;
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
|
||||
<Button type="primary" icon={<SaveOutlined />} loading={saving} onClick={handleSave}>保存</Button>
|
||||
{rule && (
|
||||
<Popconfirm title="确定删除此规则?" onConfirm={() => onDelete(rule.id)}>
|
||||
<Button danger icon={<DeleteOutlined />}>删除</Button>
|
||||
</Popconfirm>
|
||||
)}
|
||||
<Button onClick={onCancel}>取消</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// ── Main MatchModal ──
|
||||
|
||||
interface MatchModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onApplied: () => void;
|
||||
}
|
||||
|
||||
const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplied }) => {
|
||||
const [step, setStep] = useState<'connection' | 'rule' | 'match' | 'applying'>('connection');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [selectedRuleId, setSelectedRuleId] = useState<number | undefined>();
|
||||
const [rules, setRules] = useState<MatchRule[]>([]);
|
||||
const [editingRule, setEditingRule] = useState<MatchRule | null>(null);
|
||||
const [showRuleEditor, setShowRuleEditor] = useState(false);
|
||||
const [credForm] = Form.useForm();
|
||||
const formToken = Form.useWatch('formToken', credForm) ?? '';
|
||||
|
||||
const [entries, setEntries] = useState<JinshujuEntryRow[]>([]);
|
||||
const [studentOptions, setStudentOptions] = useState<StudentOption[]>([]);
|
||||
const [decisions, setDecisions] = useState<Map<number, MatchDecision>>(new Map());
|
||||
const leftRef = useRef<HTMLDivElement>(null);
|
||||
const rightRef = useRef<HTMLDivElement>(null);
|
||||
const [formFields, setFormFields] = useState<JinshujuFormField[]>([]);
|
||||
const [formName, setFormName] = useState('');
|
||||
const [scrollTop, setScrollTop] = useState(0);
|
||||
|
||||
// Load rules on open
|
||||
useEffect(() => {
|
||||
if (open) loadRules();
|
||||
}, [open]);
|
||||
|
||||
const loadRules = async () => {
|
||||
try {
|
||||
const res = await api.get<{ success: boolean; data: MatchRule[] }>('/sync/jinshuju/rules');
|
||||
if (res.success) setRules(res.data);
|
||||
} catch { /* ignore */ }
|
||||
};
|
||||
|
||||
const handleConnectionNext = async () => {
|
||||
try {
|
||||
const values = await credForm.validateFields();
|
||||
setLoading(true);
|
||||
const response = await api.post<{
|
||||
success: boolean;
|
||||
data: { name: string; fields: JinshujuFormField[] };
|
||||
}>('/sync/jinshuju/fields', values);
|
||||
setFormFields(response.data.fields);
|
||||
setFormName(response.data.name);
|
||||
setStep('rule');
|
||||
} catch (error: unknown) {
|
||||
const apiError = error as { message?: string; errorFields?: unknown[] };
|
||||
if (!apiError.errorFields && apiError.message) message.error(apiError.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePreview = async () => {
|
||||
try {
|
||||
const values = await credForm.validateFields();
|
||||
setLoading(true);
|
||||
const body: Record<string, unknown> = { ...values };
|
||||
if (selectedRuleId) body.ruleId = selectedRuleId;
|
||||
const res = await api.post<PreviewResponse>('/sync/jinshuju/preview', body);
|
||||
if (!res.success) throw new Error('预览失败');
|
||||
setEntries(res.entries);
|
||||
setStudentOptions(res.students);
|
||||
const initial = new Map<number, MatchDecision>();
|
||||
for (const entry of res.entries) {
|
||||
if (entry.suggestedStudent) {
|
||||
initial.set(entry.serialNumber, { action: 'match', matchStudentId: entry.suggestedStudent.id });
|
||||
}
|
||||
}
|
||||
setDecisions(initial);
|
||||
setStep('match');
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
if (err?.message) message.error(err.message);
|
||||
} finally { setLoading(false); }
|
||||
};
|
||||
|
||||
const handleApply = async () => {
|
||||
setLoading(true);
|
||||
setStep('applying');
|
||||
try {
|
||||
const decisionList = [...decisions.entries()].map(([serialNumber, d]) => ({ serialNumber, ...d }));
|
||||
const body: Record<string, unknown> = {
|
||||
...credForm.getFieldsValue(),
|
||||
decisions: decisionList,
|
||||
};
|
||||
if (selectedRuleId) body.ruleId = selectedRuleId;
|
||||
const res = await api.post<{ success: boolean; log: { recordsCount: number; message?: string } }>(
|
||||
'/sync/jinshuju/apply', body,
|
||||
);
|
||||
if (res.success) {
|
||||
message.success(res.log.message || `处理 ${res.log.recordsCount} 条记录`);
|
||||
onApplied();
|
||||
reset();
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
if (err?.message) message.error(err.message);
|
||||
setStep('match');
|
||||
} finally { setLoading(false); }
|
||||
};
|
||||
|
||||
const reset = () => {
|
||||
setStep('connection');
|
||||
setEntries([]);
|
||||
setStudentOptions([]);
|
||||
setDecisions(new Map());
|
||||
setSelectedRuleId(undefined);
|
||||
setFormFields([]);
|
||||
setFormName('');
|
||||
setShowRuleEditor(false);
|
||||
credForm.resetFields();
|
||||
};
|
||||
|
||||
const handleClose = () => { reset(); onClose(); };
|
||||
const handleScroll = (source: 'left' | 'right') => {
|
||||
const el = source === 'left' ? leftRef.current : rightRef.current;
|
||||
if (el) setScrollTop(el.scrollTop);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (leftRef.current) leftRef.current.scrollTop = scrollTop;
|
||||
if (rightRef.current) rightRef.current.scrollTop = scrollTop;
|
||||
}, [scrollTop]);
|
||||
|
||||
const getDecision = (serial: number): MatchDecision | undefined => decisions.get(serial);
|
||||
const setDecision = (serial: number, d: MatchDecision) => setDecisions((prev) => new Map(prev).set(serial, d));
|
||||
const total = entries.length;
|
||||
const matched = [...decisions.values()].filter((d) => d.action !== 'skip').length;
|
||||
|
||||
const visibleRules = rules.filter((rule) => rule.formToken === formToken);
|
||||
const selectedRule = visibleRules.find((rule) => rule.id === selectedRuleId) ?? null;
|
||||
|
||||
// ── Render ──
|
||||
|
||||
const renderConnectionStep = () => (
|
||||
<Form form={credForm} layout="vertical" style={{ marginTop: 24 }}>
|
||||
<Form.Item
|
||||
name="apiKey"
|
||||
label="API Key"
|
||||
extra="金数据个人中心 → API 中获取"
|
||||
rules={[{ required: true, message: '请输入 API Key' }]}
|
||||
>
|
||||
<Input placeholder="请输入 API Key" autoComplete="username" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="apiSecret"
|
||||
label="API Secret"
|
||||
rules={[{ required: true, message: '请输入 API Secret' }]}
|
||||
>
|
||||
<Input.Password placeholder="请输入 API Secret" autoComplete="current-password" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="formToken"
|
||||
label="表单 Token"
|
||||
extra="例如表单地址 /f/AbC123 中的 AbC123"
|
||||
rules={[{ required: true, message: '请输入表单 Token' }]}
|
||||
>
|
||||
<Input placeholder="请输入表单 Token" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
);
|
||||
|
||||
const renderRuleStep = () => (
|
||||
<div style={{ marginTop: 24 }}>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<Text strong>选择匹配规则</Text>
|
||||
<Text type="secondary" style={{ display: 'block', marginTop: 4 }}>
|
||||
已连接表单「{formName}」,共 {formFields.length} 个字段。选择已有规则或新建字段映射。
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
|
||||
<Select
|
||||
style={{ flex: 1 }}
|
||||
placeholder="默认规则:field_1 → 姓名,field_2 → 手机号"
|
||||
allowClear
|
||||
value={selectedRuleId}
|
||||
onChange={(value) => setSelectedRuleId(value)}
|
||||
options={visibleRules.map((rule) => ({ value: rule.id, label: rule.name }))}
|
||||
/>
|
||||
{selectedRule ? (
|
||||
<Button
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => {
|
||||
setEditingRule(selectedRule);
|
||||
setShowRuleEditor(true);
|
||||
}}
|
||||
>
|
||||
编辑
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => {
|
||||
setEditingRule(null);
|
||||
setShowRuleEditor(true);
|
||||
}}
|
||||
>
|
||||
新建规则
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{visibleRules.length === 0 && !showRuleEditor ? (
|
||||
<Text type="secondary" style={{ display: 'block', marginTop: 12 }}>
|
||||
当前表单还没有保存的规则。
|
||||
</Text>
|
||||
) : null}
|
||||
|
||||
{showRuleEditor ? (
|
||||
<RuleEditor
|
||||
rule={editingRule}
|
||||
formToken={formToken}
|
||||
fields={formFields}
|
||||
onSave={() => {
|
||||
setShowRuleEditor(false);
|
||||
loadRules();
|
||||
}}
|
||||
onDelete={async (id) => {
|
||||
await api.delete(`/sync/jinshuju/rules/${id}`);
|
||||
message.success('规则已删除');
|
||||
if (selectedRuleId === id) setSelectedRuleId(undefined);
|
||||
setShowRuleEditor(false);
|
||||
loadRules();
|
||||
}}
|
||||
onCancel={() => setShowRuleEditor(false)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderMatchStep = () => {
|
||||
const svgHeight = entries.length * ROW_HEIGHT;
|
||||
const lines: React.ReactNode[] = [];
|
||||
entries.forEach((entry, i) => {
|
||||
const y = i * ROW_HEIGHT + ROW_HEIGHT / 2;
|
||||
const d = getDecision(entry.serialNumber);
|
||||
const isMatched = d?.action === 'match';
|
||||
const color = isMatched ? '#1677ff' : '#d9d9d9';
|
||||
lines.push(<line key={entry.serialNumber} x1={LEFT_WIDTH} y1={y} x2={LEFT_WIDTH + GAP} y2={y}
|
||||
stroke={color} strokeWidth={isMatched ? 2 : 1}
|
||||
strokeDasharray={isMatched ? undefined : '4 4'} opacity={isMatched ? 0.7 : 0.3} />);
|
||||
});
|
||||
|
||||
return (
|
||||
<div style={{ position: 'relative' }}>
|
||||
<div style={{ marginBottom: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<Text type="secondary">共 {total} 条,已匹配 {matched} 条</Text>
|
||||
<Button size="small" onClick={() => setDecisions(new Map())}>清除全部匹配</Button>
|
||||
</div>
|
||||
<div style={{ display: 'flex', position: 'relative' }}>
|
||||
<svg style={{ position: 'absolute', top: 0, left: 0, width: LEFT_WIDTH + GAP, height: svgHeight, pointerEvents: 'none', zIndex: 1 }}>
|
||||
{lines}
|
||||
</svg>
|
||||
<div ref={leftRef} onScroll={() => handleScroll('left')}
|
||||
style={{ width: LEFT_WIDTH, maxHeight: 480, overflowY: 'auto', flexShrink: 0 }}>
|
||||
{entries.map((entry, i) => {
|
||||
const d = getDecision(entry.serialNumber);
|
||||
const isMatched = d?.action === 'match';
|
||||
return (
|
||||
<div key={entry.serialNumber} style={{
|
||||
height: ROW_HEIGHT, padding: '8px 12px', borderBottom: '1px solid #f0f0f0',
|
||||
display: 'flex', flexDirection: 'column', justifyContent: 'center',
|
||||
background: isMatched ? '#f6ffed' : i % 2 === 0 ? '#fafafa' : '#fff',
|
||||
borderLeft: isMatched ? '3px solid #1677ff' : '3px solid transparent',
|
||||
}}>
|
||||
<Text strong style={{ fontSize: 13 }}>{entry.name || <Text type="secondary">无姓名</Text>}</Text>
|
||||
{entry.phone && <Text type="secondary" style={{ fontSize: 12 }}>{entry.phone}</Text>}
|
||||
<Text type="secondary" style={{ fontSize: 11 }}>#{entry.serialNumber}</Text>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div style={{ width: GAP, flexShrink: 0 }} />
|
||||
<div ref={rightRef} onScroll={() => handleScroll('right')}
|
||||
style={{ flex: 1, maxHeight: 480, overflowY: 'auto' }}>
|
||||
{entries.map((entry) => (
|
||||
<div key={entry.serialNumber} style={{
|
||||
height: ROW_HEIGHT, padding: '8px 12px', borderBottom: '1px solid #f0f0f0',
|
||||
display: 'flex', alignItems: 'center', gap: 8,
|
||||
}}>
|
||||
<MatchSelector entry={entry} decision={getDecision(entry.serialNumber)}
|
||||
studentOptions={studentOptions}
|
||||
onChange={(newD) => setDecision(entry.serialNumber, newD)} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const currentStep = step === 'connection' ? 0 : step === 'rule' ? 1 : 2;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title="同步金数据"
|
||||
open={open}
|
||||
onCancel={handleClose}
|
||||
width={step === 'match' || step === 'applying' ? 900 : 640}
|
||||
maskClosable={false}
|
||||
footer={
|
||||
step === 'connection'
|
||||
? [
|
||||
<Button key="cancel" onClick={handleClose}>取消</Button>,
|
||||
<Button key="next" type="primary" onClick={handleConnectionNext}>下一步</Button>,
|
||||
]
|
||||
: step === 'rule'
|
||||
? [
|
||||
<Button key="back" onClick={() => setStep('connection')}>上一步</Button>,
|
||||
<Button key="cancel" onClick={handleClose}>取消</Button>,
|
||||
<Button key="next" type="primary" icon={<SearchOutlined />} loading={loading} onClick={handlePreview}>
|
||||
获取数据并下一步
|
||||
</Button>,
|
||||
]
|
||||
: step === 'match'
|
||||
? [
|
||||
<Button key="back" onClick={() => setStep('rule')}>上一步</Button>,
|
||||
<Button key="cancel" onClick={handleClose}>取消</Button>,
|
||||
<Button key="apply" type="primary" icon={<CloudUploadOutlined />} loading={loading} onClick={handleApply}>
|
||||
应用匹配
|
||||
</Button>,
|
||||
]
|
||||
: null
|
||||
}
|
||||
>
|
||||
<Steps
|
||||
current={currentStep}
|
||||
items={[
|
||||
{ title: '连接表单' },
|
||||
{ title: '匹配规则' },
|
||||
{ title: '确认匹配' },
|
||||
]}
|
||||
/>
|
||||
{step === 'connection' ? renderConnectionStep() : null}
|
||||
{step === 'rule' ? renderRuleStep() : null}
|
||||
{step === 'match' ? renderMatchStep() : null}
|
||||
{step === 'applying' ? <Spin tip="正在同步..." style={{ display: 'block', margin: '48px auto' }} /> : null}
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default JinshujuMatchModal;
|
||||
@@ -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;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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,203 @@ 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;
|
||||
}
|
||||
|
||||
.student-form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
column-gap: 20px;
|
||||
}
|
||||
|
||||
.student-form-grid .ant-form-item {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 575px) {
|
||||
.student-form-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-drawer-content-wrapper {
|
||||
max-width: 100vw !important;
|
||||
}
|
||||
|
||||
.ant-pagination {
|
||||
row-gap: 8px;
|
||||
}
|
||||
|
||||
/* Data tables own their horizontal scroll instead of widening the page. */
|
||||
.ant-table-wrapper {
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.ant-table-wrapper .ant-table-content {
|
||||
overscroll-behavior-inline: contain;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
/* Keep wide tables scrollable without showing a heavy bar on every table. */
|
||||
.ant-table-wrapper .ant-table-content {
|
||||
scrollbar-color: transparent transparent;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.ant-table-wrapper .ant-table-content::-webkit-scrollbar {
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.ant-table-wrapper .ant-table-content::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.ant-table-wrapper .ant-table-content::-webkit-scrollbar-thumb {
|
||||
background: transparent;
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.ant-table-wrapper:hover .ant-table-content,
|
||||
.ant-table-wrapper:focus-within .ant-table-content {
|
||||
scrollbar-color: #c8c8cc transparent;
|
||||
}
|
||||
|
||||
.ant-table-wrapper:hover .ant-table-content::-webkit-scrollbar-thumb,
|
||||
.ant-table-wrapper:focus-within .ant-table-content::-webkit-scrollbar-thumb {
|
||||
background: #c8c8cc;
|
||||
}
|
||||
|
||||
/* ── 表格单元格省略号截断(按需启用) ──
|
||||
@@ -54,6 +255,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 +335,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 +384,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 +435,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
CheckCircleOutlined,
|
||||
LaptopOutlined,
|
||||
BellOutlined,
|
||||
TrophyOutlined,
|
||||
ApiOutlined,
|
||||
RobotOutlined,
|
||||
} from '@ant-design/icons';
|
||||
@@ -32,6 +33,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;
|
||||
@@ -45,12 +47,14 @@ const iconMap: Record<string, React.ReactNode> = {
|
||||
students: <TeamOutlined />,
|
||||
classes: <TeamOutlined />,
|
||||
teachers: <UserOutlined />,
|
||||
exam: <TrophyOutlined />,
|
||||
home: <HomeOutlined />,
|
||||
overview: <AppstoreOutlined />,
|
||||
occupancy: <SwapOutlined />,
|
||||
expense: <DollarOutlined />,
|
||||
bill: <FileTextOutlined />,
|
||||
deposit: <WalletOutlined />,
|
||||
wallet: <WalletOutlined />,
|
||||
classroom: <ReadOutlined />,
|
||||
rental: <FileProtectOutlined />,
|
||||
organization: <TagsOutlined />,
|
||||
@@ -78,7 +82,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 +97,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 +120,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 +142,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 +155,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 +180,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 +214,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 } }}
|
||||
title="恭学教育基地"
|
||||
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 +252,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 +262,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 +290,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>
|
||||
|
||||
272
apps/admin/src/pages/Attendance/LessonAttendanceDetail.tsx
Normal file
272
apps/admin/src/pages/Attendance/LessonAttendanceDetail.tsx
Normal file
@@ -0,0 +1,272 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Alert, Avatar, Button, Drawer, Empty, Input, Progress, Select, Table, Tag } from 'antd';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import { message } from '../../ui/app-message';
|
||||
import {
|
||||
filterLessonAttendanceRecords,
|
||||
getPunchDisplayInfo,
|
||||
summarizeLessonCheckins,
|
||||
type LessonAttendanceFilter,
|
||||
} from './attendance-workspace';
|
||||
import type { LessonAttendanceRecord, LessonAttendanceSchedule } from './types';
|
||||
|
||||
interface LessonAttendanceSession {
|
||||
id: number;
|
||||
scheduleId: number;
|
||||
classId: number;
|
||||
lessonDate: string;
|
||||
status: 'in_progress' | 'completed';
|
||||
}
|
||||
|
||||
interface LessonAttendanceResponse {
|
||||
schedule: LessonAttendanceSchedule;
|
||||
session: LessonAttendanceSession | null;
|
||||
records: LessonAttendanceRecord[];
|
||||
}
|
||||
|
||||
interface LessonAttendanceDetailProps {
|
||||
schedule: LessonAttendanceSchedule | null;
|
||||
className: string;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
function AttendanceStatus({ status }: { status: string }) {
|
||||
const checkedIn = status === 'present' || status === 'late';
|
||||
return (
|
||||
<span className={`attendance-status ${checkedIn ? 'is-present' : 'is-absent'}`}>
|
||||
<span className="attendance-status__dot" />
|
||||
{checkedIn ? '出勤' : '缺勤'}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function LessonSummary({ records }: { records: readonly LessonAttendanceRecord[] }) {
|
||||
const summary = summarizeLessonCheckins(records);
|
||||
const rate = summary.total > 0 ? Math.round((summary.checkedIn / summary.total) * 100) : 0;
|
||||
return (
|
||||
<div className="attendance-summary-strip lesson-summary-strip">
|
||||
<div className="attendance-rate">
|
||||
<Progress type="circle" percent={rate} size={64} strokeWidth={9} />
|
||||
<div>
|
||||
<span>打卡率</span>
|
||||
<strong>{summary.total} 人</strong>
|
||||
</div>
|
||||
</div>
|
||||
<div className="attendance-summary-cell">
|
||||
<span className="attendance-summary-icon is-present">勤</span>
|
||||
<div>
|
||||
<strong>{summary.checkedIn}</strong>
|
||||
<span>已打卡</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="attendance-summary-cell">
|
||||
<span className="attendance-summary-icon is-absent">缺</span>
|
||||
<div>
|
||||
<strong>{summary.notCheckedIn}</strong>
|
||||
<span>未打卡</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const LessonAttendanceDetail: React.FC<LessonAttendanceDetailProps> = ({
|
||||
schedule,
|
||||
className,
|
||||
onClose,
|
||||
}) => {
|
||||
const [loadedSchedule, setLoadedSchedule] = useState<LessonAttendanceSchedule | null>(null);
|
||||
const [session, setSession] = useState<LessonAttendanceSession | null>(null);
|
||||
const [records, setRecords] = useState<LessonAttendanceRecord[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [filter, setFilter] = useState<LessonAttendanceFilter>('all');
|
||||
|
||||
useEffect(() => {
|
||||
if (!schedule) return;
|
||||
let cancelled = false;
|
||||
setLoadedSchedule(schedule);
|
||||
setSession(null);
|
||||
setRecords([]);
|
||||
setKeyword('');
|
||||
setFilter('all');
|
||||
setLoading(true);
|
||||
const date = dayjs().format('YYYY-MM-DD');
|
||||
void api
|
||||
.post<LessonAttendanceResponse>(`/attendance-lessons/schedules/${schedule.id}/pull`, {
|
||||
date,
|
||||
})
|
||||
.then((data) => {
|
||||
if (cancelled) return;
|
||||
setLoadedSchedule(data.schedule);
|
||||
setSession(data.session);
|
||||
setRecords(data.records);
|
||||
message.success('钉钉打卡已更新;课程截止后系统将自动结算');
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (cancelled) return;
|
||||
message.error((error as { message?: string })?.message || '加载本节课考勤失败');
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [schedule]);
|
||||
|
||||
const updateRecord = useCallback(async (record: LessonAttendanceRecord, status: string) => {
|
||||
const previous = record.status;
|
||||
setRecords((items) =>
|
||||
items.map((item) => (item.id === record.id ? { ...item, status } : item)),
|
||||
);
|
||||
try {
|
||||
await api.put(`/attendance-records/${record.id}`, { status });
|
||||
} catch (error: unknown) {
|
||||
setRecords((items) =>
|
||||
items.map((item) => (item.id === record.id ? { ...item, status: previous } : item)),
|
||||
);
|
||||
message.error((error as { message?: string })?.message || '更新考勤失败');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const filteredRecords = useMemo(
|
||||
() => filterLessonAttendanceRecords(records, keyword, filter),
|
||||
[filter, keyword, records],
|
||||
);
|
||||
const completed = session?.status === 'completed';
|
||||
const displayedSchedule = loadedSchedule ?? schedule;
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open={schedule !== null}
|
||||
onClose={onClose}
|
||||
size={960}
|
||||
title={null}
|
||||
className="attendance-drawer"
|
||||
destroyOnHidden
|
||||
>
|
||||
<div className="lesson-record-header">
|
||||
<span className="attendance-eyebrow">LESSON ATTENDANCE</span>
|
||||
<h2>{displayedSchedule?.subject || '课程考勤'}</h2>
|
||||
<p>
|
||||
{className} · {displayedSchedule?.startTime}–{displayedSchedule?.endTime} ·{' '}
|
||||
{dayjs().format('YYYY-MM-DD')}
|
||||
</p>
|
||||
</div>
|
||||
{session && (
|
||||
<Alert
|
||||
type={completed ? 'success' : 'info'}
|
||||
showIcon
|
||||
title={completed ? '本节课考勤已结算' : '当前打卡结果;课程截止后将自动做最终结算'}
|
||||
style={{ marginBottom: 16 }}
|
||||
/>
|
||||
)}
|
||||
<LessonSummary records={records} />
|
||||
<div className="lesson-record-filters">
|
||||
<Input.Search
|
||||
allowClear
|
||||
value={keyword}
|
||||
placeholder="搜索学生姓名"
|
||||
onChange={(event) => setKeyword(event.target.value)}
|
||||
className="lesson-record-search"
|
||||
/>
|
||||
<Select<LessonAttendanceFilter>
|
||||
value={filter}
|
||||
onChange={setFilter}
|
||||
options={[
|
||||
{ value: 'all', label: '全部学生' },
|
||||
{ value: 'checked_in', label: '已打卡' },
|
||||
{ value: 'not_checked_in', label: '未打卡' },
|
||||
]}
|
||||
className="lesson-record-filter-select"
|
||||
/>
|
||||
<span className="lesson-record-filter-count">
|
||||
显示 {filteredRecords.length} / {records.length} 人
|
||||
</span>
|
||||
</div>
|
||||
<Table<LessonAttendanceRecord>
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
dataSource={filteredRecords}
|
||||
pagination={false}
|
||||
locale={{
|
||||
emptyText: (
|
||||
<Empty
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
description={records.length === 0 ? '本节课尚未开始点名' : '没有符合条件的学生'}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
title: '学生',
|
||||
dataIndex: ['student', 'name'],
|
||||
render: (name: string) => (
|
||||
<div className="student-cell">
|
||||
<Avatar size={32}>{name?.slice(0, 1)}</Avatar>
|
||||
<strong>{name || '-'}</strong>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '考勤结果',
|
||||
dataIndex: 'status',
|
||||
width: 230,
|
||||
render: (value: string, record) => {
|
||||
const checkedIn = value === 'present' || value === 'late';
|
||||
return (
|
||||
<div className="attendance-marking-actions">
|
||||
<Button
|
||||
size="small"
|
||||
type={checkedIn ? 'primary' : 'default'}
|
||||
onClick={() => void updateRecord(record, 'present')}
|
||||
>
|
||||
已打卡
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
type={!checkedIn ? 'primary' : 'default'}
|
||||
danger={!checkedIn}
|
||||
onClick={() => void updateRecord(record, 'absent')}
|
||||
>
|
||||
未打卡
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '当前状态',
|
||||
dataIndex: 'status',
|
||||
width: 105,
|
||||
render: (value: string) => <AttendanceStatus status={value} />,
|
||||
},
|
||||
{
|
||||
title: '打卡设备',
|
||||
width: 220,
|
||||
render: (_: unknown, record) => {
|
||||
const info = getPunchDisplayInfo(record);
|
||||
if (!info) return <span className="muted-text">—</span>;
|
||||
return (
|
||||
<div className="punch-device-cell">
|
||||
<Tag color={info.machine ? 'green' : 'blue'}>{info.label}</Tag>
|
||||
{info.detail && <strong>{info.detail}</strong>}
|
||||
{info.time && <span>{dayjs(info.time).format('HH:mm:ss')}</span>}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '备注',
|
||||
dataIndex: 'remark',
|
||||
render: (value: string | null) => value || <span className="muted-text">—</span>,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Drawer>
|
||||
);
|
||||
};
|
||||
|
||||
export default LessonAttendanceDetail;
|
||||
@@ -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
28
apps/admin/src/pages/Attendance/types.ts
Normal file
28
apps/admin/src/pages/Attendance/types.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
export interface LessonAttendanceSchedule {
|
||||
id: number;
|
||||
classId: number;
|
||||
classroomId: number;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
subject: string;
|
||||
}
|
||||
|
||||
export interface LessonAttendanceRecord {
|
||||
id: number;
|
||||
studentId: number;
|
||||
classId: number | null;
|
||||
attendanceDate: string;
|
||||
session: string;
|
||||
status: string;
|
||||
source?: string;
|
||||
remark: string | null;
|
||||
createdAt: string;
|
||||
student: { id: number; name: string; studentNo?: string | null };
|
||||
class: { id: number; name: string } | null;
|
||||
scheduleId?: number | null;
|
||||
attendanceSessionId?: number | null;
|
||||
punchTime?: string | null;
|
||||
punchSource?: string | null;
|
||||
punchDeviceName?: string | null;
|
||||
punchDeviceId?: string | null;
|
||||
}
|
||||
353
apps/admin/src/pages/AttendanceDevices.tsx
Normal file
353
apps/admin/src/pages/AttendanceDevices.tsx
Normal file
@@ -0,0 +1,353 @@
|
||||
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 EditableCell from '../components/EditableCell';
|
||||
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 saveCell = async (record: AttendanceDeviceRow, field: string, value: unknown) => {
|
||||
await api.put(`/attendance-devices/${record.id}`, { [field]: value });
|
||||
message.success('已保存');
|
||||
await loadData();
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/attendance-devices/${id}`);
|
||||
message.success('已停用绑定');
|
||||
await loadData();
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '停用失败');
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ColumnsType<AttendanceDeviceRow> = [
|
||||
{
|
||||
title: '设备名称',
|
||||
dataIndex: 'deviceName',
|
||||
width: 180,
|
||||
render: (value: string, record) => (
|
||||
<EditableCell
|
||||
value={value}
|
||||
required
|
||||
permission="classroom:edit"
|
||||
onSave={(next) => saveCell(record, 'deviceName', next)}
|
||||
>
|
||||
{value}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'SN 码',
|
||||
dataIndex: 'deviceSn',
|
||||
width: 220,
|
||||
render: (value, record) => (
|
||||
<EditableCell
|
||||
value={value}
|
||||
required
|
||||
permission="classroom:edit"
|
||||
onSave={(next) => saveCell(record, 'deviceSn', next)}
|
||||
>
|
||||
<span style={{ fontFamily: 'monospace' }}>{value}</span>
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '绑定教室',
|
||||
dataIndex: ['classroom', 'name'],
|
||||
width: 160,
|
||||
render: (_value, record) => (
|
||||
<EditableCell
|
||||
value={record.classroomId}
|
||||
editor="select"
|
||||
options={classrooms.map((item) => ({
|
||||
value: item.id,
|
||||
label: item.building ? `${item.building} · ${item.name}` : item.name,
|
||||
}))}
|
||||
permission="classroom:edit"
|
||||
required
|
||||
onSave={(next) => saveCell(record, 'classroomId', next)}
|
||||
>
|
||||
{record.classroom?.name || `教室 ${record.classroomId}`}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '位置',
|
||||
dataIndex: 'location',
|
||||
render: (value, record) => (
|
||||
<EditableCell
|
||||
value={value}
|
||||
permission="classroom:edit"
|
||||
onSave={(next) => saveCell(record, 'location', next)}
|
||||
>
|
||||
{value || <span style={{ color: '#999' }}>—</span>}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 90,
|
||||
render: (value: keyof typeof statusMeta, record) => (
|
||||
<EditableCell
|
||||
value={value}
|
||||
editor="select"
|
||||
options={[
|
||||
{ value: 'active', label: '启用' },
|
||||
{ value: 'disabled', label: '停用' },
|
||||
]}
|
||||
permission="classroom:edit"
|
||||
onSave={(next) => saveCell(record, 'status', next)}
|
||||
>
|
||||
<Tag color={statusMeta[value]?.color}>{statusMeta[value]?.text || value}</Tag>
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '备注',
|
||||
dataIndex: 'notes',
|
||||
ellipsis: true,
|
||||
render: (value, record) => (
|
||||
<EditableCell
|
||||
value={value}
|
||||
editor="textarea"
|
||||
permission="classroom:edit"
|
||||
onSave={(next) => saveCell(record, 'notes', next)}
|
||||
>
|
||||
{value || <span style={{ color: '#999' }}>—</span>}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
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';
|
||||
@@ -9,6 +21,7 @@ import { useNavigate } from 'react-router-dom';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
import { message } from '../../ui/app-message';
|
||||
|
||||
// ---- Types ----
|
||||
@@ -96,13 +109,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 +168,165 @@ 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 saveCell = useCallback(
|
||||
async (record: ClassItem, field: string, value: unknown) => {
|
||||
await api.put(`/classes/${record.id}`, { [field]: value });
|
||||
message.success('已保存');
|
||||
await fetchData();
|
||||
},
|
||||
[fetchData],
|
||||
);
|
||||
|
||||
const columns: ColumnsType<ClassItem> = useMemo(() => [
|
||||
{
|
||||
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),
|
||||
render: (v: string, r: ClassItem) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
required
|
||||
permission="class:edit"
|
||||
disabled={r.isArchived}
|
||||
onSave={(next) => saveCell(r, 'name', next)}
|
||||
>
|
||||
{v}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
},
|
||||
{
|
||||
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,
|
||||
render: (v: string, r: ClassItem) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
required
|
||||
permission="class:edit"
|
||||
disabled={r.isArchived}
|
||||
onSave={(next) => saveCell(r, 'code', next)}
|
||||
>
|
||||
{v}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '班型',
|
||||
dataIndex: 'classType',
|
||||
width: 100,
|
||||
render: (v: string, r: ClassItem) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="select"
|
||||
options={Object.entries(TYPE_MAP).map(([value, label]) => ({ value, label }))}
|
||||
permission="class:edit"
|
||||
disabled={r.isArchived}
|
||||
onSave={(next) => saveCell(r, 'classType', next)}
|
||||
>
|
||||
<Tag>{TYPE_MAP[v] || v}</Tag>
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '开班日期',
|
||||
dataIndex: 'startDate',
|
||||
width: 110,
|
||||
render: (v: string | null, r: ClassItem) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="date"
|
||||
permission="class:edit"
|
||||
disabled={r.isArchived}
|
||||
onSave={(next) => saveCell(r, 'startDate', next)}
|
||||
>
|
||||
{v || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '学员',
|
||||
width: 100,
|
||||
render: (_: unknown, r: ClassItem) => (
|
||||
<EditableCell
|
||||
value={r.maxStudents}
|
||||
editor="number"
|
||||
min={0}
|
||||
permission="class:edit"
|
||||
disabled={r.isArchived}
|
||||
onSave={(next) => saveCell(r, 'maxStudents', next)}
|
||||
>{`${r.studentCount || 0}/${r.maxStudents || '-'}`}</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 100,
|
||||
render: (v: string, r: ClassItem) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="select"
|
||||
options={Object.entries(STATUS_MAP).map(([value, item]) => ({
|
||||
value,
|
||||
label: item.text,
|
||||
}))}
|
||||
permission="class:edit"
|
||||
disabled={r.isArchived}
|
||||
onSave={(next) => saveCell(r, 'status', next)}
|
||||
>
|
||||
{(() => {
|
||||
const cfg = STATUS_MAP[v] || { color: 'default', text: v };
|
||||
return <Tag color={cfg.color}>{cfg.text}</Tag>;
|
||||
})()}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
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>
|
||||
),
|
||||
},
|
||||
],
|
||||
[saveCell],
|
||||
);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<Space style={{ marginBottom: 16 }} wrap>
|
||||
<Space
|
||||
style={{ marginBottom: 16 }}
|
||||
wrap
|
||||
className="responsive-toolbar responsive-toolbar--single"
|
||||
>
|
||||
<Input
|
||||
placeholder="搜索名称/编码"
|
||||
prefix={<SearchOutlined />}
|
||||
@@ -244,7 +350,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 +413,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,11 +15,18 @@ 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';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
|
||||
@@ -208,13 +215,19 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const saveCell = async (record: any, field: string, value: unknown) => {
|
||||
await api.put(`/classroom-rentals/${record.id}`, { [field]: value });
|
||||
message.success('已保存');
|
||||
await fetchData();
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/classroom-rentals/${id}`);
|
||||
message.success('已删除');
|
||||
message.success('已归档');
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '删除失败');
|
||||
message.error(e?.message || '归档失败');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -239,10 +252,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 || '移除失败');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -273,34 +286,95 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
title: '教室',
|
||||
width: 120,
|
||||
dataIndex: 'classroom',
|
||||
render: (c: any) =>
|
||||
c ? (
|
||||
<span>
|
||||
{c.building ? `${c.building} · ` : ''}
|
||||
{c.name}
|
||||
</span>
|
||||
) : (
|
||||
'-'
|
||||
),
|
||||
render: (c: any, r: any) => (
|
||||
<EditableCell
|
||||
value={r.classroomId}
|
||||
editor="select"
|
||||
options={classrooms
|
||||
.filter((item) => item.status !== 'archived')
|
||||
.map((item) => ({
|
||||
value: item.id,
|
||||
label: item.building ? `${item.building} · ${item.name}` : item.name,
|
||||
}))}
|
||||
permission="rental:edit"
|
||||
disabled={r.effectiveStatus !== 'active'}
|
||||
required
|
||||
onSave={(next) => saveCell(r, 'classroomId', next)}
|
||||
>
|
||||
{c ? (
|
||||
<span>
|
||||
{c.building ? `${c.building} · ` : ''}
|
||||
{c.name}
|
||||
</span>
|
||||
) : (
|
||||
'-'
|
||||
)}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '承租机构',
|
||||
width: 100,
|
||||
dataIndex: 'lesseeOrganization',
|
||||
render: (t: any) =>
|
||||
t ? (
|
||||
<Tag
|
||||
color={t.color}
|
||||
style={{ background: t.color, color: '#fff', borderColor: t.color }}
|
||||
>
|
||||
{t.name}
|
||||
</Tag>
|
||||
) : (
|
||||
'-'
|
||||
),
|
||||
render: (t: any, r: any) => (
|
||||
<EditableCell
|
||||
value={r.lesseeOrganizationId}
|
||||
editor="select"
|
||||
options={organizations
|
||||
.filter((item) => item.status !== 'archived')
|
||||
.map((item) => ({ value: item.id, label: item.name }))}
|
||||
permission="rental:edit"
|
||||
disabled={r.effectiveStatus !== 'active'}
|
||||
required
|
||||
onSave={(next) => saveCell(r, 'lesseeOrganizationId', next)}
|
||||
>
|
||||
{t ? (
|
||||
<Tag
|
||||
color={t.color}
|
||||
style={{ background: t.color, color: '#fff', borderColor: t.color }}
|
||||
>
|
||||
{t.name}
|
||||
</Tag>
|
||||
) : (
|
||||
'-'
|
||||
)}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '开始日期',
|
||||
dataIndex: 'startDate',
|
||||
width: 110,
|
||||
render: (v: string, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="date"
|
||||
permission="rental:edit"
|
||||
disabled={r.effectiveStatus !== 'active'}
|
||||
required
|
||||
onSave={(next) => saveCell(r, 'startDate', next)}
|
||||
>
|
||||
{v}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '结束日期',
|
||||
dataIndex: 'endDate',
|
||||
width: 110,
|
||||
render: (v: string, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="date"
|
||||
permission="rental:edit"
|
||||
disabled={r.effectiveStatus !== 'active'}
|
||||
required
|
||||
onSave={(next) => saveCell(r, 'endDate', next)}
|
||||
>
|
||||
{v}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{ title: '开始日期', dataIndex: 'startDate', width: 110 },
|
||||
{ title: '结束日期', dataIndex: 'endDate', width: 110 },
|
||||
{
|
||||
title: '时长',
|
||||
width: 80,
|
||||
@@ -313,13 +387,35 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
title: '日租金',
|
||||
dataIndex: 'dailyRate',
|
||||
width: 100,
|
||||
render: (v: any) => (v ? `¥${v}` : '-'),
|
||||
render: (v: any, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="money"
|
||||
min={0.01}
|
||||
permission="rental:edit"
|
||||
disabled={r.effectiveStatus !== 'active'}
|
||||
onSave={(next) => saveCell(r, 'dailyRate', next)}
|
||||
>
|
||||
{v ? `¥${v}` : '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '总额',
|
||||
dataIndex: 'totalAmount',
|
||||
width: 100,
|
||||
render: (v: any) => (v ? `¥${v}` : '-'),
|
||||
render: (v: any, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="money"
|
||||
min={0.01}
|
||||
permission="rental:edit"
|
||||
disabled={r.effectiveStatus !== 'active'}
|
||||
onSave={(next) => saveCell(r, 'totalAmount', next)}
|
||||
>
|
||||
{v ? `¥${v}` : '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
@@ -350,8 +446,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 +488,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,15 +525,20 @@ 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>
|
||||
),
|
||||
},
|
||||
],
|
||||
[],
|
||||
[classrooms, organizations],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -511,10 +631,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 +681,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} />
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { CLASSROOM_VISIBLE_FIELDS } from './classroom-fields';
|
||||
|
||||
describe('classroom visible fields', () => {
|
||||
it('excludes obsolete course and supervisor metadata', () => {
|
||||
expect(CLASSROOM_VISIBLE_FIELDS).toEqual([
|
||||
'name',
|
||||
'building',
|
||||
'floor',
|
||||
'roomType',
|
||||
'capacity',
|
||||
'status',
|
||||
'notes',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +0,0 @@
|
||||
export const CLASSROOM_VISIBLE_FIELDS = [
|
||||
'name',
|
||||
'building',
|
||||
'floor',
|
||||
'roomType',
|
||||
'capacity',
|
||||
'status',
|
||||
'notes',
|
||||
] as const;
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
} from '@ant-design/icons';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
import { message } from '../../ui/app-message';
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
@@ -60,8 +61,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]);
|
||||
|
||||
@@ -102,6 +111,12 @@ const ClassroomsPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const saveCell = async (record: any, field: string, value: unknown) => {
|
||||
await api.put(`/classrooms/${record.id}`, { [field]: value });
|
||||
message.success('已保存');
|
||||
await fetchData();
|
||||
};
|
||||
|
||||
const handleArchive = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/classrooms/${id}`);
|
||||
@@ -140,72 +155,177 @@ 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),
|
||||
render: (v: string, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
required
|
||||
permission="classroom:edit"
|
||||
disabled={r.status === 'archived'}
|
||||
onSave={(next) => saveCell(r, 'name', next)}
|
||||
>
|
||||
{v}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
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);
|
||||
}}
|
||||
{
|
||||
title: '楼栋',
|
||||
dataIndex: 'building',
|
||||
width: 80,
|
||||
render: (v: string, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
permission="classroom:edit"
|
||||
disabled={r.status === 'archived'}
|
||||
onSave={(next) => saveCell(r, 'building', next)}
|
||||
>
|
||||
{v || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '楼层',
|
||||
dataIndex: 'floor',
|
||||
width: 80,
|
||||
render: (v: number, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="number"
|
||||
permission="classroom:edit"
|
||||
disabled={r.status === 'archived'}
|
||||
onSave={(next) => saveCell(r, 'floor', next)}
|
||||
>
|
||||
{v ?? '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '类型',
|
||||
width: 90,
|
||||
dataIndex: 'roomType',
|
||||
render: (v: string, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="select"
|
||||
options={['大', '次大', '小'].map((value) => ({ value, label: value }))}
|
||||
permission="classroom:edit"
|
||||
disabled={r.status === 'archived'}
|
||||
onSave={(next) => saveCell(r, 'roomType', next)}
|
||||
>
|
||||
<Tag color={typeColor[v] || 'default'}>{v || '-'}</Tag>
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '容量',
|
||||
dataIndex: 'capacity',
|
||||
width: 80,
|
||||
render: (v: number, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="number"
|
||||
min={0}
|
||||
permission="classroom:edit"
|
||||
disabled={r.status === 'archived'}
|
||||
onSave={(next) => saveCell(r, 'capacity', next)}
|
||||
>
|
||||
{v ?? '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
width: 100,
|
||||
dataIndex: 'status',
|
||||
render: (
|
||||
_s: string,
|
||||
record: { effectiveStatus?: string; status: string; currentUsage?: CurrentUsage | null },
|
||||
) => {
|
||||
const effectiveStatus = record.effectiveStatus || record.status;
|
||||
return (
|
||||
<EditableCell
|
||||
value={record.status}
|
||||
editor="select"
|
||||
options={[
|
||||
{ value: 'available', label: '可用' },
|
||||
{ value: 'maintenance', label: '维护中' },
|
||||
]}
|
||||
permission="classroom:edit"
|
||||
disabled={record.status === 'archived'}
|
||||
onSave={(next) => saveCell(record, 'status', next)}
|
||||
>
|
||||
<Tooltip
|
||||
title={
|
||||
record.currentUsage
|
||||
? `${record.currentUsage.title} (${record.currentUsage.startTime}-${record.currentUsage.endTime})`
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<Popconfirm
|
||||
title="归档后数据保留,可随时恢复。存在进行中的租赁将无法归档。"
|
||||
onConfirm={() => handleArchive(record.id)}
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
>
|
||||
<PermissionButton permission="classroom:delete" size="small" icon={<InboxOutlined />}>
|
||||
归档
|
||||
<Tag color={statusMap[effectiveStatus]?.color}>
|
||||
{statusMap[effectiveStatus]?.text || effectiveStatus}
|
||||
</Tag>
|
||||
</Tooltip>
|
||||
</EditableCell>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
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 +348,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 +382,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,
|
||||
@@ -10,22 +10,21 @@ import {
|
||||
Space,
|
||||
Tag,
|
||||
Popconfirm,
|
||||
List,
|
||||
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 EditableCell from '../../components/EditableCell';
|
||||
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 || '操作失败');
|
||||
@@ -171,157 +314,286 @@ const DepositsPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const saveInstallmentCell = async (
|
||||
installmentId: number,
|
||||
field: 'status' | 'paidDate',
|
||||
value: unknown,
|
||||
) => {
|
||||
await api.put(`/deposits/installments/${installmentId}`, { [field]: value });
|
||||
message.success('分期记录已保存');
|
||||
if (detailModal) {
|
||||
const refreshed = await api.get<DepositRecord>(`/deposits/${detailModal.id}`);
|
||||
setDetailModal(refreshed);
|
||||
}
|
||||
await fetchData();
|
||||
};
|
||||
|
||||
const handleDeleteInstallment = async (installmentId: number) => {
|
||||
try {
|
||||
await api.delete(`/deposits/installments/${installmentId}`);
|
||||
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 +617,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 +640,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 +662,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,43 +704,86 @@ const DepositsPage: React.FC = () => {
|
||||
添加分期
|
||||
</PermissionButton>
|
||||
</div>
|
||||
{detailModal.installments?.length > 0 ? (
|
||||
<List
|
||||
{detailModal.installments && detailModal.installments.length > 0 ? (
|
||||
<Table
|
||||
size="small"
|
||||
pagination={false}
|
||||
rowKey="id"
|
||||
dataSource={detailModal.installments}
|
||||
renderItem={(item: any) => (
|
||||
<List.Item
|
||||
actions={[
|
||||
item.status === 'pending' && (
|
||||
<PermissionButton
|
||||
key="pay"
|
||||
permission="deposit:edit"
|
||||
size="small"
|
||||
type="primary"
|
||||
icon={<DollarOutlined />}
|
||||
onClick={() => handlePayInstallment(item.id)}
|
||||
>
|
||||
标记已缴
|
||||
</PermissionButton>
|
||||
),
|
||||
<Popconfirm
|
||||
title="确定删除?"
|
||||
onConfirm={() => handleDeleteInstallment(item.id)}
|
||||
columns={[
|
||||
{
|
||||
title: '金额',
|
||||
dataIndex: 'amount',
|
||||
render: (value: number) => `¥${Number(value).toFixed(2)}`,
|
||||
},
|
||||
{ title: '到期日', dataIndex: 'dueDate' },
|
||||
{
|
||||
title: '实付日',
|
||||
dataIndex: 'paidDate',
|
||||
render: (value: string, item: any) => (
|
||||
<EditableCell
|
||||
value={value}
|
||||
editor="date"
|
||||
permission="deposit:edit"
|
||||
onSave={(next) => saveInstallmentCell(item.id, 'paidDate', next)}
|
||||
>
|
||||
<PermissionButton key="del" permission="deposit:delete" size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
].filter(Boolean)}
|
||||
>
|
||||
<List.Item.Meta
|
||||
title={`¥${Number(item.amount).toFixed(2)}`}
|
||||
description={`到期: ${item.dueDate}${item.paidDate ? ` | 缴纳: ${item.paidDate}` : ''}`}
|
||||
/>
|
||||
<Tag color={installmentStatusMap[item.status]?.color}>
|
||||
{installmentStatusMap[item.status]?.text || item.status}
|
||||
</Tag>
|
||||
</List.Item>
|
||||
)}
|
||||
{value || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
render: (value: string, item: any) => (
|
||||
<EditableCell
|
||||
value={value}
|
||||
editor="select"
|
||||
options={[
|
||||
{ value: 'pending', label: '待缴' },
|
||||
{ value: 'paid', label: '已缴' },
|
||||
{ value: 'overdue', label: '逾期' },
|
||||
]}
|
||||
permission="deposit:edit"
|
||||
onSave={(next) => saveInstallmentCell(item.id, 'status', next)}
|
||||
>
|
||||
<Tag color={installmentStatusMap[value]?.color}>
|
||||
{installmentStatusMap[value]?.text || value}
|
||||
</Tag>
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
render: (_: unknown, item: any) => (
|
||||
<Space>
|
||||
{item.status === 'pending' && (
|
||||
<PermissionButton
|
||||
permission="deposit:edit"
|
||||
size="small"
|
||||
type="primary"
|
||||
icon={<DollarOutlined />}
|
||||
onClick={() => handlePayInstallment(item.id)}
|
||||
>
|
||||
标记已缴
|
||||
</PermissionButton>
|
||||
)}
|
||||
<Popconfirm
|
||||
title="确定归档?"
|
||||
onConfirm={() => handleDeleteInstallment(item.id)}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="deposit:delete"
|
||||
size="small"
|
||||
danger
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
) : (
|
||||
<p style={{ color: '#999' }}>暂无分期记录</p>
|
||||
@@ -483,15 +802,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>
|
||||
);
|
||||
};
|
||||
|
||||
59
apps/admin/src/pages/Exams/ExamFormModal.tsx
Normal file
59
apps/admin/src/pages/Exams/ExamFormModal.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import React from 'react';
|
||||
import { DatePicker, Form, Input, Modal, Select } from 'antd';
|
||||
import type { FormInstance } from 'antd';
|
||||
import type { ClassOption, ExamFormValues } from './types';
|
||||
import { EXAM_TYPE_OPTIONS } from './types';
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
editing: boolean;
|
||||
saving: boolean;
|
||||
form: FormInstance<ExamFormValues>;
|
||||
classes: ClassOption[];
|
||||
onCancel: () => void;
|
||||
onSubmit: () => void;
|
||||
}
|
||||
|
||||
const ExamFormModal: React.FC<Props> = ({
|
||||
open,
|
||||
editing,
|
||||
saving,
|
||||
form,
|
||||
classes,
|
||||
onCancel,
|
||||
onSubmit,
|
||||
}) => (
|
||||
<Modal
|
||||
title={editing ? '编辑考试' : '创建考试'}
|
||||
open={open}
|
||||
confirmLoading={saving}
|
||||
onCancel={onCancel}
|
||||
onOk={onSubmit}
|
||||
width={560}
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="examType" label="考试类型" rules={[{ required: true, message: '请选择考试类型' }]}>
|
||||
<Select options={EXAM_TYPE_OPTIONS} placeholder="请选择" />
|
||||
</Form.Item>
|
||||
<Form.Item name="examName" label="考试名称" rules={[{ required: true, message: '请输入考试名称' }]}>
|
||||
<Input placeholder="如:2026 年 7 月月考" />
|
||||
</Form.Item>
|
||||
<Form.Item name="subject" label="科目" rules={[{ required: true, message: '请输入科目' }]}>
|
||||
<Input placeholder="如:数学" />
|
||||
</Form.Item>
|
||||
<Form.Item name="examDate" label="考试日期" rules={[{ required: true, message: '请选择考试日期' }]}>
|
||||
<DatePicker style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="classId" label="考试班级" rules={[{ required: true, message: '请选择考试班级' }]}>
|
||||
<Select
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
placeholder="选择在读班级"
|
||||
options={classes.filter((item) => !item.isArchived).map((item) => ({ value: item.id, label: item.name }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
|
||||
export default ExamFormModal;
|
||||
94
apps/admin/src/pages/Exams/detail.tsx
Normal file
94
apps/admin/src/pages/Exams/detail.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Button, Card, Descriptions, Empty, Space, Spin, Table, Tooltip } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { ArrowLeftOutlined, EyeOutlined } from '@ant-design/icons';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import api from '../../api';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
import { useViewSensitive } from '../../hooks/useViewSensitive';
|
||||
import { maskPhone } from '../../utils/sensitive';
|
||||
import { message } from '../../ui/app-message';
|
||||
import type { ExamItem } from './types';
|
||||
import './style.css';
|
||||
|
||||
interface ScoreRow {
|
||||
id: number;
|
||||
studentId: number;
|
||||
phone: string;
|
||||
name: string;
|
||||
score: number | null;
|
||||
classAvg: number | null;
|
||||
rank: number | null;
|
||||
}
|
||||
|
||||
interface ExamDetail extends ExamItem { scores: ScoreRow[] }
|
||||
|
||||
const PhoneCell: React.FC<{ row: ScoreRow }> = ({ row }) => {
|
||||
const reveal = useViewSensitive(row.studentId, '考试管理');
|
||||
if (!row.phone) return <>-</>;
|
||||
return <Space size={4}><span>{maskPhone(row.phone)}</span><Tooltip title="查看完整手机号"><Button type="text" size="small" icon={<EyeOutlined />} onClick={() => reveal('手机号', row.phone)} /></Tooltip></Space>;
|
||||
};
|
||||
|
||||
const ExamDetailPage: React.FC = () => {
|
||||
const { id } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const [detail, setDetail] = useState<ExamDetail | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try { setDetail(await api.get<ExamDetail>(`/exams/${id}`)); }
|
||||
catch (error) { message.error((error as { message?: string })?.message || '加载考试失败'); }
|
||||
finally { setLoading(false); }
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => { void load(); }, [load]);
|
||||
const saveScore = async (row: ScoreRow, value: number | undefined) => {
|
||||
await api.put(`/exams/${id}/scores/${row.id}`, { score: value ?? null });
|
||||
message.success('成绩已保存');
|
||||
await load();
|
||||
};
|
||||
|
||||
const columns = useMemo<ColumnsType<ScoreRow>>(() => {
|
||||
if (!detail) return [];
|
||||
const fixed = [
|
||||
{ title: '手机号*', width: 155, render: (_: unknown, row: ScoreRow) => <PhoneCell row={row} /> },
|
||||
{ title: '姓名', dataIndex: 'name', width: 100 },
|
||||
{ title: '考试类型*', width: 110, render: () => detail.examType },
|
||||
{ title: '考试名称', width: 170, render: () => detail.examName },
|
||||
{ title: '科目*', width: 90, render: () => detail.subject },
|
||||
];
|
||||
return [
|
||||
...fixed,
|
||||
{ title: '成绩*', dataIndex: 'score', width: 100, render: (value: number | null, row: ScoreRow) => <EditableCell<number | undefined> value={value ?? undefined} editor="money" min={0} max={999.99} permission="exam:view" onSave={(next) => saveScore(row, next)}>{value ?? '-'}</EditableCell> },
|
||||
{ title: '班级均分', dataIndex: 'classAvg', width: 110, render: (value: number | null) => value ?? '-' },
|
||||
{ title: '排名', dataIndex: 'rank', width: 80, render: (value: number | null) => value ?? '-' },
|
||||
{ title: '考试日期', width: 110, render: () => detail.examDate },
|
||||
{ title: '关联报读(班级名)', width: 180, render: () => detail.className },
|
||||
];
|
||||
}, [detail]);
|
||||
|
||||
if (loading && !detail) return <div className="exam-detail-loading"><Spin size="large" /></div>;
|
||||
if (!detail) return <Empty description="考试不存在或无权访问" />;
|
||||
|
||||
const average = detail.scores.find((row) => row.classAvg !== null)?.classAvg ?? null;
|
||||
return (
|
||||
<div className="exam-detail-page">
|
||||
<div className="exam-detail-header"><Space><Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/exams')}>返回</Button><h2>{detail.examName}</h2></Space></div>
|
||||
<Card className="exam-summary">
|
||||
<Descriptions column={{ xs: 1, sm: 2, lg: 5 }}>
|
||||
<Descriptions.Item label="考试类型">{detail.examType}</Descriptions.Item>
|
||||
<Descriptions.Item label="科目">{detail.subject}</Descriptions.Item>
|
||||
<Descriptions.Item label="考试班级">{detail.className}</Descriptions.Item>
|
||||
<Descriptions.Item label="考试日期">{detail.examDate}</Descriptions.Item>
|
||||
<Descriptions.Item label="录入进度">{detail.enteredScores}/{detail.totalStudents},均分 {average ?? '-'}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
</Card>
|
||||
<Card title="成绩表">
|
||||
<Table<ScoreRow> columns={columns} dataSource={detail.scores} rowKey="id" loading={loading} scroll={{ x: 1310 }} pagination={{ defaultPageSize: 30, showSizeChanger: true, pageSizeOptions: [30, 50, 100] }} locale={{ emptyText: <Empty description="暂无学生名单" /> }} />
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ExamDetailPage;
|
||||
129
apps/admin/src/pages/Exams/index.tsx
Normal file
129
apps/admin/src/pages/Exams/index.tsx
Normal file
@@ -0,0 +1,129 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Button, Card, Col, Empty, Form, Input, Progress, Row, Select, Space, Tag } from 'antd';
|
||||
import { CalendarOutlined, PlusOutlined, SearchOutlined, TeamOutlined } from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import api from '../../api';
|
||||
import { message } from '../../ui/app-message';
|
||||
import ExamFormModal from './ExamFormModal';
|
||||
import type { ClassOption, ExamFormValues, ExamItem } from './types';
|
||||
import { EXAM_TYPE_OPTIONS } from './types';
|
||||
import './style.css';
|
||||
|
||||
const ExamsPage: React.FC = () => {
|
||||
const navigate = useNavigate();
|
||||
const [form] = Form.useForm<ExamFormValues>();
|
||||
const [data, setData] = useState<ExamItem[]>([]);
|
||||
const [classes, setClasses] = useState<ClassOption[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [examType, setExamType] = useState<string>();
|
||||
const [classId, setClassId] = useState<number>();
|
||||
|
||||
const loadClasses = useCallback(async () => {
|
||||
const result = await api.get<ClassOption[]>('/classes');
|
||||
setClasses(result ?? []);
|
||||
}, []);
|
||||
|
||||
const loadExams = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (keyword.trim()) params.set('keyword', keyword.trim());
|
||||
if (examType) params.set('examType', examType);
|
||||
if (classId) params.set('classId', String(classId));
|
||||
const result = await api.get<ExamItem[]>(`/exams?${params.toString()}`);
|
||||
setData(result ?? []);
|
||||
} catch (error) {
|
||||
message.error((error as { message?: string })?.message || '加载考试失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [classId, examType, keyword]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadClasses().catch((error: { message?: string }) => message.error(error?.message || '加载班级失败'));
|
||||
}, [loadClasses]);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => void loadExams(), 200);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [loadExams]);
|
||||
|
||||
const classOptions = useMemo(
|
||||
() => classes.map((item) => ({ value: item.id, label: item.name })),
|
||||
[classes],
|
||||
);
|
||||
|
||||
const openCreate = () => {
|
||||
form.resetFields();
|
||||
form.setFieldValue('examDate', dayjs());
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const submit = async () => {
|
||||
try {
|
||||
const values = await form.validateFields();
|
||||
setSaving(true);
|
||||
const payload = { ...values, examDate: values.examDate.format('YYYY-MM-DD') };
|
||||
await api.post('/exams', payload);
|
||||
message.success('考试已创建');
|
||||
setModalOpen(false);
|
||||
await loadExams();
|
||||
} catch (error) {
|
||||
if ((error as { errorFields?: unknown[] }).errorFields) return;
|
||||
message.error((error as { message?: string })?.message || '保存失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="exam-page">
|
||||
<div className="exam-toolbar">
|
||||
<Space wrap>
|
||||
<Input value={keyword} onChange={(event) => setKeyword(event.target.value)} prefix={<SearchOutlined />} placeholder="搜索考试名称" allowClear />
|
||||
<Select value={examType} onChange={setExamType} options={EXAM_TYPE_OPTIONS} placeholder="考试类型" allowClear style={{ width: 140 }} />
|
||||
<Select value={classId} onChange={setClassId} options={classOptions} placeholder="考试班级" allowClear showSearch optionFilterProp="label" style={{ width: 180 }} />
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>创建考试</Button>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
{data.length === 0 && !loading ? (
|
||||
<div className="exam-empty"><Empty description="暂无考试" /></div>
|
||||
) : (
|
||||
<Row gutter={[16, 16]}>
|
||||
{data.map((exam) => {
|
||||
const percent = exam.totalStudents === 0 ? 0 : Math.round((exam.enteredScores / exam.totalStudents) * 100);
|
||||
return (
|
||||
<Col key={exam.id} xs={24} sm={12} xl={8} xxl={6}>
|
||||
<Card
|
||||
className="exam-card"
|
||||
loading={loading}
|
||||
title={<Space><Tag color="blue">{exam.examType}</Tag><span>{exam.examName}</span></Space>}
|
||||
extra={<Tag color="green">成绩录入</Tag>}
|
||||
actions={[
|
||||
<span key="detail" onClick={() => navigate(`/exams/${exam.id}`)}>查看成绩</span>,
|
||||
]}
|
||||
>
|
||||
<div className="exam-meta"><span>科目</span><strong>{exam.subject}</strong></div>
|
||||
<div className="exam-meta"><span><TeamOutlined /> 班级</span><strong>{exam.className}</strong></div>
|
||||
<div className="exam-meta"><span><CalendarOutlined /> 日期</span><strong>{exam.examDate}</strong></div>
|
||||
<div className="exam-progress"><div><span>成绩录入</span><strong>{exam.enteredScores}/{exam.totalStudents}</strong></div><Progress percent={percent} size="small" /></div>
|
||||
</Card>
|
||||
</Col>
|
||||
);
|
||||
})}
|
||||
</Row>
|
||||
)}
|
||||
|
||||
<ExamFormModal open={modalOpen} editing={false} saving={saving} form={form} classes={classes} onCancel={() => setModalOpen(false)} onSubmit={() => void submit()} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ExamsPage;
|
||||
77
apps/admin/src/pages/Exams/style.css
Normal file
77
apps/admin/src/pages/Exams/style.css
Normal file
@@ -0,0 +1,77 @@
|
||||
.exam-page,
|
||||
.exam-detail-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.exam-toolbar,
|
||||
.exam-detail-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.exam-detail-header h2 {
|
||||
margin: 0;
|
||||
font-size: 20px;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.exam-card {
|
||||
height: 100%;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.exam-card .ant-card-head-title {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.exam-card .ant-card-head-title > .ant-space {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.exam-card .ant-card-head-title span:last-child {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.exam-meta,
|
||||
.exam-progress > div {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.exam-meta span,
|
||||
.exam-progress span {
|
||||
color: rgba(0, 0, 0, 0.55);
|
||||
}
|
||||
|
||||
.exam-progress {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.exam-empty,
|
||||
.exam-detail-loading {
|
||||
min-height: 360px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.exam-summary {
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
@media (max-width: 575px) {
|
||||
.exam-toolbar > .ant-space,
|
||||
.exam-toolbar .ant-input-affix-wrapper,
|
||||
.exam-toolbar .ant-select {
|
||||
width: 100% !important;
|
||||
}
|
||||
}
|
||||
37
apps/admin/src/pages/Exams/types.ts
Normal file
37
apps/admin/src/pages/Exams/types.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import type dayjs from 'dayjs';
|
||||
|
||||
export interface ExamItem {
|
||||
id: number;
|
||||
examType: string;
|
||||
examName: string;
|
||||
subject: string;
|
||||
examDate: string;
|
||||
classId: number;
|
||||
className: string;
|
||||
status: 'active' | 'archived';
|
||||
totalStudents: number;
|
||||
enteredScores: number;
|
||||
}
|
||||
|
||||
export interface ExamFormValues {
|
||||
examType: string;
|
||||
examName: string;
|
||||
subject: string;
|
||||
examDate: dayjs.Dayjs;
|
||||
classId: number;
|
||||
}
|
||||
|
||||
export interface ClassOption {
|
||||
id: number;
|
||||
name: string;
|
||||
isArchived: boolean;
|
||||
}
|
||||
|
||||
export const EXAM_TYPE_OPTIONS = [
|
||||
{ value: '月考', label: '月考' },
|
||||
{ value: '周测', label: '周测' },
|
||||
{ value: '期中考试', label: '期中考试' },
|
||||
{ value: '期末考试', label: '期末考试' },
|
||||
{ value: '模拟考试', label: '模拟考试' },
|
||||
{ value: '入学测试', label: '入学测试' },
|
||||
];
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
} from 'antd';
|
||||
import {
|
||||
PlusOutlined,
|
||||
DeleteOutlined,
|
||||
InboxOutlined,
|
||||
EditOutlined,
|
||||
UploadOutlined,
|
||||
DownloadOutlined,
|
||||
@@ -26,17 +26,16 @@ import {
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
import { downloadBlob } from '../../utils/download';
|
||||
import { message } from '../../ui/app-message';
|
||||
|
||||
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 +45,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 +62,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 +95,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 +112,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 +198,50 @@ const ExpensesPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const saveRoomCell = useCallback(
|
||||
async (record: any, field: string, value: unknown) => {
|
||||
await api.put(`/expenses/room/${record.id}`, { [field]: value });
|
||||
message.success('已保存');
|
||||
await fetchData();
|
||||
},
|
||||
[fetchData],
|
||||
);
|
||||
|
||||
const savePersonalCell = useCallback(
|
||||
async (record: any, field: string, value: unknown) => {
|
||||
await api.put(`/expenses/personal/${record.id}`, { [field]: value });
|
||||
message.success('已保存');
|
||||
await fetchData();
|
||||
},
|
||||
[fetchData],
|
||||
);
|
||||
|
||||
const handleStudentUtility = async () => {
|
||||
const values = await utilityForm.validateFields();
|
||||
setSaving(true);
|
||||
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 +274,269 @@ 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
|
||||
const roomColumns = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: '宿舍',
|
||||
width: 120,
|
||||
render: (_: any, r: any) => (
|
||||
<EditableCell
|
||||
value={r.roomId}
|
||||
editor="select"
|
||||
options={rooms.map((item) => ({ value: item.id, label: item.roomNumber }))}
|
||||
permission="expense:edit"
|
||||
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);
|
||||
}}
|
||||
required
|
||||
onSave={(next) => saveRoomCell(r, 'roomId', next)}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<Popconfirm
|
||||
title="确定删除?"
|
||||
onConfirm={async () => {
|
||||
await api.delete(`/expenses/room/${record.id}`);
|
||||
message.success('删除成功');
|
||||
fetchData();
|
||||
}}
|
||||
{r.room?.roomNumber || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '费用类型',
|
||||
width: 100,
|
||||
dataIndex: 'expenseType',
|
||||
render: (v: string, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="select"
|
||||
options={typeOptions}
|
||||
permission="expense:edit"
|
||||
required
|
||||
onSave={(next) => saveRoomCell(r, 'expenseType', next)}
|
||||
>
|
||||
<Tag>{typeMap[v] || v}</Tag>
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '金额',
|
||||
dataIndex: 'amount',
|
||||
width: 100,
|
||||
render: (v: number, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="money"
|
||||
min={0.01}
|
||||
permission="expense:edit"
|
||||
required
|
||||
onSave={(next) => saveRoomCell(r, 'amount', next)}
|
||||
>{`¥${Number(v).toFixed(2)}`}</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '账单周期',
|
||||
width: 200,
|
||||
render: (_: any, r: any) => (
|
||||
<EditableCell
|
||||
value={[r.periodStart, r.periodEnd]}
|
||||
editor="date-range"
|
||||
permission="expense:edit"
|
||||
required
|
||||
onSave={async (next) => {
|
||||
const [periodStart, periodEnd] = next as unknown as [string, string];
|
||||
await api.put(`/expenses/room/${r.id}`, { periodStart, periodEnd });
|
||||
message.success('已保存');
|
||||
await fetchData();
|
||||
}}
|
||||
>{`${r.periodStart} ~ ${r.periodEnd}`}</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '说明',
|
||||
dataIndex: 'description',
|
||||
width: 150,
|
||||
render: (v: string, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="textarea"
|
||||
permission="expense:edit"
|
||||
onSave={(next) => saveRoomCell(r, 'description', next)}
|
||||
>
|
||||
{v || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
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>
|
||||
),
|
||||
},
|
||||
],
|
||||
[rooms, typeOptions, typeMap, saveRoomCell, roomForm, 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
|
||||
const personalColumns = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: '学生',
|
||||
width: 120,
|
||||
render: (_: any, r: any) => (
|
||||
<EditableCell
|
||||
value={r.studentId}
|
||||
editor="select"
|
||||
options={students.map((item) => ({ value: item.id, label: item.name }))}
|
||||
permission="expense:edit"
|
||||
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);
|
||||
}}
|
||||
required
|
||||
onSave={(next) => savePersonalCell(r, 'studentId', next)}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<Popconfirm
|
||||
title="确定删除?"
|
||||
onConfirm={async () => {
|
||||
await api.delete(`/expenses/personal/${record.id}`);
|
||||
message.success('删除成功');
|
||||
fetchData();
|
||||
}}
|
||||
{r.student?.name || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '费用类型',
|
||||
width: 100,
|
||||
dataIndex: 'expenseType',
|
||||
render: (v: string, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="select"
|
||||
options={personalTypeOptions}
|
||||
permission="expense:edit"
|
||||
required
|
||||
onSave={(next) => savePersonalCell(r, 'expenseType', next)}
|
||||
>
|
||||
<Tag color="orange">{typeMap[v] || v}</Tag>
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '金额',
|
||||
dataIndex: 'amount',
|
||||
render: (v: number, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="money"
|
||||
min={0.01}
|
||||
permission="expense:edit"
|
||||
required
|
||||
onSave={(next) => savePersonalCell(r, 'amount', next)}
|
||||
>{`¥${Number(v).toFixed(2)}`}</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '日期',
|
||||
dataIndex: 'expenseDate',
|
||||
width: 110,
|
||||
render: (v: string, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="date"
|
||||
permission="expense:edit"
|
||||
required
|
||||
onSave={(next) => savePersonalCell(r, 'expenseDate', next)}
|
||||
>
|
||||
{v}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '说明',
|
||||
dataIndex: 'description',
|
||||
width: 150,
|
||||
render: (v: string, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="textarea"
|
||||
permission="expense:edit"
|
||||
onSave={(next) => savePersonalCell(r, 'description', next)}
|
||||
>
|
||||
{v || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
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>
|
||||
),
|
||||
},
|
||||
],
|
||||
[students, personalTypeOptions, typeMap, savePersonalCell, personalForm, fetchData],
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -407,8 +605,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 +615,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 +722,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 +744,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 +833,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 +848,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 +918,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
|
||||
@@ -51,16 +56,32 @@ const LoginPage: React.FC = () => {
|
||||
>
|
||||
<div style={{ textAlign: 'center', marginBottom: 32 }}>
|
||||
<Title level={3} style={{ margin: 0, fontWeight: 600, color: '#1d1d1f' }}>
|
||||
恭学教育基地管理系统
|
||||
学生管理系统
|
||||
</Title>
|
||||
<p style={{ color: '#86868b', marginTop: 8 }}>水电费精准计费平台</p>
|
||||
<p style={{ color: '#86868b', marginTop: 8 }}>学生综合管理平台</p>
|
||||
</div>
|
||||
<Form name="login" onFinish={onFinish} size="large">
|
||||
<Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名' }]}>
|
||||
<Input prefix={<UserOutlined />} placeholder="用户名" />
|
||||
<Form name="login" layout="vertical" onFinish={onFinish} size="large">
|
||||
<Form.Item
|
||||
label="用户名"
|
||||
name="username"
|
||||
rules={[{ required: true, message: '请输入用户名' }]}
|
||||
>
|
||||
<Input
|
||||
prefix={<UserOutlined />}
|
||||
placeholder="用户名"
|
||||
autoComplete="username"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码' }]}>
|
||||
<Input.Password prefix={<LockOutlined />} placeholder="密码" />
|
||||
<Form.Item
|
||||
label="密码"
|
||||
name="password"
|
||||
rules={[{ required: true, message: '请输入密码' }]}
|
||||
>
|
||||
<Input.Password
|
||||
prefix={<LockOutlined />}
|
||||
placeholder="密码"
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Button
|
||||
|
||||
@@ -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,8 +1,9 @@
|
||||
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 EditableCell from '../../components/EditableCell';
|
||||
import { message } from '../../ui/app-message';
|
||||
|
||||
const PRESET_COLORS = [
|
||||
@@ -93,46 +94,108 @@ const OrganizationsPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const saveCell = async (record: OrganizationItem, field: string, value: unknown) => {
|
||||
await api.put(`/organizations/${record.id}`, { [field]: value });
|
||||
message.success('已保存');
|
||||
await fetchData();
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: '机构',
|
||||
dataIndex: 'name',
|
||||
width: 220,
|
||||
render: (name: string, record: OrganizationItem) => (
|
||||
<Space>
|
||||
<span
|
||||
style={{
|
||||
width: 10,
|
||||
height: 10,
|
||||
borderRadius: '50%',
|
||||
background: record.color || '#8c8c8c',
|
||||
}}
|
||||
/>
|
||||
<strong>{name}</strong>
|
||||
{record.isHost ? (
|
||||
<Tag color="blue" icon={<BankOutlined />}>
|
||||
本机构
|
||||
</Tag>
|
||||
) : (
|
||||
<Tag>外部机构</Tag>
|
||||
)}
|
||||
</Space>
|
||||
<EditableCell
|
||||
value={name}
|
||||
required
|
||||
permission="organization:edit"
|
||||
disabled={record.status === 'archived'}
|
||||
onSave={(next) => saveCell(record, 'name', next)}
|
||||
>
|
||||
<Space>
|
||||
<span
|
||||
style={{
|
||||
width: 10,
|
||||
height: 10,
|
||||
borderRadius: '50%',
|
||||
background: record.color || '#8c8c8c',
|
||||
}}
|
||||
/>
|
||||
<strong>{name}</strong>
|
||||
{record.isHost ? (
|
||||
<Tag color="blue" icon={<BankOutlined />}>
|
||||
本机构
|
||||
</Tag>
|
||||
) : (
|
||||
<Tag>外部机构</Tag>
|
||||
)}
|
||||
</Space>
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '机构编码',
|
||||
dataIndex: 'code',
|
||||
width: 130,
|
||||
render: (value: string) => <code>{value}</code>,
|
||||
render: (value: string, record: OrganizationItem) => (
|
||||
<EditableCell
|
||||
value={value}
|
||||
required
|
||||
permission="organization:edit"
|
||||
disabled={record.status === 'archived'}
|
||||
onSave={(next) => saveCell(record, 'code', next)}
|
||||
>
|
||||
<code>{value}</code>
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '联系人',
|
||||
dataIndex: 'contactName',
|
||||
width: 120,
|
||||
render: (value?: string) => value || '-',
|
||||
render: (value: string | undefined, record: OrganizationItem) => (
|
||||
<EditableCell
|
||||
value={value}
|
||||
permission="organization:edit"
|
||||
disabled={record.status === 'archived'}
|
||||
onSave={(next) => saveCell(record, 'contactName', next)}
|
||||
>
|
||||
{value || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '电话',
|
||||
dataIndex: 'phone',
|
||||
width: 140,
|
||||
render: (value: string | undefined, record: OrganizationItem) => (
|
||||
<EditableCell
|
||||
value={value}
|
||||
permission="organization:edit"
|
||||
disabled={record.status === 'archived'}
|
||||
onSave={(next) => saveCell(record, 'phone', next)}
|
||||
>
|
||||
{value || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '备注',
|
||||
dataIndex: 'notes',
|
||||
ellipsis: true,
|
||||
render: (value: string | undefined, record: OrganizationItem) => (
|
||||
<EditableCell
|
||||
value={value}
|
||||
editor="textarea"
|
||||
permission="organization:edit"
|
||||
disabled={record.status === 'archived'}
|
||||
onSave={(next) => saveCell(record, 'notes', next)}
|
||||
>
|
||||
{value || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{ title: '电话', dataIndex: 'phone', width: 140, render: (value?: string) => value || '-' },
|
||||
{ title: '备注', dataIndex: 'notes', ellipsis: true, render: (value?: string) => value || '-' },
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
@@ -148,35 +211,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,19 +1,9 @@
|
||||
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 EditableCell from '../../components/EditableCell';
|
||||
import { message } from '../../ui/app-message';
|
||||
|
||||
interface PermissionItem {
|
||||
@@ -106,79 +96,152 @@ 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 permissionOptions = useMemo(
|
||||
() =>
|
||||
allPerms
|
||||
.flatMap((group) => group.permissions)
|
||||
.map((item) => ({ value: item.id, label: `${item.group} · ${item.name}` })),
|
||||
[allPerms],
|
||||
);
|
||||
const saveCell = useCallback(
|
||||
async (record: RoleItem, field: string, value: unknown) => {
|
||||
await api.put(`/rbac/roles/${record.id}`, { [field]: value });
|
||||
message.success('已保存');
|
||||
await fetchData();
|
||||
},
|
||||
{
|
||||
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
|
||||
[fetchData],
|
||||
);
|
||||
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{ title: 'ID', dataIndex: 'id', width: 80 },
|
||||
{
|
||||
title: '名称',
|
||||
dataIndex: 'name',
|
||||
width: 120,
|
||||
render: (v: string, r: RoleItem) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
required
|
||||
permission="role:edit"
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => handleEdit(record)}
|
||||
onSave={(next) => saveCell(r, 'name', next)}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
{!record.isSystem && (
|
||||
<Popconfirm title="确认删除该角色?" onConfirm={() => handleDelete(record.id)}>
|
||||
<PermissionButton permission="role:delete" type="link" size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
], []);
|
||||
{v}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '描述',
|
||||
dataIndex: 'description',
|
||||
width: 200,
|
||||
render: (v: string, r: RoleItem) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="textarea"
|
||||
permission="role:edit"
|
||||
onSave={(next) => saveCell(r, 'description', next)}
|
||||
>
|
||||
{v || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '权限标签',
|
||||
dataIndex: 'permissions',
|
||||
width: 150,
|
||||
render: (perms: PermissionItem[], record: RoleItem) => (
|
||||
<EditableCell
|
||||
value={perms?.map((item) => item.id) || []}
|
||||
editor="multi-select"
|
||||
options={permissionOptions}
|
||||
permission="role:edit"
|
||||
onSave={(next) => saveCell(record, 'permissionIds', next)}
|
||||
>
|
||||
{perms?.length > 0 ? (
|
||||
<Tag color="blue">{perms.length} 个权限</Tag>
|
||||
) : (
|
||||
<Tag color="default">无权限</Tag>
|
||||
)}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '系统',
|
||||
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>
|
||||
),
|
||||
},
|
||||
],
|
||||
[permissionOptions, saveCell],
|
||||
);
|
||||
|
||||
const handleGroupCheckAll = (group: string, checked: boolean) => {
|
||||
const groupPermIds =
|
||||
|
||||
@@ -1,18 +1,50 @@
|
||||
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,
|
||||
Switch,
|
||||
Space,
|
||||
} from 'antd';
|
||||
import {
|
||||
HomeOutlined,
|
||||
UserOutlined,
|
||||
CalendarOutlined,
|
||||
BankOutlined,
|
||||
HistoryOutlined,
|
||||
ShopOutlined,
|
||||
CheckCircleOutlined,
|
||||
SaveOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import dayjs, { Dayjs } from 'dayjs';
|
||||
import api from '../../api';
|
||||
import { message } from '../../ui/app-message';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
import { getInitialPresentOccupancyIds, togglePresentOccupancy } from './inspection-state';
|
||||
|
||||
function getCardStyle(room: any): React.CSSProperties {
|
||||
let base: React.CSSProperties;
|
||||
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 +61,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;
|
||||
@@ -56,6 +91,9 @@ const RoomVisualPage: React.FC = () => {
|
||||
const [selectedOrganization, setSelectedOrganization] = useState<number | 'all'>('all');
|
||||
const [detailRoom, setDetailRoom] = useState<any>(null);
|
||||
const [asOf, setAsOf] = useState<Dayjs | null>(null);
|
||||
const [presentOccupancyIds, setPresentOccupancyIds] = useState<number[]>([]);
|
||||
const [inspectionSaving, setInspectionSaving] = useState(false);
|
||||
const { hasPermission } = usePermission();
|
||||
|
||||
const isHistorical = !!asOf && !asOf.isSame(dayjs(), 'day');
|
||||
|
||||
@@ -76,11 +114,48 @@ const RoomVisualPage: React.FC = () => {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!detailRoom) {
|
||||
setPresentOccupancyIds([]);
|
||||
return;
|
||||
}
|
||||
setPresentOccupancyIds(
|
||||
getInitialPresentOccupancyIds(
|
||||
detailRoom.occupants || [],
|
||||
detailRoom.inspection?.submitted === true,
|
||||
),
|
||||
);
|
||||
}, [detailRoom]);
|
||||
|
||||
const inspectionDate = (asOf || dayjs()).format('YYYY-MM-DD');
|
||||
|
||||
const submitInspection = async () => {
|
||||
if (!detailRoom || isHistorical) return;
|
||||
setInspectionSaving(true);
|
||||
try {
|
||||
await api.put(`/rooms/${detailRoom.id}/inspections/${inspectionDate}`, {
|
||||
presentOccupancyIds,
|
||||
});
|
||||
message.success(detailRoom.inspection?.submitted ? '查寝记录已更新' : '查寝已提交');
|
||||
const params = isHistorical ? { asOf: inspectionDate } : undefined;
|
||||
const res: any = await api.get('/rooms/visual', { params });
|
||||
setData(res);
|
||||
const updatedRoom = res.rooms.find((room: any) => room.id === detailRoom.id);
|
||||
if (updatedRoom) setDetailRoom(updatedRoom);
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
message.error(err?.message || '查寝提交失败');
|
||||
} finally {
|
||||
setInspectionSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!data) return <Spin size="large" style={{ display: 'block', margin: '100px auto' }} />;
|
||||
|
||||
const rooms = data.rooms.filter((r: any) => {
|
||||
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 +213,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 +258,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 +309,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 +340,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 +374,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>
|
||||
@@ -270,6 +391,17 @@ const RoomVisualPage: React.FC = () => {
|
||||
{room.occupants.length > 4 && <Tag>+{room.occupants.length - 4}</Tag>}
|
||||
</div>
|
||||
)}
|
||||
{room.occupants.length > 0 && (
|
||||
<div style={{ marginTop: 4 }}>
|
||||
{room.inspection?.submitted ? (
|
||||
<Tag color={room.inspection.source === 'automatic' ? 'orange' : 'green'}>
|
||||
{room.inspection.source === 'automatic' ? '自动补记' : '已查寝'}
|
||||
</Tag>
|
||||
) : (
|
||||
<Tag>未查寝</Tag>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</Col>
|
||||
))}
|
||||
@@ -313,9 +445,26 @@ const RoomVisualPage: React.FC = () => {
|
||||
<div style={{ marginBottom: 16 }}>{getStatusLabel(detailRoom)}</div>
|
||||
{detailRoom.occupants.length > 0 ? (
|
||||
<div>
|
||||
<h4 style={{ marginBottom: 8 }}>当前住户</h4>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
gap: 12,
|
||||
marginBottom: 8,
|
||||
flexWrap: 'wrap',
|
||||
}}
|
||||
>
|
||||
<h4 style={{ margin: 0 }}>床位查寝</h4>
|
||||
{detailRoom.inspection?.submitted && (
|
||||
<Tag color={detailRoom.inspection.source === 'automatic' ? 'orange' : 'green'}>
|
||||
{detailRoom.inspection.source === 'automatic' ? '自动补记' : '已提交'} ·{' '}
|
||||
{detailRoom.inspection.inspectorName}
|
||||
</Tag>
|
||||
)}
|
||||
</div>
|
||||
{detailRoom.occupants.map((o: any) => (
|
||||
<Card key={o.studentId} size="small" style={{ marginBottom: 8, borderRadius: 8 }}>
|
||||
<Card key={o.occupancyId} size="small" style={{ marginBottom: 8, borderRadius: 8 }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
@@ -332,10 +481,44 @@ const RoomVisualPage: React.FC = () => {
|
||||
</Tag>
|
||||
)}
|
||||
</div>
|
||||
<Tag color="blue">{o.days} 天</Tag>
|
||||
{isHistorical ? (
|
||||
<Tag
|
||||
color={
|
||||
o.inspectionStatus === 'present'
|
||||
? 'green'
|
||||
: o.inspectionStatus === 'absent'
|
||||
? 'red'
|
||||
: 'default'
|
||||
}
|
||||
>
|
||||
{o.inspectionStatus === 'present'
|
||||
? '在寝'
|
||||
: o.inspectionStatus === 'absent'
|
||||
? '缺勤'
|
||||
: '无记录'}
|
||||
</Tag>
|
||||
) : (
|
||||
<Space size="small">
|
||||
<span style={{ color: '#86868b', fontSize: 12 }}>
|
||||
{presentOccupancyIds.includes(o.occupancyId) ? '在寝' : '缺勤'}
|
||||
</span>
|
||||
<Switch
|
||||
checked={presentOccupancyIds.includes(o.occupancyId)}
|
||||
disabled={!hasPermission('room:inspect')}
|
||||
checkedChildren="在寝"
|
||||
unCheckedChildren="缺勤"
|
||||
onChange={(checked) =>
|
||||
setPresentOccupancyIds((current) =>
|
||||
togglePresentOccupancy(current, o.occupancyId, checked),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Space>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ color: '#86868b', fontSize: 12, marginTop: 4 }}>
|
||||
<CalendarOutlined style={{ marginRight: 4 }} />
|
||||
床位:{o.bedNumber || '未分配'} |{' '}
|
||||
入住:{o.checkInDate} | 计费起:{o.billingStartDate}
|
||||
{o.supervisor && (
|
||||
<span style={{ marginLeft: 8 }}>负责人:{o.supervisor}</span>
|
||||
@@ -343,6 +526,37 @@ const RoomVisualPage: React.FC = () => {
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
{!isHistorical && hasPermission('room:inspect') && (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'flex-end',
|
||||
gap: 8,
|
||||
marginTop: 16,
|
||||
flexWrap: 'wrap',
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
icon={<CheckCircleOutlined />}
|
||||
onClick={() =>
|
||||
setPresentOccupancyIds(
|
||||
detailRoom.occupants.map((occupant: any) => occupant.occupancyId),
|
||||
)
|
||||
}
|
||||
>
|
||||
本宿舍一键打卡
|
||||
</Button>
|
||||
<PermissionButton
|
||||
permission="room:inspect"
|
||||
type="primary"
|
||||
icon={<SaveOutlined />}
|
||||
loading={inspectionSaving}
|
||||
onClick={submitInspection}
|
||||
>
|
||||
提交查寝
|
||||
</PermissionButton>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ textAlign: 'center', padding: 24, color: '#86868b' }}>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { getInitialPresentOccupancyIds, togglePresentOccupancy } from './inspection-state';
|
||||
|
||||
describe('room inspection state', () => {
|
||||
const occupants = [
|
||||
{ occupancyId: 11, inspectionStatus: 'present' as const },
|
||||
{ occupancyId: 12, inspectionStatus: 'absent' as const },
|
||||
];
|
||||
|
||||
it('starts every occupant unchecked before the room is submitted', () => {
|
||||
expect(getInitialPresentOccupancyIds(occupants, false)).toEqual([]);
|
||||
});
|
||||
|
||||
it('restores the saved present occupants after submission', () => {
|
||||
expect(getInitialPresentOccupancyIds(occupants, true)).toEqual([11]);
|
||||
});
|
||||
|
||||
it('adds and removes a single occupant without changing the others', () => {
|
||||
expect(togglePresentOccupancy([11], 12, true).sort()).toEqual([11, 12]);
|
||||
expect(togglePresentOccupancy([11, 12], 11, false)).toEqual([12]);
|
||||
});
|
||||
});
|
||||
25
apps/admin/src/pages/RoomVisual/inspection-state.ts
Normal file
25
apps/admin/src/pages/RoomVisual/inspection-state.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
export interface InspectionOccupant {
|
||||
occupancyId: number;
|
||||
inspectionStatus?: 'present' | 'absent' | null;
|
||||
}
|
||||
|
||||
export function getInitialPresentOccupancyIds(
|
||||
occupants: InspectionOccupant[],
|
||||
submitted: boolean,
|
||||
): number[] {
|
||||
if (!submitted) return [];
|
||||
return occupants
|
||||
.filter((occupant) => occupant.inspectionStatus === 'present')
|
||||
.map((occupant) => occupant.occupancyId);
|
||||
}
|
||||
|
||||
export function togglePresentOccupancy(
|
||||
currentIds: number[],
|
||||
occupancyId: number,
|
||||
present: boolean,
|
||||
): number[] {
|
||||
const next = new Set(currentIds);
|
||||
if (present) next.add(occupancyId);
|
||||
else next.delete(occupancyId);
|
||||
return [...next];
|
||||
}
|
||||
@@ -25,11 +25,11 @@ import {
|
||||
InboxOutlined,
|
||||
SearchOutlined,
|
||||
ExportOutlined,
|
||||
DeleteOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import api from '../../api';
|
||||
import { downloadBlob } from '../../utils/download';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
import { message } from '../../ui/app-message';
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
@@ -71,8 +71,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 +93,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 +156,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);
|
||||
@@ -184,6 +200,26 @@ const RoomsPage: React.FC = () => {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const saveRoomCell = async (record: any, field: string, value: unknown) => {
|
||||
await api.put(`/rooms/${record.id}`, { [field]: value });
|
||||
message.success('已保存');
|
||||
await fetchData();
|
||||
};
|
||||
|
||||
const saveBedCell = async (record: BedItem, field: string, value: unknown) => {
|
||||
if (!drawerRoom) return;
|
||||
await api.put(`/rooms/${drawerRoom.id}/beds/${record.id}`, { [field]: value });
|
||||
message.success('已保存');
|
||||
await fetchBeds(drawerRoom.id);
|
||||
};
|
||||
|
||||
const saveLockerCell = async (record: LockerItem, field: string, value: unknown) => {
|
||||
if (!drawerRoom) return;
|
||||
await api.put(`/rooms/${drawerRoom.id}/lockers/${record.id}`, { [field]: value });
|
||||
message.success('已保存');
|
||||
await fetchLockers(drawerRoom.id);
|
||||
};
|
||||
const fetchBeds = useCallback(async (roomId: number) => {
|
||||
try {
|
||||
const res = await api.get<BedItem[]>(`/rooms/${roomId}/beds`);
|
||||
@@ -218,16 +254,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 +276,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 +295,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 +317,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 +351,242 @@ 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 '-';
|
||||
},
|
||||
},
|
||||
{
|
||||
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' }}
|
||||
/>
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: '房间号',
|
||||
dataIndex: 'roomNumber',
|
||||
width: 100,
|
||||
sorter: (a: any, b: any) => a.roomNumber.localeCompare(b.roomNumber),
|
||||
render: (v: string, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
required
|
||||
permission="room:edit"
|
||||
disabled={r.status === 'archived'}
|
||||
onSave={(next) => saveRoomCell(r, 'roomNumber', next)}
|
||||
>
|
||||
{v}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: '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,
|
||||
render: (v: string, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
permission="room:edit"
|
||||
disabled={r.status === 'archived'}
|
||||
onSave={(next) => saveRoomCell(r, 'building', next)}
|
||||
>
|
||||
{v || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '楼层',
|
||||
dataIndex: 'floor',
|
||||
width: 80,
|
||||
render: (v: number, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="number"
|
||||
permission="room:edit"
|
||||
disabled={r.status === 'archived'}
|
||||
onSave={(next) => saveRoomCell(r, 'floor', next)}
|
||||
>
|
||||
{v ?? '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '类型',
|
||||
dataIndex: 'roomType',
|
||||
width: 90,
|
||||
render: (v: any, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
permission="room:edit"
|
||||
disabled={r.status === 'archived'}
|
||||
onSave={(next) => saveRoomCell(r, 'roomType', next)}
|
||||
>
|
||||
{v || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '租赁类型',
|
||||
dataIndex: 'rentalCategory',
|
||||
width: 100,
|
||||
render: (v: string, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="select"
|
||||
options={[
|
||||
{ value: 'long', label: '长租' },
|
||||
{ value: 'short', label: '短租' },
|
||||
]}
|
||||
permission="room:edit"
|
||||
disabled={r.status === 'archived'}
|
||||
onSave={(next) => saveRoomCell(r, 'rentalCategory', next)}
|
||||
>
|
||||
{(() => {
|
||||
if (v === 'long') return <Tag color="blue">长租</Tag>;
|
||||
if (v === 'short') return <Tag color="green">短租</Tag>;
|
||||
return '-';
|
||||
})()}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '月租金',
|
||||
dataIndex: 'monthlyRate',
|
||||
width: 100,
|
||||
render: (v: number, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="money"
|
||||
min={0}
|
||||
permission="room:edit"
|
||||
disabled={r.status === 'archived'}
|
||||
onSave={(next) => saveRoomCell(r, 'monthlyRate', next)}
|
||||
>
|
||||
{v ? `¥${v}` : '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '额定人数',
|
||||
dataIndex: 'capacity',
|
||||
width: 80,
|
||||
render: (v: number, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="number"
|
||||
min={1}
|
||||
required
|
||||
permission="room:edit"
|
||||
disabled={r.status === 'archived'}
|
||||
onSave={(next) => saveRoomCell(r, 'capacity', next)}
|
||||
>
|
||||
{v}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '当前入住',
|
||||
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, r: any) => (
|
||||
<EditableCell
|
||||
value={s}
|
||||
editor="select"
|
||||
options={[
|
||||
{ value: 'available', label: '可入住' },
|
||||
{ value: 'full', label: '已满' },
|
||||
{ value: 'maintenance', label: '维修中' },
|
||||
]}
|
||||
permission="room:edit"
|
||||
disabled={r.status === 'archived'}
|
||||
onSave={(next) => saveRoomCell(r, 'status', next)}
|
||||
>
|
||||
<Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
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 +602,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 +634,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 +645,7 @@ const RoomsPage: React.FC = () => {
|
||||
<PermissionButton
|
||||
permission="room:delete"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
icon={<InboxOutlined />}
|
||||
disabled={selectedRowKeys.length === 0}
|
||||
loading={batchLoading}
|
||||
>
|
||||
@@ -606,7 +797,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 +812,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 +860,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
|
||||
@@ -667,21 +910,68 @@ const RoomsPage: React.FC = () => {
|
||||
pagination={false}
|
||||
size="small"
|
||||
columns={[
|
||||
{ title: '编号', dataIndex: 'bedNumber', width: 80 },
|
||||
{
|
||||
title: '状态', dataIndex: 'status', width: 80,
|
||||
render: (s: string) => {
|
||||
const map: Record<string, { text: string; color: string }> = {
|
||||
available: { text: '空闲', color: 'green' },
|
||||
occupied: { text: '占用', color: 'blue' },
|
||||
maintenance: { text: '维修', color: 'orange' },
|
||||
};
|
||||
return <Tag color={map[s]?.color}>{map[s]?.text || s}</Tag>;
|
||||
},
|
||||
title: '编号',
|
||||
dataIndex: 'bedNumber',
|
||||
width: 80,
|
||||
render: (v: string, r: BedItem) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
required
|
||||
permission="room:edit"
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
onSave={(next) => saveBedCell(r, 'bedNumber', next)}
|
||||
>
|
||||
{v}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{ title: '备注', dataIndex: 'notes', render: (v: string) => v || '-' },
|
||||
{
|
||||
title: '操作', width: 120,
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 80,
|
||||
render: (s: string, r: BedItem) => (
|
||||
<EditableCell
|
||||
value={s}
|
||||
editor="select"
|
||||
options={[
|
||||
{ value: 'available', label: '空闲' },
|
||||
{ value: 'occupied', label: '占用' },
|
||||
{ value: 'maintenance', label: '维修' },
|
||||
]}
|
||||
permission="room:edit"
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
onSave={(next) => saveBedCell(r, 'status', next)}
|
||||
>
|
||||
{(() => {
|
||||
const map: Record<string, { text: string; color: string }> = {
|
||||
available: { text: '空闲', color: 'green' },
|
||||
occupied: { text: '占用', color: 'blue' },
|
||||
maintenance: { text: '维修', color: 'orange' },
|
||||
};
|
||||
return <Tag color={map[s]?.color}>{map[s]?.text || s}</Tag>;
|
||||
})()}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '备注',
|
||||
dataIndex: 'notes',
|
||||
render: (v: string, r: BedItem) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="textarea"
|
||||
permission="room:edit"
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
onSave={(next) => saveBedCell(r, 'notes', next)}
|
||||
>
|
||||
{v || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 120,
|
||||
render: (_: any, r: any) => (
|
||||
<Space size="small">
|
||||
<PermissionButton
|
||||
@@ -689,12 +979,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 +999,7 @@ const RoomsPage: React.FC = () => {
|
||||
danger
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
>
|
||||
删除
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
@@ -725,23 +1022,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
|
||||
@@ -750,21 +1061,68 @@ const RoomsPage: React.FC = () => {
|
||||
pagination={false}
|
||||
size="small"
|
||||
columns={[
|
||||
{ title: '编号', dataIndex: 'lockerNumber', width: 80 },
|
||||
{
|
||||
title: '状态', dataIndex: 'status', width: 80,
|
||||
render: (s: string) => {
|
||||
const map: Record<string, { text: string; color: string }> = {
|
||||
available: { text: '空闲', color: 'green' },
|
||||
occupied: { text: '占用', color: 'blue' },
|
||||
maintenance: { text: '维修', color: 'orange' },
|
||||
};
|
||||
return <Tag color={map[s]?.color}>{map[s]?.text || s}</Tag>;
|
||||
},
|
||||
title: '编号',
|
||||
dataIndex: 'lockerNumber',
|
||||
width: 80,
|
||||
render: (v: string, r: LockerItem) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
required
|
||||
permission="room:edit"
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
onSave={(next) => saveLockerCell(r, 'lockerNumber', next)}
|
||||
>
|
||||
{v}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{ title: '备注', dataIndex: 'notes', render: (v: string) => v || '-' },
|
||||
{
|
||||
title: '操作', width: 120,
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 80,
|
||||
render: (s: string, r: LockerItem) => (
|
||||
<EditableCell
|
||||
value={s}
|
||||
editor="select"
|
||||
options={[
|
||||
{ value: 'available', label: '空闲' },
|
||||
{ value: 'occupied', label: '占用' },
|
||||
{ value: 'maintenance', label: '维修' },
|
||||
]}
|
||||
permission="room:edit"
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
onSave={(next) => saveLockerCell(r, 'status', next)}
|
||||
>
|
||||
{(() => {
|
||||
const map: Record<string, { text: string; color: string }> = {
|
||||
available: { text: '空闲', color: 'green' },
|
||||
occupied: { text: '占用', color: 'blue' },
|
||||
maintenance: { text: '维修', color: 'orange' },
|
||||
};
|
||||
return <Tag color={map[s]?.color}>{map[s]?.text || s}</Tag>;
|
||||
})()}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '备注',
|
||||
dataIndex: 'notes',
|
||||
render: (v: string, r: LockerItem) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
editor="textarea"
|
||||
permission="room:edit"
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
onSave={(next) => saveLockerCell(r, 'notes', next)}
|
||||
>
|
||||
{v || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 120,
|
||||
render: (_: any, r: any) => (
|
||||
<Space size="small">
|
||||
<PermissionButton
|
||||
@@ -772,12 +1130,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 +1150,7 @@ const RoomsPage: React.FC = () => {
|
||||
danger
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
>
|
||||
删除
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
@@ -805,7 +1170,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 +1200,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,7 @@ import {
|
||||
} from 'antd';
|
||||
import type { UploadProps } from 'antd';
|
||||
import {
|
||||
DeleteOutlined,
|
||||
CloudUploadOutlined,
|
||||
DownloadOutlined,
|
||||
ExportOutlined,
|
||||
EyeOutlined,
|
||||
@@ -33,6 +34,8 @@ import {
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import StudentProfileContent from '../../components/StudentProfileContent';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
import JinshujuMatchModal from '../../components/JinshujuMatchModal';
|
||||
import { maskIdNumber, maskPhone } from '../../utils/sensitive';
|
||||
import { message } from '../../ui/app-message';
|
||||
|
||||
@@ -62,6 +65,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 +92,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[]>([]);
|
||||
@@ -87,6 +111,8 @@ const StudentsPage: React.FC = () => {
|
||||
setDrawerOpen(true);
|
||||
};
|
||||
|
||||
const [jinshujuOpen, setJinshujuOpen] = useState(false);
|
||||
|
||||
const handleViewSensitive = (studentId: number, field: string, value: string) => {
|
||||
modal.confirm({
|
||||
title: '查看敏感信息',
|
||||
@@ -137,6 +163,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 +175,14 @@ const StudentsPage: React.FC = () => {
|
||||
message.error(err?.message || '加载失败,请稍后重试');
|
||||
}
|
||||
setLoading(false);
|
||||
}, [searchName, showArchived, filterStatus, filterOrganizationId]);
|
||||
}, [
|
||||
searchName,
|
||||
showArchived,
|
||||
filterStatus,
|
||||
filterOrganizationId,
|
||||
filterClassId,
|
||||
filterTeacherId,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
@@ -160,6 +195,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();
|
||||
@@ -183,6 +225,15 @@ const StudentsPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const saveCell = useCallback(
|
||||
async (record: any, field: string, value: unknown) => {
|
||||
await api.put(`/students/${record.id}`, { [field]: value });
|
||||
message.success('已保存');
|
||||
await fetchData();
|
||||
},
|
||||
[fetchData],
|
||||
);
|
||||
|
||||
const handleArchive = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/students/${id}`);
|
||||
@@ -221,20 +272,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 +368,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);
|
||||
@@ -265,9 +397,15 @@ const StudentsPage: React.FC = () => {
|
||||
dataIndex: 'name',
|
||||
width: 120,
|
||||
render: (v: string, record: any) => (
|
||||
<Button type="link" size="small" onClick={() => openDrawer(record.id)}>
|
||||
<EditableCell
|
||||
value={v}
|
||||
required
|
||||
permission="student:edit"
|
||||
disabled={record.status === 'archived'}
|
||||
onSave={(next) => saveCell(record, 'name', next)}
|
||||
>
|
||||
{v}
|
||||
</Button>
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -277,12 +415,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="点击查看完整号码"
|
||||
>
|
||||
@@ -296,7 +434,16 @@ const StudentsPage: React.FC = () => {
|
||||
title: '学号',
|
||||
dataIndex: 'studentNo',
|
||||
width: 120,
|
||||
render: (v: string) => v || '-',
|
||||
render: (v: string, record: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
permission="student:edit"
|
||||
disabled={record.status === 'archived'}
|
||||
onSave={(next) => saveCell(record, 'studentNo', next)}
|
||||
>
|
||||
{v || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '身份证',
|
||||
@@ -305,12 +452,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="点击查看完整号码"
|
||||
>
|
||||
@@ -320,8 +467,36 @@ const StudentsPage: React.FC = () => {
|
||||
);
|
||||
},
|
||||
},
|
||||
{ title: '民族', dataIndex: 'ethnicity', width: 90 },
|
||||
{ title: '紧急联系人', dataIndex: 'emergencyContact', width: 100 },
|
||||
{
|
||||
title: '民族',
|
||||
dataIndex: 'ethnicity',
|
||||
width: 90,
|
||||
render: (v: string, record: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
permission="student:edit"
|
||||
disabled={record.status === 'archived'}
|
||||
onSave={(next) => saveCell(record, 'ethnicity', next)}
|
||||
>
|
||||
{v || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '紧急联系人',
|
||||
dataIndex: 'emergencyContact',
|
||||
width: 100,
|
||||
render: (v: string, record: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
permission="student:edit"
|
||||
disabled={record.status === 'archived'}
|
||||
onSave={(next) => saveCell(record, 'emergencyContact', next)}
|
||||
>
|
||||
{v || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '紧急联系人电话',
|
||||
dataIndex: 'emergencyPhone',
|
||||
@@ -329,12 +504,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="点击查看完整号码"
|
||||
>
|
||||
@@ -348,30 +523,68 @@ const StudentsPage: React.FC = () => {
|
||||
title: '所属机构',
|
||||
dataIndex: 'organization',
|
||||
width: 100,
|
||||
render: (organization: { name?: string } | null) =>
|
||||
organization?.name ? (
|
||||
<Tag
|
||||
color="purple"
|
||||
style={{ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis' }}
|
||||
>
|
||||
{organization.name}
|
||||
</Tag>
|
||||
) : (
|
||||
'-'
|
||||
),
|
||||
render: (organization: { name?: string } | null, record: any) => (
|
||||
<EditableCell
|
||||
value={record.organizationId}
|
||||
editor="select"
|
||||
options={organizations.map((item) => ({ value: item.id, label: item.name }))}
|
||||
permission="student:edit"
|
||||
disabled={record.status === 'archived'}
|
||||
required
|
||||
onSave={(next) => saveCell(record, 'organizationId', next)}
|
||||
>
|
||||
{organization?.name ? (
|
||||
<Tag
|
||||
color="purple"
|
||||
style={{ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis' }}
|
||||
>
|
||||
{organization.name}
|
||||
</Tag>
|
||||
) : (
|
||||
'-'
|
||||
)}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '负责人',
|
||||
dataIndex: 'supervisor',
|
||||
width: 100,
|
||||
render: (v: string, record: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
permission="student:edit"
|
||||
disabled={record.status === 'archived'}
|
||||
onSave={(next) => saveCell(record, 'supervisor', next)}
|
||||
>
|
||||
{v || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{ title: '负责人', dataIndex: 'supervisor', width: 100 },
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 80,
|
||||
render: (s: string) => (
|
||||
<Tag
|
||||
color={statusMap[s]?.color}
|
||||
style={{ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis' }}
|
||||
render: (s: string, record: any) => (
|
||||
<EditableCell
|
||||
value={s}
|
||||
editor="select"
|
||||
options={[
|
||||
{ value: 'active', label: '在读' },
|
||||
{ value: 'graduated', label: '已毕业' },
|
||||
{ value: 'withdrawn', label: '已退训' },
|
||||
]}
|
||||
permission="student:edit"
|
||||
disabled={record.status === 'archived'}
|
||||
onSave={(next) => saveCell(record, 'status', next)}
|
||||
>
|
||||
{statusMap[s]?.text || s}
|
||||
</Tag>
|
||||
<Tag
|
||||
color={statusMap[s]?.color}
|
||||
style={{ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis' }}
|
||||
>
|
||||
{statusMap[s]?.text || s}
|
||||
</Tag>
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -436,21 +649,13 @@ const StudentsPage: React.FC = () => {
|
||||
),
|
||||
},
|
||||
],
|
||||
[handleViewSensitive, openDrawer, showArchived, organizations],
|
||||
[handleViewSensitive, openDrawer, showArchived, organizations, saveCell],
|
||||
);
|
||||
|
||||
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 +694,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 +733,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 +744,7 @@ const StudentsPage: React.FC = () => {
|
||||
<PermissionButton
|
||||
permission="student:delete"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
icon={<InboxOutlined />}
|
||||
disabled={selectedRowKeys.length === 0}
|
||||
loading={batchLoading}
|
||||
>
|
||||
@@ -533,27 +768,24 @@ 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:edit"
|
||||
icon={<CloudUploadOutlined />}
|
||||
onClick={() => setJinshujuOpen(true)}
|
||||
>
|
||||
同步金数据
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="student:view"
|
||||
icon={<DownloadOutlined />}
|
||||
@@ -570,6 +802,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 +846,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}`}
|
||||
@@ -649,6 +892,8 @@ const StudentsPage: React.FC = () => {
|
||||
<style>{`.archived-row { opacity: 0.6; background: #fafafa !important; }`}</style>
|
||||
<Modal
|
||||
title={editing ? '编辑学生' : '添加学生'}
|
||||
className="student-form-modal"
|
||||
width={720}
|
||||
open={modalOpen}
|
||||
onOk={handleSave}
|
||||
onCancel={() => {
|
||||
@@ -658,7 +903,7 @@ const StudentsPage: React.FC = () => {
|
||||
okText="保存"
|
||||
confirmLoading={saving}
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form form={form} layout="vertical" className="student-form-grid">
|
||||
<Form.Item name="name" label="姓名" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
@@ -723,6 +968,11 @@ const StudentsPage: React.FC = () => {
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<JinshujuMatchModal
|
||||
open={jinshujuOpen}
|
||||
onClose={() => setJinshujuOpen(false)}
|
||||
onApplied={() => { setJinshujuOpen(false); fetchData(); }}
|
||||
/>
|
||||
<Drawer
|
||||
title={null}
|
||||
open={drawerOpen}
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -4,6 +4,7 @@ import { EditOutlined } from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import { message } from '../../ui/app-message';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
|
||||
interface TeacherRow {
|
||||
id: number;
|
||||
@@ -101,87 +102,122 @@ 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>),
|
||||
const saveProfileCell = useCallback(
|
||||
async (record: TeacherRow, field: string, value: unknown) => {
|
||||
await api.put(`/rbac/teachers/${record.id}/profile`, { [field]: value });
|
||||
message.success('已保存');
|
||||
await fetchData();
|
||||
},
|
||||
{
|
||||
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>
|
||||
),
|
||||
},
|
||||
], []);
|
||||
[fetchData],
|
||||
);
|
||||
|
||||
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'], r: TeacherRow) => (
|
||||
<EditableCell
|
||||
value={p?.subjects || []}
|
||||
editor="tags"
|
||||
options={(p?.subjects || []).map((value) => ({ value, label: value }))}
|
||||
permission="teacher:edit"
|
||||
onSave={(next) => saveProfileCell(r, 'subjects', next)}
|
||||
>
|
||||
{p?.subjects?.join('、') || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '入职日期',
|
||||
dataIndex: 'profile',
|
||||
key: 'joinedAt',
|
||||
width: 110,
|
||||
render: (p: TeacherRow['profile'], r: TeacherRow) => (
|
||||
<EditableCell
|
||||
value={p?.joinedAt}
|
||||
editor="date"
|
||||
permission="teacher:edit"
|
||||
onSave={(next) => saveProfileCell(r, 'joinedAt', next)}
|
||||
>
|
||||
{p?.joinedAt || '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
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>
|
||||
),
|
||||
},
|
||||
],
|
||||
[saveProfileCell],
|
||||
);
|
||||
|
||||
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,18 @@
|
||||
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 EditableCell from '../../components/EditableCell';
|
||||
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 +30,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 +72,6 @@ const UsersPage: React.FC = () => {
|
||||
setLoading(false);
|
||||
}, [showArchived]);
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
@@ -141,18 +133,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 +154,162 @@ 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>
|
||||
const saveCell = useCallback(
|
||||
async (record: any, field: string, value: unknown) => {
|
||||
await api.put(`/rbac/users/${record.id}`, { [field]: value });
|
||||
message.success('已保存');
|
||||
await fetchData();
|
||||
},
|
||||
[fetchData],
|
||||
);
|
||||
|
||||
const columns = useMemo(
|
||||
() => [
|
||||
{ title: 'ID', dataIndex: 'id', width: 60 },
|
||||
{
|
||||
title: '用户名',
|
||||
dataIndex: 'username',
|
||||
width: 120,
|
||||
render: (v: string, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
required
|
||||
permission="user:edit"
|
||||
disabled={r.isArchived}
|
||||
onSave={(next) => saveCell(r, 'username', next)}
|
||||
>
|
||||
{v}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: '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
|
||||
},
|
||||
{
|
||||
title: '姓名',
|
||||
dataIndex: 'name',
|
||||
width: 120,
|
||||
render: (v: string, r: any) => (
|
||||
<EditableCell
|
||||
value={v}
|
||||
required
|
||||
permission="user:edit"
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<IdcardOutlined />}
|
||||
onClick={() => handleOpenProfile(record)}
|
||||
disabled={r.isArchived}
|
||||
onSave={(next) => saveCell(r, 'name', next)}
|
||||
>
|
||||
档案
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
{v}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '角色',
|
||||
dataIndex: 'roles',
|
||||
width: 200,
|
||||
render: (v: any[], record: any) => (
|
||||
<EditableCell
|
||||
value={v?.map((item) => item.id) || []}
|
||||
editor="multi-select"
|
||||
options={roles.map((item) => ({ value: item.id, label: item.name }))}
|
||||
permission="user:edit"
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => handleEdit(record)}
|
||||
disabled={record.isArchived}
|
||||
onSave={(next) => saveCell(record, 'roleIds', next)}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="user:reset-password"
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<KeyOutlined />}
|
||||
onClick={() => handleResetPwd(record)}
|
||||
{v && v.length > 0 ? (
|
||||
v.map((r: any) => (
|
||||
<Tag key={r.id} color="blue">
|
||||
{r.name}
|
||||
</Tag>
|
||||
))
|
||||
) : (
|
||||
<Tag color="default">无角色</Tag>
|
||||
)}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'isActive',
|
||||
width: 80,
|
||||
render: (v: boolean, r: any) => (
|
||||
<EditableCell
|
||||
value={String(v)}
|
||||
editor="select"
|
||||
options={[
|
||||
{ value: 'true', label: '启用' },
|
||||
{ value: 'false', label: '禁用' },
|
||||
]}
|
||||
permission="user:edit"
|
||||
disabled={r.isArchived}
|
||||
onSave={(next) => saveCell(r, 'isActive', String(next) === 'true')}
|
||||
>
|
||||
重置密码
|
||||
</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>
|
||||
)}
|
||||
{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={v ? 'green' : 'default'}>{v ? '启用' : '禁用'}</Tag>
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
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>
|
||||
),
|
||||
},
|
||||
],
|
||||
[roles, saveCell],
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -275,7 +321,8 @@ const UsersPage: React.FC = () => {
|
||||
alignItems: 'center',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}>
|
||||
}}
|
||||
>
|
||||
<h2 style={{ margin: 0 }}>账号管理</h2>
|
||||
<Space wrap>
|
||||
<PermissionButton
|
||||
@@ -393,10 +440,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 +459,7 @@ const UsersPage: React.FC = () => {
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
398
apps/admin/src/pages/Wallets/index.tsx
Normal file
398
apps/admin/src/pages/Wallets/index.tsx
Normal file
@@ -0,0 +1,398 @@
|
||||
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={{
|
||||
defaultPageSize: 15,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [15, 30, 50, 100],
|
||||
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();
|
||||
@@ -4,6 +4,33 @@ import react from '@vitejs/plugin-react';
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
build: {
|
||||
rolldownOptions: {
|
||||
output: {
|
||||
codeSplitting: {
|
||||
groups: [
|
||||
{
|
||||
name: 'react',
|
||||
test: /node_modules[\\/](react|react-dom|react-router|react-router-dom)[\\/]/,
|
||||
priority: 30,
|
||||
},
|
||||
{
|
||||
name: 'echarts',
|
||||
test: /node_modules[\\/](echarts|zrender)[\\/]/,
|
||||
priority: 20,
|
||||
maxSize: 600_000,
|
||||
},
|
||||
{
|
||||
name: 'antd',
|
||||
test: /node_modules[\\/](@ant-design|antd|rc-[^\\/]+)[\\/]/,
|
||||
priority: 10,
|
||||
maxSize: 600_000,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 3002,
|
||||
proxy: {
|
||||
|
||||
@@ -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')],
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import tseslint from 'typescript-eslint';
|
||||
|
||||
export default tseslint.config(
|
||||
{
|
||||
ignores: ['eslint.config.mjs'],
|
||||
ignores: ['eslint.config.mjs', 'dist/**'],
|
||||
},
|
||||
eslint.configs.recommended,
|
||||
...tseslint.configs.recommendedTypeChecked,
|
||||
@@ -27,6 +27,29 @@ export default tseslint.config(
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/no-floating-promises': 'warn',
|
||||
'@typescript-eslint/no-unsafe-argument': 'warn',
|
||||
'@typescript-eslint/no-unsafe-assignment': 'warn',
|
||||
'@typescript-eslint/no-unsafe-call': 'warn',
|
||||
'@typescript-eslint/no-unsafe-enum-comparison': 'warn',
|
||||
'@typescript-eslint/no-unsafe-member-access': 'warn',
|
||||
'@typescript-eslint/no-unsafe-return': 'warn',
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'warn',
|
||||
{
|
||||
argsIgnorePattern: '^_',
|
||||
caughtErrorsIgnorePattern: '^_',
|
||||
varsIgnorePattern: '^_',
|
||||
},
|
||||
],
|
||||
'@typescript-eslint/no-base-to-string': 'warn',
|
||||
'@typescript-eslint/no-require-imports': 'warn',
|
||||
'@typescript-eslint/no-unnecessary-type-assertion': 'warn',
|
||||
'@typescript-eslint/restrict-template-expressions': 'warn',
|
||||
'no-empty': ['warn', { allowEmptyCatch: true }],
|
||||
'no-useless-escape': 'warn',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.spec.ts', '**/*.test.ts', 'test/**/*.ts'],
|
||||
extends: [tseslint.configs.disableTypeChecked],
|
||||
},
|
||||
);
|
||||
|
||||
@@ -13,13 +13,20 @@
|
||||
"start": "nest start",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"generate:student-import": "ts-node -r tsconfig-paths/register -P tsconfig.json scripts/generate-student-import-xlsx.ts",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\"",
|
||||
"lint:fix": "npm run lint -- --fix",
|
||||
"typecheck": "tsc -p tsconfig.build.json --noEmit",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"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",
|
||||
|
||||
106
apps/server/scripts/generate-student-import-xlsx.ts
Normal file
106
apps/server/scripts/generate-student-import-xlsx.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
/// <reference types="node" />
|
||||
|
||||
import * as ExcelJS from 'exceljs';
|
||||
import {
|
||||
STUDENT_IMPORT_COLUMNS,
|
||||
createStudentImportTemplateWorkbook,
|
||||
} from '../src/students/student-import';
|
||||
|
||||
const count = Number(process.argv[2] || 1000);
|
||||
const output = process.argv[3] || `student-import-${count}.xlsx`;
|
||||
|
||||
function getWorksheetOrThrow(workbook: ExcelJS.Workbook, name: string) {
|
||||
const sheet = workbook.getWorksheet(name);
|
||||
if (!sheet) throw new Error(`Worksheet not found: ${name}`);
|
||||
return sheet;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (!Number.isInteger(count) || count <= 0) {
|
||||
throw new Error('Count must be a positive integer');
|
||||
}
|
||||
|
||||
const workbook = createStudentImportTemplateWorkbook();
|
||||
const students = getWorksheetOrThrow(workbook, '学生基础+档案+录取');
|
||||
const enrollments = getWorksheetOrThrow(workbook, '报读班型');
|
||||
const examScores = getWorksheetOrThrow(workbook, '考试成绩');
|
||||
const learningRecords = getWorksheetOrThrow(workbook, '课堂回访');
|
||||
|
||||
for (let i = 1; i <= count; i++) {
|
||||
const serial = String(i).padStart(4, '0');
|
||||
const phone = `138${String(i).padStart(8, '0')}`;
|
||||
students.addRow({
|
||||
phone,
|
||||
name: `导入学生${serial}`,
|
||||
studentNo: `GX${serial}`,
|
||||
gender: i % 2 === 0 ? '女' : '男',
|
||||
idNumber: `110101200601${String((i % 28) + 1).padStart(2, '0')}${String(i % 1000).padStart(3, '0')}X`,
|
||||
ethnicity: '汉族',
|
||||
emergencyContact: `联系人${serial}`,
|
||||
emergencyPhone: `139${String(i).padStart(8, '0')}`,
|
||||
organization: '',
|
||||
supervisor: '',
|
||||
targetCollege: `目标院校${(i % 20) + 1}`,
|
||||
targetMajor: `目标专业${(i % 10) + 1}`,
|
||||
collegeSchool: `大专院校${(i % 12) + 1}`,
|
||||
collegeMajor: `大专专业${(i % 8) + 1}`,
|
||||
subjectDirection: ['物化生', '物化地', '史政地'][i % 3],
|
||||
grade: '高三',
|
||||
profileDate: '2024-09-01',
|
||||
notes: '',
|
||||
cultureFinalScore: 500 + (i % 151),
|
||||
professionalFinalScore: 300 + (i % 101),
|
||||
admissionStatus: 'pending',
|
||||
admittedCollege: '',
|
||||
admittedMajor: '',
|
||||
});
|
||||
|
||||
enrollments.addRow({
|
||||
phone,
|
||||
name: `导入学生${serial}`,
|
||||
courseCategory: i % 2 === 0 ? 'culture' : 'professional',
|
||||
classType: i % 3 === 0 ? 'small_group' : 'one_on_one',
|
||||
className: `导入测试班${(i % 10) + 1}`,
|
||||
headTeacher: '',
|
||||
subjectTeacher: '',
|
||||
startDate: '2024-09-01',
|
||||
endDate: '2025-06-01',
|
||||
status: 'active',
|
||||
});
|
||||
|
||||
examScores.addRow({
|
||||
phone,
|
||||
name: `导入学生${serial}`,
|
||||
examType: 'monthly',
|
||||
examName: '导入测试月考',
|
||||
subject: '语文',
|
||||
score: 80 + (i % 41),
|
||||
classAvg: 90,
|
||||
rank: (i % 50) + 1,
|
||||
examDate: '2024-10-15',
|
||||
enrollmentName: `导入测试班${(i % 10) + 1}`,
|
||||
});
|
||||
|
||||
learningRecords.addRow({
|
||||
phone,
|
||||
name: `导入学生${serial}`,
|
||||
recordDate: '2024-10-20',
|
||||
recordType: 'study_feedback',
|
||||
content: `导入测试回访${serial}`,
|
||||
followUpMethod: 'phone',
|
||||
nextStep: '',
|
||||
});
|
||||
}
|
||||
|
||||
for (const sheet of workbook.worksheets) {
|
||||
sheet.views = [{ state: 'frozen', ySplit: 1 }];
|
||||
}
|
||||
|
||||
await workbook.xlsx.writeFile(output);
|
||||
console.log(`Generated ${count} students with ${STUDENT_IMPORT_COLUMNS.length} main columns: ${output}`);
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -8,6 +8,16 @@ import {
|
||||
randomBytes,
|
||||
} from 'node:crypto';
|
||||
|
||||
jest.mock('node:dns', () => ({
|
||||
lookup: jest.fn(
|
||||
(
|
||||
_hostname: string,
|
||||
_options: unknown,
|
||||
callback: (error: null, addresses: Array<{ address: string; family: number }>) => void,
|
||||
) => callback(null, [{ address: '203.0.113.10', family: 4 }]),
|
||||
),
|
||||
}));
|
||||
|
||||
import { AiConfigService } from './ai-config.service';
|
||||
import { AiConfig, AiProvider, SINGLETON_KEY } from './ai-config.entity';
|
||||
|
||||
@@ -105,6 +115,8 @@ describe('AiConfigService', () => {
|
||||
afterEach(() => {
|
||||
delete process.env.AI_CONFIG_ENCRYPTION_KEY;
|
||||
delete process.env.AI_API_KEY;
|
||||
delete process.env.AI_ALLOW_PRIVATE_BASE_URL;
|
||||
delete process.env.NODE_ENV;
|
||||
});
|
||||
|
||||
// ── Encryption ────────────────────────────────────────────────────────
|
||||
|
||||
@@ -17,6 +17,8 @@ import {
|
||||
BillItem,
|
||||
User,
|
||||
OperationLog,
|
||||
RoomInspection,
|
||||
RoomInspectionDetail,
|
||||
Deposit,
|
||||
DepositInstallment,
|
||||
Classroom,
|
||||
@@ -30,6 +32,8 @@ import {
|
||||
ClassSchedule,
|
||||
AttendanceRecord,
|
||||
AttendanceSession,
|
||||
AttendanceDevice,
|
||||
AttendancePeriodConfig,
|
||||
DingAttendanceRaw,
|
||||
SyncLog,
|
||||
SyncState,
|
||||
@@ -37,14 +41,29 @@ import {
|
||||
StudentProfile,
|
||||
StudentEnrollment,
|
||||
ExamScore,
|
||||
Exam,
|
||||
LearningRecord,
|
||||
ExpenseType,
|
||||
ResultArchive,
|
||||
ArchiveAttachment,
|
||||
StudentDingMapping,
|
||||
JinshujuMatchRule,
|
||||
AiConfig,
|
||||
StudentWallet,
|
||||
WalletTransaction,
|
||||
FinancialOperation,
|
||||
} from './entities';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { InitialSchema1784520727860 } from './migrations/1784520727860-InitialSchema';
|
||||
import { AddExamManagement1784600000000 } from './migrations/1784600000000-AddExamManagement';
|
||||
import { AddRoomInspections1784680000000 } from './migrations/1784680000000-AddRoomInspections';
|
||||
import { AddJinshujuMatchRules1784700000000 } from './migrations/1784700000000-AddJinshujuMatchRules';
|
||||
const allMigrations = [
|
||||
InitialSchema1784520727860,
|
||||
AddExamManagement1784600000000,
|
||||
AddRoomInspections1784680000000,
|
||||
AddJinshujuMatchRules1784700000000,
|
||||
];
|
||||
import { AuthorizationModule } from './authorization';
|
||||
import { RbacModule } from './rbac/rbac.module';
|
||||
import { StudentsModule } from './students/students.module';
|
||||
@@ -62,6 +81,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 +91,9 @@ 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 { ExamsModule } from './exams/exams.module';
|
||||
|
||||
import {
|
||||
IntegrationConfig,
|
||||
@@ -107,6 +130,8 @@ import { IntegrationConfigModule } from './integration/config/config.module';
|
||||
BillItem,
|
||||
User,
|
||||
OperationLog,
|
||||
RoomInspection,
|
||||
RoomInspectionDetail,
|
||||
Deposit,
|
||||
DepositInstallment,
|
||||
Classroom,
|
||||
@@ -120,12 +145,17 @@ import { IntegrationConfigModule } from './integration/config/config.module';
|
||||
ClassSchedule,
|
||||
AttendanceRecord,
|
||||
AttendanceSession,
|
||||
AttendanceDevice,
|
||||
AttendancePeriodConfig,
|
||||
DingAttendanceRaw,
|
||||
Notification,
|
||||
StudentProfile,
|
||||
StudentEnrollment,
|
||||
ExamScore,
|
||||
Exam,
|
||||
LearningRecord,
|
||||
StudentDingMapping,
|
||||
JinshujuMatchRule,
|
||||
ExpenseType,
|
||||
ArchiveAttachment,
|
||||
ResultArchive,
|
||||
@@ -135,6 +165,9 @@ import { IntegrationConfigModule } from './integration/config/config.module';
|
||||
IntegrationConfig,
|
||||
IntegrationConfigDetail,
|
||||
AiConfig,
|
||||
StudentWallet,
|
||||
WalletTransaction,
|
||||
FinancialOperation,
|
||||
];
|
||||
if (dbType === 'mysql') {
|
||||
return {
|
||||
@@ -145,6 +178,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 +186,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',
|
||||
};
|
||||
@@ -161,6 +196,7 @@ import { IntegrationConfigModule } from './integration/config/config.module';
|
||||
AuthModule,
|
||||
RbacModule,
|
||||
StudentsModule,
|
||||
ExamsModule,
|
||||
RoomsModule,
|
||||
OccupanciesModule,
|
||||
ExpensesModule,
|
||||
@@ -168,8 +204,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()}
|
||||
`);
|
||||
}
|
||||
@@ -412,11 +412,13 @@ ${this.buildLearningAndResult(learnings, result, now)}
|
||||
const highestName = highestExam?.examName ?? '-';
|
||||
|
||||
// Improvement: last exam score minus first exam score
|
||||
const sortedExams = [...cultureExams].filter((e) => e.score != null);
|
||||
const sortedScores = cultureExams
|
||||
.map((exam) => exam.score)
|
||||
.filter((score): score is number => score !== null && score !== undefined);
|
||||
let improvement = '—';
|
||||
if (sortedExams.length >= 2) {
|
||||
const first = sortedExams[0].score;
|
||||
const last = sortedExams[sortedExams.length - 1].score;
|
||||
if (sortedScores.length >= 2) {
|
||||
const first = sortedScores[0];
|
||||
const last = sortedScores[sortedScores.length - 1];
|
||||
improvement = (last - first).toFixed(1);
|
||||
}
|
||||
|
||||
@@ -511,7 +513,7 @@ ${this.buildLearningAndResult(learnings, result, now)}
|
||||
const cultureExams = exams.filter((e) => e.score != null);
|
||||
if (cultureExams.length === 0) return '';
|
||||
|
||||
const scores = cultureExams.map((e) => e.score);
|
||||
const scores = cultureExams.map((e) => Number(e.score));
|
||||
const labels = cultureExams.map((e) => {
|
||||
const d = e.examDate || '-';
|
||||
return d.length > 7 ? d.slice(5) : d;
|
||||
|
||||
118
apps/server/src/archive/archive.boundaries.spec.ts
Normal file
118
apps/server/src/archive/archive.boundaries.spec.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
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('keeps exam-management scores read-only in the student archive', async () => {
|
||||
const exam = {
|
||||
findOne: jest.fn().mockResolvedValue({ id: 3, studentId: 7, examId: 8 }),
|
||||
save: jest.fn(),
|
||||
update: jest.fn(),
|
||||
};
|
||||
const service = createService({ exam });
|
||||
|
||||
await expect(service.updateExamScore(3, { score: 95 })).rejects.toBeInstanceOf(
|
||||
BadRequestException,
|
||||
);
|
||||
await expect(service.deleteExamScore(3)).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(exam.save).not.toHaveBeenCalled();
|
||||
expect(exam.update).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,
|
||||
) {}
|
||||
|
||||
@@ -56,18 +58,37 @@ export class ArchiveService {
|
||||
}
|
||||
|
||||
async getProfile(studentId: number) {
|
||||
const student = await this.studentRepo.findOne({ where: { id: studentId } });
|
||||
const student = await this.studentRepo.findOne({
|
||||
where: { id: studentId },
|
||||
relations: ['organization'],
|
||||
});
|
||||
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' },
|
||||
relations: ['exam', 'exam.class'],
|
||||
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 +98,7 @@ export class ArchiveService {
|
||||
learningRecords,
|
||||
result: resultArchive,
|
||||
attachments,
|
||||
attendances,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -111,13 +133,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 +158,8 @@ export class ArchiveService {
|
||||
async updateExamScore(id: number, dto: UpdateExamScoreDto) {
|
||||
const entity = await this.examScoreRepo.findOne({ where: { id } });
|
||||
if (!entity) throw new NotFoundException('考试成绩不存在');
|
||||
if (entity.examId) throw new BadRequestException('考试管理同步成绩请在考试管理中修改');
|
||||
await this.assertEnrollmentBelongsToStudent(entity.studentId, dto.enrollmentId);
|
||||
Object.assign(entity, dto);
|
||||
return this.examScoreRepo.save(entity);
|
||||
}
|
||||
@@ -133,8 +167,10 @@ 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.examId) throw new BadRequestException('考试管理同步成绩不能在学生档案中归档');
|
||||
if (entity.status === 'archived') throw new BadRequestException('考试成绩已归档');
|
||||
await this.examScoreRepo.update(id, { status: 'archived' });
|
||||
return { message: '已归档' };
|
||||
}
|
||||
|
||||
async addLearningRecord(studentId: number, dto: CreateLearningRecordDto) {
|
||||
@@ -155,8 +191,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 +210,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 +253,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,9 +1,11 @@
|
||||
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;
|
||||
@IsOptional() @IsString() targetMajor?: string;
|
||||
@IsOptional() @IsString() collegeSchool?: string;
|
||||
@IsOptional() @IsString() collegeMajor?: string;
|
||||
@IsOptional() @IsString() subjectDirection?: string;
|
||||
@IsOptional() @IsString() grade?: string;
|
||||
@IsOptional() @IsDateString() profileDate?: string;
|
||||
@@ -11,8 +13,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 +26,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 +40,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 +49,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 {}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user