feat: auto-populate department_id on create + seed default campus with backfill

This commit is contained in:
2026-07-06 00:05:00 +08:00
parent cd6364268d
commit df61ebbc5b
16 changed files with 130 additions and 23 deletions

View File

@@ -1,6 +1,6 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Repository, In } from 'typeorm';
import { RoomExpense } from '../entities/room-expense.entity';
import { PersonalExpense } from '../entities/personal-expense.entity';
import { Room } from '../entities/room.entity';
@@ -25,12 +25,19 @@ export class ExpensesService {
// 宿舍费用
async createRoomExpense(dto: CreateRoomExpenseDto, userId?: number) {
return this.roomExpRepo.save(this.roomExpRepo.create({ ...dto, recordedBy: userId }));
const room = await this.roomRepo.findOne({ where: { id: dto.roomId } });
if (!room) throw new NotFoundException('宿舍不存在');
const entity = this.roomExpRepo.create({ ...dto, recordedBy: userId });
entity.departmentId = room.departmentId;
return this.roomExpRepo.save(entity);
}
async batchCreateRoomExpenses(dto: BatchRoomExpenseDto, userId?: number) {
const entities = dto.expenses.map((e) =>
this.roomExpRepo.create({
const roomIds = [...new Set(dto.expenses.map((e) => e.roomId))];
const rooms = await this.roomRepo.find({ where: { id: In(roomIds) } });
const roomDeptMap = new Map(rooms.map((r) => [r.id, r.departmentId]));
const entities = dto.expenses.map((e) => {
const entity = this.roomExpRepo.create({
roomId: e.roomId,
expenseType: e.expenseType,
amount: e.amount,
@@ -38,8 +45,10 @@ export class ExpensesService {
periodStart: dto.periodStart,
periodEnd: dto.periodEnd,
recordedBy: userId,
}),
);
});
entity.departmentId = roomDeptMap.get(e.roomId)!;
return entity;
});
return this.roomExpRepo.save(entities);
}
@@ -82,7 +91,11 @@ export class ExpensesService {
// 个人附加费
async createPersonalExpense(dto: CreatePersonalExpenseDto, userId?: number) {
return this.personalExpRepo.save(this.personalExpRepo.create({ ...dto, recordedBy: userId }));
const student = await this.studentRepo.findOne({ where: { id: dto.studentId } });
if (!student) throw new NotFoundException('学生不存在');
const entity = this.personalExpRepo.create({ ...dto, recordedBy: userId });
entity.departmentId = student.departmentId;
return this.personalExpRepo.save(entity);
}
async findPersonalExpenses(query?: { studentId?: number }) {