Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 2 additions & 11 deletions RikiPath.Application/Services/HomeworkService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -518,20 +518,11 @@ await unit.ExecuteInTransactionAsync(async token =>
return;
}

var exerciseIds = assignment.Exercises.Select(item => item.PracticeExerciseId).ToArray();
var completed = await unit.PracticeExerciseAttempts.Query().CountAsync(attempt =>
attempt.HomeworkAssignmentId == assignmentId && attempt.UserId == userId &&
attempt.IsCompleted && !attempt.IsDeleted && exerciseIds.Contains(attempt.PracticeExerciseId), token);
if (completed != exerciseIds.Length)
{
response = ApiResponse<HomeworkSubmissionDetail>.Fail("Hãy làm hết các bài luyện tập trước khi nộp.",
HttpStatusCode.Conflict, "HOMEWORK_EXERCISES_INCOMPLETE");
return;
}
var existing = assignment.Submission is { IsDeleted: false } current ? current : null;
var hasStoredScan = existing is not null && ScanReference(existing) is not null;
// Attached exercises may be submitted without a separate answer; the Mentor reviews the work.
// Online answers (trắc nghiệm) and audio recordings are valid payloads on their own.
if (completed == 0 && string.IsNullOrEmpty(text) && string.IsNullOrEmpty(link) && scan is null && !hasStoredScan
if (assignment.Exercises.Count == 0 && string.IsNullOrEmpty(text) && string.IsNullOrEmpty(link) && scan is null && !hasStoredScan
&& request.SelectedOptions is not { Length: > 0 } && audio is null && fileCount == 0)
{
response = ApiResponse<HomeworkSubmissionDetail>.Fail("Hãy nhập nội dung, đường dẫn hoặc đính kèm ảnh/PDF bài làm.");
Expand Down
30 changes: 30 additions & 0 deletions RikiPath.Application/Services/MockTestService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1135,6 +1135,7 @@ await unitOfWork.ExecuteInTransactionAsync(async transactionCancellationToken =>
attempt.QuestionSnapshotJson = JsonSerializer.Serialize(existingSnapshot, MockSnapshotJson);
}
attempt.ModifiedDate = now;
await PersistProjectedAnswersAsync(attemptId, snapshotAnswers, transactionCancellationToken);
unitOfWork.MockTestAttempts.Update(attempt);
await unitOfWork.SaveChangesAsync(transactionCancellationToken);
response = ApiResponse<AttemptResultResponse>.Success(new AttemptResultResponse
Expand Down Expand Up @@ -1178,6 +1179,7 @@ await unitOfWork.MockTestSectionResults.AddRangeAsync(
attempt.SubmittedAt = expired && deadline.HasValue ? deadline.Value : now;
attempt.IsCompleted = true;
attempt.TotalScore = evaluated.OverallAccuracyPercent;
await PersistProjectedAnswersAsync(attemptId, snapshotAnswers, transactionCancellationToken);
unitOfWork.MockTestAttempts.Update(attempt);

// Answers, section results và trạng thái attempt cùng commit trong một transaction.
Expand Down Expand Up @@ -1408,6 +1410,7 @@ await unitOfWork.ExecuteInTransactionAsync(async ct =>
attempt.QuestionSnapshotJson = JsonSerializer.Serialize(existingSnap, MockSnapshotJson);
}
attempt.ModifiedDate = saveUtc;
await PersistProjectedAnswersAsync(attemptId, snapshots, ct);
unitOfWork.MockTestAttempts.Update(attempt);
await unitOfWork.SaveChangesAsync(ct);
response = ApiResponse<bool>.Success(true);
Expand Down Expand Up @@ -1615,6 +1618,7 @@ await unitOfWork.ExecuteInTransactionAsync(async ct =>
existingSnap.Scoring = evaluated.Scoring;
attempt.QuestionSnapshotJson = JsonSerializer.Serialize(existingSnap, MockSnapshotJson);
}
await PersistProjectedAnswersAsync(attemptId, answers, ct);
unitOfWork.MockTestAttempts.Update(attempt);
await unitOfWork.SaveChangesAsync(ct);

Expand Down Expand Up @@ -3327,6 +3331,7 @@ public async Task<ApiResponse<PlacementAnswerAckResponse>> SavePlacementAnswerAs
if (validationError is not null)
return ApiResponse<PlacementAnswerAckResponse>.Fail(validationError, HttpStatusCode.BadRequest);

await PersistProjectedAnswersAsync(attemptId, snapshots, cancellationToken);
await unitOfWork.SaveChangesAsync(cancellationToken);
return ApiResponse<PlacementAnswerAckResponse>.Success(new PlacementAnswerAckResponse
{
Expand Down Expand Up @@ -3378,6 +3383,7 @@ public async Task<ApiResponse<PlacementAnswersSavedResponse>> SavePlacementAnswe
saved++;
}

await PersistProjectedAnswersAsync(attemptId, snapshots, cancellationToken);
await unitOfWork.SaveChangesAsync(cancellationToken);
return ApiResponse<PlacementAnswersSavedResponse>.Success(new PlacementAnswersSavedResponse
{
Expand Down Expand Up @@ -3457,6 +3463,7 @@ await unitOfWork.ExecuteInTransactionAsync(async ct =>
attempt.SubmittedAt = DateTime.UtcNow;
attempt.IsCompleted = true;
attempt.TotalScore = sections.OverallScore;
await PersistProjectedAnswersAsync(attemptId, snapshots, ct);
unitOfWork.MockTestAttempts.Update(attempt);
await unitOfWork.SaveChangesAsync(ct);

Expand Down Expand Up @@ -3565,6 +3572,7 @@ private async Task<List<MockTestAnswer>> LoadAttemptAnswersWithLegacyProjectionA
.Where(answer => answer.MockTestAttemptId == attemptId)
.OrderBy(answer => answer.MockQuestion.MockTestSection!.SortOrder)
.ThenBy(answer => answer.MockQuestion.SortOrder)
.AsNoTracking()
.ToListAsync(ct);

if (answers.Count == 0)
Expand Down Expand Up @@ -3727,6 +3735,28 @@ private async Task<List<MockTestAnswer>> LoadAttemptAnswersWithLegacyProjectionA
return answers;
}

// The projected question/test/level graph above is incomplete and must never be tracked for writes.
// Copy only answer fields back to the real tracked rows before SaveChanges.
private async Task PersistProjectedAnswersAsync(
int attemptId, IReadOnlyCollection<MockTestAnswer> projectedAnswers, CancellationToken ct)
{
var byId = projectedAnswers.ToDictionary(answer => answer.Id);
var ids = byId.Keys.ToArray();
var storedAnswers = await unitOfWork.MockTestAnswers.Query()
.Where(answer => answer.MockTestAttemptId == attemptId && ids.Contains(answer.Id))
.ToListAsync(ct);
if (storedAnswers.Count != projectedAnswers.Count)
throw new InvalidOperationException("Danh sách câu trả lời của lượt làm bài đã thay đổi.");

foreach (var stored in storedAnswers)
{
var projected = byId[stored.Id];
stored.SelectedOptionId = projected.SelectedOptionId;
stored.ResponseJson = projected.ResponseJson;
stored.IsCorrect = projected.IsCorrect;
}
}

// Tổng thời gian = tổng TimeLimitMinutes của các đề tham gia attempt; tính từ StartedAt phía server.
private static int GetTimeLimitMinutes(IEnumerable<MockTestAnswer> answers)
{
Expand Down
Loading