feat(task1): restructure directories for turborepo monorepo
- Move backend/ to apps/server/ via git mv - Move frontend/ to apps/admin/ via git mv - Create packages/typescript-config/ with base, nestjs, and react-vite presets
This commit is contained in:
24
apps/admin/.gitignore
vendored
Normal file
24
apps/admin/.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
12
apps/admin/Dockerfile
Normal file
12
apps/admin/Dockerfile
Normal file
@@ -0,0 +1,12 @@
|
||||
FROM node:22-alpine AS builder
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
EXPOSE 80
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
73
apps/admin/README.md
Normal file
73
apps/admin/README.md
Normal file
@@ -0,0 +1,73 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
```js
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
|
||||
// Remove tseslint.configs.recommended and replace with this
|
||||
tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
tseslint.configs.stylisticTypeChecked,
|
||||
|
||||
// Other configs...
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
// Enable lint rules for React
|
||||
reactX.configs['recommended-typescript'],
|
||||
// Enable lint rules for React DOM
|
||||
reactDom.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
23
apps/admin/eslint.config.js
Normal file
23
apps/admin/eslint.config.js
Normal file
@@ -0,0 +1,23 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
13
apps/admin/index.html
Normal file
13
apps/admin/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<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>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
17
apps/admin/nginx.conf
Normal file
17
apps/admin/nginx.conf
Normal file
@@ -0,0 +1,17 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://backend:3000/api/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
}
|
||||
}
|
||||
4340
apps/admin/package-lock.json
generated
Normal file
4340
apps/admin/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
38
apps/admin/package.json
Normal file
38
apps/admin/package.json
Normal file
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^6.1.1",
|
||||
"antd": "^6.3.6",
|
||||
"axios": "^1.15.1",
|
||||
"dayjs": "^1.11.20",
|
||||
"echarts": "^6.0.0",
|
||||
"echarts-for-react": "^3.0.6",
|
||||
"react": "^19.2.5",
|
||||
"react-dom": "^19.2.5",
|
||||
"react-router-dom": "^7.14.1",
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.4",
|
||||
"@types/node": "^24.12.2",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"eslint": "^9.39.4",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.5.0",
|
||||
"typescript": "~6.0.2",
|
||||
"typescript-eslint": "^8.58.2",
|
||||
"vite": "^8.0.9"
|
||||
}
|
||||
}
|
||||
1
apps/admin/public/favicon.svg
Normal file
1
apps/admin/public/favicon.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
24
apps/admin/public/icons.svg
Normal file
24
apps/admin/public/icons.svg
Normal file
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
184
apps/admin/src/App.css
Normal file
184
apps/admin/src/App.css
Normal file
@@ -0,0 +1,184 @@
|
||||
.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);
|
||||
}
|
||||
}
|
||||
63
apps/admin/src/App.tsx
Normal file
63
apps/admin/src/App.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
import React from 'react';
|
||||
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
|
||||
import { ConfigProvider, App as AntdApp } from 'antd';
|
||||
import zhCN from 'antd/es/locale/zh_CN';
|
||||
import MainLayout from './layouts/MainLayout';
|
||||
import LoginPage from './pages/Login';
|
||||
import DashboardPage from './pages/Dashboard';
|
||||
import StudentsPage from './pages/Students';
|
||||
import RoomsPage from './pages/Rooms';
|
||||
import OccupanciesPage from './pages/Occupancies';
|
||||
import ExpensesPage from './pages/Expenses';
|
||||
import BillsPage from './pages/Bills';
|
||||
import RoomVisualPage from './pages/RoomVisual';
|
||||
import OperationLogsPage from './pages/OperationLogs';
|
||||
import UsersPage from './pages/Users';
|
||||
import DepositsPage from './pages/Deposits';
|
||||
import ClassroomsPage from './pages/Classrooms';
|
||||
import TenantsPage from './pages/Tenants';
|
||||
import ClassroomRentalsPage from './pages/ClassroomRentals';
|
||||
import ClassroomSchedulePage from './pages/ClassroomSchedule';
|
||||
import RolesPage from './pages/Roles';
|
||||
import PermissionsPage from './pages/Permissions';
|
||||
import PermissionRoute from './components/PermissionRoute';
|
||||
|
||||
const PrivateRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const token = localStorage.getItem('token');
|
||||
return token ? <>{children}</> : <Navigate to="/login" />;
|
||||
};
|
||||
|
||||
const App: React.FC = () => {
|
||||
return (
|
||||
<ConfigProvider locale={zhCN} theme={{ token: { colorPrimary: '#007AFF', borderRadius: 10, colorBgContainer: '#fff', fontFamily: "-apple-system, BlinkMacSystemFont, 'SF Pro Display', 'SF Pro Text', 'Helvetica Neue', Arial, sans-serif" } }}>
|
||||
<AntdApp>
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/" element={<PrivateRoute><MainLayout /></PrivateRoute>}>
|
||||
<Route index element={<Navigate to="/dashboard" />} />
|
||||
<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="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="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="classrooms" element={<PermissionRoute permission="classroom:view"><ClassroomsPage /></PermissionRoute>} />
|
||||
<Route path="tenants" element={<PermissionRoute permission="tenant:view"><TenantsPage /></PermissionRoute>} />
|
||||
<Route path="classroom-rentals" element={<PermissionRoute permission="rental:view"><ClassroomRentalsPage /></PermissionRoute>} />
|
||||
<Route path="classroom-schedule" element={<PermissionRoute permission="classroom:view"><ClassroomSchedulePage /></PermissionRoute>} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</AntdApp>
|
||||
</ConfigProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export default App;
|
||||
33
apps/admin/src/api/index.ts
Normal file
33
apps/admin/src/api/index.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import axios from 'axios';
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: '/api',
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem('token');
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
api.interceptors.response.use(
|
||||
(res) => res.data,
|
||||
(err) => {
|
||||
if (err.response?.status === 401) {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('user');
|
||||
localStorage.removeItem('permissions');
|
||||
window.location.href = '/login';
|
||||
}
|
||||
if (err.response?.status === 403) {
|
||||
const msg = err.response?.data?.message || '权限不足';
|
||||
console.warn('[403]', msg);
|
||||
}
|
||||
return Promise.reject(err.response?.data || err);
|
||||
},
|
||||
);
|
||||
|
||||
export default api;
|
||||
BIN
apps/admin/src/assets/hero.png
Normal file
BIN
apps/admin/src/assets/hero.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
1
apps/admin/src/assets/react.svg
Normal file
1
apps/admin/src/assets/react.svg
Normal file
@@ -0,0 +1 @@
|
||||
<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>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
1
apps/admin/src/assets/vite.svg
Normal file
1
apps/admin/src/assets/vite.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 8.5 KiB |
17
apps/admin/src/components/PermissionButton.tsx
Normal file
17
apps/admin/src/components/PermissionButton.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import React from 'react';
|
||||
import { Button } from 'antd';
|
||||
import type { ButtonProps } from 'antd';
|
||||
import { usePermission } from '../hooks/usePermission';
|
||||
|
||||
interface PermissionButtonProps extends ButtonProps {
|
||||
permission: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
const PermissionButton: React.FC<PermissionButtonProps> = ({ permission, children, ...btnProps }) => {
|
||||
const { hasPermission } = usePermission();
|
||||
if (!hasPermission(permission)) return null;
|
||||
return <Button {...btnProps}>{children}</Button>;
|
||||
};
|
||||
|
||||
export default PermissionButton;
|
||||
24
apps/admin/src/components/PermissionRoute.tsx
Normal file
24
apps/admin/src/components/PermissionRoute.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import React from 'react';
|
||||
import { Result } from 'antd';
|
||||
import { usePermission } from '../hooks/usePermission';
|
||||
|
||||
interface PermissionRouteProps {
|
||||
permission: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
const PermissionRoute: React.FC<PermissionRouteProps> = ({ permission, children }) => {
|
||||
const { hasPermission } = usePermission();
|
||||
if (!hasPermission(permission)) {
|
||||
return (
|
||||
<Result
|
||||
status="403"
|
||||
title="无权访问"
|
||||
subTitle="您没有访问此页面的权限"
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <>{children}</>;
|
||||
};
|
||||
|
||||
export default PermissionRoute;
|
||||
21
apps/admin/src/hooks/usePermission.ts
Normal file
21
apps/admin/src/hooks/usePermission.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { useMemo } from 'react';
|
||||
|
||||
export function usePermission() {
|
||||
const permissions: string[] = useMemo(() => {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem('permissions') || '[]');
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}, []);
|
||||
|
||||
const hasPermission = (code: string): boolean => permissions.includes(code);
|
||||
|
||||
const hasAnyPermission = (...codes: string[]): boolean =>
|
||||
codes.some(c => permissions.includes(c));
|
||||
|
||||
const hasAllPermissions = (...codes: string[]): boolean =>
|
||||
codes.every(c => permissions.includes(c));
|
||||
|
||||
return { permissions, hasPermission, hasAnyPermission, hasAllPermissions };
|
||||
}
|
||||
47
apps/admin/src/index.css
Normal file
47
apps/admin/src/index.css
Normal file
@@ -0,0 +1,47 @@
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
#root {
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
/* 移动端自适应 */
|
||||
@media (max-width: 767px) {
|
||||
.ant-table {
|
||||
font-size: 13px;
|
||||
}
|
||||
.ant-table-cell {
|
||||
padding: 8px 6px !important;
|
||||
}
|
||||
.ant-descriptions-item-label,
|
||||
.ant-descriptions-item-content {
|
||||
font-size: 13px;
|
||||
}
|
||||
.ant-modal {
|
||||
max-width: calc(100vw - 24px) !important;
|
||||
margin: 12px auto !important;
|
||||
}
|
||||
.ant-modal .ant-modal-body {
|
||||
max-height: 60vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
h2 {
|
||||
font-size: 18px !important;
|
||||
}
|
||||
.ant-card {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.ant-space-item .ant-btn {
|
||||
padding: 2px 6px;
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
166
apps/admin/src/layouts/MainLayout.tsx
Normal file
166
apps/admin/src/layouts/MainLayout.tsx
Normal file
@@ -0,0 +1,166 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
|
||||
import { Layout, Menu, Button, Avatar, Dropdown, Drawer } from 'antd';
|
||||
import {
|
||||
DashboardOutlined,
|
||||
TeamOutlined,
|
||||
HomeOutlined,
|
||||
SwapOutlined,
|
||||
DollarOutlined,
|
||||
FileTextOutlined,
|
||||
LogoutOutlined,
|
||||
UserOutlined,
|
||||
MenuFoldOutlined,
|
||||
MenuUnfoldOutlined,
|
||||
AppstoreOutlined,
|
||||
AuditOutlined,
|
||||
SettingOutlined,
|
||||
WalletOutlined,
|
||||
ReadOutlined,
|
||||
TagsOutlined,
|
||||
FileProtectOutlined,
|
||||
CalendarOutlined,
|
||||
SafetyOutlined,
|
||||
KeyOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { usePermission } from '../hooks/usePermission';
|
||||
|
||||
const { Header, Sider, Content } = Layout;
|
||||
|
||||
interface MenuItemType {
|
||||
key: string;
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
permission?: string;
|
||||
children?: MenuItemType[];
|
||||
}
|
||||
|
||||
const allMenuItems: MenuItemType[] = [
|
||||
{ key: '/dashboard', icon: <DashboardOutlined />, label: '数据面板', permission: 'dashboard:view' },
|
||||
{ key: '/room-visual', icon: <AppstoreOutlined />, label: '宿舍总览', permission: 'room:view' },
|
||||
{ key: '/students', icon: <TeamOutlined />, label: '学生管理', permission: 'student:view' },
|
||||
{ key: '/rooms', icon: <HomeOutlined />, label: '宿舍管理', permission: 'room:view' },
|
||||
{ key: '/occupancies', icon: <SwapOutlined />, label: '入住管理', permission: 'occupancy:view' },
|
||||
{ key: '/expenses', icon: <DollarOutlined />, label: '费用录入', permission: 'expense:view' },
|
||||
{ key: '/deposits', icon: <WalletOutlined />, label: '押金管理', permission: 'deposit:view' },
|
||||
{ key: '/bills', icon: <FileTextOutlined />, label: '账单管理', permission: 'bill:view' },
|
||||
{
|
||||
key: 'classroom-group',
|
||||
icon: <ReadOutlined />,
|
||||
label: '教室管理',
|
||||
permission: 'classroom:view',
|
||||
children: [
|
||||
{ key: '/classroom-schedule', icon: <CalendarOutlined />, label: '排期总览', permission: 'classroom:view' },
|
||||
{ key: '/classrooms', icon: <ReadOutlined />, label: '教室列表', permission: 'classroom:view' },
|
||||
{ key: '/classroom-rentals', icon: <FileProtectOutlined />, label: '租赁订单', permission: 'rental:view' },
|
||||
{ key: '/tenants', icon: <TagsOutlined />, label: '租赁方', permission: 'tenant:view' },
|
||||
],
|
||||
},
|
||||
{ key: '/operation-logs', icon: <AuditOutlined />, label: '操作日志', permission: 'log:view' },
|
||||
{ key: '/roles', icon: <SafetyOutlined />, label: '角色管理', permission: 'role:view' },
|
||||
{ key: '/permissions', icon: <KeyOutlined />, label: '权限一览', permission: 'role:view' },
|
||||
{ key: '/users', icon: <SettingOutlined />, label: '账号管理', permission: 'user:view' },
|
||||
];
|
||||
|
||||
const MainLayout: React.FC = () => {
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const [isMobile, setIsMobile] = useState(window.innerWidth < 768);
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const user = JSON.parse(localStorage.getItem('user') || '{}');
|
||||
const { hasPermission } = usePermission();
|
||||
|
||||
useEffect(() => {
|
||||
const handleResize = () => setIsMobile(window.innerWidth < 768);
|
||||
window.addEventListener('resize', handleResize);
|
||||
return () => window.removeEventListener('resize', handleResize);
|
||||
}, []);
|
||||
|
||||
// 按 permission 过滤菜单
|
||||
const filterByPermission = (items: MenuItemType[]): MenuItemType[] => {
|
||||
return items
|
||||
.map(item => {
|
||||
if (item.children) {
|
||||
const kids = filterByPermission(item.children);
|
||||
if (kids.length === 0) return null;
|
||||
return { ...item, children: kids };
|
||||
}
|
||||
if (!item.permission) return item;
|
||||
return hasPermission(item.permission) ? item : null;
|
||||
})
|
||||
.filter(Boolean) as MenuItemType[];
|
||||
};
|
||||
|
||||
const menuItems = filterByPermission(allMenuItems);
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('user');
|
||||
localStorage.removeItem('permissions');
|
||||
navigate('/login');
|
||||
};
|
||||
|
||||
const handleMenuClick = (key: string) => {
|
||||
navigate(key);
|
||||
if (isMobile) setDrawerOpen(false);
|
||||
};
|
||||
|
||||
const transformToMenuItems = (items: MenuItemType[]): any[] => {
|
||||
return items.map(item => ({
|
||||
key: item.key,
|
||||
icon: item.icon,
|
||||
label: item.label,
|
||||
children: item.children ? transformToMenuItems(item.children) : undefined,
|
||||
}));
|
||||
};
|
||||
|
||||
const menuContent = (
|
||||
<Menu
|
||||
theme="light"
|
||||
mode="inline"
|
||||
selectedKeys={[location.pathname]}
|
||||
items={transformToMenuItems(menuItems)}
|
||||
onClick={({ key }) => handleMenuClick(key)}
|
||||
style={{ border: 'none' }}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<Layout style={{ minHeight: '100vh' }}>
|
||||
{!isMobile && (
|
||||
<Sider trigger={null} collapsible collapsed={collapsed} theme="light" style={{ background: '#fff', borderRight: '1px solid #e5e5e7' }}>
|
||||
<div style={{ height: 64, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#1d1d1f', fontSize: collapsed ? 16 : 17, fontWeight: 600, borderBottom: '1px solid #e5e5e7' }}>
|
||||
{collapsed ? '恭' : '恭学教育基地'}
|
||||
</div>
|
||||
{menuContent}
|
||||
</Sider>
|
||||
)}
|
||||
{isMobile && (
|
||||
<Drawer placement="left" open={drawerOpen} onClose={() => setDrawerOpen(false)} width={240} styles={{ body: { padding: 0 } }} title="恭学教育基地">
|
||||
{menuContent}
|
||||
</Drawer>
|
||||
)}
|
||||
<Layout style={{ background: '#f5f5f7' }}>
|
||||
<Header style={{ padding: '0 16px', background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderBottom: '1px solid #e5e5e7', boxShadow: 'none' }}>
|
||||
<Button
|
||||
type="text"
|
||||
icon={isMobile ? <MenuUnfoldOutlined /> : (collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />)}
|
||||
onClick={() => isMobile ? setDrawerOpen(true) : setCollapsed(!collapsed)}
|
||||
/>
|
||||
<Dropdown menu={{ items: [{ key: 'logout', icon: <LogoutOutlined />, label: '退出登录', onClick: handleLogout }] }}>
|
||||
<div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<Avatar icon={<UserOutlined />} />
|
||||
<span>{user.name || user.username || '用户'}</span>
|
||||
</div>
|
||||
</Dropdown>
|
||||
</Header>
|
||||
<Content style={{ margin: isMobile ? 12 : 24, padding: isMobile ? 12 : 24, background: '#fff', borderRadius: 12, overflow: 'auto' }}>
|
||||
<Outlet />
|
||||
</Content>
|
||||
</Layout>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
export default MainLayout;
|
||||
31
apps/admin/src/main.tsx
Normal file
31
apps/admin/src/main.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App';
|
||||
import './index.css';
|
||||
import dayjs from 'dayjs';
|
||||
import 'dayjs/locale/zh-cn';
|
||||
import customParseFormat from 'dayjs/plugin/customParseFormat';
|
||||
import advancedFormat from 'dayjs/plugin/advancedFormat';
|
||||
import weekday from 'dayjs/plugin/weekday';
|
||||
import localeData from 'dayjs/plugin/localeData';
|
||||
import weekOfYear from 'dayjs/plugin/weekOfYear';
|
||||
import weekYear from 'dayjs/plugin/weekYear';
|
||||
import updateLocale from 'dayjs/plugin/updateLocale';
|
||||
|
||||
// 扩展 antd DatePicker/RangePicker 面板所需的 dayjs 插件,否则中文 locale 无法生效
|
||||
dayjs.extend(customParseFormat);
|
||||
dayjs.extend(advancedFormat);
|
||||
dayjs.extend(weekday);
|
||||
dayjs.extend(localeData);
|
||||
dayjs.extend(weekOfYear);
|
||||
dayjs.extend(weekYear);
|
||||
dayjs.extend(updateLocale);
|
||||
|
||||
// 必须在所有插件加载后设置 locale
|
||||
dayjs.locale('zh-cn');
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
306
apps/admin/src/pages/Bills/index.tsx
Normal file
306
apps/admin/src/pages/Bills/index.tsx
Normal file
@@ -0,0 +1,306 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { Table, Button, Modal, Form, DatePicker, Space, message, Tag, Descriptions, Popconfirm, Input, Select, Tooltip } from 'antd';
|
||||
import { FileTextOutlined, DeleteOutlined, DownloadOutlined, FilePdfOutlined } from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
draft: { text: '草稿', color: 'default' },
|
||||
confirmed: { text: '已确认', color: 'blue' },
|
||||
paid: { text: '已支付', color: 'green' },
|
||||
};
|
||||
|
||||
const typeMap: Record<string, string> = { water: '水费', electricity: '电费', cleaning: '保洁费', damage: '损坏赔偿', penalty: '罚款', other: '其他' };
|
||||
|
||||
const BillsPage: React.FC = () => {
|
||||
const [bills, setBills] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [generateModal, setGenerateModal] = useState(false);
|
||||
const [detailModal, setDetailModal] = useState<any>(null);
|
||||
const [selectedRows, setSelectedRows] = useState<number[]>([]);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
|
||||
const [generateForm] = Form.useForm();
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res: any = await api.get('/bills');
|
||||
setBills(res);
|
||||
} catch (e) { console.error(e); }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => { fetchData(); }, []);
|
||||
|
||||
const filteredBills = useMemo(() => {
|
||||
return bills.filter((b: any) => {
|
||||
if (searchText) {
|
||||
const s = searchText.toLowerCase();
|
||||
const matchName = b.student?.name?.toLowerCase().includes(s);
|
||||
const matchPeriod = `${b.periodStart} ~ ${b.periodEnd}`.includes(s);
|
||||
if (!matchName && !matchPeriod) return false;
|
||||
}
|
||||
if (filterStatus && b.status !== filterStatus) return false;
|
||||
return true;
|
||||
});
|
||||
}, [bills, searchText, filterStatus]);
|
||||
|
||||
const handleGenerate = async () => {
|
||||
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'),
|
||||
});
|
||||
message.success(res.message || '生成成功');
|
||||
setGenerateModal(false);
|
||||
generateForm.resetFields();
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '生成失败'); }
|
||||
};
|
||||
|
||||
const showDetail = async (id: number) => {
|
||||
try {
|
||||
const res = await api.get(`/bills/${id}`);
|
||||
setDetailModal(res);
|
||||
} catch (e) { console.error(e); }
|
||||
};
|
||||
|
||||
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 batchUpdateStatus = async (status: string) => {
|
||||
if (selectedRows.length === 0) return message.warning('请先选择账单');
|
||||
try {
|
||||
await api.put('/bills/batch/status', { ids: selectedRows, status });
|
||||
message.success(`已批量更新 ${selectedRows.length} 条账单`);
|
||||
setSelectedRows([]);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/bills/${id}`);
|
||||
message.success('账单已删除');
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '删除失败'); }
|
||||
};
|
||||
|
||||
const batchDelete = async () => {
|
||||
if (selectedRows.length === 0) return message.warning('请先选择账单');
|
||||
try {
|
||||
await api.post('/bills/batch/delete', { ids: selectedRows });
|
||||
message.success(`已删除 ${selectedRows.length} 条账单`);
|
||||
setSelectedRows([]);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const handleExportExcel = () => {
|
||||
const baseURL = import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
|
||||
const token = localStorage.getItem('token');
|
||||
const url = `${baseURL}/bills/export/excel`;
|
||||
const a = document.createElement('a');
|
||||
// 使用 fetch 来携带 token
|
||||
fetch(url, { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then(res => res.blob())
|
||||
.then(blob => {
|
||||
const blobUrl = URL.createObjectURL(blob);
|
||||
a.href = blobUrl;
|
||||
a.download = `账单导出_${dayjs().format('YYYYMMDD_HHmmss')}.xlsx`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
message.success('Excel 导出成功');
|
||||
})
|
||||
.catch(() => message.error('导出失败'));
|
||||
};
|
||||
|
||||
const handleExportPdf = (billId: number) => {
|
||||
const baseURL = import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
|
||||
const token = localStorage.getItem('token');
|
||||
fetch(`${baseURL}/bills/export/pdf/${billId}`, { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then(res => res.blob())
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `账单_${billId}.pdf`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch(() => message.error('导出失败'));
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{ title: '学生', render: (_: any, r: any) => r.student?.name || '-' },
|
||||
{ title: '账单周期', render: (_: any, r: any) => `${r.periodStart} ~ ${r.periodEnd}` },
|
||||
{ title: '分摊费用', dataIndex: 'sharedAmount', render: (v: number) => `¥${Number(v).toFixed(2)}` },
|
||||
{ title: '个人费用', dataIndex: 'personalAmount', render: (v: number) => `¥${Number(v).toFixed(2)}` },
|
||||
{ title: '总计', dataIndex: 'totalAmount', render: (v: number) => <strong>¥{Number(v).toFixed(2)}</strong> },
|
||||
{
|
||||
title: '可用押金',
|
||||
dataIndex: 'availableDeposit',
|
||||
render: (v: number) => v > 0
|
||||
? <span style={{ color: '#52c41a' }}>¥{Number(v).toFixed(2)}</span>
|
||||
: <span style={{ color: '#999' }}>-</span>,
|
||||
},
|
||||
{
|
||||
title: '抵扣后应付',
|
||||
dataIndex: 'amountAfterDeposit',
|
||||
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>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '状态', dataIndex: 'status',
|
||||
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text}</Tag>,
|
||||
},
|
||||
{ title: '生成时间', dataIndex: 'generatedAt', 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' && <PermissionButton permission="bill:confirm" size="small" onClick={() => updateStatus(record.id, 'confirmed')}>确认</PermissionButton>}
|
||||
{record.status === 'confirmed' && <PermissionButton permission="bill:confirm" size="small" type="primary" onClick={() => updateStatus(record.id, 'paid')}>标记已付</PermissionButton>}
|
||||
<PermissionButton permission="bill:export-pdf" size="small" icon={<FilePdfOutlined />} onClick={() => handleExportPdf(record.id)}>PDF</PermissionButton>
|
||||
<PermissionButton permission="bill:delete">
|
||||
<Popconfirm title="确定删除此账单?" onConfirm={() => handleDelete(record.id)} okText="删除" cancelText="取消">
|
||||
<Button size="small" danger icon={<DeleteOutlined />}>删除</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
|
||||
<Space wrap>
|
||||
<Input.Search
|
||||
placeholder="搜索学生姓名或账单周期"
|
||||
allowClear
|
||||
style={{ width: 220 }}
|
||||
onSearch={v => setSearchText(v)}
|
||||
onChange={e => { if (!e.target.value) setSearchText(''); }}
|
||||
/>
|
||||
<Select
|
||||
placeholder="状态筛选"
|
||||
allowClear
|
||||
style={{ width: 120 }}
|
||||
value={filterStatus}
|
||||
onChange={v => setFilterStatus(v)}
|
||||
options={[
|
||||
{ value: 'draft', label: '草稿' },
|
||||
{ value: 'confirmed', label: '已确认' },
|
||||
{ value: 'paid', 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>
|
||||
<PermissionButton permission="bill:delete">
|
||||
<Popconfirm title={`确定删除选中的 ${selectedRows.length} 条账单?`} onConfirm={batchDelete} okText="删除" cancelText="取消" disabled={selectedRows.length === 0}>
|
||||
<Button danger disabled={selectedRows.length === 0} icon={<DeleteOutlined />}>批量删除</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
<Space>
|
||||
<PermissionButton permission="bill:generate" type="primary" icon={<FileTextOutlined />} onClick={() => { generateForm.resetFields(); setGenerateModal(true); }}>
|
||||
生成账单
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="bill:export-excel" icon={<DownloadOutlined />} onClick={handleExportExcel}>导出Excel</PermissionButton>
|
||||
</Space>
|
||||
</div>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={filteredBills}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
pagination={{ pageSize: 15, showTotal: (total) => `共 ${total} 条` }}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedRows,
|
||||
onChange: (keys) => setSelectedRows(keys as number[]),
|
||||
}}
|
||||
/>
|
||||
|
||||
<Modal title="生成账单" open={generateModal} onOk={handleGenerate} onCancel={() => setGenerateModal(false)} okText="生成">
|
||||
<Form form={generateForm} layout="vertical">
|
||||
<Form.Item name="period" label="账单周期" rules={[{ required: true, message: '请选择账单周期' }]} extra="选择费用对应的时间段,系统将自动计算每个学生的分摊费用">
|
||||
<RangePicker style={{ width: '100%' }} placeholder={['开始日期', '结束日期']} format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="账单详情"
|
||||
open={!!detailModal}
|
||||
onCancel={() => setDetailModal(null)}
|
||||
footer={null}
|
||||
width={800}
|
||||
>
|
||||
{detailModal && (
|
||||
<>
|
||||
<Descriptions bordered size="small" column={2} style={{ marginBottom: 16 }}>
|
||||
<Descriptions.Item label="学生">{detailModal.student?.name}</Descriptions.Item>
|
||||
<Descriptions.Item label="状态"><Tag color={statusMap[detailModal.status]?.color}>{statusMap[detailModal.status]?.text}</Tag></Descriptions.Item>
|
||||
<Descriptions.Item label="账单周期">{detailModal.periodStart} ~ {detailModal.periodEnd}</Descriptions.Item>
|
||||
<Descriptions.Item label="生成时间">{dayjs(detailModal.generatedAt).format('YYYY-MM-DD HH:mm')}</Descriptions.Item>
|
||||
<Descriptions.Item label="分摊费用">¥{Number(detailModal.sharedAmount).toFixed(2)}</Descriptions.Item>
|
||||
<Descriptions.Item label="个人费用">¥{Number(detailModal.personalAmount).toFixed(2)}</Descriptions.Item>
|
||||
<Descriptions.Item label="合计" span={2}><strong style={{ fontSize: 18, color: '#007AFF' }}>¥{Number(detailModal.totalAmount).toFixed(2)}</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>
|
||||
)}
|
||||
<h4>费用明细</h4>
|
||||
<Table
|
||||
dataSource={detailModal.items || []}
|
||||
rowKey="id"
|
||||
pagination={false}
|
||||
size="small"
|
||||
columns={[
|
||||
{ title: '类型', dataIndex: 'expenseType', render: (v: string) => typeMap[v] || v },
|
||||
{ title: '说明', dataIndex: 'description' },
|
||||
{ title: '计费天数', dataIndex: 'days', render: (v: number) => v > 0 ? `${v}天` : '-' },
|
||||
{ title: '宿舍总人天', dataIndex: 'totalRoomDays', render: (v: number) => v > 0 ? `${v}天` : '-' },
|
||||
{ title: '宿舍总费用', dataIndex: 'roomTotalAmount', render: (v: number) => `¥${Number(v).toFixed(2)}` },
|
||||
{ title: '应分摊', dataIndex: 'studentAmount', render: (v: number) => <strong>¥{Number(v).toFixed(2)}</strong> },
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default BillsPage;
|
||||
257
apps/admin/src/pages/ClassroomRentals/index.tsx
Normal file
257
apps/admin/src/pages/ClassroomRentals/index.tsx
Normal file
@@ -0,0 +1,257 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { Table, Button, Modal, Form, Select, DatePicker, InputNumber, Input, Space, message, Tag, Popconfirm, Upload, Tooltip } from 'antd';
|
||||
import { PlusOutlined, UploadOutlined, DeleteOutlined, FileTextOutlined } from '@ant-design/icons';
|
||||
import dayjs, { Dayjs } from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
|
||||
const ClassroomRentalsPage: React.FC = () => {
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [classrooms, setClassrooms] = useState<any[]>([]);
|
||||
const [tenants, setTenants] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<any>(null);
|
||||
const [form] = Form.useForm();
|
||||
const [filterMonth, setFilterMonth] = useState<Dayjs | null>(null);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
if (!searchText) return data;
|
||||
const s = searchText.toLowerCase();
|
||||
return data.filter((r: any) => {
|
||||
const matchClassroom = r.classroom?.name?.toLowerCase().includes(s);
|
||||
const matchTenant = r.tenant?.name?.toLowerCase().includes(s);
|
||||
return matchClassroom || matchTenant;
|
||||
});
|
||||
}, [data, searchText]);
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params: any = {};
|
||||
if (filterMonth) params.month = filterMonth.format('YYYY-MM');
|
||||
const res: any = await api.get('/classroom-rentals', { params });
|
||||
setData(res);
|
||||
} catch (e) { console.error(e); }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const fetchMeta = async () => {
|
||||
try {
|
||||
const [cr, tn]: any = await Promise.all([
|
||||
api.get('/classrooms'),
|
||||
api.get('/tenants'),
|
||||
]);
|
||||
setClassrooms(cr);
|
||||
setTenants(tn);
|
||||
} catch (e) { console.error(e); }
|
||||
};
|
||||
|
||||
useEffect(() => { fetchMeta(); }, []);
|
||||
useEffect(() => { fetchData(); }, [filterMonth]);
|
||||
|
||||
const handleSave = async () => {
|
||||
const values = await form.validateFields();
|
||||
const payload = {
|
||||
classroomId: values.classroomId,
|
||||
tenantId: values.tenantId,
|
||||
startDate: values.dateRange[0].format('YYYY-MM-DD'),
|
||||
endDate: values.dateRange[1].format('YYYY-MM-DD'),
|
||||
dailyRate: values.dailyRate,
|
||||
totalAmount: values.totalAmount,
|
||||
notes: values.notes,
|
||||
};
|
||||
try {
|
||||
if (editing) {
|
||||
await api.put(`/classroom-rentals/${editing.id}`, payload);
|
||||
message.success('更新成功');
|
||||
} else {
|
||||
await api.post('/classroom-rentals', payload);
|
||||
message.success('创建成功');
|
||||
}
|
||||
setModalOpen(false);
|
||||
form.resetFields();
|
||||
setEditing(null);
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
if (e?.conflicts?.length) {
|
||||
const list = e.conflicts.map((c: any) => `${c.tenantName}(${c.startDate}~${c.endDate})`).join('、');
|
||||
message.error(`时间段冲突:${list}`);
|
||||
} else {
|
||||
message.error(e?.message || '操作失败');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/classroom-rentals/${id}`);
|
||||
message.success('已删除');
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '删除失败'); }
|
||||
};
|
||||
|
||||
const handleDownloadContract = (id: number, filename?: string) => {
|
||||
const baseURL = import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
|
||||
const token = localStorage.getItem('token');
|
||||
fetch(`${baseURL}/classroom-rentals/${id}/contract`, { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then(res => {
|
||||
if (!res.ok) throw new Error('下载失败');
|
||||
return res.blob();
|
||||
})
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename || `contract-${id}.pdf`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch(() => message.error('下载失败(可能文件已丢失)'));
|
||||
};
|
||||
|
||||
const handleDeleteContract = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/classroom-rentals/${id}/contract`);
|
||||
message.success('合同已删除');
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '删除失败'); }
|
||||
};
|
||||
|
||||
const openEdit = (record: any) => {
|
||||
setEditing(record);
|
||||
form.setFieldsValue({
|
||||
classroomId: record.classroomId,
|
||||
tenantId: record.tenantId,
|
||||
dateRange: [dayjs(record.startDate), dayjs(record.endDate)],
|
||||
dailyRate: record.dailyRate ? Number(record.dailyRate) : undefined,
|
||||
totalAmount: record.totalAmount ? Number(record.totalAmount) : undefined,
|
||||
notes: record.notes,
|
||||
});
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: '教室', dataIndex: 'classroom',
|
||||
render: (c: any) => c ? <span>{c.building ? `${c.building} · ` : ''}{c.name}</span> : '-',
|
||||
},
|
||||
{
|
||||
title: '租赁方', dataIndex: 'tenant',
|
||||
render: (t: any) => t ? <Tag color={t.color} style={{ background: t.color, color: '#fff', borderColor: t.color }}>{t.name}</Tag> : '-',
|
||||
},
|
||||
{ title: '开始日期', dataIndex: 'startDate' },
|
||||
{ title: '结束日期', dataIndex: 'endDate' },
|
||||
{
|
||||
title: '时长', render: (_: any, r: any) => {
|
||||
const d = dayjs(r.endDate).diff(dayjs(r.startDate), 'day') + 1;
|
||||
return `${d}天`;
|
||||
},
|
||||
},
|
||||
{ title: '日租金', dataIndex: 'dailyRate', render: (v: any) => v ? `¥${v}` : '-' },
|
||||
{ title: '总额', dataIndex: 'totalAmount', render: (v: any) => v ? `¥${v}` : '-' },
|
||||
{
|
||||
title: '合同', dataIndex: 'contractPath',
|
||||
render: (v: string, r: any) => v ? (
|
||||
<Space>
|
||||
<Tooltip title={r.contractOriginalName}>
|
||||
<Button size="small" icon={<FileTextOutlined />} onClick={() => handleDownloadContract(r.id, r.contractOriginalName)}>下载</Button>
|
||||
</Tooltip>
|
||||
<Popconfirm title="删除合同文件?" onConfirm={() => handleDeleteContract(r.id)}>
|
||||
<Button size="small" danger icon={<DeleteOutlined />} />
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
) : (
|
||||
<Upload
|
||||
accept="application/pdf"
|
||||
showUploadList={false}
|
||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
message.error('文件不能超过 10MB');
|
||||
onError?.(new Error('size'));
|
||||
return;
|
||||
}
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
try {
|
||||
await api.post(`/classroom-rentals/${r.id}/contract`, formData, { headers: { 'Content-Type': 'multipart/form-data' } });
|
||||
message.success('合同已上传');
|
||||
onSuccess?.({});
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '上传失败'); onError?.(e); }
|
||||
}}
|
||||
>
|
||||
<Button size="small" icon={<UploadOutlined />}>上传PDF</Button>
|
||||
</Upload>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作', width: 150,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
<PermissionButton permission="rental:edit" size="small" onClick={() => openEdit(record)}>编辑</PermissionButton>
|
||||
<PermissionButton permission="rental:delete">
|
||||
<Popconfirm title="确定删除该租赁订单?合同文件将一并删除。" onConfirm={() => handleDelete(record.id)}>
|
||||
<Button size="small" danger>删除</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
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(''); }}
|
||||
/>
|
||||
<DatePicker picker="month" placeholder="按月筛选" value={filterMonth} onChange={setFilterMonth} allowClear format="YYYY-MM" />
|
||||
</Space>
|
||||
<PermissionButton permission="rental:create" type="primary" icon={<PlusOutlined />} onClick={() => { setEditing(null); form.resetFields(); setModalOpen(true); }}>
|
||||
新增租赁
|
||||
</PermissionButton>
|
||||
</div>
|
||||
<Table columns={columns} dataSource={filteredData} rowKey="id" loading={loading} pagination={{ pageSize: 15, showTotal: (total) => `共 ${total} 条` }} scroll={{ x: 1200 }} />
|
||||
|
||||
<Modal title={editing ? '编辑租赁' : '新增租赁'} open={modalOpen} onOk={handleSave} onCancel={() => { setModalOpen(false); setEditing(null); }} okText="保存" width={600}>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="classroomId" label="教室" rules={[{ required: true }]}>
|
||||
<Select
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
placeholder="选择教室"
|
||||
options={classrooms.map(c => ({ value: c.id, label: `${c.building ? c.building + ' · ' : ''}${c.name}(${c.roomType})` }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="tenantId" label="租赁方" rules={[{ required: true }]}>
|
||||
<Select
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
placeholder="选择租赁方"
|
||||
options={tenants.map(t => ({ value: t.id, label: t.name }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="dateRange" label="租赁起止日期" rules={[{ required: true }]}>
|
||||
<DatePicker.RangePicker style={{ width: '100%' }} placeholder={['开始日期', '结束日期']} format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="dailyRate" label="日租金(可选)">
|
||||
<InputNumber min={0} precision={2} style={{ width: '100%' }} prefix="¥" />
|
||||
</Form.Item>
|
||||
<Form.Item name="totalAmount" label="合同总额(可选)">
|
||||
<InputNumber min={0} precision={2} style={{ width: '100%' }} prefix="¥" />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注"><Input.TextArea rows={2} /></Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ClassroomRentalsPage;
|
||||
228
apps/admin/src/pages/ClassroomSchedule/index.tsx
Normal file
228
apps/admin/src/pages/ClassroomSchedule/index.tsx
Normal file
@@ -0,0 +1,228 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { DatePicker, Card, Row, Col, Statistic, Tag, Space, Button, Modal, Spin, Empty, Tooltip } from 'antd';
|
||||
import { CalendarOutlined, FileTextOutlined } from '@ant-design/icons';
|
||||
import dayjs, { Dayjs } from 'dayjs';
|
||||
import api from '../../api';
|
||||
|
||||
interface ScheduleData {
|
||||
year: number;
|
||||
month: number;
|
||||
days: number;
|
||||
classrooms: any[];
|
||||
tenants: any[];
|
||||
matrix: Record<number, Record<number, any>>;
|
||||
summary: Record<number, { totalDays: number; rentedDays: number; idleDays: number; occupancyRate: number }>;
|
||||
}
|
||||
|
||||
const ClassroomSchedulePage: React.FC = () => {
|
||||
const [month, setMonth] = useState<Dayjs>(dayjs());
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [data, setData] = useState<ScheduleData | null>(null);
|
||||
const [detailModal, setDetailModal] = useState<any>(null);
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res: any = await api.get('/classroom-rentals/schedule', {
|
||||
params: { year: month.year(), month: month.month() + 1 },
|
||||
});
|
||||
setData(res);
|
||||
} catch (e) { console.error(e); }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => { fetchData(); }, [month]);
|
||||
|
||||
// 按楼栋+楼层分组教室
|
||||
const groups = useMemo(() => {
|
||||
if (!data) return [];
|
||||
const map = new Map<string, any[]>();
|
||||
for (const c of data.classrooms) {
|
||||
const key = `${c.building || '其他'}${c.floor ? ` · ${c.floor}层` : ''}`;
|
||||
if (!map.has(key)) map.set(key, []);
|
||||
map.get(key)!.push(c);
|
||||
}
|
||||
return Array.from(map.entries()).map(([name, classrooms]) => ({ name, classrooms }));
|
||||
}, [data]);
|
||||
|
||||
// 整体统计
|
||||
const overall = useMemo(() => {
|
||||
if (!data) return { total: 0, rented: 0, rate: 0 };
|
||||
let rented = 0;
|
||||
const total = data.classrooms.length * data.days;
|
||||
for (const cid of Object.keys(data.summary)) {
|
||||
rented += data.summary[+cid].rentedDays;
|
||||
}
|
||||
return {
|
||||
total,
|
||||
rented,
|
||||
rate: total > 0 ? Math.round((rented / total) * 100) : 0,
|
||||
};
|
||||
}, [data]);
|
||||
|
||||
const showDetail = async (rentalId: number) => {
|
||||
try {
|
||||
const res: any = await api.get(`/classroom-rentals/${rentalId}`);
|
||||
setDetailModal(res);
|
||||
} catch (e) { console.error(e); }
|
||||
};
|
||||
|
||||
const handleDownloadContract = (id: number, filename?: string) => {
|
||||
const baseURL = import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
|
||||
const token = localStorage.getItem('token');
|
||||
fetch(`${baseURL}/classroom-rentals/${id}/contract`, { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then(res => res.blob())
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename || `contract-${id}.pdf`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
|
||||
<Space>
|
||||
<CalendarOutlined style={{ fontSize: 20 }} />
|
||||
<h3 style={{ margin: 0 }}>教室排期总览</h3>
|
||||
</Space>
|
||||
<Space>
|
||||
<Button onClick={() => setMonth(month.subtract(1, 'month'))}>上月</Button>
|
||||
<DatePicker picker="month" value={month} onChange={(v) => v && setMonth(v)} allowClear={false} placeholder="选择月份" format="YYYY年M月" />
|
||||
<Button onClick={() => setMonth(month.add(1, 'month'))}>下月</Button>
|
||||
<Button type="primary" onClick={() => setMonth(dayjs())}>回到本月</Button>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
{/* 统计卡片 */}
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
|
||||
<Col xs={12} sm={6}><Card size="small"><Statistic title="教室总数" value={data?.classrooms.length || 0} /></Card></Col>
|
||||
<Col xs={12} sm={6}><Card size="small"><Statistic title="本月天数" value={data?.days || 0} /></Card></Col>
|
||||
<Col xs={12} sm={6}><Card size="small"><Statistic title="总占用天数" value={overall.rented} suffix={`/${overall.total}`} /></Card></Col>
|
||||
<Col xs={12} sm={6}><Card size="small"><Statistic title="整体占用率" value={overall.rate} suffix="%" valueStyle={{ color: overall.rate > 70 ? '#cf1322' : overall.rate > 40 ? '#fa8c16' : '#3f8600' }} /></Card></Col>
|
||||
</Row>
|
||||
|
||||
{/* 租赁方图例 */}
|
||||
{data && data.tenants.length > 0 && (
|
||||
<Card size="small" style={{ marginBottom: 16 }} title="租赁方图例">
|
||||
<Space wrap>
|
||||
{data.tenants.map(t => (
|
||||
<Tag key={t.id} color={t.color} style={{ background: t.color, color: '#fff', borderColor: t.color }}>{t.name}</Tag>
|
||||
))}
|
||||
</Space>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Spin spinning={loading}>
|
||||
{!data || data.classrooms.length === 0 ? (
|
||||
<Empty description="暂无教室数据" />
|
||||
) : (
|
||||
<div style={{ overflowX: 'auto' }}>
|
||||
{groups.map(group => (
|
||||
<Card
|
||||
key={group.name}
|
||||
size="small"
|
||||
title={group.name}
|
||||
style={{ marginBottom: 12 }}
|
||||
bodyStyle={{ padding: 0 }}
|
||||
>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
|
||||
<thead>
|
||||
<tr style={{ background: '#fafafa' }}>
|
||||
<th style={{ position: 'sticky', left: 0, background: '#fafafa', zIndex: 2, padding: '8px', border: '1px solid #f0f0f0', minWidth: 120, textAlign: 'left' }}>教室</th>
|
||||
<th style={{ padding: '8px 6px', border: '1px solid #f0f0f0', minWidth: 60 }}>类型</th>
|
||||
<th style={{ padding: '8px 6px', border: '1px solid #f0f0f0', minWidth: 70 }}>占用率</th>
|
||||
{Array.from({ length: data.days }, (_, i) => i + 1).map(d => (
|
||||
<th key={d} style={{ padding: '8px 4px', border: '1px solid #f0f0f0', minWidth: 26, textAlign: 'center' }}>{d}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{group.classrooms.map(c => {
|
||||
const sum = data.summary[c.id] || { rentedDays: 0, totalDays: data.days, occupancyRate: 0 };
|
||||
return (
|
||||
<tr key={c.id}>
|
||||
<td style={{ position: 'sticky', left: 0, background: '#fff', zIndex: 1, padding: '6px 8px', border: '1px solid #f0f0f0', fontWeight: 500 }}>{c.name}</td>
|
||||
<td style={{ padding: '6px', border: '1px solid #f0f0f0', textAlign: 'center' }}>{c.roomType}</td>
|
||||
<td style={{ padding: '6px', border: '1px solid #f0f0f0', textAlign: 'center', color: sum.occupancyRate > 0.7 ? '#cf1322' : sum.occupancyRate > 0.4 ? '#fa8c16' : '#3f8600' }}>
|
||||
{Math.round(sum.occupancyRate * 100)}%
|
||||
</td>
|
||||
{Array.from({ length: data.days }, (_, i) => i + 1).map(d => {
|
||||
const cell = data.matrix[c.id]?.[d];
|
||||
return (
|
||||
<td
|
||||
key={d}
|
||||
onClick={() => cell && showDetail(cell.rentalId)}
|
||||
style={{
|
||||
padding: 0,
|
||||
border: '1px solid #f0f0f0',
|
||||
background: cell?.color || '#fff',
|
||||
height: 26,
|
||||
cursor: cell ? 'pointer' : 'default',
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
{cell && (
|
||||
<Tooltip title={`${cell.tenantName}${cell.hasContract ? ' · 有合同' : ''}`}>
|
||||
<span style={{ color: '#fff', fontSize: 10, fontWeight: 600 }}>
|
||||
{cell.hasContract ? '📄' : ''}
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Spin>
|
||||
|
||||
<Modal
|
||||
title="租赁详情"
|
||||
open={!!detailModal}
|
||||
onCancel={() => setDetailModal(null)}
|
||||
footer={null}
|
||||
width={500}
|
||||
>
|
||||
{detailModal && (
|
||||
<div style={{ lineHeight: 2 }}>
|
||||
<div><strong>教室:</strong>{detailModal.classroom?.building} · {detailModal.classroom?.name}({detailModal.classroom?.roomType})</div>
|
||||
<div><strong>租赁方:</strong>
|
||||
<Tag color={detailModal.tenant?.color} style={{ background: detailModal.tenant?.color, color: '#fff', borderColor: detailModal.tenant?.color }}>
|
||||
{detailModal.tenant?.name}
|
||||
</Tag>
|
||||
</div>
|
||||
<div><strong>联系人:</strong>{detailModal.tenant?.contact || '-'} {detailModal.tenant?.phone || ''}</div>
|
||||
<div><strong>起止日期:</strong>{detailModal.startDate} ~ {detailModal.endDate}({dayjs(detailModal.endDate).diff(dayjs(detailModal.startDate), 'day') + 1}天)</div>
|
||||
{detailModal.dailyRate && <div><strong>日租金:</strong>¥{detailModal.dailyRate}</div>}
|
||||
{detailModal.totalAmount && <div><strong>合同总额:</strong>¥{detailModal.totalAmount}</div>}
|
||||
{detailModal.notes && <div><strong>备注:</strong>{detailModal.notes}</div>}
|
||||
<div style={{ marginTop: 12 }}>
|
||||
<strong>合同文件:</strong>
|
||||
{detailModal.contractPath ? (
|
||||
<Button
|
||||
type="link"
|
||||
icon={<FileTextOutlined />}
|
||||
onClick={() => handleDownloadContract(detailModal.id, detailModal.contractOriginalName)}
|
||||
>
|
||||
{detailModal.contractOriginalName || '下载'}
|
||||
</Button>
|
||||
) : '未上传'}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ClassroomSchedulePage;
|
||||
194
apps/admin/src/pages/Classrooms/index.tsx
Normal file
194
apps/admin/src/pages/Classrooms/index.tsx
Normal file
@@ -0,0 +1,194 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { Table, Button, Modal, Form, Input, InputNumber, Select, Space, message, Tag, Popconfirm, Upload } from 'antd';
|
||||
import { PlusOutlined, UploadOutlined, DownloadOutlined, UndoOutlined, InboxOutlined } from '@ant-design/icons';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
available: { text: '可用', color: 'green' },
|
||||
archived: { text: '已归档', color: '#999' },
|
||||
};
|
||||
|
||||
const typeColor: Record<string, string> = {
|
||||
大: 'volcano',
|
||||
次大: 'geekblue',
|
||||
小: 'cyan',
|
||||
};
|
||||
|
||||
const ClassroomsPage: React.FC = () => {
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<any>(null);
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
const [form] = Form.useForm();
|
||||
const [searchText, setSearchText] = useState('');
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
if (!searchText) return data;
|
||||
const s = searchText.toLowerCase();
|
||||
return data.filter((d: any) => d.name?.toLowerCase().includes(s) || d.building?.toLowerCase().includes(s));
|
||||
}, [data, searchText]);
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res: any = await api.get('/classrooms', { params: { includeArchived: showArchived } });
|
||||
setData(res);
|
||||
} catch (e) { console.error(e); }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => { fetchData(); }, [showArchived]);
|
||||
|
||||
const handleSave = async () => {
|
||||
const values = await form.validateFields();
|
||||
try {
|
||||
if (editing) {
|
||||
await api.put(`/classrooms/${editing.id}`, values);
|
||||
message.success('更新成功');
|
||||
} else {
|
||||
await api.post('/classrooms', values);
|
||||
message.success('创建成功');
|
||||
}
|
||||
setModalOpen(false);
|
||||
form.resetFields();
|
||||
setEditing(null);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const handleArchive = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/classrooms/${id}`);
|
||||
message.success('已归档');
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '归档失败'); }
|
||||
};
|
||||
|
||||
const handleRestore = async (id: number) => {
|
||||
try {
|
||||
await api.put(`/classrooms/${id}/restore`);
|
||||
message.success('已恢复');
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '恢复失败'); }
|
||||
};
|
||||
|
||||
const handleDownloadTemplate = () => {
|
||||
const baseURL = import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
|
||||
const token = localStorage.getItem('token');
|
||||
fetch(`${baseURL}/classrooms/template`, { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then(res => res.blob())
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = '教室导入模板.xlsx';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch(() => message.error('下载失败'));
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{ title: '教室名', dataIndex: 'name', sorter: (a: any, b: any) => a.name.localeCompare(b.name) },
|
||||
{ title: '楼栋', dataIndex: 'building' },
|
||||
{ title: '楼层', dataIndex: 'floor' },
|
||||
{ title: '类型', dataIndex: 'roomType', render: (v: string) => <Tag color={typeColor[v] || 'default'}>{v || '-'}</Tag> },
|
||||
{ title: '容量', dataIndex: 'capacity' },
|
||||
{ title: '课程类型', dataIndex: 'courseType', render: (v: string) => v || '-' },
|
||||
{ title: '负责人', dataIndex: 'supervisor', render: (v: string) => v || '-' },
|
||||
{
|
||||
title: '状态', dataIndex: 'status',
|
||||
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '操作', width: 180,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
{record.status === 'archived' ? (
|
||||
<PermissionButton permission="classroom:edit">
|
||||
<Popconfirm title="确定恢复此教室?" onConfirm={() => handleRestore(record.id)}>
|
||||
<Button size="small" icon={<UndoOutlined />} type="link">恢复</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
) : (
|
||||
<>
|
||||
<PermissionButton permission="classroom:edit" size="small" onClick={() => { setEditing(record); form.setFieldsValue(record); setModalOpen(true); }}>编辑</PermissionButton>
|
||||
<PermissionButton permission="classroom:delete">
|
||||
<Popconfirm title="归档后数据保留,可随时恢复。存在进行中的租赁将无法归档。" onConfirm={() => handleArchive(record.id)} okText="归档" cancelText="取消">
|
||||
<Button size="small" icon={<InboxOutlined />}>归档</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
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(''); }}
|
||||
/>
|
||||
<Button type={showArchived ? 'primary' : 'default'} onClick={() => setShowArchived(!showArchived)}>
|
||||
{showArchived ? '隐藏已归档' : '显示已归档'}
|
||||
</Button>
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<PermissionButton permission="classroom:create" type="primary" icon={<PlusOutlined />} onClick={() => { setEditing(null); form.resetFields(); setModalOpen(true); }}>
|
||||
添加教室
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="classroom:create">
|
||||
<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('/classrooms/import', formData, { headers: { 'Content-Type': 'multipart/form-data' } });
|
||||
message.success(res.message);
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '导入失败'); onError?.(e); }
|
||||
}}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入Excel</Button>
|
||||
</Upload>
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="classroom:view" icon={<DownloadOutlined />} onClick={handleDownloadTemplate}>下载模板</PermissionButton>
|
||||
</Space>
|
||||
</div>
|
||||
<Table columns={columns} dataSource={filteredData} rowKey="id" loading={loading} pagination={{ pageSize: 20, showTotal: (total) => `共 ${total} 条` }} />
|
||||
|
||||
<Modal title={editing ? '编辑教室' : '添加教室'} open={modalOpen} onOk={handleSave} onCancel={() => { setModalOpen(false); setEditing(null); }} okText="保存">
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="name" label="教室名" rules={[{ required: true }]}><Input placeholder="如:A201 / B301" /></Form.Item>
|
||||
<Form.Item name="building" label="楼栋"><Input placeholder="如:A座 / B座" /></Form.Item>
|
||||
<Form.Item name="floor" label="楼层"><InputNumber min={1} style={{ width: '100%' }} /></Form.Item>
|
||||
<Form.Item name="roomType" label="类型" tooltip="大/次大/小 对应可容纳规模">
|
||||
<Select options={[
|
||||
{ value: '大', label: '大' },
|
||||
{ value: '次大', label: '次大' },
|
||||
{ value: '小', label: '小' },
|
||||
]} placeholder="选择类型" />
|
||||
</Form.Item>
|
||||
<Form.Item name="capacity" label="容量"><InputNumber min={1} max={500} style={{ width: '100%' }} /></Form.Item>
|
||||
<Form.Item name="courseType" label="课程类型" tooltip="如:尊享培优班 / 专业课集训班"><Input /></Form.Item>
|
||||
<Form.Item name="supervisor" label="负责人/班主任"><Input /></Form.Item>
|
||||
<Form.Item name="notes" label="备注"><Input.TextArea rows={2} /></Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ClassroomsPage;
|
||||
179
apps/admin/src/pages/Dashboard/index.tsx
Normal file
179
apps/admin/src/pages/Dashboard/index.tsx
Normal file
@@ -0,0 +1,179 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Row, Col, Card, Statistic, DatePicker, Spin } from 'antd';
|
||||
import { TeamOutlined, HomeOutlined, DollarOutlined, CheckCircleOutlined } from '@ant-design/icons';
|
||||
import ReactECharts from 'echarts-for-react';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
const COLORS = ['#007AFF', '#34C759', '#FF9500', '#FF3B30', '#5AC8FA', '#AF52DE', '#FF2D55', '#FFCC00'];
|
||||
|
||||
const DashboardPage: React.FC = () => {
|
||||
const [stats, setStats] = useState<any>(null);
|
||||
const [ganttData, setGanttData] = useState<any[]>([]);
|
||||
const [expenseStats, setExpenseStats] = useState<any[]>([]);
|
||||
const [roomRanking, setRoomRanking] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [period, setPeriod] = useState<[string, string]>([
|
||||
dayjs().startOf('month').format('YYYY-MM-DD'),
|
||||
dayjs().endOf('month').format('YYYY-MM-DD'),
|
||||
]);
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [s, g, e, r] = await Promise.all([
|
||||
api.get('/dashboard/stats'),
|
||||
api.get('/dashboard/gantt', { params: { periodStart: period[0], periodEnd: period[1] } }),
|
||||
api.get('/dashboard/expense-stats', { params: { periodStart: period[0], periodEnd: period[1] } }),
|
||||
api.get('/dashboard/room-ranking', { params: { periodStart: period[0], periodEnd: period[1] } }),
|
||||
]);
|
||||
setStats(s);
|
||||
setGanttData(g as any);
|
||||
setExpenseStats(e as any);
|
||||
setRoomRanking(r as any);
|
||||
} catch (e) { console.error(e); }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => { fetchData(); }, [period]);
|
||||
|
||||
const expenseTypeMap: Record<string, string> = {
|
||||
water: '水费', electricity: '电费', cleaning: '保洁费', damage: '损坏赔偿', penalty: '罚款', key: '钥匙费', remote: '空调遥控器', deposit_deduction: '押金扣除', other: '其他',
|
||||
};
|
||||
|
||||
// 甘特图配置
|
||||
const ganttOption = () => {
|
||||
if (!ganttData.length) return {};
|
||||
const rooms = ganttData.map((d) => d.roomNumber);
|
||||
const pStart = new Date(period[0]).getTime();
|
||||
const pEnd = new Date(period[1]).getTime();
|
||||
|
||||
const data: any[] = [];
|
||||
ganttData.forEach((room, roomIdx) => {
|
||||
room.occupancies.forEach((occ: any, i: number) => {
|
||||
const start = Math.max(new Date(occ.checkInDate).getTime(), pStart);
|
||||
const end = occ.checkOutDate ? Math.min(new Date(occ.checkOutDate).getTime(), pEnd) : pEnd;
|
||||
data.push({
|
||||
name: occ.studentName,
|
||||
value: [roomIdx, start, end, occ.studentName],
|
||||
itemStyle: { color: COLORS[(occ.studentId || i) % COLORS.length] },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
tooltip: {
|
||||
formatter: (p: any) => {
|
||||
const v = p.value;
|
||||
return `${p.name}<br/>宿舍: ${rooms[v[0]]}<br/>入住: ${dayjs(v[1]).format('MM-DD')} ~ ${dayjs(v[2]).format('MM-DD')}`;
|
||||
},
|
||||
},
|
||||
grid: { left: 80, right: 30, top: 20, bottom: 30 },
|
||||
xAxis: { type: 'time', min: pStart, max: pEnd },
|
||||
yAxis: { type: 'category', data: rooms, inverse: true },
|
||||
series: [{
|
||||
type: 'custom',
|
||||
renderItem: (_params: any, api: any) => {
|
||||
const catIdx = api.value(0);
|
||||
const start = api.coord([api.value(1), catIdx]);
|
||||
const end = api.coord([api.value(2), catIdx]);
|
||||
const height = api.size([0, 1])[1] * 0.6;
|
||||
return {
|
||||
type: 'rect',
|
||||
shape: { x: start[0], y: start[1] - height / 2, width: end[0] - start[0], height },
|
||||
style: { ...api.style(), fill: api.visual('color'), stroke: '#fff', lineWidth: 1 },
|
||||
};
|
||||
},
|
||||
encode: { x: [1, 2], y: 0 },
|
||||
data,
|
||||
}],
|
||||
};
|
||||
};
|
||||
|
||||
// 费用饼图
|
||||
const pieOption = {
|
||||
tooltip: { trigger: 'item' },
|
||||
legend: { bottom: 0 },
|
||||
series: [{
|
||||
type: 'pie',
|
||||
radius: ['40%', '70%'],
|
||||
data: expenseStats.map((e) => ({
|
||||
name: expenseTypeMap[e.type] || e.type,
|
||||
value: Number(e.total),
|
||||
})),
|
||||
}],
|
||||
};
|
||||
|
||||
// 宿舍费用排行
|
||||
const barOption = {
|
||||
tooltip: {},
|
||||
grid: { left: 80, right: 20, bottom: 30, top: 10 },
|
||||
xAxis: { type: 'value' },
|
||||
yAxis: { type: 'category', data: roomRanking.map((r) => r.roomNumber).reverse(), inverse: false },
|
||||
series: [{ type: 'bar', data: roomRanking.map((r) => Number(r.total)).reverse(), itemStyle: { color: '#007AFF', borderRadius: [0, 4, 4, 0] } }],
|
||||
};
|
||||
|
||||
if (loading && !stats) return <Spin size="large" style={{ display: 'block', margin: '100px auto' }} />;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<h2 style={{ margin: 0 }}>数据面板</h2>
|
||||
<RangePicker
|
||||
value={[dayjs(period[0]), dayjs(period[1])]}
|
||||
onChange={(dates) => {
|
||||
if (dates) setPeriod([dates[0]!.format('YYYY-MM-DD'), dates[1]!.format('YYYY-MM-DD')]);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Row gutter={16} style={{ marginBottom: 24 }}>
|
||||
<Col span={6}>
|
||||
<Card><Statistic title="宿舍总数" value={stats?.totalRooms || 0} prefix={<HomeOutlined />} /></Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Card><Statistic title="在读学生" value={stats?.totalStudents || 0} prefix={<TeamOutlined />} /></Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Card><Statistic title="当前在住" value={stats?.occupiedBeds || 0} suffix={`/ ${stats?.totalCapacity || 0}`} prefix={<CheckCircleOutlined />} /></Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Card><Statistic title="入住率" value={stats?.occupancyRate || 0} suffix="%" prefix={<DollarOutlined />} /></Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Card title="入住时间线(甘特图)" style={{ marginBottom: 24 }}>
|
||||
{ganttData.length > 0 ? (
|
||||
<ReactECharts option={ganttOption()} style={{ height: Math.max(300, ganttData.length * 40) }} />
|
||||
) : (
|
||||
<div style={{ textAlign: 'center', padding: 40, color: '#999' }}>暂无入住数据</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Row gutter={16}>
|
||||
<Col span={12}>
|
||||
<Card title="费用类型分布">
|
||||
{expenseStats.length > 0 ? (
|
||||
<ReactECharts option={pieOption} style={{ height: 300 }} />
|
||||
) : (
|
||||
<div style={{ textAlign: 'center', padding: 40, color: '#999' }}>暂无费用数据</div>
|
||||
)}
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Card title="宿舍费用排行 TOP 20">
|
||||
{roomRanking.length > 0 ? (
|
||||
<ReactECharts option={barOption} style={{ height: 300 }} />
|
||||
) : (
|
||||
<div style={{ textAlign: 'center', padding: 40, color: '#999' }}>暂无费用数据</div>
|
||||
)}
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DashboardPage;
|
||||
191
apps/admin/src/pages/Deposits/index.tsx
Normal file
191
apps/admin/src/pages/Deposits/index.tsx
Normal file
@@ -0,0 +1,191 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { Table, Button, Modal, Form, Select, DatePicker, InputNumber, Input, Space, message, Tag, Popconfirm } from 'antd';
|
||||
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
paid: { text: '已缴', color: 'green' },
|
||||
refunded: { text: '已全退', color: 'blue' },
|
||||
partial_refund: { text: '部分退还', color: 'orange' },
|
||||
deducted: { text: '已全扣', color: 'red' },
|
||||
};
|
||||
|
||||
const DepositsPage: React.FC = () => {
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [students, setStudents] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [createModal, setCreateModal] = useState(false);
|
||||
const [refundModal, setRefundModal] = useState<any>(null);
|
||||
const [createForm] = Form.useForm();
|
||||
const [refundForm] = Form.useForm();
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [d, s]: any[] = await Promise.all([
|
||||
api.get('/deposits'),
|
||||
api.get('/students'),
|
||||
]);
|
||||
setData(d);
|
||||
setStudents(s);
|
||||
} catch (e) { console.error(e); }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => { fetchData(); }, []);
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
return data.filter((d: any) => {
|
||||
if (searchText) {
|
||||
const s = searchText.toLowerCase();
|
||||
if (!d.student?.name?.toLowerCase().includes(s)) return false;
|
||||
}
|
||||
if (filterStatus && d.status !== filterStatus) return false;
|
||||
return true;
|
||||
});
|
||||
}, [data, searchText, filterStatus]);
|
||||
|
||||
const handleCreate = async () => {
|
||||
const values = await createForm.validateFields();
|
||||
try {
|
||||
await api.post('/deposits', {
|
||||
studentId: values.studentId,
|
||||
amount: values.amount,
|
||||
paidDate: values.paidDate.format('YYYY-MM-DD'),
|
||||
notes: values.notes,
|
||||
});
|
||||
message.success('押金记录已创建');
|
||||
setCreateModal(false);
|
||||
createForm.resetFields();
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const handleRefund = async () => {
|
||||
const values = await refundForm.validateFields();
|
||||
try {
|
||||
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();
|
||||
} catch (e: any) { message.error(e?.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{ title: '学生', render: (_: any, r: any) => r.student?.name || '-' },
|
||||
{ title: '押金金额', dataIndex: 'amount', render: (v: number) => `¥${Number(v).toFixed(2)}` },
|
||||
{ title: '缴纳日期', dataIndex: 'paidDate' },
|
||||
{
|
||||
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', render: (v: any) => v || '-' },
|
||||
{ title: '退还日期', dataIndex: 'refundDate', render: (v: any) => v || '-' },
|
||||
{ title: '备注', dataIndex: 'notes', render: (v: any) => v || '-' },
|
||||
{
|
||||
title: '操作', width: 160,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
{record.status === 'paid' && (
|
||||
<PermissionButton permission="deposit:edit" size="small" type="primary" onClick={() => {
|
||||
setRefundModal(record);
|
||||
refundForm.setFieldsValue({ refundDate: dayjs(), deductionAmount: 0 });
|
||||
}}>退还</PermissionButton>
|
||||
)}
|
||||
<PermissionButton permission="deposit:delete">
|
||||
<Popconfirm title="确定删除?" onConfirm={async () => {
|
||||
try { await api.delete(`/deposits/${record.id}`); message.success('删除成功'); fetchData(); } catch (e: any) { message.error(e?.message || '删除失败'); }
|
||||
}}>
|
||||
<Button size="small" danger icon={<DeleteOutlined />} />
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
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(''); }}
|
||||
/>
|
||||
<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} pagination={{ pageSize: 15, showTotal: (total) => `共 ${total} 条` }} />
|
||||
|
||||
<Modal title="收取押金" open={createModal} onOk={handleCreate} onCancel={() => setCreateModal(false)} okText="确认">
|
||||
<Form form={createForm} layout="vertical">
|
||||
<Form.Item name="studentId" label="学生" rules={[{ required: true, message: '请选择学生' }]}>
|
||||
<Select showSearch optionFilterProp="label" placeholder="搜索并选择学生"
|
||||
options={students.filter((s: any) => s.status === 'active').map((s: any) => ({ value: s.id, label: `${s.name} (${s.idNumber || s.phone || ''})` }))} />
|
||||
</Form.Item>
|
||||
<Form.Item name="amount" label="押金金额(元)" rules={[{ required: true }]}>
|
||||
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="paidDate" label="缴纳日期" rules={[{ required: true }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择缴纳日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal title={`退还押金 - ${refundModal?.student?.name}`} open={!!refundModal} onOk={handleRefund} onCancel={() => setRefundModal(null)} okText="确认退还">
|
||||
<Form form={refundForm} layout="vertical">
|
||||
<div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 8 }}>
|
||||
押金金额: <strong>¥{Number(refundModal?.amount || 0).toFixed(2)}</strong>
|
||||
</div>
|
||||
<Form.Item name="refundDate" label="退还日期" rules={[{ required: true }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择退还日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="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>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DepositsPage;
|
||||
435
apps/admin/src/pages/Expenses/index.tsx
Normal file
435
apps/admin/src/pages/Expenses/index.tsx
Normal file
@@ -0,0 +1,435 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { Table, Button, Modal, Form, Select, DatePicker, InputNumber, Input, Space, message, Tag, Tabs, Popconfirm, Upload } from 'antd';
|
||||
import { PlusOutlined, DeleteOutlined, EditOutlined, UploadOutlined, DownloadOutlined, ExportOutlined } from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
const expenseTypeOptions = [
|
||||
{ value: 'water', label: '水费' },
|
||||
{ value: 'electricity', label: '电费' },
|
||||
{ value: 'cleaning', label: '保洁费' },
|
||||
{ value: 'damage', label: '损坏赔偿' },
|
||||
{ value: 'other', label: '其他' },
|
||||
];
|
||||
|
||||
const personalExpenseTypeOptions = [
|
||||
{ value: 'damage', label: '物品损坏' },
|
||||
{ value: 'cleaning', label: '保洁费' },
|
||||
{ value: 'penalty', label: '罚款' },
|
||||
{ value: 'key', label: '钥匙费' },
|
||||
{ value: 'remote', label: '空调遥控器' },
|
||||
{ value: 'deposit_deduction', label: '押金扣除' },
|
||||
{ value: 'other', label: '其他' },
|
||||
];
|
||||
|
||||
const typeMap: Record<string, string> = { water: '水费', electricity: '电费', cleaning: '保洁费', damage: '损坏赔偿', penalty: '罚款', key: '钥匙费', remote: '空调遥控器', deposit_deduction: '押金扣除', other: '其他' };
|
||||
|
||||
const ExpensesPage: React.FC = () => {
|
||||
const [roomExpenses, setRoomExpenses] = useState<any[]>([]);
|
||||
const [personalExpenses, setPersonalExpenses] = useState<any[]>([]);
|
||||
const [rooms, setRooms] = useState<any[]>([]);
|
||||
const [students, setStudents] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [roomModal, setRoomModal] = useState(false);
|
||||
const [personalModal, setPersonalModal] = useState(false);
|
||||
const [editingRoom, setEditingRoom] = useState<any>(null);
|
||||
const [editingPersonal, setEditingPersonal] = useState<any>(null);
|
||||
const [roomForm] = Form.useForm();
|
||||
const [personalForm] = Form.useForm();
|
||||
const [roomSearch, setRoomSearch] = useState('');
|
||||
const [roomTypeFilter, setRoomTypeFilter] = useState<string | undefined>(undefined);
|
||||
const [personalSearch, setPersonalSearch] = useState('');
|
||||
const [personalTypeFilter, setPersonalTypeFilter] = useState<string | undefined>(undefined);
|
||||
const [selectedRoomKeys, setSelectedRoomKeys] = useState<number[]>([]);
|
||||
const [selectedPersonalKeys, setSelectedPersonalKeys] = useState<number[]>([]);
|
||||
|
||||
const handleBatchDeleteRoom = async () => {
|
||||
try {
|
||||
const res: any = await api.post('/expenses/room/batch-delete', { ids: selectedRoomKeys });
|
||||
message.success(res?.message || `已删除 ${selectedRoomKeys.length} 条`);
|
||||
setSelectedRoomKeys([]);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '批量删除失败'); }
|
||||
};
|
||||
|
||||
const handleBatchDeletePersonal = async () => {
|
||||
try {
|
||||
const res: any = await api.post('/expenses/personal/batch-delete', { ids: selectedPersonalKeys });
|
||||
message.success(res?.message || `已删除 ${selectedPersonalKeys.length} 条`);
|
||||
setSelectedPersonalKeys([]);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '批量删除失败'); }
|
||||
};
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [re, pe, rm, st]: any[] = await Promise.all([
|
||||
api.get('/expenses/room'),
|
||||
api.get('/expenses/personal'),
|
||||
api.get('/rooms'),
|
||||
api.get('/students'),
|
||||
]);
|
||||
setRoomExpenses(re);
|
||||
setPersonalExpenses(pe);
|
||||
setRooms(rm);
|
||||
setStudents(st);
|
||||
} catch (e) { console.error(e); }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => { fetchData(); }, []);
|
||||
|
||||
const filteredRoomExpenses = useMemo(() => {
|
||||
return roomExpenses.filter((r: any) => {
|
||||
if (roomSearch) {
|
||||
const s = roomSearch.toLowerCase();
|
||||
if (!r.room?.roomNumber?.toLowerCase().includes(s)) return false;
|
||||
}
|
||||
if (roomTypeFilter && r.expenseType !== roomTypeFilter) return false;
|
||||
return true;
|
||||
});
|
||||
}, [roomExpenses, roomSearch, roomTypeFilter]);
|
||||
|
||||
const filteredPersonalExpenses = useMemo(() => {
|
||||
return personalExpenses.filter((p: any) => {
|
||||
if (personalSearch) {
|
||||
const s = personalSearch.toLowerCase();
|
||||
if (!p.student?.name?.toLowerCase().includes(s)) return false;
|
||||
}
|
||||
if (personalTypeFilter && p.expenseType !== personalTypeFilter) return false;
|
||||
return true;
|
||||
});
|
||||
}, [personalExpenses, personalSearch, personalTypeFilter]);
|
||||
|
||||
const handleRoomExpense = async () => {
|
||||
const values = await roomForm.validateFields();
|
||||
const payload = {
|
||||
roomId: values.roomId,
|
||||
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,
|
||||
};
|
||||
try {
|
||||
if (editingRoom) {
|
||||
await api.put(`/expenses/room/${editingRoom.id}`, payload);
|
||||
message.success('更新成功');
|
||||
} else {
|
||||
await api.post('/expenses/room', payload);
|
||||
message.success('录入成功');
|
||||
}
|
||||
setRoomModal(false);
|
||||
setEditingRoom(null);
|
||||
roomForm.resetFields();
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const handlePersonalExpense = async () => {
|
||||
const values = await personalForm.validateFields();
|
||||
const payload = {
|
||||
studentId: values.studentId,
|
||||
roomId: values.roomId,
|
||||
expenseType: values.expenseType,
|
||||
amount: values.amount,
|
||||
expenseDate: values.expenseDate.format('YYYY-MM-DD'),
|
||||
description: values.description,
|
||||
};
|
||||
try {
|
||||
if (editingPersonal) {
|
||||
await api.put(`/expenses/personal/${editingPersonal.id}`, payload);
|
||||
message.success('更新成功');
|
||||
} else {
|
||||
await api.post('/expenses/personal', payload);
|
||||
message.success('录入成功');
|
||||
}
|
||||
setPersonalModal(false);
|
||||
setEditingPersonal(null);
|
||||
personalForm.resetFields();
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const roomColumns = [
|
||||
{ title: '宿舍', render: (_: any, r: any) => r.room?.roomNumber || '-' },
|
||||
{ title: '费用类型', dataIndex: 'expenseType', render: (v: string) => <Tag>{typeMap[v] || v}</Tag> },
|
||||
{ title: '金额', dataIndex: 'amount', render: (v: number) => `¥${Number(v).toFixed(2)}` },
|
||||
{ title: '账单周期', render: (_: any, r: any) => `${r.periodStart} ~ ${r.periodEnd}` },
|
||||
{ title: '说明', dataIndex: 'description' },
|
||||
{ title: '录入时间', dataIndex: 'createdAt', render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm') },
|
||||
{
|
||||
title: '操作', width: 120,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
<PermissionButton permission="expense:edit" size="small" icon={<EditOutlined />} onClick={() => {
|
||||
setEditingRoom(record);
|
||||
roomForm.setFieldsValue({
|
||||
roomId: record.roomId,
|
||||
expenseType: record.expenseType,
|
||||
amount: Number(record.amount),
|
||||
period: [dayjs(record.periodStart), dayjs(record.periodEnd)],
|
||||
description: record.description,
|
||||
});
|
||||
setRoomModal(true);
|
||||
}}>{''}</PermissionButton>
|
||||
<PermissionButton permission="expense:delete">
|
||||
<Popconfirm title="确定删除?" onConfirm={async () => { await api.delete(`/expenses/room/${record.id}`); message.success('删除成功'); fetchData(); }}>
|
||||
<Button size="small" danger icon={<DeleteOutlined />} />
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const personalColumns = [
|
||||
{ title: '学生', render: (_: any, r: any) => r.student?.name || '-' },
|
||||
{ title: '费用类型', 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' },
|
||||
{ title: '说明', dataIndex: 'description' },
|
||||
{
|
||||
title: '操作', width: 120,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
<PermissionButton permission="expense:edit" size="small" icon={<EditOutlined />} onClick={() => {
|
||||
setEditingPersonal(record);
|
||||
personalForm.setFieldsValue({
|
||||
studentId: record.studentId,
|
||||
roomId: record.roomId,
|
||||
expenseType: record.expenseType,
|
||||
amount: Number(record.amount),
|
||||
expenseDate: dayjs(record.expenseDate),
|
||||
description: record.description,
|
||||
});
|
||||
setPersonalModal(true);
|
||||
}}>{''}</PermissionButton>
|
||||
<PermissionButton permission="expense:delete">
|
||||
<Popconfirm title="确定删除?" onConfirm={async () => { await api.delete(`/expenses/personal/${record.id}`); message.success('删除成功'); fetchData(); }}>
|
||||
<Button size="small" danger icon={<DeleteOutlined />} />
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Tabs items={[
|
||||
{
|
||||
key: 'room',
|
||||
label: '宿舍费用',
|
||||
children: (
|
||||
<>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
|
||||
<Space wrap>
|
||||
<Input.Search
|
||||
placeholder="搜索宿舍号"
|
||||
allowClear
|
||||
style={{ width: 160 }}
|
||||
onSearch={v => setRoomSearch(v)}
|
||||
onChange={e => { if (!e.target.value) setRoomSearch(''); }}
|
||||
/>
|
||||
<Select
|
||||
placeholder="费用类型"
|
||||
allowClear
|
||||
style={{ width: 120 }}
|
||||
value={roomTypeFilter}
|
||||
onChange={v => setRoomTypeFilter(v)}
|
||||
options={expenseTypeOptions}
|
||||
/>
|
||||
<PermissionButton permission="expense:create">
|
||||
<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('/expenses/utility/import', formData, { headers: { 'Content-Type': 'multipart/form-data' } });
|
||||
if (res.errors?.length > 0) {
|
||||
Modal.warning({ title: res.message, content: res.errors.join('\n'), width: 500 });
|
||||
} else {
|
||||
message.success(res.message);
|
||||
}
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '导入失败'); onError?.(e); }
|
||||
}}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入水电费Excel</Button>
|
||||
</Upload>
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="expense:view" icon={<DownloadOutlined />} onClick={() => {
|
||||
const baseURL = import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
|
||||
const token = localStorage.getItem('token');
|
||||
fetch(`${baseURL}/expenses/utility/template`, { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then(res => res.blob())
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = '水电费导入模板.xlsx';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch(() => message.error('下载失败'));
|
||||
}}>下载水电费模板</PermissionButton>
|
||||
</Space>
|
||||
<Space>
|
||||
<PermissionButton permission="expense:delete">
|
||||
<Popconfirm title={`确定删除选中的 ${selectedRoomKeys.length} 条费用?`} onConfirm={handleBatchDeleteRoom} okText="删除" cancelText="取消" disabled={selectedRoomKeys.length === 0}>
|
||||
<Button danger icon={<DeleteOutlined />} disabled={selectedRoomKeys.length === 0}>批量删除</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="expense:create" type="primary" icon={<PlusOutlined />} onClick={() => { setEditingRoom(null); roomForm.resetFields(); setRoomModal(true); }}>录入宿舍费用</PermissionButton>
|
||||
</Space>
|
||||
</div>
|
||||
<Table columns={roomColumns} dataSource={filteredRoomExpenses} rowKey="id" loading={loading} pagination={{ pageSize: 15, showTotal: (total) => `共 ${total} 条` }}
|
||||
rowSelection={{ selectedRowKeys: selectedRoomKeys, onChange: (keys) => setSelectedRoomKeys(keys as number[]) }}
|
||||
/>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'personal',
|
||||
label: '个人附加费',
|
||||
children: (
|
||||
<>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
|
||||
<Space wrap>
|
||||
<Input.Search
|
||||
placeholder="搜索学生姓名"
|
||||
allowClear
|
||||
style={{ width: 160 }}
|
||||
onSearch={v => setPersonalSearch(v)}
|
||||
onChange={e => { if (!e.target.value) setPersonalSearch(''); }}
|
||||
/>
|
||||
<Select
|
||||
placeholder="费用类型"
|
||||
allowClear
|
||||
style={{ width: 120 }}
|
||||
value={personalTypeFilter}
|
||||
onChange={v => setPersonalTypeFilter(v)}
|
||||
options={personalExpenseTypeOptions}
|
||||
/>
|
||||
<PermissionButton permission="expense:create">
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
const res: any = await api.post('/expenses/personal/import', formData);
|
||||
message.success(res.message || '导入完成');
|
||||
if (res.errors?.length) res.errors.forEach((e: string) => message.warning(e));
|
||||
fetchData();
|
||||
onSuccess?.(res);
|
||||
} catch (e: any) { message.error(e?.message || '导入失败'); onError?.(e); }
|
||||
}}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入个人附加费</Button>
|
||||
</Upload>
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="expense:view" icon={<DownloadOutlined />} onClick={() => {
|
||||
const baseURL = import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
|
||||
const token = localStorage.getItem('token');
|
||||
fetch(`${baseURL}/expenses/personal/template`, { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then(res => res.blob())
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = '个人附加费导入模板.xlsx';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch(() => message.error('下载失败'));
|
||||
}}>下载模板</PermissionButton>
|
||||
<PermissionButton permission="expense:view" icon={<ExportOutlined />} onClick={() => {
|
||||
const baseURL = import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
|
||||
const token = localStorage.getItem('token');
|
||||
fetch(`${baseURL}/expenses/personal/export`, { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then(res => res.blob())
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = '个人附加费导出.xlsx';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch(() => message.error('导出失败'));
|
||||
}}>导出</PermissionButton>
|
||||
</Space>
|
||||
<Space>
|
||||
<PermissionButton permission="expense:delete">
|
||||
<Popconfirm title={`确定删除选中的 ${selectedPersonalKeys.length} 条个人费用?`} onConfirm={handleBatchDeletePersonal} okText="删除" cancelText="取消" disabled={selectedPersonalKeys.length === 0}>
|
||||
<Button danger icon={<DeleteOutlined />} disabled={selectedPersonalKeys.length === 0}>批量删除</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="expense:create" type="primary" icon={<PlusOutlined />} onClick={() => { setEditingPersonal(null); personalForm.resetFields(); setPersonalModal(true); }}>录入个人费用</PermissionButton>
|
||||
</Space>
|
||||
</div>
|
||||
<Table columns={personalColumns} dataSource={filteredPersonalExpenses} rowKey="id" loading={loading} pagination={{ pageSize: 15, showTotal: (total) => `共 ${total} 条` }}
|
||||
rowSelection={{ selectedRowKeys: selectedPersonalKeys, onChange: (keys) => setSelectedPersonalKeys(keys as number[]) }}
|
||||
/>
|
||||
</>
|
||||
),
|
||||
},
|
||||
]} />
|
||||
|
||||
<Modal title={editingRoom ? '编辑宿舍费用' : '录入宿舍费用'} open={roomModal} onOk={handleRoomExpense} onCancel={() => { setRoomModal(false); setEditingRoom(null); }} okText={editingRoom ? '保存' : '确认录入'}>
|
||||
<Form form={roomForm} layout="vertical">
|
||||
<Form.Item name="roomId" label="宿舍" rules={[{ required: true }]}>
|
||||
<Select showSearch optionFilterProp="label" options={rooms.map((r: any) => ({ value: r.id, label: `${r.roomNumber} (${r.building || ''})` }))} />
|
||||
</Form.Item>
|
||||
<Form.Item name="expenseType" label="费用类型" rules={[{ required: true }]}>
|
||||
<Select options={expenseTypeOptions} />
|
||||
</Form.Item>
|
||||
<Form.Item name="amount" label="金额(元)" rules={[{ required: true }]}>
|
||||
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="period" label="账单周期" rules={[{ required: true }]}>
|
||||
<RangePicker style={{ width: '100%' }} placeholder={['开始日期', '结束日期']} format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="description" label="说明">
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal title={editingPersonal ? '编辑个人费用' : '录入个人附加费'} open={personalModal} onOk={handlePersonalExpense} onCancel={() => { setPersonalModal(false); setEditingPersonal(null); }} okText={editingPersonal ? '保存' : '确认录入'}>
|
||||
<Form form={personalForm} layout="vertical">
|
||||
<Form.Item name="studentId" label="学生" rules={[{ required: true }]}>
|
||||
<Select showSearch optionFilterProp="label" options={students.map((s: any) => ({ value: s.id, label: s.name }))} />
|
||||
</Form.Item>
|
||||
<Form.Item name="roomId" label="关联宿舍">
|
||||
<Select allowClear showSearch optionFilterProp="label" options={rooms.map((r: any) => ({ value: r.id, label: r.roomNumber }))} />
|
||||
</Form.Item>
|
||||
<Form.Item name="expenseType" label="费用类型" rules={[{ required: true }]}>
|
||||
<Select options={personalExpenseTypeOptions} />
|
||||
</Form.Item>
|
||||
<Form.Item name="amount" label="金额(元)" rules={[{ required: true }]}>
|
||||
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="expenseDate" label="费用日期" rules={[{ required: true }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="description" label="说明">
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ExpensesPage;
|
||||
54
apps/admin/src/pages/Login/index.tsx
Normal file
54
apps/admin/src/pages/Login/index.tsx
Normal file
@@ -0,0 +1,54 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Form, Input, Button, Card, message, Typography } from 'antd';
|
||||
import { UserOutlined, LockOutlined } from '@ant-design/icons';
|
||||
import api from '../../api';
|
||||
|
||||
const { Title } = Typography;
|
||||
|
||||
const LoginPage: React.FC = () => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const onFinish = 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));
|
||||
localStorage.setItem('permissions', JSON.stringify(res.user.permissions || []));
|
||||
message.success('登录成功');
|
||||
navigate('/dashboard');
|
||||
} catch (err: any) {
|
||||
message.error(err?.message || '登录失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f5f5f7' }}>
|
||||
<Card style={{ width: 400, borderRadius: 16, boxShadow: '0 4px 24px rgba(0,0,0,0.08)', border: 'none' }}>
|
||||
<div style={{ textAlign: 'center', marginBottom: 32 }}>
|
||||
<Title level={3} style={{ margin: 0, fontWeight: 600, color: '#1d1d1f' }}>恭学教育基地管理系统</Title>
|
||||
<p style={{ color: '#86868b', marginTop: 8 }}>水电费精准计费平台</p>
|
||||
</div>
|
||||
<Form name="login" onFinish={onFinish} size="large">
|
||||
<Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
|
||||
<Input prefix={<UserOutlined />} placeholder="用户名" />
|
||||
</Form.Item>
|
||||
<Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
|
||||
<Input.Password prefix={<LockOutlined />} placeholder="密码" />
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Button type="primary" htmlType="submit" loading={loading} block style={{ height: 44, borderRadius: 10, fontWeight: 500 }}>
|
||||
登 录
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LoginPage;
|
||||
375
apps/admin/src/pages/Occupancies/index.tsx
Normal file
375
apps/admin/src/pages/Occupancies/index.tsx
Normal file
@@ -0,0 +1,375 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { Table, Button, Modal, Form, Select, DatePicker, Input, InputNumber, Space, message, Tag, Popconfirm, Upload, Switch, Alert, Tooltip } from 'antd';
|
||||
import { PlusOutlined, SwapOutlined, LogoutOutlined, DeleteOutlined, UploadOutlined, DownloadOutlined, ExportOutlined } from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
|
||||
const OccupanciesPage: React.FC = () => {
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [students, setStudents] = useState<any[]>([]);
|
||||
const [rooms, setRooms] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [checkInModal, setCheckInModal] = useState(false);
|
||||
const [checkOutModal, setCheckOutModal] = useState<any>(null);
|
||||
const [transferModal, setTransferModal] = useState<any>(null);
|
||||
const [showActive, setShowActive] = useState(true);
|
||||
const [autoDeposit, setAutoDeposit] = useState(true);
|
||||
const [depositAmount, setDepositAmount] = useState(500);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
|
||||
const [batchCheckOutModal, setBatchCheckOutModal] = useState(false);
|
||||
const [checkInForm] = Form.useForm();
|
||||
const [checkOutForm] = Form.useForm();
|
||||
const [transferForm] = Form.useForm();
|
||||
const [batchCheckOutForm] = Form.useForm();
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [occ, stu, rm]: any[] = await Promise.all([
|
||||
api.get('/occupancies', { params: { active: showActive ? 'true' : undefined } }),
|
||||
api.get('/students'),
|
||||
api.get('/rooms/overview'),
|
||||
]);
|
||||
setData(occ);
|
||||
setStudents(stu);
|
||||
setRooms(rm);
|
||||
} catch (e) { console.error(e); }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => { fetchData(); setSelectedRowKeys([]); }, [showActive]);
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
if (!searchText) return data;
|
||||
const keyword = searchText.toLowerCase();
|
||||
return data.filter((r: any) =>
|
||||
r.student?.name?.toLowerCase().includes(keyword) ||
|
||||
r.room?.roomNumber?.toLowerCase().includes(keyword)
|
||||
);
|
||||
}, [data, searchText]);
|
||||
|
||||
const handleCheckIn = async () => {
|
||||
const values = await checkInForm.validateFields();
|
||||
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'),
|
||||
notes: values.notes,
|
||||
});
|
||||
message.success('入住登记成功');
|
||||
setCheckInModal(false);
|
||||
checkInForm.resetFields();
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const handleCheckOut = async () => {
|
||||
const values = await checkOutForm.validateFields();
|
||||
try {
|
||||
await api.put(`/occupancies/${checkOutModal.id}/check-out`, {
|
||||
checkOutDate: values.checkOutDate.format('YYYY-MM-DD'),
|
||||
billingEndDate: values.billingEndDate?.format('YYYY-MM-DD'),
|
||||
checkOutReason: values.checkOutReason,
|
||||
});
|
||||
message.success('退宿成功');
|
||||
setCheckOutModal(null);
|
||||
checkOutForm.resetFields();
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const handleTransfer = async () => {
|
||||
const values = await transferForm.validateFields();
|
||||
try {
|
||||
await api.put(`/occupancies/${transferModal.id}/transfer`, {
|
||||
newRoomId: values.newRoomId,
|
||||
transferDate: values.transferDate.format('YYYY-MM-DD'),
|
||||
oldBillingEndDate: values.oldBillingEndDate?.format('YYYY-MM-DD'),
|
||||
newBillingStartDate: values.newBillingStartDate?.format('YYYY-MM-DD'),
|
||||
reason: values.reason,
|
||||
});
|
||||
message.success('换房成功');
|
||||
setTransferModal(null);
|
||||
transferForm.resetFields();
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const handleBatchCheckOut = async () => {
|
||||
const values = await batchCheckOutForm.validateFields();
|
||||
try {
|
||||
const res: any = await api.post('/occupancies/batch-check-out', {
|
||||
ids: selectedRowKeys,
|
||||
checkOutDate: values.checkOutDate.format('YYYY-MM-DD'),
|
||||
billingEndDate: values.billingEndDate?.format('YYYY-MM-DD'),
|
||||
checkOutReason: values.checkOutReason,
|
||||
});
|
||||
message.success(res.message || `已成功退宿 ${res.success} 人`);
|
||||
setBatchCheckOutModal(false);
|
||||
batchCheckOutForm.resetFields();
|
||||
setSelectedRowKeys([]);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '批量退宿失败'); }
|
||||
};
|
||||
|
||||
const handleBatchDelete = async () => {
|
||||
try {
|
||||
const res: any = await api.post('/occupancies/batch-delete', { ids: selectedRowKeys });
|
||||
message.success(res?.message || `已删除 ${selectedRowKeys.length} 条`);
|
||||
setSelectedRowKeys([]);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '批量删除失败'); }
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{ title: '学生', render: (_: any, r: any) => r.student?.name || '-' },
|
||||
{ title: '宿舍', render: (_: any, r: any) => r.room?.roomNumber || '-' },
|
||||
{ title: '入住日期', dataIndex: 'checkInDate' },
|
||||
{ title: '计费起始', dataIndex: 'billingStartDate' },
|
||||
{ title: '退宿日期', dataIndex: 'checkOutDate', render: (v: any) => v || <Tag color="green">在住</Tag> },
|
||||
{ title: '计费截止', dataIndex: 'billingEndDate', render: (v: any) => v || '-' },
|
||||
{ title: '退宿原因', dataIndex: 'checkOutReason', render: (v: any) => v || '-' },
|
||||
{
|
||||
title: '操作', width: 200,
|
||||
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={() => { setTransferModal(record); transferForm.setFieldsValue({ transferDate: dayjs() }); }}>换房</PermissionButton>
|
||||
</Space>
|
||||
) : (
|
||||
<Space>
|
||||
<Tag>已退宿</Tag>
|
||||
<PermissionButton permission="occupancy:delete">
|
||||
<Popconfirm title="确定删除此记录?" onConfirm={async () => { try { await api.delete(`/occupancies/${record.id}`); message.success('删除成功'); fetchData(); } catch (e: any) { message.error(e?.message || '删除失败'); } }}>
|
||||
<Button size="small" danger icon={<DeleteOutlined />} />
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const rowSelection = {
|
||||
selectedRowKeys,
|
||||
onChange: (keys: any[]) => setSelectedRowKeys(keys),
|
||||
// 「在住记录」Tab:禁用已退宿(防止误选用于批量退宿);「全部记录」Tab:均可选用于批量删除
|
||||
getCheckboxProps: (record: any) => showActive ? { disabled: !!record.checkOutDate } : {},
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Alert
|
||||
message="一站式导入"
|
||||
description="导入入住名单时会自动创建学生和宿舍,无需单独在「学生管理」或「宿舍管理」中手动添加。后续仅需在此页面处理换房/退宿等日常操作即可。"
|
||||
type="info"
|
||||
showIcon
|
||||
closable
|
||||
style={{ marginBottom: 16 }}
|
||||
/>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
|
||||
<Space wrap>
|
||||
<Button type={showActive ? 'primary' : 'default'} onClick={() => setShowActive(true)}>在住记录</Button>
|
||||
<Button type={!showActive ? 'primary' : 'default'} onClick={() => setShowActive(false)}>全部记录</Button>
|
||||
<Input.Search placeholder="搜索学生姓名或房间号" onSearch={setSearchText} allowClear style={{ width: 200 }} />
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<PermissionButton permission="occupancy:checkin" type="primary" icon={<PlusOutlined />} onClick={() => { checkInForm.resetFields(); checkInForm.setFieldsValue({ checkInDate: dayjs() }); setCheckInModal(true); }}>
|
||||
入住登记
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="occupancy:checkin">
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
const params = new URLSearchParams();
|
||||
if (autoDeposit) {
|
||||
params.set('autoDeposit', 'true');
|
||||
params.set('depositAmount', String(depositAmount));
|
||||
}
|
||||
try {
|
||||
const res: any = await api.post(`/occupancies/import?${params.toString()}`, formData, { headers: { 'Content-Type': 'multipart/form-data' } });
|
||||
if (res.errors?.length > 0) {
|
||||
Modal.warning({ title: res.message, content: res.errors.join('\n'), width: 500 });
|
||||
} else {
|
||||
message.success(res.message);
|
||||
}
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '导入失败'); onError?.(e); }
|
||||
}}
|
||||
>
|
||||
<Tooltip title="导入时自动创建学生、宿舍和入住记录">
|
||||
<Button type="primary" ghost icon={<UploadOutlined />}>导入入住名单</Button>
|
||||
</Tooltip>
|
||||
</Upload>
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="occupancy:view" icon={<DownloadOutlined />} onClick={() => {
|
||||
const baseURL = import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
|
||||
const token = localStorage.getItem('token');
|
||||
fetch(`${baseURL}/occupancies/template`, { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then(res => res.blob())
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = '入住名单导入模板.xlsx';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch(() => message.error('下载失败'));
|
||||
}}>下载模板</PermissionButton>
|
||||
<PermissionButton permission="occupancy:view" icon={<ExportOutlined />} onClick={() => {
|
||||
const baseURL = import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
|
||||
const token = localStorage.getItem('token');
|
||||
const params = showActive ? '?active=true' : '';
|
||||
fetch(`${baseURL}/occupancies/export${params}`, { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then(res => res.blob())
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = showActive ? '在住记录.xlsx' : '全部入住记录.xlsx';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch(() => message.error('导出失败'));
|
||||
}}>导出记录</PermissionButton>
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
|
||||
<Switch size="small" checked={autoDeposit} onChange={setAutoDeposit} />
|
||||
导入时自动收押金
|
||||
{autoDeposit && <InputNumber size="small" min={0} value={depositAmount} onChange={(v) => setDepositAmount(v || 500)} style={{ width: 80 }} addonAfter="元" />}
|
||||
</span>
|
||||
</Space>
|
||||
</div>
|
||||
{selectedRowKeys.length > 0 && (
|
||||
<Alert
|
||||
message={
|
||||
<span>
|
||||
已选 <strong>{selectedRowKeys.length}</strong> 条记录
|
||||
{showActive ? (
|
||||
<PermissionButton permission="occupancy:checkout" type="primary" size="small" icon={<LogoutOutlined />} onClick={() => { batchCheckOutForm.resetFields(); batchCheckOutForm.setFieldsValue({ checkOutDate: dayjs() }); setBatchCheckOutModal(true); }} style={{ marginLeft: 12 }}>批量退宿</PermissionButton>
|
||||
) : (
|
||||
<PermissionButton permission="occupancy:delete">
|
||||
<Popconfirm title={`确定删除选中的 ${selectedRowKeys.length} 条入住记录?在住记录会自动跳过`} onConfirm={handleBatchDelete} okText="删除" cancelText="取消">
|
||||
<Button danger size="small" icon={<DeleteOutlined />} style={{ marginLeft: 12 }}>批量删除</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
)}
|
||||
<Button size="small" onClick={() => setSelectedRowKeys([])} style={{ marginLeft: 8 }}>取消选择</Button>
|
||||
</span>
|
||||
}
|
||||
type="info"
|
||||
style={{ marginBottom: 12 }}
|
||||
/>
|
||||
)}
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={filteredData}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
pagination={{ pageSize: 15, showTotal: (total) => `共 ${total} 条` }}
|
||||
rowSelection={rowSelection}
|
||||
/>
|
||||
|
||||
{/* 入住登记弹窗 */}
|
||||
<Modal title="入住登记" open={checkInModal} onOk={handleCheckIn} onCancel={() => setCheckInModal(false)} okText="确认入住" width={500}>
|
||||
<Form form={checkInForm} layout="vertical">
|
||||
<Form.Item name="studentId" label="选择学生" rules={[{ required: true, message: '请选择学生' }]}>
|
||||
<Select showSearch optionFilterProp="label" placeholder="搜索并选择学生"
|
||||
options={students.filter((s: any) => s.status === 'active').map((s: any) => ({ value: s.id, label: `${s.name} (${s.idNumber || s.phone || ''})` }))} />
|
||||
</Form.Item>
|
||||
<Form.Item name="roomId" label="选择宿舍" rules={[{ required: true, message: '请选择宿舍' }]}>
|
||||
<Select showSearch optionFilterProp="label" placeholder="搜索并选择宿舍"
|
||||
options={rooms.map((r: any) => ({ value: r.id, label: `${r.roomNumber} (${r.building || ''}) [${r.currentCount}/${r.capacity}]`, disabled: r.currentCount >= r.capacity }))} />
|
||||
</Form.Item>
|
||||
<Form.Item name="checkInDate" label="入住日期" rules={[{ required: true }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择入住日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="billingStartDate" label="计费起始日" extra="默认与入住日期相同,可调整(如学生要求从次日开始计费)">
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择计费起始日" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
{/* 退宿弹窗 */}
|
||||
<Modal title={`退宿 - ${checkOutModal?.student?.name}`} open={!!checkOutModal} onOk={handleCheckOut} onCancel={() => setCheckOutModal(null)} okText="确认退宿">
|
||||
<Form form={checkOutForm} layout="vertical">
|
||||
<Form.Item name="checkOutDate" label="退宿日期" rules={[{ required: true }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择退宿日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="billingEndDate" label="计费截止日" extra="默认与退宿日期相同">
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择计费截止日" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="checkOutReason" label="退宿原因">
|
||||
<Select allowClear options={[
|
||||
{ value: '换房', label: '换房' },
|
||||
{ value: '退训', label: '退训' },
|
||||
{ value: '结业', label: '结业' },
|
||||
{ value: '毕业', label: '毕业' },
|
||||
{ value: '其他', label: '其他' },
|
||||
]} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
{/* 批量退宿弹窗 */}
|
||||
<Modal title={`批量退宿(${selectedRowKeys.length} 人)`} open={batchCheckOutModal} onOk={handleBatchCheckOut} onCancel={() => setBatchCheckOutModal(false)} okText="确认批量退宿" width={500}>
|
||||
<Form form={batchCheckOutForm} layout="vertical">
|
||||
<Form.Item name="checkOutDate" label="退宿日期" rules={[{ required: true }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择退宿日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="billingEndDate" label="计费截止日" extra="默认与退宿日期相同">
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择计费截止日" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="checkOutReason" label="退宿原因">
|
||||
<Select allowClear options={[
|
||||
{ value: '结业', label: '结业' },
|
||||
{ value: '退训', label: '退训' },
|
||||
{ value: '毕业', label: '毕业' },
|
||||
{ value: '其他', label: '其他' },
|
||||
]} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
<div style={{ marginTop: 12, padding: '8px 12px', background: '#f5f5f5', borderRadius: 6, maxHeight: 150, overflow: 'auto' }}>
|
||||
<div style={{ fontSize: 12, color: '#666', marginBottom: 4 }}>即将退宿的学生:</div>
|
||||
{data.filter((r: any) => selectedRowKeys.includes(r.id)).map((r: any) => (
|
||||
<Tag key={r.id} style={{ marginBottom: 4 }}>{r.student?.name} ({r.room?.roomNumber})</Tag>
|
||||
))}
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
{/* 换房弹窗 */}
|
||||
<Modal title={`换房 - ${transferModal?.student?.name}`} open={!!transferModal} onOk={handleTransfer} onCancel={() => setTransferModal(null)} okText="确认换房" width={500}>
|
||||
<Form form={transferForm} layout="vertical">
|
||||
<Form.Item name="newRoomId" label="目标宿舍" rules={[{ required: true }]}>
|
||||
<Select showSearch optionFilterProp="label" placeholder="选择目标宿舍"
|
||||
options={rooms.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 }))} />
|
||||
</Form.Item>
|
||||
<Form.Item name="transferDate" label="换房日期" rules={[{ required: true }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择换房日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="oldBillingEndDate" label="旧房计费截止日" extra="默认为换房当天">
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择旧房计费截止日" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="newBillingStartDate" label="新房计费起始日" extra="默认为换房次日">
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择新房计费起始日" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="reason" label="换房原因">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OccupanciesPage;
|
||||
97
apps/admin/src/pages/OperationLogs/index.tsx
Normal file
97
apps/admin/src/pages/OperationLogs/index.tsx
Normal file
@@ -0,0 +1,97 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Table, Select, DatePicker, Space, Tag, Tooltip } from 'antd';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
const moduleColorMap: Record<string, string> = {
|
||||
'学生': 'blue', '宿舍': 'green', '入住': 'cyan', '费用': 'orange', '账单': 'red', '账号': 'purple', '认证': 'magenta',
|
||||
};
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
success: { text: '成功', color: 'green' },
|
||||
fail: { text: '失败', color: 'red' },
|
||||
};
|
||||
|
||||
const OperationLogsPage: React.FC = () => {
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [page, setPage] = useState(1);
|
||||
const [filterModule, setFilterModule] = useState<string | undefined>();
|
||||
const [dateRange, setDateRange] = useState<[string, string] | null>(null);
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params: any = { page, pageSize: 20 };
|
||||
if (filterModule) params.module = filterModule;
|
||||
if (dateRange) { params.startDate = dateRange[0]; params.endDate = dateRange[1]; }
|
||||
const res: any = await api.get('/operation-logs', { params });
|
||||
setData(res.data);
|
||||
setTotal(res.total);
|
||||
} catch (e) { console.error(e); }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => { fetchData(); }, [page, filterModule, dateRange]);
|
||||
|
||||
const columns = [
|
||||
{ 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: 80, render: (v: string) => <Tag color={moduleColorMap[v] || 'default'}>{v}</Tag> },
|
||||
{ title: '操作', dataIndex: 'action', width: 150 },
|
||||
{ title: '状态', dataIndex: 'status', width: 70, render: (v: string) => {
|
||||
const s = statusMap[v] || statusMap['success'];
|
||||
return <Tag color={s.color}>{s.text}</Tag>;
|
||||
}},
|
||||
{ title: '详情', 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: 100, 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>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
|
||||
<h2 style={{ margin: 0 }}>操作日志</h2>
|
||||
<Space wrap>
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="筛选模块"
|
||||
style={{ width: 140 }}
|
||||
value={filterModule}
|
||||
onChange={(v) => { setFilterModule(v); setPage(1); }}
|
||||
options={['认证', '学生', '宿舍', '入住', '费用', '账单', '账号'].map((m) => ({ value: m, label: m }))}
|
||||
/>
|
||||
<RangePicker
|
||||
placeholder={['开始日期', '结束日期']}
|
||||
format="YYYY-MM-DD"
|
||||
onChange={(dates) => {
|
||||
if (dates) setDateRange([dates[0]!.format('YYYY-MM-DD'), dates[1]!.format('YYYY-MM-DD')]);
|
||||
else setDateRange(null);
|
||||
setPage(1);
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
</div>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
scroll={{ x: 1000 }}
|
||||
pagination={{ current: page, total, pageSize: 20, onChange: setPage, showTotal: (t) => `共 ${t} 条` }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OperationLogsPage;
|
||||
77
apps/admin/src/pages/Permissions/index.tsx
Normal file
77
apps/admin/src/pages/Permissions/index.tsx
Normal file
@@ -0,0 +1,77 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Card, Tag, Input, Space, Spin } from 'antd';
|
||||
import api from '../../api';
|
||||
|
||||
interface PermissionItem {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
group: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
const PermissionsPage: React.FC = () => {
|
||||
const [permTree, setPermTree] = useState<{ group: string; permissions: PermissionItem[] }[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
const groupNames: Record<string, string> = {
|
||||
dashboard: '数据面板', student: '学生管理', room: '宿舍管理', occupancy: '入住管理',
|
||||
expense: '费用管理', bill: '账单管理', deposit: '押金管理',
|
||||
classroom: '教室管理', tenant: '租赁方', rental: '租赁订单',
|
||||
log: '操作日志', user: '用户管理', role: '角色管理',
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
api.get('/rbac/permissions/tree')
|
||||
.then((res: any) => setPermTree(res))
|
||||
.catch(console.error)
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const filteredTree = search
|
||||
? permTree.map(g => ({
|
||||
...g,
|
||||
permissions: g.permissions.filter(p =>
|
||||
p.name.includes(search) || p.code.includes(search)
|
||||
),
|
||||
})).filter(g => g.permissions.length > 0)
|
||||
: permTree;
|
||||
|
||||
if (loading) return <Spin style={{ display: 'block', margin: '40px auto' }} />;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<h2 style={{ margin: 0 }}>权限一览</h2>
|
||||
<Input.Search
|
||||
placeholder="搜索权限名称或编码"
|
||||
allowClear
|
||||
style={{ width: 280 }}
|
||||
onSearch={setSearch}
|
||||
onChange={e => !e.target.value && setSearch('')}
|
||||
/>
|
||||
</div>
|
||||
<Space direction="vertical" style={{ width: '100%' }} size={16}>
|
||||
{filteredTree.map(group => (
|
||||
<Card
|
||||
key={group.group}
|
||||
title={<span style={{ fontWeight: 600 }}>{groupNames[group.group] || group.group} ({group.permissions.length})</span>}
|
||||
size="small"
|
||||
>
|
||||
<Space wrap>
|
||||
{group.permissions.map(p => (
|
||||
<Tag key={p.id} color="blue" style={{ marginBottom: 8 }}>
|
||||
{p.name} <Tag color="geekblue" style={{ marginLeft: 4 }}>{p.code}</Tag>
|
||||
</Tag>
|
||||
))}
|
||||
</Space>
|
||||
</Card>
|
||||
))}
|
||||
</Space>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PermissionsPage;
|
||||
206
apps/admin/src/pages/Roles/index.tsx
Normal file
206
apps/admin/src/pages/Roles/index.tsx
Normal file
@@ -0,0 +1,206 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Table, Button, Modal, Form, Input, Space, Tag, Popconfirm, message, Card, Checkbox } from 'antd';
|
||||
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
|
||||
interface PermissionItem {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
group: string;
|
||||
}
|
||||
|
||||
interface RoleItem {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
isSystem: boolean;
|
||||
status: number;
|
||||
permissions: PermissionItem[];
|
||||
}
|
||||
|
||||
const RolesPage: React.FC = () => {
|
||||
const [data, setData] = useState<RoleItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<RoleItem | null>(null);
|
||||
const [allPerms, setAllPerms] = useState<{ group: string; permissions: PermissionItem[] }[]>([]);
|
||||
const [form] = Form.useForm();
|
||||
const [selectedPermIds, setSelectedPermIds] = useState<number[]>([]);
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [roles, permTree] = await Promise.all([
|
||||
api.get('/rbac/roles') as Promise<RoleItem[]>,
|
||||
api.get('/rbac/permissions/tree') as Promise<{ group: string; permissions: PermissionItem[] }[]>,
|
||||
]);
|
||||
setData(roles);
|
||||
setAllPerms(permTree);
|
||||
} catch (e) { console.error(e); }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => { fetchData(); }, []);
|
||||
|
||||
const handleAdd = () => {
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
setSelectedPermIds([]);
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const handleEdit = (record: RoleItem) => {
|
||||
setEditing(record);
|
||||
form.setFieldsValue({ name: record.name, description: record.description });
|
||||
setSelectedPermIds(record.permissions.map(p => p.id));
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const values = await form.validateFields();
|
||||
try {
|
||||
if (editing) {
|
||||
await api.put(`/rbac/roles/${editing.id}`, { name: values.name, description: values.description, permissionIds: selectedPermIds });
|
||||
message.success('角色更新成功');
|
||||
} else {
|
||||
await api.post('/rbac/roles', { name: values.name, description: values.description, permissionIds: selectedPermIds });
|
||||
message.success('角色创建成功');
|
||||
}
|
||||
setModalOpen(false);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/rbac/roles/${id}`);
|
||||
message.success('角色已删除');
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e.message || '删除失败'); }
|
||||
};
|
||||
|
||||
const groupNames: Record<string, string> = {
|
||||
dashboard: '数据面板', student: '学生管理', room: '宿舍管理', occupancy: '入住管理',
|
||||
expense: '费用管理', bill: '账单管理', deposit: '押金管理',
|
||||
classroom: '教室管理', tenant: '租赁方', rental: '租赁订单',
|
||||
log: '操作日志', user: '用户管理', role: '角色管理',
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{ title: 'ID', dataIndex: 'id', width: 60 },
|
||||
{ title: '名称', dataIndex: 'name', width: 120 },
|
||||
{ title: '描述', dataIndex: 'description', width: 200, ellipsis: true },
|
||||
{
|
||||
title: '权限标签', dataIndex: 'permissions', width: 150, ellipsis: true,
|
||||
render: (perms: PermissionItem[]) => perms?.length > 0
|
||||
? <Tag color="blue">{perms.length} 个权限</Tag>
|
||||
: <Tag color="default">无权限</Tag>,
|
||||
},
|
||||
{
|
||||
title: '系统', dataIndex: 'isSystem', width: 70,
|
||||
render: (v: boolean) => v ? <Tag color="orange">系统</Tag> : null,
|
||||
},
|
||||
{
|
||||
title: '操作', width: 160, 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 && (
|
||||
<PermissionButton permission="role:delete">
|
||||
<Popconfirm title="确认删除该角色?" onConfirm={() => handleDelete(record.id)}>
|
||||
<Button type="link" size="small" danger icon={<DeleteOutlined />}>删除</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const handleGroupCheckAll = (group: string, checked: boolean) => {
|
||||
const groupPermIds = allPerms.find(g => g.group === group)?.permissions.map(p => p.id) || [];
|
||||
if (checked) {
|
||||
setSelectedPermIds(prev => [...new Set([...prev, ...groupPermIds])]);
|
||||
} else {
|
||||
setSelectedPermIds(prev => prev.filter(id => !groupPermIds.includes(id)));
|
||||
}
|
||||
};
|
||||
|
||||
const isGroupAllChecked = (group: string) => {
|
||||
const groupPermIds = allPerms.find(g => g.group === group)?.permissions.map(p => p.id) || [];
|
||||
return groupPermIds.length > 0 && groupPermIds.every(id => selectedPermIds.includes(id));
|
||||
};
|
||||
|
||||
const isGroupIndeterminate = (group: string) => {
|
||||
const groupPermIds = allPerms.find(g => g.group === group)?.permissions.map(p => p.id) || [];
|
||||
const checkedCount = groupPermIds.filter(id => selectedPermIds.includes(id)).length;
|
||||
return checkedCount > 0 && checkedCount < groupPermIds.length;
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<h2 style={{ margin: 0 }}>角色管理</h2>
|
||||
<PermissionButton permission="role:create" type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
|
||||
新增角色
|
||||
</PermissionButton>
|
||||
</div>
|
||||
<Table columns={columns} dataSource={data} rowKey="id" loading={loading} scroll={{ x: 800 }} pagination={false} />
|
||||
|
||||
<Modal
|
||||
title={editing ? '编辑角色' : '新增角色'}
|
||||
open={modalOpen}
|
||||
onOk={handleSubmit}
|
||||
onCancel={() => setModalOpen(false)}
|
||||
width={700}
|
||||
destroyOnClose
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="name" label="角色名称" rules={[{ required: true, message: '请输入角色名称' }]}>
|
||||
<Input disabled={editing?.isSystem} />
|
||||
</Form.Item>
|
||||
<Form.Item name="description" label="角色描述">
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
<Form.Item label="权限分配">
|
||||
<div style={{ maxHeight: 400, overflow: 'auto' }}>
|
||||
{allPerms.map(group => (
|
||||
<Card
|
||||
key={group.group}
|
||||
size="small"
|
||||
title={
|
||||
<Checkbox
|
||||
checked={isGroupAllChecked(group.group)}
|
||||
indeterminate={isGroupIndeterminate(group.group)}
|
||||
onChange={e => handleGroupCheckAll(group.group, e.target.checked)}
|
||||
>
|
||||
{groupNames[group.group] || group.group}
|
||||
</Checkbox>
|
||||
}
|
||||
style={{ marginBottom: 8 }}
|
||||
>
|
||||
<Checkbox.Group
|
||||
value={selectedPermIds}
|
||||
onChange={vals => setSelectedPermIds(vals as number[])}
|
||||
>
|
||||
<Space wrap>
|
||||
{group.permissions.map(p => (
|
||||
<Checkbox key={p.id} value={p.id}>{p.name}</Checkbox>
|
||||
))}
|
||||
</Space>
|
||||
</Checkbox.Group>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default RolesPage;
|
||||
179
apps/admin/src/pages/RoomVisual/index.tsx
Normal file
179
apps/admin/src/pages/RoomVisual/index.tsx
Normal file
@@ -0,0 +1,179 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Row, Col, Card, Tag, Select, Statistic, Modal, Spin, Badge, Tooltip } from 'antd';
|
||||
import { HomeOutlined, UserOutlined, CalendarOutlined, BankOutlined } from '@ant-design/icons';
|
||||
import api from '../../api';
|
||||
|
||||
const RoomVisualPage: React.FC = () => {
|
||||
const [data, setData] = useState<any>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [selectedBuilding, setSelectedBuilding] = useState<string>('all');
|
||||
const [detailRoom, setDetailRoom] = useState<any>(null);
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res: any = await api.get('/rooms/visual');
|
||||
setData(res);
|
||||
} catch (e) { console.error(e); }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => { fetchData(); }, []);
|
||||
|
||||
if (loading || !data) return <Spin size="large" style={{ display: 'block', margin: '100px auto' }} />;
|
||||
|
||||
const rooms = selectedBuilding === 'all'
|
||||
? data.rooms
|
||||
: data.rooms.filter((r: any) => r.building === selectedBuilding);
|
||||
|
||||
const totalRooms = rooms.length;
|
||||
const emptyRooms = rooms.filter((r: any) => r.currentCount === 0 && r.status !== 'maintenance').length;
|
||||
const availableBeds = rooms.reduce((sum: number, r: any) => r.status !== 'maintenance' ? sum + (r.capacity - r.currentCount) : sum, 0);
|
||||
const fullRooms = rooms.filter((r: any) => r.currentCount >= r.capacity).length;
|
||||
|
||||
const getCardStyle = (room: any): React.CSSProperties => {
|
||||
if (room.status === 'maintenance') return { background: '#f5f5f5', borderColor: '#d9d9d9' };
|
||||
if (room.currentCount === 0) return { background: '#f6ffed', borderColor: '#b7eb8f' };
|
||||
if (room.currentCount >= room.capacity) return { background: '#fff2f0', borderColor: '#ffccc7' };
|
||||
return { background: '#e6f4ff', borderColor: '#91caff' };
|
||||
};
|
||||
|
||||
const getStatusLabel = (room: any) => {
|
||||
if (room.status === 'maintenance') return <Tag color="default">维修中</Tag>;
|
||||
if (room.currentCount === 0) return <Tag color="success">空闲</Tag>;
|
||||
if (room.currentCount >= room.capacity) return <Tag color="error">满员</Tag>;
|
||||
return <Tag color="processing">部分入住</Tag>;
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
|
||||
<h2 style={{ margin: 0 }}>宿舍总览</h2>
|
||||
<Select
|
||||
value={selectedBuilding}
|
||||
onChange={setSelectedBuilding}
|
||||
style={{ width: 160 }}
|
||||
options={[
|
||||
{ value: 'all', label: '全部楼栋' },
|
||||
...data.buildings.map((b: string) => ({ value: b, label: b })),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 统计栏 */}
|
||||
<Row gutter={[12, 12]} style={{ marginBottom: 20 }}>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small"><Statistic title="宿舍总数" value={totalRooms} prefix={<HomeOutlined />} /></Card>
|
||||
</Col>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small"><Statistic title="空闲房间" value={emptyRooms} valueStyle={{ color: '#34C759' }} /></Card>
|
||||
</Col>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small"><Statistic title="可安排床位" value={availableBeds} valueStyle={{ color: '#007AFF' }} /></Card>
|
||||
</Col>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small"><Statistic title="满员房间" value={fullRooms} valueStyle={{ color: '#FF3B30' }} /></Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* 房态网格 */}
|
||||
<Row gutter={[12, 12]}>
|
||||
{rooms.map((room: any) => (
|
||||
<Col xs={12} sm={8} md={6} lg={4} key={room.id}>
|
||||
<Card
|
||||
size="small"
|
||||
hoverable
|
||||
style={{ ...getCardStyle(room), borderRadius: 12, borderWidth: 2, cursor: 'pointer', height: '100%' }}
|
||||
onClick={() => setDetailRoom(room)}
|
||||
>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
|
||||
<span style={{ fontSize: 16, fontWeight: 600, color: '#1d1d1f' }}>{room.roomNumber}</span>
|
||||
{getStatusLabel(room)}
|
||||
</div>
|
||||
<div style={{ color: '#86868b', fontSize: 12, marginBottom: 6 }}>
|
||||
{room.building && <span>{room.building} </span>}
|
||||
{room.floor && <span>{room.floor}F</span>}
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 4, marginBottom: 8 }}>
|
||||
<Badge
|
||||
count={`${room.currentCount}/${room.capacity}`}
|
||||
showZero
|
||||
style={{
|
||||
backgroundColor: room.currentCount >= room.capacity ? '#FF3B30' : room.currentCount > 0 ? '#007AFF' : '#34C759',
|
||||
fontSize: 11,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{room.orgLabel && (
|
||||
<div style={{ marginBottom: 6 }}>
|
||||
<Tag color="purple" style={{ fontSize: 11 }} icon={<BankOutlined />}>{room.orgLabel}</Tag>
|
||||
</div>
|
||||
)}
|
||||
{room.occupants.length > 0 && (
|
||||
<div 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: 11 }} icon={<UserOutlined />}>
|
||||
{o.studentName}
|
||||
</Tag>
|
||||
</Tooltip>
|
||||
))}
|
||||
{room.occupants.length > 4 && <Tag>+{room.occupants.length - 4}</Tag>}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</Col>
|
||||
))}
|
||||
</Row>
|
||||
|
||||
{/* 详情弹窗 */}
|
||||
<Modal
|
||||
title={`宿舍 ${detailRoom?.roomNumber} 详情`}
|
||||
open={!!detailRoom}
|
||||
onCancel={() => setDetailRoom(null)}
|
||||
footer={null}
|
||||
width={500}
|
||||
>
|
||||
{detailRoom && (
|
||||
<div>
|
||||
<Row gutter={16} style={{ marginBottom: 16 }}>
|
||||
<Col span={8}><Statistic title="额定人数" value={detailRoom.capacity} /></Col>
|
||||
<Col span={8}><Statistic title="当前入住" value={detailRoom.currentCount} /></Col>
|
||||
<Col span={8}><Statistic title="剩余床位" value={Math.max(0, detailRoom.capacity - detailRoom.currentCount)} /></Col>
|
||||
</Row>
|
||||
<div style={{ marginBottom: 8, fontWeight: 500 }}>
|
||||
位置:{detailRoom.building || '-'} {detailRoom.floor ? `${detailRoom.floor}F` : ''}
|
||||
</div>
|
||||
<div style={{ marginBottom: 16 }}>{getStatusLabel(detailRoom)}</div>
|
||||
{detailRoom.occupants.length > 0 ? (
|
||||
<div>
|
||||
<h4 style={{ marginBottom: 8 }}>当前住户</h4>
|
||||
{detailRoom.occupants.map((o: any) => (
|
||||
<Card key={o.studentId} size="small" style={{ marginBottom: 8, borderRadius: 8 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<div>
|
||||
<UserOutlined style={{ marginRight: 6 }} />
|
||||
<strong>{o.studentName}</strong>
|
||||
{o.organization && <Tag color="purple" style={{ marginLeft: 6, fontSize: 11 }}>{o.organization}</Tag>}
|
||||
</div>
|
||||
<Tag color="blue">{o.days} 天</Tag>
|
||||
</div>
|
||||
<div style={{ color: '#86868b', fontSize: 12, marginTop: 4 }}>
|
||||
<CalendarOutlined style={{ marginRight: 4 }} />
|
||||
入住:{o.checkInDate} | 计费起:{o.billingStartDate}
|
||||
{o.supervisor && <span style={{ marginLeft: 8 }}>负责人:{o.supervisor}</span>}
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ textAlign: 'center', padding: 24, color: '#86868b' }}>当前无住户,可安排入住</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default RoomVisualPage;
|
||||
302
apps/admin/src/pages/Rooms/index.tsx
Normal file
302
apps/admin/src/pages/Rooms/index.tsx
Normal file
@@ -0,0 +1,302 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { Table, Button, Modal, Form, Input, InputNumber, Select, Space, message, Tag, Popconfirm, Badge, Upload } from 'antd';
|
||||
import { PlusOutlined, UploadOutlined, DownloadOutlined, UndoOutlined, InboxOutlined, SearchOutlined, ExportOutlined, DeleteOutlined } from '@ant-design/icons';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
available: { text: '可入住', color: 'green' },
|
||||
full: { text: '已满', color: 'red' },
|
||||
maintenance: { text: '维修中', color: 'orange' },
|
||||
archived: { text: '已归档', color: '#999' },
|
||||
};
|
||||
|
||||
const RoomsPage: React.FC = () => {
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<any>(null);
|
||||
const [detailModal, setDetailModal] = useState<any>(null);
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
const [archivedCount, setArchivedCount] = useState(0);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [filterBuilding, setFilterBuilding] = useState<string | undefined>(undefined);
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
|
||||
const [form] = Form.useForm();
|
||||
|
||||
const handleBatchDelete = async () => {
|
||||
try {
|
||||
const res: any = await api.post('/rooms/batch-delete', { ids: selectedRowKeys });
|
||||
message.success(res?.message || `已批量归档 ${selectedRowKeys.length} 间`);
|
||||
setSelectedRowKeys([]);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '批量归档失败'); }
|
||||
};
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params: any = { includeArchived: 'true' };
|
||||
const res: any = await api.get('/rooms/overview', { params });
|
||||
const archived = res.filter((r: any) => r.status === 'archived');
|
||||
setArchivedCount(archived.length);
|
||||
const filtered = showArchived ? res : res.filter((r: any) => r.status !== 'archived');
|
||||
setData(filtered);
|
||||
} catch (e) { console.error(e); }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => { fetchData(); }, [showArchived]);
|
||||
|
||||
// 获取楼栋列表用于筛选
|
||||
const buildings = useMemo(() => {
|
||||
const set = new Set(data.map((r: any) => r.building).filter(Boolean));
|
||||
return [...set].sort();
|
||||
}, [data]);
|
||||
|
||||
// 前端搜索和楼栋筛选
|
||||
const filteredData = useMemo(() => {
|
||||
let result = data;
|
||||
if (searchText) {
|
||||
const keyword = searchText.toLowerCase();
|
||||
result = result.filter((r: any) => r.roomNumber?.toLowerCase().includes(keyword));
|
||||
}
|
||||
if (filterBuilding) {
|
||||
result = result.filter((r: any) => r.building === filterBuilding);
|
||||
}
|
||||
return result;
|
||||
}, [data, searchText, filterBuilding]);
|
||||
|
||||
const handleSave = async () => {
|
||||
const values = await form.validateFields();
|
||||
try {
|
||||
if (editing) {
|
||||
await api.put(`/rooms/${editing.id}`, values);
|
||||
message.success('更新成功');
|
||||
} else {
|
||||
await api.post('/rooms', values);
|
||||
message.success('创建成功');
|
||||
}
|
||||
setModalOpen(false);
|
||||
form.resetFields();
|
||||
setEditing(null);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const showDetail = async (id: number) => {
|
||||
try {
|
||||
const res = await api.get(`/rooms/${id}`);
|
||||
setDetailModal(res);
|
||||
} catch (e) { console.error(e); }
|
||||
};
|
||||
|
||||
const handleArchive = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/rooms/${id}`);
|
||||
message.success('已归档');
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '归档失败'); }
|
||||
};
|
||||
|
||||
const handleRestore = async (id: number) => {
|
||||
try {
|
||||
await api.put(`/rooms/${id}/restore`);
|
||||
message.success('已恢复');
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '恢复失败'); }
|
||||
};
|
||||
|
||||
const handleDownloadTemplate = () => {
|
||||
const baseURL = import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
|
||||
const token = localStorage.getItem('token');
|
||||
fetch(`${baseURL}/rooms/template`, { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then(res => res.blob())
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = '宿舍导入模板.xlsx';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch(() => message.error('下载失败'));
|
||||
};
|
||||
|
||||
const handleExport = () => {
|
||||
const baseURL = import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
|
||||
const token = localStorage.getItem('token');
|
||||
const params = showArchived ? '?includeArchived=true' : '';
|
||||
fetch(`${baseURL}/rooms/export${params}`, { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then(res => res.blob())
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = '宿舍列表.xlsx';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch(() => message.error('导出失败'));
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{ title: '房间号', dataIndex: 'roomNumber', sorter: (a: any, b: any) => a.roomNumber.localeCompare(b.roomNumber) },
|
||||
{ title: '楼栋', dataIndex: 'building' },
|
||||
{ title: '楼层', dataIndex: 'floor' },
|
||||
{ title: '类型', dataIndex: 'roomType', render: (v: any) => v || '-' },
|
||||
{ title: '额定人数', dataIndex: 'capacity' },
|
||||
{
|
||||
title: '当前入住',
|
||||
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: 'gender', width: 60, render: (v: any) => v ? <Tag color={v === '男' ? 'blue' : 'pink'}>{v}</Tag> : '-' },
|
||||
{
|
||||
title: '状态', dataIndex: 'status',
|
||||
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '操作', width: 220,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
{record.status === 'archived' ? (
|
||||
<PermissionButton permission="room:edit">
|
||||
<Popconfirm title="确定恢复此宿舍?恢复后将重新出现在宿舍总览中。" onConfirm={() => handleRestore(record.id)} okText="恢复" cancelText="取消">
|
||||
<Button size="small" icon={<UndoOutlined />} type="link">恢复</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
) : (
|
||||
<>
|
||||
<PermissionButton permission="room:view" size="small" type="link" onClick={() => showDetail(record.id)}>查看住户</PermissionButton>
|
||||
<PermissionButton permission="room:edit" size="small" onClick={() => { setEditing(record); form.setFieldsValue(record); setModalOpen(true); }}>编辑</PermissionButton>
|
||||
<PermissionButton permission="room:delete">
|
||||
<Popconfirm title="归档后不会删除数据,可随时恢复。有在住人员将无法归档。" onConfirm={() => handleArchive(record.id)} okText="归档" cancelText="取消">
|
||||
<Button size="small" icon={<InboxOutlined />}>归档</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
|
||||
<Space wrap>
|
||||
<h3 style={{ margin: 0 }}>宿舍管理</h3>
|
||||
<Input.Search
|
||||
placeholder="搜索房间号"
|
||||
onSearch={setSearchText}
|
||||
allowClear
|
||||
style={{ width: 160 }}
|
||||
prefix={<SearchOutlined />}
|
||||
/>
|
||||
<Select
|
||||
placeholder="筛选楼栋"
|
||||
allowClear
|
||||
style={{ width: 120 }}
|
||||
onChange={(v) => setFilterBuilding(v)}
|
||||
options={buildings.map((b) => ({ value: b, label: b }))}
|
||||
/>
|
||||
<Button
|
||||
type={showArchived ? 'primary' : 'default'}
|
||||
onClick={() => setShowArchived(!showArchived)}
|
||||
>
|
||||
{showArchived ? '隐藏已归档' : `显示已归档${archivedCount > 0 ? ` (${archivedCount})` : ''}`}
|
||||
</Button>
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<PermissionButton permission="room:delete">
|
||||
<Popconfirm title={`确定批量归档选中的 ${selectedRowKeys.length} 间宿舍?(有在住人员的会跳过)`} onConfirm={handleBatchDelete} okText="归档" cancelText="取消" disabled={selectedRowKeys.length === 0}>
|
||||
<Button danger icon={<DeleteOutlined />} disabled={selectedRowKeys.length === 0}>批量归档</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="room:create" type="primary" icon={<PlusOutlined />} onClick={() => { setEditing(null); form.resetFields(); setModalOpen(true); }}>
|
||||
添加宿舍
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="room:create">
|
||||
<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('/rooms/import', formData, { headers: { 'Content-Type': 'multipart/form-data' } });
|
||||
message.success(res.message);
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '导入失败'); onError?.(e); }
|
||||
}}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入Excel</Button>
|
||||
</Upload>
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="room:view" icon={<DownloadOutlined />} onClick={handleDownloadTemplate}>下载模板</PermissionButton>
|
||||
<PermissionButton permission="room:view" icon={<ExportOutlined />} onClick={handleExport}>导出列表</PermissionButton>
|
||||
</Space>
|
||||
</div>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={filteredData}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
pagination={{ pageSize: 20, showTotal: (total) => `共 ${total} 间` }}
|
||||
rowClassName={(record) => record.status === 'archived' ? 'archived-row' : ''}
|
||||
rowSelection={{
|
||||
selectedRowKeys,
|
||||
onChange: (keys) => setSelectedRowKeys(keys as number[]),
|
||||
getCheckboxProps: (record: any) => ({ disabled: record.status === 'archived' }),
|
||||
}}
|
||||
/>
|
||||
<style>{`.archived-row { opacity: 0.6; background: #fafafa !important; }`}</style>
|
||||
|
||||
<Modal title={editing ? '编辑宿舍' : '添加宿舍'} open={modalOpen} onOk={handleSave} onCancel={() => { setModalOpen(false); setEditing(null); }} okText="保存">
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="roomNumber" label="房间号" rules={[{ required: true }]}><Input placeholder="如:4-102(自动解析楼栋楼层)" /></Form.Item>
|
||||
<Form.Item name="building" label="楼栋"><Input placeholder="如:4号楼(留空自动解析)" /></Form.Item>
|
||||
<Form.Item name="floor" label="楼层"><InputNumber min={1} style={{ width: '100%' }} /></Form.Item>
|
||||
<Form.Item name="capacity" label="额定人数" rules={[{ required: true }]}><InputNumber min={1} max={20} style={{ width: '100%' }} /></Form.Item>
|
||||
<Form.Item name="roomType" label="宿舍类型">
|
||||
<Select allowClear options={[
|
||||
{ value: '四人间', label: '四人间' },
|
||||
{ value: '单人间', label: '单人间' },
|
||||
{ value: '家庭房', label: '家庭房' },
|
||||
{ value: '爆改房', label: '爆改房' },
|
||||
]} placeholder="留空自动解析" />
|
||||
</Form.Item>
|
||||
{editing && (
|
||||
<Form.Item name="status" label="状态">
|
||||
<Select options={[
|
||||
{ value: 'available', label: '可入住' },
|
||||
{ value: 'full', label: '已满' },
|
||||
{ value: 'maintenance', label: '维修中' },
|
||||
]} />
|
||||
</Form.Item>
|
||||
)}
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal title={`宿舍 ${detailModal?.roomNumber} 当前住户`} open={!!detailModal} onCancel={() => setDetailModal(null)} footer={null} width={600}>
|
||||
{detailModal?.currentOccupants?.length > 0 ? (
|
||||
<Table
|
||||
dataSource={detailModal.currentOccupants}
|
||||
rowKey="id"
|
||||
pagination={false}
|
||||
columns={[
|
||||
{ title: '学生', render: (_: any, r: any) => r.student?.name },
|
||||
{ title: '入住日期', dataIndex: 'checkInDate' },
|
||||
{ title: '计费起始', dataIndex: 'billingStartDate' },
|
||||
]}
|
||||
/>
|
||||
) : (
|
||||
<div style={{ textAlign: 'center', padding: 24, color: '#999' }}>暂无住户</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default RoomsPage;
|
||||
259
apps/admin/src/pages/Students/index.tsx
Normal file
259
apps/admin/src/pages/Students/index.tsx
Normal file
@@ -0,0 +1,259 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Table, Button, Modal, Form, Input, Select, Space, message, Tag, Popconfirm, Upload } from 'antd';
|
||||
import { PlusOutlined, UploadOutlined, DownloadOutlined, UndoOutlined, InboxOutlined, ExportOutlined, DeleteOutlined } from '@ant-design/icons';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
active: { text: '在读', color: 'green' },
|
||||
graduated: { text: '已毕业', color: 'blue' },
|
||||
withdrawn: { text: '已退训', color: 'red' },
|
||||
archived: { text: '已归档', color: '#999' },
|
||||
};
|
||||
|
||||
const StudentsPage: React.FC = () => {
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<any>(null);
|
||||
const [searchName, setSearchName] = useState('');
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
const [archivedCount, setArchivedCount] = useState(0);
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
|
||||
const [form] = Form.useForm();
|
||||
|
||||
const handleBatchDelete = async () => {
|
||||
try {
|
||||
const res: any = await api.post('/students/batch-delete', { ids: selectedRowKeys });
|
||||
message.success(res?.message || `已批量归档 ${selectedRowKeys.length} 人`);
|
||||
setSelectedRowKeys([]);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '批量归档失败'); }
|
||||
};
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params: any = { name: searchName || undefined, includeArchived: 'true' };
|
||||
const res: any = await api.get('/students', { params });
|
||||
const archived = res.filter((r: any) => r.status === 'archived');
|
||||
setArchivedCount(archived.length);
|
||||
const filtered = showArchived ? res : res.filter((r: any) => r.status !== 'archived');
|
||||
setData(filtered);
|
||||
} catch (e) { console.error(e); }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => { fetchData(); }, [searchName, showArchived]);
|
||||
|
||||
const handleSave = async () => {
|
||||
const values = await form.validateFields();
|
||||
try {
|
||||
if (editing) {
|
||||
await api.put(`/students/${editing.id}`, values);
|
||||
message.success('更新成功');
|
||||
} else {
|
||||
await api.post('/students', values);
|
||||
message.success('创建成功');
|
||||
}
|
||||
setModalOpen(false);
|
||||
form.resetFields();
|
||||
setEditing(null);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const handleArchive = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/students/${id}`);
|
||||
message.success('已归档');
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '归档失败'); }
|
||||
};
|
||||
|
||||
const handleRestore = async (id: number) => {
|
||||
try {
|
||||
await api.put(`/students/${id}/restore`);
|
||||
message.success('已恢复');
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '恢复失败'); }
|
||||
};
|
||||
|
||||
const handleDownloadTemplate = () => {
|
||||
const baseURL = import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
|
||||
const token = localStorage.getItem('token');
|
||||
fetch(`${baseURL}/students/template`, { headers: { Authorization: `Bearer ${token}` } })
|
||||
.then(res => res.blob())
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = '学生导入模板.xlsx';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch(() => message.error('下载失败'));
|
||||
};
|
||||
|
||||
const handleExport = () => {
|
||||
const baseURL = import.meta.env.PROD ? '/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}` } })
|
||||
.then(res => res.blob())
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = '学生名单.xlsx';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch(() => message.error('导出失败'));
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{ title: 'ID', dataIndex: 'id', width: 60 },
|
||||
{ title: '姓名', dataIndex: 'name' },
|
||||
{ title: '性别', dataIndex: 'gender', width: 60 },
|
||||
{ title: '电话', dataIndex: 'phone' },
|
||||
{ title: '学号/身份证', dataIndex: 'idNumber' },
|
||||
{ title: '民族', dataIndex: 'ethnicity', width: 80 },
|
||||
{ title: '紧急联系人', dataIndex: 'emergencyContact' },
|
||||
{ title: '紧急联系人电话', dataIndex: 'emergencyPhone' },
|
||||
{ title: '所属机构', dataIndex: 'organization', render: (v: string) => v ? <Tag color="purple">{v}</Tag> : '-' },
|
||||
{ title: '负责人', dataIndex: 'supervisor' },
|
||||
{
|
||||
title: '状态', dataIndex: 'status',
|
||||
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '操作', width: 180,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
{record.status === 'archived' ? (
|
||||
<PermissionButton permission="student:edit">
|
||||
<Popconfirm title="确定恢复此学生?恢复后将重新出现在学生列表中。" onConfirm={() => handleRestore(record.id)} okText="恢复" cancelText="取消">
|
||||
<Button size="small" icon={<UndoOutlined />} type="link">恢复</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
) : (
|
||||
<>
|
||||
<PermissionButton permission="student:edit" size="small" onClick={() => { setEditing(record); form.setFieldsValue(record); setModalOpen(true); }}>编辑</PermissionButton>
|
||||
<PermissionButton permission="student:delete">
|
||||
<Popconfirm title="归档后不会删除数据,可随时恢复。确定归档?" onConfirm={() => handleArchive(record.id)} okText="归档" cancelText="取消">
|
||||
<Button size="small" icon={<InboxOutlined />}>归档</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
|
||||
<Space>
|
||||
<Input.Search placeholder="搜索学生姓名" onSearch={setSearchName} allowClear style={{ width: 250 }} />
|
||||
<Button type={showArchived ? 'primary' : 'default'} onClick={() => setShowArchived(!showArchived)}>
|
||||
{showArchived ? '隐藏已归档' : `显示已归档${archivedCount > 0 ? ` (${archivedCount})` : ''}`}
|
||||
</Button>
|
||||
</Space>
|
||||
<Space>
|
||||
<PermissionButton permission="student:delete">
|
||||
<Popconfirm title={`确定批量归档选中的 ${selectedRowKeys.length} 名学生?(数据保留,可恢复)`} onConfirm={handleBatchDelete} okText="归档" cancelText="取消" disabled={selectedRowKeys.length === 0}>
|
||||
<Button danger icon={<DeleteOutlined />} disabled={selectedRowKeys.length === 0}>批量归档</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="student:create" type="primary" icon={<PlusOutlined />} onClick={() => { setEditing(null); form.resetFields(); setModalOpen(true); }}>
|
||||
添加学生
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="student:import">
|
||||
<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); }
|
||||
}}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入Excel</Button>
|
||||
</Upload>
|
||||
</PermissionButton>
|
||||
<PermissionButton permission="student:view" icon={<DownloadOutlined />} onClick={handleDownloadTemplate}>下载模板</PermissionButton>
|
||||
<PermissionButton permission="student:export" icon={<ExportOutlined />} onClick={handleExport}>导出名单</PermissionButton>
|
||||
</Space>
|
||||
</div>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
pagination={{ pageSize: 15, showTotal: (total) => `共 ${total} 人` }}
|
||||
rowClassName={(record: any) => record.status === 'archived' ? 'archived-row' : ''}
|
||||
rowSelection={{
|
||||
selectedRowKeys,
|
||||
onChange: (keys) => setSelectedRowKeys(keys as number[]),
|
||||
getCheckboxProps: (record: any) => ({ disabled: record.status === 'archived' }),
|
||||
}}
|
||||
/>
|
||||
<style>{`.archived-row { opacity: 0.6; background: #fafafa !important; }`}</style>
|
||||
<Modal
|
||||
title={editing ? '编辑学生' : '添加学生'}
|
||||
open={modalOpen}
|
||||
onOk={handleSave}
|
||||
onCancel={() => { setModalOpen(false); setEditing(null); }}
|
||||
okText="保存"
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="name" label="姓名" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="gender" label="性别">
|
||||
<Select allowClear options={[{ value: '男', label: '男' }, { value: '女', label: '女' }]} />
|
||||
</Form.Item>
|
||||
<Form.Item name="phone" label="电话">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="idNumber" label="学号/身份证">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="ethnicity" label="民族">
|
||||
<Input placeholder="如:汉族" />
|
||||
</Form.Item>
|
||||
<Form.Item name="emergencyContact" label="紧急联系人">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="emergencyPhone" label="紧急联系人电话">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="organization" label="所属机构" tooltip="外部合作公司/机构名称,留空表示本机构">
|
||||
<Input placeholder="如:XXX教育科技公司" />
|
||||
</Form.Item>
|
||||
<Form.Item name="supervisor" label="负责人/班主任">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
{editing && (
|
||||
<Form.Item name="status" label="状态">
|
||||
<Select options={[
|
||||
{ value: 'active', label: '在读' },
|
||||
{ value: 'graduated', label: '已毕业' },
|
||||
{ value: 'withdrawn', label: '已退训' },
|
||||
]} />
|
||||
</Form.Item>
|
||||
)}
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default StudentsPage;
|
||||
131
apps/admin/src/pages/Tenants/index.tsx
Normal file
131
apps/admin/src/pages/Tenants/index.tsx
Normal file
@@ -0,0 +1,131 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { Table, Button, Modal, Form, Input, Space, message, Tag, Popconfirm } from 'antd';
|
||||
import { PlusOutlined, InboxOutlined } from '@ant-design/icons';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
|
||||
const PRESET_COLORS = [
|
||||
'#ff7875', '#ffa940', '#ffc53d', '#73d13d', '#36cfc9',
|
||||
'#40a9ff', '#597ef7', '#9254de', '#f759ab', '#8c8c8c',
|
||||
];
|
||||
|
||||
const TenantsPage: React.FC = () => {
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<any>(null);
|
||||
const [form] = Form.useForm();
|
||||
const [searchText, setSearchText] = useState('');
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
if (!searchText) return data;
|
||||
const s = searchText.toLowerCase();
|
||||
return data.filter((d: any) => d.name?.toLowerCase().includes(s) || d.contact?.toLowerCase().includes(s));
|
||||
}, [data, searchText]);
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res: any = await api.get('/tenants');
|
||||
setData(res);
|
||||
} catch (e) { console.error(e); }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => { fetchData(); }, []);
|
||||
|
||||
const handleSave = async () => {
|
||||
const values = await form.validateFields();
|
||||
try {
|
||||
if (editing) {
|
||||
await api.put(`/tenants/${editing.id}`, values);
|
||||
message.success('更新成功');
|
||||
} else {
|
||||
await api.post('/tenants', values);
|
||||
message.success('创建成功');
|
||||
}
|
||||
setModalOpen(false);
|
||||
form.resetFields();
|
||||
setEditing(null);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const handleArchive = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/tenants/${id}`);
|
||||
message.success('已归档');
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '归档失败'); }
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: '租赁方名称', dataIndex: 'name',
|
||||
render: (v: string, r: any) => (
|
||||
<Space>
|
||||
<Tag color={r.color || 'default'} style={{ borderColor: r.color, color: '#fff', background: r.color }}>{v}</Tag>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{ title: '联系人', dataIndex: 'contact', render: (v: string) => v || '-' },
|
||||
{ title: '电话', dataIndex: 'phone', render: (v: string) => v || '-' },
|
||||
{ title: '颜色', dataIndex: 'color', render: (v: string) => v ? <span style={{ display: 'inline-block', width: 20, height: 20, background: v, borderRadius: 4, verticalAlign: 'middle' }} /> : '-' },
|
||||
{ title: '备注', dataIndex: 'notes', ellipsis: true, render: (v: string) => v || '-' },
|
||||
{
|
||||
title: '操作', width: 150,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
<PermissionButton permission="tenant:edit" size="small" onClick={() => { setEditing(record); form.setFieldsValue(record); setModalOpen(true); }}>编辑</PermissionButton>
|
||||
<PermissionButton permission="tenant:delete">
|
||||
<Popconfirm title="归档后仍可查看历史租赁" onConfirm={() => handleArchive(record.id)} okText="归档" cancelText="取消">
|
||||
<Button size="small" icon={<InboxOutlined />}>归档</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
|
||||
<Input.Search
|
||||
placeholder="搜索名称或联系人"
|
||||
allowClear
|
||||
style={{ width: 200 }}
|
||||
onSearch={v => setSearchText(v)}
|
||||
onChange={e => { if (!e.target.value) setSearchText(''); }}
|
||||
/>
|
||||
<PermissionButton permission="tenant:create" type="primary" icon={<PlusOutlined />} onClick={() => { setEditing(null); form.resetFields(); setModalOpen(true); }}>
|
||||
添加租赁方
|
||||
</PermissionButton>
|
||||
</div>
|
||||
<Table columns={columns} dataSource={filteredData} rowKey="id" loading={loading} pagination={{ pageSize: 20, showTotal: (total) => `共 ${total} 条` }} />
|
||||
|
||||
<Modal title={editing ? '编辑租赁方' : '添加租赁方'} open={modalOpen} onOk={handleSave} onCancel={() => { setModalOpen(false); setEditing(null); }} okText="保存">
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="name" label="名称" rules={[{ required: true }]}><Input placeholder="如:犀牛华安 / 艺考 / 博才" /></Form.Item>
|
||||
<Form.Item name="contact" label="联系人"><Input /></Form.Item>
|
||||
<Form.Item name="phone" label="电话"><Input /></Form.Item>
|
||||
<Form.Item name="color" label="标签颜色" tooltip="可视化排期时用的颜色,留空则自动分配">
|
||||
<Input placeholder="#40a9ff" addonAfter={
|
||||
<Space size={4}>
|
||||
{PRESET_COLORS.map(c => (
|
||||
<span
|
||||
key={c}
|
||||
onClick={() => form.setFieldValue('color', c)}
|
||||
style={{ display: 'inline-block', width: 16, height: 16, background: c, borderRadius: 3, cursor: 'pointer', border: '1px solid #d9d9d9' }}
|
||||
/>
|
||||
))}
|
||||
</Space>
|
||||
} />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注"><Input.TextArea rows={2} /></Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TenantsPage;
|
||||
176
apps/admin/src/pages/Users/index.tsx
Normal file
176
apps/admin/src/pages/Users/index.tsx
Normal file
@@ -0,0 +1,176 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Table, Button, Modal, Form, Input, Select, Switch, Space, Tag, Popconfirm, message } from 'antd';
|
||||
import { PlusOutlined, EditOutlined, DeleteOutlined, KeyOutlined } from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
|
||||
const UsersPage: React.FC = () => {
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [roles, setRoles] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [pwdModalOpen, setPwdModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<any>(null);
|
||||
const [resetTarget, setResetTarget] = useState<any>(null);
|
||||
const [form] = Form.useForm();
|
||||
const [pwdForm] = Form.useForm();
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [users, rolesRes] = await Promise.all([
|
||||
api.get('/rbac/users') as Promise<any[]>,
|
||||
api.get('/rbac/roles') as Promise<any[]>,
|
||||
]);
|
||||
setData(users);
|
||||
setRoles(rolesRes);
|
||||
} catch (e) { console.error(e); }
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => { fetchData(); }, []);
|
||||
|
||||
const handleAdd = () => {
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const handleEdit = (record: any) => {
|
||||
setEditing(record);
|
||||
form.setFieldsValue({
|
||||
username: record.username,
|
||||
name: record.name,
|
||||
isActive: record.isActive,
|
||||
roleIds: record.roles?.map((r: any) => r.id) || [],
|
||||
});
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const values = await form.validateFields();
|
||||
try {
|
||||
if (editing) {
|
||||
await api.put(`/rbac/users/${editing.id}`, { username: values.username, name: values.name, isActive: values.isActive, roleIds: values.roleIds || [] });
|
||||
message.success('更新成功');
|
||||
} else {
|
||||
await api.post('/rbac/users', { username: values.username, password: values.password, name: values.name, roleIds: values.roleIds || [] });
|
||||
message.success('创建成功');
|
||||
}
|
||||
setModalOpen(false);
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/rbac/users/${id}`);
|
||||
message.success('已删除');
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e.message || '删除失败'); }
|
||||
};
|
||||
|
||||
const handleResetPwd = (record: any) => {
|
||||
setResetTarget(record);
|
||||
pwdForm.resetFields();
|
||||
setPwdModalOpen(true);
|
||||
};
|
||||
|
||||
const handlePwdSubmit = async () => {
|
||||
const values = await pwdForm.validateFields();
|
||||
try {
|
||||
await api.put(`/rbac/users/${resetTarget.id}/password`, { password: values.password });
|
||||
message.success('密码已重置');
|
||||
setPwdModalOpen(false);
|
||||
} catch (e: any) { message.error(e.message || '操作失败'); }
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{ title: 'ID', dataIndex: 'id', width: 60 },
|
||||
{ title: '用户名', dataIndex: 'username', width: 120 },
|
||||
{ title: '姓名', dataIndex: 'name', width: 120 },
|
||||
{
|
||||
title: '角色', dataIndex: 'roles', width: 200,
|
||||
render: (v: any[]) => v && v.length > 0
|
||||
? v.map((r: any) => <Tag key={r.id} color="blue">{r.name}</Tag>)
|
||||
: <Tag color="default">无角色</Tag>,
|
||||
},
|
||||
{
|
||||
title: '状态', dataIndex: 'isActive', width: 80,
|
||||
render: (v: boolean) => <Tag color={v ? 'green' : 'default'}>{v ? '启用' : '禁用'}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '最后登录', dataIndex: 'lastLoginAt', width: 170,
|
||||
render: (v: string) => v ? dayjs(v).format('YYYY-MM-DD HH:mm:ss') : '-',
|
||||
},
|
||||
{
|
||||
title: '创建时间', dataIndex: 'createdAt', width: 170,
|
||||
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm:ss'),
|
||||
},
|
||||
{
|
||||
title: '操作', width: 220, fixed: 'right' as const,
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
<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.username !== 'admin' && (
|
||||
<PermissionButton permission="user:delete">
|
||||
<Popconfirm title="确认删除该用户?" onConfirm={() => handleDelete(record.id)}>
|
||||
<Button type="link" size="small" danger icon={<DeleteOutlined />}>删除</Button>
|
||||
</Popconfirm>
|
||||
</PermissionButton>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<h2 style={{ margin: 0 }}>账号管理</h2>
|
||||
<PermissionButton permission="user:create" type="primary" icon={<PlusOutlined />} onClick={handleAdd}>新增账号</PermissionButton>
|
||||
</div>
|
||||
<Table columns={columns} dataSource={data} rowKey="id" loading={loading} scroll={{ x: 1000 }} pagination={false} />
|
||||
|
||||
<Modal title={editing ? '编辑账号' : '新增账号'} open={modalOpen} onOk={handleSubmit} onCancel={() => setModalOpen(false)} destroyOnClose>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="username" label="用户名" rules={[{ required: true, message: '请输入用户名' }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
{!editing && (
|
||||
<Form.Item name="password" label="密码" rules={[{ required: true, min: 4, message: '密码至少4位' }]}>
|
||||
<Input.Password />
|
||||
</Form.Item>
|
||||
)}
|
||||
<Form.Item name="name" label="姓名" rules={[{ required: true, message: '请输入姓名' }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
{editing && (
|
||||
<Form.Item name="isActive" label="状态" valuePropName="checked">
|
||||
<Switch checkedChildren="启用" unCheckedChildren="禁用" />
|
||||
</Form.Item>
|
||||
)}
|
||||
<Form.Item name="roleIds" label="角色分配" rules={[{ required: !editing, message: '请至少选择一个角色' }]}>
|
||||
<Select
|
||||
mode="multiple"
|
||||
placeholder="选择角色"
|
||||
options={roles.filter((r: any) => r.status !== 0).map((r: any) => ({ value: r.id, label: `${r.name}${r.isSystem ? ' (系统)' : ''}` }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal title={`重置密码 - ${resetTarget?.username}`} open={pwdModalOpen} onOk={handlePwdSubmit} onCancel={() => setPwdModalOpen(false)} destroyOnClose>
|
||||
<Form form={pwdForm} layout="vertical">
|
||||
<Form.Item name="password" label="新密码" rules={[{ required: true, min: 4, message: '密码至少4位' }]}>
|
||||
<Input.Password />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UsersPage;
|
||||
25
apps/admin/tsconfig.app.json
Normal file
25
apps/admin/tsconfig.app.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
7
apps/admin/tsconfig.json
Normal file
7
apps/admin/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
24
apps/admin/tsconfig.node.json
Normal file
24
apps/admin/tsconfig.node.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "esnext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
30
apps/admin/vite.config.ts
Normal file
30
apps/admin/vite.config.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
port: 3002,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:3003',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
optimizeDeps: {
|
||||
include: [
|
||||
'dayjs',
|
||||
'dayjs/locale/zh-cn',
|
||||
'dayjs/plugin/customParseFormat',
|
||||
'dayjs/plugin/advancedFormat',
|
||||
'dayjs/plugin/weekday',
|
||||
'dayjs/plugin/localeData',
|
||||
'dayjs/plugin/weekOfYear',
|
||||
'dayjs/plugin/weekYear',
|
||||
'dayjs/plugin/updateLocale',
|
||||
'antd/es/locale/zh_CN',
|
||||
],
|
||||
},
|
||||
})
|
||||
31
apps/server/.env.example
Normal file
31
apps/server/.env.example
Normal file
@@ -0,0 +1,31 @@
|
||||
# ============================
|
||||
# 宿舍水电费系统 - 生产环境配置
|
||||
# ============================
|
||||
# 复制此文件为 .env 并修改配置值
|
||||
# cp .env.example .env
|
||||
|
||||
# ---- 数据库配置 ----
|
||||
DB_TYPE=mysql
|
||||
DB_HOST=localhost
|
||||
DB_PORT=3306
|
||||
DB_USERNAME=dorm_billing
|
||||
DB_PASSWORD=你的数据库密码
|
||||
DB_DATABASE=dorm_billing
|
||||
|
||||
# ---- JWT 认证 ----
|
||||
# 务必修改为一个复杂的随机字符串!
|
||||
JWT_SECRET=请替换为一个复杂的随机字符串-至少32位
|
||||
JWT_EXPIRES_IN=24h
|
||||
|
||||
# ---- 初始管理员 ----
|
||||
# 首次启动时自动创建的管理员密码(之后可在系统内修改)
|
||||
ADMIN_PASSWORD=请替换为强密码
|
||||
|
||||
# ---- 服务端口 ----
|
||||
PORT=3000
|
||||
|
||||
# ---- 文件上传 ----
|
||||
# 合同 PDF 存储根目录(相对或绝对)
|
||||
# 生产环境建议设为绝对路径,如 /www/wwwroot/jidi.gongxue100.com/backend/uploads
|
||||
# 目录需由 pm2/Node 进程用户可读写
|
||||
UPLOAD_DIR=./uploads
|
||||
4
apps/server/.prettierrc
Normal file
4
apps/server/.prettierrc
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
14
apps/server/Dockerfile
Normal file
14
apps/server/Dockerfile
Normal file
@@ -0,0 +1,14 @@
|
||||
FROM node:22-alpine AS builder
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM node:22-alpine
|
||||
WORKDIR /app
|
||||
COPY --from=builder /app/dist ./dist
|
||||
COPY --from=builder /app/node_modules ./node_modules
|
||||
COPY --from=builder /app/package.json ./
|
||||
EXPOSE 3000
|
||||
CMD ["node", "dist/main.js"]
|
||||
98
apps/server/README.md
Normal file
98
apps/server/README.md
Normal file
@@ -0,0 +1,98 @@
|
||||
<p align="center">
|
||||
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||
</p>
|
||||
|
||||
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||
|
||||
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||
</p>
|
||||
<!--[](https://opencollective.com/nest#backer)
|
||||
[](https://opencollective.com/nest#sponsor)-->
|
||||
|
||||
## Description
|
||||
|
||||
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||
|
||||
## Project setup
|
||||
|
||||
```bash
|
||||
$ npm install
|
||||
```
|
||||
|
||||
## Compile and run the project
|
||||
|
||||
```bash
|
||||
# development
|
||||
$ npm run start
|
||||
|
||||
# watch mode
|
||||
$ npm run start:dev
|
||||
|
||||
# production mode
|
||||
$ npm run start:prod
|
||||
```
|
||||
|
||||
## Run tests
|
||||
|
||||
```bash
|
||||
# unit tests
|
||||
$ npm run test
|
||||
|
||||
# e2e tests
|
||||
$ npm run test:e2e
|
||||
|
||||
# test coverage
|
||||
$ npm run test:cov
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||
|
||||
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||
|
||||
```bash
|
||||
$ npm install -g @nestjs/mau
|
||||
$ mau deploy
|
||||
```
|
||||
|
||||
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||
|
||||
## Resources
|
||||
|
||||
Check out a few resources that may come in handy when working with NestJS:
|
||||
|
||||
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||
|
||||
## Support
|
||||
|
||||
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||
|
||||
## Stay in touch
|
||||
|
||||
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||
|
||||
## License
|
||||
|
||||
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||
35
apps/server/eslint.config.mjs
Normal file
35
apps/server/eslint.config.mjs
Normal file
@@ -0,0 +1,35 @@
|
||||
// @ts-check
|
||||
import eslint from '@eslint/js';
|
||||
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
|
||||
import globals from 'globals';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
export default tseslint.config(
|
||||
{
|
||||
ignores: ['eslint.config.mjs'],
|
||||
},
|
||||
eslint.configs.recommended,
|
||||
...tseslint.configs.recommendedTypeChecked,
|
||||
eslintPluginPrettierRecommended,
|
||||
{
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.node,
|
||||
...globals.jest,
|
||||
},
|
||||
sourceType: 'commonjs',
|
||||
parserOptions: {
|
||||
projectService: true,
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/no-floating-promises': 'warn',
|
||||
'@typescript-eslint/no-unsafe-argument': 'warn',
|
||||
"prettier/prettier": ["error", { endOfLine: "auto" }],
|
||||
},
|
||||
},
|
||||
);
|
||||
8
apps/server/nest-cli.json
Normal file
8
apps/server/nest-cli.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
12040
apps/server/package-lock.json
generated
Normal file
12040
apps/server/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
93
apps/server/package.json
Normal file
93
apps/server/package.json
Normal file
@@ -0,0 +1,93 @@
|
||||
{
|
||||
"name": "backend",
|
||||
"version": "0.0.1",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"start": "nest start",
|
||||
"start:dev": "nest start --watch",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"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"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/config": "^4.0.4",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
"@nestjs/jwt": "^11.0.2",
|
||||
"@nestjs/passport": "^11.0.5",
|
||||
"@nestjs/platform-express": "^11.1.19",
|
||||
"@nestjs/throttler": "^6.5.0",
|
||||
"@nestjs/typeorm": "^11.0.1",
|
||||
"@types/multer": "^2.1.0",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"better-sqlite3": "^12.9.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.15.1",
|
||||
"exceljs": "^4.4.0",
|
||||
"multer": "^2.1.1",
|
||||
"mysql2": "^3.22.2",
|
||||
"passport": "^0.7.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"passport-local": "^1.0.0",
|
||||
"pdfkit": "^0.18.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"typeorm": "^0.3.28"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.2.0",
|
||||
"@eslint/js": "^9.18.0",
|
||||
"@nestjs/cli": "^11.0.0",
|
||||
"@nestjs/schematics": "^11.0.0",
|
||||
"@nestjs/testing": "^11.0.1",
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/passport-jwt": "^4.0.1",
|
||||
"@types/passport-local": "^1.0.38",
|
||||
"@types/supertest": "^7.0.0",
|
||||
"eslint": "^9.18.0",
|
||||
"eslint-config-prettier": "^10.0.1",
|
||||
"eslint-plugin-prettier": "^5.2.2",
|
||||
"globals": "^17.0.0",
|
||||
"jest": "^30.0.0",
|
||||
"prettier": "^3.4.2",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^7.0.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-loader": "^9.5.2",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.7.3",
|
||||
"typescript-eslint": "^8.20.0"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "src",
|
||||
"testRegex": ".*\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"collectCoverageFrom": [
|
||||
"**/*.(t|j)s"
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
}
|
||||
22
apps/server/src/app.controller.spec.ts
Normal file
22
apps/server/src/app.controller.spec.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
describe('AppController', () => {
|
||||
let appController: AppController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const app: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
}).compile();
|
||||
|
||||
appController = app.get<AppController>(AppController);
|
||||
});
|
||||
|
||||
describe('root', () => {
|
||||
it('should return "Hello World!"', () => {
|
||||
expect(appController.getHello()).toBe('Hello World!');
|
||||
});
|
||||
});
|
||||
});
|
||||
12
apps/server/src/app.controller.ts
Normal file
12
apps/server/src/app.controller.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
@Controller()
|
||||
export class AppController {
|
||||
constructor(private readonly appService: AppService) {}
|
||||
|
||||
@Get()
|
||||
getHello(): string {
|
||||
return this.appService.getHello();
|
||||
}
|
||||
}
|
||||
83
apps/server/src/app.module.ts
Normal file
83
apps/server/src/app.module.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';
|
||||
import {
|
||||
Student, Room, Occupancy, RoomExpense, PersonalExpense,
|
||||
Bill, BillItem, User, OperationLog, Deposit, Classroom,
|
||||
Tenant, ClassroomRental, Permission, Role,
|
||||
} from './entities';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { RbacModule } from './rbac/rbac.module';
|
||||
import { StudentsModule } from './students/students.module';
|
||||
import { PermissionGuard } from './auth/guards/permission.guard';
|
||||
import { RoomsModule } from './rooms/rooms.module';
|
||||
import { OccupanciesModule } from './occupancies/occupancies.module';
|
||||
import { ExpensesModule } from './expenses/expenses.module';
|
||||
import { BillsModule } from './bills/bills.module';
|
||||
import { DashboardModule } from './dashboard/dashboard.module';
|
||||
import { OperationLogsModule } from './operation-logs/operation-logs.module';
|
||||
import { DepositsModule } from './deposits/deposits.module';
|
||||
import { ClassroomsModule } from './classrooms/classrooms.module';
|
||||
import { TenantsModule } from './tenants/tenants.module';
|
||||
import { ClassroomRentalsModule } from './classroom-rentals/classroom-rentals.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true }),
|
||||
ThrottlerModule.forRoot([{
|
||||
ttl: 60000, // 60秒窗口
|
||||
limit: 100, // 普通接口每分钟100次
|
||||
}]),
|
||||
TypeOrmModule.forRootAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: (config: ConfigService): any => {
|
||||
const dbType = config.get('DB_TYPE', 'sqlite');
|
||||
const allEntities = [
|
||||
Student, Room, Occupancy, RoomExpense, PersonalExpense,
|
||||
Bill, BillItem, User, OperationLog, Deposit, Classroom,
|
||||
Tenant, ClassroomRental, Permission, Role,
|
||||
];
|
||||
if (dbType === 'mysql') {
|
||||
return {
|
||||
type: 'mysql' as const,
|
||||
host: config.get('DB_HOST', 'localhost'),
|
||||
port: config.get<number>('DB_PORT', 3306),
|
||||
username: config.get('DB_USERNAME', 'root'),
|
||||
password: config.get('DB_PASSWORD', ''),
|
||||
database: config.get('DB_DATABASE', 'dorm_billing'),
|
||||
entities: allEntities,
|
||||
synchronize: true,
|
||||
charset: 'utf8mb4',
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: 'better-sqlite3' as const,
|
||||
database: config.get('DB_DATABASE', 'dorm_billing.db'),
|
||||
entities: allEntities,
|
||||
synchronize: true,
|
||||
};
|
||||
},
|
||||
}),
|
||||
AuthModule,
|
||||
RbacModule,
|
||||
StudentsModule,
|
||||
RoomsModule,
|
||||
OccupanciesModule,
|
||||
ExpensesModule,
|
||||
BillsModule,
|
||||
DashboardModule,
|
||||
OperationLogsModule,
|
||||
DepositsModule,
|
||||
ClassroomsModule,
|
||||
TenantsModule,
|
||||
ClassroomRentalsModule,
|
||||
],
|
||||
providers: [
|
||||
{ provide: APP_GUARD, useClass: ThrottlerGuard },
|
||||
{ provide: APP_GUARD, useClass: PermissionGuard },
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
8
apps/server/src/app.service.ts
Normal file
8
apps/server/src/app.service.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getHello(): string {
|
||||
return 'Hello World!';
|
||||
}
|
||||
}
|
||||
44
apps/server/src/auth/auth.controller.ts
Normal file
44
apps/server/src/auth/auth.controller.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { Controller, Post, Body, Get, Request, Req, UseGuards } from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { LoginDto } from './dto/auth.dto';
|
||||
import { JwtAuthGuard } from './guards/jwt-auth.guard';
|
||||
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
||||
import { extractRequestInfo } from '../common/request-utils';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import { Public } from './decorators/public.decorator';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private authService: AuthService, private logService: OperationLogsService) {}
|
||||
|
||||
@Public()
|
||||
@Post('login')
|
||||
@Throttle({ default: { ttl: 60000, limit: 5 } })
|
||||
async login(@Body() dto: LoginDto, @Req() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
try {
|
||||
const result = await this.authService.login(dto, ipAddress);
|
||||
await this.logService.log({
|
||||
userId: result.user.id, username: result.user.username,
|
||||
module: '认证', action: '登录成功',
|
||||
ipAddress, userAgent, status: 'success',
|
||||
});
|
||||
return result;
|
||||
} catch (e: any) {
|
||||
await this.logService.log({
|
||||
username: dto.username,
|
||||
module: '认证', action: '登录失败',
|
||||
detail: e.message || '密码错误',
|
||||
ipAddress, userAgent, status: 'fail',
|
||||
});
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Public()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('profile')
|
||||
getProfile(@Request() req: any) {
|
||||
return req.user;
|
||||
}
|
||||
}
|
||||
30
apps/server/src/auth/auth.module.ts
Normal file
30
apps/server/src/auth/auth.module.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { Module, forwardRef } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { User } from '../entities/user.entity';
|
||||
import { AuthService } from './auth.service';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { JwtStrategy } from './strategies/jwt.strategy';
|
||||
import { RbacModule } from '../rbac/rbac.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([User]),
|
||||
PassportModule,
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: (config: ConfigService) => ({
|
||||
secret: config.get('JWT_SECRET', 'dorm-billing-jwt-secret-key-2024'),
|
||||
signOptions: { expiresIn: config.get('JWT_EXPIRES_IN', '4h') },
|
||||
}),
|
||||
}),
|
||||
forwardRef(() => RbacModule),
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, JwtStrategy],
|
||||
exports: [AuthService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
91
apps/server/src/auth/auth.service.ts
Normal file
91
apps/server/src/auth/auth.service.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { Injectable, UnauthorizedException, forwardRef, Inject } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { User } from '../entities/user.entity';
|
||||
import { LoginDto } from './dto/auth.dto';
|
||||
import { RbacService } from '../rbac/rbac.service';
|
||||
|
||||
// 内存中的登录失败计数器(按IP+用户名)
|
||||
const loginAttempts = new Map<string, { count: number; lockedUntil?: Date }>();
|
||||
const MAX_ATTEMPTS = 5;
|
||||
const LOCK_MINUTES = 15;
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
@InjectRepository(User) private userRepo: Repository<User>,
|
||||
private jwtService: JwtService,
|
||||
@Inject(forwardRef(() => RbacService)) private rbacService: RbacService,
|
||||
) {}
|
||||
|
||||
async login(dto: LoginDto, ip?: string) {
|
||||
const attemptKey = `${ip || 'unknown'}:${dto.username}`;
|
||||
const attempt = loginAttempts.get(attemptKey);
|
||||
|
||||
// 检查是否在锁定期
|
||||
if (attempt?.lockedUntil && attempt.lockedUntil > new Date()) {
|
||||
const remaining = Math.ceil((attempt.lockedUntil.getTime() - Date.now()) / 60000);
|
||||
throw new UnauthorizedException(`账号已被临时锁定,请 ${remaining} 分钟后重试`);
|
||||
}
|
||||
|
||||
const user = await this.userRepo.findOne({
|
||||
where: { username: dto.username },
|
||||
relations: ['roles'],
|
||||
});
|
||||
if (!user) {
|
||||
this.recordFailedAttempt(attemptKey);
|
||||
throw new UnauthorizedException('用户名或密码错误');
|
||||
}
|
||||
if (!user.isActive) throw new UnauthorizedException('账号已被禁用,请联系管理员');
|
||||
const valid = await bcrypt.compare(dto.password, user.passwordHash);
|
||||
if (!valid) {
|
||||
this.recordFailedAttempt(attemptKey);
|
||||
const att = loginAttempts.get(attemptKey);
|
||||
const remaining = MAX_ATTEMPTS - (att?.count || 0);
|
||||
if (remaining > 0) {
|
||||
throw new UnauthorizedException(`用户名或密码错误,还剩 ${remaining} 次尝试机会`);
|
||||
}
|
||||
throw new UnauthorizedException(`登录失败次数过多,账号已被锁定 ${LOCK_MINUTES} 分钟`);
|
||||
}
|
||||
|
||||
// 登录成功,清除失败计数
|
||||
loginAttempts.delete(attemptKey);
|
||||
|
||||
// 记录登录时间
|
||||
user.lastLoginAt = new Date();
|
||||
await this.userRepo.save(user);
|
||||
|
||||
// 获取用户权限
|
||||
const permissions = await this.rbacService.getUserPermissions(user.id);
|
||||
const payload = { sub: user.id, username: user.username, permissions };
|
||||
|
||||
// 获取角色名称列表
|
||||
const roleNames = user.roles ? user.roles.filter(r => r.status === 1).map(r => r.name) : [];
|
||||
|
||||
return {
|
||||
access_token: this.jwtService.sign(payload),
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
name: user.name,
|
||||
roles: roleNames,
|
||||
permissions,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private recordFailedAttempt(key: string) {
|
||||
const attempt = loginAttempts.get(key) || { count: 0 };
|
||||
attempt.count++;
|
||||
if (attempt.count >= MAX_ATTEMPTS) {
|
||||
attempt.lockedUntil = new Date(Date.now() + LOCK_MINUTES * 60 * 1000);
|
||||
}
|
||||
loginAttempts.set(key, attempt);
|
||||
}
|
||||
|
||||
async validateUser(payload: any) {
|
||||
return this.userRepo.findOne({ where: { id: payload.sub } });
|
||||
}
|
||||
}
|
||||
11
apps/server/src/auth/decorators/permission.decorator.ts
Normal file
11
apps/server/src/auth/decorators/permission.decorator.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const PERMISSION_KEY = 'permissions';
|
||||
|
||||
/**
|
||||
* 声明接口所需权限。
|
||||
* 多个参数之间为 OR 关系(用户拥有其中任一权限即可通过)。
|
||||
* 不支持 AND 语义:多次调用装饰器会被全局 PermissionGuard 合并为扁平数组,效果等同于单次多参数调用。
|
||||
*/
|
||||
export const RequirePermission = (...permissions: string[]) =>
|
||||
SetMetadata(PERMISSION_KEY, permissions);
|
||||
4
apps/server/src/auth/decorators/public.decorator.ts
Normal file
4
apps/server/src/auth/decorators/public.decorator.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const IS_PUBLIC_KEY = 'isPublic';
|
||||
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||
22
apps/server/src/auth/dto/auth.dto.ts
Normal file
22
apps/server/src/auth/dto/auth.dto.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { IsString, MinLength } from 'class-validator';
|
||||
|
||||
export class LoginDto {
|
||||
@IsString()
|
||||
username: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(4)
|
||||
password: string;
|
||||
}
|
||||
|
||||
export class RegisterDto {
|
||||
@IsString()
|
||||
username: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(4)
|
||||
password: string;
|
||||
|
||||
@IsString()
|
||||
name: string;
|
||||
}
|
||||
5
apps/server/src/auth/guards/jwt-auth.guard.ts
Normal file
5
apps/server/src/auth/guards/jwt-auth.guard.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { Injectable, ExecutionContext } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {}
|
||||
34
apps/server/src/auth/guards/permission.guard.ts
Normal file
34
apps/server/src/auth/guards/permission.guard.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
||||
import { PERMISSION_KEY } from '../decorators/permission.decorator';
|
||||
|
||||
@Injectable()
|
||||
export class PermissionGuard implements CanActivate {
|
||||
constructor(private reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
// 1. @Public() 豁免
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (isPublic) return true;
|
||||
|
||||
// 2. 获取所需权限(getAllAndMerge 合并 handler+class 层的所有 metadata)
|
||||
const requiredPermissions = this.reflector.getAllAndMerge<string[]>(
|
||||
PERMISSION_KEY,
|
||||
[context.getHandler(), context.getClass()],
|
||||
);
|
||||
// 无装饰器 = 默认拒绝
|
||||
if (!requiredPermissions || requiredPermissions.length === 0) return false;
|
||||
|
||||
// 3. 从 JWT payload 获取用户权限
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const user = request.user;
|
||||
if (!user || !user.permissions || !Array.isArray(user.permissions)) return false;
|
||||
|
||||
// 4. OR 匹配:用户拥有 requiredPermissions 中任一权限即可通过
|
||||
return requiredPermissions.some(p => user.permissions.includes(p));
|
||||
}
|
||||
}
|
||||
23
apps/server/src/auth/strategies/jwt.strategy.ts
Normal file
23
apps/server/src/auth/strategies/jwt.strategy.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor(config: ConfigService) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: config.get('JWT_SECRET', 'dorm-billing-jwt-secret-key-2024'),
|
||||
});
|
||||
}
|
||||
|
||||
async validate(payload: any) {
|
||||
return {
|
||||
id: payload.sub,
|
||||
username: payload.username,
|
||||
permissions: payload.permissions || [],
|
||||
};
|
||||
}
|
||||
}
|
||||
242
apps/server/src/bills/bills-export.service.ts
Normal file
242
apps/server/src/bills/bills-export.service.ts
Normal file
@@ -0,0 +1,242 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { Bill } from '../entities/bill.entity';
|
||||
import { BillItem } from '../entities/bill-item.entity';
|
||||
import { Deposit } from '../entities/deposit.entity';
|
||||
import * as ExcelJS from 'exceljs';
|
||||
import * as PDFDocument from 'pdfkit';
|
||||
import { Response } from 'express';
|
||||
|
||||
@Injectable()
|
||||
export class BillsExportService {
|
||||
constructor(
|
||||
@InjectRepository(Bill) private billRepo: Repository<Bill>,
|
||||
@InjectRepository(BillItem) private itemRepo: Repository<BillItem>,
|
||||
@InjectRepository(Deposit) private depositRepo: Repository<Deposit>,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 导出账单列表为 Excel
|
||||
*/
|
||||
async exportExcel(query: { periodStart?: string; periodEnd?: string; studentId?: number; status?: string }, res: Response) {
|
||||
const qb = this.billRepo.createQueryBuilder('b')
|
||||
.leftJoinAndSelect('b.student', 'student')
|
||||
.leftJoinAndSelect('b.items', 'items')
|
||||
.orderBy('b.generatedAt', 'DESC');
|
||||
if (query.periodStart) qb.andWhere('b.periodStart = :ps', { ps: query.periodStart });
|
||||
if (query.periodEnd) qb.andWhere('b.periodEnd = :pe', { pe: query.periodEnd });
|
||||
if (query.studentId) qb.andWhere('b.studentId = :sid', { sid: query.studentId });
|
||||
if (query.status) qb.andWhere('b.status = :status', { status: query.status });
|
||||
const bills = await qb.getMany();
|
||||
|
||||
// 查询涉及学生的"已缴未退"押金,用于导出押金抵扣字段
|
||||
const studentIds = Array.from(new Set(bills.map((b) => b.studentId)));
|
||||
const depMap = new Map<number, number>();
|
||||
if (studentIds.length > 0) {
|
||||
const deposits = await this.depositRepo.createQueryBuilder('d')
|
||||
.where('d.studentId IN (:...ids)', { ids: studentIds })
|
||||
.andWhere('d.status = :status', { status: 'paid' })
|
||||
.getMany();
|
||||
for (const d of deposits) {
|
||||
depMap.set(d.studentId, (depMap.get(d.studentId) || 0) + Number(d.amount || 0));
|
||||
}
|
||||
}
|
||||
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
workbook.creator = '恭学教育基地管理系统';
|
||||
|
||||
// Sheet 1: 账单汇总
|
||||
const ws = workbook.addWorksheet('账单汇总');
|
||||
ws.columns = [
|
||||
{ header: '账单ID', key: 'id', width: 10 },
|
||||
{ header: '学生姓名', key: 'studentName', width: 14 },
|
||||
{ header: '计费周期', key: 'period', width: 24 },
|
||||
{ header: '分摊费用', key: 'shared', width: 12 },
|
||||
{ header: '个人费用', key: 'personal', width: 12 },
|
||||
{ header: '总金额', key: 'total', width: 12 },
|
||||
{ header: '可用押金', key: 'deposit', width: 12 },
|
||||
{ header: '押金抵扣', key: 'depositApplied', width: 12 },
|
||||
{ header: '抵扣后应付', key: 'afterDeposit', width: 14 },
|
||||
{ header: '状态', key: 'status', width: 10 },
|
||||
{ header: '生成时间', key: 'generatedAt', width: 20 },
|
||||
];
|
||||
// 表头样式
|
||||
ws.getRow(1).font = { bold: true };
|
||||
ws.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
|
||||
|
||||
const statusMap: Record<string, string> = { draft: '草稿', confirmed: '已确认', paid: '已结清' };
|
||||
for (const bill of bills) {
|
||||
const total = Number(bill.totalAmount || 0);
|
||||
const dep = Number((depMap.get(bill.studentId) || 0).toFixed(2));
|
||||
const applied = Number(Math.min(dep, total).toFixed(2));
|
||||
const after = Number(Math.max(0, total - applied).toFixed(2));
|
||||
ws.addRow({
|
||||
id: bill.id,
|
||||
studentName: (bill as any).student?.name || '-',
|
||||
period: `${bill.periodStart} ~ ${bill.periodEnd}`,
|
||||
shared: Number(bill.sharedAmount),
|
||||
personal: Number(bill.personalAmount),
|
||||
total,
|
||||
deposit: dep,
|
||||
depositApplied: applied,
|
||||
afterDeposit: after,
|
||||
status: statusMap[bill.status] || bill.status,
|
||||
generatedAt: bill.generatedAt ? new Date(bill.generatedAt).toLocaleString('zh-CN') : '',
|
||||
});
|
||||
}
|
||||
|
||||
// Sheet 2: 费用明细
|
||||
const ws2 = workbook.addWorksheet('费用明细');
|
||||
ws2.columns = [
|
||||
{ header: '账单ID', key: 'billId', width: 10 },
|
||||
{ header: '学生姓名', key: 'studentName', width: 14 },
|
||||
{ header: '费用类型', key: 'expenseType', width: 12 },
|
||||
{ header: '说明', key: 'description', width: 24 },
|
||||
{ header: '计费天数', key: 'days', width: 10 },
|
||||
{ header: '宿舍总人天', key: 'totalRoomDays', width: 12 },
|
||||
{ header: '宿舍总费用', key: 'roomTotal', width: 12 },
|
||||
{ header: '学生应付', key: 'studentAmount', width: 12 },
|
||||
];
|
||||
ws2.getRow(1).font = { bold: true };
|
||||
ws2.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
|
||||
|
||||
for (const bill of bills) {
|
||||
for (const item of bill.items || []) {
|
||||
ws2.addRow({
|
||||
billId: bill.id,
|
||||
studentName: (bill as any).student?.name || '-',
|
||||
expenseType: item.expenseType,
|
||||
description: item.description,
|
||||
days: item.days,
|
||||
totalRoomDays: item.totalRoomDays,
|
||||
roomTotal: Number(item.roomTotalAmount),
|
||||
studentAmount: Number(item.studentAmount),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
||||
res.setHeader('Content-Disposition', `attachment; filename=bills_${Date.now()}.xlsx`);
|
||||
await workbook.xlsx.write(res);
|
||||
res.end();
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出单个学生的 PDF 账单
|
||||
*/
|
||||
async exportStudentPdf(billId: number, res: Response) {
|
||||
const bill = await this.billRepo.findOne({ where: { id: billId }, relations: ['student', 'items'] });
|
||||
if (!bill) { res.status(404).json({ message: '账单不存在' }); return; }
|
||||
|
||||
// 查询该学生的可用押金(已缴未退)
|
||||
const deposits = await this.depositRepo.createQueryBuilder('d')
|
||||
.where('d.studentId = :sid', { sid: bill.studentId })
|
||||
.andWhere('d.status = :status', { status: 'paid' })
|
||||
.getMany();
|
||||
const availableDeposit = deposits.reduce((s, d) => s + Number(d.amount || 0), 0);
|
||||
const totalAmount = Number(bill.totalAmount || 0);
|
||||
const depositApplied = Math.min(availableDeposit, totalAmount);
|
||||
const amountAfterDeposit = Math.max(0, totalAmount - depositApplied);
|
||||
|
||||
const doc = new PDFDocument({ size: 'A4', margin: 50 });
|
||||
res.setHeader('Content-Type', 'application/pdf');
|
||||
res.setHeader('Content-Disposition', `attachment; filename=bill_${billId}.pdf`);
|
||||
doc.pipe(res);
|
||||
|
||||
// 注册中文字体(优先使用系统字体,兼容 macOS 和 Linux)
|
||||
const fontPaths = [
|
||||
'/System/Library/Fonts/PingFang.ttc', // macOS
|
||||
'/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc', // Linux Noto
|
||||
'/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc',
|
||||
'/usr/share/fonts/google-noto-cjk/NotoSansCJK-Regular.ttc',
|
||||
'/usr/share/fonts/noto-cjk/NotoSansSC-Regular.otf',
|
||||
'/usr/share/fonts/wqy-microhei/wqy-microhei.ttc', // Linux WenQuanYi
|
||||
'/usr/share/fonts/truetype/wqy/wqy-microhei.ttc',
|
||||
];
|
||||
let fontRegistered = false;
|
||||
const fs = require('fs');
|
||||
for (const fp of fontPaths) {
|
||||
try {
|
||||
if (fs.existsSync(fp)) {
|
||||
doc.registerFont('Chinese', fp);
|
||||
doc.font('Chinese');
|
||||
fontRegistered = true;
|
||||
break;
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
if (!fontRegistered) {
|
||||
// 如果没有中文字体,使用 Helvetica(中文可能乱码)
|
||||
doc.font('Helvetica');
|
||||
}
|
||||
|
||||
const statusMap: Record<string, string> = { draft: '草稿', confirmed: '已确认', paid: '已结清' };
|
||||
|
||||
// 标题
|
||||
doc.fontSize(20).text('恭学教育基地水电费账单', { align: 'center' });
|
||||
doc.moveDown(0.5);
|
||||
doc.fontSize(10).fillColor('#666').text(`生成时间: ${new Date().toLocaleString('zh-CN')}`, { align: 'center' });
|
||||
doc.moveDown(1);
|
||||
|
||||
// 基本信息
|
||||
doc.fontSize(12).fillColor('#000');
|
||||
doc.text(`学生姓名: ${(bill as any).student?.name || '-'}`);
|
||||
doc.text(`计费周期: ${bill.periodStart} ~ ${bill.periodEnd}`);
|
||||
doc.text(`账单状态: ${statusMap[bill.status] || bill.status}`);
|
||||
doc.moveDown(0.5);
|
||||
|
||||
// 金额汇总
|
||||
doc.fontSize(14).text('费用汇总', { underline: true });
|
||||
doc.moveDown(0.3);
|
||||
doc.fontSize(12);
|
||||
doc.text(`分摊费用: ¥${Number(bill.sharedAmount).toFixed(2)}`);
|
||||
doc.text(`个人费用: ¥${Number(bill.personalAmount).toFixed(2)}`);
|
||||
doc.fontSize(14).fillColor('#007AFF').text(`应付总额: ¥${totalAmount.toFixed(2)}`);
|
||||
doc.moveDown(0.3);
|
||||
if (availableDeposit > 0) {
|
||||
doc.fontSize(11).fillColor('#52C41A').text(`可用押金: ¥${availableDeposit.toFixed(2)}`);
|
||||
doc.fontSize(11).fillColor('#FA8C16').text(`押金抵扣: -¥${depositApplied.toFixed(2)}`);
|
||||
doc.fontSize(14).fillColor('#FF3B30').text(`抵扣后应付: ¥${amountAfterDeposit.toFixed(2)}`);
|
||||
}
|
||||
doc.moveDown(1);
|
||||
|
||||
// 明细表格
|
||||
doc.fontSize(14).fillColor('#000').text('费用明细', { underline: true });
|
||||
doc.moveDown(0.5);
|
||||
|
||||
const items = bill.items || [];
|
||||
const tableTop = doc.y;
|
||||
const colWidths = [120, 180, 60, 60, 70];
|
||||
const headers = ['费用类型', '说明', '天数', '总人天', '金额(元)'];
|
||||
|
||||
// 表头
|
||||
doc.fontSize(10).fillColor('#333');
|
||||
let x = 50;
|
||||
for (let i = 0; i < headers.length; i++) {
|
||||
doc.text(headers[i], x, tableTop, { width: colWidths[i], align: 'left' });
|
||||
x += colWidths[i];
|
||||
}
|
||||
doc.moveDown(0.3);
|
||||
doc.moveTo(50, doc.y).lineTo(540, doc.y).stroke('#ccc');
|
||||
doc.moveDown(0.2);
|
||||
|
||||
// 数据行
|
||||
for (const item of items) {
|
||||
const y = doc.y;
|
||||
x = 50;
|
||||
doc.fontSize(9).fillColor('#000');
|
||||
doc.text(item.expenseType || '', x, y, { width: colWidths[0] }); x += colWidths[0];
|
||||
doc.text(item.description || '', x, y, { width: colWidths[1] }); x += colWidths[1];
|
||||
doc.text(String(item.days || 0), x, y, { width: colWidths[2] }); x += colWidths[2];
|
||||
doc.text(String(item.totalRoomDays || 0), x, y, { width: colWidths[3] }); x += colWidths[3];
|
||||
doc.text(Number(item.studentAmount).toFixed(2), x, y, { width: colWidths[4] });
|
||||
doc.moveDown(0.8);
|
||||
}
|
||||
|
||||
doc.moveDown(2);
|
||||
doc.fontSize(8).fillColor('#999').text('本账单由恭学教育基地管理系统自动生成', { align: 'center' });
|
||||
|
||||
doc.end();
|
||||
}
|
||||
}
|
||||
108
apps/server/src/bills/bills.controller.ts
Normal file
108
apps/server/src/bills/bills.controller.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { Controller, Get, Post, Put, Delete, Param, Body, Query, UseGuards, Request, Res, Req } from '@nestjs/common';
|
||||
import { BillsService } from './bills.service';
|
||||
import { BillsExportService } from './bills-export.service';
|
||||
import { GenerateBillsDto, UpdateBillStatusDto } from './dto/bill.dto';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
||||
import { extractRequestInfo } from '../common/request-utils';
|
||||
import { RequirePermission } from '../auth/decorators/permission.decorator';
|
||||
import type { Response } from 'express';
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('bills')
|
||||
export class BillsController {
|
||||
constructor(private service: BillsService, private exportService: BillsExportService, private logService: OperationLogsService) {}
|
||||
|
||||
@Post('generate')
|
||||
@RequirePermission('bill:generate')
|
||||
async generateBills(@Body() dto: GenerateBillsDto, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.generateBills(dto);
|
||||
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '账单', action: '生成账单', detail: `周期 ${dto.periodStart}~${dto.periodEnd}, 生成 ${result.count} 条`, ipAddress, userAgent });
|
||||
return result;
|
||||
}
|
||||
|
||||
@Get()
|
||||
@RequirePermission('bill:view')
|
||||
findAll(
|
||||
@Query('periodStart') periodStart?: string,
|
||||
@Query('periodEnd') periodEnd?: string,
|
||||
@Query('studentId') studentId?: string,
|
||||
@Query('status') status?: string,
|
||||
) {
|
||||
return this.service.findAll({
|
||||
periodStart, periodEnd,
|
||||
studentId: studentId ? +studentId : undefined,
|
||||
status,
|
||||
});
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@RequirePermission('bill:view')
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.service.findOne(+id);
|
||||
}
|
||||
|
||||
@Put(':id/status')
|
||||
@RequirePermission('bill:confirm')
|
||||
async updateStatus(@Param('id') id: string, @Body() dto: UpdateBillStatusDto, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.updateStatus(+id, dto);
|
||||
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '账单', action: `状态变更为${dto.status}`, targetId: +id, targetType: 'bill', ipAddress, userAgent });
|
||||
return result;
|
||||
}
|
||||
|
||||
@Put('batch/status')
|
||||
@RequirePermission('bill:confirm')
|
||||
async batchUpdateStatus(@Body() body: { ids: number[]; status: string }, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.batchUpdateStatus(body.ids, body.status);
|
||||
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '账单', action: `批量状态变更为${body.status}`, detail: `IDs: ${body.ids.join(',')}`, ipAddress, userAgent });
|
||||
return result;
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@RequirePermission('bill:delete')
|
||||
async remove(@Param('id') id: string, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.remove(+id);
|
||||
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '账单', action: '删除账单', targetId: +id, targetType: 'bill', ipAddress, userAgent });
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post('batch/delete')
|
||||
@RequirePermission('bill:delete')
|
||||
async batchRemove(@Body() body: { ids: number[] }, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.batchRemove(body.ids);
|
||||
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '账单', action: '批量删除账单', detail: `IDs: ${body.ids.join(',')}`, ipAddress, userAgent });
|
||||
return result;
|
||||
}
|
||||
|
||||
@Get('export/excel')
|
||||
@RequirePermission('bill:export-excel')
|
||||
async exportExcel(
|
||||
@Query('periodStart') periodStart?: string,
|
||||
@Query('periodEnd') periodEnd?: string,
|
||||
@Query('studentId') studentId?: string,
|
||||
@Query('status') status?: string,
|
||||
@Res() res?: Response,
|
||||
@Req() req?: any,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
await this.logService.log({ userId: req?.user?.id, username: req?.user?.username, module: '账单', action: '导出Excel', detail: `筛选: 周期${periodStart || '全部'}~${periodEnd || '全部'}, 状态${status || '全部'}`, ipAddress, userAgent });
|
||||
return this.exportService.exportExcel({
|
||||
periodStart, periodEnd,
|
||||
studentId: studentId ? +studentId : undefined,
|
||||
status,
|
||||
}, res!);
|
||||
}
|
||||
|
||||
@Get('export/pdf/:id')
|
||||
@RequirePermission('bill:export-pdf')
|
||||
async exportPdf(@Param('id') id: string, @Res() res: Response, @Req() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
await this.logService.log({ userId: req?.user?.id, username: req?.user?.username, module: '账单', action: '导出PDF', targetId: +id, targetType: 'bill', ipAddress, userAgent });
|
||||
return this.exportService.exportStudentPdf(+id, res);
|
||||
}
|
||||
}
|
||||
20
apps/server/src/bills/bills.module.ts
Normal file
20
apps/server/src/bills/bills.module.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Bill } from '../entities/bill.entity';
|
||||
import { BillItem } from '../entities/bill-item.entity';
|
||||
import { RoomExpense } from '../entities/room-expense.entity';
|
||||
import { PersonalExpense } from '../entities/personal-expense.entity';
|
||||
import { Occupancy } from '../entities/occupancy.entity';
|
||||
import { Room } from '../entities/room.entity';
|
||||
import { Deposit } from '../entities/deposit.entity';
|
||||
import { BillsService } from './bills.service';
|
||||
import { BillsExportService } from './bills-export.service';
|
||||
import { BillsController } from './bills.controller';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Bill, BillItem, RoomExpense, PersonalExpense, Occupancy, Room, Deposit])],
|
||||
controllers: [BillsController],
|
||||
providers: [BillsService, BillsExportService],
|
||||
exports: [BillsService],
|
||||
})
|
||||
export class BillsModule {}
|
||||
240
apps/server/src/bills/bills.service.ts
Normal file
240
apps/server/src/bills/bills.service.ts
Normal file
@@ -0,0 +1,240 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, DataSource } from 'typeorm';
|
||||
import { Bill } from '../entities/bill.entity';
|
||||
import { BillItem } from '../entities/bill-item.entity';
|
||||
import { RoomExpense } from '../entities/room-expense.entity';
|
||||
import { PersonalExpense } from '../entities/personal-expense.entity';
|
||||
import { Occupancy } from '../entities/occupancy.entity';
|
||||
import { Room } from '../entities/room.entity';
|
||||
import { Deposit } from '../entities/deposit.entity';
|
||||
import { GenerateBillsDto, UpdateBillStatusDto } from './dto/bill.dto';
|
||||
|
||||
@Injectable()
|
||||
export class BillsService {
|
||||
constructor(
|
||||
@InjectRepository(Bill) private billRepo: Repository<Bill>,
|
||||
@InjectRepository(BillItem) private itemRepo: Repository<BillItem>,
|
||||
@InjectRepository(RoomExpense) private roomExpRepo: Repository<RoomExpense>,
|
||||
@InjectRepository(PersonalExpense) private personalExpRepo: Repository<PersonalExpense>,
|
||||
@InjectRepository(Occupancy) private occRepo: Repository<Occupancy>,
|
||||
@InjectRepository(Room) private roomRepo: Repository<Room>,
|
||||
@InjectRepository(Deposit) private depositRepo: Repository<Deposit>,
|
||||
private dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 核心计费引擎:按"人天数"加权分摊
|
||||
*/
|
||||
async generateBills(dto: GenerateBillsDto) {
|
||||
const { periodStart, periodEnd } = dto;
|
||||
const pStart = new Date(periodStart);
|
||||
const pEnd = new Date(periodEnd);
|
||||
|
||||
// 删除该周期已有的草稿账单
|
||||
const existingDrafts = await this.billRepo.find({
|
||||
where: { periodStart, periodEnd, status: 'draft' },
|
||||
});
|
||||
if (existingDrafts.length > 0) {
|
||||
const draftIds = existingDrafts.map((b) => b.id);
|
||||
await this.itemRepo.createQueryBuilder().delete().where('billId IN (:...ids)', { ids: draftIds }).execute();
|
||||
await this.billRepo.createQueryBuilder().delete().where('id IN (:...ids)', { ids: draftIds }).execute();
|
||||
}
|
||||
|
||||
// 获取所有有费用的宿舍
|
||||
const roomExpenses = await this.roomExpRepo.createQueryBuilder('e')
|
||||
.where('e.periodStart = :periodStart AND e.periodEnd = :periodEnd', { periodStart, periodEnd })
|
||||
.getMany();
|
||||
|
||||
// 按宿舍分组费用
|
||||
const roomExpMap = new Map<number, RoomExpense[]>();
|
||||
for (const exp of roomExpenses) {
|
||||
if (!roomExpMap.has(exp.roomId)) roomExpMap.set(exp.roomId, []);
|
||||
roomExpMap.get(exp.roomId)!.push(exp);
|
||||
}
|
||||
|
||||
// 计算每个学生的分摊费用
|
||||
const studentBillData = new Map<number, { shared: number; items: any[] }>();
|
||||
|
||||
for (const [roomId, expenses] of roomExpMap) {
|
||||
// 获取该宿舍在此周期内的所有入住记录
|
||||
const occupancies = await this.occRepo.createQueryBuilder('o')
|
||||
.leftJoinAndSelect('o.student', 'student')
|
||||
.where('o.roomId = :roomId', { roomId })
|
||||
.andWhere('o.billingStartDate <= :periodEnd', { periodEnd })
|
||||
.andWhere('(o.billingEndDate IS NULL OR o.billingEndDate >= :periodStart)', { periodStart })
|
||||
.getMany();
|
||||
|
||||
if (occupancies.length === 0) continue;
|
||||
|
||||
// 计算每个学生的计费天数
|
||||
const studentDays: { studentId: number; days: number }[] = [];
|
||||
let totalDays = 0;
|
||||
|
||||
for (const occ of occupancies) {
|
||||
const start = new Date(Math.max(new Date(occ.billingStartDate).getTime(), pStart.getTime()));
|
||||
const end = occ.billingEndDate
|
||||
? new Date(Math.min(new Date(occ.billingEndDate).getTime(), pEnd.getTime()))
|
||||
: pEnd;
|
||||
const days = Math.max(0, Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)) + 1);
|
||||
studentDays.push({ studentId: occ.studentId, days });
|
||||
totalDays += days;
|
||||
}
|
||||
|
||||
if (totalDays === 0) continue;
|
||||
|
||||
// 对每项费用进行分摊
|
||||
for (const expense of expenses) {
|
||||
for (const sd of studentDays) {
|
||||
if (sd.days === 0) continue;
|
||||
const amount = Number(((sd.days / totalDays) * Number(expense.amount)).toFixed(2));
|
||||
if (!studentBillData.has(sd.studentId)) {
|
||||
studentBillData.set(sd.studentId, { shared: 0, items: [] });
|
||||
}
|
||||
const data = studentBillData.get(sd.studentId)!;
|
||||
data.shared += amount;
|
||||
data.items.push({
|
||||
roomId,
|
||||
expenseType: expense.expenseType,
|
||||
description: `${expense.expenseType} 分摊`,
|
||||
days: sd.days,
|
||||
totalRoomDays: totalDays,
|
||||
roomTotalAmount: expense.amount,
|
||||
studentAmount: amount,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取个人附加费
|
||||
const personalExps = await this.personalExpRepo.createQueryBuilder('pe')
|
||||
.where('pe.expenseDate >= :periodStart AND pe.expenseDate <= :periodEnd', { periodStart, periodEnd })
|
||||
.getMany();
|
||||
|
||||
const personalMap = new Map<number, number>();
|
||||
const personalItems = new Map<number, any[]>();
|
||||
for (const pe of personalExps) {
|
||||
personalMap.set(pe.studentId, (personalMap.get(pe.studentId) || 0) + Number(pe.amount));
|
||||
if (!personalItems.has(pe.studentId)) personalItems.set(pe.studentId, []);
|
||||
personalItems.get(pe.studentId)!.push({
|
||||
roomId: pe.roomId,
|
||||
expenseType: pe.expenseType,
|
||||
description: `个人费用: ${pe.description || pe.expenseType}`,
|
||||
days: 0,
|
||||
totalRoomDays: 0,
|
||||
roomTotalAmount: pe.amount,
|
||||
studentAmount: pe.amount,
|
||||
});
|
||||
}
|
||||
|
||||
// 合并所有涉及的学生
|
||||
const allStudentIds = new Set([...studentBillData.keys(), ...personalMap.keys()]);
|
||||
|
||||
// 生成账单
|
||||
const bills: Bill[] = [];
|
||||
for (const studentId of allStudentIds) {
|
||||
const shared = studentBillData.get(studentId)?.shared || 0;
|
||||
const personal = personalMap.get(studentId) || 0;
|
||||
const total = Number((shared + personal).toFixed(2));
|
||||
|
||||
const bill = this.billRepo.create({
|
||||
studentId,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
sharedAmount: Number(shared.toFixed(2)),
|
||||
personalAmount: personal,
|
||||
totalAmount: total,
|
||||
status: 'draft',
|
||||
});
|
||||
const savedBill = await this.billRepo.save(bill);
|
||||
|
||||
// 保存明细
|
||||
const items = [
|
||||
...(studentBillData.get(studentId)?.items || []),
|
||||
...(personalItems.get(studentId) || []),
|
||||
];
|
||||
for (const item of items) {
|
||||
await this.itemRepo.save(this.itemRepo.create({ ...item, billId: savedBill.id }));
|
||||
}
|
||||
bills.push(savedBill);
|
||||
}
|
||||
|
||||
return { message: `成功生成 ${bills.length} 条账单`, count: bills.length, bills };
|
||||
}
|
||||
|
||||
async findAll(query?: { periodStart?: string; periodEnd?: string; studentId?: number; status?: string }) {
|
||||
const qb = this.billRepo.createQueryBuilder('b')
|
||||
.leftJoinAndSelect('b.student', 'student')
|
||||
.orderBy('b.generatedAt', 'DESC');
|
||||
if (query?.periodStart) qb.andWhere('b.periodStart = :ps', { ps: query.periodStart });
|
||||
if (query?.periodEnd) qb.andWhere('b.periodEnd = :pe', { pe: query.periodEnd });
|
||||
if (query?.studentId) qb.andWhere('b.studentId = :sid', { sid: query.studentId });
|
||||
if (query?.status) qb.andWhere('b.status = :status', { status: query.status });
|
||||
const bills = await qb.getMany();
|
||||
return this.attachDepositInfo(bills);
|
||||
}
|
||||
|
||||
async findOne(id: number) {
|
||||
const bill = await this.billRepo.findOne({ where: { id }, relations: ['student', 'items'] });
|
||||
if (!bill) throw new NotFoundException('账单不存在');
|
||||
const [withDeposit] = await this.attachDepositInfo([bill]);
|
||||
return withDeposit;
|
||||
}
|
||||
|
||||
/**
|
||||
* 给账单挂上"押金联动"信息:
|
||||
* - availableDeposit: 当前学生处于已缴未退状态(paid)的押金总额
|
||||
* - depositApplied: 本张账单可从押金抵扣的金额(min(押金, 应付总额))
|
||||
* - amountAfterDeposit: 抵扣押金后学生需另外支付的金额
|
||||
*/
|
||||
private async attachDepositInfo(bills: Bill[]): Promise<any[]> {
|
||||
if (!bills || bills.length === 0) return bills;
|
||||
const studentIds = Array.from(new Set(bills.map((b) => b.studentId)));
|
||||
if (studentIds.length === 0) return bills;
|
||||
const deposits = await this.depositRepo.createQueryBuilder('d')
|
||||
.where('d.studentId IN (:...ids)', { ids: studentIds })
|
||||
.andWhere('d.status = :status', { status: 'paid' })
|
||||
.getMany();
|
||||
const depMap = new Map<number, number>();
|
||||
for (const d of deposits) {
|
||||
depMap.set(d.studentId, (depMap.get(d.studentId) || 0) + Number(d.amount || 0));
|
||||
}
|
||||
return bills.map((b) => {
|
||||
const total = Number(b.totalAmount || 0);
|
||||
const available = Number((depMap.get(b.studentId) || 0).toFixed(2));
|
||||
const applied = Number(Math.min(available, total).toFixed(2));
|
||||
const afterDeposit = Number(Math.max(0, total - applied).toFixed(2));
|
||||
return Object.assign({}, b, {
|
||||
availableDeposit: available,
|
||||
depositApplied: applied,
|
||||
amountAfterDeposit: afterDeposit,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async updateStatus(id: number, dto: UpdateBillStatusDto) {
|
||||
const bill = await this.billRepo.findOne({ where: { id } });
|
||||
if (!bill) throw new NotFoundException('账单不存在');
|
||||
bill.status = dto.status;
|
||||
return this.billRepo.save(bill);
|
||||
}
|
||||
|
||||
async batchUpdateStatus(ids: number[], status: string) {
|
||||
await this.billRepo.createQueryBuilder().update().set({ status }).where('id IN (:...ids)', { ids }).execute();
|
||||
return { message: `成功更新 ${ids.length} 条账单状态` };
|
||||
}
|
||||
|
||||
async remove(id: number) {
|
||||
const exists = await this.billRepo.findOne({ where: { id } });
|
||||
if (!exists) throw new NotFoundException('账单不存在');
|
||||
await this.itemRepo.delete({ billId: id });
|
||||
await this.billRepo.delete(id);
|
||||
return { message: '账单已删除' };
|
||||
}
|
||||
|
||||
async batchRemove(ids: number[]) {
|
||||
await this.itemRepo.createQueryBuilder().delete().where('billId IN (:...ids)', { ids }).execute();
|
||||
await this.billRepo.createQueryBuilder().delete().where('id IN (:...ids)', { ids }).execute();
|
||||
return { message: `成功删除 ${ids.length} 条账单` };
|
||||
}
|
||||
}
|
||||
14
apps/server/src/bills/dto/bill.dto.ts
Normal file
14
apps/server/src/bills/dto/bill.dto.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { IsString, IsOptional } from 'class-validator';
|
||||
|
||||
export class GenerateBillsDto {
|
||||
@IsString()
|
||||
periodStart: string; // YYYY-MM-DD
|
||||
|
||||
@IsString()
|
||||
periodEnd: string; // YYYY-MM-DD
|
||||
}
|
||||
|
||||
export class UpdateBillStatusDto {
|
||||
@IsString()
|
||||
status: 'draft' | 'confirmed' | 'paid';
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards, Request, Res, UseInterceptors, UploadedFile, BadRequestException } from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import type { Response } from 'express';
|
||||
import * as fs from 'fs';
|
||||
import { ClassroomRentalsService } from './classroom-rentals.service';
|
||||
import { CreateRentalDto, UpdateRentalDto } from './dto/rental.dto';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
||||
import { extractRequestInfo } from '../common/request-utils';
|
||||
import { RequirePermission } from '../auth/decorators/permission.decorator';
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('classroom-rentals')
|
||||
export class ClassroomRentalsController {
|
||||
constructor(private service: ClassroomRentalsService, private logService: OperationLogsService) {}
|
||||
|
||||
@Get()
|
||||
@RequirePermission('rental:view')
|
||||
findAll(
|
||||
@Query('classroomId') classroomId?: string,
|
||||
@Query('tenantId') tenantId?: string,
|
||||
@Query('month') month?: string,
|
||||
@Query('includeEnded') includeEnded?: string,
|
||||
) {
|
||||
return this.service.findAll({
|
||||
classroomId: classroomId ? +classroomId : undefined,
|
||||
tenantId: tenantId ? +tenantId : undefined,
|
||||
month,
|
||||
includeEnded: includeEnded === 'true',
|
||||
});
|
||||
}
|
||||
|
||||
@Get('schedule')
|
||||
@RequirePermission('rental:view')
|
||||
getSchedule(@Query('year') year?: string, @Query('month') month?: string) {
|
||||
const now = new Date();
|
||||
const y = year ? +year : now.getFullYear();
|
||||
const m = month ? +month : now.getMonth() + 1;
|
||||
if (m < 1 || m > 12) throw new BadRequestException('月份必须在 1-12 之间');
|
||||
return this.service.getSchedule(y, m);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@RequirePermission('rental:view')
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.service.findOne(+id);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@RequirePermission('rental:create')
|
||||
async create(@Body() dto: CreateRentalDto, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.create(dto, req.user?.id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id, username: req.user?.username,
|
||||
module: '教室租赁', action: '新增租赁', targetId: result.id, targetType: 'classroom-rental',
|
||||
detail: `教室${dto.classroomId} 租赁方${dto.tenantId} ${dto.startDate}~${dto.endDate}`,
|
||||
ipAddress, userAgent,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
@RequirePermission('rental:edit')
|
||||
async update(@Param('id') id: string, @Body() dto: UpdateRentalDto, @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: 'classroom-rental',
|
||||
detail: JSON.stringify(dto), ipAddress, userAgent,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@RequirePermission('rental:delete')
|
||||
async remove(@Param('id') id: string, @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: 'classroom-rental',
|
||||
ipAddress, userAgent,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
// 合同上传:multer 限制 10MB + 仅 PDF
|
||||
@Post(':id/contract')
|
||||
@RequirePermission('rental:edit')
|
||||
@UseInterceptors(FileInterceptor('file', {
|
||||
limits: { fileSize: 10 * 1024 * 1024 },
|
||||
fileFilter: (_req, file, cb) => {
|
||||
if (file.mimetype !== 'application/pdf') {
|
||||
return cb(new BadRequestException('仅支持 PDF 文件'), false);
|
||||
}
|
||||
cb(null, true);
|
||||
},
|
||||
}))
|
||||
async uploadContract(@Param('id') id: string, @UploadedFile() file: Express.Multer.File, @Request() req: any) {
|
||||
if (!file) throw new BadRequestException('请上传合同文件');
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.attachContract(+id, file);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id, username: req.user?.username,
|
||||
module: '教室租赁', action: '上传合同', targetId: +id, targetType: 'classroom-rental',
|
||||
detail: file.originalname, ipAddress, userAgent,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@Get(':id/contract')
|
||||
@RequirePermission('rental:view')
|
||||
async downloadContract(@Param('id') id: string, @Res() res: Response) {
|
||||
const { fullPath, originalName } = await this.service.getContractPath(+id);
|
||||
res.setHeader('Content-Type', 'application/pdf');
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(originalName)}"`);
|
||||
const stream = fs.createReadStream(fullPath);
|
||||
stream.pipe(res);
|
||||
}
|
||||
|
||||
@Delete(':id/contract')
|
||||
@RequirePermission('rental:edit')
|
||||
async deleteContract(@Param('id') id: string, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.removeContract(+id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id, username: req.user?.username,
|
||||
module: '教室租赁', action: '删除合同', targetId: +id, targetType: 'classroom-rental',
|
||||
ipAddress, userAgent,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { ClassroomRental } from '../entities/classroom-rental.entity';
|
||||
import { Classroom } from '../entities/classroom.entity';
|
||||
import { Tenant } from '../entities/tenant.entity';
|
||||
import { ClassroomRentalsService } from './classroom-rentals.service';
|
||||
import { ClassroomRentalsController } from './classroom-rentals.controller';
|
||||
import { OperationLogsModule } from '../operation-logs/operation-logs.module';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([ClassroomRental, Classroom, Tenant]), OperationLogsModule],
|
||||
controllers: [ClassroomRentalsController],
|
||||
providers: [ClassroomRentalsService],
|
||||
exports: [ClassroomRentalsService],
|
||||
})
|
||||
export class ClassroomRentalsModule {}
|
||||
252
apps/server/src/classroom-rentals/classroom-rentals.service.ts
Normal file
252
apps/server/src/classroom-rentals/classroom-rentals.service.ts
Normal file
@@ -0,0 +1,252 @@
|
||||
import { Injectable, NotFoundException, BadRequestException, ConflictException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, Not } from 'typeorm';
|
||||
import { ClassroomRental } from '../entities/classroom-rental.entity';
|
||||
import { Classroom } from '../entities/classroom.entity';
|
||||
import { Tenant } from '../entities/tenant.entity';
|
||||
import { CreateRentalDto, UpdateRentalDto } from './dto/rental.dto';
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs';
|
||||
|
||||
// 预设色板(与 tenants.service 保持一致,作为颜色兜底)
|
||||
const COLOR_PALETTE = [
|
||||
'#ff7875', '#ffa940', '#ffc53d', '#73d13d', '#36cfc9',
|
||||
'#40a9ff', '#597ef7', '#9254de', '#f759ab', '#8c8c8c',
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
export class ClassroomRentalsService {
|
||||
constructor(
|
||||
@InjectRepository(ClassroomRental) private repo: Repository<ClassroomRental>,
|
||||
@InjectRepository(Classroom) private classroomRepo: Repository<Classroom>,
|
||||
@InjectRepository(Tenant) private tenantRepo: Repository<Tenant>,
|
||||
) {}
|
||||
|
||||
get uploadDir(): string {
|
||||
const base = process.env.UPLOAD_DIR || './uploads';
|
||||
return path.resolve(base, 'contracts');
|
||||
}
|
||||
|
||||
ensureUploadDir() {
|
||||
if (!fs.existsSync(this.uploadDir)) {
|
||||
fs.mkdirSync(this.uploadDir, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
async findAll(query?: { classroomId?: number; tenantId?: number; month?: string; includeEnded?: boolean }) {
|
||||
const qb = this.repo.createQueryBuilder('r')
|
||||
.leftJoinAndSelect('r.classroom', 'classroom')
|
||||
.leftJoinAndSelect('r.tenant', 'tenant')
|
||||
.orderBy('r.startDate', 'DESC');
|
||||
if (query?.classroomId) qb.andWhere('r.classroomId = :cid', { cid: query.classroomId });
|
||||
if (query?.tenantId) qb.andWhere('r.tenantId = :tid', { tid: query.tenantId });
|
||||
if (query?.month) {
|
||||
// month 格式 2026-06,查询当月有重叠的租赁
|
||||
const [y, m] = query.month.split('-').map(Number);
|
||||
const first = `${y}-${String(m).padStart(2, '0')}-01`;
|
||||
const lastDay = new Date(y, m, 0).getDate();
|
||||
const last = `${y}-${String(m).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`;
|
||||
qb.andWhere('r.startDate <= :last AND r.endDate >= :first', { first, last });
|
||||
}
|
||||
if (!query?.includeEnded) qb.andWhere('r.status != :cancelled', { cancelled: 'cancelled' });
|
||||
return qb.getMany();
|
||||
}
|
||||
|
||||
async findOne(id: number) {
|
||||
const rental = await this.repo.findOne({ where: { id }, relations: ['classroom', 'tenant'] });
|
||||
if (!rental) throw new NotFoundException('租赁订单不存在');
|
||||
return rental;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找与给定区间冲突的租赁订单
|
||||
* 重叠判定:start1 <= end2 AND start2 <= end1
|
||||
*/
|
||||
async findConflicts(classroomId: number, startDate: string, endDate: string, excludeId?: number) {
|
||||
const qb = this.repo.createQueryBuilder('r')
|
||||
.leftJoinAndSelect('r.tenant', 'tenant')
|
||||
.where('r.classroomId = :cid', { cid: classroomId })
|
||||
.andWhere('r.status != :cancelled', { cancelled: 'cancelled' })
|
||||
.andWhere('r.startDate <= :end', { end: endDate })
|
||||
.andWhere('r.endDate >= :start', { start: startDate });
|
||||
if (excludeId) qb.andWhere('r.id != :excludeId', { excludeId });
|
||||
return qb.getMany();
|
||||
}
|
||||
|
||||
async create(dto: CreateRentalDto, userId?: number) {
|
||||
if (dto.startDate > dto.endDate) throw new BadRequestException('起始日期不能晚于结束日期');
|
||||
const classroom = await this.classroomRepo.findOne({ where: { id: dto.classroomId } });
|
||||
if (!classroom) throw new NotFoundException('教室不存在');
|
||||
const tenant = await this.tenantRepo.findOne({ where: { id: dto.tenantId } });
|
||||
if (!tenant) throw new NotFoundException('租赁方不存在');
|
||||
|
||||
const conflicts = await this.findConflicts(dto.classroomId, dto.startDate, dto.endDate);
|
||||
if (conflicts.length > 0) {
|
||||
throw new ConflictException({
|
||||
message: '该教室在此时间段已有租赁',
|
||||
conflicts: conflicts.map(c => ({ id: c.id, startDate: c.startDate, endDate: c.endDate, tenantName: c.tenant?.name })),
|
||||
});
|
||||
}
|
||||
return this.repo.save(this.repo.create({ ...dto, createdBy: userId, status: 'active' }));
|
||||
}
|
||||
|
||||
async update(id: number, dto: UpdateRentalDto) {
|
||||
const rental = await this.findOne(id);
|
||||
// 若修改了教室/日期,重新冲突检查
|
||||
const newClassroomId = dto.classroomId ?? rental.classroomId;
|
||||
const newStart = dto.startDate ?? rental.startDate;
|
||||
const newEnd = dto.endDate ?? rental.endDate;
|
||||
if (newStart > newEnd) throw new BadRequestException('起始日期不能晚于结束日期');
|
||||
if (dto.classroomId || dto.startDate || dto.endDate) {
|
||||
const conflicts = await this.findConflicts(newClassroomId, newStart, newEnd, id);
|
||||
if (conflicts.length > 0) {
|
||||
throw new ConflictException({
|
||||
message: '修改后时间段与已有租赁冲突',
|
||||
conflicts: conflicts.map(c => ({ id: c.id, startDate: c.startDate, endDate: c.endDate, tenantName: c.tenant?.name })),
|
||||
});
|
||||
}
|
||||
}
|
||||
await this.repo.update(id, dto);
|
||||
return this.findOne(id);
|
||||
}
|
||||
|
||||
async remove(id: number) {
|
||||
const rental = await this.findOne(id);
|
||||
// 同时删除合同文件
|
||||
if (rental.contractPath) {
|
||||
const full = path.join(this.uploadDir, rental.contractPath);
|
||||
if (fs.existsSync(full)) {
|
||||
try { fs.unlinkSync(full); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
await this.repo.delete(id);
|
||||
return { message: '删除成功' };
|
||||
}
|
||||
|
||||
async attachContract(id: number, file: Express.Multer.File) {
|
||||
const rental = await this.findOne(id);
|
||||
this.ensureUploadDir();
|
||||
// 安全校验:MIME + 扩展名
|
||||
if (file.mimetype !== 'application/pdf') {
|
||||
throw new BadRequestException('仅支持 PDF 文件');
|
||||
}
|
||||
const ext = path.extname(file.originalname).toLowerCase();
|
||||
if (ext !== '.pdf') throw new BadRequestException('文件扩展名必须为 .pdf');
|
||||
// UUID 文件名
|
||||
const uuid = (globalThis as any).crypto?.randomUUID?.() || require('crypto').randomBytes(16).toString('hex');
|
||||
const filename = `${uuid}.pdf`;
|
||||
const fullPath = path.join(this.uploadDir, filename);
|
||||
// 路径遍历防护
|
||||
if (!fullPath.startsWith(this.uploadDir)) throw new BadRequestException('路径非法');
|
||||
// 删除旧文件
|
||||
if (rental.contractPath) {
|
||||
const oldPath = path.join(this.uploadDir, rental.contractPath);
|
||||
if (fs.existsSync(oldPath)) {
|
||||
try { fs.unlinkSync(oldPath); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
fs.writeFileSync(fullPath, file.buffer);
|
||||
await this.repo.update(id, {
|
||||
contractPath: filename,
|
||||
contractOriginalName: file.originalname,
|
||||
});
|
||||
return this.findOne(id);
|
||||
}
|
||||
|
||||
async removeContract(id: number) {
|
||||
const rental = await this.findOne(id);
|
||||
if (!rental.contractPath) throw new BadRequestException('该租赁未上传合同');
|
||||
const fullPath = path.join(this.uploadDir, rental.contractPath);
|
||||
if (fs.existsSync(fullPath)) {
|
||||
try { fs.unlinkSync(fullPath); } catch { /* ignore */ }
|
||||
}
|
||||
await this.repo.update(id, { contractPath: null as any, contractOriginalName: null as any });
|
||||
return { message: '合同已删除' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取合同文件的绝对路径(供控制器流式返回),严格校验路径安全
|
||||
*/
|
||||
async getContractPath(id: number): Promise<{ fullPath: string; originalName: string }> {
|
||||
const rental = await this.findOne(id);
|
||||
if (!rental.contractPath) throw new NotFoundException('该租赁未上传合同');
|
||||
const fullPath = path.join(this.uploadDir, rental.contractPath);
|
||||
if (!fullPath.startsWith(this.uploadDir)) throw new BadRequestException('路径非法');
|
||||
if (!fs.existsSync(fullPath)) throw new NotFoundException('合同文件丢失');
|
||||
return { fullPath, originalName: rental.contractOriginalName || 'contract.pdf' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取月度排期矩阵
|
||||
*/
|
||||
async getSchedule(year: number, month: number) {
|
||||
const lastDay = new Date(year, month, 0).getDate();
|
||||
const first = `${year}-${String(month).padStart(2, '0')}-01`;
|
||||
const last = `${year}-${String(month).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`;
|
||||
|
||||
const classrooms = await this.classroomRepo.find({
|
||||
where: { status: Not('archived') },
|
||||
order: { building: 'ASC', name: 'ASC' },
|
||||
});
|
||||
const rentals = await this.repo.createQueryBuilder('r')
|
||||
.leftJoinAndSelect('r.tenant', 'tenant')
|
||||
.leftJoinAndSelect('r.classroom', 'classroom')
|
||||
.where('r.status != :cancelled', { cancelled: 'cancelled' })
|
||||
.andWhere('r.startDate <= :last AND r.endDate >= :first', { first, last })
|
||||
.getMany();
|
||||
|
||||
const tenantMap = new Map<number, any>();
|
||||
const matrix: Record<number, Record<number, any>> = {};
|
||||
const summary: Record<number, { totalDays: number; rentedDays: number; idleDays: number; occupancyRate: number }> = {};
|
||||
|
||||
for (const cls of classrooms) {
|
||||
matrix[cls.id] = {};
|
||||
summary[cls.id] = { totalDays: lastDay, rentedDays: 0, idleDays: lastDay, occupancyRate: 0 };
|
||||
}
|
||||
|
||||
for (const rental of rentals) {
|
||||
const start = new Date(rental.startDate);
|
||||
const end = new Date(rental.endDate);
|
||||
const monthStart = new Date(first);
|
||||
const monthEnd = new Date(last);
|
||||
const effStart = start < monthStart ? monthStart : start;
|
||||
const effEnd = end > monthEnd ? monthEnd : end;
|
||||
if (rental.tenant && !tenantMap.has(rental.tenant.id)) {
|
||||
tenantMap.set(rental.tenant.id, {
|
||||
id: rental.tenant.id,
|
||||
name: rental.tenant.name,
|
||||
color: rental.tenant.color || COLOR_PALETTE[rental.tenant.id % COLOR_PALETTE.length],
|
||||
});
|
||||
}
|
||||
for (let d = new Date(effStart); d <= effEnd; d.setDate(d.getDate() + 1)) {
|
||||
const day = d.getDate();
|
||||
if (!matrix[rental.classroomId]) continue;
|
||||
matrix[rental.classroomId][day] = {
|
||||
rentalId: rental.id,
|
||||
tenantId: rental.tenantId,
|
||||
tenantName: rental.tenant?.name || '未知',
|
||||
color: rental.tenant?.color || COLOR_PALETTE[(rental.tenantId || 0) % COLOR_PALETTE.length],
|
||||
hasContract: !!rental.contractPath,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 统计
|
||||
for (const cls of classrooms) {
|
||||
const rented = Object.keys(matrix[cls.id]).length;
|
||||
summary[cls.id].rentedDays = rented;
|
||||
summary[cls.id].idleDays = lastDay - rented;
|
||||
summary[cls.id].occupancyRate = lastDay > 0 ? Math.round((rented / lastDay) * 100) / 100 : 0;
|
||||
}
|
||||
|
||||
return {
|
||||
year,
|
||||
month,
|
||||
days: lastDay,
|
||||
classrooms: classrooms.map(c => ({ id: c.id, name: c.name, building: c.building, floor: c.floor, roomType: c.roomType, capacity: c.capacity, supervisor: c.supervisor })),
|
||||
tenants: Array.from(tenantMap.values()),
|
||||
matrix,
|
||||
summary,
|
||||
};
|
||||
}
|
||||
}
|
||||
61
apps/server/src/classroom-rentals/dto/rental.dto.ts
Normal file
61
apps/server/src/classroom-rentals/dto/rental.dto.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { IsOptional, IsString, IsNotEmpty, IsInt, IsNumber, IsEnum, IsDateString } from 'class-validator';
|
||||
|
||||
export class CreateRentalDto {
|
||||
@IsInt()
|
||||
classroomId: number;
|
||||
|
||||
@IsInt()
|
||||
tenantId: number;
|
||||
|
||||
@IsDateString()
|
||||
startDate: string;
|
||||
|
||||
@IsDateString()
|
||||
endDate: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
dailyRate?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
totalAmount?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export class UpdateRentalDto {
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
classroomId?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
tenantId?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
startDate?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
endDate?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
dailyRate?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
totalAmount?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(['active', 'ended', 'cancelled'])
|
||||
status?: string;
|
||||
}
|
||||
132
apps/server/src/classrooms/classrooms.controller.ts
Normal file
132
apps/server/src/classrooms/classrooms.controller.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards, Request, Res, UseInterceptors, UploadedFile } from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import type { Response } from 'express';
|
||||
import { ClassroomsService } from './classrooms.service';
|
||||
import { CreateClassroomDto, UpdateClassroomDto } from './dto/classroom.dto';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
||||
import { extractRequestInfo } from '../common/request-utils';
|
||||
import { RequirePermission } from '../auth/decorators/permission.decorator';
|
||||
import * as ExcelJS from 'exceljs';
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('classrooms')
|
||||
export class ClassroomsController {
|
||||
constructor(private service: ClassroomsService, private logService: OperationLogsService) {}
|
||||
|
||||
@Get()
|
||||
@RequirePermission('classroom:view')
|
||||
findAll(@Query('building') building?: string, @Query('roomType') roomType?: string, @Query('includeArchived') includeArchived?: string) {
|
||||
return this.service.findAll({
|
||||
building,
|
||||
roomType,
|
||||
includeArchived: includeArchived === 'true',
|
||||
});
|
||||
}
|
||||
|
||||
@Get('template')
|
||||
@RequirePermission('classroom:view')
|
||||
async downloadTemplate(@Res() res: Response) {
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const ws = workbook.addWorksheet('教室导入模板');
|
||||
ws.columns = [
|
||||
{ header: '教室名', key: 'name', width: 15 },
|
||||
{ header: '楼栋', key: 'building', width: 12 },
|
||||
{ header: '楼层', key: 'floor', width: 8 },
|
||||
{ header: '类型', key: 'roomType', width: 10 },
|
||||
{ header: '容量', key: 'capacity', width: 10 },
|
||||
{ header: '课程类型', key: 'courseType', width: 16 },
|
||||
{ header: '负责人', key: 'supervisor', width: 12 },
|
||||
];
|
||||
ws.getRow(1).font = { bold: true };
|
||||
ws.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
|
||||
ws.addRow({ name: 'A201', building: 'A座', floor: 2, roomType: '大', capacity: 60, courseType: '尊享培优班', supervisor: '张老师' });
|
||||
ws.addRow({ name: 'B301', building: 'B座', floor: 3, roomType: '次大', capacity: 40, courseType: '专业课集训班', supervisor: '李老师' });
|
||||
ws.addRow({ name: 'B405', building: 'B座', floor: 4, roomType: '小', capacity: 20, courseType: '', supervisor: '' });
|
||||
|
||||
// 说明sheet
|
||||
const ws2 = workbook.addWorksheet('使用说明');
|
||||
ws2.columns = [{ header: '说明', key: 'note', width: 80 }];
|
||||
ws2.getRow(1).font = { bold: true };
|
||||
[
|
||||
'1. 教室名必填,建议采用「楼栋+房号」如 A201、B301',
|
||||
'2. 类型可填 大 / 次大 / 小,为空默认「大」',
|
||||
'3. 同名教室会自动跳过(不覆盖)',
|
||||
'4. 课程类型可填尊享培优班、专业课集训班等产品班级',
|
||||
'5. 负责人为班主任/对接人',
|
||||
].forEach((note) => ws2.addRow({ note }));
|
||||
|
||||
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=classroom_template.xlsx');
|
||||
await workbook.xlsx.write(res);
|
||||
res.end();
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@RequirePermission('classroom:view')
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.service.findOne(+id);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@RequirePermission('classroom:create')
|
||||
async create(@Body() dto: CreateClassroomDto, @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: 'classroom', detail: dto.name, ipAddress, userAgent });
|
||||
return result;
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
@RequirePermission('classroom:edit')
|
||||
async update(@Param('id') id: string, @Body() dto: UpdateClassroomDto, @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: 'classroom', detail: JSON.stringify(dto), ipAddress, userAgent });
|
||||
return result;
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@RequirePermission('classroom:delete')
|
||||
async remove(@Param('id') id: string, @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: 'classroom', ipAddress, userAgent });
|
||||
return result;
|
||||
}
|
||||
|
||||
@Put(':id/restore')
|
||||
@RequirePermission('classroom:edit')
|
||||
async restore(@Param('id') id: string, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.restore(+id);
|
||||
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '教室', action: '恢复教室', targetId: +id, targetType: 'classroom', ipAddress, userAgent });
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post('import')
|
||||
@RequirePermission('classroom:create')
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
async importExcel(@UploadedFile() file: Express.Multer.File, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
await workbook.xlsx.load(file.buffer as any);
|
||||
const ws = workbook.worksheets[0];
|
||||
const rows: any[] = [];
|
||||
ws.eachRow((row, idx) => {
|
||||
if (idx === 1) return;
|
||||
rows.push({
|
||||
name: String(row.getCell(1).value || ''),
|
||||
building: String(row.getCell(2).value || '') || undefined,
|
||||
floor: Number(row.getCell(3).value) || undefined,
|
||||
roomType: String(row.getCell(4).value || '') || undefined,
|
||||
capacity: Number(row.getCell(5).value) || undefined,
|
||||
courseType: String(row.getCell(6).value || '') || undefined,
|
||||
supervisor: String(row.getCell(7).value || '') || undefined,
|
||||
});
|
||||
});
|
||||
const result = await this.service.batchImport(rows);
|
||||
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '教室', action: '批量导入', detail: result.message, ipAddress, userAgent });
|
||||
return result;
|
||||
}
|
||||
}
|
||||
15
apps/server/src/classrooms/classrooms.module.ts
Normal file
15
apps/server/src/classrooms/classrooms.module.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Classroom } from '../entities/classroom.entity';
|
||||
import { ClassroomRental } from '../entities/classroom-rental.entity';
|
||||
import { ClassroomsService } from './classrooms.service';
|
||||
import { ClassroomsController } from './classrooms.controller';
|
||||
import { OperationLogsModule } from '../operation-logs/operation-logs.module';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Classroom, ClassroomRental]), OperationLogsModule],
|
||||
controllers: [ClassroomsController],
|
||||
providers: [ClassroomsService],
|
||||
exports: [ClassroomsService],
|
||||
})
|
||||
export class ClassroomsModule {}
|
||||
78
apps/server/src/classrooms/classrooms.service.ts
Normal file
78
apps/server/src/classrooms/classrooms.service.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, Not } from 'typeorm';
|
||||
import { Classroom } from '../entities/classroom.entity';
|
||||
import { ClassroomRental } from '../entities/classroom-rental.entity';
|
||||
import { CreateClassroomDto, UpdateClassroomDto } from './dto/classroom.dto';
|
||||
|
||||
@Injectable()
|
||||
export class ClassroomsService {
|
||||
constructor(
|
||||
@InjectRepository(Classroom) private repo: Repository<Classroom>,
|
||||
@InjectRepository(ClassroomRental) private rentalRepo: Repository<ClassroomRental>,
|
||||
) {}
|
||||
|
||||
async findAll(query?: { building?: string; roomType?: string; includeArchived?: boolean }) {
|
||||
const where: any = {};
|
||||
if (query?.building) where.building = query.building;
|
||||
if (query?.roomType) where.roomType = query.roomType;
|
||||
if (!query?.includeArchived) where.status = Not('archived');
|
||||
return this.repo.find({ where, order: { building: 'ASC', name: 'ASC' } });
|
||||
}
|
||||
|
||||
async findOne(id: number) {
|
||||
const cls = await this.repo.findOne({ where: { id } });
|
||||
if (!cls) throw new NotFoundException('教室不存在');
|
||||
return cls;
|
||||
}
|
||||
|
||||
async create(dto: CreateClassroomDto) {
|
||||
const exists = await this.repo.findOne({ where: { name: dto.name } });
|
||||
if (exists) throw new BadRequestException(`教室 ${dto.name} 已存在`);
|
||||
return this.repo.save(this.repo.create(dto));
|
||||
}
|
||||
|
||||
async update(id: number, dto: UpdateClassroomDto) {
|
||||
await this.findOne(id);
|
||||
await this.repo.update(id, dto);
|
||||
return this.repo.findOne({ where: { id } });
|
||||
}
|
||||
|
||||
async remove(id: number) {
|
||||
await this.findOne(id);
|
||||
// 若存在未结束的租赁订单,不允许归档
|
||||
const active = await this.rentalRepo.count({ where: { classroomId: id, status: 'active' } });
|
||||
if (active > 0) throw new BadRequestException('该教室存在进行中的租赁订单,无法归档');
|
||||
await this.repo.update(id, { status: 'archived' });
|
||||
return { message: '已归档' };
|
||||
}
|
||||
|
||||
async restore(id: number) {
|
||||
const cls = await this.findOne(id);
|
||||
if (cls.status !== 'archived') throw new BadRequestException('该教室未被归档');
|
||||
await this.repo.update(id, { status: 'available' });
|
||||
return { message: '已恢复' };
|
||||
}
|
||||
|
||||
async batchImport(rows: { name: string; building?: string; floor?: number; capacity?: number; roomType?: string; courseType?: string; supervisor?: string }[]) {
|
||||
let imported = 0;
|
||||
let skipped = 0;
|
||||
for (const row of rows) {
|
||||
if (!row.name || !row.name.trim()) { skipped++; continue; }
|
||||
const name = row.name.trim();
|
||||
const exists = await this.repo.findOne({ where: { name } });
|
||||
if (exists) { skipped++; continue; }
|
||||
await this.repo.save(this.repo.create({
|
||||
name,
|
||||
building: row.building?.trim() || undefined,
|
||||
floor: row.floor || undefined,
|
||||
capacity: row.capacity || 30,
|
||||
roomType: row.roomType?.trim() || '大',
|
||||
courseType: row.courseType?.trim() || undefined,
|
||||
supervisor: row.supervisor?.trim() || undefined,
|
||||
}));
|
||||
imported++;
|
||||
}
|
||||
return { message: `成功导入 ${imported} 间教室,跳过 ${skipped} 条(重复或空行)`, imported, skipped };
|
||||
}
|
||||
}
|
||||
73
apps/server/src/classrooms/dto/classroom.dto.ts
Normal file
73
apps/server/src/classrooms/dto/classroom.dto.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { IsOptional, IsString, IsNotEmpty, IsInt, IsEnum } from 'class-validator';
|
||||
|
||||
export class CreateClassroomDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
building?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
floor?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
capacity?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
roomType?: string; // 大 / 次大 / 小
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
courseType?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
supervisor?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export class UpdateClassroomDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
name?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
building?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
floor?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
capacity?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
roomType?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
courseType?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
supervisor?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(['available', 'archived'])
|
||||
status?: string;
|
||||
}
|
||||
9
apps/server/src/common/request-utils.ts
Normal file
9
apps/server/src/common/request-utils.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* 从请求对象中提取客户端 IP 和 UserAgent
|
||||
*/
|
||||
export function extractRequestInfo(req: any): { ipAddress: string; userAgent: string } {
|
||||
const forwarded = req.headers?.['x-forwarded-for'] || req.headers?.['x-real-ip'] || req.connection?.remoteAddress || '';
|
||||
const ipAddress = String(forwarded).split(',')[0].trim() || 'unknown';
|
||||
const userAgent = (req.headers?.['user-agent'] || '').substring(0, 500);
|
||||
return { ipAddress, userAgent };
|
||||
}
|
||||
41
apps/server/src/dashboard/dashboard.controller.ts
Normal file
41
apps/server/src/dashboard/dashboard.controller.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
|
||||
import { DashboardService } from './dashboard.service';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RequirePermission } from '../auth/decorators/permission.decorator';
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@RequirePermission('dashboard:view')
|
||||
@Controller('dashboard')
|
||||
export class DashboardController {
|
||||
constructor(private service: DashboardService) {}
|
||||
|
||||
@Get('stats')
|
||||
getStats() {
|
||||
return this.service.getStats();
|
||||
}
|
||||
|
||||
@Get('gantt')
|
||||
getGanttData(
|
||||
@Query('periodStart') periodStart?: string,
|
||||
@Query('periodEnd') periodEnd?: string,
|
||||
@Query('building') building?: string,
|
||||
) {
|
||||
return this.service.getGanttData({ periodStart, periodEnd, building });
|
||||
}
|
||||
|
||||
@Get('expense-stats')
|
||||
getExpenseStats(
|
||||
@Query('periodStart') periodStart?: string,
|
||||
@Query('periodEnd') periodEnd?: string,
|
||||
) {
|
||||
return this.service.getExpenseStats(periodStart, periodEnd);
|
||||
}
|
||||
|
||||
@Get('room-ranking')
|
||||
getRoomExpenseRanking(
|
||||
@Query('periodStart') periodStart?: string,
|
||||
@Query('periodEnd') periodEnd?: string,
|
||||
) {
|
||||
return this.service.getRoomExpenseRanking(periodStart, periodEnd);
|
||||
}
|
||||
}
|
||||
16
apps/server/src/dashboard/dashboard.module.ts
Normal file
16
apps/server/src/dashboard/dashboard.module.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Room } from '../entities/room.entity';
|
||||
import { Student } from '../entities/student.entity';
|
||||
import { Occupancy } from '../entities/occupancy.entity';
|
||||
import { Bill } from '../entities/bill.entity';
|
||||
import { RoomExpense } from '../entities/room-expense.entity';
|
||||
import { DashboardService } from './dashboard.service';
|
||||
import { DashboardController } from './dashboard.controller';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Room, Student, Occupancy, Bill, RoomExpense])],
|
||||
controllers: [DashboardController],
|
||||
providers: [DashboardService],
|
||||
})
|
||||
export class DashboardModule {}
|
||||
108
apps/server/src/dashboard/dashboard.service.ts
Normal file
108
apps/server/src/dashboard/dashboard.service.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, IsNull, Not } from 'typeorm';
|
||||
import { Room } from '../entities/room.entity';
|
||||
import { Student } from '../entities/student.entity';
|
||||
import { Occupancy } from '../entities/occupancy.entity';
|
||||
import { Bill } from '../entities/bill.entity';
|
||||
import { RoomExpense } from '../entities/room-expense.entity';
|
||||
|
||||
@Injectable()
|
||||
export class DashboardService {
|
||||
constructor(
|
||||
@InjectRepository(Room) private roomRepo: Repository<Room>,
|
||||
@InjectRepository(Student) private studentRepo: Repository<Student>,
|
||||
@InjectRepository(Occupancy) private occRepo: Repository<Occupancy>,
|
||||
@InjectRepository(Bill) private billRepo: Repository<Bill>,
|
||||
@InjectRepository(RoomExpense) private expRepo: Repository<RoomExpense>,
|
||||
) {}
|
||||
|
||||
async getStats() {
|
||||
const totalRooms = await this.roomRepo.count({ where: { status: Not('archived') } });
|
||||
const totalStudents = await this.studentRepo.count({ where: { status: 'active' } });
|
||||
const occupiedBeds = await this.occRepo.count({ where: { checkOutDate: IsNull() } });
|
||||
const totalCapacity = await this.roomRepo.createQueryBuilder('r')
|
||||
.select('SUM(r.capacity)', 'total')
|
||||
.where('r.status != :archived', { archived: 'archived' })
|
||||
.getRawOne();
|
||||
const cap = totalCapacity?.total || 0;
|
||||
const occupancyRate = cap > 0 ? ((occupiedBeds / cap) * 100).toFixed(1) : 0;
|
||||
|
||||
const billStats = await this.billRepo.createQueryBuilder('b')
|
||||
.select('b.status', 'status')
|
||||
.addSelect('COUNT(*)', 'count')
|
||||
.addSelect('SUM(b.totalAmount)', 'total')
|
||||
.groupBy('b.status')
|
||||
.getRawMany();
|
||||
|
||||
return { totalRooms, totalStudents, occupiedBeds, totalCapacity: cap, occupancyRate, billStats };
|
||||
}
|
||||
|
||||
// 甘特图数据:每个宿舍的入住时间线
|
||||
async getGanttData(query?: { periodStart?: string; periodEnd?: string; building?: string }) {
|
||||
const qb = this.occRepo.createQueryBuilder('o')
|
||||
.leftJoinAndSelect('o.student', 'student')
|
||||
.leftJoinAndSelect('o.room', 'room')
|
||||
.where('room.status != :archived', { archived: 'archived' })
|
||||
.orderBy('room.roomNumber', 'ASC')
|
||||
.addOrderBy('o.checkInDate', 'ASC');
|
||||
|
||||
if (query?.building) {
|
||||
qb.andWhere('room.building = :building', { building: query.building });
|
||||
}
|
||||
if (query?.periodStart) {
|
||||
qb.andWhere('(o.checkOutDate IS NULL OR o.checkOutDate >= :ps)', { ps: query.periodStart });
|
||||
}
|
||||
if (query?.periodEnd) {
|
||||
qb.andWhere('o.checkInDate <= :pe', { pe: query.periodEnd });
|
||||
}
|
||||
|
||||
const records = await qb.getMany();
|
||||
|
||||
// 按宿舍分组
|
||||
const roomMap = new Map<string, any[]>();
|
||||
for (const r of records) {
|
||||
const key = r.room?.roomNumber || String(r.roomId);
|
||||
if (!roomMap.has(key)) roomMap.set(key, []);
|
||||
roomMap.get(key)!.push({
|
||||
studentName: r.student?.name || '未知',
|
||||
studentId: r.studentId,
|
||||
checkInDate: r.checkInDate,
|
||||
checkOutDate: r.checkOutDate,
|
||||
billingStartDate: r.billingStartDate,
|
||||
billingEndDate: r.billingEndDate,
|
||||
});
|
||||
}
|
||||
|
||||
return Array.from(roomMap.entries()).map(([roomNumber, occupancies]) => ({
|
||||
roomNumber,
|
||||
occupancies,
|
||||
}));
|
||||
}
|
||||
|
||||
// 费用统计
|
||||
async getExpenseStats(periodStart?: string, periodEnd?: string) {
|
||||
const qb = this.expRepo.createQueryBuilder('e')
|
||||
.select('e.expenseType', 'type')
|
||||
.addSelect('SUM(e.amount)', 'total')
|
||||
.groupBy('e.expenseType');
|
||||
if (periodStart) qb.andWhere('e.periodStart >= :ps', { ps: periodStart });
|
||||
if (periodEnd) qb.andWhere('e.periodEnd <= :pe', { pe: periodEnd });
|
||||
return qb.getRawMany();
|
||||
}
|
||||
|
||||
// 各宿舍费用排行
|
||||
async getRoomExpenseRanking(periodStart?: string, periodEnd?: string) {
|
||||
const qb = this.expRepo.createQueryBuilder('e')
|
||||
.leftJoin('e.room', 'room')
|
||||
.select('room.roomNumber', 'roomNumber')
|
||||
.addSelect('SUM(e.amount)', 'total')
|
||||
.where('room.status != :archived', { archived: 'archived' })
|
||||
.groupBy('e.roomId')
|
||||
.orderBy('total', 'DESC')
|
||||
.limit(20);
|
||||
if (periodStart) qb.andWhere('e.periodStart >= :ps', { ps: periodStart });
|
||||
if (periodEnd) qb.andWhere('e.periodEnd <= :pe', { pe: periodEnd });
|
||||
return qb.getRawMany();
|
||||
}
|
||||
}
|
||||
55
apps/server/src/deposits/deposits.controller.ts
Normal file
55
apps/server/src/deposits/deposits.controller.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards, Request } from '@nestjs/common';
|
||||
import { DepositsService } from './deposits.service';
|
||||
import { CreateDepositDto, RefundDepositDto } from './dto/deposit.dto';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
||||
import { extractRequestInfo } from '../common/request-utils';
|
||||
import { RequirePermission } from '../auth/decorators/permission.decorator';
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('deposits')
|
||||
export class DepositsController {
|
||||
constructor(private service: DepositsService, private logService: OperationLogsService) {}
|
||||
|
||||
@Get()
|
||||
@RequirePermission('deposit:view')
|
||||
findAll(@Query('studentId') studentId?: string, @Query('status') status?: string) {
|
||||
return this.service.findAll({
|
||||
studentId: studentId ? +studentId : undefined,
|
||||
status: status || undefined,
|
||||
});
|
||||
}
|
||||
|
||||
@Get('stats')
|
||||
@RequirePermission('deposit:view')
|
||||
getStats() {
|
||||
return this.service.getStats();
|
||||
}
|
||||
|
||||
@Post()
|
||||
@RequirePermission('deposit:create')
|
||||
async create(@Body() dto: CreateDepositDto, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.create(dto, req.user?.id);
|
||||
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '押金', action: '收取押金', targetId: result.id, targetType: 'deposit', detail: `学生${dto.studentId} ¥${dto.amount}`, ipAddress, userAgent });
|
||||
return result;
|
||||
}
|
||||
|
||||
@Put(':id/refund')
|
||||
@RequirePermission('deposit:edit')
|
||||
async refund(@Param('id') id: string, @Body() dto: RefundDepositDto, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.refund(+id, dto, req.user?.id);
|
||||
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '押金', action: '退还押金', targetId: +id, targetType: 'deposit', detail: `退还¥${result.refundAmount}, 扣除¥${result.deductionAmount}`, ipAddress, userAgent });
|
||||
return result;
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@RequirePermission('deposit:delete')
|
||||
async remove(@Param('id') id: string, @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: 'deposit', ipAddress, userAgent });
|
||||
return result;
|
||||
}
|
||||
}
|
||||
14
apps/server/src/deposits/deposits.module.ts
Normal file
14
apps/server/src/deposits/deposits.module.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Deposit } from '../entities/deposit.entity';
|
||||
import { DepositsService } from './deposits.service';
|
||||
import { DepositsController } from './deposits.controller';
|
||||
import { OperationLogsModule } from '../operation-logs/operation-logs.module';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Deposit]), OperationLogsModule],
|
||||
controllers: [DepositsController],
|
||||
providers: [DepositsService],
|
||||
exports: [DepositsService],
|
||||
})
|
||||
export class DepositsModule {}
|
||||
66
apps/server/src/deposits/deposits.service.ts
Normal file
66
apps/server/src/deposits/deposits.service.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { Deposit } from '../entities/deposit.entity';
|
||||
import { CreateDepositDto, RefundDepositDto } from './dto/deposit.dto';
|
||||
|
||||
@Injectable()
|
||||
export class DepositsService {
|
||||
constructor(@InjectRepository(Deposit) private repo: Repository<Deposit>) {}
|
||||
|
||||
async findAll(query?: { studentId?: number; status?: string }) {
|
||||
const qb = this.repo.createQueryBuilder('d')
|
||||
.leftJoinAndSelect('d.student', 'student')
|
||||
.orderBy('d.createdAt', 'DESC');
|
||||
if (query?.studentId) qb.andWhere('d.studentId = :studentId', { studentId: query.studentId });
|
||||
if (query?.status) qb.andWhere('d.status = :status', { status: query.status });
|
||||
return qb.getMany();
|
||||
}
|
||||
|
||||
async create(dto: CreateDepositDto, userId?: number) {
|
||||
return this.repo.save(this.repo.create({
|
||||
studentId: dto.studentId,
|
||||
amount: dto.amount,
|
||||
paidDate: dto.paidDate,
|
||||
notes: dto.notes,
|
||||
status: 'paid',
|
||||
recordedBy: userId,
|
||||
}));
|
||||
}
|
||||
|
||||
async refund(id: number, dto: RefundDepositDto, userId?: number) {
|
||||
const deposit = await this.repo.findOne({ where: { id } });
|
||||
if (!deposit) throw new NotFoundException('押金记录不存在');
|
||||
if (deposit.status !== 'paid') throw new BadRequestException('该押金已处理');
|
||||
|
||||
const deduction = dto.deductionAmount || 0;
|
||||
const refundAmount = Number(deposit.amount) - deduction;
|
||||
if (refundAmount < 0) throw new BadRequestException('扣除金额不能大于押金金额');
|
||||
|
||||
deposit.refundDate = dto.refundDate;
|
||||
deposit.deductionAmount = deduction;
|
||||
deposit.deductionReason = dto.deductionReason || '';
|
||||
deposit.refundAmount = refundAmount;
|
||||
deposit.status = deduction > 0 ? (refundAmount > 0 ? 'partial_refund' : 'deducted') : 'refunded';
|
||||
if (dto.notes) deposit.notes = dto.notes;
|
||||
|
||||
return this.repo.save(deposit);
|
||||
}
|
||||
|
||||
async remove(id: number) {
|
||||
const deposit = await this.repo.findOne({ where: { id } });
|
||||
if (!deposit) throw new NotFoundException('押金记录不存在');
|
||||
await this.repo.delete(id);
|
||||
return { message: '删除成功' };
|
||||
}
|
||||
|
||||
async getStats() {
|
||||
const result = await this.repo.createQueryBuilder('d')
|
||||
.select('d.status', 'status')
|
||||
.addSelect('COUNT(*)', 'count')
|
||||
.addSelect('SUM(d.amount)', 'totalAmount')
|
||||
.groupBy('d.status')
|
||||
.getRawMany();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
33
apps/server/src/deposits/dto/deposit.dto.ts
Normal file
33
apps/server/src/deposits/dto/deposit.dto.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { IsInt, IsNumber, IsString, IsOptional } from 'class-validator';
|
||||
|
||||
export class CreateDepositDto {
|
||||
@IsInt()
|
||||
studentId: number;
|
||||
|
||||
@IsNumber()
|
||||
amount: number;
|
||||
|
||||
@IsString()
|
||||
paidDate: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export class RefundDepositDto {
|
||||
@IsString()
|
||||
refundDate: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
deductionAmount?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
deductionReason?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
}
|
||||
36
apps/server/src/entities/bill-item.entity.ts
Normal file
36
apps/server/src/entities/bill-item.entity.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { Bill } from './bill.entity';
|
||||
|
||||
@Entity('bill_items')
|
||||
export class BillItem {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ name: 'bill_id' })
|
||||
billId: number;
|
||||
|
||||
@Column({ name: 'room_id', nullable: true })
|
||||
roomId: number;
|
||||
|
||||
@Column({ name: 'expense_type', length: 20, nullable: true })
|
||||
expenseType: string;
|
||||
|
||||
@Column({ length: 200, nullable: true })
|
||||
description: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
days: number;
|
||||
|
||||
@Column({ name: 'total_room_days', nullable: true })
|
||||
totalRoomDays: number;
|
||||
|
||||
@Column({ name: 'room_total_amount', type: 'decimal', precision: 10, scale: 2, nullable: true })
|
||||
roomTotalAmount: number;
|
||||
|
||||
@Column({ name: 'student_amount', type: 'decimal', precision: 10, scale: 2, nullable: true })
|
||||
studentAmount: number;
|
||||
|
||||
@ManyToOne(() => Bill, (b) => b.items)
|
||||
@JoinColumn({ name: 'bill_id' })
|
||||
bill: Bill;
|
||||
}
|
||||
40
apps/server/src/entities/bill.entity.ts
Normal file
40
apps/server/src/entities/bill.entity.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn, OneToMany } from 'typeorm';
|
||||
import { Student } from './student.entity';
|
||||
import { BillItem } from './bill-item.entity';
|
||||
|
||||
@Entity('bills')
|
||||
export class Bill {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ name: 'student_id' })
|
||||
studentId: number;
|
||||
|
||||
@Column({ name: 'period_start', type: 'date' })
|
||||
periodStart: string;
|
||||
|
||||
@Column({ name: 'period_end', type: 'date' })
|
||||
periodEnd: string;
|
||||
|
||||
@Column({ name: 'shared_amount', type: 'decimal', precision: 10, scale: 2, default: 0 })
|
||||
sharedAmount: number;
|
||||
|
||||
@Column({ name: 'personal_amount', type: 'decimal', precision: 10, scale: 2, default: 0 })
|
||||
personalAmount: number;
|
||||
|
||||
@Column({ name: 'total_amount', type: 'decimal', precision: 10, scale: 2, default: 0 })
|
||||
totalAmount: number;
|
||||
|
||||
@Column({ type: 'varchar', length: 20, default: 'draft' })
|
||||
status: string;
|
||||
|
||||
@CreateDateColumn({ name: 'generated_at' })
|
||||
generatedAt: Date;
|
||||
|
||||
@ManyToOne(() => Student, (s) => s.bills)
|
||||
@JoinColumn({ name: 'student_id' })
|
||||
student: Student;
|
||||
|
||||
@OneToMany(() => BillItem, (bi) => bi.bill)
|
||||
items: BillItem[];
|
||||
}
|
||||
58
apps/server/src/entities/classroom-rental.entity.ts
Normal file
58
apps/server/src/entities/classroom-rental.entity.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn, CreateDateColumn, UpdateDateColumn, Index } from 'typeorm';
|
||||
import { Classroom } from './classroom.entity';
|
||||
import { Tenant } from './tenant.entity';
|
||||
|
||||
@Entity('classroom_rentals')
|
||||
@Index(['classroomId', 'startDate', 'endDate'])
|
||||
export class ClassroomRental {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ name: 'classroom_id' })
|
||||
classroomId: number;
|
||||
|
||||
@ManyToOne(() => Classroom)
|
||||
@JoinColumn({ name: 'classroom_id' })
|
||||
classroom: Classroom;
|
||||
|
||||
@Column({ name: 'tenant_id' })
|
||||
tenantId: number;
|
||||
|
||||
@ManyToOne(() => Tenant)
|
||||
@JoinColumn({ name: 'tenant_id' })
|
||||
tenant: Tenant;
|
||||
|
||||
@Column({ name: 'start_date', type: 'date' })
|
||||
startDate: string;
|
||||
|
||||
@Column({ name: 'end_date', type: 'date' })
|
||||
endDate: string;
|
||||
|
||||
// 合同 PDF 相对路径(相对 UPLOAD_DIR),仅存文件名
|
||||
@Column({ name: 'contract_path', length: 255, nullable: true })
|
||||
contractPath: string;
|
||||
|
||||
@Column({ name: 'contract_original_name', length: 255, nullable: true })
|
||||
contractOriginalName: string;
|
||||
|
||||
@Column({ name: 'daily_rate', type: 'decimal', precision: 10, scale: 2, nullable: true })
|
||||
dailyRate: number;
|
||||
|
||||
@Column({ name: 'total_amount', type: 'decimal', precision: 10, scale: 2, nullable: true })
|
||||
totalAmount: number;
|
||||
|
||||
@Column({ type: 'varchar', length: 20, default: 'active' })
|
||||
status: string; // active / ended / cancelled
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
notes: string;
|
||||
|
||||
@Column({ name: 'created_by', nullable: true })
|
||||
createdBy: number;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn({ name: 'updated_at' })
|
||||
updatedAt: Date;
|
||||
}
|
||||
37
apps/server/src/entities/classroom.entity.ts
Normal file
37
apps/server/src/entities/classroom.entity.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from 'typeorm';
|
||||
|
||||
@Entity('classrooms')
|
||||
export class Classroom {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ length: 50 })
|
||||
name: string;
|
||||
|
||||
@Column({ length: 50, nullable: true })
|
||||
building: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
floor: number;
|
||||
|
||||
@Column({ default: 30 })
|
||||
capacity: number;
|
||||
|
||||
@Column({ name: 'room_type', type: 'varchar', length: 20, default: '大' })
|
||||
roomType: string; // 大 / 次大 / 小
|
||||
|
||||
@Column({ name: 'course_type', length: 50, nullable: true })
|
||||
courseType: string;
|
||||
|
||||
@Column({ length: 50, nullable: true })
|
||||
supervisor: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 20, default: 'available' })
|
||||
status: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
notes: string;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt: Date;
|
||||
}
|
||||
46
apps/server/src/entities/deposit.entity.ts
Normal file
46
apps/server/src/entities/deposit.entity.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { Student } from './student.entity';
|
||||
|
||||
@Entity('deposits')
|
||||
export class Deposit {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ name: 'student_id' })
|
||||
studentId: number;
|
||||
|
||||
@Column({ type: 'decimal', precision: 10, scale: 2, default: 500 })
|
||||
amount: number;
|
||||
|
||||
// paid: 已缴 | refunded: 已退 | deducted: 已扣除(部分或全部)
|
||||
@Column({ type: 'varchar', length: 20, default: 'paid' })
|
||||
status: string;
|
||||
|
||||
@Column({ name: 'paid_date', type: 'date' })
|
||||
paidDate: string;
|
||||
|
||||
@Column({ name: 'refund_date', type: 'date', nullable: true })
|
||||
refundDate: string;
|
||||
|
||||
@Column({ name: 'refund_amount', type: 'decimal', precision: 10, scale: 2, nullable: true })
|
||||
refundAmount: number;
|
||||
|
||||
@Column({ name: 'deduction_amount', type: 'decimal', precision: 10, scale: 2, default: 0 })
|
||||
deductionAmount: number;
|
||||
|
||||
@Column({ name: 'deduction_reason', type: 'text', nullable: true })
|
||||
deductionReason: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
notes: string;
|
||||
|
||||
@Column({ name: 'recorded_by', nullable: true })
|
||||
recordedBy: number;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt: Date;
|
||||
|
||||
@ManyToOne(() => Student, { eager: true })
|
||||
@JoinColumn({ name: 'student_id' })
|
||||
student: Student;
|
||||
}
|
||||
15
apps/server/src/entities/index.ts
Normal file
15
apps/server/src/entities/index.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
export { Student } from './student.entity';
|
||||
export { Room } from './room.entity';
|
||||
export { Occupancy } from './occupancy.entity';
|
||||
export { RoomExpense } from './room-expense.entity';
|
||||
export { PersonalExpense } from './personal-expense.entity';
|
||||
export { Bill } from './bill.entity';
|
||||
export { BillItem } from './bill-item.entity';
|
||||
export { User } from './user.entity';
|
||||
export { OperationLog } from './operation-log.entity';
|
||||
export { Deposit } from './deposit.entity';
|
||||
export { Classroom } from './classroom.entity';
|
||||
export { Tenant } from './tenant.entity';
|
||||
export { ClassroomRental } from './classroom-rental.entity';
|
||||
export { Permission } from './permission.entity';
|
||||
export { Role } from './role.entity';
|
||||
44
apps/server/src/entities/occupancy.entity.ts
Normal file
44
apps/server/src/entities/occupancy.entity.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { Student } from './student.entity';
|
||||
import { Room } from './room.entity';
|
||||
|
||||
@Entity('occupancies')
|
||||
export class Occupancy {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ name: 'student_id' })
|
||||
studentId: number;
|
||||
|
||||
@Column({ name: 'room_id' })
|
||||
roomId: number;
|
||||
|
||||
@Column({ name: 'check_in_date', type: 'date' })
|
||||
checkInDate: string;
|
||||
|
||||
@Column({ name: 'check_out_date', type: 'date', nullable: true })
|
||||
checkOutDate: string;
|
||||
|
||||
@Column({ name: 'billing_start_date', type: 'date' })
|
||||
billingStartDate: string;
|
||||
|
||||
@Column({ name: 'billing_end_date', type: 'date', nullable: true })
|
||||
billingEndDate: string;
|
||||
|
||||
@Column({ name: 'check_out_reason', length: 100, nullable: true })
|
||||
checkOutReason: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
notes: string;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt: Date;
|
||||
|
||||
@ManyToOne(() => Student, (s) => s.occupancies)
|
||||
@JoinColumn({ name: 'student_id' })
|
||||
student: Student;
|
||||
|
||||
@ManyToOne(() => Room, (r) => r.occupancies)
|
||||
@JoinColumn({ name: 'room_id' })
|
||||
room: Room;
|
||||
}
|
||||
40
apps/server/src/entities/operation-log.entity.ts
Normal file
40
apps/server/src/entities/operation-log.entity.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from 'typeorm';
|
||||
|
||||
@Entity('operation_logs')
|
||||
export class OperationLog {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ name: 'user_id', nullable: true })
|
||||
userId: number;
|
||||
|
||||
@Column({ length: 50, nullable: true })
|
||||
username: string;
|
||||
|
||||
@Column({ length: 50 })
|
||||
module: string;
|
||||
|
||||
@Column({ length: 50 })
|
||||
action: string;
|
||||
|
||||
@Column({ name: 'target_id', nullable: true })
|
||||
targetId: number;
|
||||
|
||||
@Column({ name: 'target_type', length: 50, nullable: true })
|
||||
targetType: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
detail: string;
|
||||
|
||||
@Column({ name: 'ip_address', length: 50, nullable: true })
|
||||
ipAddress: string;
|
||||
|
||||
@Column({ name: 'user_agent', length: 500, nullable: true })
|
||||
userAgent: string;
|
||||
|
||||
@Column({ name: 'status', length: 20, nullable: true, default: 'success' })
|
||||
status: string;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt: Date;
|
||||
}
|
||||
19
apps/server/src/entities/permission.entity.ts
Normal file
19
apps/server/src/entities/permission.entity.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
|
||||
|
||||
@Entity('permissions')
|
||||
export class Permission {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ type: 'varchar', length: 50, unique: true })
|
||||
code: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 50 })
|
||||
name: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 30 })
|
||||
group: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 200, nullable: true })
|
||||
description: string;
|
||||
}
|
||||
36
apps/server/src/entities/personal-expense.entity.ts
Normal file
36
apps/server/src/entities/personal-expense.entity.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { Student } from './student.entity';
|
||||
|
||||
@Entity('personal_expenses')
|
||||
export class PersonalExpense {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ name: 'student_id' })
|
||||
studentId: number;
|
||||
|
||||
@Column({ name: 'room_id', nullable: true })
|
||||
roomId: number;
|
||||
|
||||
@Column({ name: 'expense_type', type: 'varchar', length: 20 })
|
||||
expenseType: string;
|
||||
|
||||
@Column({ type: 'decimal', precision: 10, scale: 2 })
|
||||
amount: number;
|
||||
|
||||
@Column({ name: 'expense_date', type: 'date' })
|
||||
expenseDate: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
description: string;
|
||||
|
||||
@Column({ name: 'recorded_by', nullable: true })
|
||||
recordedBy: number;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt: Date;
|
||||
|
||||
@ManyToOne(() => Student, (s) => s.personalExpenses)
|
||||
@JoinColumn({ name: 'student_id' })
|
||||
student: Student;
|
||||
}
|
||||
38
apps/server/src/entities/role.entity.ts
Normal file
38
apps/server/src/entities/role.entity.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, ManyToMany, JoinTable } from 'typeorm';
|
||||
import { Permission } from './permission.entity';
|
||||
import { User } from './user.entity';
|
||||
|
||||
@Entity('roles')
|
||||
export class Role {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ type: 'varchar', length: 30, unique: true })
|
||||
name: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 200, nullable: true })
|
||||
description: string;
|
||||
|
||||
@Column({ name: 'is_system', type: 'boolean', default: false })
|
||||
isSystem: boolean;
|
||||
|
||||
@Column({ type: 'tinyint', default: 1 })
|
||||
status: number;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn({ name: 'updated_at' })
|
||||
updatedAt: Date;
|
||||
|
||||
@ManyToMany(() => Permission)
|
||||
@JoinTable({
|
||||
name: 'role_permissions',
|
||||
joinColumn: { name: 'role_id', referencedColumnName: 'id' },
|
||||
inverseJoinColumn: { name: 'permission_id', referencedColumnName: 'id' },
|
||||
})
|
||||
permissions: Permission[];
|
||||
|
||||
@ManyToMany(() => User, (user) => user.roles)
|
||||
users: User[];
|
||||
}
|
||||
36
apps/server/src/entities/room-expense.entity.ts
Normal file
36
apps/server/src/entities/room-expense.entity.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { Room } from './room.entity';
|
||||
|
||||
@Entity('room_expenses')
|
||||
export class RoomExpense {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ name: 'room_id' })
|
||||
roomId: number;
|
||||
|
||||
@Column({ name: 'expense_type', type: 'varchar', length: 20 })
|
||||
expenseType: string;
|
||||
|
||||
@Column({ type: 'decimal', precision: 10, scale: 2 })
|
||||
amount: number;
|
||||
|
||||
@Column({ name: 'period_start', type: 'date' })
|
||||
periodStart: string;
|
||||
|
||||
@Column({ name: 'period_end', type: 'date' })
|
||||
periodEnd: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
description: string;
|
||||
|
||||
@Column({ name: 'recorded_by', nullable: true })
|
||||
recordedBy: number;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt: Date;
|
||||
|
||||
@ManyToOne(() => Room, (r) => r.roomExpenses)
|
||||
@JoinColumn({ name: 'room_id' })
|
||||
room: Room;
|
||||
}
|
||||
39
apps/server/src/entities/room.entity.ts
Normal file
39
apps/server/src/entities/room.entity.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, OneToMany } from 'typeorm';
|
||||
import { Occupancy } from './occupancy.entity';
|
||||
import { RoomExpense } from './room-expense.entity';
|
||||
|
||||
@Entity('rooms')
|
||||
export class Room {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ name: 'room_number', length: 20, unique: true })
|
||||
roomNumber: string;
|
||||
|
||||
@Column({ length: 50, nullable: true })
|
||||
building: string;
|
||||
|
||||
@Column({ nullable: true })
|
||||
floor: number;
|
||||
|
||||
@Column()
|
||||
capacity: number;
|
||||
|
||||
@Column({ type: 'varchar', length: 20, default: 'available' })
|
||||
status: string;
|
||||
|
||||
@Column({ name: 'room_type', length: 20, nullable: true })
|
||||
roomType: string;
|
||||
|
||||
@Column({ length: 10, nullable: true })
|
||||
gender: string;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt: Date;
|
||||
|
||||
@OneToMany(() => Occupancy, (o) => o.room)
|
||||
occupancies: Occupancy[];
|
||||
|
||||
@OneToMany(() => RoomExpense, (e) => e.room)
|
||||
roomExpenses: RoomExpense[];
|
||||
}
|
||||
55
apps/server/src/entities/student.entity.ts
Normal file
55
apps/server/src/entities/student.entity.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, OneToMany } from 'typeorm';
|
||||
import { Occupancy } from './occupancy.entity';
|
||||
import { PersonalExpense } from './personal-expense.entity';
|
||||
import { Bill } from './bill.entity';
|
||||
|
||||
@Entity('students')
|
||||
export class Student {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ length: 50 })
|
||||
name: string;
|
||||
|
||||
@Column({ length: 20, nullable: true })
|
||||
phone: string;
|
||||
|
||||
@Column({ name: 'id_number', length: 30, nullable: true })
|
||||
idNumber: string;
|
||||
|
||||
@Column({ length: 10, nullable: true })
|
||||
gender: string;
|
||||
|
||||
@Column({ length: 20, nullable: true })
|
||||
ethnicity: string;
|
||||
|
||||
@Column({ name: 'emergency_contact', length: 50, nullable: true })
|
||||
emergencyContact: string;
|
||||
|
||||
@Column({ name: 'emergency_phone', length: 20, nullable: true })
|
||||
emergencyPhone: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 20, default: 'active' })
|
||||
status: string;
|
||||
|
||||
@Column({ length: 100, nullable: true })
|
||||
organization: string;
|
||||
|
||||
@Column({ length: 50, nullable: true })
|
||||
supervisor: string;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn({ name: 'updated_at' })
|
||||
updatedAt: Date;
|
||||
|
||||
@OneToMany(() => Occupancy, (o) => o.student)
|
||||
occupancies: Occupancy[];
|
||||
|
||||
@OneToMany(() => PersonalExpense, (e) => e.student)
|
||||
personalExpenses: PersonalExpense[];
|
||||
|
||||
@OneToMany(() => Bill, (b) => b.student)
|
||||
bills: Bill[];
|
||||
}
|
||||
32
apps/server/src/entities/tenant.entity.ts
Normal file
32
apps/server/src/entities/tenant.entity.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';
|
||||
|
||||
@Entity('tenants')
|
||||
export class Tenant {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ length: 100 })
|
||||
name: string;
|
||||
|
||||
@Column({ length: 50, nullable: true })
|
||||
contact: string;
|
||||
|
||||
@Column({ length: 30, nullable: true })
|
||||
phone: string;
|
||||
|
||||
// 可视化颜色(hex),为空时由后端自动分配
|
||||
@Column({ length: 20, nullable: true })
|
||||
color: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
notes: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 20, default: 'active' })
|
||||
status: string; // active / archived
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn({ name: 'updated_at' })
|
||||
updatedAt: Date;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user