feat: 恭学教育基地管理系统初始提交

- 后端: NestJS 11 + TypeORM + JWT认证 + SQLite/MySQL
- 前端: React 19 + Ant Design 6 + Vite 8 + ECharts
- 功能模块: 数据面板、学生管理、宿舍管理、入住管理、费用录入、账单管理、教室管理、押金管理、操作日志、账号管理
- 支持Docker一键部署
This commit is contained in:
陈浩
2026-06-06 17:26:10 +08:00
commit 78676a124a
123 changed files with 26403 additions and 0 deletions

40
.gitignore vendored Normal file
View File

@@ -0,0 +1,40 @@
# 依赖
node_modules/
# 构建产物
dist/
build/
# 环境变量(包含密码等敏感信息)
.env
.env.local
.env.production
# 数据库文件
*.db
*.sqlite
# 上传文件合同PDF等敏感文件不入版本库和部署包
uploads/
backend/uploads/
# 日志
logs/
*.log
# 编辑器 / IDE
.vscode/
.idea/
.qoder/
# 部署包 / 压缩包
*.zip
*.tar.gz
# 参考资料(非源码)
*.xls
*.xlsx
# 系统文件
.DS_Store
Thumbs.db

111
README.md Normal file
View File

@@ -0,0 +1,111 @@
# 恭学教育基地管理系统
教培公司集训基地宿舍水电费精准计费系统,采用「人天数加权分摊」算法,按每位学生的实际入住天数公平分摊宿舍公共费用。
## 功能模块
| 模块 | 功能说明 |
|------|---------|
| 数据面板 | 统计卡片、费用趋势图、宿舍排行、甘特图 |
| 宿舍总览 | 房态可视化网格,空置/在住/满员颜色区分 |
| 学生管理 | 增删改查、批量导入/删除 |
| 宿舍管理 | 增删改查,删除前检查在住人员 |
| 入住管理 | 入住登记、退宿、换房、一键导入名单 |
| 费用录入 | 宿舍公共费用(水/电/保洁等)+ 个人附加费 |
| 账单管理 | 自动生成、确认、标记已付、删除、批量操作 |
| 账单导出 | Excel汇总+明细双Sheet、单条PDF账单 |
| 教室管理 | 教室信息维护、教室租赁记录 |
| 押金管理 | 押金收取与退还 |
| 操作日志 | 所有涉及钱的操作自动审计留痕 |
| 账号管理 | 用户增删改查、角色区分、启用/禁用、重置密码 |
## 技术架构
```
前端 (React + Vite) 后端 (NestJS) 数据库
┌─────────────────┐ ┌──────────────────┐ ┌──────────┐
│ React 19 │ │ NestJS 11 │ │ SQLite │
│ Ant Design 6 │────▶│ TypeORM 0.3 │────▶│ (开发) │
│ ECharts │ │ JWT + Passport │ │ MySQL 8 │
│ Vite 8 │ │ ExcelJS + PDFKit │ │ (生产) │
└─────────────────┘ └──────────────────┘ └──────────┘
```
## 快速开始
### 环境要求
- Node.js >= 18
- npm >= 9
### 后端启动
```bash
cd backend
cp .env.example .env # 复制并修改环境配置
npm install
npm run start:dev # 开发模式启动,默认端口 3000
```
### 前端启动
```bash
cd frontend
npm install
npm run dev # 开发模式启动,默认端口 5173
```
### Docker 部署
```bash
docker-compose up -d # 一键启动 MySQL + 后端 + 前端
```
## 项目结构
```
├── backend/ # 后端 NestJS 服务
│ ├── src/
│ │ ├── auth/ # 认证模块 (JWT)
│ │ ├── bills/ # 账单模块
│ │ ├── classrooms/ # 教室管理
│ │ ├── dashboard/ # 数据面板
│ │ ├── deposits/ # 押金管理
│ │ ├── entities/ # 数据实体
│ │ ├── expenses/ # 费用录入
│ │ ├── occupancies/# 入住管理
│ │ ├── rooms/ # 宿舍管理
│ │ ├── students/ # 学生管理
│ │ └── tenants/ # 租户管理
│ └── .env.example # 环境配置模板
├── frontend/ # 前端 React 应用
│ └── src/
│ ├── api/ # API 请求封装
│ ├── layouts/ # 布局组件
│ └── pages/ # 页面组件
├── docker-compose.yml # Docker 编排配置
└── 技术文档.md # 详细技术文档
```
## 环境配置
复制 `backend/.env.example``backend/.env`,按需修改:
| 配置项 | 说明 | 默认值 |
|--------|------|--------|
| `DB_TYPE` | 数据库类型 | `mysql` |
| `DB_HOST` | 数据库地址 | `localhost` |
| `DB_PORT` | 数据库端口 | `3306` |
| `DB_USERNAME` | 数据库用户名 | `dorm_billing` |
| `DB_PASSWORD` | 数据库密码 | - |
| `DB_DATABASE` | 数据库名 | `dorm_billing` |
| `JWT_SECRET` | JWT 密钥(务必替换) | - |
| `JWT_EXPIRES_IN` | Token 有效期 | `24h` |
| `ADMIN_PASSWORD` | 初始管理员密码 | - |
| `PORT` | 后端服务端口 | `3000` |
## 开发规范
- 后端代码使用 Prettier + ESLint 格式化
- 提交前确保 `npm run lint` 无报错
- 敏感配置(密码、密钥等)仅存放在 `.env` 文件,不提交到版本库

31
backend/.env.example Normal file
View 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
backend/.prettierrc Normal file
View File

@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

14
backend/Dockerfile Normal file
View 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
backend/README.md Normal file
View 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>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](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
backend/eslint.config.mjs Normal file
View 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
backend/nest-cli.json Normal file
View File

@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

12040
backend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

93
backend/package.json Normal file
View 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"
}
}

View 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!');
});
});
});

View 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();
}
}

70
backend/src/app.module.ts Normal file
View File

@@ -0,0 +1,70 @@
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 } from './entities';
import { AuthModule } from './auth/auth.module';
import { StudentsModule } from './students/students.module';
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');
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: [Student, Room, Occupancy, RoomExpense, PersonalExpense, Bill, BillItem, User, OperationLog, Deposit, Classroom, Tenant, ClassroomRental],
synchronize: true,
charset: 'utf8mb4',
};
}
return {
type: 'better-sqlite3' as const,
database: config.get('DB_DATABASE', 'dorm_billing.db'),
entities: [Student, Room, Occupancy, RoomExpense, PersonalExpense, Bill, BillItem, User, OperationLog, Deposit, Classroom, Tenant, ClassroomRental],
synchronize: true,
};
},
}),
AuthModule,
StudentsModule,
RoomsModule,
OccupanciesModule,
ExpensesModule,
BillsModule,
DashboardModule,
OperationLogsModule,
DepositsModule,
ClassroomsModule,
TenantsModule,
ClassroomRentalsModule,
],
providers: [
{ provide: APP_GUARD, useClass: ThrottlerGuard },
],
})
export class AppModule {}

View File

@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@@ -0,0 +1,85 @@
import { Controller, Post, Body, UseGuards, Get, Put, Delete, Param, Request, Req } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginDto, RegisterDto } 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';
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService, private logService: OperationLogsService) {}
@Post('login')
@Throttle({ default: { ttl: 60000, limit: 5 } }) // 登录接口每分钟最多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;
}
}
@Post('register')
@UseGuards(JwtAuthGuard)
async register(@Body() dto: RegisterDto, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.authService.register(dto);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '账号', action: '创建账号', detail: `用户名: ${dto.username}, 姓名: ${dto.name}`, ipAddress, userAgent });
return result;
}
@UseGuards(JwtAuthGuard)
@Get('profile')
getProfile(@Request() req: any) {
return req.user;
}
// ---- 用户管理 ----
@UseGuards(JwtAuthGuard)
@Get('users')
findAllUsers() {
return this.authService.findAllUsers();
}
@UseGuards(JwtAuthGuard)
@Put('users/:id')
async updateUser(@Param('id') id: string, @Body() body: { name?: string; role?: string; isActive?: boolean; username?: string; allowedMenus?: string[] }, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.authService.updateUser(+id, body);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '账号', action: '更新账号', targetId: +id, targetType: 'user', detail: JSON.stringify(body), ipAddress, userAgent });
return result;
}
@UseGuards(JwtAuthGuard)
@Put('users/:id/password')
async resetPassword(@Param('id') id: string, @Body() body: { password: string }, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.authService.resetPassword(+id, body.password);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '账号', action: '重置密码', targetId: +id, targetType: 'user', ipAddress, userAgent });
return result;
}
@UseGuards(JwtAuthGuard)
@Delete('users/:id')
async removeUser(@Param('id') id: string, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.authService.removeUser(+id);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '账号', action: '删除账号', targetId: +id, targetType: 'user', ipAddress, userAgent });
return result;
}
}

View File

@@ -0,0 +1,33 @@
import { Module, OnModuleInit } 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';
@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') },
}),
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
exports: [AuthService],
})
export class AuthModule implements OnModuleInit {
constructor(private authService: AuthService) {}
async onModuleInit() {
await this.authService.initAdmin();
}
}

View File

@@ -0,0 +1,149 @@
import { Injectable, UnauthorizedException, BadRequestException, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Not, MoreThan } from 'typeorm';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import * as bcrypt from 'bcryptjs';
import { User } from '../entities/user.entity';
import { LoginDto, RegisterDto } from './dto/auth.dto';
// 内存中的登录失败计数器按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,
private configService: ConfigService,
) {}
async register(dto: RegisterDto) {
const exists = await this.userRepo.findOne({ where: { username: dto.username } });
if (exists) throw new UnauthorizedException('用户名已存在');
const hash = await bcrypt.hash(dto.password, 10);
const user = this.userRepo.create({
username: dto.username,
passwordHash: hash,
name: dto.name,
role: 'operator',
allowedMenus: (dto as any).allowedMenus ? JSON.stringify((dto as any).allowedMenus) : null as any,
});
await this.userRepo.save(user);
return { message: '注册成功' };
}
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 } });
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 payload = { sub: user.id, username: user.username, role: user.role };
const allowedMenus = user.allowedMenus ? JSON.parse(user.allowedMenus) : null;
return { access_token: this.jwtService.sign(payload), user: { id: user.id, username: user.username, name: user.name, role: user.role, allowedMenus } };
}
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 } });
}
async initAdmin() {
const count = await this.userRepo.count();
if (count === 0) {
const adminPassword = this.configService.get('ADMIN_PASSWORD', 'admin123');
const hash = await bcrypt.hash(adminPassword, 10);
await this.userRepo.save(this.userRepo.create({ username: 'admin', passwordHash: hash, name: '管理员', role: 'admin' }));
console.log(`已创建默认管理员: admin / ${adminPassword === 'admin123' ? 'admin123 (请尽快修改!)' : '******'}`);
}
}
// ---- 用户管理 CRUD ----
async findAllUsers() {
const users = await this.userRepo.find({
select: ['id', 'username', 'name', 'role', 'isActive', 'allowedMenus', 'lastLoginAt', 'createdAt', 'updatedAt'],
order: { createdAt: 'DESC' },
});
return users.map(u => ({
...u,
allowedMenus: u.allowedMenus ? JSON.parse(u.allowedMenus) : null,
}));
}
async updateUser(id: number, data: { name?: string; role?: string; isActive?: boolean; username?: string; allowedMenus?: string[] }) {
const user = await this.userRepo.findOne({ where: { id } });
if (!user) throw new NotFoundException('用户不存在');
if (user.username === 'admin' && data.role && data.role !== 'admin') {
throw new BadRequestException('不能修改默认管理员的角色');
}
if (user.username === 'admin' && data.isActive === false) {
throw new BadRequestException('不能禁用默认管理员');
}
if (data.username !== undefined && data.username !== user.username) {
const exists = await this.userRepo.findOne({ where: { username: data.username } });
if (exists) throw new BadRequestException('用户名已存在');
user.username = data.username;
}
if (data.name !== undefined) user.name = data.name;
if (data.role !== undefined) user.role = data.role;
if (data.isActive !== undefined) user.isActive = data.isActive;
if (data.allowedMenus !== undefined) user.allowedMenus = data.allowedMenus ? JSON.stringify(data.allowedMenus) : null as any;
await this.userRepo.save(user);
return { message: '更新成功' };
}
async resetPassword(id: number, newPassword: string) {
const user = await this.userRepo.findOne({ where: { id } });
if (!user) throw new NotFoundException('用户不存在');
user.passwordHash = await bcrypt.hash(newPassword, 10);
await this.userRepo.save(user);
return { message: '密码已重置' };
}
async removeUser(id: number) {
const user = await this.userRepo.findOne({ where: { id } });
if (!user) throw new NotFoundException('用户不存在');
if (user.username === 'admin') throw new BadRequestException('不能删除默认管理员');
await this.userRepo.delete(id);
return { message: '用户已删除' };
}
}

View 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;
}

View File

@@ -0,0 +1,5 @@
import { Injectable, ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}

View File

@@ -0,0 +1,19 @@
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, role: payload.role };
}
}

View 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();
}
}

View File

@@ -0,0 +1,98 @@
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 type { Response } from 'express';
@UseGuards(JwtAuthGuard)
@Controller('bills')
export class BillsController {
constructor(private service: BillsService, private exportService: BillsExportService, private logService: OperationLogsService) {}
@Post('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()
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')
findOne(@Param('id') id: string) {
return this.service.findOne(+id);
}
@Put(':id/status')
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')
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')
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')
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')
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')
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);
}
}

View 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 {}

View 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} 条账单` };
}
}

View 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';
}

View File

@@ -0,0 +1,125 @@
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';
@UseGuards(JwtAuthGuard)
@Controller('classroom-rentals')
export class ClassroomRentalsController {
constructor(private service: ClassroomRentalsService, private logService: OperationLogsService) {}
@Get()
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')
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')
findOne(@Param('id') id: string) {
return this.service.findOne(+id);
}
@Post()
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')
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')
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')
@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')
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')
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;
}
}

View File

@@ -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 {}

View 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,
};
}
}

View 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;
}

View File

@@ -0,0 +1,123 @@
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 * as ExcelJS from 'exceljs';
@UseGuards(JwtAuthGuard)
@Controller('classrooms')
export class ClassroomsController {
constructor(private service: ClassroomsService, private logService: OperationLogsService) {}
@Get()
findAll(@Query('building') building?: string, @Query('roomType') roomType?: string, @Query('includeArchived') includeArchived?: string) {
return this.service.findAll({
building,
roomType,
includeArchived: includeArchived === 'true',
});
}
@Get('template')
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')
findOne(@Param('id') id: string) {
return this.service.findOne(+id);
}
@Post()
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')
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')
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')
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')
@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;
}
}

View 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 {}

View 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 };
}
}

View 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;
}

View 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 };
}

View File

@@ -0,0 +1,39 @@
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
import { DashboardService } from './dashboard.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
@UseGuards(JwtAuthGuard)
@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);
}
}

View 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 {}

View 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();
}
}

View File

@@ -0,0 +1,49 @@
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';
@UseGuards(JwtAuthGuard)
@Controller('deposits')
export class DepositsController {
constructor(private service: DepositsService, private logService: OperationLogsService) {}
@Get()
findAll(@Query('studentId') studentId?: string, @Query('status') status?: string) {
return this.service.findAll({
studentId: studentId ? +studentId : undefined,
status: status || undefined,
});
}
@Get('stats')
getStats() {
return this.service.getStats();
}
@Post()
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')
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')
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;
}
}

View 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 {}

View 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;
}
}

View 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;
}

View 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;
}

View 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[];
}

View 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;
}

View 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;
}

View 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;
}

View File

@@ -0,0 +1,13 @@
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';

View 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;
}

View 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;
}

View 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;
}

View 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;
}

View 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[];
}

View 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[];
}

View 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;
}

View File

@@ -0,0 +1,34 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';
@Entity('users')
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({ length: 50, unique: true })
username: string;
@Column({ name: 'password_hash', length: 255 })
passwordHash: string;
@Column({ type: 'varchar', length: 20, default: 'operator' })
role: string;
@Column({ length: 50, nullable: true })
name: string;
@Column({ name: 'allowed_menus', type: 'text', nullable: true })
allowedMenus: string;
@Column({ name: 'is_active', default: true })
isActive: boolean;
@Column({ name: 'last_login_at', type: 'datetime', nullable: true })
lastLoginAt: Date;
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
}

View File

@@ -0,0 +1,54 @@
import { IsInt, IsString, IsNumber, IsOptional, IsEnum } from 'class-validator';
export class CreateRoomExpenseDto {
@IsInt()
roomId: number;
@IsEnum(['water', 'electricity', 'cleaning', 'damage', 'other'])
expenseType: string;
@IsNumber()
amount: number;
@IsString()
periodStart: string;
@IsString()
periodEnd: string;
@IsOptional()
@IsString()
description?: string;
}
export class CreatePersonalExpenseDto {
@IsInt()
studentId: number;
@IsOptional()
@IsInt()
roomId?: number;
@IsEnum(['damage', 'cleaning', 'penalty', 'key', 'remote', 'deposit_deduction', 'other'])
expenseType: string;
@IsNumber()
amount: number;
@IsString()
expenseDate: string;
@IsOptional()
@IsString()
description?: string;
}
export class BatchRoomExpenseDto {
@IsString()
periodStart: string;
@IsString()
periodEnd: string;
expenses: { roomId: number; expenseType: string; amount: number; description?: string }[];
}

View File

@@ -0,0 +1,269 @@
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 { ExpensesService } from './expenses.service';
import { CreateRoomExpenseDto, CreatePersonalExpenseDto, BatchRoomExpenseDto } from './dto/expense.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
import { extractRequestInfo } from '../common/request-utils';
import * as ExcelJS from 'exceljs';
/** 提取 ExcelJS 单元格的真实值,兼容公式、富文本、日期、超链接等情况 */
function readCell(cell: ExcelJS.Cell): any {
let v: any = cell?.value;
if (v == null) return '';
if (typeof v === 'object') {
// 公式单元格:{ formula, result }
if ('result' in v) v = (v as any).result;
// 富文本:{ richText: [...] }
else if ('richText' in v && Array.isArray((v as any).richText)) {
return (v as any).richText.map((r: any) => r.text || '').join('');
}
// 超链接:{ text, hyperlink }
else if ('text' in v) v = (v as any).text;
// 错误值:{ error: '#DIV/0!' }
else if ('error' in v) return '';
}
if (v instanceof Date) {
const y = v.getFullYear();
const m = String(v.getMonth() + 1).padStart(2, '0');
const d = String(v.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
return v;
}
function readCellNum(cell: ExcelJS.Cell): number {
const v = readCell(cell);
if (v === '' || v == null) return 0;
const n = Number(v);
return isFinite(n) ? n : 0;
}
function readCellStr(cell: ExcelJS.Cell): string {
const v = readCell(cell);
return v == null ? '' : String(v).trim();
}
@UseGuards(JwtAuthGuard)
@Controller('expenses')
export class ExpensesController {
constructor(private service: ExpensesService, private logService: OperationLogsService) {}
@Post('room')
async createRoomExpense(@Body() dto: CreateRoomExpenseDto, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.createRoomExpense(dto, req.user?.id);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '费用', action: '录入宿舍费用', targetId: result.id, targetType: 'room_expense', detail: `房间${dto.roomId} ¥${dto.amount} ${dto.expenseType}`, ipAddress, userAgent });
return result;
}
@Post('room/batch')
async batchCreateRoomExpenses(@Body() dto: BatchRoomExpenseDto, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.batchCreateRoomExpenses(dto, req.user?.id);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '费用', action: '批量录入费用', detail: JSON.stringify(dto), ipAddress, userAgent });
return result;
}
@Get('room')
findRoomExpenses(
@Query('roomId') roomId?: string,
@Query('periodStart') periodStart?: string,
@Query('periodEnd') periodEnd?: string,
) {
return this.service.findRoomExpenses({
roomId: roomId ? +roomId : undefined,
periodStart, periodEnd,
});
}
@Delete('room/:id')
async deleteRoomExpense(@Param('id') id: string, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.deleteRoomExpense(+id);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '费用', action: '删除宿舍费用', targetId: +id, targetType: 'room_expense', ipAddress, userAgent });
return result;
}
@Post('room/batch-delete')
async batchDeleteRoomExpenses(@Body() body: { ids: number[] }, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.batchDeleteRoomExpenses(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;
}
@Put('room/:id')
async updateRoomExpense(@Param('id') id: string, @Body() dto: CreateRoomExpenseDto, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.updateRoomExpense(+id, dto);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '费用', action: '编辑宿舍费用', targetId: +id, targetType: 'room_expense', detail: `¥${dto.amount} ${dto.expenseType}`, ipAddress, userAgent });
return result;
}
@Post('personal')
async createPersonalExpense(@Body() dto: CreatePersonalExpenseDto, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.createPersonalExpense(dto, req.user?.id);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '费用', action: '录入个人费用', detail: `学生${dto.studentId} ¥${dto.amount} ${dto.expenseType}`, ipAddress, userAgent });
return result;
}
@Get('personal')
findPersonalExpenses(@Query('studentId') studentId?: string) {
return this.service.findPersonalExpenses({ studentId: studentId ? +studentId : undefined });
}
@Delete('personal/:id')
async deletePersonalExpense(@Param('id') id: string, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.deletePersonalExpense(+id);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '费用', action: '删除个人费用', targetId: +id, ipAddress, userAgent });
return result;
}
@Post('personal/batch-delete')
async batchDeletePersonalExpenses(@Body() body: { ids: number[] }, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.batchDeletePersonalExpenses(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;
}
@Put('personal/:id')
async updatePersonalExpense(@Param('id') id: string, @Body() dto: CreatePersonalExpenseDto, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.updatePersonalExpense(+id, dto);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '费用', action: '编辑个人费用', targetId: +id, detail: `¥${dto.amount} ${dto.expenseType}`, ipAddress, userAgent });
return result;
}
@Get('utility/template')
async downloadUtilityTemplate(@Res() res: Response) {
const workbook = new ExcelJS.Workbook();
const ws = workbook.addWorksheet('水电费导入模板');
ws.columns = [
{ header: '序号', key: 'seq', width: 8 },
{ header: '时间', key: 'period', width: 30 },
{ header: '房间号', key: 'roomNumber', width: 12 },
{ header: '房间电量', key: 'electricity', width: 12 },
{ header: '电费', key: 'electricityFee', width: 10 },
{ header: '冷水用量(吨)', key: 'water', width: 14 },
{ header: '水费', key: 'waterFee', width: 10 },
{ header: '应缴金额', key: 'total', width: 12 },
];
ws.getRow(1).font = { bold: true };
ws.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
ws.addRow({ seq: 1, period: '2026-01-21 - 2026-02-08', roomNumber: '4-102', electricity: 50, electricityFee: 25.5, water: 3, waterFee: 14.7, total: 40.2 });
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename=utility_template.xlsx');
await workbook.xlsx.write(res);
res.end();
}
@Post('utility/import')
@UseInterceptors(FileInterceptor('file'))
async importUtilityExpenses(@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; // 跳过表头
const roomNumber = readCellStr(row.getCell(3));
if (!roomNumber) return;
rows.push({
periodStr: readCellStr(row.getCell(2)),
roomNumber,
electricityAmount: readCellNum(row.getCell(4)),
electricityFee: readCellNum(row.getCell(5)),
waterAmount: readCellNum(row.getCell(6)),
waterFee: readCellNum(row.getCell(7)),
totalFee: readCellNum(row.getCell(8)),
});
});
const result = await this.service.batchImportUtilityExpenses(rows, req.user?.id);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '费用', action: '导入水电费', detail: result.message, ipAddress, userAgent });
return result;
}
@Get('personal/template')
async downloadPersonalTemplate(@Res() res: Response) {
const workbook = new ExcelJS.Workbook();
const ws = workbook.addWorksheet('个人附加费导入模板');
ws.columns = [
{ header: '学生姓名', key: 'studentName', width: 15 },
{ header: '费用类型', key: 'expenseType', width: 15 },
{ header: '金额', key: 'amount', width: 12 },
{ header: '费用日期', key: 'expenseDate', width: 15 },
{ header: '说明', key: 'description', width: 25 },
];
ws.getRow(1).font = { bold: true };
ws.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
ws.addRow({ studentName: '张三', expenseType: '钥匙费', amount: 30, expenseDate: '2026-01-15', description: '丢失宿舍钥匙' });
// 添加费用类型说明
const noteSheet = workbook.addWorksheet('费用类型说明');
noteSheet.columns = [{ header: '费用类型可用值', key: 'type', width: 25 }];
['物品损坏', '保洁费', '罚款', '钥匙费', '空调遥控器', '押金扣除', '其他'].forEach(t => noteSheet.addRow({ type: t }));
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename=personal_expense_template.xlsx');
await workbook.xlsx.write(res);
res.end();
}
@Post('personal/import')
@UseInterceptors(FileInterceptor('file'))
async importPersonalExpenses(@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;
const studentName = readCellStr(row.getCell(1));
if (!studentName) return;
rows.push({
studentName,
expenseType: readCellStr(row.getCell(2)),
amount: readCellNum(row.getCell(3)),
expenseDate: readCellStr(row.getCell(4)),
description: readCellStr(row.getCell(5)) || undefined,
});
});
const result = await this.service.batchImportPersonalExpenses(rows, req.user?.id);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '费用', action: '导入个人附加费', detail: result.message, ipAddress, userAgent });
return result;
}
@Get('personal/export')
async exportPersonalExpenses(@Res() res: Response) {
const data = await this.service.findPersonalExpenses();
const typeMap: Record<string, string> = { damage: '物品损坏', cleaning: '保洁费', penalty: '罚款', key: '钥匙费', remote: '空调遥控器', deposit_deduction: '押金扣除', other: '其他' };
const workbook = new ExcelJS.Workbook();
const ws = workbook.addWorksheet('个人附加费');
ws.columns = [
{ header: '学生姓名', key: 'studentName', width: 15 },
{ header: '费用类型', key: 'expenseType', width: 15 },
{ header: '金额', key: 'amount', width: 12 },
{ header: '费用日期', key: 'expenseDate', width: 15 },
{ header: '说明', key: 'description', width: 30 },
];
ws.getRow(1).font = { bold: true };
data.forEach((d: any) => {
ws.addRow({
studentName: d.student?.name || '',
expenseType: typeMap[d.expenseType] || d.expenseType,
amount: Number(d.amount),
expenseDate: d.expenseDate,
description: d.description || '',
});
});
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename=personal_expenses_export.xlsx');
await workbook.xlsx.write(res);
res.end();
}
}

View File

@@ -0,0 +1,17 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { RoomExpense } from '../entities/room-expense.entity';
import { PersonalExpense } from '../entities/personal-expense.entity';
import { Room } from '../entities/room.entity';
import { Student } from '../entities/student.entity';
import { ExpensesService } from './expenses.service';
import { ExpensesController } from './expenses.controller';
import { OperationLogsModule } from '../operation-logs/operation-logs.module';
@Module({
imports: [TypeOrmModule.forFeature([RoomExpense, PersonalExpense, Room, Student]), OperationLogsModule],
controllers: [ExpensesController],
providers: [ExpensesService],
exports: [ExpensesService],
})
export class ExpensesModule {}

View File

@@ -0,0 +1,330 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { RoomExpense } from '../entities/room-expense.entity';
import { PersonalExpense } from '../entities/personal-expense.entity';
import { Room } from '../entities/room.entity';
import { Student } from '../entities/student.entity';
import { CreateRoomExpenseDto, CreatePersonalExpenseDto, BatchRoomExpenseDto } from './dto/expense.dto';
import { RoomsService } from '../rooms/rooms.service';
@Injectable()
export class ExpensesService {
constructor(
@InjectRepository(RoomExpense) private roomExpRepo: Repository<RoomExpense>,
@InjectRepository(PersonalExpense) private personalExpRepo: Repository<PersonalExpense>,
@InjectRepository(Room) private roomRepo: Repository<Room>,
@InjectRepository(Student) private studentRepo: Repository<Student>,
) {}
// 宿舍费用
async createRoomExpense(dto: CreateRoomExpenseDto, userId?: number) {
return this.roomExpRepo.save(this.roomExpRepo.create({ ...dto, recordedBy: userId }));
}
async batchCreateRoomExpenses(dto: BatchRoomExpenseDto, userId?: number) {
const entities = dto.expenses.map((e) =>
this.roomExpRepo.create({
roomId: e.roomId,
expenseType: e.expenseType,
amount: e.amount,
description: e.description,
periodStart: dto.periodStart,
periodEnd: dto.periodEnd,
recordedBy: userId,
}),
);
return this.roomExpRepo.save(entities);
}
async findRoomExpenses(query?: { roomId?: number; periodStart?: string; periodEnd?: string }) {
const qb = this.roomExpRepo.createQueryBuilder('e')
.leftJoinAndSelect('e.room', 'room')
.orderBy('e.createdAt', 'DESC');
if (query?.roomId) qb.andWhere('e.roomId = :roomId', { roomId: query.roomId });
if (query?.periodStart) qb.andWhere('e.periodStart >= :ps', { ps: query.periodStart });
if (query?.periodEnd) qb.andWhere('e.periodEnd <= :pe', { pe: query.periodEnd });
return qb.getMany();
}
async deleteRoomExpense(id: number) {
const e = await this.roomExpRepo.findOne({ where: { id } });
if (!e) throw new NotFoundException('费用记录不存在');
await this.roomExpRepo.delete(id);
return { message: '删除成功' };
}
async batchDeleteRoomExpenses(ids: number[]) {
if (!ids || ids.length === 0) throw new BadRequestException('请选择要删除的记录');
const result = await this.roomExpRepo.createQueryBuilder()
.delete()
.where('id IN (:...ids)', { ids })
.execute();
return { message: '批量删除成功', deleted: result.affected || 0 };
}
async updateRoomExpense(id: number, dto: Partial<CreateRoomExpenseDto>) {
const e = await this.roomExpRepo.findOne({ where: { id } });
if (!e) throw new NotFoundException('费用记录不存在');
Object.assign(e, dto);
return this.roomExpRepo.save(e);
}
// 个人附加费
async createPersonalExpense(dto: CreatePersonalExpenseDto, userId?: number) {
return this.personalExpRepo.save(this.personalExpRepo.create({ ...dto, recordedBy: userId }));
}
async findPersonalExpenses(query?: { studentId?: number }) {
const where: any = {};
if (query?.studentId) where.studentId = query.studentId;
return this.personalExpRepo.find({ where, relations: ['student'], order: { createdAt: 'DESC' } });
}
async deletePersonalExpense(id: number) {
const e = await this.personalExpRepo.findOne({ where: { id } });
if (!e) throw new NotFoundException('费用记录不存在');
await this.personalExpRepo.delete(id);
return { message: '删除成功' };
}
async batchDeletePersonalExpenses(ids: number[]) {
if (!ids || ids.length === 0) throw new BadRequestException('请选择要删除的记录');
const result = await this.personalExpRepo.createQueryBuilder()
.delete()
.where('id IN (:...ids)', { ids })
.execute();
return { message: '批量删除成功', deleted: result.affected || 0 };
}
async updatePersonalExpense(id: number, dto: Partial<CreatePersonalExpenseDto>) {
const e = await this.personalExpRepo.findOne({ where: { id } });
if (!e) throw new NotFoundException('费用记录不存在');
Object.assign(e, dto);
return this.personalExpRepo.save(e);
}
/**
* 水电费Excel批量导入
* Excel格式: 序号|时间|房间号|房间电量|电费|冷水用量(吨)|水费|应缴金额
* 时间格式: "2026-01-21 - 2026-02-08"
*/
async batchImportUtilityExpenses(rows: {
periodStr: string;
roomNumber: string;
electricityAmount: number;
electricityFee: number;
waterAmount: number;
waterFee: number;
totalFee: number;
}[], userId?: number) {
let imported = 0;
let skipped = 0;
const errors: string[] = [];
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
const rowNum = i + 2;
if (!row.roomNumber?.trim()) { skipped++; continue; }
try {
// 查找或创建宿舍
let room = await this.roomRepo.findOne({ where: { roomNumber: row.roomNumber.trim() } });
if (!room) {
const parsed = RoomsService.parseRoomNumber(row.roomNumber.trim());
room = await this.roomRepo.save(this.roomRepo.create({
roomNumber: row.roomNumber.trim(),
building: parsed.building || undefined,
floor: parsed.floor || undefined,
capacity: parsed.capacity || 4,
roomType: parsed.roomType || undefined,
}));
}
// 解析时间段 "2026-01-21 - 2026-02-08" 或 "2026-01-21~2026-02-08"
let periodStart = '';
let periodEnd = '';
if (row.periodStr) {
// 先尝试用" - "或" ~ "分割(带空格的分隔符,避免拆分日期内部的连字符)
let parts = row.periodStr.split(/\s+[-~]\s+/);
if (parts.length < 2) {
// 回退:尝试用正则提取 YYYY-MM-DD 格式的日期
const dateMatches = row.periodStr.match(/(\d{4}-\d{1,2}-\d{1,2})/g);
if (dateMatches && dateMatches.length >= 2) {
parts = [dateMatches[0], dateMatches[1]];
}
}
if (parts.length >= 2) {
periodStart = this.normalizeDate(parts[0].trim());
periodEnd = this.normalizeDate(parts[1].trim());
}
}
if (!periodStart || !periodEnd) {
errors.push(`${rowNum}行: 时间格式无法解析 "${row.periodStr}"`);
skipped++;
continue;
}
// 关键校验:电费 + 水费 都为 0 时,多半是 Excel 公式未正确计算或字段缺失,
// 必须给出明确错误,避免出现"提示成功但无数据"的迷之现象。
if ((row.electricityFee || 0) <= 0 && (row.waterFee || 0) <= 0) {
errors.push(`${rowNum}行: ${row.roomNumber} 电费和水费均为 0可能 Excel 中是未生效的公式(请打开文件让公式重算后再保存导入),已跳过`);
skipped++;
continue;
}
// 幂等:先删除该房间在同一周期已有的水/电费用记录,避免重复导入产生脏数据
await this.roomExpRepo.createQueryBuilder()
.delete()
.where('roomId = :roomId', { roomId: room.id })
.andWhere('periodStart = :ps AND periodEnd = :pe', { ps: periodStart, pe: periodEnd })
.andWhere('expenseType IN (:...types)', { types: ['water', 'electricity'] })
.execute();
let savedAny = false;
// 导入电费
if (row.electricityFee > 0) {
await this.roomExpRepo.save(this.roomExpRepo.create({
roomId: room.id,
expenseType: 'electricity',
amount: row.electricityFee,
periodStart,
periodEnd,
description: `电量${row.electricityAmount}kWh`,
recordedBy: userId,
}));
savedAny = true;
}
// 导入水费
if (row.waterFee > 0) {
await this.roomExpRepo.save(this.roomExpRepo.create({
roomId: room.id,
expenseType: 'water',
amount: row.waterFee,
periodStart,
periodEnd,
description: `用水${row.waterAmount}`,
recordedBy: userId,
}));
savedAny = true;
}
if (savedAny) imported++;
else { skipped++; errors.push(`${rowNum}行: ${row.roomNumber} 无有效金额`); }
} catch (e: any) {
errors.push(`${rowNum}行: ${row.roomNumber} 导入失败 - ${e.message}`);
skipped++;
}
}
return {
message: imported > 0
? `成功导入 ${imported} 间宿舍水电费${skipped > 0 ? `,跳过 ${skipped}` : ''}`
: `未导入任何记录${skipped > 0 ? `,共 ${skipped} 条被跳过` : ''}`,
imported,
skipped,
errors: errors.length > 0 ? errors : undefined,
};
}
/** 把 2026/4/1、2026-4-1 之类格式归一化为 YYYY-MM-DD */
private normalizeDate(s: string): string {
if (!s) return '';
if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s;
const m = s.match(/(\d{4})[\-\/.](\d{1,2})[\-\/.](\d{1,2})/);
if (m) return `${m[1]}-${m[2].padStart(2, '0')}-${m[3].padStart(2, '0')}`;
return s;
}
/**
* 个人附加费Excel批量导入
* Excel格式: 学生姓名|费用类型|金额|费用日期|说明
*/
async batchImportPersonalExpenses(rows: {
studentName: string;
expenseType: string;
amount: number;
expenseDate: string;
description?: string;
}[], userId?: number) {
let imported = 0;
let skipped = 0;
const errors: string[] = [];
const typeMap: Record<string, string> = {
'物品损坏': 'damage', '损坏': 'damage',
'保洁费': 'cleaning', '保洁': 'cleaning',
'罚款': 'penalty',
'钥匙费': 'key', '钥匙': 'key',
'空调遥控器': 'remote', '遥控器': 'remote',
'押金扣除': 'deposit_deduction',
'其他': 'other',
};
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
const rowNum = i + 2;
if (!row.studentName?.trim()) { skipped++; continue; }
try {
// 查找学生
const student = await this.studentRepo.findOne({ where: { name: row.studentName.trim() } });
if (!student) {
errors.push(`${rowNum}行: 学生"${row.studentName}"未找到`);
skipped++;
continue;
}
// 解析费用类型
let expenseType = row.expenseType?.trim() || '';
if (typeMap[expenseType]) {
expenseType = typeMap[expenseType];
}
const validTypes = ['damage', 'cleaning', 'penalty', 'key', 'remote', 'deposit_deduction', 'other'];
if (!validTypes.includes(expenseType)) {
errors.push(`${rowNum}行: 费用类型"${row.expenseType}"无效`);
skipped++;
continue;
}
// 解析日期
let expenseDate = row.expenseDate?.trim() || '';
if (!expenseDate.match(/^\d{4}-\d{2}-\d{2}$/)) {
// 尝试从各种格式解析
const dateMatch = expenseDate.match(/(\d{4})[\-\/](\d{1,2})[\-\/](\d{1,2})/);
if (dateMatch) {
expenseDate = `${dateMatch[1]}-${dateMatch[2].padStart(2, '0')}-${dateMatch[3].padStart(2, '0')}`;
} else {
errors.push(`${rowNum}行: 日期格式"${row.expenseDate}"无效需要YYYY-MM-DD`);
skipped++;
continue;
}
}
await this.personalExpRepo.save(this.personalExpRepo.create({
studentId: student.id,
expenseType,
amount: row.amount,
expenseDate,
description: row.description || undefined,
recordedBy: userId,
}));
imported++;
} catch (e: any) {
errors.push(`${rowNum}行: ${row.studentName} 导入失败 - ${e.message}`);
skipped++;
}
}
return {
message: `成功导入 ${imported} 条个人附加费,跳过 ${skipped}`,
imported,
skipped,
errors: errors.length > 0 ? errors : undefined,
};
}
}

13
backend/src/main.ts Normal file
View File

@@ -0,0 +1,13 @@
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api');
app.enableCors();
app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));
await app.listen(process.env.PORT ?? 3000);
console.log(`Server running on http://localhost:${process.env.PORT ?? 3000}`);
}
bootstrap();

View File

@@ -0,0 +1,69 @@
import { IsInt, IsString, IsOptional, IsArray } from 'class-validator';
export class CheckInDto {
@IsInt()
studentId: number;
@IsInt()
roomId: number;
@IsString()
checkInDate: string; // YYYY-MM-DD
@IsOptional()
@IsString()
billingStartDate?: string; // 默认=checkInDate可调整
@IsOptional()
@IsString()
notes?: string;
}
export class CheckOutDto {
@IsString()
checkOutDate: string;
@IsOptional()
@IsString()
billingEndDate?: string; // 默认=checkOutDate
@IsOptional()
@IsString()
checkOutReason?: string;
}
export class TransferRoomDto {
@IsInt()
newRoomId: number;
@IsString()
transferDate: string; // YYYY-MM-DD
@IsOptional()
@IsString()
oldBillingEndDate?: string; // 旧房计费截止日,默认=transferDate
@IsOptional()
@IsString()
newBillingStartDate?: string; // 新房计费起始日,默认=transferDate次日
@IsOptional()
@IsString()
reason?: string;
}
export class BatchCheckOutDto {
@IsArray()
ids: number[];
@IsString()
checkOutDate: string; // YYYY-MM-DD
@IsOptional()
@IsString()
billingEndDate?: string; // 默认=checkOutDate
@IsOptional()
@IsString()
checkOutReason?: string;
}

View File

@@ -0,0 +1,220 @@
import { Controller, Get, Post, Put, Delete, Param, Body, Query, UseGuards, Request, Res, UseInterceptors, UploadedFile } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import type { Response } from 'express';
import { OccupanciesService } from './occupancies.service';
import { CheckInDto, CheckOutDto, TransferRoomDto, BatchCheckOutDto } from './dto/occupancy.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
import { extractRequestInfo } from '../common/request-utils';
import * as ExcelJS from 'exceljs';
@UseGuards(JwtAuthGuard)
@Controller('occupancies')
export class OccupanciesController {
constructor(private service: OccupanciesService, private logService: OperationLogsService) {}
@Get()
findAll(
@Query('roomId') roomId?: string,
@Query('studentId') studentId?: string,
@Query('active') active?: string,
) {
return this.service.findAll({
roomId: roomId ? +roomId : undefined,
studentId: studentId ? +studentId : undefined,
active: active === 'true',
});
}
@Post('batch-check-out')
async batchCheckOut(@Body() dto: BatchCheckOutDto, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.batchCheckOut(dto);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '入住', action: '批量退宿', detail: `退宿 ${dto.ids.length} 人,日期 ${dto.checkOutDate}`, ipAddress, userAgent });
return result;
}
@Post('check-in')
async checkIn(@Body() dto: CheckInDto, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.checkIn(dto);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '入住', action: '入住登记', targetId: result.id, targetType: 'occupancy', detail: `学生${dto.studentId} 入住房间${dto.roomId}`, ipAddress, userAgent });
return result;
}
@Put(':id/check-out')
async checkOut(@Param('id') id: string, @Body() dto: CheckOutDto, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.checkOut(+id, dto);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '入住', action: '退宿', targetId: +id, targetType: 'occupancy', ipAddress, userAgent });
return result;
}
@Put(':id/transfer')
async transferRoom(@Param('id') id: string, @Body() dto: TransferRoomDto, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.transferRoom(+id, dto);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '入住', action: '换房', targetId: +id, targetType: 'occupancy', detail: `换到房间${dto.newRoomId}`, ipAddress, userAgent });
return result;
}
@Delete(':id')
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: 'occupancy', ipAddress, userAgent });
return result;
}
@Post('batch-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')
async exportExcel(@Query('active') active?: string, @Res() res?: Response) {
const records = await this.service.findAll({ active: active === 'true' });
const workbook = new ExcelJS.Workbook();
const ws = workbook.addWorksheet('入住记录');
ws.columns = [
{ header: '宿舍号', key: 'roomNumber', width: 12 },
{ header: '楼栋', key: 'building', width: 12 },
{ header: '学生姓名', key: 'studentName', width: 12 },
{ header: '性别', key: 'gender', width: 8 },
{ header: '电话', key: 'phone', width: 18 },
{ header: '学号/身份证', key: 'idNumber', width: 22 },
{ header: '所属机构', key: 'organization', width: 18 },
{ header: '负责人/班主任', key: 'supervisor', width: 15 },
{ header: '入住日期', key: 'checkInDate', width: 14 },
{ header: '退宿日期', key: 'checkOutDate', width: 14 },
{ header: '计费起始', key: 'billingStartDate', width: 14 },
{ header: '计费截止', key: 'billingEndDate', width: 14 },
{ header: '退宿原因', key: 'checkOutReason', width: 12 },
];
ws.getRow(1).font = { bold: true };
ws.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
for (const r of records) {
ws.addRow({
roomNumber: r.room?.roomNumber || '',
building: r.room?.building || '',
studentName: r.student?.name || '',
gender: r.student?.gender || '',
phone: r.student?.phone || '',
idNumber: r.student?.idNumber || '',
organization: r.student?.organization || '',
supervisor: r.student?.supervisor || '',
checkInDate: r.checkInDate || '',
checkOutDate: r.checkOutDate || '',
billingStartDate: r.billingStartDate || '',
billingEndDate: r.billingEndDate || '',
checkOutReason: r.checkOutReason || '',
});
}
res!.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res!.setHeader('Content-Disposition', 'attachment; filename=occupancies.xlsx');
await workbook.xlsx.write(res!);
res!.end();
}
@Get('template')
async downloadTemplate(@Res() res: Response) {
const workbook = new ExcelJS.Workbook();
const ws = workbook.addWorksheet('入住名单导入模板');
ws.columns = [
{ header: '宿舍号', key: 'roomNumber', width: 12 },
{ header: '床位号', key: 'bedNumber', width: 8 },
{ header: '姓名', key: 'name', width: 12 },
{ header: '性别', key: 'gender', width: 8 },
{ header: '民族', key: 'ethnicity', width: 10 },
{ header: '电话', key: 'phone', width: 15 },
{ header: '学号/身份证', key: 'idNumber', width: 22 },
{ header: '入住时间', key: 'checkInDate', width: 14 },
{ header: '离宿时间', key: 'checkOutDate', width: 14 },
{ header: '紧急联系人', key: 'emergencyContact', width: 15 },
{ header: '紧急联系人电话', key: 'emergencyPhone', width: 18 },
{ header: '所属机构', key: 'organization', width: 18 },
{ header: '负责人/班主任', key: 'supervisor', width: 15 },
];
ws.getRow(1).font = { bold: true };
ws.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
// 添加说明行
ws.addRow({ roomNumber: '4-102', bedNumber: 1, name: '张三', gender: '男', ethnicity: '汉族', phone: '13800138000', idNumber: '2024001', checkInDate: '2026-04-21', checkOutDate: '', emergencyContact: '张父', emergencyPhone: '13900000000', organization: '', supervisor: '' });
ws.addRow({ roomNumber: '4-102', bedNumber: 2, name: '李四', gender: '男', ethnicity: '汉族', phone: '13800138001', idNumber: '2024002', checkInDate: '2026-04-21', checkOutDate: '', emergencyContact: '', emergencyPhone: '', organization: 'XXX教育科技', supervisor: '王老师' });
// 添加使用说明sheet
const helpWs = workbook.addWorksheet('使用说明');
helpWs.getColumn(1).width = 60;
helpWs.addRow(['【入住名单导入说明】']);
helpWs.addRow(['1. 导入入住名单会自动创建不存在的学生和宿舍,无需单独导入学生或宿舍']);
helpWs.addRow(['2. 宿舍号会智能解析楼栋、楼层和房间类型如4-102自动识别为4号楼1层四人间']);
helpWs.addRow(['3. 同一宿舍号的多个学生可合并宿舍号单元格,系统会自动继承上一行的宿舍号']);
helpWs.addRow(['4. 已存在的学生(按姓名匹配)会自动补充缺失信息(性别、民族等)']);
helpWs.addRow(['5. 已有在住记录的学生会自动跳过,不会重复入住']);
helpWs.addRow(['6. 填了离宿时间的记录会直接标记为已退宿(用于导入历史数据)']);
helpWs.addRow(['7. 性别约束:同一宿舍只能住同性别学生,首位入住者确定宿舍性别']);
helpWs.addRow(['8. 床位号仅做标识参考,不影响入住逻辑']);
helpWs.getRow(1).font = { bold: true, size: 14 };
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename=checkin_template.xlsx');
await workbook.xlsx.write(res);
res.end();
}
@Post('import')
@UseInterceptors(FileInterceptor('file'))
async importCheckIn(@UploadedFile() file: Express.Multer.File, @Request() req: any, @Query('autoDeposit') autoDeposit?: string, @Query('depositAmount') depositAmount?: string) {
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[] = [];
let lastRoomNumber = '';
ws.eachRow((row, idx) => {
if (idx === 1) return; // 跳过表头
// 宿舍号可能是合并单元格,需要继承上一行
const roomNumberVal = row.getCell(1).value;
const roomNumber = roomNumberVal ? String(roomNumberVal).trim() : '';
if (roomNumber) lastRoomNumber = roomNumber;
const name = String(row.getCell(3).value || '').trim();
if (!name) return; // 无姓名则跳过空行
// 解析日期
const parseDate = (cell: any): string => {
const val = cell.value;
if (!val) return '';
if (val instanceof Date) return val.toISOString().split('T')[0];
const s = String(val).trim();
// 处理 "YYYY/MM/DD" 或 "YYYY-MM-DD" 或 "YYYY.MM.DD"
const m = s.match(/(\d{4})[\/\-\.](\d{1,2})[\/\-\.](\d{1,2})/);
if (m) return `${m[1]}-${m[2].padStart(2, '0')}-${m[3].padStart(2, '0')}`;
return s;
};
rows.push({
name,
roomNumber: lastRoomNumber,
gender: String(row.getCell(4).value || '').trim() || undefined,
ethnicity: String(row.getCell(5).value || '').trim() || undefined,
phone: String(row.getCell(6).value || '').trim() || undefined,
idNumber: String(row.getCell(7).value || '').trim() || undefined,
checkInDate: parseDate(row.getCell(8)),
checkOutDate: parseDate(row.getCell(9)) || undefined,
emergencyContact: String(row.getCell(10).value || '').trim() || undefined,
emergencyPhone: String(row.getCell(11).value || '').trim() || undefined,
organization: String(row.getCell(12).value || '').trim() || undefined,
supervisor: String(row.getCell(13).value || '').trim() || undefined,
});
});
const result = await this.service.batchImportCheckIn(rows, {
autoDeposit: autoDeposit === 'true',
depositAmount: depositAmount ? +depositAmount : undefined,
});
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '入住', action: '批量导入入住', detail: result.message, ipAddress, userAgent });
return result;
}
}

View File

@@ -0,0 +1,17 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Occupancy } from '../entities/occupancy.entity';
import { Room } from '../entities/room.entity';
import { Student } from '../entities/student.entity';
import { Deposit } from '../entities/deposit.entity';
import { OccupanciesService } from './occupancies.service';
import { OccupanciesController } from './occupancies.controller';
import { OperationLogsModule } from '../operation-logs/operation-logs.module';
@Module({
imports: [TypeOrmModule.forFeature([Occupancy, Room, Student, Deposit]), OperationLogsModule],
controllers: [OccupanciesController],
providers: [OccupanciesService],
exports: [OccupanciesService],
})
export class OccupanciesModule {}

View File

@@ -0,0 +1,393 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource, IsNull, Between, LessThanOrEqual, MoreThanOrEqual, In } from 'typeorm';
import { Occupancy } from '../entities/occupancy.entity';
import { Room } from '../entities/room.entity';
import { Student } from '../entities/student.entity';
import { Deposit } from '../entities/deposit.entity';
import { CheckInDto, CheckOutDto, TransferRoomDto } from './dto/occupancy.dto';
import { RoomsService } from '../rooms/rooms.service';
@Injectable()
export class OccupanciesService {
constructor(
@InjectRepository(Occupancy) private repo: Repository<Occupancy>,
@InjectRepository(Room) private roomRepo: Repository<Room>,
@InjectRepository(Student) private studentRepo: Repository<Student>,
@InjectRepository(Deposit) private depositRepo: Repository<Deposit>,
private dataSource: DataSource,
) {}
async findAll(query?: { roomId?: number; studentId?: number; active?: boolean }) {
const qb = this.repo.createQueryBuilder('o')
.leftJoinAndSelect('o.student', 'student')
.leftJoinAndSelect('o.room', 'room')
.orderBy('o.checkInDate', 'DESC');
if (query?.roomId) qb.andWhere('o.roomId = :roomId', { roomId: query.roomId });
if (query?.studentId) qb.andWhere('o.studentId = :studentId', { studentId: query.studentId });
if (query?.active) qb.andWhere('o.checkOutDate IS NULL');
return qb.getMany();
}
async checkIn(dto: CheckInDto) {
// 检查学生是否已有活跃入住
const existing = await this.repo.findOne({ where: { studentId: dto.studentId, checkOutDate: IsNull() } });
if (existing) throw new BadRequestException('该学生已有在住记录,请先办理退宿');
// 检查宿舍容量
const room = await this.roomRepo.findOne({ where: { id: dto.roomId } });
if (!room) throw new NotFoundException('宿舍不存在');
const count = await this.repo.count({ where: { roomId: dto.roomId, checkOutDate: IsNull() } });
if (count >= room.capacity) throw new BadRequestException('宿舍已满');
// 房间级别性别约束
const student = await this.studentRepo.findOne({ where: { id: dto.studentId } });
if (!student) throw new NotFoundException('学生不存在');
if (student.gender && room.gender && student.gender !== room.gender) {
throw new BadRequestException(`该宿舍当前为${room.gender}生寝室,${student.gender}生无法入住`);
}
const occ = this.repo.create({
studentId: dto.studentId,
roomId: dto.roomId,
checkInDate: dto.checkInDate,
billingStartDate: dto.billingStartDate || dto.checkInDate,
notes: dto.notes,
});
const saved = await this.repo.save(occ);
// 首位入住者确定房间性别
if (student.gender && !room.gender) {
await this.roomRepo.update(room.id, { gender: student.gender });
}
// 更新宿舍状态
if (count + 1 >= room.capacity) {
await this.roomRepo.update(room.id, { status: 'full' });
}
return saved;
}
async checkOut(occupancyId: number, dto: CheckOutDto) {
const occ = await this.repo.findOne({ where: { id: occupancyId } });
if (!occ) throw new NotFoundException('入住记录不存在');
if (occ.checkOutDate) throw new BadRequestException('该记录已退宿');
occ.checkOutDate = dto.checkOutDate;
occ.billingEndDate = dto.billingEndDate || dto.checkOutDate;
occ.checkOutReason = dto.checkOutReason || '';
await this.repo.save(occ);
// 更新宿舍状态
await this.roomRepo.update(occ.roomId, { status: 'available' });
// 如果房间已无在住人员,重置房间性别
const remaining = await this.repo.count({ where: { roomId: occ.roomId, checkOutDate: IsNull() } });
if (remaining === 0) {
await this.roomRepo.update(occ.roomId, { gender: null as any });
}
return occ;
}
async transferRoom(occupancyId: number, dto: TransferRoomDto) {
const runner = this.dataSource.createQueryRunner();
await runner.connect();
await runner.startTransaction();
try {
const oldOcc = await runner.manager.findOne(Occupancy, { where: { id: occupancyId } });
if (!oldOcc) throw new NotFoundException('入住记录不存在');
if (oldOcc.checkOutDate) throw new BadRequestException('该记录已退宿');
// 退旧房
oldOcc.checkOutDate = dto.transferDate;
oldOcc.billingEndDate = dto.oldBillingEndDate || dto.transferDate;
oldOcc.checkOutReason = dto.reason || '换房';
await runner.manager.save(oldOcc);
await runner.manager.update(Room, oldOcc.roomId, { status: 'available' });
// 旧房如果已无在住人员,重置性别
const oldRemaining = await runner.manager.count(Occupancy, { where: { roomId: oldOcc.roomId, checkOutDate: IsNull() } });
if (oldRemaining === 0) {
await runner.manager.update(Room, oldOcc.roomId, { gender: null as any });
}
// 检查新房容量
const newRoom = await runner.manager.findOne(Room, { where: { id: dto.newRoomId } });
if (!newRoom) throw new NotFoundException('目标宿舍不存在');
const count = await runner.manager.count(Occupancy, { where: { roomId: dto.newRoomId, checkOutDate: IsNull() } });
if (count >= newRoom.capacity) throw new BadRequestException('目标宿舍已满');
// 换房性别约束检查
const student = await runner.manager.findOne(Student, { where: { id: oldOcc.studentId } });
if (student?.gender && newRoom.gender && student.gender !== newRoom.gender) {
throw new BadRequestException(`目标宿舍为${newRoom.gender}生寝室,无法换入`);
}
// 计算新房计费起始日:默认为换房日期次日
const transferDate = new Date(dto.transferDate);
const nextDay = new Date(transferDate);
nextDay.setDate(nextDay.getDate() + 1);
const defaultBillingStart = nextDay.toISOString().split('T')[0];
// 入住新房
const newOcc = runner.manager.create(Occupancy, {
studentId: oldOcc.studentId,
roomId: dto.newRoomId,
checkInDate: dto.transferDate,
billingStartDate: dto.newBillingStartDate || defaultBillingStart,
notes: `${oldOcc.roomId}号房换入`,
});
await runner.manager.save(newOcc);
// 首位入住者确定新房性别
if (student?.gender && !newRoom.gender) {
await runner.manager.update(Room, newRoom.id, { gender: student.gender });
}
if (count + 1 >= newRoom.capacity) {
await runner.manager.update(Room, newRoom.id, { status: 'full' });
}
await runner.commitTransaction();
return { oldOccupancy: oldOcc, newOccupancy: newOcc };
} catch (err) {
await runner.rollbackTransaction();
throw err;
} finally {
await runner.release();
}
}
// 获取某宿舍在指定时间段内的入住记录(用于计费)
async getRoomOccupanciesInPeriod(roomId: number, periodStart: string, periodEnd: string) {
return this.repo.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();
}
async remove(id: number) {
const occ = await this.repo.findOne({ where: { id } });
if (!occ) throw new NotFoundException('入住记录不存在');
if (!occ.checkOutDate) throw new BadRequestException('在住记录不能删除,请先办理退宿');
await this.repo.delete(id);
return { message: '删除成功' };
}
async batchRemove(ids: number[]) {
if (!ids || ids.length === 0) throw new BadRequestException('请选择要删除的记录');
const records = await this.repo.find({ where: { id: In(ids) }, relations: ['student'] });
const skipped: string[] = [];
const deletableIds: number[] = [];
for (const occ of records) {
if (!occ.checkOutDate) {
skipped.push(occ.student?.name || `记录${occ.id}`);
} else {
deletableIds.push(occ.id);
}
}
let deleted = 0;
if (deletableIds.length > 0) {
const result = await this.repo.createQueryBuilder()
.delete()
.where('id IN (:...ids)', { ids: deletableIds })
.execute();
deleted = result.affected || 0;
}
const message = skipped.length > 0
? `成功删除 ${deleted} 条;${skipped.length} 条在住记录被跳过(${skipped.slice(0, 5).join('、')}${skipped.length > 5 ? '…' : ''}),请先办理退宿`
: `批量删除成功,共 ${deleted}`;
return { message, deleted, skipped: skipped.length };
}
async batchCheckOut(dto: { ids: number[]; checkOutDate: string; billingEndDate?: string; checkOutReason?: string }) {
if (!dto.ids || dto.ids.length === 0) {
throw new BadRequestException('请选择要退宿的记录');
}
const runner = this.dataSource.createQueryRunner();
await runner.connect();
await runner.startTransaction();
let success = 0;
const errors: string[] = [];
try {
for (const id of dto.ids) {
const occ = await runner.manager.findOne(Occupancy, { where: { id }, relations: ['student'] });
if (!occ) { errors.push(`记录${id}不存在`); continue; }
if (occ.checkOutDate) { errors.push(`${occ.student?.name || id}已退宿`); continue; }
occ.checkOutDate = dto.checkOutDate;
occ.billingEndDate = dto.billingEndDate || dto.checkOutDate;
occ.checkOutReason = dto.checkOutReason || '';
await runner.manager.save(occ);
// 更新房间状态
await runner.manager.update(Room, occ.roomId, { status: 'available' });
// 如果房间已无在住人员,重置性别
const remaining = await runner.manager.count(Occupancy, { where: { roomId: occ.roomId, checkOutDate: IsNull() } });
if (remaining === 0) {
await runner.manager.update(Room, occ.roomId, { gender: null as any });
}
success++;
}
await runner.commitTransaction();
} catch (err) {
await runner.rollbackTransaction();
throw err;
} finally {
await runner.release();
}
return { success, failed: errors.length, message: `已成功退宿 ${success}${errors.length > 0 ? `${errors.length} 条失败` : ''}`, errors: errors.length > 0 ? errors : undefined };
}
/**
* 一键导入入住名单
* 每行数据:姓名、电话、学号、房间号、楼栋、入住日期
* 自动创建不存在的学生和宿舍,并登记入住
*/
async batchImportCheckIn(rows: {
name: string; phone?: string; idNumber?: string;
gender?: string; ethnicity?: string; emergencyContact?: string; emergencyPhone?: string;
organization?: string; supervisor?: string;
roomNumber: string; building?: string;
checkInDate: string; checkOutDate?: string;
}[], options?: { autoDeposit?: boolean; depositAmount?: number }) {
let imported = 0;
let skipped = 0;
let depositsCreated = 0;
const errors: string[] = [];
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
const rowNum = i + 2; // Excel第2行开始第1行是表头
if (!row.name?.trim() || !row.roomNumber?.trim()) {
skipped++;
continue;
}
try {
// 1. 查找或创建学生
let student = await this.studentRepo.findOne({ where: { name: row.name.trim() } });
if (!student) {
student = await this.studentRepo.save(this.studentRepo.create({
name: row.name.trim(),
phone: row.phone?.trim() || undefined,
idNumber: row.idNumber?.trim() || undefined,
gender: row.gender?.trim() || undefined,
ethnicity: row.ethnicity?.trim() || undefined,
emergencyContact: row.emergencyContact?.trim() || undefined,
emergencyPhone: row.emergencyPhone?.trim() || undefined,
organization: row.organization?.trim() || undefined,
supervisor: row.supervisor?.trim() || undefined,
}));
} else {
// 更新已有学生的缺失信息
const updates: any = {};
if (!student.phone && row.phone?.trim()) updates.phone = row.phone.trim();
if (!student.idNumber && row.idNumber?.trim()) updates.idNumber = row.idNumber.trim();
if (!student.gender && row.gender?.trim()) updates.gender = row.gender.trim();
if (!student.ethnicity && row.ethnicity?.trim()) updates.ethnicity = row.ethnicity.trim();
if (!student.emergencyContact && row.emergencyContact?.trim()) updates.emergencyContact = row.emergencyContact.trim();
if (!student.emergencyPhone && row.emergencyPhone?.trim()) updates.emergencyPhone = row.emergencyPhone.trim();
if (!student.organization && row.organization?.trim()) updates.organization = row.organization.trim();
if (!student.supervisor && row.supervisor?.trim()) updates.supervisor = row.supervisor.trim();
if (Object.keys(updates).length > 0) {
await this.studentRepo.update(student.id, updates);
Object.assign(student, updates);
}
}
// 2. 查找或创建宿舍(使用智能解析)
let room = await this.roomRepo.findOne({ where: { roomNumber: row.roomNumber.trim() } });
if (!room) {
const parsed = RoomsService.parseRoomNumber(row.roomNumber.trim());
room = await this.roomRepo.save(this.roomRepo.create({
roomNumber: row.roomNumber.trim(),
building: row.building?.trim() || parsed.building || undefined,
floor: parsed.floor || undefined,
capacity: parsed.capacity || 4,
roomType: parsed.roomType || undefined,
}));
}
// 3. 检查是否已有活跃入住
const existing = await this.repo.findOne({ where: { studentId: student.id, checkOutDate: IsNull() }, relations: ['room'] });
if (existing) {
errors.push(`${rowNum}行: ${row.name} 已在住(${existing.room?.roomNumber || '房间' + existing.roomId}),跳过`);
skipped++;
continue;
}
// 4. 检查宿舍容量
const count = await this.repo.count({ where: { roomId: room.id, checkOutDate: IsNull() } });
if (count >= room.capacity) {
errors.push(`${rowNum}行: 宿舍 ${row.roomNumber} 已满(${count}/${room.capacity}),跳过 ${row.name}`);
skipped++;
continue;
}
// 5. 房间级别性别约束
if (student.gender && room.gender && student.gender !== room.gender) {
errors.push(`${rowNum}行: 宿舍 ${row.roomNumber}${room.gender}生寝室,${row.name}(${student.gender})无法入住,跳过`);
skipped++;
continue;
}
// 6. 创建入住记录
const checkInDate = row.checkInDate?.trim() || new Date().toISOString().split('T')[0];
const occData: any = {
studentId: student.id,
roomId: room.id,
checkInDate,
billingStartDate: checkInDate,
};
// 如果有退宿日期,直接记录
if (row.checkOutDate?.trim()) {
occData.checkOutDate = row.checkOutDate.trim();
occData.billingEndDate = row.checkOutDate.trim();
}
await this.repo.save(this.repo.create(occData));
// 7. 首位入住者确定房间性别
if (student.gender && !room.gender) {
await this.roomRepo.update(room.id, { gender: student.gender });
room.gender = student.gender;
}
// 8. 更新宿舍状态
if (!row.checkOutDate?.trim() && count + 1 >= room.capacity) {
await this.roomRepo.update(room.id, { status: 'full' });
}
// 9. 自动收取押金(仅对新入住且非历史记录的学生)
if (options?.autoDeposit && !row.checkOutDate?.trim()) {
const existingDeposit = await this.depositRepo.findOne({ where: { studentId: student.id, status: 'paid' } });
if (!existingDeposit) {
await this.depositRepo.save(this.depositRepo.create({
studentId: student.id,
amount: options.depositAmount || 500,
paidDate: checkInDate,
status: 'paid',
notes: '入住导入自动收取',
}));
depositsCreated++;
}
}
imported++;
} catch (e: any) {
errors.push(`${rowNum}行: ${row.name} 导入失败 - ${e.message}`);
skipped++;
}
}
const depositMsg = depositsCreated > 0 ? `,自动收取 ${depositsCreated} 笔押金` : '';
return {
message: `成功导入 ${imported} 条入住记录,跳过 ${skipped}${depositMsg}`,
imported,
skipped,
depositsCreated,
errors: errors.length > 0 ? errors : undefined,
};
}
}

View File

@@ -0,0 +1,28 @@
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
import { OperationLogsService } from './operation-logs.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
@UseGuards(JwtAuthGuard)
@Controller('operation-logs')
export class OperationLogsController {
constructor(private service: OperationLogsService) {}
@Get()
findAll(
@Query('module') module?: string,
@Query('userId') userId?: string,
@Query('startDate') startDate?: string,
@Query('endDate') endDate?: string,
@Query('page') page?: string,
@Query('pageSize') pageSize?: string,
) {
return this.service.findAll({
module,
userId: userId ? +userId : undefined,
startDate,
endDate,
page: page ? +page : 1,
pageSize: pageSize ? +pageSize : 50,
});
}
}

View File

@@ -0,0 +1,14 @@
import { Module, Global } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { OperationLog } from '../entities/operation-log.entity';
import { OperationLogsService } from './operation-logs.service';
import { OperationLogsController } from './operation-logs.controller';
@Global()
@Module({
imports: [TypeOrmModule.forFeature([OperationLog])],
controllers: [OperationLogsController],
providers: [OperationLogsService],
exports: [OperationLogsService],
})
export class OperationLogsModule {}

View File

@@ -0,0 +1,48 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { OperationLog } from '../entities/operation-log.entity';
@Injectable()
export class OperationLogsService {
constructor(
@InjectRepository(OperationLog) private repo: Repository<OperationLog>,
) {}
async log(params: {
userId?: number;
username?: string;
module: string;
action: string;
targetId?: number;
targetType?: string;
detail?: string;
ipAddress?: string;
userAgent?: string;
status?: string;
}) {
const entry = this.repo.create(params);
return this.repo.save(entry);
}
async findAll(query?: {
module?: string;
userId?: number;
startDate?: string;
endDate?: string;
page?: number;
pageSize?: number;
}) {
const qb = this.repo.createQueryBuilder('log')
.orderBy('log.createdAt', 'DESC');
if (query?.module) qb.andWhere('log.module = :module', { module: query.module });
if (query?.userId) qb.andWhere('log.userId = :userId', { userId: query.userId });
if (query?.startDate) qb.andWhere('log.createdAt >= :startDate', { startDate: query.startDate });
if (query?.endDate) qb.andWhere('log.createdAt <= :endDate', { endDate: query.endDate + ' 23:59:59' });
const page = query?.page || 1;
const pageSize = query?.pageSize || 50;
const [data, total] = await qb.skip((page - 1) * pageSize).take(pageSize).getManyAndCount();
return { data, total, page, pageSize };
}
}

View File

@@ -0,0 +1,53 @@
import { IsString, IsOptional, IsInt, IsEnum, Min } from 'class-validator';
export class CreateRoomDto {
@IsString()
roomNumber: string;
@IsOptional()
@IsString()
building?: string;
@IsOptional()
@IsInt()
floor?: number;
@IsInt()
@Min(1)
capacity: number;
@IsOptional()
@IsString()
roomType?: string;
}
export class UpdateRoomDto {
@IsOptional()
@IsString()
roomNumber?: string;
@IsOptional()
@IsString()
building?: string;
@IsOptional()
@IsInt()
floor?: number;
@IsOptional()
@IsInt()
@Min(1)
capacity?: number;
@IsOptional()
@IsString()
roomType?: string;
@IsOptional()
@IsString()
gender?: string;
@IsOptional()
@IsEnum(['available', 'full', 'maintenance'])
status?: string;
}

View File

@@ -0,0 +1,146 @@
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 { RoomsService } from './rooms.service';
import { CreateRoomDto, UpdateRoomDto } from './dto/room.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
import { extractRequestInfo } from '../common/request-utils';
import * as ExcelJS from 'exceljs';
@UseGuards(JwtAuthGuard)
@Controller('rooms')
export class RoomsController {
constructor(private service: RoomsService, private logService: OperationLogsService) {}
@Get()
findAll(@Query('building') building?: string, @Query('includeArchived') includeArchived?: string) {
return this.service.findAll({ building, includeArchived: includeArchived === 'true' });
}
@Get('overview')
getOverview(@Query('includeArchived') includeArchived?: string) {
return this.service.getRoomOverview({ includeArchived: includeArchived === 'true' });
}
@Get('visual')
getVisual() {
return this.service.getRoomVisual();
}
@Get('template')
async downloadTemplate(@Res() res: Response) {
const workbook = new ExcelJS.Workbook();
const ws = workbook.addWorksheet('宿舍导入模板');
ws.columns = [
{ header: '房间号', key: 'roomNumber', width: 12 },
{ header: '楼栋', key: 'building', width: 12 },
{ header: '楼层', key: 'floor', width: 8 },
{ header: '额定人数', key: 'capacity', width: 10 },
{ header: '宿舍类型', key: 'roomType', width: 12 },
];
ws.getRow(1).font = { bold: true };
ws.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
ws.addRow({ roomNumber: '4-102', building: '4号楼', floor: 1, capacity: 4, roomType: '四人间' });
ws.addRow({ roomNumber: '2-201', building: '2号楼', floor: 2, capacity: 1, roomType: '单人间' });
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename=room_template.xlsx');
await workbook.xlsx.write(res);
res.end();
}
@Get('export')
async exportExcel(@Query('includeArchived') includeArchived?: string, @Res() res?: Response) {
const rooms = await this.service.getRoomOverview({ includeArchived: includeArchived === 'true' });
const workbook = new ExcelJS.Workbook();
const ws = workbook.addWorksheet('宿舍列表');
ws.columns = [
{ header: '房间号', key: 'roomNumber', width: 12 },
{ header: '楼栋', key: 'building', width: 12 },
{ header: '楼层', key: 'floor', width: 8 },
{ header: '宿舍类型', key: 'roomType', width: 12 },
{ header: '额定人数', key: 'capacity', width: 10 },
{ header: '当前入住', key: 'currentCount', width: 10 },
{ header: '性别', key: 'gender', width: 8 },
{ header: '状态', key: 'status', width: 10 },
];
ws.getRow(1).font = { bold: true };
ws.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
const statusMap: Record<string, string> = { available: '可入住', full: '已满', maintenance: '维修中', archived: '已归档' };
for (const r of rooms) {
ws.addRow({ roomNumber: r.roomNumber, building: r.building || '', floor: r.floor || '', roomType: r.roomType || '', capacity: r.capacity, currentCount: r.currentCount, gender: r.gender || '', status: statusMap[r.status] || r.status });
}
res!.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res!.setHeader('Content-Disposition', 'attachment; filename=rooms.xlsx');
await workbook.xlsx.write(res!);
res!.end();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.service.findOneWithOccupants(+id);
}
@Post()
async create(@Body() dto: CreateRoomDto, @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: '添加宿舍', detail: `房间号: ${dto.roomNumber}, 楼栋: ${dto.building || '无'}, 额定: ${dto.capacity}`, ipAddress, userAgent });
return result;
}
@Put(':id')
async update(@Param('id') id: string, @Body() dto: UpdateRoomDto, @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: 'room', detail: JSON.stringify(dto), ipAddress, userAgent });
return result;
}
@Delete(':id')
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: 'room', ipAddress, userAgent });
return result;
}
@Post('batch-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;
}
@Put(':id/restore')
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: 'room', ipAddress, userAgent });
return result;
}
@Post('import')
@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: { roomNumber: string; building?: string; floor?: number; capacity?: number; roomType?: string }[] = [];
ws.eachRow((row, idx) => {
if (idx === 1) return;
rows.push({
roomNumber: String(row.getCell(1).value || ''),
building: String(row.getCell(2).value || '') || undefined,
floor: Number(row.getCell(3).value) || undefined,
capacity: Number(row.getCell(4).value) || 4,
roomType: String(row.getCell(5).value || '').trim() || 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;
}
}

View File

@@ -0,0 +1,16 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Room } from '../entities/room.entity';
import { Occupancy } from '../entities/occupancy.entity';
import { RoomExpense } from '../entities/room-expense.entity';
import { RoomsService } from './rooms.service';
import { RoomsController } from './rooms.controller';
import { OperationLogsModule } from '../operation-logs/operation-logs.module';
@Module({
imports: [TypeOrmModule.forFeature([Room, Occupancy, RoomExpense]), OperationLogsModule],
controllers: [RoomsController],
providers: [RoomsService],
exports: [RoomsService],
})
export class RoomsModule {}

View File

@@ -0,0 +1,224 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, IsNull, Not, In } from 'typeorm';
import { Room } from '../entities/room.entity';
import { Occupancy } from '../entities/occupancy.entity';
import { RoomExpense } from '../entities/room-expense.entity';
import { CreateRoomDto, UpdateRoomDto } from './dto/room.dto';
@Injectable()
export class RoomsService {
constructor(
@InjectRepository(Room) private repo: Repository<Room>,
@InjectRepository(Occupancy) private occRepo: Repository<Occupancy>,
@InjectRepository(RoomExpense) private roomExpRepo: Repository<RoomExpense>,
) {}
/**
* 智能解析房间号,自动推导楼栋、楼层、宿舍类型
* "4-102" → building:"4号楼", floor:1, roomType:"四人间"
* "1-2-101" → building:"1-2栋", floor:1, roomType:"家庭房"
* "3-301" → building:"3号楼", floor:3, roomType:"四人间"
* "8-102" → building:"8号楼", floor:1, roomType:"爆改房"
*/
static parseRoomNumber(roomNumber: string): { building?: string; floor?: number; roomType?: string; capacity?: number } {
const cleaned = roomNumber.replace(/[(].*?[)]/g, '').trim();
// 家庭房: X-Y-ZZZ 格式
const familyMatch = cleaned.match(/^(\d+)-(\d+)-(\d+)$/);
if (familyMatch) {
const bldg = `${familyMatch[1]}-${familyMatch[2]}`;
const roomPart = familyMatch[3];
const floor = parseInt(roomPart.charAt(0), 10) || undefined;
return { building: bldg, floor, roomType: '家庭房', capacity: 4 };
}
// 标准: X-YZZ 格式
const stdMatch = cleaned.match(/^(\d+)-(\d+)$/);
if (stdMatch) {
const bldgNum = stdMatch[1];
const roomPart = stdMatch[2];
const floor = roomPart.length >= 3 ? parseInt(roomPart.charAt(0), 10) : parseInt(roomPart.charAt(0), 10);
const building = `${bldgNum}号楼`;
let roomType = '四人间';
let capacity = 4;
if (bldgNum === '2') { roomType = '单人间'; capacity = 1; }
else if (bldgNum === '8') { roomType = '爆改房'; capacity = 2; }
return { building, floor, roomType, capacity };
}
return {};
}
async findAll(query?: { building?: string; includeArchived?: boolean }) {
const where: any = {};
if (query?.building) where.building = query.building;
if (!query?.includeArchived) where.status = Not('archived');
return this.repo.find({ where, order: { roomNumber: 'ASC' } });
}
async findOne(id: number) {
const room = await this.repo.findOne({ where: { id } });
if (!room) throw new NotFoundException('宿舍不存在');
return room;
}
async findOneWithOccupants(id: number) {
const room = await this.findOne(id);
const occupants = await this.occRepo.find({
where: { roomId: id, checkOutDate: IsNull() },
relations: ['student'],
order: { checkInDate: 'ASC' },
});
return { ...room, currentOccupants: occupants };
}
async getRoomOverview(query?: { includeArchived?: boolean }) {
const where: any = {};
if (!query?.includeArchived) where.status = Not('archived');
const rooms = await this.repo.find({ where, order: { building: 'ASC', roomNumber: 'ASC' } });
const result: any[] = [];
for (const room of rooms) {
const count = await this.occRepo.count({ where: { roomId: room.id, checkOutDate: IsNull() } });
result.push({ ...room, currentCount: count });
}
return result;
}
async create(dto: CreateRoomDto) {
return this.repo.save(this.repo.create(dto));
}
async update(id: number, dto: UpdateRoomDto) {
await this.findOne(id);
await this.repo.update(id, dto);
return this.repo.findOne({ where: { id } });
}
async remove(id: number) {
const room = await this.findOne(id);
// 检查是否有在住人员
const activeCount = await this.occRepo.count({ where: { roomId: id, checkOutDate: IsNull() } });
if (activeCount > 0) throw new BadRequestException('该宿舍有在住人员,无法归档');
if (room.status === 'archived') throw new BadRequestException('该宿舍已归档');
// 软删除:归档而非物理删除
await this.repo.update(id, { status: 'archived' });
return { message: '已归档(数据已保留,可随时恢复)' };
}
async batchRemove(ids: number[]) {
if (!ids || ids.length === 0) throw new BadRequestException('请选择要归档的宿舍');
const rooms = await this.repo.find({ where: { id: In(ids) } });
const skipped: string[] = [];
const targetIds: number[] = [];
for (const r of rooms) {
if (r.status === 'archived') {
skipped.push(`${r.roomNumber}(已归档)`);
continue;
}
const activeCount = await this.occRepo.count({ where: { roomId: r.id, checkOutDate: IsNull() } });
if (activeCount > 0) {
skipped.push(`${r.roomNumber}(有在住人员)`);
continue;
}
targetIds.push(r.id);
}
let affected = 0;
if (targetIds.length > 0) {
const result = await this.repo.createQueryBuilder()
.update()
.set({ status: 'archived' })
.where('id IN (:...ids)', { ids: targetIds })
.execute();
affected = result.affected || 0;
}
const message = skipped.length > 0
? `成功归档 ${affected} 间;${skipped.length} 间被跳过(${skipped.slice(0, 5).join('、')}${skipped.length > 5 ? '…' : ''}`
: `已批量归档 ${affected} 间宿舍(数据已保留,可随时恢复)`;
return { message, archived: affected, skipped: skipped.length };
}
async restore(id: number) {
const room = await this.findOne(id);
if (room.status !== 'archived') throw new BadRequestException('该宿舍未被归档');
await this.repo.update(id, { status: 'available' });
return { message: '已恢复' };
}
async getRoomVisual() {
const rooms = await this.repo.find({ where: { status: Not('archived') }, order: { building: 'ASC', roomNumber: 'ASC' } });
const occupancies = await this.occRepo.find({
where: { checkOutDate: IsNull() },
relations: ['student'],
order: { checkInDate: 'ASC' },
});
// 按roomId分组入住记录
const occMap = new Map<number, any[]>();
for (const occ of occupancies) {
if (!occMap.has(occ.roomId)) occMap.set(occ.roomId, []);
const now = new Date();
const checkIn = new Date(occ.checkInDate);
const days = Math.max(1, Math.ceil((now.getTime() - checkIn.getTime()) / (1000 * 60 * 60 * 24)));
occMap.get(occ.roomId)!.push({
studentId: occ.studentId,
studentName: occ.student?.name || '未知',
checkInDate: occ.checkInDate,
billingStartDate: occ.billingStartDate,
days,
organization: occ.student?.organization || null,
supervisor: occ.student?.supervisor || null,
});
}
// 获取各楼栋列表
const buildings = [...new Set(rooms.map((r) => r.building).filter(Boolean))];
return {
buildings,
rooms: rooms.map((room) => {
const occ = occMap.get(room.id) || [];
// 计算机构标注
const orgs = [...new Set(occ.map((o: any) => o.organization).filter(Boolean))];
let orgLabel: string | null = null;
if (orgs.length > 0 && occ.length > 0) {
const allSameOrg = occ.every((o: any) => o.organization && o.organization === orgs[0]);
if (allSameOrg) {
orgLabel = `均为${orgs[0]}人员`;
} else {
orgLabel = `存在${orgs.join('、')}人员`;
}
}
return {
id: room.id,
roomNumber: room.roomNumber,
building: room.building,
floor: room.floor,
capacity: room.capacity,
status: room.status,
currentCount: occ.length,
occupants: occ,
orgLabel,
};
}),
};
}
async batchImport(rows: { roomNumber: string; building?: string; floor?: number; capacity?: number; roomType?: string }[]) {
let imported = 0;
let skipped = 0;
for (const row of rows) {
if (!row.roomNumber || !row.roomNumber.trim()) { skipped++; continue; }
const exists = await this.repo.findOne({ where: { roomNumber: row.roomNumber.trim() } });
if (exists) { skipped++; continue; }
// 智能解析房间号
const parsed = RoomsService.parseRoomNumber(row.roomNumber.trim());
await this.repo.save(this.repo.create({
roomNumber: row.roomNumber.trim(),
building: row.building?.trim() || parsed.building || undefined,
floor: row.floor || parsed.floor || undefined,
capacity: row.capacity || parsed.capacity || 4,
roomType: row.roomType || parsed.roomType || undefined,
}));
imported++;
}
return { message: `成功导入 ${imported} 间宿舍,跳过 ${skipped} 条(重复或空行)`, imported, skipped };
}
}

View File

@@ -0,0 +1,80 @@
import { IsString, IsOptional, IsEnum } from 'class-validator';
export class CreateStudentDto {
@IsString()
name: string;
@IsOptional()
@IsString()
phone?: string;
@IsOptional()
@IsString()
idNumber?: string;
@IsOptional()
@IsString()
gender?: string;
@IsOptional()
@IsString()
ethnicity?: string;
@IsOptional()
@IsString()
emergencyContact?: string;
@IsOptional()
@IsString()
emergencyPhone?: string;
@IsOptional()
@IsString()
organization?: string;
@IsOptional()
@IsString()
supervisor?: string;
}
export class UpdateStudentDto {
@IsOptional()
@IsString()
name?: string;
@IsOptional()
@IsString()
phone?: string;
@IsOptional()
@IsString()
idNumber?: string;
@IsOptional()
@IsString()
gender?: string;
@IsOptional()
@IsString()
ethnicity?: string;
@IsOptional()
@IsString()
emergencyContact?: string;
@IsOptional()
@IsString()
emergencyPhone?: string;
@IsOptional()
@IsString()
organization?: string;
@IsOptional()
@IsString()
supervisor?: string;
@IsOptional()
@IsEnum(['active', 'graduated', 'withdrawn'])
status?: string;
}

View File

@@ -0,0 +1,145 @@
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 { StudentsService } from './students.service';
import { CreateStudentDto, UpdateStudentDto } from './dto/student.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
import { extractRequestInfo } from '../common/request-utils';
import * as ExcelJS from 'exceljs';
@UseGuards(JwtAuthGuard)
@Controller('students')
export class StudentsController {
constructor(private service: StudentsService, private logService: OperationLogsService) {}
@Get()
findAll(@Query('name') name?: string, @Query('status') status?: string, @Query('includeArchived') includeArchived?: string) {
return this.service.findAll({ name, status, includeArchived: includeArchived === 'true' });
}
@Get('export')
async exportExcel(@Query('includeArchived') includeArchived?: string, @Res() res?: Response) {
const students = await this.service.findAll({ includeArchived: includeArchived === 'true' });
const workbook = new ExcelJS.Workbook();
const ws = workbook.addWorksheet('学生名单');
ws.columns = [
{ header: '姓名', key: 'name', width: 12 },
{ header: '性别', key: 'gender', width: 8 },
{ header: '电话', key: 'phone', width: 18 },
{ header: '学号/身份证', key: 'idNumber', width: 22 },
{ header: '民族', key: 'ethnicity', width: 10 },
{ header: '紧急联系人', key: 'emergencyContact', width: 15 },
{ header: '紧急联系人电话', key: 'emergencyPhone', width: 18 },
{ header: '所属机构', key: 'organization', width: 18 },
{ header: '负责人/班主任', key: 'supervisor', width: 15 },
{ header: '状态', key: 'status', width: 10 },
];
ws.getRow(1).font = { bold: true };
ws.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
const statusMap: Record<string, string> = { active: '在读', graduated: '已毕业', withdrawn: '已退训', archived: '已归档' };
for (const s of students) {
ws.addRow({ name: s.name, gender: s.gender || '', phone: s.phone || '', idNumber: s.idNumber || '', ethnicity: s.ethnicity || '', emergencyContact: s.emergencyContact || '', emergencyPhone: s.emergencyPhone || '', organization: s.organization || '', supervisor: s.supervisor || '', status: statusMap[s.status] || s.status });
}
res!.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res!.setHeader('Content-Disposition', 'attachment; filename=students.xlsx');
await workbook.xlsx.write(res!);
res!.end();
}
@Get('template')
async downloadTemplate(@Res() res: Response) {
const workbook = new ExcelJS.Workbook();
const ws = workbook.addWorksheet('学生导入模板');
ws.columns = [
{ header: '姓名', key: 'name', width: 15 },
{ header: '电话', key: 'phone', width: 18 },
{ header: '学号/身份证', key: 'idNumber', width: 22 },
{ header: '性别', key: 'gender', width: 8 },
{ header: '民族', key: 'ethnicity', width: 10 },
{ header: '紧急联系人', key: 'emergencyContact', width: 15 },
{ header: '紧急联系人电话', key: 'emergencyPhone', width: 18 },
{ header: '所属机构', key: 'organization', width: 18 },
{ header: '负责人/班主任', key: 'supervisor', width: 15 },
];
ws.getRow(1).font = { bold: true };
ws.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
ws.addRow({ name: '张三', phone: '13800138000', idNumber: '2024001', gender: '男', ethnicity: '汉族', emergencyContact: '张父', emergencyPhone: '13900000000', organization: '', supervisor: '' });
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename=student_template.xlsx');
await workbook.xlsx.write(res);
res.end();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.service.findOne(+id);
}
@Post()
async create(@Body() dto: CreateStudentDto, @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: 'student', detail: `姓名: ${dto.name}, 电话: ${dto.phone || '无'}, 学号: ${dto.idNumber || '无'}`, ipAddress, userAgent });
return result;
}
@Put(':id')
async update(@Param('id') id: string, @Body() dto: UpdateStudentDto, @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: 'student', detail: JSON.stringify(dto), ipAddress, userAgent });
return result;
}
@Delete(':id')
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: 'student', ipAddress, userAgent });
return result;
}
@Post('batch-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;
}
@Put(':id/restore')
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: 'student', ipAddress, userAgent });
return result;
}
@Post('import')
@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: { name: string; phone?: string; idNumber?: string; gender?: string; ethnicity?: string; emergencyContact?: string; emergencyPhone?: string; organization?: string; supervisor?: string }[] = [];
ws.eachRow((row, idx) => {
if (idx === 1) return;
rows.push({
name: String(row.getCell(1).value || ''),
phone: String(row.getCell(2).value || ''),
idNumber: String(row.getCell(3).value || ''),
gender: String(row.getCell(4).value || '').trim() || undefined,
ethnicity: String(row.getCell(5).value || '').trim() || undefined,
emergencyContact: String(row.getCell(6).value || '').trim() || undefined,
emergencyPhone: String(row.getCell(7).value || '').trim() || undefined,
organization: String(row.getCell(8).value || '').trim() || undefined,
supervisor: String(row.getCell(9).value || '').trim() || 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;
}
}

View File

@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Student } from '../entities/student.entity';
import { StudentsService } from './students.service';
import { StudentsController } from './students.controller';
@Module({
imports: [TypeOrmModule.forFeature([Student])],
controllers: [StudentsController],
providers: [StudentsService],
exports: [StudentsService],
})
export class StudentsModule {}

View File

@@ -0,0 +1,103 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, Not, In } from 'typeorm';
import { Student } from '../entities/student.entity';
import { CreateStudentDto, UpdateStudentDto } from './dto/student.dto';
@Injectable()
export class StudentsService {
constructor(@InjectRepository(Student) private repo: Repository<Student>) {}
async findAll(query?: { name?: string; status?: string; includeArchived?: boolean }) {
const where: any = {};
if (query?.name) where.name = Like(`%${query.name}%`);
if (query?.status) {
where.status = query.status;
} else if (!query?.includeArchived) {
where.status = Not('archived');
}
return this.repo.find({ where, order: { createdAt: 'DESC' } });
}
async findOne(id: number) {
const student = await this.repo.findOne({ where: { id }, relations: ['occupancies', 'occupancies.room'] });
if (!student) throw new NotFoundException('学生不存在');
return student;
}
async create(dto: CreateStudentDto) {
return this.repo.save(this.repo.create(dto));
}
async update(id: number, dto: UpdateStudentDto) {
await this.findOne(id);
await this.repo.update(id, dto);
return this.repo.findOne({ where: { id } });
}
async remove(id: number) {
const student = await this.findOne(id);
if (student.status === 'archived') {
throw new BadRequestException('该学生已归档');
}
// 软删除:归档而非物理删除,保留历史数据
await this.repo.update(id, { status: 'archived' });
return { message: '已归档(数据已保留,可随时恢复)' };
}
async batchRemove(ids: number[]) {
if (!ids || ids.length === 0) throw new BadRequestException('请选择要归档的学生');
const students = await this.repo.find({ where: { id: In(ids) } });
const skipped: string[] = [];
const targetIds: number[] = [];
for (const s of students) {
if (s.status === 'archived') skipped.push(s.name);
else targetIds.push(s.id);
}
let affected = 0;
if (targetIds.length > 0) {
const result = await this.repo.createQueryBuilder()
.update()
.set({ status: 'archived' })
.where('id IN (:...ids)', { ids: targetIds })
.execute();
affected = result.affected || 0;
}
const message = skipped.length > 0
? `成功归档 ${affected} 人;${skipped.length} 人已是归档状态被跳过(${skipped.slice(0, 5).join('、')}${skipped.length > 5 ? '…' : ''}`
: `已批量归档 ${affected} 人(数据已保留,可随时恢复)`;
return { message, archived: affected, skipped: skipped.length };
}
async restore(id: number) {
const student = await this.findOne(id);
if (student.status !== 'archived') {
throw new BadRequestException('该学生未被归档');
}
await this.repo.update(id, { status: 'active' });
return { message: '已恢复' };
}
async batchImport(rows: { name: string; phone?: string; idNumber?: string; gender?: string; ethnicity?: string; emergencyContact?: string; emergencyPhone?: string; organization?: string; supervisor?: string }[]) {
let imported = 0;
let skipped = 0;
for (const row of rows) {
if (!row.name || !row.name.trim()) { skipped++; continue; }
const exists = await this.repo.findOne({ where: { name: row.name.trim() } });
if (exists) { skipped++; continue; }
await this.repo.save(this.repo.create({
name: row.name.trim(),
phone: row.phone?.trim() || undefined,
idNumber: row.idNumber?.trim() || undefined,
gender: row.gender || undefined,
ethnicity: row.ethnicity || undefined,
emergencyContact: row.emergencyContact || undefined,
emergencyPhone: row.emergencyPhone || undefined,
organization: row.organization || undefined,
supervisor: row.supervisor || undefined,
}));
imported++;
}
return { message: `成功导入 ${imported} 名学生,跳过 ${skipped} 条(重复或空行)`, imported, skipped };
}
}

View File

@@ -0,0 +1,49 @@
import { IsOptional, IsString, IsNotEmpty, IsEnum } from 'class-validator';
export class CreateTenantDto {
@IsString()
@IsNotEmpty()
name: string;
@IsOptional()
@IsString()
contact?: string;
@IsOptional()
@IsString()
phone?: string;
@IsOptional()
@IsString()
color?: string;
@IsOptional()
@IsString()
notes?: string;
}
export class UpdateTenantDto {
@IsOptional()
@IsString()
name?: string;
@IsOptional()
@IsString()
contact?: string;
@IsOptional()
@IsString()
phone?: string;
@IsOptional()
@IsString()
color?: string;
@IsOptional()
@IsString()
notes?: string;
@IsOptional()
@IsEnum(['active', 'archived'])
status?: string;
}

View File

@@ -0,0 +1,46 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards, Request } from '@nestjs/common';
import { TenantsService } from './tenants.service';
import { CreateTenantDto, UpdateTenantDto } from './dto/tenant.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
import { extractRequestInfo } from '../common/request-utils';
@UseGuards(JwtAuthGuard)
@Controller('tenants')
export class TenantsController {
constructor(private service: TenantsService, private logService: OperationLogsService) {}
@Get()
findAll(@Query('includeArchived') includeArchived?: string) {
return this.service.findAll({ includeArchived: includeArchived === 'true' });
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.service.findOne(+id);
}
@Post()
async create(@Body() dto: CreateTenantDto, @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: 'tenant', detail: dto.name, ipAddress, userAgent });
return result;
}
@Put(':id')
async update(@Param('id') id: string, @Body() dto: UpdateTenantDto, @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: 'tenant', detail: JSON.stringify(dto), ipAddress, userAgent });
return result;
}
@Delete(':id')
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: 'tenant', ipAddress, userAgent });
return result;
}
}

View File

@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Tenant } from '../entities/tenant.entity';
import { TenantsService } from './tenants.service';
import { TenantsController } from './tenants.controller';
import { OperationLogsModule } from '../operation-logs/operation-logs.module';
@Module({
imports: [TypeOrmModule.forFeature([Tenant]), OperationLogsModule],
controllers: [TenantsController],
providers: [TenantsService],
exports: [TenantsService],
})
export class TenantsModule {}

View File

@@ -0,0 +1,50 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Not } from 'typeorm';
import { Tenant } from '../entities/tenant.entity';
import { CreateTenantDto, UpdateTenantDto } from './dto/tenant.dto';
// 预设色板(避开红绿盲敏感色,保证差异度)
const COLOR_PALETTE = [
'#ff7875', '#ffa940', '#ffc53d', '#73d13d', '#36cfc9',
'#40a9ff', '#597ef7', '#9254de', '#f759ab', '#8c8c8c',
];
@Injectable()
export class TenantsService {
constructor(@InjectRepository(Tenant) private repo: Repository<Tenant>) {}
async findAll(query?: { includeArchived?: boolean }) {
const where: any = {};
if (!query?.includeArchived) where.status = Not('archived');
return this.repo.find({ where, order: { createdAt: 'DESC' } });
}
async findOne(id: number) {
const tenant = await this.repo.findOne({ where: { id } });
if (!tenant) throw new NotFoundException('租赁方不存在');
return tenant;
}
async create(dto: CreateTenantDto) {
// 颜色未指定则自动分配(按当前租赁方数量取模)
let color = dto.color;
if (!color) {
const total = await this.repo.count();
color = COLOR_PALETTE[total % COLOR_PALETTE.length];
}
return this.repo.save(this.repo.create({ ...dto, color }));
}
async update(id: number, dto: UpdateTenantDto) {
await this.findOne(id);
await this.repo.update(id, dto);
return this.repo.findOne({ where: { id } });
}
async remove(id: number) {
await this.findOne(id);
await this.repo.update(id, { status: 'archived' });
return { message: '已归档' };
}
}

View File

@@ -0,0 +1,29 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { App } from 'supertest/types';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication<App>;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
afterEach(async () => {
await app.close();
});
});

View File

@@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

View File

@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

25
backend/tsconfig.json Normal file
View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "nodenext",
"moduleResolution": "nodenext",
"resolvePackageJsonExports": true,
"esModuleInterop": true,
"isolatedModules": true,
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2023",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"noImplicitAny": false,
"strictBindCallApply": false,
"noFallthroughCasesInSwitch": false
}
}

46
docker-compose.yml Normal file
View File

@@ -0,0 +1,46 @@
version: '3.8'
services:
mysql:
image: mysql:8.0
container_name: dorm_billing_mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: dorm_billing_2024
MYSQL_DATABASE: dorm_billing
MYSQL_CHARSET: utf8mb4
MYSQL_COLLATION: utf8mb4_unicode_ci
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
command: --default-authentication-plugin=mysql_native_password --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
backend:
build: ./backend
container_name: dorm_billing_backend
restart: always
ports:
- "3000:3000"
environment:
DB_HOST: mysql
DB_PORT: 3306
DB_USERNAME: root
DB_PASSWORD: dorm_billing_2024
DB_DATABASE: dorm_billing
JWT_SECRET: dorm-billing-jwt-secret-key-2024
JWT_EXPIRES_IN: 24h
depends_on:
- mysql
frontend:
build: ./frontend
container_name: dorm_billing_frontend
restart: always
ports:
- "80:80"
depends_on:
- backend
volumes:
mysql_data:

24
frontend/.gitignore vendored Normal file
View 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
frontend/Dockerfile Normal file
View 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
frontend/README.md Normal file
View 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
frontend/eslint.config.js Normal file
View 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
frontend/index.html Normal file
View 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
frontend/nginx.conf Normal file
View 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
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

38
frontend/package.json Normal file
View 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"
}
}

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

24
frontend/public/icons.svg Normal file
View 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
frontend/src/App.css Normal file
View 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);
}
}

58
frontend/src/App.tsx Normal file
View File

@@ -0,0 +1,58 @@
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';
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={<DashboardPage />} />
<Route path="students" element={<StudentsPage />} />
<Route path="rooms" element={<RoomsPage />} />
<Route path="occupancies" element={<OccupanciesPage />} />
<Route path="expenses" element={<ExpensesPage />} />
<Route path="deposits" element={<DepositsPage />} />
<Route path="bills" element={<BillsPage />} />
<Route path="room-visual" element={<RoomVisualPage />} />
<Route path="operation-logs" element={<OperationLogsPage />} />
<Route path="users" element={<UsersPage />} />
<Route path="classrooms" element={<ClassroomsPage />} />
<Route path="tenants" element={<TenantsPage />} />
<Route path="classroom-rentals" element={<ClassroomRentalsPage />} />
<Route path="classroom-schedule" element={<ClassroomSchedulePage />} />
</Route>
</Routes>
</BrowserRouter>
</AntdApp>
</ConfigProvider>
);
};
export default App;

28
frontend/src/api/index.ts Normal file
View File

@@ -0,0 +1,28 @@
import axios from 'axios';
const api = axios.create({
baseURL: import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/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');
window.location.href = '/login';
}
return Promise.reject(err.response?.data || err);
},
);
export default api;

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View 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

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

Some files were not shown because too many files have changed in this diff Show More