chore: commit oxfmt formatting changes and verify artifacts

This commit is contained in:
2026-07-02 15:55:09 +08:00
parent 34726cc46d
commit 4f4cee157a
77 changed files with 5576 additions and 1400 deletions

View File

@@ -4,9 +4,21 @@ import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';
import {
Student, Room, Occupancy, RoomExpense, PersonalExpense,
Bill, BillItem, User, OperationLog, Deposit, Classroom,
Tenant, ClassroomRental, Permission, Role,
Student,
Room,
Occupancy,
RoomExpense,
PersonalExpense,
Bill,
BillItem,
User,
OperationLog,
Deposit,
Classroom,
Tenant,
ClassroomRental,
Permission,
Role,
} from './entities';
import { AuthModule } from './auth/auth.module';
import { RbacModule } from './rbac/rbac.module';
@@ -26,19 +38,33 @@ import { ClassroomRentalsModule } from './classroom-rentals/classroom-rentals.mo
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
ThrottlerModule.forRoot([{
ttl: 60000, // 60秒窗口
limit: 100, // 普通接口每分钟100次
}]),
ThrottlerModule.forRoot([
{
ttl: 60000, // 60秒窗口
limit: 100, // 普通接口每分钟100次
},
]),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService): any => {
const dbType = config.get('DB_TYPE', 'sqlite');
const allEntities = [
Student, Room, Occupancy, RoomExpense, PersonalExpense,
Bill, BillItem, User, OperationLog, Deposit, Classroom,
Tenant, ClassroomRental, Permission, Role,
Student,
Room,
Occupancy,
RoomExpense,
PersonalExpense,
Bill,
BillItem,
User,
OperationLog,
Deposit,
Classroom,
Tenant,
ClassroomRental,
Permission,
Role,
];
if (dbType === 'mysql') {
return {

View File

@@ -9,7 +9,10 @@ import { Public } from './decorators/public.decorator';
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService, private logService: OperationLogsService) {}
constructor(
private authService: AuthService,
private logService: OperationLogsService,
) {}
@Public()
@Post('login')
@@ -19,17 +22,24 @@ export class AuthController {
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',
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: '登录失败',
module: '认证',
action: '登录失败',
detail: e.message || '密码错误',
ipAddress, userAgent, status: 'fail',
ipAddress,
userAgent,
status: 'fail',
});
throw e;
}

View File

@@ -62,7 +62,7 @@ export class AuthService {
const payload = { sub: user.id, username: user.username, permissions };
// 获取角色名称列表
const roleNames = user.roles ? user.roles.filter(r => r.status === 1).map(r => r.name) : [];
const roleNames = user.roles ? user.roles.filter((r) => r.status === 1).map((r) => r.name) : [];
return {
access_token: this.jwtService.sign(payload),

View File

@@ -16,10 +16,10 @@ export class PermissionGuard implements CanActivate {
if (isPublic) return true;
// 2. 获取所需权限getAllAndMerge 合并 handler+class 层的所有 metadata
const requiredPermissions = this.reflector.getAllAndMerge<string[]>(
PERMISSION_KEY,
[context.getHandler(), context.getClass()],
);
const requiredPermissions = this.reflector.getAllAndMerge<string[]>(PERMISSION_KEY, [
context.getHandler(),
context.getClass(),
]);
// 无装饰器 = 默认拒绝
if (!requiredPermissions || requiredPermissions.length === 0) return false;
@@ -29,6 +29,6 @@ export class PermissionGuard implements CanActivate {
if (!user || !user.permissions || !Array.isArray(user.permissions)) return false;
// 4. OR 匹配:用户拥有 requiredPermissions 中任一权限即可通过
return requiredPermissions.some(p => user.permissions.includes(p));
return requiredPermissions.some((p) => user.permissions.includes(p));
}
}

View File

@@ -19,8 +19,12 @@ export class BillsExportService {
/**
* 导出账单列表为 Excel
*/
async exportExcel(query: { periodStart?: string; periodEnd?: string; studentId?: number; status?: string }, res: Response) {
const qb = this.billRepo.createQueryBuilder('b')
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');
@@ -34,7 +38,8 @@ export class BillsExportService {
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')
const deposits = await this.depositRepo
.createQueryBuilder('d')
.where('d.studentId IN (:...ids)', { ids: studentIds })
.andWhere('d.status = :status', { status: 'paid' })
.getMany();
@@ -65,7 +70,11 @@ export class BillsExportService {
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: '已结清' };
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));
@@ -116,7 +125,10 @@ export class BillsExportService {
}
}
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
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();
@@ -126,11 +138,18 @@ export class BillsExportService {
* 导出单个学生的 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 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')
const deposits = await this.depositRepo
.createQueryBuilder('d')
.where('d.studentId = :sid', { sid: bill.studentId })
.andWhere('d.status = :status', { status: 'paid' })
.getMany();
@@ -146,12 +165,12 @@ export class BillsExportService {
// 注册中文字体(优先使用系统字体,兼容 macOS 和 Linux
const fontPaths = [
'/System/Library/Fonts/PingFang.ttc', // macOS
'/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc', // Linux Noto
'/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/wqy-microhei/wqy-microhei.ttc', // Linux WenQuanYi
'/usr/share/fonts/truetype/wqy/wqy-microhei.ttc',
];
let fontRegistered = false;
@@ -171,12 +190,19 @@ export class BillsExportService {
doc.font('Helvetica');
}
const statusMap: Record<string, string> = { draft: '草稿', confirmed: '已确认', paid: '已结清' };
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
.fontSize(10)
.fillColor('#666')
.text(`生成时间: ${new Date().toLocaleString('zh-CN')}`, { align: 'center' });
doc.moveDown(1);
// 基本信息
@@ -192,12 +218,24 @@ export class BillsExportService {
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
.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
.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);
@@ -226,16 +264,23 @@ export class BillsExportService {
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(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
.fontSize(8)
.fillColor('#999')
.text('本账单由恭学教育基地管理系统自动生成', { align: 'center' });
doc.end();
}

View File

@@ -1,4 +1,17 @@
import { Controller, Get, Post, Put, Delete, Param, Body, Query, UseGuards, Request, Res, Req } from '@nestjs/common';
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';
@@ -11,14 +24,26 @@ import type { Response } from 'express';
@UseGuards(JwtAuthGuard)
@Controller('bills')
export class BillsController {
constructor(private service: BillsService, private exportService: BillsExportService, private logService: OperationLogsService) {}
constructor(
private service: BillsService,
private exportService: BillsExportService,
private logService: OperationLogsService,
) {}
@Post('generate')
@RequirePermission('bill:generate')
async generateBills(@Body() dto: GenerateBillsDto, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.generateBills(dto);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '账单', action: '生成账单', detail: `周期 ${dto.periodStart}~${dto.periodEnd}, 生成 ${result.count}`, ipAddress, userAgent });
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;
}
@@ -31,7 +56,8 @@ export class BillsController {
@Query('status') status?: string,
) {
return this.service.findAll({
periodStart, periodEnd,
periodStart,
periodEnd,
studentId: studentId ? +studentId : undefined,
status,
});
@@ -45,10 +71,23 @@ export class BillsController {
@Put(':id/status')
@RequirePermission('bill:confirm')
async updateStatus(@Param('id') id: string, @Body() dto: UpdateBillStatusDto, @Request() req: any) {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '账单',
action: `状态变更为${dto.status}`,
targetId: +id,
targetType: 'bill',
ipAddress,
userAgent,
});
return result;
}
@@ -57,7 +96,15 @@ export class BillsController {
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 });
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;
}
@@ -66,7 +113,16 @@ export class BillsController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '账单',
action: '删除账单',
targetId: +id,
targetType: 'bill',
ipAddress,
userAgent,
});
return result;
}
@@ -75,7 +131,15 @@ export class BillsController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '账单',
action: '批量删除账单',
detail: `IDs: ${body.ids.join(',')}`,
ipAddress,
userAgent,
});
return result;
}
@@ -90,19 +154,40 @@ export class BillsController {
@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!);
await this.logService.log({
userId: req?.user?.id,
username: req?.user?.username,
module: '账单',
action: '导出Excel',
detail: `筛选: 周期${periodStart || '全部'}~${periodEnd || '全部'}, 状态${status || '全部'}`,
ipAddress,
userAgent,
});
return this.exportService.exportExcel(
{
periodStart,
periodEnd,
studentId: studentId ? +studentId : undefined,
status,
},
res!,
);
}
@Get('export/pdf/:id')
@RequirePermission('bill:export-pdf')
async exportPdf(@Param('id') id: string, @Res() res: Response, @Req() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
await this.logService.log({ userId: req?.user?.id, username: req?.user?.username, module: '账单', action: '导出PDF', targetId: +id, targetType: 'bill', ipAddress, userAgent });
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

@@ -12,7 +12,17 @@ import { BillsExportService } from './bills-export.service';
import { BillsController } from './bills.controller';
@Module({
imports: [TypeOrmModule.forFeature([Bill, BillItem, RoomExpense, PersonalExpense, Occupancy, Room, Deposit])],
imports: [
TypeOrmModule.forFeature([
Bill,
BillItem,
RoomExpense,
PersonalExpense,
Occupancy,
Room,
Deposit,
]),
],
controllers: [BillsController],
providers: [BillsService, BillsExportService],
exports: [BillsService],

View File

@@ -37,13 +37,25 @@ export class BillsService {
});
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();
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 })
const roomExpenses = await this.roomExpRepo
.createQueryBuilder('e')
.where('e.periodStart = :periodStart AND e.periodEnd = :periodEnd', {
periodStart,
periodEnd,
})
.getMany();
// 按宿舍分组费用
@@ -58,7 +70,8 @@ export class BillsService {
for (const [roomId, expenses] of roomExpMap) {
// 获取该宿舍在此周期内的所有入住记录
const occupancies = await this.occRepo.createQueryBuilder('o')
const occupancies = await this.occRepo
.createQueryBuilder('o')
.leftJoinAndSelect('o.student', 'student')
.where('o.roomId = :roomId', { roomId })
.andWhere('o.billingStartDate <= :periodEnd', { periodEnd })
@@ -72,11 +85,16 @@ export class BillsService {
let totalDays = 0;
for (const occ of occupancies) {
const start = new Date(Math.max(new Date(occ.billingStartDate).getTime(), pStart.getTime()));
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);
const days = Math.max(
0,
Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)) + 1,
);
studentDays.push({ studentId: occ.studentId, days });
totalDays += days;
}
@@ -107,8 +125,12 @@ export class BillsService {
}
// 获取个人附加费
const personalExps = await this.personalExpRepo.createQueryBuilder('pe')
.where('pe.expenseDate >= :periodStart AND pe.expenseDate <= :periodEnd', { periodStart, periodEnd })
const personalExps = await this.personalExpRepo
.createQueryBuilder('pe')
.where('pe.expenseDate >= :periodStart AND pe.expenseDate <= :periodEnd', {
periodStart,
periodEnd,
})
.getMany();
const personalMap = new Map<number, number>();
@@ -162,8 +184,14 @@ export class BillsService {
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')
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 });
@@ -191,7 +219,8 @@ export class BillsService {
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')
const deposits = await this.depositRepo
.createQueryBuilder('d')
.where('d.studentId IN (:...ids)', { ids: studentIds })
.andWhere('d.status = :status', { status: 'paid' })
.getMany();
@@ -220,7 +249,12 @@ export class BillsService {
}
async batchUpdateStatus(ids: number[], status: string) {
await this.billRepo.createQueryBuilder().update().set({ status }).where('id IN (:...ids)', { ids }).execute();
await this.billRepo
.createQueryBuilder()
.update()
.set({ status })
.where('id IN (:...ids)', { ids })
.execute();
return { message: `成功更新 ${ids.length} 条账单状态` };
}
@@ -233,7 +267,11 @@ export class BillsService {
}
async batchRemove(ids: number[]) {
await this.itemRepo.createQueryBuilder().delete().where('billId IN (:...ids)', { ids }).execute();
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

@@ -1,4 +1,19 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards, Request, Res, UseInterceptors, UploadedFile, BadRequestException } from '@nestjs/common';
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';
@@ -12,7 +27,10 @@ import { RequirePermission } from '../auth/decorators/permission.decorator';
@UseGuards(JwtAuthGuard)
@Controller('classroom-rentals')
export class ClassroomRentalsController {
constructor(private service: ClassroomRentalsService, private logService: OperationLogsService) {}
constructor(
private service: ClassroomRentalsService,
private logService: OperationLogsService,
) {}
@Get()
@RequirePermission('rental:view')
@@ -52,10 +70,15 @@ export class ClassroomRentalsController {
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',
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,
ipAddress,
userAgent,
});
return result;
}
@@ -66,9 +89,15 @@ export class ClassroomRentalsController {
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,
userId: req.user?.id,
username: req.user?.username,
module: '教室租赁',
action: '编辑租赁',
targetId: +id,
targetType: 'classroom-rental',
detail: JSON.stringify(dto),
ipAddress,
userAgent,
});
return result;
}
@@ -79,9 +108,14 @@ export class ClassroomRentalsController {
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,
userId: req.user?.id,
username: req.user?.username,
module: '教室租赁',
action: '删除租赁',
targetId: +id,
targetType: 'classroom-rental',
ipAddress,
userAgent,
});
return result;
}
@@ -89,23 +123,35 @@ export class ClassroomRentalsController {
// 合同上传multer 限制 10MB + 仅 PDF
@Post(':id/contract')
@RequirePermission('rental:edit')
@UseInterceptors(FileInterceptor('file', {
limits: { fileSize: 10 * 1024 * 1024 },
fileFilter: (_req, file, cb) => {
if (file.mimetype !== 'application/pdf') {
return cb(new BadRequestException('仅支持 PDF 文件'), false);
}
cb(null, true);
},
}))
async uploadContract(@Param('id') id: string, @UploadedFile() file: Express.Multer.File, @Request() req: any) {
@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,
userId: req.user?.id,
username: req.user?.username,
module: '教室租赁',
action: '上传合同',
targetId: +id,
targetType: 'classroom-rental',
detail: file.originalname,
ipAddress,
userAgent,
});
return result;
}
@@ -115,7 +161,10 @@ export class ClassroomRentalsController {
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)}"`);
res.setHeader(
'Content-Disposition',
`attachment; filename="${encodeURIComponent(originalName)}"`,
);
const stream = fs.createReadStream(fullPath);
stream.pipe(res);
}
@@ -126,9 +175,14 @@ export class ClassroomRentalsController {
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,
userId: req.user?.id,
username: req.user?.username,
module: '教室租赁',
action: '删除合同',
targetId: +id,
targetType: 'classroom-rental',
ipAddress,
userAgent,
});
return result;
}

View File

@@ -1,4 +1,9 @@
import { Injectable, NotFoundException, BadRequestException, ConflictException } from '@nestjs/common';
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';
@@ -10,8 +15,16 @@ import * as fs from 'fs';
// 预设色板(与 tenants.service 保持一致,作为颜色兜底)
const COLOR_PALETTE = [
'#ff7875', '#ffa940', '#ffc53d', '#73d13d', '#36cfc9',
'#40a9ff', '#597ef7', '#9254de', '#f759ab', '#8c8c8c',
'#ff7875',
'#ffa940',
'#ffc53d',
'#73d13d',
'#36cfc9',
'#40a9ff',
'#597ef7',
'#9254de',
'#f759ab',
'#8c8c8c',
];
@Injectable()
@@ -33,8 +46,14 @@ export class ClassroomRentalsService {
}
}
async findAll(query?: { classroomId?: number; tenantId?: number; month?: string; includeEnded?: boolean }) {
const qb = this.repo.createQueryBuilder('r')
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');
@@ -63,7 +82,8 @@ export class ClassroomRentalsService {
* 重叠判定start1 <= end2 AND start2 <= end1
*/
async findConflicts(classroomId: number, startDate: string, endDate: string, excludeId?: number) {
const qb = this.repo.createQueryBuilder('r')
const qb = this.repo
.createQueryBuilder('r')
.leftJoinAndSelect('r.tenant', 'tenant')
.where('r.classroomId = :cid', { cid: classroomId })
.andWhere('r.status != :cancelled', { cancelled: 'cancelled' })
@@ -84,7 +104,12 @@ export class ClassroomRentalsService {
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 })),
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' }));
@@ -102,7 +127,12 @@ export class ClassroomRentalsService {
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 })),
conflicts: conflicts.map((c) => ({
id: c.id,
startDate: c.startDate,
endDate: c.endDate,
tenantName: c.tenant?.name,
})),
});
}
}
@@ -116,7 +146,11 @@ export class ClassroomRentalsService {
if (rental.contractPath) {
const full = path.join(this.uploadDir, rental.contractPath);
if (fs.existsSync(full)) {
try { fs.unlinkSync(full); } catch { /* ignore */ }
try {
fs.unlinkSync(full);
} catch {
/* ignore */
}
}
}
await this.repo.delete(id);
@@ -133,7 +167,9 @@ export class ClassroomRentalsService {
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 uuid =
(globalThis as any).crypto?.randomUUID?.() ||
require('crypto').randomBytes(16).toString('hex');
const filename = `${uuid}.pdf`;
const fullPath = path.join(this.uploadDir, filename);
// 路径遍历防护
@@ -142,7 +178,11 @@ export class ClassroomRentalsService {
if (rental.contractPath) {
const oldPath = path.join(this.uploadDir, rental.contractPath);
if (fs.existsSync(oldPath)) {
try { fs.unlinkSync(oldPath); } catch { /* ignore */ }
try {
fs.unlinkSync(oldPath);
} catch {
/* ignore */
}
}
}
fs.writeFileSync(fullPath, file.buffer);
@@ -158,7 +198,11 @@ export class ClassroomRentalsService {
if (!rental.contractPath) throw new BadRequestException('该租赁未上传合同');
const fullPath = path.join(this.uploadDir, rental.contractPath);
if (fs.existsSync(fullPath)) {
try { fs.unlinkSync(fullPath); } catch { /* ignore */ }
try {
fs.unlinkSync(fullPath);
} catch {
/* ignore */
}
}
await this.repo.update(id, { contractPath: null as any, contractOriginalName: null as any });
return { message: '合同已删除' };
@@ -188,7 +232,8 @@ export class ClassroomRentalsService {
where: { status: Not('archived') },
order: { building: 'ASC', name: 'ASC' },
});
const rentals = await this.repo.createQueryBuilder('r')
const rentals = await this.repo
.createQueryBuilder('r')
.leftJoinAndSelect('r.tenant', 'tenant')
.leftJoinAndSelect('r.classroom', 'classroom')
.where('r.status != :cancelled', { cancelled: 'cancelled' })
@@ -197,7 +242,10 @@ export class ClassroomRentalsService {
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 }> = {};
const summary: Record<
number,
{ totalDays: number; rentedDays: number; idleDays: number; occupancyRate: number }
> = {};
for (const cls of classrooms) {
matrix[cls.id] = {};
@@ -225,7 +273,8 @@ export class ClassroomRentalsService {
rentalId: rental.id,
tenantId: rental.tenantId,
tenantName: rental.tenant?.name || '未知',
color: rental.tenant?.color || COLOR_PALETTE[(rental.tenantId || 0) % COLOR_PALETTE.length],
color:
rental.tenant?.color || COLOR_PALETTE[(rental.tenantId || 0) % COLOR_PALETTE.length],
hasContract: !!rental.contractPath,
};
}
@@ -243,7 +292,15 @@ export class ClassroomRentalsService {
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 })),
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

@@ -1,4 +1,12 @@
import { IsOptional, IsString, IsNotEmpty, IsInt, IsNumber, IsEnum, IsDateString } from 'class-validator';
import {
IsOptional,
IsString,
IsNotEmpty,
IsInt,
IsNumber,
IsEnum,
IsDateString,
} from 'class-validator';
export class CreateRentalDto {
@IsInt()

View File

@@ -1,4 +1,18 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards, Request, Res, UseInterceptors, UploadedFile } from '@nestjs/common';
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';
@@ -12,11 +26,18 @@ import * as ExcelJS from 'exceljs';
@UseGuards(JwtAuthGuard)
@Controller('classrooms')
export class ClassroomsController {
constructor(private service: ClassroomsService, private logService: OperationLogsService) {}
constructor(
private service: ClassroomsService,
private logService: OperationLogsService,
) {}
@Get()
@RequirePermission('classroom:view')
findAll(@Query('building') building?: string, @Query('roomType') roomType?: string, @Query('includeArchived') includeArchived?: string) {
findAll(
@Query('building') building?: string,
@Query('roomType') roomType?: string,
@Query('includeArchived') includeArchived?: string,
) {
return this.service.findAll({
building,
roomType,
@@ -40,9 +61,33 @@ export class ClassroomsController {
];
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: '' });
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('使用说明');
@@ -56,7 +101,10 @@ export class ClassroomsController {
'5. 负责人为班主任/对接人',
].forEach((note) => ws2.addRow({ note }));
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
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();
@@ -73,7 +121,17 @@ export class ClassroomsController {
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 });
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;
}
@@ -82,7 +140,17 @@ export class ClassroomsController {
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 });
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;
}
@@ -91,7 +159,16 @@ export class ClassroomsController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '教室',
action: '归档教室',
targetId: +id,
targetType: 'classroom',
ipAddress,
userAgent,
});
return result;
}
@@ -100,7 +177,16 @@ export class ClassroomsController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '教室',
action: '恢复教室',
targetId: +id,
targetType: 'classroom',
ipAddress,
userAgent,
});
return result;
}
@@ -126,7 +212,15 @@ export class ClassroomsController {
});
});
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '教室',
action: '批量导入',
detail: result.message,
ipAddress,
userAgent,
});
return result;
}
}

View File

@@ -54,25 +54,47 @@ export class ClassroomsService {
return { message: '已恢复' };
}
async batchImport(rows: { name: string; building?: string; floor?: number; capacity?: number; roomType?: string; courseType?: string; supervisor?: string }[]) {
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; }
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,
}));
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 };
return {
message: `成功导入 ${imported} 间教室,跳过 ${skipped} 条(重复或空行)`,
imported,
skipped,
};
}
}

View File

@@ -2,7 +2,11 @@
* 从请求对象中提取客户端 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 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

@@ -21,26 +21,36 @@ export class DashboardService {
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')
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')
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 };
return {
totalRooms,
totalStudents,
occupiedBeds,
totalCapacity: cap,
occupancyRate,
billStats,
};
}
// 甘特图数据:每个宿舍的入住时间线
async getGanttData(query?: { periodStart?: string; periodEnd?: string; building?: string }) {
const qb = this.occRepo.createQueryBuilder('o')
const qb = this.occRepo
.createQueryBuilder('o')
.leftJoinAndSelect('o.student', 'student')
.leftJoinAndSelect('o.room', 'room')
.where('room.status != :archived', { archived: 'archived' })
@@ -82,7 +92,8 @@ export class DashboardService {
// 费用统计
async getExpenseStats(periodStart?: string, periodEnd?: string) {
const qb = this.expRepo.createQueryBuilder('e')
const qb = this.expRepo
.createQueryBuilder('e')
.select('e.expenseType', 'type')
.addSelect('SUM(e.amount)', 'total')
.groupBy('e.expenseType');
@@ -93,7 +104,8 @@ export class DashboardService {
// 各宿舍费用排行
async getRoomExpenseRanking(periodStart?: string, periodEnd?: string) {
const qb = this.expRepo.createQueryBuilder('e')
const qb = this.expRepo
.createQueryBuilder('e')
.leftJoin('e.room', 'room')
.select('room.roomNumber', 'roomNumber')
.addSelect('SUM(e.amount)', 'total')

View File

@@ -1,4 +1,15 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards, Request } from '@nestjs/common';
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';
@@ -9,7 +20,10 @@ import { RequirePermission } from '../auth/decorators/permission.decorator';
@UseGuards(JwtAuthGuard)
@Controller('deposits')
export class DepositsController {
constructor(private service: DepositsService, private logService: OperationLogsService) {}
constructor(
private service: DepositsService,
private logService: OperationLogsService,
) {}
@Get()
@RequirePermission('deposit:view')
@@ -31,7 +45,17 @@ export class DepositsController {
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 });
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;
}
@@ -40,7 +64,17 @@ export class DepositsController {
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 });
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;
}
@@ -49,7 +83,16 @@ export class DepositsController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '押金',
action: '删除押金记录',
targetId: +id,
targetType: 'deposit',
ipAddress,
userAgent,
});
return result;
}
}

View File

@@ -9,7 +9,8 @@ export class DepositsService {
constructor(@InjectRepository(Deposit) private repo: Repository<Deposit>) {}
async findAll(query?: { studentId?: number; status?: string }) {
const qb = this.repo.createQueryBuilder('d')
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 });
@@ -18,14 +19,16 @@ export class DepositsService {
}
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,
}));
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) {
@@ -41,7 +44,8 @@ export class DepositsService {
deposit.deductionAmount = deduction;
deposit.deductionReason = dto.deductionReason || '';
deposit.refundAmount = refundAmount;
deposit.status = deduction > 0 ? (refundAmount > 0 ? 'partial_refund' : 'deducted') : 'refunded';
deposit.status =
deduction > 0 ? (refundAmount > 0 ? 'partial_refund' : 'deducted') : 'refunded';
if (dto.notes) deposit.notes = dto.notes;
return this.repo.save(deposit);
@@ -55,7 +59,8 @@ export class DepositsService {
}
async getStats() {
const result = await this.repo.createQueryBuilder('d')
const result = await this.repo
.createQueryBuilder('d')
.select('d.status', 'status')
.addSelect('COUNT(*)', 'count')
.addSelect('SUM(d.amount)', 'totalAmount')

View File

@@ -1,4 +1,12 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn, OneToMany } from 'typeorm';
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
ManyToOne,
JoinColumn,
OneToMany,
} from 'typeorm';
import { Student } from './student.entity';
import { BillItem } from './bill-item.entity';

View File

@@ -1,4 +1,13 @@
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn, CreateDateColumn, UpdateDateColumn, Index } from 'typeorm';
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
JoinColumn,
CreateDateColumn,
UpdateDateColumn,
Index,
} from 'typeorm';
import { Classroom } from './classroom.entity';
import { Tenant } from './tenant.entity';

View File

@@ -1,4 +1,11 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn } from 'typeorm';
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
ManyToOne,
JoinColumn,
} from 'typeorm';
import { Student } from './student.entity';
@Entity('deposits')

View File

@@ -1,4 +1,11 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn } from 'typeorm';
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
ManyToOne,
JoinColumn,
} from 'typeorm';
import { Student } from './student.entity';
import { Room } from './room.entity';

View File

@@ -1,4 +1,11 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn } from 'typeorm';
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
ManyToOne,
JoinColumn,
} from 'typeorm';
import { Student } from './student.entity';
@Entity('personal_expenses')

View File

@@ -1,4 +1,12 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, ManyToMany, JoinTable } from 'typeorm';
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToMany,
JoinTable,
} from 'typeorm';
import { Permission } from './permission.entity';
import { User } from './user.entity';

View File

@@ -1,4 +1,11 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn } from 'typeorm';
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
ManyToOne,
JoinColumn,
} from 'typeorm';
import { Room } from './room.entity';
@Entity('room_expenses')

View File

@@ -1,4 +1,11 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, OneToMany } from 'typeorm';
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';

View File

@@ -1,4 +1,10 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
} from 'typeorm';
@Entity('tenants')
export class Tenant {

View File

@@ -1,4 +1,12 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, ManyToMany, JoinTable } from 'typeorm';
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToMany,
JoinTable,
} from 'typeorm';
import { Role } from './role.entity';
@Entity('users')

View File

@@ -1,8 +1,26 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards, Request, Res, UseInterceptors, UploadedFile } from '@nestjs/common';
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 {
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';
@@ -15,13 +33,13 @@ function readCell(cell: ExcelJS.Cell): any {
if (v == null) return '';
if (typeof v === 'object') {
// 公式单元格:{ formula, result }
if ('result' in v) v = (v as any).result;
if ('result' in v) v = v.result;
// 富文本:{ richText: [...] }
else if ('richText' in v && Array.isArray((v as any).richText)) {
return (v as any).richText.map((r: any) => r.text || '').join('');
else if ('richText' in v && Array.isArray(v.richText)) {
return v.richText.map((r: any) => r.text || '').join('');
}
// 超链接:{ text, hyperlink }
else if ('text' in v) v = (v as any).text;
else if ('text' in v) v = v.text;
// 错误值:{ error: '#DIV/0!' }
else if ('error' in v) return '';
}
@@ -49,14 +67,27 @@ function readCellStr(cell: ExcelJS.Cell): string {
@UseGuards(JwtAuthGuard)
@Controller('expenses')
export class ExpensesController {
constructor(private service: ExpensesService, private logService: OperationLogsService) {}
constructor(
private service: ExpensesService,
private logService: OperationLogsService,
) {}
@Post('room')
@RequirePermission('expense:create')
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 });
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;
}
@@ -65,7 +96,15 @@ export class ExpensesController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '费用',
action: '批量录入费用',
detail: JSON.stringify(dto),
ipAddress,
userAgent,
});
return result;
}
@@ -78,7 +117,8 @@ export class ExpensesController {
) {
return this.service.findRoomExpenses({
roomId: roomId ? +roomId : undefined,
periodStart, periodEnd,
periodStart,
periodEnd,
});
}
@@ -87,7 +127,16 @@ export class ExpensesController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '费用',
action: '删除宿舍费用',
targetId: +id,
targetType: 'room_expense',
ipAddress,
userAgent,
});
return result;
}
@@ -96,16 +145,38 @@ export class ExpensesController {
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 });
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')
@RequirePermission('expense:edit')
async updateRoomExpense(@Param('id') id: string, @Body() dto: CreateRoomExpenseDto, @Request() req: any) {
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 });
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;
}
@@ -114,7 +185,15 @@ export class ExpensesController {
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 });
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;
}
@@ -129,7 +208,15 @@ export class ExpensesController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '费用',
action: '删除个人费用',
targetId: +id,
ipAddress,
userAgent,
});
return result;
}
@@ -138,16 +225,37 @@ export class ExpensesController {
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 });
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')
@RequirePermission('expense:edit')
async updatePersonalExpense(@Param('id') id: string, @Body() dto: CreatePersonalExpenseDto, @Request() req: any) {
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 });
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;
}
@@ -168,8 +276,20 @@ export class ExpensesController {
];
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');
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();
@@ -199,7 +319,15 @@ export class ExpensesController {
});
});
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '费用',
action: '导入水电费',
detail: result.message,
ipAddress,
userAgent,
});
return result;
}
@@ -217,12 +345,23 @@ export class ExpensesController {
];
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: '丢失宿舍钥匙' });
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');
['物品损坏', '保洁费', '罚款', '钥匙费', '空调遥控器', '押金扣除', '其他'].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();
@@ -250,7 +389,15 @@ export class ExpensesController {
});
});
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '费用',
action: '导入个人附加费',
detail: result.message,
ipAddress,
userAgent,
});
return result;
}
@@ -258,7 +405,15 @@ export class ExpensesController {
@RequirePermission('expense:view')
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 typeMap: Record<string, string> = {
damage: '物品损坏',
cleaning: '保洁费',
penalty: '罚款',
key: '钥匙费',
remote: '空调遥控器',
deposit_deduction: '押金扣除',
other: '其他',
};
const workbook = new ExcelJS.Workbook();
const ws = workbook.addWorksheet('个人附加费');
ws.columns = [
@@ -278,7 +433,10 @@ export class ExpensesController {
description: d.description || '',
});
});
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
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

@@ -9,7 +9,10 @@ import { ExpensesController } from './expenses.controller';
import { OperationLogsModule } from '../operation-logs/operation-logs.module';
@Module({
imports: [TypeOrmModule.forFeature([RoomExpense, PersonalExpense, Room, Student]), OperationLogsModule],
imports: [
TypeOrmModule.forFeature([RoomExpense, PersonalExpense, Room, Student]),
OperationLogsModule,
],
controllers: [ExpensesController],
providers: [ExpensesService],
exports: [ExpensesService],

View File

@@ -5,7 +5,11 @@ 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 {
CreateRoomExpenseDto,
CreatePersonalExpenseDto,
BatchRoomExpenseDto,
} from './dto/expense.dto';
import { RoomsService } from '../rooms/rooms.service';
@Injectable()
@@ -38,7 +42,8 @@ export class ExpensesService {
}
async findRoomExpenses(query?: { roomId?: number; periodStart?: string; periodEnd?: string }) {
const qb = this.roomExpRepo.createQueryBuilder('e')
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 });
@@ -56,7 +61,8 @@ export class ExpensesService {
async batchDeleteRoomExpenses(ids: number[]) {
if (!ids || ids.length === 0) throw new BadRequestException('请选择要删除的记录');
const result = await this.roomExpRepo.createQueryBuilder()
const result = await this.roomExpRepo
.createQueryBuilder()
.delete()
.where('id IN (:...ids)', { ids })
.execute();
@@ -78,7 +84,11 @@ export class ExpensesService {
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' } });
return this.personalExpRepo.find({
where,
relations: ['student'],
order: { createdAt: 'DESC' },
});
}
async deletePersonalExpense(id: number) {
@@ -90,7 +100,8 @@ export class ExpensesService {
async batchDeletePersonalExpenses(ids: number[]) {
if (!ids || ids.length === 0) throw new BadRequestException('请选择要删除的记录');
const result = await this.personalExpRepo.createQueryBuilder()
const result = await this.personalExpRepo
.createQueryBuilder()
.delete()
.where('id IN (:...ids)', { ids })
.execute();
@@ -109,15 +120,18 @@ export class ExpensesService {
* 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) {
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[] = [];
@@ -126,20 +140,25 @@ export class ExpensesService {
const row = rows[i];
const rowNum = i + 2;
if (!row.roomNumber?.trim()) { skipped++; continue; }
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,
}));
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"
@@ -169,13 +188,16 @@ export class ExpensesService {
// 关键校验:电费 + 水费 都为 0 时,多半是 Excel 公式未正确计算或字段缺失,
// 必须给出明确错误,避免出现"提示成功但无数据"的迷之现象。
if ((row.electricityFee || 0) <= 0 && (row.waterFee || 0) <= 0) {
errors.push(`${rowNum}行: ${row.roomNumber} 电费和水费均为 0可能 Excel 中是未生效的公式(请打开文件让公式重算后再保存导入),已跳过`);
errors.push(
`${rowNum}行: ${row.roomNumber} 电费和水费均为 0可能 Excel 中是未生效的公式(请打开文件让公式重算后再保存导入),已跳过`,
);
skipped++;
continue;
}
// 幂等:先删除该房间在同一周期已有的水/电费用记录,避免重复导入产生脏数据
await this.roomExpRepo.createQueryBuilder()
await this.roomExpRepo
.createQueryBuilder()
.delete()
.where('roomId = :roomId', { roomId: room.id })
.andWhere('periodStart = :ps AND periodEnd = :pe', { ps: periodStart, pe: periodEnd })
@@ -185,34 +207,41 @@ export class ExpensesService {
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,
}));
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,
}));
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} 无有效金额`); }
else {
skipped++;
errors.push(`${rowNum}行: ${row.roomNumber} 无有效金额`);
}
} catch (e: any) {
errors.push(`${rowNum}行: ${row.roomNumber} 导入失败 - ${e.message}`);
skipped++;
@@ -220,9 +249,10 @@ export class ExpensesService {
}
return {
message: imported > 0
? `成功导入 ${imported} 间宿舍水电费${skipped > 0 ? `,跳过 ${skipped}` : ''}`
: `未导入任何记录${skipped > 0 ? ` ${skipped}被跳过` : ''}`,
message:
imported > 0
? `成功导入 ${imported} 间宿舍水电费${skipped > 0 ? `跳过 ${skipped}` : ''}`
: `未导入任何记录${skipped > 0 ? `,共 ${skipped} 条被跳过` : ''}`,
imported,
skipped,
errors: errors.length > 0 ? errors : undefined,
@@ -242,32 +272,42 @@ export class ExpensesService {
* 个人附加费Excel批量导入
* Excel格式: 学生姓名|费用类型|金额|费用日期|说明
*/
async batchImportPersonalExpenses(rows: {
studentName: string;
expenseType: string;
amount: number;
expenseDate: string;
description?: string;
}[], userId?: number) {
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',
: '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; }
if (!row.studentName?.trim()) {
skipped++;
continue;
}
try {
// 查找学生
@@ -283,7 +323,15 @@ export class ExpensesService {
if (typeMap[expenseType]) {
expenseType = typeMap[expenseType];
}
const validTypes = ['damage', 'cleaning', 'penalty', 'key', 'remote', 'deposit_deduction', 'other'];
const validTypes = [
'damage',
'cleaning',
'penalty',
'key',
'remote',
'deposit_deduction',
'other',
];
if (!validTypes.includes(expenseType)) {
errors.push(`${rowNum}行: 费用类型"${row.expenseType}"无效`);
skipped++;
@@ -304,14 +352,16 @@ export class ExpensesService {
}
}
await this.personalExpRepo.save(this.personalExpRepo.create({
studentId: student.id,
expenseType,
amount: row.amount,
expenseDate,
description: row.description || undefined,
recordedBy: userId,
}));
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) {

View File

@@ -1,4 +1,18 @@
import { Controller, Get, Post, Put, Delete, Param, Body, Query, UseGuards, Request, Res, UseInterceptors, UploadedFile } from '@nestjs/common';
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';
@@ -12,7 +26,10 @@ import * as ExcelJS from 'exceljs';
@UseGuards(JwtAuthGuard)
@Controller('occupancies')
export class OccupanciesController {
constructor(private service: OccupanciesService, private logService: OperationLogsService) {}
constructor(
private service: OccupanciesService,
private logService: OperationLogsService,
) {}
@Get()
@RequirePermission('occupancy:view')
@@ -33,7 +50,15 @@ export class OccupanciesController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '入住',
action: '批量退宿',
detail: `退宿 ${dto.ids.length} 人,日期 ${dto.checkOutDate}`,
ipAddress,
userAgent,
});
return result;
}
@@ -42,7 +67,17 @@ export class OccupanciesController {
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 });
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;
}
@@ -51,7 +86,16 @@ export class OccupanciesController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '入住',
action: '退宿',
targetId: +id,
targetType: 'occupancy',
ipAddress,
userAgent,
});
return result;
}
@@ -60,7 +104,17 @@ export class OccupanciesController {
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 });
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;
}
@@ -69,7 +123,16 @@ export class OccupanciesController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '入住',
action: '删除入住记录',
targetId: +id,
targetType: 'occupancy',
ipAddress,
userAgent,
});
return result;
}
@@ -78,7 +141,15 @@ export class OccupanciesController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '入住',
action: '批量删除入住记录',
detail: `IDs: ${(body.ids || []).join(',')}`,
ipAddress,
userAgent,
});
return result;
}
@@ -122,7 +193,10 @@ export class OccupanciesController {
checkOutReason: r.checkOutReason || '',
});
}
res!.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
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();
@@ -151,8 +225,36 @@ export class OccupanciesController {
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: '王老师' });
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;
@@ -166,7 +268,10 @@ export class OccupanciesController {
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-Type',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
);
res.setHeader('Content-Disposition', 'attachment; filename=checkin_template.xlsx');
await workbook.xlsx.write(res);
res.end();
@@ -175,7 +280,12 @@ export class OccupanciesController {
@Post('import')
@RequirePermission('occupancy:checkin')
@UseInterceptors(FileInterceptor('file'))
async importCheckIn(@UploadedFile() file: Express.Multer.File, @Request() req: any, @Query('autoDeposit') autoDeposit?: string, @Query('depositAmount') depositAmount?: string) {
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);
@@ -225,7 +335,15 @@ export class OccupanciesController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '入住',
action: '批量导入入住',
detail: result.message,
ipAddress,
userAgent,
});
return result;
}
}

View File

@@ -1,6 +1,14 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource, IsNull, Between, LessThanOrEqual, MoreThanOrEqual, In } from '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';
@@ -19,7 +27,8 @@ export class OccupanciesService {
) {}
async findAll(query?: { roomId?: number; studentId?: number; active?: boolean }) {
const qb = this.repo.createQueryBuilder('o')
const qb = this.repo
.createQueryBuilder('o')
.leftJoinAndSelect('o.student', 'student')
.leftJoinAndSelect('o.room', 'room')
.orderBy('o.checkInDate', 'DESC');
@@ -31,7 +40,9 @@ export class OccupanciesService {
async checkIn(dto: CheckInDto) {
// 检查学生是否已有活跃入住
const existing = await this.repo.findOne({ where: { studentId: dto.studentId, checkOutDate: IsNull() } });
const existing = await this.repo.findOne({
where: { studentId: dto.studentId, checkOutDate: IsNull() },
});
if (existing) throw new BadRequestException('该学生已有在住记录,请先办理退宿');
// 检查宿舍容量
@@ -44,7 +55,9 @@ export class OccupanciesService {
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}生无法入住`);
throw new BadRequestException(
`该宿舍当前为${room.gender}生寝室,${student.gender}生无法入住`,
);
}
const occ = this.repo.create({
@@ -82,7 +95,9 @@ export class OccupanciesService {
await this.roomRepo.update(occ.roomId, { status: 'available' });
// 如果房间已无在住人员,重置房间性别
const remaining = await this.repo.count({ where: { roomId: occ.roomId, checkOutDate: IsNull() } });
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 });
}
@@ -106,7 +121,9 @@ export class OccupanciesService {
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() } });
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 });
}
@@ -114,7 +131,9 @@ export class OccupanciesService {
// 检查新房容量
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() } });
const count = await runner.manager.count(Occupancy, {
where: { roomId: dto.newRoomId, checkOutDate: IsNull() },
});
if (count >= newRoom.capacity) throw new BadRequestException('目标宿舍已满');
// 换房性别约束检查
@@ -160,7 +179,8 @@ export class OccupanciesService {
// 获取某宿舍在指定时间段内的入住记录(用于计费)
async getRoomOccupanciesInPeriod(roomId: number, periodStart: string, periodEnd: string) {
return this.repo.createQueryBuilder('o')
return this.repo
.createQueryBuilder('o')
.leftJoinAndSelect('o.student', 'student')
.where('o.roomId = :roomId', { roomId })
.andWhere('o.billingStartDate <= :periodEnd', { periodEnd })
@@ -190,19 +210,26 @@ export class OccupanciesService {
}
let deleted = 0;
if (deletableIds.length > 0) {
const result = await this.repo.createQueryBuilder()
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}`;
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 }) {
async batchCheckOut(dto: {
ids: number[];
checkOutDate: string;
billingEndDate?: string;
checkOutReason?: string;
}) {
if (!dto.ids || dto.ids.length === 0) {
throw new BadRequestException('请选择要退宿的记录');
}
@@ -213,9 +240,18 @@ export class OccupanciesService {
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; }
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 || '';
@@ -223,7 +259,9 @@ export class OccupanciesService {
// 更新房间状态
await runner.manager.update(Room, occ.roomId, { status: 'available' });
// 如果房间已无在住人员,重置性别
const remaining = await runner.manager.count(Occupancy, { where: { roomId: occ.roomId, checkOutDate: IsNull() } });
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 });
}
@@ -236,7 +274,12 @@ export class OccupanciesService {
} finally {
await runner.release();
}
return { success, failed: errors.length, message: `已成功退宿 ${success}${errors.length > 0 ? `${errors.length} 条失败` : ''}`, errors: errors.length > 0 ? errors : undefined };
return {
success,
failed: errors.length,
message: `已成功退宿 ${success}${errors.length > 0 ? `${errors.length} 条失败` : ''}`,
errors: errors.length > 0 ? errors : undefined,
};
}
/**
@@ -244,13 +287,24 @@ export class OccupanciesService {
* 每行数据:姓名、电话、学号、房间号、楼栋、入住日期
* 自动创建不存在的学生和宿舍,并登记入住
*/
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 }) {
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;
@@ -269,17 +323,19 @@ export class OccupanciesService {
// 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,
}));
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 = {};
@@ -287,10 +343,14 @@ export class OccupanciesService {
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 (!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);
@@ -301,19 +361,26 @@ export class OccupanciesService {
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,
}));
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'] });
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}),跳过`);
errors.push(
`${rowNum}行: ${row.name} 已在住(${existing.room?.roomNumber || '房间' + existing.roomId}),跳过`,
);
skipped++;
continue;
}
@@ -321,14 +388,18 @@ export class OccupanciesService {
// 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}`);
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})无法入住,跳过`);
errors.push(
`${rowNum}行: 宿舍 ${row.roomNumber}${room.gender}生寝室,${row.name}(${student.gender})无法入住,跳过`,
);
skipped++;
continue;
}
@@ -361,15 +432,19 @@ export class OccupanciesService {
// 9. 自动收取押金(仅对新入住且非历史记录的学生)
if (options?.autoDeposit && !row.checkOutDate?.trim()) {
const existingDeposit = await this.depositRepo.findOne({ where: { studentId: student.id, status: 'paid' } });
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: '入住导入自动收取',
}));
await this.depositRepo.save(
this.depositRepo.create({
studentId: student.id,
amount: options.depositAmount || 500,
paidDate: checkInDate,
status: 'paid',
notes: '入住导入自动收取',
}),
);
depositsCreated++;
}
}

View File

@@ -5,9 +5,7 @@ import { OperationLog } from '../entities/operation-log.entity';
@Injectable()
export class OperationLogsService {
constructor(
@InjectRepository(OperationLog) private repo: Repository<OperationLog>,
) {}
constructor(@InjectRepository(OperationLog) private repo: Repository<OperationLog>) {}
async log(params: {
userId?: number;
@@ -33,16 +31,20 @@ export class OperationLogsService {
page?: number;
pageSize?: number;
}) {
const qb = this.repo.createQueryBuilder('log')
.orderBy('log.createdAt', 'DESC');
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' });
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();
const [data, total] = await qb
.skip((page - 1) * pageSize)
.take(pageSize)
.getManyAndCount();
return { data, total, page, pageSize };
}
}

View File

@@ -1,8 +1,23 @@
import {
Controller, Get, Post, Put, Delete, Body, Param, UseGuards, Request, BadRequestException,
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
UseGuards,
Request,
BadRequestException,
} from '@nestjs/common';
import { RbacService } from './rbac.service';
import { CreateRoleDto, UpdateRoleDto, CreateUserDto, UpdateUserDto, ResetPasswordDto } from './dto/rbac.dto';
import {
CreateRoleDto,
UpdateRoleDto,
CreateUserDto,
UpdateUserDto,
ResetPasswordDto,
} from './dto/rbac.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RequirePermission } from '../auth/decorators/permission.decorator';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
@@ -35,7 +50,15 @@ export class RbacController {
async createRole(@Body() dto: CreateRoleDto, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.rbacService.createRole(dto);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: 'RBAC', action: '创建角色', detail: `角色: ${dto.name}`, ipAddress, userAgent });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: 'RBAC',
action: '创建角色',
detail: `角色: ${dto.name}`,
ipAddress,
userAgent,
});
return result;
}
@@ -45,7 +68,17 @@ export class RbacController {
const { ipAddress, userAgent } = extractRequestInfo(req);
try {
const result = await this.rbacService.updateRole(+id, dto);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: 'RBAC', action: '编辑角色', targetId: +id, targetType: 'role', detail: JSON.stringify(dto), ipAddress, userAgent });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: 'RBAC',
action: '编辑角色',
targetId: +id,
targetType: 'role',
detail: JSON.stringify(dto),
ipAddress,
userAgent,
});
return result;
} catch (e: any) {
throw new BadRequestException(e.message);
@@ -58,7 +91,16 @@ export class RbacController {
const { ipAddress, userAgent } = extractRequestInfo(req);
try {
const result = await this.rbacService.deleteRole(+id);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: 'RBAC', action: '删除角色', targetId: +id, targetType: 'role', ipAddress, userAgent });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: 'RBAC',
action: '删除角色',
targetId: +id,
targetType: 'role',
ipAddress,
userAgent,
});
return result;
} catch (e: any) {
throw new BadRequestException(e.message);
@@ -93,7 +135,15 @@ export class RbacController {
const { ipAddress, userAgent } = extractRequestInfo(req);
try {
const result = await this.rbacService.createUser(dto);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '账号', action: '创建账号', detail: `用户名: ${dto.username}`, ipAddress, userAgent });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '账号',
action: '创建账号',
detail: `用户名: ${dto.username}`,
ipAddress,
userAgent,
});
return result;
} catch (e: any) {
throw new BadRequestException(e.message);
@@ -106,7 +156,17 @@ export class RbacController {
const { ipAddress, userAgent } = extractRequestInfo(req);
try {
const result = await this.rbacService.updateUser(+id, dto);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '账号', action: '更新账号', targetId: +id, targetType: 'user', detail: JSON.stringify(dto), ipAddress, userAgent });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '账号',
action: '更新账号',
targetId: +id,
targetType: 'user',
detail: JSON.stringify(dto),
ipAddress,
userAgent,
});
return result;
} catch (e: any) {
throw new BadRequestException(e.message);
@@ -119,7 +179,16 @@ export class RbacController {
const { ipAddress, userAgent } = extractRequestInfo(req);
try {
const result = await this.rbacService.resetPassword(+id, dto.password);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '账号', action: '重置密码', targetId: +id, targetType: 'user', ipAddress, userAgent });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '账号',
action: '重置密码',
targetId: +id,
targetType: 'user',
ipAddress,
userAgent,
});
return result;
} catch (e: any) {
throw new BadRequestException(e.message);
@@ -132,7 +201,16 @@ export class RbacController {
const { ipAddress, userAgent } = extractRequestInfo(req);
try {
const result = await this.rbacService.deleteUser(+id);
await this.logService.log({ userId: req.user?.id, username: req.user?.username, module: '账号', action: '删除账号', targetId: +id, targetType: 'user', ipAddress, userAgent });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '账号',
action: '删除账号',
targetId: +id,
targetType: 'user',
ipAddress,
userAgent,
});
return result;
} catch (e: any) {
throw new BadRequestException(e.message);

View File

@@ -6,10 +6,7 @@ import { RbacController } from './rbac.controller';
import { AuthModule } from '../auth/auth.module';
@Module({
imports: [
TypeOrmModule.forFeature([Permission, Role, User]),
forwardRef(() => AuthModule),
],
imports: [TypeOrmModule.forFeature([Permission, Role, User]), forwardRef(() => AuthModule)],
controllers: [RbacController],
providers: [RbacService],
exports: [RbacService],

View File

@@ -79,7 +79,16 @@ const PRESET_ROLES: Array<{
code: 'dormitory_supervisor',
description: '管理宿舍相关业务',
isSystem: true,
permissionGroups: ['student', 'room', 'occupancy', 'expense', 'bill', 'deposit', 'log', 'dashboard'],
permissionGroups: [
'student',
'room',
'occupancy',
'expense',
'bill',
'deposit',
'log',
'dashboard',
],
},
{
name: '老师',
@@ -216,9 +225,7 @@ export class RbacService {
if (dto.description !== undefined) role.description = dto.description;
if (dto.permissionIds !== undefined) {
role.permissions =
dto.permissionIds.length > 0
? await this.permRepo.findByIds(dto.permissionIds)
: [];
dto.permissionIds.length > 0 ? await this.permRepo.findByIds(dto.permissionIds) : [];
}
return this.roleRepo.save(role);
}
@@ -267,7 +274,7 @@ export class RbacService {
relations: ['roles'],
order: { createdAt: 'DESC' },
});
return users.map(u => ({
return users.map((u) => ({
id: u.id,
username: u.username,
name: u.name,
@@ -275,7 +282,7 @@ export class RbacService {
lastLoginAt: u.lastLoginAt,
createdAt: u.createdAt,
updatedAt: u.updatedAt,
roles: u.roles?.map(r => ({ id: r.id, name: r.name })) || [],
roles: u.roles?.map((r) => ({ id: r.id, name: r.name })) || [],
}));
}
@@ -283,7 +290,11 @@ export class RbacService {
const exists = await this.userRepo.findOne({ where: { username: dto.username } });
if (exists) throw new Error('用户名已存在');
const hash = await bcrypt.hash(dto.password, 10);
const user = this.userRepo.create({ username: dto.username, passwordHash: hash, name: dto.name });
const user = this.userRepo.create({
username: dto.username,
passwordHash: hash,
name: dto.name,
});
if (dto.roleIds && dto.roleIds.length > 0) {
user.roles = await this.roleRepo.findByIds(dto.roleIds);
}
@@ -291,7 +302,10 @@ export class RbacService {
return { message: '用户创建成功' };
}
async updateUser(id: number, dto: { username?: string; name?: string; isActive?: boolean; roleIds?: number[] }) {
async updateUser(
id: number,
dto: { username?: string; name?: string; isActive?: boolean; roleIds?: number[] },
) {
const user = await this.userRepo.findOne({ where: { id }, relations: ['roles'] });
if (!user) throw new Error('用户不存在');
if (dto.username !== undefined && dto.username !== user.username) {
@@ -302,9 +316,7 @@ export class RbacService {
if (dto.name !== undefined) user.name = dto.name;
if (dto.isActive !== undefined) user.isActive = dto.isActive;
if (dto.roleIds !== undefined) {
user.roles = dto.roleIds.length > 0
? await this.roleRepo.findByIds(dto.roleIds)
: [];
user.roles = dto.roleIds.length > 0 ? await this.roleRepo.findByIds(dto.roleIds) : [];
}
await this.userRepo.save(user);
return { message: '更新成功' };

View File

@@ -1,4 +1,18 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards, Request, Res, UseInterceptors, UploadedFile } from '@nestjs/common';
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';
@@ -12,11 +26,17 @@ import * as ExcelJS from 'exceljs';
@UseGuards(JwtAuthGuard)
@Controller('rooms')
export class RoomsController {
constructor(private service: RoomsService, private logService: OperationLogsService) {}
constructor(
private service: RoomsService,
private logService: OperationLogsService,
) {}
@Get()
@RequirePermission('room:view')
findAll(@Query('building') building?: string, @Query('includeArchived') includeArchived?: string) {
findAll(
@Query('building') building?: string,
@Query('includeArchived') includeArchived?: string,
) {
return this.service.findAll({ building, includeArchived: includeArchived === 'true' });
}
@@ -46,9 +66,24 @@ export class RoomsController {
];
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');
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();
@@ -57,7 +92,9 @@ export class RoomsController {
@Get('export')
@RequirePermission('room:view')
async exportExcel(@Query('includeArchived') includeArchived?: string, @Res() res?: Response) {
const rooms = await this.service.getRoomOverview({ includeArchived: includeArchived === 'true' });
const rooms = await this.service.getRoomOverview({
includeArchived: includeArchived === 'true',
});
const workbook = new ExcelJS.Workbook();
const ws = workbook.addWorksheet('宿舍列表');
ws.columns = [
@@ -72,11 +109,28 @@ export class RoomsController {
];
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: '已归档' };
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 });
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-Type',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
);
res!.setHeader('Content-Disposition', 'attachment; filename=rooms.xlsx');
await workbook.xlsx.write(res!);
res!.end();
@@ -93,7 +147,15 @@ export class RoomsController {
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 });
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;
}
@@ -102,7 +164,17 @@ export class RoomsController {
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 });
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;
}
@@ -111,7 +183,16 @@ export class RoomsController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '宿舍',
action: '归档宿舍',
targetId: +id,
targetType: 'room',
ipAddress,
userAgent,
});
return result;
}
@@ -120,7 +201,15 @@ export class RoomsController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '宿舍',
action: '批量归档宿舍',
detail: `IDs: ${(body.ids || []).join(',')}`,
ipAddress,
userAgent,
});
return result;
}
@@ -129,7 +218,16 @@ export class RoomsController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '宿舍',
action: '恢复宿舍',
targetId: +id,
targetType: 'room',
ipAddress,
userAgent,
});
return result;
}
@@ -141,7 +239,13 @@ export class RoomsController {
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 }[] = [];
const rows: {
roomNumber: string;
building?: string;
floor?: number;
capacity?: number;
roomType?: string;
}[] = [];
ws.eachRow((row, idx) => {
if (idx === 1) return;
rows.push({
@@ -153,7 +257,15 @@ export class RoomsController {
});
});
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '宿舍',
action: '批量导入',
detail: result.message,
ipAddress,
userAgent,
});
return result;
}
}

View File

@@ -21,7 +21,12 @@ export class RoomsService {
* "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 } {
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+)$/);
@@ -36,12 +41,18 @@ export class RoomsService {
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 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; }
if (bldgNum === '2') {
roomType = '单人间';
capacity = 1;
} else if (bldgNum === '8') {
roomType = '爆改房';
capacity = 2;
}
return { building, floor, roomType, capacity };
}
return {};
@@ -76,7 +87,9 @@ export class RoomsService {
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() } });
const count = await this.occRepo.count({
where: { roomId: room.id, checkOutDate: IsNull() },
});
result.push({ ...room, currentCount: count });
}
return result;
@@ -113,7 +126,9 @@ export class RoomsService {
skipped.push(`${r.roomNumber}(已归档)`);
continue;
}
const activeCount = await this.occRepo.count({ where: { roomId: r.id, checkOutDate: IsNull() } });
const activeCount = await this.occRepo.count({
where: { roomId: r.id, checkOutDate: IsNull() },
});
if (activeCount > 0) {
skipped.push(`${r.roomNumber}(有在住人员)`);
continue;
@@ -122,16 +137,18 @@ export class RoomsService {
}
let affected = 0;
if (targetIds.length > 0) {
const result = await this.repo.createQueryBuilder()
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}宿舍(数据已保留,可随时恢复`;
const message =
skipped.length > 0
? `成功归档 ${affected}${skipped.length} 间被跳过(${skipped.slice(0, 5).join('、')}${skipped.length > 5 ? '…' : ''}`
: `已批量归档 ${affected} 间宿舍(数据已保留,可随时恢复)`;
return { message, archived: affected, skipped: skipped.length };
}
@@ -143,7 +160,10 @@ export class RoomsService {
}
async getRoomVisual() {
const rooms = await this.repo.find({ where: { status: Not('archived') }, order: { building: 'ASC', roomNumber: 'ASC' } });
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'],
@@ -156,7 +176,10 @@ export class RoomsService {
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)));
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 || '未知',
@@ -201,24 +224,44 @@ export class RoomsService {
};
}
async batchImport(rows: { roomNumber: string; building?: string; floor?: number; capacity?: number; roomType?: string }[]) {
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; }
if (!row.roomNumber || !row.roomNumber.trim()) {
skipped++;
continue;
}
const exists = await this.repo.findOne({ where: { roomNumber: row.roomNumber.trim() } });
if (exists) { skipped++; continue; }
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,
}));
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 };
return {
message: `成功导入 ${imported} 间宿舍,跳过 ${skipped} 条(重复或空行)`,
imported,
skipped,
};
}
}

View File

@@ -1,4 +1,18 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards, Request, Res, UseInterceptors, UploadedFile } from '@nestjs/common';
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';
@@ -12,11 +26,18 @@ import * as ExcelJS from 'exceljs';
@UseGuards(JwtAuthGuard)
@Controller('students')
export class StudentsController {
constructor(private service: StudentsService, private logService: OperationLogsService) {}
constructor(
private service: StudentsService,
private logService: OperationLogsService,
) {}
@Get()
@RequirePermission('student:view')
findAll(@Query('name') name?: string, @Query('status') status?: string, @Query('includeArchived') includeArchived?: string) {
findAll(
@Query('name') name?: string,
@Query('status') status?: string,
@Query('includeArchived') includeArchived?: string,
) {
return this.service.findAll({ name, status, includeArchived: includeArchived === 'true' });
}
@@ -40,11 +61,30 @@ export class StudentsController {
];
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: '已归档' };
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 });
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-Type',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
);
res!.setHeader('Content-Disposition', 'attachment; filename=students.xlsx');
await workbook.xlsx.write(res!);
res!.end();
@@ -68,8 +108,21 @@ export class StudentsController {
];
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');
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();
@@ -86,7 +139,17 @@ export class StudentsController {
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 });
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;
}
@@ -95,7 +158,17 @@ export class StudentsController {
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 });
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;
}
@@ -104,7 +177,16 @@ export class StudentsController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '学生',
action: '归档学生',
targetId: +id,
targetType: 'student',
ipAddress,
userAgent,
});
return result;
}
@@ -113,7 +195,15 @@ export class StudentsController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '学生',
action: '批量归档学生',
detail: `IDs: ${(body.ids || []).join(',')}`,
ipAddress,
userAgent,
});
return result;
}
@@ -122,7 +212,16 @@ export class StudentsController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '学生',
action: '恢复学生',
targetId: +id,
targetType: 'student',
ipAddress,
userAgent,
});
return result;
}
@@ -134,7 +233,17 @@ export class StudentsController {
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 }[] = [];
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({
@@ -150,7 +259,15 @@ export class StudentsController {
});
});
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '学生',
action: '批量导入',
detail: result.message,
ipAddress,
userAgent,
});
return result;
}
}

View File

@@ -20,7 +20,10 @@ export class StudentsService {
}
async findOne(id: number) {
const student = await this.repo.findOne({ where: { id }, relations: ['occupancies', 'occupancies.room'] });
const student = await this.repo.findOne({
where: { id },
relations: ['occupancies', 'occupancies.room'],
});
if (!student) throw new NotFoundException('学生不存在');
return student;
}
@@ -56,16 +59,18 @@ export class StudentsService {
}
let affected = 0;
if (targetIds.length > 0) {
const result = await this.repo.createQueryBuilder()
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}(数据已保留,可随时恢复`;
const message =
skipped.length > 0
? `成功归档 ${affected}${skipped.length} 人已是归档状态被跳过(${skipped.slice(0, 5).join('、')}${skipped.length > 5 ? '…' : ''}`
: `已批量归档 ${affected} 人(数据已保留,可随时恢复)`;
return { message, archived: affected, skipped: skipped.length };
}
@@ -78,26 +83,50 @@ export class StudentsService {
return { message: '已恢复' };
}
async batchImport(rows: { name: string; phone?: string; idNumber?: string; gender?: string; ethnicity?: string; emergencyContact?: string; emergencyPhone?: string; organization?: string; supervisor?: string }[]) {
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; }
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,
}));
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 };
return {
message: `成功导入 ${imported} 名学生,跳过 ${skipped} 条(重复或空行)`,
imported,
skipped,
};
}
}

View File

@@ -1,4 +1,15 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards, Request } from '@nestjs/common';
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';
@@ -9,7 +20,10 @@ import { RequirePermission } from '../auth/decorators/permission.decorator';
@UseGuards(JwtAuthGuard)
@Controller('tenants')
export class TenantsController {
constructor(private service: TenantsService, private logService: OperationLogsService) {}
constructor(
private service: TenantsService,
private logService: OperationLogsService,
) {}
@Get()
@RequirePermission('tenant:view')
@@ -28,7 +42,17 @@ export class TenantsController {
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 });
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;
}
@@ -37,7 +61,17 @@ export class TenantsController {
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 });
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;
}
@@ -46,7 +80,16 @@ export class TenantsController {
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 });
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '租赁方',
action: '归档租赁方',
targetId: +id,
targetType: 'tenant',
ipAddress,
userAgent,
});
return result;
}
}

View File

@@ -6,8 +6,16 @@ import { CreateTenantDto, UpdateTenantDto } from './dto/tenant.dto';
// 预设色板(避开红绿盲敏感色,保证差异度)
const COLOR_PALETTE = [
'#ff7875', '#ffa940', '#ffc53d', '#73d13d', '#36cfc9',
'#40a9ff', '#597ef7', '#9254de', '#f759ab', '#8c8c8c',
'#ff7875',
'#ffa940',
'#ffc53d',
'#73d13d',
'#36cfc9',
'#40a9ff',
'#597ef7',
'#9254de',
'#f759ab',
'#8c8c8c',
];
@Injectable()