feat: complete remaining PRD tasks — RBAC nodes and staff split, schedule month view, auto-generate attendance from schedules, plus fix TypeORM name

This commit is contained in:
2026-07-06 18:10:14 +08:00
parent 67952af52e
commit 693ba5d3b8
12 changed files with 447 additions and 48 deletions

View File

@@ -442,8 +442,8 @@ ${this.buildLearningAndResult(learnings, result, now)}
const sortedExams = [...cultureExams].filter((e) => e.score != null);
let improvement = '—';
if (sortedExams.length >= 2) {
const first = sortedExams[0].score!;
const last = sortedExams[sortedExams.length - 1].score!;
const first = sortedExams[0].score;
const last = sortedExams[sortedExams.length - 1].score;
improvement = (last - first).toFixed(1);
}
@@ -538,7 +538,7 @@ ${this.buildLearningAndResult(learnings, result, now)}
const cultureExams = exams.filter((e) => e.score != null);
if (cultureExams.length === 0) return '';
const scores = cultureExams.map((e) => e.score!);
const scores = cultureExams.map((e) => e.score);
const labels = cultureExams.map((e) => {
const d = e.examDate || '-';
return d.length > 7 ? d.slice(5) : d;

View File

@@ -22,6 +22,7 @@ import {
MatchDingRecordDto,
AttendanceReportQueryDto,
UpdateAttendanceRecordDto,
GenerateFromSchedulesDto,
} from './dto/attendance.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
@@ -58,6 +59,28 @@ export class AttendanceController {
return result;
}
// ── Generate attendance records from schedules (with optional date range) ──
@Post('attendance-records/generate-from-schedules')
@RequirePermission('attendance:create')
async generateFromSchedules(
@Body() dto: GenerateFromSchedulesDto,
@Request() req: any,
) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.generateFromSchedules(dto);
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '考勤管理',
action: '按课表生成考勤',
detail: `班级 ${dto.classId}, 共 ${result.count}`,
ipAddress,
userAgent,
});
return result;
}
// ── Export attendance records ──
@Get('attendance-records/export')
@RequirePermission('attendance:export')

View File

@@ -1,13 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AttendanceRecord, DingAttendanceRaw, Student, Class } from '../entities';
import { AttendanceRecord, DingAttendanceRaw, Student, Class, ClassSchedule, ClassStudent } from '../entities';
import { AttendanceService } from './attendance.service';
import { AttendanceController } from './attendance.controller';
import { OperationLogsModule } from '../operation-logs/operation-logs.module';
import { CommonModule } from '../common/common.module';
@Module({
imports: [
TypeOrmModule.forFeature([AttendanceRecord, DingAttendanceRaw, Student, Class]),
TypeOrmModule.forFeature([AttendanceRecord, DingAttendanceRaw, Student, Class, ClassSchedule, ClassStudent]),
OperationLogsModule,
CommonModule,
],

View File

@@ -25,7 +25,7 @@ describe('AttendanceService — batchCreate', () => {
save: jest
.fn()
.mockImplementation((entities: AttendanceRecord[]) => {
const result = entities.map((e, i) => ({ ...e, id: i + 1 } as AttendanceRecord));
const result = entities.map((e, i) => ({ ...e, id: i + 1 }));
savedRecords.push(...result);
return Promise.resolve(result);
}),

View File

@@ -4,8 +4,8 @@ import {
BadRequestException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In, Between } from 'typeorm';
import { AttendanceRecord, DingAttendanceRaw, Class, Student } from '../entities';
import { Repository, In, Between, LessThanOrEqual, MoreThanOrEqual } from 'typeorm';
import { AttendanceRecord, DingAttendanceRaw, Class, Student, ClassSchedule, ClassStudent, ScheduleType } from '../entities';
import { CampusScope } from '../common/campus-scope';
import {
BatchCreateAttendanceDto,
@@ -15,6 +15,8 @@ import {
MatchDingRecordDto,
AttendanceReportQueryDto,
UpdateAttendanceRecordDto,
GenerateAttendanceFromSchedulesDto,
GenerateFromSchedulesDto,
} from './dto/attendance.dto';
@Injectable()
@@ -28,6 +30,10 @@ export class AttendanceService {
private classRepo: Repository<Class>,
@InjectRepository(Student)
private studentRepo: Repository<Student>,
@InjectRepository(ClassSchedule)
private scheduleRepo: Repository<ClassSchedule>,
@InjectRepository(ClassStudent)
private classStudentRepo: Repository<ClassStudent>,
private readonly scope: CampusScope,
) {}
@@ -60,6 +66,114 @@ export class AttendanceService {
return { count: saved.length, records: saved };
}
// ── Generate attendance records from class schedules ──
async generateAttendanceFromSchedules(dto: GenerateAttendanceFromSchedulesDto) {
const { classId, dateFrom, dateTo } = dto;
if (dateFrom > dateTo) {
throw new BadRequestException('dateFrom must not be later than dateTo');
}
const cls = await this.classRepo.findOne({ where: { id: classId } });
if (!cls) {
throw new NotFoundException(`Class ${classId} not found`);
}
const schedules = await this.scheduleRepo.find({
where: {
classId,
scheduleType: ScheduleType.INTERNAL,
status: 'active',
startDate: LessThanOrEqual(dateTo),
endDate: MoreThanOrEqual(dateFrom),
},
});
const classStudents = await this.classStudentRepo.find({
where: { classId, status: 'active' },
relations: ['student'],
});
if (schedules.length === 0 || classStudents.length === 0) {
return { count: 0, records: [] };
}
const existingRecords = await this.attendanceRepo.find({
where: { classId, attendanceDate: Between(dateFrom, dateTo) },
});
const existingKeys = new Set(
existingRecords.map((r) => `${r.studentId}|${r.attendanceDate}|${r.session}`),
);
const entities: AttendanceRecord[] = [];
const end = new Date(dateTo);
for (let d = new Date(dateFrom); d <= end; d.setDate(d.getDate() + 1)) {
const dateStr = d.toISOString().slice(0, 10);
const weekDay = d.getDay() === 0 ? 7 : d.getDay();
for (const sched of schedules) {
if (sched.weekDay !== weekDay) continue;
if (dateStr < sched.startDate || dateStr > sched.endDate) continue;
const session = this.mapScheduleTimeToSession(sched.startTime);
for (const cs of classStudents) {
const key = `${cs.studentId}|${dateStr}|${session}`;
if (existingKeys.has(key)) continue;
const entity = this.attendanceRepo.create({
studentId: cs.studentId,
classId,
attendanceDate: dateStr,
session,
status: 'pending',
source: 'schedule',
});
entity.departmentId = cs.student?.departmentId ?? cls.departmentId ?? undefined;
entities.push(entity);
existingKeys.add(key);
}
}
}
const saved = await this.attendanceRepo.save(entities);
return { count: saved.length, records: saved };
}
// ── Generate attendance records from schedules (optional date range, defaults to current week) ──
async generateFromSchedules(dto: GenerateFromSchedulesDto): Promise<{ count: number; records: AttendanceRecord[] }> {
const { classId, startDate, endDate } = dto;
// Default to current week (MondaySunday)
const now = new Date();
const dayOfWeek = now.getDay();
const mondayOffset = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
const monday = new Date(now);
monday.setDate(now.getDate() + mondayOffset);
monday.setHours(0, 0, 0, 0);
const sunday = new Date(monday);
sunday.setDate(monday.getDate() + 6);
sunday.setHours(23, 59, 59, 999);
const dateFrom = startDate ?? monday.toISOString().slice(0, 10);
const dateTo = endDate ?? sunday.toISOString().slice(0, 10);
return this.generateAttendanceFromSchedules({
classId,
dateFrom,
dateTo,
});
}
private mapScheduleTimeToSession(startTime: string): string {
const hour = parseInt(startTime.slice(0, 2), 10);
if (hour < 8) return 'morning_reading';
if (hour < 12) return 'morning';
if (hour < 17) return 'afternoon';
if (hour < 20) return 'evening_study';
return 'night_check';
}
// ── Attendance summary ──
async getSummary(query: AttendanceSummaryQueryDto) {
const qb = this.attendanceRepo.createQueryBuilder('ar');

View File

@@ -151,3 +151,33 @@ export class AttendanceReportQueryDto {
@IsDateString()
dateTo?: string;
}
export class GenerateAttendanceFromSchedulesDto {
@IsInt()
@Type(() => Number)
@IsNotEmpty()
classId: number;
@IsDateString()
@IsNotEmpty()
dateFrom: string;
@IsDateString()
@IsNotEmpty()
dateTo: string;
}
export class GenerateFromSchedulesDto {
@IsInt()
@Type(() => Number)
@IsNotEmpty()
classId: number;
@IsOptional()
@IsDateString()
startDate?: string;
@IsOptional()
@IsDateString()
endDate?: string;
}

View File

@@ -47,12 +47,12 @@ export class CampusScope {
if (ids.length === 0) {
// Non-super-admin with no scoping → match nothing, never leak unfiltered data
if (!this.isSuperAdmin) {
return { ...where, departmentId: In([]) } as unknown as T;
return { ...where, departmentId: In([]) };
}
return where;
}
return { ...where, departmentId: In(ids) } as unknown as T;
return { ...where, departmentId: In(ids) };
}
/** Returns department IDs for QueryBuilder .andWhere() usage. null = no filtering needed. */

View File

@@ -123,7 +123,7 @@ export class DingTalkService {
name: dd.name,
source: 'dingtalk',
sourceId,
parentSourceId: (dd.parent_id ? String(dd.parent_id) : undefined) as any,
parentSourceId: (dd.parent_id ? String(dd.parent_id) : undefined),
type: 'department',
});
deptCount++;

View File

@@ -117,7 +117,7 @@ export class WeComService {
name: wd.name,
source: 'wecom',
sourceId,
parentSourceId: (wd.parentid ? String(wd.parentid) : undefined) as any,
parentSourceId: (wd.parentid ? String(wd.parentid) : undefined),
type: 'department',
});
deptCount++;

View File

@@ -69,6 +69,17 @@ const PRESET_PERMISSIONS: Array<{ code: string; name: string; group: string }> =
{ code: 'attendance:create', name: '新增考勤', group: 'attendance' },
{ code: 'attendance:edit', name: '编辑考勤', group: 'attendance' },
{ code: 'attendance:export', name: '导出考勤', group: 'attendance' },
{ code: 'attendance:generate', name: '按课表生成考勤', group: 'attendance' },
{ code: 'learning:create', name: '创建学习任务', group: 'learning' },
{ code: 'learning:edit', name: '编辑学习任务', group: 'learning' },
{ code: 'learning:delete', name: '删除学习任务', group: 'learning' },
{ code: 'exam:create', name: '创建考试', group: 'exam' },
{ code: 'exam:edit', name: '编辑考试', group: 'exam' },
{ code: 'exam:delete', name: '删除考试', group: 'exam' },
{ code: 'sync:trigger', name: '触发数据同步', group: 'sync' },
{ code: 'sync:read', name: '查看同步状态', group: 'sync' },
{ code: 'integration:trigger', name: '触发集成', group: 'integration' },
{ code: 'integration:read', name: '查看集成状态', group: 'integration' },
];
const PRESET_ROLES: Array<{
@@ -120,6 +131,27 @@ const PRESET_ROLES: Array<{
isSystem: true,
permissionGroups: ['classroom', 'rental', 'tenant'],
},
{
name: '财务',
code: 'finance',
description: '管理费用、账单与押金',
isSystem: true,
permissionGroups: ['expense', 'bill', 'deposit', 'dashboard'],
},
{
name: '宿管',
code: 'dorm_manager',
description: '管理宿舍入住与宿舍信息',
isSystem: true,
permissionGroups: ['student', 'room', 'occupancy', 'dashboard'],
},
{
name: '教务',
code: 'academic',
description: '管理班级、排课、考勤、学习与考试',
isSystem: true,
permissionGroups: ['class', 'schedule', 'attendance', 'classroom', 'learning', 'exam', 'dashboard'],
},
];
@Injectable()

View File

@@ -177,9 +177,9 @@ export class StudentsService {
// Group attendance by class
const attendanceByClass = new Map<number, AttendanceRecord[]>();
for (const r of attendanceRecords) {
const list = attendanceByClass.get(r.classId!) || [];
const list = attendanceByClass.get(r.classId) || [];
list.push(r);
attendanceByClass.set(r.classId!, list);
attendanceByClass.set(r.classId, list);
}
const comparison = enrollments.map((e) => {