fix permissions and teacher attendance workflows

This commit is contained in:
2026-07-10 20:40:52 +08:00
parent 247879f276
commit 8ed1682b90
95 changed files with 4745 additions and 1237 deletions

View File

@@ -1,8 +1,31 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import {
Injectable,
NotFoundException,
BadRequestException,
ForbiddenException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In, Like } from 'typeorm';
import { Class, ClassStudent, ClassTeacher, ClassSchedule, AttendanceRecord, Classroom, Student, StudentDingMapping } from '../entities';
import { CreateClassDto, UpdateClassDto, QueryClassDto, AddTeacherDto, QueryClassScheduleDto, QueryClassAttendanceSummaryDto, BatchImportStudentsDto } from './dto/class.dto';
import {
Class,
ClassStudent,
ClassTeacher,
ClassSchedule,
AttendanceRecord,
Classroom,
Student,
StudentDingMapping,
} from '../entities';
import { normalizeDateOnly } from '../database/date-normalization';
import {
CreateClassDto,
UpdateClassDto,
QueryClassDto,
AddTeacherDto,
QueryClassScheduleDto,
QueryClassAttendanceSummaryDto,
BatchImportStudentsDto,
} from './dto/class.dto';
interface RawStudentCount {
classId: string;
@@ -28,7 +51,19 @@ export class ClassesService {
private studentDingMappingRepo: Repository<StudentDingMapping>,
) {}
async findAll(query: QueryClassDto) {
async getAccessibleClassIds(userId: number, canManageAll = false): Promise<number[] | undefined> {
if (canManageAll) return undefined;
const assignments = await this.classTeacherRepo.find({ where: { userId } });
return [...new Set(assignments.map((assignment) => assignment.classId))];
}
async assertClassAccess(userId: number, classId: number, canManageAll = false): Promise<void> {
if (canManageAll) return;
const assignment = await this.classTeacherRepo.findOne({ where: { userId, classId } });
if (!assignment) throw new ForbiddenException('只能访问自己被分配的班级');
}
async findAll(query: QueryClassDto, accessibleClassIds?: number[]) {
let where: Record<string, unknown> = {};
if (query.status) where.status = query.status;
if (query.classType) where.classType = query.classType;
@@ -36,6 +71,11 @@ export class ClassesService {
// Default: hide archived, unless explicitly requested
where.isArchived = query.isArchived ?? false;
if (accessibleClassIds) {
if (accessibleClassIds.length === 0) return [];
where.id = In(accessibleClassIds);
}
const classes = await this.classRepo.find({
where,
order: { createdAt: 'DESC' as const },
@@ -96,14 +136,21 @@ export class ClassesService {
async create(dto: CreateClassDto) {
const { studentIds, teachers, users, ...classData } = dto;
const cls = this.classRepo.create(classData);
const cls = this.classRepo.create({
...classData,
startDate: normalizeDateOnly(classData.startDate) ?? undefined,
endDate: normalizeDateOnly(classData.endDate) ?? undefined,
});
const saved = await this.classRepo.save(cls);
// add students
if (studentIds?.length) {
const entries = studentIds.map((sid: number) =>
this.classStudentRepo.create({ classId: saved.id, studentId: sid, joinDate: new Date().toISOString().split('T')[0] }),
this.classStudentRepo.create({
classId: saved.id,
studentId: sid,
joinDate: new Date().toISOString().split('T')[0],
}),
);
await this.classStudentRepo.save(entries);
}
@@ -111,7 +158,12 @@ export class ClassesService {
// add teachers
if (teachers?.length) {
const entries = teachers.map((t) =>
this.classTeacherRepo.create({ classId: saved.id, userId: t.userId, roleType: t.roleType, subject: t.subject }),
this.classTeacherRepo.create({
classId: saved.id,
userId: t.userId,
roleType: t.roleType,
subject: t.subject,
}),
);
await this.classTeacherRepo.save(entries);
@@ -127,37 +179,41 @@ export class ClassesService {
return this.findOne(saved.id);
}
async batchImportStudents(classId: number, users: Array<{
dingUserId: string; name: string; mobile?: string;
}>): Promise<{ imported: number; skipped: number }> {
async batchImportStudents(
classId: number,
users: Array<{
dingUserId: string;
name: string;
mobile?: string;
}>,
): Promise<{ imported: number; skipped: number }> {
const classEntity = await this.classRepo.findOne({ where: { id: classId } });
if (!classEntity) throw new NotFoundException('班级不存在');
if (users.length === 0) return { imported: 0, skipped: 0 };
const dingUserIds = users.map(u => u.dingUserId);
const dingUserIds = users.map((u) => u.dingUserId);
// 1. Fetch all existing ding mappings in one query
const existingMappings = await this.studentDingMappingRepo.find({
where: { dingUserId: In(dingUserIds) },
});
const dingToStudentId = new Map(existingMappings.map(m => [m.dingUserId, m.studentId]));
const dingToStudentId = new Map(existingMappings.map((m) => [m.dingUserId, m.studentId]));
// 2. Batch create students for new dingUserIds
const newUsers = users.filter(u => !dingToStudentId.has(u.dingUserId));
const newUsers = users.filter((u) => !dingToStudentId.has(u.dingUserId));
if (newUsers.length > 0) {
const newStudents = newUsers.map(u =>
const newStudents = newUsers.map((u) =>
this.studentRepo.create({
name: u.name,
phone: u.mobile || `dt_${u.dingUserId}`,
status: 'active',
})
}),
);
const savedStudents = await this.studentRepo.save(newStudents);
const newMappings = savedStudents.map((s, i) =>
this.studentDingMappingRepo.create({ dingUserId: newUsers[i].dingUserId, studentId: s.id })
this.studentDingMappingRepo.create({ dingUserId: newUsers[i].dingUserId, studentId: s.id }),
);
await this.studentDingMappingRepo.save(newMappings);
@@ -180,12 +236,14 @@ export class ClassesService {
// 4. Batch insert new class-student records
const newClassStudents = allStudentIds
.filter(sid => !alreadyInClass.has(sid))
.map(studentId =>
.filter((sid) => !alreadyInClass.has(sid))
.map((studentId) =>
this.classStudentRepo.create({
classId, studentId, status: 'active',
classId,
studentId,
status: 'active',
joinDate: new Date().toISOString().slice(0, 10),
})
}),
);
if (newClassStudents.length > 0) {
@@ -197,7 +255,15 @@ export class ClassesService {
async update(id: number, dto: UpdateClassDto) {
const cls = await this.classRepo.findOne({ where: { id } });
if (!cls) throw new NotFoundException('班级不存在');
await this.classRepo.update(id, dto);
await this.classRepo.update(id, {
...dto,
...(dto.startDate !== undefined
? { startDate: normalizeDateOnly(dto.startDate) ?? undefined }
: {}),
...(dto.endDate !== undefined
? { endDate: normalizeDateOnly(dto.endDate) ?? undefined }
: {}),
});
return this.findOne(id);
}
@@ -226,7 +292,6 @@ export class ClassesService {
return { success: true };
}
async getStudents(classId: number) {
return this.classStudentRepo.find({
where: { classId },
@@ -243,7 +308,11 @@ export class ClassesService {
const newIds = studentIds.filter((id) => !existingIds.has(id));
const entries = newIds.map((sid) =>
this.classStudentRepo.create({ classId, studentId: sid, joinDate: new Date().toISOString().split('T')[0] }),
this.classStudentRepo.create({
classId,
studentId: sid,
joinDate: new Date().toISOString().split('T')[0],
}),
);
if (entries.length) await this.classStudentRepo.save(entries);
@@ -268,7 +337,12 @@ export class ClassesService {
});
if (existing) throw new BadRequestException('该教师已分配此角色');
const entry = this.classTeacherRepo.create({ classId, userId: dto.userId, roleType: dto.roleType, subject: dto.subject });
const entry = this.classTeacherRepo.create({
classId,
userId: dto.userId,
roleType: dto.roleType,
subject: dto.subject,
});
await this.classTeacherRepo.save(entry);
await this.syncClassTeacherIds(classId);
@@ -281,18 +355,22 @@ export class ClassesService {
return { success: true };
}
async removeTeacherAssignment(classId: number, assignmentId: number) {
await this.classTeacherRepo.delete({ id: assignmentId, classId });
await this.syncClassTeacherIds(classId);
return { success: true };
}
private async syncClassTeacherIds(classId: number) {
const teachers = await this.classTeacherRepo.find({ where: { classId } });
const updates: Record<string, number> = {};
const head = teachers.find((t) => t.roleType === 'head_teacher');
const life = teachers.find((t) => t.roleType === 'life_teacher');
const academic = teachers.find((t) => t.roleType === 'academic_teacher');
if (head) updates.headTeacherId = head.userId;
if (life) updates.lifeTeacherId = life.userId;
if (academic) updates.academicTeacherId = academic.userId;
if (Object.keys(updates).length > 0) {
await this.classRepo.update(classId, updates);
}
await this.classRepo.update(classId, {
headTeacherId: head?.userId ?? null,
lifeTeacherId: life?.userId ?? null,
academicTeacherId: academic?.userId ?? null,
} as Partial<Class>);
}
async getSchedule(classId: number, query: QueryClassScheduleDto) {