feat: 为批量归档补充批量恢复

This commit is contained in:
2026-07-25 09:34:03 +08:00
parent 1da763109b
commit 0ef86e65ce
19 changed files with 1365 additions and 317 deletions

View File

@@ -71,6 +71,10 @@ export class QueryRoomExpenseDto {
@IsOptional()
@IsDateString()
periodEnd?: string;
@IsOptional()
@IsIn(['active', 'archived'])
status?: 'active' | 'archived';
}
export class QueryPersonalExpenseDto {
@@ -78,6 +82,10 @@ export class QueryPersonalExpenseDto {
@Type(() => Number)
@IsInt()
studentId?: number;
@IsOptional()
@IsIn(['active', 'archived'])
status?: 'active' | 'archived';
}
export class BatchRoomExpenseItemDto {

View File

@@ -13,6 +13,8 @@ import {
UseInterceptors,
UploadedFile,
ParseIntPipe,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import type { Response } from 'express';
@@ -31,6 +33,7 @@ import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
import { extractRequestInfo } from '../common/request-utils';
import { RequirePermission } from '../auth/decorators/permission.decorator';
import { BatchIdsDto } from '../common/batch-ids.dto';
import * as ExcelJS from 'exceljs';
/** 提取 ExcelJS 单元格的真实值,兼容公式、富文本、日期、超链接等情况 */
@@ -180,6 +183,24 @@ export class ExpensesController {
return result;
}
@Put('room/batch-restore')
@RequirePermission('expense:edit')
@UsePipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))
async batchRestoreRoomExpenses(@Body() dto: BatchIdsDto, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.batchRestoreRoomExpenses(dto.ids);
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '费用管理',
action: '批量恢复宿舍费用',
detail: `IDs: ${dto.ids.join(',')}`,
ipAddress,
userAgent,
});
return result;
}
@Put('room/:id')
@RequirePermission('expense:edit')
async updateRoomExpense(
@@ -260,6 +281,24 @@ export class ExpensesController {
return result;
}
@Put('personal/batch-restore')
@RequirePermission('expense:edit')
@UsePipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))
async batchRestorePersonalExpenses(@Body() dto: BatchIdsDto, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.batchRestorePersonalExpenses(dto.ids);
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '费用管理',
action: '批量恢复个人费用',
detail: `IDs: ${dto.ids.join(',')}`,
ipAddress,
userAgent,
});
return result;
}
@Put('personal/:id')
@RequirePermission('expense:edit')
async updatePersonalExpense(

View File

@@ -73,11 +73,13 @@ export class ExpensesService {
return this.roomExpRepo.save(entities);
}
async findRoomExpenses(query?: { roomId?: number; periodStart?: string; periodEnd?: string }) {
async findRoomExpenses(query?: { roomId?: number; periodStart?: string; periodEnd?: string; status?: 'active' | 'archived' }) {
const status = query?.status ?? 'active';
if (status !== 'active' && status !== 'archived') throw new BadRequestException('费用状态无效');
const qb = this.roomExpRepo
.createQueryBuilder('e')
.leftJoinAndSelect('e.room', 'room')
.where('e.status = :status', { status: 'active' })
.where('e.status = :status', { status })
.orderBy('e.createdAt', 'DESC');
if (query?.roomId) qb.andWhere('e.roomId = :roomId', { roomId: query.roomId });
if (query?.periodStart) qb.andWhere('e.periodStart >= :ps', { ps: query.periodStart });
@@ -111,6 +113,33 @@ export class ExpensesService {
return { message: `已批量归档 ${result.affected || 0}`, archived: result.affected || 0 };
}
async batchRestoreRoomExpenses(ids: number[]) {
const uniqueIds = [...new Set(ids || [])];
if (uniqueIds.length === 0) throw new BadRequestException('请选择要恢复的记录');
if (uniqueIds.some((id) => !Number.isInteger(id) || id <= 0)) {
throw new BadRequestException('费用记录 ID 无效');
}
const existing = await this.roomExpRepo.find({ where: { id: In(uniqueIds) } });
if (existing.length !== uniqueIds.length) throw new NotFoundException('部分费用记录不存在');
const targetIds = existing.filter((expense) => expense.status === 'archived').map((expense) => expense.id);
const skipped = existing.length - targetIds.length;
let restored = 0;
if (targetIds.length > 0) {
const billed = await this.dataSource
.getRepository('bill_items')
.count({ where: { roomExpenseId: In(targetIds) } });
if (billed) throw new BadRequestException('选中记录包含已计入账单的宿舍费用');
const result = await this.roomExpRepo
.createQueryBuilder()
.update()
.set({ status: 'active' })
.where('id IN (:...ids)', { ids: targetIds })
.execute();
restored = result.affected || 0;
}
return { message: `已批量恢复 ${restored} 条宿舍费用`, restored, skipped };
}
async updateRoomExpense(id: number, dto: Partial<CreateRoomExpenseDto>) {
const e = await this.roomExpRepo.findOne({ where: { id } });
const billed = await this.dataSource?.getRepository('bill_items').count({ where: { roomExpenseId: id } });
@@ -173,8 +202,10 @@ export class ExpensesService {
return this.personalExpRepo.save(entity);
}
async findPersonalExpenses(query?: { studentId?: number }) {
const where: Record<string, unknown> = { status: 'active' };
async findPersonalExpenses(query?: { studentId?: number; status?: 'active' | 'archived' }) {
const status = query?.status ?? 'active';
if (status !== 'active' && status !== 'archived') throw new BadRequestException('费用状态无效');
const where: Record<string, unknown> = { status };
if (query?.studentId) where.studentId = query.studentId;
return this.personalExpRepo.find({
where,
@@ -209,6 +240,34 @@ export class ExpensesService {
return { message: `已批量归档 ${result.affected || 0}`, archived: result.affected || 0 };
}
async batchRestorePersonalExpenses(ids: number[]) {
const uniqueIds = [...new Set(ids || [])];
if (uniqueIds.length === 0) throw new BadRequestException('请选择要恢复的记录');
if (uniqueIds.some((id) => !Number.isInteger(id) || id <= 0)) {
throw new BadRequestException('费用记录 ID 无效');
}
const existing = await this.personalExpRepo.find({ where: { id: In(uniqueIds) } });
if (existing.length !== uniqueIds.length) throw new NotFoundException('部分费用记录不存在');
const targets = existing.filter((expense) => expense.status === 'archived');
if (targets.some((expense) => expense.billId)) {
throw new BadRequestException('选中记录包含已计入账单的个人费用');
}
const targetIds = targets.map((expense) => expense.id);
const skipped = existing.length - targetIds.length;
let restored = 0;
if (targetIds.length > 0) {
const result = await this.personalExpRepo
.createQueryBuilder()
.update()
.set({ status: 'active' })
.where('id IN (:...ids)', { ids: targetIds })
.execute();
restored = result.affected || 0;
}
return { message: `已批量恢复 ${restored} 条个人费用`, restored, skipped };
}
async updatePersonalExpense(id: number, dto: Partial<CreatePersonalExpenseDto>) {
const e = await this.personalExpRepo.findOne({ where: { id } });
if (!e) throw new NotFoundException('费用记录不存在');