forked from wangziqi/gongxue-base
chore: commit oxfmt formatting changes and verify artifacts
This commit is contained in:
@@ -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();
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user