修复“其他考试”成绩链路
This commit is contained in:
1 parent
ce2f91c36f
commit
a5ef6d7b8e
3 files changed
+132
-21
No files matched your search
@@ -97,15 +97,35 @@ public sealed class OtherExamsController(AppDbContext db, ICurrentUserDataScope
|
||||
|
||||
[HttpGet("batches/{id:guid}")]
|
||||
[Authorize(Roles = Managers)]
|
||||
public async Task<ActionResult> GetBatch(Guid id, CancellationToken ct)
|
||||
public async Task<ActionResult> GetBatch(Guid id, string? cursor = null, int pageSize = 30, CancellationToken ct = default)
|
||||
{
|
||||
var batch = await db.OtherExamBatches.AsNoTracking().Where(x => x.Id == id)
|
||||
.Select(x => new { x.Id, x.ExamCode, x.Name, x.Organizer, x.ExamDate, x.MetricKind, x.MaxScore, x.LevelOptions, x.Status, x.PublicationCount, x.PublishedAt }).FirstOrDefaultAsync(ct);
|
||||
if (batch is null) return NotFound();
|
||||
var results = await db.OtherExamResults.AsNoTracking().Where(x => x.OtherExamBatchId == id)
|
||||
pageSize = Math.Clamp(pageSize, 10, 100);
|
||||
if (!CursorToken.TryDecode<OtherExamResultCursor>(cursor, out var after)) return BadRequest("无效的游标。");
|
||||
var source = db.OtherExamResults.AsNoTracking().Where(x => x.OtherExamBatchId == id);
|
||||
var total = await source.CountAsync(ct);
|
||||
if (after is not null)
|
||||
{
|
||||
source = source.Where(x => string.Compare(x.Student!.StudentNumber, after.StudentNumber) > 0 ||
|
||||
(x.Student!.StudentNumber == after.StudentNumber && x.Id.CompareTo(after.Id) > 0));
|
||||
}
|
||||
var rows = await source
|
||||
.OrderBy(x => x.Student!.StudentNumber)
|
||||
.ThenBy(x => x.Id)
|
||||
.Take(pageSize + 1)
|
||||
.Select(x => new { x.Id, x.StudentId, StudentNumber = x.Student!.StudentNumber, StudentName = x.Student.Name, CollegeName = x.Student.AdministrativeClass!.Major!.College!.Name, ClassName = x.Student.AdministrativeClass.Name, x.AttemptNumber, x.Score, x.Level, x.IsPassed, x.Notes }).ToListAsync(ct);
|
||||
return Ok(new { Batch = batch, Results = results });
|
||||
var hasMore = rows.Count > pageSize;
|
||||
var items = rows.Take(pageSize).Cast<object>().ToArray();
|
||||
var last = rows.Take(pageSize).LastOrDefault();
|
||||
return Ok(new
|
||||
{
|
||||
Batch = batch,
|
||||
Results = new CursorPagedResult<object>(items,
|
||||
hasMore && last is not null ? CursorToken.Encode(new OtherExamResultCursor(last.StudentNumber, last.Id)) : null,
|
||||
hasMore, pageSize, total)
|
||||
});
|
||||
}
|
||||
|
||||
[HttpPut("batches/{id:guid}/results")]
|
||||
@@ -114,7 +134,7 @@ public sealed class OtherExamsController(AppDbContext db, ICurrentUserDataScope
|
||||
{
|
||||
var batch = await db.OtherExamBatches.Include(x => x.Results).FirstOrDefaultAsync(x => x.Id == id, ct);
|
||||
if (batch is null) return NotFound();
|
||||
var result = await ReplaceResultsAsync(batch, request.Results, ct);
|
||||
var result = await MergeResultsAsync(batch, request.Results, ct);
|
||||
return result is null ? Ok(new { updated = request.Results.Count }) : result;
|
||||
}
|
||||
|
||||
@@ -153,8 +173,8 @@ public sealed class OtherExamsController(AppDbContext db, ICurrentUserDataScope
|
||||
inputs.Add(new OtherExamResultRequest(number, score, level, passed, Normalize(row["备注"])));
|
||||
}
|
||||
if (errors.Count > 0) return ImportValidationProblem(errors);
|
||||
var result = await ReplaceResultsAsync(batch, inputs, ct);
|
||||
return result ?? Ok(new { updated = inputs.Count });
|
||||
var result = await MergeResultsAsync(batch, inputs, ct);
|
||||
return result ?? Ok(new { imported = inputs.Count });
|
||||
}
|
||||
|
||||
[HttpPost("batches/{id:guid}/publish")]
|
||||
@@ -179,7 +199,7 @@ public sealed class OtherExamsController(AppDbContext db, ICurrentUserDataScope
|
||||
if (studentId is null) return ConflictProblem("当前账号未关联有效学生档案。");
|
||||
var history = await db.OtherExamResults.AsNoTracking().Where(x => x.StudentId == studentId && x.OtherExamBatch!.Status == OtherExamBatchStatus.Published)
|
||||
.OrderByDescending(x => x.OtherExamBatch!.ExamDate).ThenByDescending(x => x.AttemptNumber)
|
||||
.Select(x => new { x.Id, ExamCode = x.OtherExamBatch!.ExamCode ?? x.OtherExamBatch.Name, BatchId = x.OtherExamBatchId, ExamName = x.OtherExamBatch.Name, x.OtherExamBatch.ExamDate, x.OtherExamBatch.MetricKind, x.OtherExamBatch.MaxScore, x.OtherExamBatch.LevelOptions, x.AttemptNumber, x.Score, x.Level, x.IsPassed, x.OtherExamBatch.PublishedAt }).ToListAsync(ct);
|
||||
.Select(x => new { x.Id, ExamCode = x.OtherExamBatch!.ExamCode ?? x.OtherExamBatch.Name, BatchId = x.OtherExamBatchId, ExamName = x.OtherExamBatch.Name, x.OtherExamBatch.ExamDate, x.OtherExamBatch.MetricKind, x.OtherExamBatch.MaxScore, x.OtherExamBatch.LevelOptions, x.AttemptNumber, x.Score, x.Level, x.IsPassed, x.Notes, x.OtherExamBatch.PublishedAt }).ToListAsync(ct);
|
||||
var best = history.GroupBy(x => x.ExamCode).Select(g => g.OrderByDescending(x => Rank(x.MetricKind, x.Score, x.Level, x.IsPassed, x.LevelOptions)).ThenByDescending(x => x.ExamDate).First()).ToList();
|
||||
return Ok(new { Best = best, History = history });
|
||||
}
|
||||
@@ -205,7 +225,6 @@ public sealed class OtherExamsController(AppDbContext db, ICurrentUserDataScope
|
||||
return await db.ExecuteInRetriableTransactionAsync<ActionResult?>(async transaction =>
|
||||
{
|
||||
db.OtherExamResults.RemoveRange(batch.Results);
|
||||
batch.Status = OtherExamBatchStatus.Draft;
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
var replacementResults = inputs.Select(x =>
|
||||
@@ -229,6 +248,53 @@ public sealed class OtherExamsController(AppDbContext db, ICurrentUserDataScope
|
||||
}, ct);
|
||||
}
|
||||
|
||||
private async Task<ActionResult?> MergeResultsAsync(OtherExamBatch batch, IReadOnlyList<OtherExamResultRequest> inputs, CancellationToken ct)
|
||||
{
|
||||
var numbers = inputs.Select(x => x.StudentNumber.Trim()).ToList();
|
||||
if (numbers.Count != numbers.Distinct(StringComparer.OrdinalIgnoreCase).Count()) return ValidationProblem("同一导入文件中学生不能重复出现。");
|
||||
var studentRows = await db.Students.Where(x => numbers.Contains(x.StudentNumber)).ToListAsync(ct);
|
||||
var students = studentRows.ToDictionary(x => x.StudentNumber, StringComparer.OrdinalIgnoreCase);
|
||||
if (students.Count != numbers.Count) return ValidationProblem("存在不存在的学号,请先检查学生档案。");
|
||||
foreach (var item in inputs)
|
||||
{
|
||||
var error = ValidateResult(batch, item.Score, item.Level, item.IsPassed, item.Notes);
|
||||
if (error is not null) return ValidationProblem(error);
|
||||
}
|
||||
|
||||
var existing = batch.Results.ToDictionary(x => x.StudentId);
|
||||
var newStudentIds = students.Values.Where(x => !existing.ContainsKey(x.Id)).Select(x => x.Id).ToList();
|
||||
var beforeCount = await db.OtherExamResults.AsNoTracking()
|
||||
.Where(x => x.OtherExamBatchId != batch.Id && newStudentIds.Contains(x.StudentId) &&
|
||||
(x.OtherExamBatch!.ExamCode == batch.ExamCode || (x.OtherExamBatch.ExamCode == null && batch.ExamCode == null && x.OtherExamBatch.Name == batch.Name)) &&
|
||||
(x.OtherExamBatch.ExamDate < batch.ExamDate || (x.OtherExamBatch.ExamDate == batch.ExamDate && x.OtherExamBatch.CreatedAt < batch.CreatedAt)))
|
||||
.GroupBy(x => x.StudentId).Select(x => new { StudentId = x.Key, Count = x.Count() }).ToDictionaryAsync(x => x.StudentId, x => x.Count, ct);
|
||||
|
||||
return await db.ExecuteInRetriableTransactionAsync<ActionResult?>(async transaction =>
|
||||
{
|
||||
foreach (var item in inputs)
|
||||
{
|
||||
var student = students[item.StudentNumber.Trim()];
|
||||
if (existing.TryGetValue(student.Id, out var result))
|
||||
{
|
||||
result.Score = item.Score;
|
||||
result.Level = Normalize(item.Level);
|
||||
result.IsPassed = item.IsPassed;
|
||||
result.Notes = Normalize(item.Notes);
|
||||
continue;
|
||||
}
|
||||
db.OtherExamResults.Add(new OtherExamResult
|
||||
{
|
||||
OtherExamBatchId = batch.Id, StudentId = student.Id,
|
||||
AttemptNumber = beforeCount.GetValueOrDefault(student.Id) + 1,
|
||||
Score = item.Score, Level = Normalize(item.Level), IsPassed = item.IsPassed, Notes = Normalize(item.Notes)
|
||||
});
|
||||
}
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
return null;
|
||||
}, ct);
|
||||
}
|
||||
|
||||
private static string[] HeadersFor(OtherExamBatch batch) => batch.MetricKind switch
|
||||
{
|
||||
OtherExamMetricKind.Score => ["学号", "成绩", "备注"],
|
||||
@@ -287,3 +353,4 @@ public sealed record CreateOtherExamRequest([Required] string ExamCode, [Require
|
||||
public sealed record ReplaceOtherExamResultsRequest(List<OtherExamResultRequest> Results);
|
||||
public sealed record OtherExamResultRequest([Required] string StudentNumber, decimal? Score, string? Level, bool? IsPassed, string? Notes);
|
||||
public sealed record OtherExamBatchCursor(DateOnly ExamDate, DateTime CreatedAt, Guid Id);
|
||||
public sealed record OtherExamResultCursor(string StudentNumber, Guid Id);
|
||||
Reference in new issue
Block a user