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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# RikiPath.Backend — EF Core Migration & Database Safety Standards

## Mentor homework attachments

Configure `Supabase:Url`, `Supabase:Bucket`, `Supabase:ServiceRoleKey` and `Supabase:VerificationBucket` on the backend. The private bucket can be named `rikipath-private-documents`; set `Supabase__VerificationBucket=rikipath-private-documents` in environments without local appsettings. A server-side service/secret key is required. When this configured bucket is missing, the storage service creates it as **private** on first use and verifies that it remains private. It will reject an existing public bucket. Do not put the secret key in frontend configuration.

Mentors upload JPG, PNG, PDF or DOCX (10 MB per file) with `POST /api/homework/draft-files`. The response contains a short-lived signed `previewUrl` and an owner-bound draft token. `GET /api/homework/draft-files/preview-content` returns a read-only Word preview; `GET /api/homework/draft-files/preview` streams the original for images and PDFs. Pass `promptDraftTokens` and `answerDraftTokens` to `POST /api/homework/cohorts/{cohortId}/with-files` when assigning. The existing multipart file fields still work for older clients. The assignment, attachments and learner notifications are saved together; answer keys are visible only to the Mentor/Admin.

## Class lifecycle with direct transitions

Scheduled dates remain planning and conflict-check inputs. Authorized Mentors can close enrollment after at least one confirmed enrollment, start the next valid session, mark attendance, and end it without waiting for scheduled time. No mode flag, environment switch or special time control is used. PayOS verification and financial expiry remain unchanged. Existing automatic enrollment-deadline processing remains active.
Expand Down
154 changes: 151 additions & 3 deletions RikiPath.Application/Services/HomeworkFileService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
using System.Net;
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using RikiPath.Application.IServices;
using RikiPath.Application.Requests.Homework;
using RikiPath.Application.Responses;
Expand All @@ -25,7 +29,117 @@ public sealed record HomeworkFileStream(PrivateVerificationReadResult Content, s
public sealed record HomeworkCreateExtras(
string? AnswerGuide,
List<(IFormFile File, string ContentType)> PromptFiles,
List<(IFormFile File, string ContentType)> AnswerFiles);
List<(IFormFile File, string ContentType)> AnswerFiles,
List<(string Kind, string Reference, string FileName, string ContentType, long Size)>? DraftFiles = null);

public sealed record HomeworkDraftUpload(string Token, string PreviewUrl, string FileName,
string ContentType, long SizeBytes, string Kind);

private sealed record DraftFileToken(int MentorId, string Kind, string Reference,
string FileName, string ContentType, long SizeBytes);

private ITimeLimitedDataProtector DraftProtector => (dataProtection
?? throw new InvalidOperationException("Dịch vụ bảo vệ tài liệu chưa được cấu hình."))
.CreateProtector("RikiPath.Homework.DraftFile.v1").ToTimeLimitedDataProtector();

private bool TryReadDraft(string token, int mentorId, string expectedKind, out DraftFileToken? draft)
{
draft = null;
try
{
draft = JsonSerializer.Deserialize<DraftFileToken>(DraftProtector.Unprotect(token));
return draft is not null && draft.MentorId == mentorId && draft.Kind == expectedKind
&& draft.SizeBytes is >= 8 and <= ScanLimit && DocumentTypes.Contains(draft.ContentType)
&& !string.IsNullOrWhiteSpace(draft.Reference);
}
catch (Exception ex) when (ex is CryptographicException or JsonException or FormatException or ArgumentException)
{
return false;
}
}

/// <summary>Store a Mentor draft privately; the short-lived signed URL is for preview only.</summary>
public async Task<ApiResponse<HomeworkDraftUpload>> UploadDraftFileAsync(IFormFile? file, string? kind, CancellationToken ct)
{
var actor = claims.GetUserClaim();
if (actor.Role != Role.Mentor)
return ApiResponse<HomeworkDraftUpload>.Fail("Chỉ Giáo viên được tải tài liệu bài tập.", HttpStatusCode.Forbidden);
var normalizedKind = string.Equals(kind, HomeworkAssignmentAttachment.AnswerKeyKind, StringComparison.OrdinalIgnoreCase)
? HomeworkAssignmentAttachment.AnswerKeyKind : HomeworkAssignmentAttachment.PromptKind;
var (accepted, error) = await ValidateDocumentsAsync(file is null ? [] : [file], 1, ct);
if (error is not null || accepted.Count != 1)
return ApiResponse<HomeworkDraftUpload>.Fail(error ?? "Chọn một tệp hợp lệ.", HttpStatusCode.BadRequest);
if (storage is null)
return ApiResponse<HomeworkDraftUpload>.Fail("Kho tài liệu chưa sẵn sàng.", HttpStatusCode.ServiceUnavailable);

string? reference = null;
try
{
var (selected, contentType) = accepted[0];
await using var stream = selected.OpenReadStream();
var stored = await storage.UploadPrivateVerificationAsync(stream, contentType, actor.Id, ct);
reference = stored.Url;
var previewUrl = await storage.CreateSignedReadUrlAsync(reference, ct);
var fileName = SafeFileName(selected.FileName, contentType);
var token = DraftProtector.Protect(JsonSerializer.Serialize(new DraftFileToken(
actor.Id, normalizedKind, reference, fileName, contentType, selected.Length)), TimeSpan.FromHours(2));
return ApiResponse<HomeworkDraftUpload>.Created(new(token, previewUrl, fileName,
contentType, selected.Length, normalizedKind));
}
catch (Exception ex) when (ex is HttpRequestException or InvalidOperationException or ArgumentException or IOException)
{
if (reference is not null) await DiscardUnsavedUploadsAsync([reference]);
logger?.LogError(ex, "Homework draft upload failed for Mentor {MentorId}.", actor.Id);
var missingConfiguration = ex is InvalidOperationException &&
(ex.Message.Contains("chưa được cấu hình", StringComparison.OrdinalIgnoreCase) ||
ex.Message.Contains("bucket tài liệu riêng tư", StringComparison.OrdinalIgnoreCase));
return ApiResponse<HomeworkDraftUpload>.Fail(missingConfiguration
? "Kho tài liệu riêng tư chưa được cấu hình. Cần kiểm tra Supabase:VerificationBucket và quyền truy cập."
: "Chưa tải được tài liệu lên kho lưu trữ.",
missingConfiguration ? HttpStatusCode.ServiceUnavailable : HttpStatusCode.BadGateway);
}
}

public async Task<ApiResponse<string>> RefreshDraftPreviewAsync(string token, string? kind, CancellationToken ct)
{
var actor = claims.GetUserClaim();
var normalizedKind = string.Equals(kind, HomeworkAssignmentAttachment.AnswerKeyKind, StringComparison.OrdinalIgnoreCase)
? HomeworkAssignmentAttachment.AnswerKeyKind : HomeworkAssignmentAttachment.PromptKind;
if (actor.Role != Role.Mentor || !TryReadDraft(token, actor.Id, normalizedKind, out var draft))
return ApiResponse<string>.Fail("Tài liệu nháp không hợp lệ hoặc đã hết hạn.", HttpStatusCode.BadRequest);
if (storage is null) return ApiResponse<string>.Fail("Kho tài liệu chưa sẵn sàng.", HttpStatusCode.ServiceUnavailable);
try { return ApiResponse<string>.Success(await storage.CreateSignedReadUrlAsync(draft!.Reference, ct)); }
catch (Exception ex) when (ex is HttpRequestException or InvalidOperationException or ArgumentException)
{
logger?.LogError(ex, "Cannot refresh homework draft preview.");
return ApiResponse<string>.Fail("Chưa đọc được tài liệu nháp.", HttpStatusCode.BadGateway);
}
}

public async Task<HomeworkFileStream?> ReadDraftFileAsync(string token, string? kind, CancellationToken ct)
{
var actor = claims.GetUserClaim();
var normalizedKind = string.Equals(kind, HomeworkAssignmentAttachment.AnswerKeyKind, StringComparison.OrdinalIgnoreCase)
? HomeworkAssignmentAttachment.AnswerKeyKind : HomeworkAssignmentAttachment.PromptKind;
if (actor.Role != Role.Mentor || !TryReadDraft(token, actor.Id, normalizedKind, out var draft) || storage is null)
return null;
return new HomeworkFileStream(await storage.OpenPrivateVerificationAsync(draft!.Reference, ct), draft.FileName);
}

public async Task<ApiResponse<bool>> DiscardDraftFileAsync(string token, string? kind, CancellationToken ct)
{
var actor = claims.GetUserClaim();
var normalizedKind = string.Equals(kind, HomeworkAssignmentAttachment.AnswerKeyKind, StringComparison.OrdinalIgnoreCase)
? HomeworkAssignmentAttachment.AnswerKeyKind : HomeworkAssignmentAttachment.PromptKind;
if (actor.Role != Role.Mentor || !TryReadDraft(token, actor.Id, normalizedKind, out var draft))
return ApiResponse<bool>.Fail("Tài liệu nháp không hợp lệ hoặc đã hết hạn.", HttpStatusCode.BadRequest);
if (storage is null) return ApiResponse<bool>.Fail("Kho tài liệu chưa sẵn sàng.", HttpStatusCode.ServiceUnavailable);
if (await unit.HomeworkAssignments.Query().AsNoTracking()
.SelectMany(a => a.Attachments).AnyAsync(a => a.StorageReference == draft!.Reference, ct))
return ApiResponse<bool>.Fail("Tài liệu đã được giao cho học viên.", HttpStatusCode.Conflict);
await storage.DeletePrivateVerificationAsync(draft!.Reference, ct);
return ApiResponse<bool>.Success(true);
}

private static readonly HashSet<string> DocumentTypes =
["image/jpeg", "image/png", "application/pdf", HomeworkDocumentFormat.DocxMediaType];
Expand Down Expand Up @@ -138,13 +252,47 @@ private async Task SaveOrDiscardUploadsAsync(List<string> uploadedReferences, Ca

/// <summary>Giao bài with content, private answer guide and files in one request (multipart).</summary>
public async Task<ApiResponse<List<int>>> CreateCohortAssignmentsWithFilesAsync(int cohortId, CreateHomeworkRequest request,
string? answerGuide, IReadOnlyList<IFormFile>? promptFiles, IReadOnlyList<IFormFile>? answerFiles, CancellationToken ct)
string? answerGuide, IReadOnlyList<IFormFile>? promptFiles, IReadOnlyList<IFormFile>? answerFiles, CancellationToken ct,
IReadOnlyList<string>? promptDraftTokens = null, IReadOnlyList<string>? answerDraftTokens = null)
{
var (prompt, promptError) = await ValidateDocumentsAsync(promptFiles, MaxHomeworkAttachmentFiles, ct);
if (promptError is not null) return ApiResponse<List<int>>.Fail(promptError);
var (answers, answerError) = await ValidateDocumentsAsync(answerFiles, MaxHomeworkAttachmentFiles, ct);
if (answerError is not null) return ApiResponse<List<int>>.Fail(answerError);
return await CreateCohortAssignmentsAsync(cohortId, request, ct, new HomeworkCreateExtras(answerGuide, prompt, answers));
if (prompt.Count + (promptDraftTokens?.Count ?? 0) > MaxHomeworkAttachmentFiles ||
answers.Count + (answerDraftTokens?.Count ?? 0) > MaxHomeworkAttachmentFiles)
return ApiResponse<List<int>>.Fail("Mỗi loại tài liệu chỉ được tối đa 10 tệp.", HttpStatusCode.BadRequest);
var actor = claims.GetUserClaim();
var drafts = new List<(string Kind, string Reference, string FileName, string ContentType, long Size)>();
foreach (var (tokens, kind) in new[]
{
(promptDraftTokens ?? [], HomeworkAssignmentAttachment.PromptKind),
(answerDraftTokens ?? [], HomeworkAssignmentAttachment.AnswerKeyKind),
})
{
foreach (var token in tokens)
{
if (!TryReadDraft(token, actor.Id, kind, out var draft))
return ApiResponse<List<int>>.Fail("Tài liệu nháp không hợp lệ hoặc đã hết hạn.", HttpStatusCode.BadRequest);
drafts.Add((kind, draft!.Reference, draft.FileName, draft.ContentType, draft.SizeBytes));
}
}
if (drafts.Select(d => d.Reference).Distinct(StringComparer.Ordinal).Count() != drafts.Count)
return ApiResponse<List<int>>.Fail("Tài liệu nháp bị lặp.", HttpStatusCode.BadRequest);
if (drafts.Count > 0)
{
if (storage is null) return ApiResponse<List<int>>.Fail("Kho tài liệu chưa sẵn sàng.", HttpStatusCode.ServiceUnavailable);
try
{
foreach (var draft in drafts) await storage.VerifyPrivateVerificationAsync(draft.Reference, ct);
}
catch (Exception ex) when (ex is HttpRequestException or InvalidOperationException or ArgumentException)
{
logger?.LogError(ex, "Homework draft verification failed.");
return ApiResponse<List<int>>.Fail("Tài liệu nháp chưa sẵn sàng. Hãy tải lại.", HttpStatusCode.BadGateway);
}
}
return await CreateCohortAssignmentsAsync(cohortId, request, ct, new HomeworkCreateExtras(answerGuide, prompt, answers, drafts));
}

public async Task<ApiResponse<List<HomeworkFileView>>> AddAttachmentsAsync(int assignmentId, IReadOnlyList<IFormFile>? files,
Expand Down
22 changes: 17 additions & 5 deletions RikiPath.Application/Services/HomeworkService.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using RikiPath.Application.EmailTemplates;
using RikiPath.Application.Helpers;
using RikiPath.Application.IClients;
Expand Down Expand Up @@ -32,7 +33,9 @@ public sealed partial class HomeworkService(
AppSettings? appSettings = null,
ISidebarCounterNotifier? sidebarNotifier = null,
INotificationService? notificationService = null,
Microsoft.Extensions.Caching.Memory.IMemoryCache? memoryCache = null)
Microsoft.Extensions.Caching.Memory.IMemoryCache? memoryCache = null,
Microsoft.AspNetCore.DataProtection.IDataProtectionProvider? dataProtection = null,
Microsoft.Extensions.Logging.ILogger<HomeworkService>? logger = null)
{
private static readonly TimeSpan VietnamOffset = TimeSpan.FromHours(7);
private static readonly string[] SupportedLevels = ["N5", "N4", "N3", "N2", "N1"];
Expand Down Expand Up @@ -193,17 +196,20 @@ public async Task<ApiResponse<List<int>>> CreateCohortAssignmentsAsync(int cohor
var authoredJson = authoredDefinition is null ? null : JsonSerializer.Serialize(authoredDefinition, HomeworkJson);
var promptUploads = extras?.PromptFiles ?? [];
var answerUploads = extras?.AnswerFiles ?? [];
var draftFiles = extras?.DraftFiles ?? [];

var defaultDeadlineDays = groupPolicies is null
? 7
: (await groupPolicies.GetEffectiveAsync(DateTime.UtcNow, ct))?.HomeworkDeadlineDays ?? 7;
var validated = await ValidateAssignmentContentAsync(request, DateTime.UtcNow.AddDays(defaultDeadlineDays), ct,
hasAuthoredQuestions: authoredDefinition is { Questions.Length: > 0 } || promptUploads.Count > 0);
hasAuthoredQuestions: authoredDefinition is { Questions.Length: > 0 } || promptUploads.Count > 0
|| draftFiles.Any(f => f.Kind == HomeworkAssignmentAttachment.PromptKind));
if (validated.Error is not null)
return ApiResponse<List<int>>.Fail(validated.Error.ErrorMessage ?? "Yêu cầu giao bài không hợp lệ.", (HttpStatusCode)validated.Error.StatusCode);

// Upload each file once before anything is saved: a storage failure leaves no half-created homework.
var storedFiles = new List<(string Kind, string Reference, string FileName, string ContentType, long Size)>();
var storedFiles = new List<(string Kind, string Reference, string FileName, string ContentType, long Size)>(draftFiles);
var uploadedInRequest = new List<string>();
if (promptUploads.Count + answerUploads.Count > 0)
{
if (storage is null)
Expand All @@ -221,15 +227,21 @@ public async Task<ApiResponse<List<int>>> CreateCohortAssignmentsAsync(int cohor
await using var stream = file.OpenReadStream();
var stored = await storage.UploadPrivateVerificationAsync(stream, contentType, user.Id, ct);
storedFiles.Add((kind, stored.Url, SafeFileName(file.FileName, contentType), contentType, file.Length));
uploadedInRequest.Add(stored.Url);
}
}
}
catch (Exception ex) when (ex is HttpRequestException or InvalidOperationException or ArgumentException
or IOException or OperationCanceledException)
{
// Files uploaded before the failing one are not referenced anywhere: remove them (no orphan objects).
await DiscardUnsavedUploadsAsync(storedFiles.Select(f => f.Reference));
await DiscardUnsavedUploadsAsync(uploadedInRequest);
if (ex is OperationCanceledException) throw;
logger?.LogError(ex, "Homework attachment upload failed for cohort {CohortId}.", cohortId);
if (ex is InvalidOperationException &&
(ex.Message.Contains("chưa được cấu hình", StringComparison.OrdinalIgnoreCase) ||
ex.Message.Contains("bucket tài liệu riêng tư", StringComparison.OrdinalIgnoreCase)))
return ApiResponse<List<int>>.Fail("Kho tài liệu riêng tư chưa được cấu hình. Cần kiểm tra Supabase:VerificationBucket và quyền truy cập.", HttpStatusCode.ServiceUnavailable);
return ApiResponse<List<int>>.Fail("Chưa lưu được tài liệu đính kèm. Hãy thử lại.", HttpStatusCode.BadGateway);
}
}
Expand Down Expand Up @@ -274,7 +286,7 @@ public async Task<ApiResponse<List<int>>> CreateCohortAssignmentsAsync(int cohor
catch
{
// Nothing was persisted, so the uploaded objects are unreferenced; remove them, then surface the error.
await DiscardUnsavedUploadsAsync(storedFiles.Select(f => f.Reference));
await DiscardUnsavedUploadsAsync(uploadedInRequest);
throw;
}
if (notificationService is not null)
Expand Down
Loading
Loading