成绩+点名

This commit is contained in:
2026-07-25 14:08:50 +08:00 Unverified
parent 7800951aee
commit 36049af692
16 changed files with 1809 additions and 98 deletions
@@ -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);