成绩+点名
This commit is contained in:
@@ -0,0 +1,359 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Security.Claims;
|
||||
using ClosedXML.Excel;
|
||||
using Jiaowu.Api.Domain.Academic;
|
||||
using Jiaowu.Api.Domain.Identity;
|
||||
using Jiaowu.Api.Infrastructure.Auth;
|
||||
using Jiaowu.Api.Infrastructure.Excel;
|
||||
using Jiaowu.Api.Infrastructure.Persistence;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Jiaowu.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Authorize(Roles = AttendanceRoles)]
|
||||
[Route("api/attendance")]
|
||||
public sealed class AttendanceController(
|
||||
AppDbContext db,
|
||||
ICurrentUserDataScope currentUserDataScope) : ControllerBase
|
||||
{
|
||||
private const string AttendanceRoles =
|
||||
SystemRoles.SuperAdmin + "," +
|
||||
SystemRoles.AcademicAdmin + "," +
|
||||
SystemRoles.CollegeAdmin + "," +
|
||||
SystemRoles.Teacher;
|
||||
|
||||
[HttpGet("my-tasks")]
|
||||
public async Task<ActionResult> GetMyTasks(
|
||||
Guid? academicTermId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var tasks = AccessibleTasks().AsNoTracking()
|
||||
.Where(x => x.Status == TeachingTaskStatus.Published);
|
||||
if (academicTermId.HasValue)
|
||||
tasks = tasks.Where(x => x.AcademicTermId == academicTermId);
|
||||
var result = await tasks
|
||||
.OrderBy(x => x.Course!.Code)
|
||||
.Select(x => new
|
||||
{
|
||||
x.Id,
|
||||
x.TaskNumber,
|
||||
x.Name,
|
||||
x.AcademicTermId,
|
||||
TermName = x.AcademicTerm!.Name,
|
||||
CourseCode = x.Course!.Code,
|
||||
CourseName = x.Course!.Name,
|
||||
StudentCount = db.CourseEnrollments.Count(enrollment =>
|
||||
enrollment.Status == CourseEnrollmentStatus.Enrolled &&
|
||||
enrollment.CourseSelectionOffering!.TeachingTaskId == x.Id),
|
||||
SheetCount = db.AttendanceSheets.Count(sheet =>
|
||||
sheet.TeachingTaskId == x.Id)
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet("sheets")]
|
||||
public async Task<ActionResult> GetSheets(
|
||||
Guid teachingTaskId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var task = await AccessibleTasks().AsNoTracking()
|
||||
.FirstOrDefaultAsync(x => x.Id == teachingTaskId, cancellationToken);
|
||||
if (task is null) return NotFound();
|
||||
|
||||
var sheets = await db.AttendanceSheets.AsNoTracking()
|
||||
.Where(x => x.TeachingTaskId == teachingTaskId)
|
||||
.OrderByDescending(x => x.AttendanceDate)
|
||||
.Select(x => new
|
||||
{
|
||||
x.Id,
|
||||
x.Name,
|
||||
x.AttendanceDate,
|
||||
x.Status,
|
||||
x.Notes,
|
||||
x.SubmittedAt,
|
||||
PresentCount = x.Records.Count(r => r.Status == AttendanceStatus.Present),
|
||||
AbsentCount = x.Records.Count(r => r.Status == AttendanceStatus.Absent),
|
||||
LateCount = x.Records.Count(r => r.Status == AttendanceStatus.Late),
|
||||
LeaveCount = x.Records.Count(r => r.Status == AttendanceStatus.Leave),
|
||||
ExcusedCount = x.Records.Count(r => r.Status == AttendanceStatus.Excused),
|
||||
TotalCount = x.Records.Count
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
return Ok(sheets);
|
||||
}
|
||||
|
||||
[HttpPost("sheets")]
|
||||
public async Task<ActionResult> CreateSheet(
|
||||
AttendanceSheetRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var task = await AccessibleTasks().AsNoTracking()
|
||||
.FirstOrDefaultAsync(x => x.Id == request.TeachingTaskId, cancellationToken);
|
||||
if (task is null) return NotFound();
|
||||
|
||||
var studentIds = await db.CourseEnrollments.AsNoTracking()
|
||||
.Where(x =>
|
||||
x.Status == CourseEnrollmentStatus.Enrolled &&
|
||||
x.CourseSelectionOffering!.TeachingTaskId == request.TeachingTaskId)
|
||||
.Select(x => x.StudentId)
|
||||
.Distinct()
|
||||
.ToListAsync(cancellationToken);
|
||||
if (studentIds.Count == 0)
|
||||
return ConflictProblem("该教学班没有有效选课学生。");
|
||||
|
||||
var sheet = new AttendanceSheet
|
||||
{
|
||||
TeachingTaskId = request.TeachingTaskId,
|
||||
Name = request.Name.Trim(),
|
||||
AttendanceDate = request.AttendanceDate,
|
||||
Notes = Normalize(request.Notes),
|
||||
Records = studentIds.Select(studentId => new AttendanceRecord
|
||||
{
|
||||
StudentId = studentId
|
||||
}).ToList()
|
||||
};
|
||||
db.AttendanceSheets.Add(sheet);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return Created(string.Empty, new { sheet.Id });
|
||||
}
|
||||
|
||||
[HttpGet("sheets/{id:guid}")]
|
||||
public async Task<ActionResult> GetSheet(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var sheet = await db.AttendanceSheets.AsNoTracking()
|
||||
.Where(x => x.Id == id)
|
||||
.Select(x => new
|
||||
{
|
||||
x.Id,
|
||||
x.TeachingTaskId,
|
||||
x.Name,
|
||||
x.AttendanceDate,
|
||||
x.Status,
|
||||
x.Notes,
|
||||
x.SubmittedAt,
|
||||
TaskNumber = x.TeachingTask!.TaskNumber,
|
||||
TaskName = x.TeachingTask.Name,
|
||||
CourseCode = x.TeachingTask.Course!.Code,
|
||||
CourseName = x.TeachingTask.Course.Name,
|
||||
Records = x.Records
|
||||
.OrderBy(r => r.Student!.StudentNumber)
|
||||
.Select(r => new
|
||||
{
|
||||
r.StudentId,
|
||||
r.Student!.StudentNumber,
|
||||
r.Student.Name,
|
||||
ClassName = r.Student.AdministrativeClass!.Name,
|
||||
r.Status,
|
||||
r.Notes
|
||||
})
|
||||
})
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
if (sheet is null) return NotFound();
|
||||
|
||||
var canEdit = sheet.Status == AttendanceSheetStatus.Draft;
|
||||
return Ok(new { Sheet = sheet, CanEdit = canEdit });
|
||||
}
|
||||
|
||||
[HttpPut("sheets/{id:guid}/records")]
|
||||
public async Task<ActionResult> UpdateRecords(
|
||||
Guid id,
|
||||
AttendanceRecordsRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var sheet = await db.AttendanceSheets
|
||||
.Include(x => x.Records)
|
||||
.Include(x => x.TeachingTask)
|
||||
.ThenInclude(x => x!.Teachers)
|
||||
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
|
||||
if (sheet is null) return NotFound();
|
||||
if (!CanManageSheet(sheet)) return Forbid();
|
||||
if (sheet.Status != AttendanceSheetStatus.Draft)
|
||||
return ConflictProblem("考勤表已提交,不能修改。");
|
||||
|
||||
var recordMap = sheet.Records.ToDictionary(r => r.StudentId);
|
||||
foreach (var item in request.Records)
|
||||
{
|
||||
if (recordMap.TryGetValue(item.StudentId, out var record))
|
||||
{
|
||||
record.Status = item.Status;
|
||||
record.Notes = Normalize(item.Notes);
|
||||
}
|
||||
}
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpPost("sheets/{id:guid}/import")]
|
||||
public async Task<ActionResult> Import(
|
||||
Guid id,
|
||||
IFormFile file,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var sheet = await db.AttendanceSheets
|
||||
.Include(x => x.Records)
|
||||
.ThenInclude(x => x.Student)
|
||||
.Include(x => x.TeachingTask)
|
||||
.ThenInclude(x => x!.Teachers)
|
||||
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
|
||||
if (sheet is null) return NotFound();
|
||||
if (!CanManageSheet(sheet)) return Forbid();
|
||||
if (sheet.Status != AttendanceSheetStatus.Draft)
|
||||
return ConflictProblem("考勤表已提交,不能导入。");
|
||||
|
||||
var rows = await ExcelWorkbookHelper.ReadAsync(
|
||||
file,
|
||||
new HashSet<string> { "学号", "考勤状态" },
|
||||
cancellationToken);
|
||||
var studentNumberMap = sheet.Records
|
||||
.ToDictionary(r => r.Student!.StudentNumber, r => r);
|
||||
var statusMap = new Dictionary<string, AttendanceStatus>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["出勤"] = AttendanceStatus.Present,
|
||||
["缺勤"] = AttendanceStatus.Absent,
|
||||
["迟到"] = AttendanceStatus.Late,
|
||||
["请假"] = AttendanceStatus.Leave,
|
||||
["免修"] = AttendanceStatus.Excused
|
||||
};
|
||||
|
||||
var updated = 0;
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var studentNumber = row["学号"];
|
||||
var statusText = row["考勤状态"];
|
||||
if (string.IsNullOrEmpty(studentNumber)) continue;
|
||||
if (!studentNumberMap.TryGetValue(studentNumber, out var record)) continue;
|
||||
if (statusMap.TryGetValue(statusText, out var status))
|
||||
{
|
||||
record.Status = status;
|
||||
updated++;
|
||||
}
|
||||
}
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return Ok(new { Updated = updated });
|
||||
}
|
||||
|
||||
[HttpGet("sheets/{id:guid}/export.xlsx")]
|
||||
public async Task<ActionResult> Export(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var sheetData = await db.AttendanceSheets.AsNoTracking()
|
||||
.Where(x => x.Id == id)
|
||||
.Select(x => new
|
||||
{
|
||||
x.Name,
|
||||
x.AttendanceDate,
|
||||
TaskNumber = x.TeachingTask!.TaskNumber,
|
||||
CourseName = x.TeachingTask.Course!.Name,
|
||||
Records = x.Records
|
||||
.OrderBy(r => r.Student!.StudentNumber)
|
||||
.Select(r => new
|
||||
{
|
||||
r.Student!.StudentNumber,
|
||||
r.Student.Name,
|
||||
ClassName = r.Student.AdministrativeClass!.Name,
|
||||
r.Status,
|
||||
r.Notes
|
||||
})
|
||||
.ToList()
|
||||
})
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
if (sheetData is null) return NotFound();
|
||||
|
||||
var statusLabels = new Dictionary<AttendanceStatus, string>
|
||||
{
|
||||
[AttendanceStatus.Present] = "出勤",
|
||||
[AttendanceStatus.Absent] = "缺勤",
|
||||
[AttendanceStatus.Late] = "迟到",
|
||||
[AttendanceStatus.Leave] = "请假",
|
||||
[AttendanceStatus.Excused] = "免修"
|
||||
};
|
||||
var bytes = ExcelWorkbookHelper.Create(
|
||||
"考勤表",
|
||||
["学号", "姓名", "班级", "考勤状态", "备注"],
|
||||
sheetData.Records.Select(r => new List<object?>
|
||||
{
|
||||
r.StudentNumber, r.Name, r.ClassName,
|
||||
statusLabels.GetValueOrDefault(r.Status, "出勤"), r.Notes
|
||||
}).ToList<IReadOnlyList<object?>>());
|
||||
return File(bytes, ExcelWorkbookHelper.ContentType,
|
||||
$"考勤表-{sheetData.TaskNumber}-{sheetData.AttendanceDate:yyyyMMdd}.xlsx");
|
||||
}
|
||||
|
||||
[HttpPost("sheets/{id:guid}/submit")]
|
||||
public async Task<ActionResult> Submit(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var sheet = await db.AttendanceSheets
|
||||
.Include(x => x.TeachingTask)
|
||||
.ThenInclude(x => x!.Teachers)
|
||||
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
|
||||
if (sheet is null) return NotFound();
|
||||
if (!CanManageSheet(sheet)) return Forbid();
|
||||
if (sheet.Status != AttendanceSheetStatus.Draft)
|
||||
return ConflictProblem("考勤表已提交。");
|
||||
sheet.Status = AttendanceSheetStatus.Submitted;
|
||||
sheet.SubmittedAt = DateTime.UtcNow;
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpDelete("sheets/{id:guid}")]
|
||||
public async Task<ActionResult> Delete(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var sheet = await db.AttendanceSheets
|
||||
.Include(x => x.TeachingTask)
|
||||
.ThenInclude(x => x!.Teachers)
|
||||
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
|
||||
if (sheet is null) return NotFound();
|
||||
if (!CanManageSheet(sheet)) return Forbid();
|
||||
db.AttendanceSheets.Remove(sheet);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
private IQueryable<TeachingTask> AccessibleTasks()
|
||||
{
|
||||
var source = db.TeachingTasks.AsQueryable();
|
||||
var scope = currentUserDataScope.Current;
|
||||
if (scope.Scope == DataScope.All) return source;
|
||||
if (scope.Scope == DataScope.College)
|
||||
return source.Where(x => x.Course!.CollegeId == scope.RestrictedCollegeId);
|
||||
if (scope.IsInRole(SystemRoles.Teacher))
|
||||
return source.Where(x =>
|
||||
x.Teachers.Any(item => item.Teacher!.UserId == scope.UserId));
|
||||
return source.Where(_ => false);
|
||||
}
|
||||
|
||||
private bool CanManageSheet(AttendanceSheet sheet) =>
|
||||
currentUserDataScope.Current.IsInRole(SystemRoles.SuperAdmin) ||
|
||||
currentUserDataScope.Current.IsInRole(SystemRoles.AcademicAdmin) ||
|
||||
sheet.TeachingTask!.Teachers.Any(x =>
|
||||
x.Teacher?.UserId == currentUserDataScope.Current.UserId);
|
||||
|
||||
private static string? Normalize(string? value) =>
|
||||
string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
|
||||
private ActionResult ConflictProblem(string detail) =>
|
||||
Conflict(new ProblemDetails
|
||||
{
|
||||
Title = "无法完成考勤操作",
|
||||
Detail = detail,
|
||||
Status = StatusCodes.Status409Conflict
|
||||
});
|
||||
}
|
||||
|
||||
public sealed record AttendanceSheetRequest(
|
||||
Guid TeachingTaskId,
|
||||
[MaxLength(120)] string Name,
|
||||
DateTime AttendanceDate,
|
||||
[MaxLength(500)] string? Notes);
|
||||
|
||||
public sealed record AttendanceRecordsRequest(
|
||||
IReadOnlyCollection<AttendanceRecordRequest> Records);
|
||||
|
||||
public sealed record AttendanceRecordRequest(
|
||||
Guid StudentId,
|
||||
AttendanceStatus Status,
|
||||
[MaxLength(300)] string? Notes);
|
||||
@@ -4,6 +4,7 @@ using Jiaowu.Api.Domain.Academic;
|
||||
using Jiaowu.Api.Domain.Identity;
|
||||
using Jiaowu.Api.Infrastructure.Auth;
|
||||
using Jiaowu.Api.Infrastructure.CourseSelection;
|
||||
using Jiaowu.Api.Infrastructure.Excel;
|
||||
using Jiaowu.Api.Infrastructure.Persistence;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
@@ -868,6 +869,100 @@ public sealed class CourseSelectionsController(
|
||||
return await SaveAsync(id, false, cancellationToken);
|
||||
}
|
||||
|
||||
[HttpGet("my-offerings")]
|
||||
[Authorize(Roles = SystemRoles.Teacher)]
|
||||
public async Task<ActionResult> GetMyOfferings(
|
||||
Guid? academicTermId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var userId = currentUserDataScope.Current.UserId;
|
||||
var offeringsQuery = db.CourseSelectionOfferings.AsNoTracking()
|
||||
.Where(x =>
|
||||
x.TeachingTask!.Teachers.Any(t =>
|
||||
t.Teacher!.UserId == userId) &&
|
||||
x.CourseSelectionRound!.Status != CourseSelectionRoundStatus.Draft);
|
||||
if (academicTermId.HasValue)
|
||||
offeringsQuery = offeringsQuery.Where(x =>
|
||||
x.CourseSelectionRound!.AcademicTermId == academicTermId);
|
||||
var offerings = await offeringsQuery
|
||||
.OrderByDescending(x => x.CourseSelectionRound!.AcademicTerm!.StartDate)
|
||||
.ThenBy(x => x.TeachingTask!.Course!.Code)
|
||||
.Select(x => new
|
||||
{
|
||||
x.Id,
|
||||
x.TeachingTaskId,
|
||||
x.TeachingTask!.TaskNumber,
|
||||
TaskName = x.TeachingTask.Name,
|
||||
x.TeachingTask.AcademicTermId,
|
||||
TermName = x.TeachingTask.AcademicTerm!.Name,
|
||||
CourseCode = x.TeachingTask.Course!.Code,
|
||||
CourseName = x.TeachingTask.Course.Name,
|
||||
RoundName = x.CourseSelectionRound!.Name,
|
||||
x.Capacity,
|
||||
EnrolledCount = x.Enrollments.Count(e =>
|
||||
e.Status == CourseEnrollmentStatus.Enrolled),
|
||||
RoundStatus = x.CourseSelectionRound.Status
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
return Ok(offerings);
|
||||
}
|
||||
|
||||
[HttpGet("offerings/{id:guid}/roster/export.xlsx")]
|
||||
[Authorize(Roles = RosterReaders)]
|
||||
public async Task<ActionResult> ExportRoster(
|
||||
Guid id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var offering = await db.CourseSelectionOfferings.AsNoTracking()
|
||||
.Where(x => x.Id == id)
|
||||
.Select(x => new
|
||||
{
|
||||
x.Id,
|
||||
x.TeachingTask!.TaskNumber,
|
||||
CourseCode = x.TeachingTask.Course!.Code,
|
||||
CourseName = x.TeachingTask.Course.Name,
|
||||
RoundName = x.CourseSelectionRound!.Name,
|
||||
CollegeId = x.TeachingTask.Course.CollegeId,
|
||||
TeacherUserIds = x.TeachingTask.Teachers
|
||||
.Select(item => item.Teacher!.UserId)
|
||||
})
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
if (offering is null) return NotFound();
|
||||
|
||||
var scope = currentUserDataScope.Current;
|
||||
var isAssignedTeacher =
|
||||
scope.IsInRole(SystemRoles.Teacher) &&
|
||||
offering.TeacherUserIds.Contains(scope.UserId);
|
||||
if (!isAssignedTeacher && !scope.CanAccessCollege(offering.CollegeId))
|
||||
return Forbid();
|
||||
|
||||
var students = await db.CourseEnrollments.AsNoTracking()
|
||||
.Where(x =>
|
||||
x.CourseSelectionOfferingId == id &&
|
||||
x.Status == CourseEnrollmentStatus.Enrolled)
|
||||
.OrderBy(x => x.Student!.StudentNumber)
|
||||
.Select(x => new
|
||||
{
|
||||
x.Student!.StudentNumber,
|
||||
x.Student.Name,
|
||||
ClassName = x.Student.AdministrativeClass!.Name,
|
||||
MajorName = x.Student.AdministrativeClass.Major!.Name,
|
||||
x.EnrolledAt
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var bytes = ExcelWorkbookHelper.Create(
|
||||
"选课名单",
|
||||
["学号", "姓名", "班级", "专业", "选课时间"],
|
||||
students.Select(s => new List<object?>
|
||||
{
|
||||
s.StudentNumber, s.Name, s.ClassName, s.MajorName,
|
||||
s.EnrolledAt.ToString("yyyy-MM-dd HH:mm")
|
||||
}).ToList<IReadOnlyList<object?>>());
|
||||
return File(bytes, ExcelWorkbookHelper.ContentType,
|
||||
$"选课名单-{offering.TaskNumber}.xlsx");
|
||||
}
|
||||
|
||||
private IQueryable<CourseSelectionOffering> ScopedOfferings()
|
||||
{
|
||||
var source = db.CourseSelectionOfferings.AsQueryable();
|
||||
|
||||
@@ -71,8 +71,13 @@ public sealed class GradesController(
|
||||
sheet.Id,
|
||||
sheet.Status,
|
||||
sheet.RegularWeight,
|
||||
sheet.MidtermWeight,
|
||||
sheet.FinalWeight,
|
||||
Items = sheet.Items.OrderBy(item => item.SortOrder).Select(item => new
|
||||
{
|
||||
item.Id,
|
||||
item.Name,
|
||||
item.Weight
|
||||
}),
|
||||
StudentCount = sheet.Records.Count,
|
||||
CompletedCount = sheet.Records.Count(record =>
|
||||
record.TotalScore != null ||
|
||||
@@ -99,11 +104,20 @@ public sealed class GradesController(
|
||||
GradeSheetRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var items = request.Items?
|
||||
.Select((item, index) => new GradeItem
|
||||
{
|
||||
Name = item.Name.Trim(),
|
||||
Weight = item.Weight,
|
||||
SortOrder = index
|
||||
})
|
||||
.ToList() ?? [];
|
||||
|
||||
if (!GradeCalculator.AreWeightsValid(
|
||||
request.RegularWeight,
|
||||
request.MidtermWeight,
|
||||
request.FinalWeight))
|
||||
return ValidationProblem("平时、期中和期末成绩比例必须合计 100%。");
|
||||
request.FinalWeight,
|
||||
items))
|
||||
return ValidationProblem("平时、期末与所有分项的比例必须合计 100%。");
|
||||
|
||||
var task = await AccessibleTasks()
|
||||
.Include(x => x.Teachers)
|
||||
@@ -131,11 +145,15 @@ public sealed class GradesController(
|
||||
{
|
||||
TeachingTaskId = task.Id,
|
||||
RegularWeight = request.RegularWeight,
|
||||
MidtermWeight = request.MidtermWeight,
|
||||
FinalWeight = request.FinalWeight,
|
||||
Items = items,
|
||||
Records = studentIds.Select(studentId => new GradeRecord
|
||||
{
|
||||
StudentId = studentId
|
||||
StudentId = studentId,
|
||||
ItemScores = items.Select(item => new GradeItemScore
|
||||
{
|
||||
GradeItemId = item.Id
|
||||
}).ToList()
|
||||
}).ToList()
|
||||
};
|
||||
db.GradeSheets.Add(sheet);
|
||||
@@ -166,8 +184,13 @@ public sealed class GradesController(
|
||||
ClassNames = x.TeachingTask.Classes
|
||||
.Select(item => item.AdministrativeClass!.Name),
|
||||
x.RegularWeight,
|
||||
x.MidtermWeight,
|
||||
x.FinalWeight,
|
||||
Items = x.Items.OrderBy(item => item.SortOrder).Select(item => new
|
||||
{
|
||||
item.Id,
|
||||
item.Name,
|
||||
item.Weight
|
||||
}),
|
||||
x.Status,
|
||||
x.ReviewComment,
|
||||
x.SubmittedAt,
|
||||
@@ -183,8 +206,15 @@ public sealed class GradesController(
|
||||
record.Student.Name,
|
||||
ClassName = record.Student.AdministrativeClass!.Name,
|
||||
record.RegularScore,
|
||||
record.MidtermScore,
|
||||
record.FinalScore,
|
||||
ItemScores = record.ItemScores
|
||||
.OrderBy(itemScore => itemScore.GradeItem!.SortOrder)
|
||||
.Select(itemScore => new
|
||||
{
|
||||
itemScore.GradeItemId,
|
||||
itemScore.GradeItem!.Name,
|
||||
itemScore.Score
|
||||
}),
|
||||
record.TotalScore,
|
||||
record.GradePoint,
|
||||
record.ExamStatus,
|
||||
@@ -218,20 +248,58 @@ public sealed class GradesController(
|
||||
GradeWeightsRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var items = request.Items?
|
||||
.Select((item, index) => new GradeItem
|
||||
{
|
||||
Name = item.Name.Trim(),
|
||||
Weight = item.Weight,
|
||||
SortOrder = index
|
||||
})
|
||||
.ToList() ?? [];
|
||||
|
||||
if (!GradeCalculator.AreWeightsValid(
|
||||
request.RegularWeight,
|
||||
request.MidtermWeight,
|
||||
request.FinalWeight))
|
||||
return ValidationProblem("平时、期中和期末成绩比例必须合计 100%。");
|
||||
var sheet = await EditableSheetAsync(id, cancellationToken);
|
||||
request.FinalWeight,
|
||||
items))
|
||||
return ValidationProblem("平时、期末与所有分项的比例必须合计 100%。");
|
||||
|
||||
var sheet = await AccessibleSheets()
|
||||
.Include(x => x.Items)
|
||||
.Include(x => x.Records)
|
||||
.ThenInclude(x => x.ItemScores)
|
||||
.Include(x => x.TeachingTask)
|
||||
.ThenInclude(x => x!.Teachers)
|
||||
.ThenInclude(x => x.Teacher)
|
||||
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
|
||||
if (sheet is null) return NotFound();
|
||||
if (!CanEditScores(sheet.TeachingTask!)) return Forbid();
|
||||
if (sheet.Status is not (GradeSheetStatus.Draft or GradeSheetStatus.Returned))
|
||||
return ConflictProblem("当前状态不能修改成绩构成。");
|
||||
|
||||
sheet.RegularWeight = request.RegularWeight;
|
||||
sheet.MidtermWeight = request.MidtermWeight;
|
||||
sheet.FinalWeight = request.FinalWeight;
|
||||
foreach (var record in sheet.Records) Recalculate(sheet, record);
|
||||
|
||||
db.GradeItems.RemoveRange(sheet.Items);
|
||||
var itemIdsToRemove = sheet.Items.Select(item => item.Id).ToHashSet();
|
||||
foreach (var record in sheet.Records)
|
||||
{
|
||||
var toRemove = record.ItemScores
|
||||
.Where(itemScore => itemIdsToRemove.Contains(itemScore.GradeItemId))
|
||||
.ToList();
|
||||
foreach (var removed in toRemove)
|
||||
record.ItemScores.Remove(removed);
|
||||
}
|
||||
|
||||
sheet.Items = items;
|
||||
foreach (var record in sheet.Records)
|
||||
{
|
||||
foreach (var item in items)
|
||||
{
|
||||
record.ItemScores.Add(new GradeItemScore { GradeItemId = item.Id });
|
||||
}
|
||||
Recalculate(sheet, record);
|
||||
}
|
||||
|
||||
return await SaveAsync(id, false, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -242,28 +310,49 @@ public sealed class GradesController(
|
||||
GradeRecordsRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var sheet = await EditableSheetAsync(id, cancellationToken);
|
||||
var sheet = await AccessibleSheets()
|
||||
.Include(x => x.Items)
|
||||
.Include(x => x.Records)
|
||||
.ThenInclude(x => x.ItemScores)
|
||||
.Include(x => x.TeachingTask)
|
||||
.ThenInclude(x => x!.Teachers)
|
||||
.ThenInclude(x => x.Teacher)
|
||||
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
|
||||
if (sheet is null) return NotFound();
|
||||
if (!CanEditScores(sheet.TeachingTask!)) return Forbid();
|
||||
if (sheet.Status is not (GradeSheetStatus.Draft or GradeSheetStatus.Returned))
|
||||
return ConflictProblem("成绩单提交后不能继续修改。");
|
||||
|
||||
var records = sheet.Records.ToDictionary(x => x.Id);
|
||||
if (request.Records.Select(x => x.Id).Distinct().Count() != request.Records.Count ||
|
||||
request.Records.Any(x => !records.ContainsKey(x.Id)))
|
||||
return ValidationProblem("包含无效或重复的成绩记录。");
|
||||
|
||||
var itemIds = sheet.Items.Select(item => item.Id).ToHashSet();
|
||||
foreach (var item in request.Records)
|
||||
{
|
||||
if (!ValidScore(item.RegularScore) ||
|
||||
!ValidScore(item.MidtermScore) ||
|
||||
!ValidScore(item.FinalScore))
|
||||
return ValidationProblem("成绩必须在 0—100 分之间。");
|
||||
|
||||
var record = records[item.Id];
|
||||
record.RegularScore = item.RegularScore;
|
||||
record.MidtermScore = item.MidtermScore;
|
||||
record.FinalScore = item.FinalScore;
|
||||
record.ExamStatus = item.ExamStatus;
|
||||
record.Notes = Normalize(item.Notes);
|
||||
|
||||
if (item.ItemScores is not null)
|
||||
{
|
||||
var scoreMap = record.ItemScores.ToDictionary(s => s.GradeItemId);
|
||||
foreach (var scoreEntry in item.ItemScores)
|
||||
{
|
||||
if (!ValidScore(scoreEntry.Score))
|
||||
return ValidationProblem("分项成绩必须在 0—100 分之间。");
|
||||
if (scoreMap.TryGetValue(scoreEntry.GradeItemId, out var existing))
|
||||
existing.Score = scoreEntry.Score;
|
||||
}
|
||||
}
|
||||
|
||||
Recalculate(sheet, record);
|
||||
}
|
||||
return await SaveAsync(id, false, cancellationToken);
|
||||
@@ -273,7 +362,14 @@ public sealed class GradesController(
|
||||
[Authorize(Roles = SheetUsers)]
|
||||
public async Task<ActionResult> Submit(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var sheet = await EditableSheetAsync(id, cancellationToken);
|
||||
var sheet = await AccessibleSheets()
|
||||
.Include(x => x.Items)
|
||||
.Include(x => x.Records)
|
||||
.ThenInclude(x => x.ItemScores)
|
||||
.Include(x => x.TeachingTask)
|
||||
.ThenInclude(x => x!.Teachers)
|
||||
.ThenInclude(x => x.Teacher)
|
||||
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
|
||||
if (sheet is null) return NotFound();
|
||||
if (!CanEditScores(sheet.TeachingTask!)) return Forbid();
|
||||
if (sheet.Status is not (GradeSheetStatus.Draft or GradeSheetStatus.Returned))
|
||||
@@ -412,16 +508,6 @@ public sealed class GradesController(
|
||||
db.GradeSheets.Where(x => AccessibleTasks().Any(task =>
|
||||
task.Id == x.TeachingTaskId));
|
||||
|
||||
private async Task<GradeSheet?> EditableSheetAsync(
|
||||
Guid id,
|
||||
CancellationToken cancellationToken) =>
|
||||
await AccessibleSheets()
|
||||
.Include(x => x.Records)
|
||||
.Include(x => x.TeachingTask)
|
||||
.ThenInclude(x => x!.Teachers)
|
||||
.ThenInclude(x => x.Teacher)
|
||||
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
|
||||
|
||||
private bool CanInitialize(TeachingTask task) =>
|
||||
currentUserDataScope.Current.IsInRole(SystemRoles.SuperAdmin) ||
|
||||
currentUserDataScope.Current.IsInRole(SystemRoles.AcademicAdmin) ||
|
||||
@@ -449,11 +535,11 @@ public sealed class GradesController(
|
||||
{
|
||||
record.TotalScore = GradeCalculator.CalculateTotal(
|
||||
record.RegularScore,
|
||||
record.MidtermScore,
|
||||
record.FinalScore,
|
||||
record.ItemScores.ToList(),
|
||||
sheet.RegularWeight,
|
||||
sheet.MidtermWeight,
|
||||
sheet.FinalWeight,
|
||||
sheet.Items.ToList(),
|
||||
record.ExamStatus);
|
||||
record.GradePoint = GradeCalculator.CalculateGradePoint(record.TotalScore);
|
||||
}
|
||||
@@ -492,13 +578,17 @@ public sealed class GradesController(
|
||||
public sealed record GradeSheetRequest(
|
||||
Guid TeachingTaskId,
|
||||
[Range(typeof(decimal), "0", "100")] decimal RegularWeight,
|
||||
[Range(typeof(decimal), "0", "100")] decimal MidtermWeight,
|
||||
[Range(typeof(decimal), "0", "100")] decimal FinalWeight);
|
||||
[Range(typeof(decimal), "0", "100")] decimal FinalWeight,
|
||||
IReadOnlyCollection<GradeItemRequest>? Items);
|
||||
|
||||
public sealed record GradeItemRequest(
|
||||
[MaxLength(60)] string Name,
|
||||
[Range(typeof(decimal), "0", "100")] decimal Weight);
|
||||
|
||||
public sealed record GradeWeightsRequest(
|
||||
[Range(typeof(decimal), "0", "100")] decimal RegularWeight,
|
||||
[Range(typeof(decimal), "0", "100")] decimal MidtermWeight,
|
||||
[Range(typeof(decimal), "0", "100")] decimal FinalWeight);
|
||||
[Range(typeof(decimal), "0", "100")] decimal FinalWeight,
|
||||
IReadOnlyCollection<GradeItemRequest>? Items);
|
||||
|
||||
public sealed record GradeRecordsRequest(
|
||||
IReadOnlyCollection<GradeRecordRequest> Records);
|
||||
@@ -506,10 +596,14 @@ public sealed record GradeRecordsRequest(
|
||||
public sealed record GradeRecordRequest(
|
||||
Guid Id,
|
||||
decimal? RegularScore,
|
||||
decimal? MidtermScore,
|
||||
decimal? FinalScore,
|
||||
IReadOnlyCollection<GradeItemScoreRequest>? ItemScores,
|
||||
GradeExamStatus ExamStatus,
|
||||
[MaxLength(300)] string? Notes);
|
||||
|
||||
public sealed record GradeItemScoreRequest(
|
||||
Guid GradeItemId,
|
||||
decimal? Score);
|
||||
|
||||
public sealed record GradeReviewRequest(
|
||||
[MaxLength(500)] string? Comment);
|
||||
|
||||
Reference in New Issue
Block a user