feat: 为批量归档补充批量恢复
This commit is contained in:
20
apps/server/src/common/batch-ids.dto.spec.ts
Normal file
20
apps/server/src/common/batch-ids.dto.spec.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { validate } from 'class-validator';
|
||||
import { BatchIdsDto } from './batch-ids.dto';
|
||||
|
||||
describe('BatchIdsDto', () => {
|
||||
it.each([
|
||||
{ ids: [] },
|
||||
{ ids: [0] },
|
||||
{ ids: [-1] },
|
||||
{ ids: [1.5] },
|
||||
{ ids: ['1'] },
|
||||
])('rejects invalid ids: $ids', async ({ ids }) => {
|
||||
const dto = Object.assign(new BatchIdsDto(), { ids });
|
||||
await expect(validate(dto)).resolves.not.toHaveLength(0);
|
||||
});
|
||||
|
||||
it('allows duplicate positive integer ids for service-level normalization', async () => {
|
||||
const dto = Object.assign(new BatchIdsDto(), { ids: [1, 1, 2] });
|
||||
await expect(validate(dto)).resolves.toHaveLength(0);
|
||||
});
|
||||
});
|
||||
9
apps/server/src/common/batch-ids.dto.ts
Normal file
9
apps/server/src/common/batch-ids.dto.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { ArrayNotEmpty, IsArray, IsInt, Min } from 'class-validator';
|
||||
|
||||
export class BatchIdsDto {
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@IsInt({ each: true })
|
||||
@Min(1, { each: true })
|
||||
ids: number[];
|
||||
}
|
||||
65
apps/server/src/common/batch-restore.controllers.spec.ts
Normal file
65
apps/server/src/common/batch-restore.controllers.spec.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import 'reflect-metadata';
|
||||
import { PIPES_METADATA } from '@nestjs/common/constants';
|
||||
import { PERMISSION_KEY } from '../auth/decorators/permission.decorator';
|
||||
import { ExpensesController } from '../expenses/expenses.controller';
|
||||
import { OccupanciesController } from '../occupancies/occupancies.controller';
|
||||
import { RoomsController } from '../rooms/rooms.controller';
|
||||
import { StudentsController } from '../students/students.controller';
|
||||
import { BatchIdsDto } from './batch-ids.dto';
|
||||
|
||||
describe('batch restore controllers', () => {
|
||||
const cases = [
|
||||
[StudentsController, 'batchRestore', ['student:edit']],
|
||||
[RoomsController, 'batchRestore', ['room:edit']],
|
||||
[ExpensesController, 'batchRestoreRoomExpenses', ['expense:edit']],
|
||||
[ExpensesController, 'batchRestorePersonalExpenses', ['expense:edit']],
|
||||
[OccupanciesController, 'batchRestore', ['occupancy:delete']],
|
||||
] as const;
|
||||
|
||||
it.each(cases)('%p.%s has permission and method-level validation', (controller, method, permission) => {
|
||||
const handler = controller.prototype[method] as (...args: never[]) => unknown;
|
||||
expect(Reflect.getMetadata(PERMISSION_KEY, handler)).toEqual(permission);
|
||||
expect(Reflect.getMetadata(PIPES_METADATA, handler)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each(cases)('%p.%s rejects invalid and non-whitelisted request bodies', async (controller, method) => {
|
||||
const handler = controller.prototype[method] as (...args: never[]) => unknown;
|
||||
const [pipe] = Reflect.getMetadata(PIPES_METADATA, handler);
|
||||
const metadata = { type: 'body' as const, metatype: BatchIdsDto, data: undefined };
|
||||
await expect(pipe.transform({ ids: [] }, metadata)).rejects.toBeDefined();
|
||||
await expect(pipe.transform({ ids: [0] }, metadata)).rejects.toBeDefined();
|
||||
await expect(pipe.transform({ ids: [1], unexpected: true }, metadata)).rejects.toBeDefined();
|
||||
});
|
||||
|
||||
it('writes the requested audit action and ids for every successful restore endpoint', async () => {
|
||||
const log = jest.fn().mockResolvedValue(undefined);
|
||||
const req = { user: { id: 7, username: 'admin' }, ip: '127.0.0.1', headers: {} };
|
||||
const services = {
|
||||
students: { batchRestore: jest.fn().mockResolvedValue({ restored: 1, skipped: 0 }) },
|
||||
rooms: { batchRestore: jest.fn().mockResolvedValue({ restored: 1, skipped: 0 }) },
|
||||
expenses: {
|
||||
batchRestoreRoomExpenses: jest.fn().mockResolvedValue({ restored: 1, skipped: 0 }),
|
||||
batchRestorePersonalExpenses: jest.fn().mockResolvedValue({ restored: 1, skipped: 0 }),
|
||||
},
|
||||
occupancies: { batchRestore: jest.fn().mockResolvedValue({ restored: 1, skipped: 0 }) },
|
||||
};
|
||||
const students = new StudentsController(services.students as never, { log } as never, {} as never, {} as never);
|
||||
const rooms = new RoomsController(services.rooms as never, { log } as never, {} as never);
|
||||
const expenses = new ExpensesController(services.expenses as never, { log } as never);
|
||||
const occupancies = new OccupanciesController(services.occupancies as never, { log } as never, {} as never, {} as never);
|
||||
|
||||
await students.batchRestore({ ids: [1, 2] }, req);
|
||||
await rooms.batchRestore({ ids: [1, 2] }, req);
|
||||
await expenses.batchRestoreRoomExpenses({ ids: [1, 2] }, req);
|
||||
await expenses.batchRestorePersonalExpenses({ ids: [1, 2] }, req);
|
||||
await occupancies.batchRestore({ ids: [1, 2] }, req);
|
||||
|
||||
expect(log.mock.calls.map(([entry]) => [entry.action, entry.detail])).toEqual([
|
||||
['批量恢复学生', 'IDs: 1,2'],
|
||||
['批量恢复宿舍', 'IDs: 1,2'],
|
||||
['批量恢复宿舍费用', 'IDs: 1,2'],
|
||||
['批量恢复个人费用', 'IDs: 1,2'],
|
||||
['批量恢复入住记录', 'IDs: 1,2'],
|
||||
]);
|
||||
});
|
||||
});
|
||||
307
apps/server/src/common/batch-restore.services.spec.ts
Normal file
307
apps/server/src/common/batch-restore.services.spec.ts
Normal file
@@ -0,0 +1,307 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { ExpensesService } from '../expenses/expenses.service';
|
||||
import { OccupanciesService } from '../occupancies/occupancies.service';
|
||||
import { RoomsService } from '../rooms/rooms.service';
|
||||
import { StudentsService } from '../students/students.service';
|
||||
|
||||
function updateQb(affected = 1) {
|
||||
const qb = {
|
||||
update: jest.fn(),
|
||||
set: jest.fn(),
|
||||
where: jest.fn(),
|
||||
execute: jest.fn().mockResolvedValue({ affected }),
|
||||
};
|
||||
qb.update.mockReturnValue(qb);
|
||||
qb.set.mockReturnValue(qb);
|
||||
qb.where.mockReturnValue(qb);
|
||||
return qb;
|
||||
}
|
||||
|
||||
function listQb() {
|
||||
const qb = {
|
||||
leftJoinAndSelect: jest.fn(),
|
||||
where: jest.fn(),
|
||||
orderBy: jest.fn(),
|
||||
andWhere: jest.fn(),
|
||||
getMany: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
qb.leftJoinAndSelect.mockReturnValue(qb);
|
||||
qb.where.mockReturnValue(qb);
|
||||
qb.orderBy.mockReturnValue(qb);
|
||||
qb.andWhere.mockReturnValue(qb);
|
||||
return qb;
|
||||
}
|
||||
|
||||
describe('batch restore service semantics', () => {
|
||||
it('rejects empty and invalid ids in every restore service', async () => {
|
||||
const students = new StudentsService(
|
||||
{} as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
{} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
);
|
||||
const rooms = new RoomsService(
|
||||
{} as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
);
|
||||
const expenses = new ExpensesService(
|
||||
{} as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
);
|
||||
const occupancies = new OccupanciesService(
|
||||
{} as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
);
|
||||
const calls = [
|
||||
(ids: number[]) => students.batchRestore(ids),
|
||||
(ids: number[]) => rooms.batchRestore(ids),
|
||||
(ids: number[]) => expenses.batchRestoreRoomExpenses(ids),
|
||||
(ids: number[]) => expenses.batchRestorePersonalExpenses(ids),
|
||||
(ids: number[]) => occupancies.batchRestore(ids),
|
||||
];
|
||||
for (const call of calls) {
|
||||
await expect(call([])).rejects.toBeInstanceOf(BadRequestException);
|
||||
await expect(call([0])).rejects.toBeInstanceOf(BadRequestException);
|
||||
await expect(call([1.5])).rejects.toBeInstanceOf(BadRequestException);
|
||||
}
|
||||
});
|
||||
|
||||
it('deduplicates student ids, restores archived rows, and skips active rows', async () => {
|
||||
const qb = updateQb();
|
||||
const repo = {
|
||||
find: jest.fn().mockResolvedValue([
|
||||
{ id: 1, status: 'archived' },
|
||||
{ id: 2, status: 'active' },
|
||||
]),
|
||||
createQueryBuilder: jest.fn(() => qb),
|
||||
};
|
||||
const service = new StudentsService(
|
||||
repo as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
|
||||
await expect(service.batchRestore([1, 1, 2])).resolves.toEqual({
|
||||
message: '已批量恢复 1 名学生',
|
||||
restored: 1,
|
||||
skipped: 1,
|
||||
});
|
||||
expect(repo.find).toHaveBeenCalledWith({ where: { id: expect.anything() } });
|
||||
expect(qb.set).toHaveBeenCalledWith({ status: 'active' });
|
||||
expect(qb.where).toHaveBeenCalledWith('id IN (:...ids)', { ids: [1] });
|
||||
});
|
||||
|
||||
it('rejects missing student ids before updating', async () => {
|
||||
const repo = { find: jest.fn().mockResolvedValue([{ id: 1, status: 'archived' }]), createQueryBuilder: jest.fn() };
|
||||
const service = new StudentsService(
|
||||
repo as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
{} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
);
|
||||
await expect(service.batchRestore([1, 2])).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(repo.createQueryBuilder).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('restores archived rooms to available and skips non-archived rooms', async () => {
|
||||
const qb = updateQb();
|
||||
const repo = {
|
||||
find: jest.fn().mockResolvedValue([
|
||||
{ id: 1, status: 'archived' },
|
||||
{ id: 2, status: 'maintenance' },
|
||||
]),
|
||||
createQueryBuilder: jest.fn(() => qb),
|
||||
};
|
||||
const service = new RoomsService(
|
||||
repo as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
);
|
||||
await expect(service.batchRestore([1, 2])).resolves.toEqual({
|
||||
message: '已批量恢复 1 间宿舍', restored: 1, skipped: 1,
|
||||
});
|
||||
expect(qb.set).toHaveBeenCalledWith({ status: 'available' });
|
||||
});
|
||||
|
||||
it('rejects room-expense restore when any selected record is billed', async () => {
|
||||
const qb = updateQb();
|
||||
const roomExpRepo = {
|
||||
find: jest.fn().mockResolvedValue([{ id: 1, status: 'archived' }]),
|
||||
createQueryBuilder: jest.fn(() => qb),
|
||||
};
|
||||
const billItemsRepo = { count: jest.fn().mockResolvedValue(1) };
|
||||
const service = new ExpensesService(
|
||||
roomExpRepo as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{ getRepository: jest.fn(() => billItemsRepo) } as never,
|
||||
);
|
||||
await expect(service.batchRestoreRoomExpenses([1])).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(roomExpRepo.createQueryBuilder).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('restores unbilled room expenses and reports active rows as skipped', async () => {
|
||||
const qb = updateQb();
|
||||
const roomExpRepo = {
|
||||
find: jest.fn().mockResolvedValue([
|
||||
{ id: 1, status: 'archived' },
|
||||
{ id: 2, status: 'active' },
|
||||
]),
|
||||
createQueryBuilder: jest.fn(() => qb),
|
||||
};
|
||||
const service = new ExpensesService(
|
||||
roomExpRepo as never, {} as never, {} as never, {} as never, {} as never,
|
||||
{ getRepository: jest.fn(() => ({ count: jest.fn().mockResolvedValue(0) })) } as never,
|
||||
);
|
||||
await expect(service.batchRestoreRoomExpenses([1, 2])).resolves.toMatchObject({ restored: 1, skipped: 1 });
|
||||
expect(qb.set).toHaveBeenCalledWith({ status: 'active' });
|
||||
});
|
||||
|
||||
it('skips an active billed room expense without blocking an archived unbilled expense', async () => {
|
||||
const qb = updateQb();
|
||||
const count = jest.fn().mockResolvedValue(0);
|
||||
const roomExpRepo = {
|
||||
find: jest.fn().mockResolvedValue([
|
||||
{ id: 1, status: 'archived' },
|
||||
{ id: 2, status: 'active' },
|
||||
]),
|
||||
createQueryBuilder: jest.fn(() => qb),
|
||||
};
|
||||
const service = new ExpensesService(
|
||||
roomExpRepo as never, {} as never, {} as never, {} as never, {} as never,
|
||||
{ getRepository: jest.fn(() => ({ count })) } as never,
|
||||
);
|
||||
await expect(service.batchRestoreRoomExpenses([1, 2])).resolves.toMatchObject({
|
||||
restored: 1,
|
||||
skipped: 1,
|
||||
});
|
||||
expect(count).toHaveBeenCalledWith({ where: { roomExpenseId: expect.anything() } });
|
||||
expect(qb.where).toHaveBeenCalledWith('id IN (:...ids)', { ids: [1] });
|
||||
});
|
||||
|
||||
it('rejects personal-expense restore when any selected record has a bill id', async () => {
|
||||
const personalExpRepo = {
|
||||
find: jest.fn().mockResolvedValue([{ id: 1, status: 'archived', billId: 9 }]),
|
||||
createQueryBuilder: jest.fn(),
|
||||
};
|
||||
const service = new ExpensesService(
|
||||
{} as never, personalExpRepo as never, {} as never, {} as never, {} as never, {} as never,
|
||||
);
|
||||
await expect(service.batchRestorePersonalExpenses([1])).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(personalExpRepo.createQueryBuilder).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('restores unbilled personal expenses and skips already active records', async () => {
|
||||
const qb = updateQb();
|
||||
const personalExpRepo = {
|
||||
find: jest.fn().mockResolvedValue([
|
||||
{ id: 1, status: 'archived', billId: null },
|
||||
{ id: 2, status: 'active', billId: null },
|
||||
]),
|
||||
createQueryBuilder: jest.fn(() => qb),
|
||||
};
|
||||
const service = new ExpensesService(
|
||||
{} as never, personalExpRepo as never, {} as never, {} as never, {} as never, {} as never,
|
||||
);
|
||||
await expect(service.batchRestorePersonalExpenses([1, 1, 2])).resolves.toMatchObject({
|
||||
restored: 1,
|
||||
skipped: 1,
|
||||
});
|
||||
expect(qb.where).toHaveBeenCalledWith('id IN (:...ids)', { ids: [1] });
|
||||
});
|
||||
|
||||
it('skips an active billed personal expense without blocking an archived unbilled expense', async () => {
|
||||
const qb = updateQb();
|
||||
const personalExpRepo = {
|
||||
find: jest.fn().mockResolvedValue([
|
||||
{ id: 1, status: 'archived', billId: null },
|
||||
{ id: 2, status: 'active', billId: 9 },
|
||||
]),
|
||||
createQueryBuilder: jest.fn(() => qb),
|
||||
};
|
||||
const service = new ExpensesService(
|
||||
{} as never, personalExpRepo as never, {} as never, {} as never, {} as never, {} as never,
|
||||
);
|
||||
await expect(service.batchRestorePersonalExpenses([1, 2])).resolves.toMatchObject({
|
||||
restored: 1,
|
||||
skipped: 1,
|
||||
});
|
||||
expect(qb.where).toHaveBeenCalledWith('id IN (:...ids)', { ids: [1] });
|
||||
});
|
||||
|
||||
it('uses archived status when querying expense archive views', async () => {
|
||||
const roomQb = listQb();
|
||||
const personalRepo = { find: jest.fn().mockResolvedValue([]) };
|
||||
const service = new ExpensesService(
|
||||
{ createQueryBuilder: jest.fn(() => roomQb) } as never,
|
||||
personalRepo as never,
|
||||
{} as never, {} as never, {} as never, {} as never,
|
||||
);
|
||||
await service.findRoomExpenses({ status: 'archived' });
|
||||
await service.findPersonalExpenses({ status: 'archived' });
|
||||
expect(roomQb.where).toHaveBeenCalledWith('e.status = :status', { status: 'archived' });
|
||||
expect(personalRepo.find).toHaveBeenCalledWith(expect.objectContaining({ where: { status: 'archived' } }));
|
||||
});
|
||||
|
||||
it('rejects invalid expense query status values', async () => {
|
||||
const service = new ExpensesService(
|
||||
{} as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
);
|
||||
await expect(service.findRoomExpenses({ status: 'deleted' as never })).rejects.toBeInstanceOf(BadRequestException);
|
||||
await expect(service.findPersonalExpenses({ status: 'deleted' as never })).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('rejects an archived occupancy without a checkout date before updating', async () => {
|
||||
const repo = {
|
||||
find: jest.fn().mockResolvedValue([{ id: 1, status: 'archived', checkOutDate: null }]),
|
||||
createQueryBuilder: jest.fn(),
|
||||
};
|
||||
const service = new OccupanciesService(
|
||||
repo as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
);
|
||||
await expect(service.batchRestore([1])).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(repo.createQueryBuilder).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('restores checked-out occupancies without changing room, bed, or locker state', async () => {
|
||||
const qb = updateQb();
|
||||
const repo = {
|
||||
find: jest.fn().mockResolvedValue([
|
||||
{ id: 1, status: 'archived', checkOutDate: '2026-07-01' },
|
||||
{ id: 2, status: 'active', checkOutDate: '2026-07-02' },
|
||||
]),
|
||||
createQueryBuilder: jest.fn(() => qb),
|
||||
};
|
||||
const roomRepo = { update: jest.fn() };
|
||||
const bedRepo = { update: jest.fn() };
|
||||
const lockerRepo = { update: jest.fn() };
|
||||
const service = new OccupanciesService(
|
||||
repo as never, roomRepo as never, {} as never, {} as never, bedRepo as never,
|
||||
lockerRepo as never, {} as never, {} as never,
|
||||
);
|
||||
await expect(service.batchRestore([1, 2])).resolves.toMatchObject({ restored: 1, skipped: 1 });
|
||||
expect(qb.set).toHaveBeenCalledWith({ status: 'active' });
|
||||
expect(roomRepo.update).not.toHaveBeenCalled();
|
||||
expect(bedRepo.update).not.toHaveBeenCalled();
|
||||
expect(lockerRepo.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses archived status while preserving active=true as checkout filtering', async () => {
|
||||
const qb = listQb();
|
||||
const service = new OccupanciesService(
|
||||
{ createQueryBuilder: jest.fn(() => qb) } as never,
|
||||
{} as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
);
|
||||
await service.findAll({ status: 'archived', active: true });
|
||||
expect(qb.where).toHaveBeenCalledWith('o.status = :status', { status: 'archived' });
|
||||
expect(qb.andWhere).toHaveBeenCalledWith('o.checkOutDate IS NULL');
|
||||
});
|
||||
|
||||
it('rejects invalid occupancy query status values', async () => {
|
||||
const service = new OccupanciesService(
|
||||
{} as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
);
|
||||
await expect(service.findAll({ status: 'deleted' as never })).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
});
|
||||
@@ -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 {
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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('费用记录不存在');
|
||||
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
UseInterceptors,
|
||||
UploadedFile,
|
||||
BadRequestException,
|
||||
UsePipes,
|
||||
ValidationPipe,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
@@ -27,6 +29,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';
|
||||
import {
|
||||
createOccupancyImportTemplateWorkbook,
|
||||
@@ -49,14 +52,34 @@ export class OccupanciesController {
|
||||
@Query('roomId') roomId?: string,
|
||||
@Query('studentId') studentId?: string,
|
||||
@Query('active') active?: string,
|
||||
@Query('status') status?: 'active' | 'archived',
|
||||
) {
|
||||
return this.service.findAll({
|
||||
roomId: roomId ? +roomId : undefined,
|
||||
studentId: studentId ? +studentId : undefined,
|
||||
active: active === 'true',
|
||||
status,
|
||||
});
|
||||
}
|
||||
|
||||
@Put('batch-restore')
|
||||
@RequirePermission('occupancy:delete')
|
||||
@UsePipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))
|
||||
async batchRestore(@Body() dto: BatchIdsDto, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.batchRestore(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;
|
||||
}
|
||||
|
||||
@Post('batch-check-out')
|
||||
@RequirePermission('occupancy:checkout')
|
||||
async batchCheckOut(@Body() dto: BatchCheckOutDto, @Request() req: any) {
|
||||
|
||||
@@ -46,14 +46,16 @@ export class OccupanciesService {
|
||||
return qb;
|
||||
}
|
||||
|
||||
async findAll(query?: { roomId?: number; studentId?: number; active?: boolean }) {
|
||||
async findAll(query?: { roomId?: number; studentId?: number; active?: boolean; status?: 'active' | 'archived' }) {
|
||||
const status = query?.status ?? 'active';
|
||||
if (status !== 'active' && status !== 'archived') throw new BadRequestException('入住记录状态无效');
|
||||
const qb = this.repo
|
||||
.createQueryBuilder('o')
|
||||
.leftJoinAndSelect('o.student', 'student')
|
||||
.leftJoinAndSelect('o.room', 'room')
|
||||
.leftJoinAndSelect('o.bed', 'bed')
|
||||
.leftJoinAndSelect('o.locker', 'locker')
|
||||
.where('o.status = :status', { status: 'active' })
|
||||
.where('o.status = :status', { status })
|
||||
.orderBy('o.checkInDate', 'DESC');
|
||||
if (query?.roomId) qb.andWhere('o.roomId = :roomId', { roomId: query.roomId });
|
||||
if (query?.studentId) qb.andWhere('o.studentId = :studentId', { studentId: query.studentId });
|
||||
@@ -348,6 +350,33 @@ export class OccupanciesService {
|
||||
return { message, archived, skipped: skipped.length };
|
||||
}
|
||||
|
||||
async batchRestore(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 records = await this.repo.find({ where: { id: In(uniqueIds) } });
|
||||
if (records.length !== uniqueIds.length) throw new NotFoundException('部分入住记录不存在');
|
||||
if (records.some((record) => record.status === 'archived' && !record.checkOutDate)) {
|
||||
throw new BadRequestException('选中记录包含未退宿的异常归档记录');
|
||||
}
|
||||
|
||||
const targetIds = records.filter((record) => record.status === 'archived').map((record) => record.id);
|
||||
const skipped = records.length - targetIds.length;
|
||||
let restored = 0;
|
||||
if (targetIds.length > 0) {
|
||||
const result = await this.repo
|
||||
.createQueryBuilder()
|
||||
.update()
|
||||
.set({ status: 'active' })
|
||||
.where('id IN (:...ids)', { ids: targetIds })
|
||||
.execute();
|
||||
restored = result.affected || 0;
|
||||
}
|
||||
return { message: `已批量恢复 ${restored} 条入住记录`, restored, skipped };
|
||||
}
|
||||
|
||||
async batchCheckOut(dto: {
|
||||
ids: number[];
|
||||
checkOutDate: string;
|
||||
|
||||
@@ -12,6 +12,8 @@ import {
|
||||
Res,
|
||||
UseInterceptors,
|
||||
UploadedFile,
|
||||
UsePipes,
|
||||
ValidationPipe,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import type { Response } from 'express';
|
||||
@@ -25,6 +27,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';
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@@ -57,6 +60,24 @@ export class RoomsController {
|
||||
return this.service.getRoomVisual(asOf);
|
||||
}
|
||||
|
||||
@Put('batch-restore')
|
||||
@RequirePermission('room:edit')
|
||||
@UsePipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))
|
||||
async batchRestore(@Body() dto: BatchIdsDto, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.batchRestore(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(':roomId/inspections/:date')
|
||||
@RequirePermission('room:inspect')
|
||||
async updateInspection(
|
||||
|
||||
@@ -306,6 +306,30 @@ export class RoomsService {
|
||||
return { message: '已恢复' };
|
||||
}
|
||||
|
||||
async batchRestore(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 rooms = await this.repo.find({ where: { id: In(uniqueIds) } });
|
||||
if (rooms.length !== uniqueIds.length) throw new NotFoundException('部分宿舍不存在');
|
||||
|
||||
const targetIds = rooms.filter((room) => room.status === 'archived').map((room) => room.id);
|
||||
const skipped = rooms.length - targetIds.length;
|
||||
let restored = 0;
|
||||
if (targetIds.length > 0) {
|
||||
const result = await this.repo
|
||||
.createQueryBuilder()
|
||||
.update()
|
||||
.set({ status: 'available' })
|
||||
.where('id IN (:...ids)', { ids: targetIds })
|
||||
.execute();
|
||||
restored = result.affected || 0;
|
||||
}
|
||||
return { message: `已批量恢复 ${restored} 间宿舍`, restored, skipped };
|
||||
}
|
||||
|
||||
async getRoomVisual(asOf?: string) {
|
||||
// asOf 为空 = 实时(今天)。带 asOf = 还原该日期结束时的历史入住快照。
|
||||
const isHistorical = !!asOf;
|
||||
|
||||
@@ -14,6 +14,8 @@ import {
|
||||
UploadedFile,
|
||||
Inject,
|
||||
ParseIntPipe,
|
||||
UsePipes,
|
||||
ValidationPipe,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
@@ -35,6 +37,7 @@ import {
|
||||
parseStudentImportWorkbook,
|
||||
STUDENT_EXPORT_COLUMNS,
|
||||
} from './student-import';
|
||||
import { BatchIdsDto } from '../common/batch-ids.dto';
|
||||
|
||||
interface AuthenticatedRequest {
|
||||
user: AuthenticatedUser;
|
||||
@@ -196,6 +199,24 @@ export class StudentsController {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Put('batch-restore')
|
||||
@RequirePermission('student:edit')
|
||||
@UsePipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))
|
||||
async batchRestore(@Body() dto: BatchIdsDto, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.batchRestore(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(':id')
|
||||
@RequirePermission('student:edit')
|
||||
async update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateStudentDto, @Request() req: any) {
|
||||
|
||||
@@ -219,6 +219,30 @@ export class StudentsService {
|
||||
return { message: '已恢复' };
|
||||
}
|
||||
|
||||
async batchRestore(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 students = await this.repo.find({ where: { id: In(uniqueIds) } });
|
||||
if (students.length !== uniqueIds.length) throw new NotFoundException('部分学生不存在');
|
||||
|
||||
const targetIds = students.filter((student) => student.status === 'archived').map((student) => student.id);
|
||||
const skipped = students.length - targetIds.length;
|
||||
let restored = 0;
|
||||
if (targetIds.length > 0) {
|
||||
const result = await this.repo
|
||||
.createQueryBuilder()
|
||||
.update()
|
||||
.set({ status: 'active' })
|
||||
.where('id IN (:...ids)', { ids: targetIds })
|
||||
.execute();
|
||||
restored = result.affected || 0;
|
||||
}
|
||||
return { message: `已批量恢复 ${restored} 名学生`, restored, skipped };
|
||||
}
|
||||
|
||||
async batchImport(importData: StudentWorkbookImport | StudentImportRow[]) {
|
||||
const data = this.normalizeImportData(importData);
|
||||
let imported = 0;
|
||||
|
||||
Reference in New Issue
Block a user