diff --git a/src/Jiaowu.Api/Controllers/OtherExamsController.cs b/src/Jiaowu.Api/Controllers/OtherExamsController.cs index 9f257fd..5211549 100644 --- a/src/Jiaowu.Api/Controllers/OtherExamsController.cs +++ b/src/Jiaowu.Api/Controllers/OtherExamsController.cs @@ -97,15 +97,35 @@ public sealed class OtherExamsController(AppDbContext db, ICurrentUserDataScope [HttpGet("batches/{id:guid}")] [Authorize(Roles = Managers)] - public async Task GetBatch(Guid id, CancellationToken ct) + public async Task 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(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().ToArray(); + var last = rows.Take(pageSize).LastOrDefault(); + return Ok(new + { + Batch = batch, + Results = new CursorPagedResult(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(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 MergeResultsAsync(OtherExamBatch batch, IReadOnlyList 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(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 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); diff --git a/tests/Jiaowu.Api.Tests/OtherExamsControllerTests.cs b/tests/Jiaowu.Api.Tests/OtherExamsControllerTests.cs index 383d87e..57ac2ac 100644 --- a/tests/Jiaowu.Api.Tests/OtherExamsControllerTests.cs +++ b/tests/Jiaowu.Api.Tests/OtherExamsControllerTests.cs @@ -66,13 +66,23 @@ public sealed class OtherExamsControllerTests EnrollmentDate = new DateOnly(2026, 9, 1), Status = StudentStatus.Active }; + var anotherStudent = new Student + { + StudentNumber = "202600002", + Name = "另一测试学生", + AdministrativeClassId = administrativeClass.Id, + EnrollmentYear = 2026, + EnrollmentDate = new DateOnly(2026, 9, 1), + Status = StudentStatus.Active + }; var batch = new OtherExamBatch { ExamCode = "CET4", Name = "大学英语四级", ExamDate = new DateOnly(2026, 6, 1), MetricKind = OtherExamMetricKind.Score, - MaxScore = 710 + MaxScore = 710, + Status = OtherExamBatchStatus.Published }; var oldResult = new OtherExamResult { @@ -81,7 +91,14 @@ public sealed class OtherExamsControllerTests Score = 500, AttemptNumber = 1 }; - db.AddRange(college, major, administrativeClass, student, batch, oldResult); + var anotherOldResult = new OtherExamResult + { + OtherExamBatchId = batch.Id, + StudentId = anotherStudent.Id, + Score = 520, + AttemptNumber = 1 + }; + db.AddRange(college, major, administrativeClass, student, anotherStudent, batch, oldResult, anotherOldResult); await db.SaveChangesAsync(); var controller = new OtherExamsController(db, new TestDataScope(college.Id)); @@ -91,10 +108,13 @@ public sealed class OtherExamsControllerTests Assert.IsType(result); db.ChangeTracker.Clear(); - var saved = await db.OtherExamResults.SingleAsync(x => x.OtherExamBatchId == batch.Id); + var saved = await db.OtherExamResults.SingleAsync(x => x.StudentId == student.Id); Assert.Equal(610.5m, saved.Score); Assert.Equal("已复核", saved.Notes); Assert.Equal(1, saved.AttemptNumber); + Assert.Equal(2, await db.OtherExamResults.CountAsync(x => x.OtherExamBatchId == batch.Id)); + Assert.Equal(520m, (await db.OtherExamResults.SingleAsync(x => x.StudentId == anotherStudent.Id)).Score); + Assert.Equal(OtherExamBatchStatus.Published, (await db.OtherExamBatches.SingleAsync()).Status); } [Fact] diff --git a/web/src/views/OtherExamsView.vue b/web/src/views/OtherExamsView.vue index 8797095..4789217 100644 --- a/web/src/views/OtherExamsView.vue +++ b/web/src/views/OtherExamsView.vue @@ -23,6 +23,12 @@ const nextBatchCursor = ref() const batchHasMore = ref(false) const selected = ref(null) const results = ref([]) +const resultPage = ref(1) +const resultPageSize = 30 +const resultCursors = ref([]) +const nextResultCursor = ref() +const resultHasMore = ref(false) +const resultTotal = ref(0) const mine = reactive({ best: [] as any[], history: [] as any[] }) const dialog = ref(false) const publishDialog = ref(false) @@ -73,15 +79,33 @@ async function previousBatchPage() { batchPage.value -= 1 await load() } -async function openBatch(row: any) { +async function openBatch(row: any, resetPage = true) { + if (resetPage) { + resultPage.value = 1 + resultCursors.value = [] + nextResultCursor.value = undefined + } try { - const data = (await http.get(`/other-exams/batches/${row.id}`)).data + const data = (await http.get(`/other-exams/batches/${row.id}`, { params: { cursor: resultCursors.value.at(-1), pageSize: resultPageSize } })).data const metricKind = Number(data.batch.metricKind ?? 3) data.batch.metricKind = [1, 2, 3].includes(metricKind) ? metricKind : 3 selected.value = data.batch - results.value = data.results.map((item: any) => ({ ...item, score: item.score ?? null, level: item.level ?? '', notes: item.notes ?? '' })) + results.value = data.results.items.map((item: any) => ({ ...item, score: item.score ?? null, level: item.level ?? '', notes: item.notes ?? '' })) + resultTotal.value = data.results.total + resultHasMore.value = data.results.hasMore + nextResultCursor.value = data.results.nextCursor } catch (error) { ElMessage.error(apiErrorMessage(error)) } } +async function nextResultPage() { + if (!selected.value || !nextResultCursor.value || loading.value) return + resultCursors.value.push(nextResultCursor.value); resultPage.value += 1 + await openBatch(selected.value, false) +} +async function previousResultPage() { + if (!selected.value || !resultCursors.value.length || loading.value) return + resultCursors.value.pop(); resultPage.value -= 1 + await openBatch(selected.value, false) +} function addResult() { results.value.push({ studentNumber: '', studentName: '', collegeName: '', className: '', score: null, level: '', isPassed: null, notes: '' }) } async function lookupStudent(row: ResultRow | any) { row.studentName = ''; row.collegeName = ''; row.className = '' @@ -95,7 +119,7 @@ async function saveResults() { saving.value = true try { await http.put(`/other-exams/batches/${selected.value.id}/results`, { results: results.value.map(row => ({ studentNumber: row.studentNumber, score: isScoreMetric.value ? row.score : null, level: isLevelMetric.value ? row.level : null, isPassed: isPassMetric.value ? row.isPassed : null, notes: row.notes })) }) - ElMessage.success('成绩已保存,参加次数由系统自动计算'); await openBatch(selected.value); await load() + ElMessage.success('本页成绩已保存,参加次数由系统自动计算'); await openBatch(selected.value, false); await load() } catch (error) { ElMessage.error(apiErrorMessage(error)) } finally { saving.value = false } } async function publish() { @@ -126,11 +150,11 @@ async function importExcel(event: Event) { const input = event.target as HTMLInputElement; const file = input.files?.[0]; input.value = '' if (!file) return const data = new FormData(); data.append('file', file) - try { await http.post(`/other-exams/batches/${selected.value.id}/import`, data, { headers: { 'Content-Type': 'multipart/form-data' } }); ElMessage.success('其他考试成绩导入成功'); await openBatch(selected.value); await load() } + try { await http.post(`/other-exams/batches/${selected.value.id}/import`, data, { headers: { 'Content-Type': 'multipart/form-data' } }); ElMessage.success('其他考试成绩导入成功,未在导入文件中的原有记录已保留'); await openBatch(selected.value, false); await load() } catch (error) { ElMessage.error(apiErrorMessage(error)) } } function metricName(kind: number | string) { const value = Number(kind); return value === 1 ? '合格制' : value === 2 ? '等级制' : '分数制' } -function displayResult(row: any) { return row.metricKind === 3 ? `${row.score} / ${row.maxScore}` : row.metricKind === 2 ? row.level : row.isPassed ? '合格' : '不合格' } +function displayResult(row: any) { return Number(row.metricKind) === 3 ? `${row.score} / ${row.maxScore}` : Number(row.metricKind) === 2 ? row.level : row.isPassed ? '合格' : '不合格' } onMounted(load) @@ -138,12 +162,12 @@ onMounted(load)
考试成绩

其他考试成绩

{{ isStudent ? '你的证书、等级考试与校外考试,按考试归档,最优结果一目了然。' : '用考试编码归并同一考试,按场次维护成绩,系统自动记录每位学生的参加次数。' }}

新建考试场次
确认发布“{{ selected?.name }}”成绩?

发布后学生可以查看本批次成绩;如需更正,可以修改后再次发布。